blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
d5ab529064abbee81f8e85aa52f55eb586fc3db9
40db2023c173aebe109d3d0804b1cf09b38ec8a0
/find_position.cpp
a9e317147a9334fc81123d745b7df89490aa2a1b
[]
no_license
kumarmeet/competative-programming-CPP-mysirg
905de091d176665f50824673da97deee0890e0dd
80e5d0b7c7d0048db56c05a082d6211923463a19
refs/heads/main
2023-07-30T20:14:05.064066
2021-09-20T17:19:08
2021-09-20T17:19:08
403,526,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,075
cpp
#include<iostream> #include<limits> using namespace std; class FindPosition { private: int *p1, *p2, *p3; int n; int minimum(int *arr, int size) { int mini{INT8_MAX}; int index; for(int i = 0; i < size; i++) { if(mini > arr[i]) { mini = arr[i]; index = i; } } return index + 1; } public: FindPosition() { } void init(int n) { this->n = n; p1 = new int[n]; p2 = new int[n]; p3 = new int[n]; int val{0}; for(int i = 0; i < n; i++) { cin>>val; p1[i] = val; } for(int i = 0; i < n; i++) { cin>>val; p2[i] = val; } for(int i = 0; i < n; i++) { cin>>val; p3[i] = val; } } void find() { int arr[3]; arr[0] = minimum(p1,n); arr[1] = minimum(p2,n); arr[2] = minimum(p3,n); for(int i = 0 ; i < 3; i++) cout<<arr[i] << " "; } };
[ "noreply@github.com" ]
noreply@github.com
25e287e44324b8deba69f82e0a51e838f3a7b97a
e05ee73f59fa33c462743b30cbc5d35263383e89
/sparse/src/zparict_cpu.cpp
22814dfe6d31f5442f828fa501abed9af5634136
[]
no_license
bhrnjica/magma
33c9e8a89f9bc2352f70867a48ec2dab7f94a984
88c8ca1a668055859a1cb9a31a204b702b688df5
refs/heads/master
2021-10-09T18:49:50.396412
2019-01-02T13:51:33
2019-01-02T13:51:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,255
cpp
/* -- MAGMA (version 2.4.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date June 2018 @author Hartwig Anzt @precisions normal z -> s d c */ #include "magmasparse_internal.h" #ifdef _OPENMP #include <omp.h> #endif #define PRECISION_z /***************************************************************************//** Purpose ------- Generates an incomplete threshold Cholesky preconditioner via the ParILUT algorithm. The strategy is to interleave a parallel fixed-point iteration that approximates an incomplete factorization for a given nonzero pattern with a procedure that adaptively changes the pattern. Much of this algorithm has fine-grained parallelism, and can efficiently exploit the compute power of shared memory architectures. This is the routine used in the publication by Anzt, Chow, Dongarra: ''ParILUT - A new parallel threshold ILU factorization'' submitted to SIAM SISC in 2017. This version uses the default setting which adds all candidates to the sparsity pattern. It is the variant for SPD systems. This function requires OpenMP, and is only available if OpenMP is activated. The parameter list is: precond.sweeps : number of ParILUT steps precond.atol : absolute fill ratio (1.0 keeps nnz count constant) Arguments --------- @param[in] A magma_z_matrix input matrix A @param[in] b magma_z_matrix input RHS b @param[in,out] precond magma_z_preconditioner* preconditioner parameters @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zgepr *******************************************************************************/ extern "C" magma_int_t magma_zparict_cpu( magma_z_matrix A, magma_z_matrix b, magma_z_preconditioner *precond, magma_queue_t queue) { magma_int_t info = 0; #ifdef _OPENMP real_Double_t start, end; real_Double_t t_rm=0.0, t_add=0.0, t_res=0.0, t_sweep1=0.0, t_sweep2=0.0, t_cand=0.0, t_transpose1=0.0, t_transpose2=0.0, t_selectrm=0.0, t_selectadd=0.0, t_nrm=0.0, t_total = 0.0, accum=0.0; double sum, sumL; magma_z_matrix hA={Magma_CSR}, hL={Magma_CSR}, oneL={Magma_CSR}, LT={Magma_CSR}, L={Magma_CSR}, L_new={Magma_CSR}, L0={Magma_CSR}; magma_int_t num_rmL; double thrsL = 0.0; magma_int_t num_threads = 1, timing = 1; // 1 = print timing magma_int_t L0nnz; #pragma omp parallel { num_threads = omp_get_max_threads(); } CHECK(magma_zmtransfer(A, &hA, A.memory_location, Magma_CPU, queue)); // in case using fill-in if (precond->levels > 0) { CHECK(magma_zsymbilu(&hA, precond->levels, &hL, &LT , queue)); magma_zmfree(&LT, queue); } CHECK(magma_zmatrix_tril(hA, &L, queue)); CHECK(magma_zmtransfer(L, &L0, A.memory_location, Magma_CPU, queue)); CHECK(magma_zmatrix_addrowindex(&L, queue)); L0nnz=L.nnz; if (timing == 1) { printf("ilut_fill_ratio = %.6f;\n\n", precond->atol); printf("performance_%d = [\n%%iter L.nnz U.nnz ILU-Norm candidat resid ILU-norm selectad add transp1 sweep1 selectrm remove sweep2 transp2 total accum\n", (int) num_threads); } //########################################################################## for (magma_int_t iters =0; iters<precond->sweeps; iters++) { t_rm=0.0; t_add=0.0; t_res=0.0; t_sweep1=0.0; t_sweep2=0.0; t_cand=0.0; t_transpose1=0.0; t_transpose2=0.0; t_selectrm=0.0; t_selectadd=0.0; t_nrm=0.0; t_total = 0.0; // step 1: find candidates start = magma_sync_wtime(queue); magma_zmfree(&LT, queue); magma_zcsrcoo_transpose(L, &LT, queue); end = magma_sync_wtime(queue); t_transpose1+=end-start; start = magma_sync_wtime(queue); magma_zparict_candidates(L0, L, LT, &hL, queue); end = magma_sync_wtime(queue); t_cand=+end-start; // step 2: compute residuals (optional when adding all candidates) start = magma_sync_wtime(queue); magma_zparilut_residuals(hA, L, L, &hL, queue); end = magma_sync_wtime(queue); t_res=+end-start; start = magma_sync_wtime(queue); magma_zmatrix_abssum(hL, &sumL, queue); sum = sumL*2; end = magma_sync_wtime(queue); t_nrm+=end-start; // step 3: add candidates start = magma_sync_wtime(queue); CHECK(magma_zcsr_sort(&hL, queue)); end = magma_sync_wtime(queue); t_selectadd+=end-start; start = magma_sync_wtime(queue); CHECK(magma_zmatrix_cup( L, hL, &L_new, queue)); end = magma_sync_wtime(queue); t_add=+end-start; magma_zmfree(&hL, queue); // step 4: sweep start = magma_sync_wtime(queue); CHECK(magma_zparict_sweep_sync(&hA, &L_new, queue)); end = magma_sync_wtime(queue); t_sweep1+=end-start; // step 5: select threshold to remove elements start = magma_sync_wtime(queue); num_rmL = max((L_new.nnz-L0nnz*(1+(precond->atol-1.) *(iters+1)/precond->sweeps)), 0); // pre-select: ignore the diagonal entries CHECK(magma_zparilut_preselect(0, &L_new, &oneL, queue)); if (num_rmL>0) { CHECK(magma_zparilut_set_thrs_randomselect(num_rmL, &oneL, 0, &thrsL, queue)); } else { thrsL = 0.0; } magma_zmfree(&oneL, queue); end = magma_sync_wtime(queue); t_selectrm=end-start; // step 6: remove elements start = magma_sync_wtime(queue); CHECK(magma_zparilut_thrsrm(1, &L_new, &thrsL, queue)); CHECK(magma_zmatrix_swap(&L_new, &L, queue)); magma_zmfree(&L_new, queue); end = magma_sync_wtime(queue); t_rm=end-start; // step 7: sweep start = magma_sync_wtime(queue); CHECK(magma_zparict_sweep_sync(&hA, &L, queue)); end = magma_sync_wtime(queue); t_sweep2+=end-start; if (timing == 1) { t_total = t_cand+t_res+t_nrm+t_selectadd+t_add+t_transpose1 +t_sweep1+t_selectrm+t_rm+t_sweep2+t_transpose2; accum = accum + t_total; printf("%5lld %5lld %5lld %.4e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e\n", (long long) iters, (long long) L.nnz, (long long) L.nnz, (double) sum, t_cand, t_res, t_nrm, t_selectadd, t_add, t_transpose1, t_sweep1, t_selectrm, t_rm, t_sweep2, t_transpose2, t_total, accum); fflush(stdout); } } if (timing == 1) { printf("]; \n"); fflush(stdout); } //########################################################################## CHECK(magma_zmtransfer(L, &precond->L, Magma_CPU, Magma_DEV , queue)); CHECK(magma_z_cucsrtranspose(precond->L, &precond->U, queue)); CHECK(magma_zmtransfer(precond->L, &precond->M, Magma_DEV, Magma_DEV, queue)); if (precond->trisolver == 0 || precond->trisolver == Magma_CUSOLVE) { CHECK(magma_zcumicgeneratesolverinfo(precond, queue)); } else { //prepare for iterative solves // extract the diagonal of L into precond->d CHECK(magma_zjacobisetup_diagscal(precond->L, &precond->d, queue)); CHECK(magma_zvinit(&precond->work1, Magma_DEV, hA.num_rows, 1, MAGMA_Z_ZERO, queue)); // extract the diagonal of U into precond->d2 CHECK(magma_zjacobisetup_diagscal(precond->U, &precond->d2, queue)); CHECK(magma_zvinit(&precond->work2, Magma_DEV, hA.num_rows, 1, MAGMA_Z_ZERO, queue)); } cleanup: magma_zmfree(&hA, queue); magma_zmfree(&L0, queue); magma_zmfree(&hL, queue); magma_zmfree(&oneL, queue); magma_zmfree(&L, queue); magma_zmfree(&LT, queue); magma_zmfree(&L_new, queue); #endif return info; }
[ "sinkingsugar@gmail.com" ]
sinkingsugar@gmail.com
5b48d9866839765c849ed6ba0f9974d3b54d8b1e
77966793a9fb4d69b96aa217ff0dfe431c5fc18d
/src/qt/notificator.h
4b9c3c91edb827c2561ebff3f086e0ef40944a2c
[]
no_license
admecoin/algo_Quark
5132ed4d1e874b8900f9f63e1d8a40e67e866eba
af637eb42a6ab0b0126188fa97eefc959ac50e81
refs/heads/master
2022-06-29T03:58:21.354331
2020-05-09T13:22:02
2020-05-09T13:22:02
262,575,614
0
0
null
null
null
null
UTF-8
C++
false
false
2,814
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_NOTIFICATOR_H #define BITCOIN_QT_NOTIFICATOR_H #if defined(HAVE_CONFIG_H) #include "config/parq-config.h" #endif #include <QIcon> #include <QObject> QT_BEGIN_NAMESPACE class QSystemTrayIcon; #ifdef USE_DBUS class QDBusInterface; #endif QT_END_NAMESPACE /** Cross-platform desktop notification client. */ class Notificator : public QObject { Q_OBJECT public: /** Create a new notificator. @note Ownership of trayIcon is not transferred to this object. */ Notificator(const QString& programName, QSystemTrayIcon* trayIcon, QWidget* parent); ~Notificator(); // Message class enum Class { Information, /**< Informational message */ Warning, /**< Notify user of potential problem */ Critical /**< An error occurred */ }; public slots: /** Show notification message. @param[in] cls general message class @param[in] title title shown with message @param[in] text message content @param[in] icon optional icon to show with message @param[in] millisTimeout notification timeout in milliseconds (defaults to 10 seconds) @note Platform implementations are free to ignore any of the provided fields except for \a text. */ void notify(Class cls, const QString& title, const QString& text, const QIcon& icon = QIcon(), int millisTimeout = 10000); private: QWidget* parent; enum Mode { None, /**< Ignore informational notifications, and show a modal pop-up dialog for Critical notifications. */ Freedesktop, /**< Use DBus org.freedesktop.Notifications */ QSystemTray, /**< Use QSystemTray::showMessage */ Growl12, /**< Use the Growl 1.2 notification system (Mac only) */ Growl13, /**< Use the Growl 1.3 notification system (Mac only) */ UserNotificationCenter /**< Use the 10.8+ User Notification Center (Mac only) */ }; QString programName; Mode mode; QSystemTrayIcon* trayIcon; #ifdef USE_DBUS QDBusInterface* interface; void notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout); #endif void notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout); #ifdef Q_OS_MAC void notifyGrowl(Class cls, const QString& title, const QString& text, const QIcon& icon); void notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon); #endif }; #endif // BITCOIN_QT_NOTIFICATOR_H
[ "34143043+admecoin@users.noreply.github.com" ]
34143043+admecoin@users.noreply.github.com
6c47d85c296c9539c5002c6a53a8f2b7df24aa9f
9f2f386a692a6ddeb7670812d1395a0b0009dad9
/paddle/fluid/operators/mkldnn/reshape_mkldnn_op.cc
a21034d48baaa5a64a64ab9c1a32ce40ff0233a0
[ "Apache-2.0" ]
permissive
sandyhouse/Paddle
2f866bf1993a036564986e5140e69e77674b8ff5
86e0b07fe7ee6442ccda0aa234bd690a3be2cffa
refs/heads/develop
2023-08-16T22:59:28.165742
2022-06-03T05:23:39
2022-06-03T05:23:39
181,423,712
0
7
Apache-2.0
2022-08-15T08:46:04
2019-04-15T06:15:22
C++
UTF-8
C++
false
false
18,696
cc
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/flatten_op.h" #include "paddle/fluid/operators/squeeze_op.h" #include "paddle/fluid/platform/mkldnn_reuse.h" namespace { enum class ReshapeKernelOpName { reshape, reshape2, squeeze, squeeze2, flatten, flatten2, }; } // anonymous namespace namespace paddle { namespace operators { using paddle::framework::LoDTensor; using platform::to_void_cast; using platform::GetMKLDNNFormat; static std::vector<int> extract_shape( const std::vector<const Tensor*>& list_new_shape_tensor) { std::vector<int> vec_new_shape; vec_new_shape.reserve(list_new_shape_tensor.size()); for (const auto& tensor : list_new_shape_tensor) { PADDLE_ENFORCE_EQ( tensor->dims(), phi::make_ddim({1}), platform::errors::InvalidArgument( "If the element type of 'shape' in ReshapeOp is Tensor, " "the element's shape must be [1]. But received the element's shape " "is [%s]", tensor->dims())); vec_new_shape.emplace_back(*tensor->data<int32_t>()); } return vec_new_shape; } template <typename T, ReshapeKernelOpName op_name> class ReshapeMKLDNNKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { RunKernel(ctx); } private: void RunKernel(const framework::ExecutionContext& ctx) const { const auto& dev_ctx = ctx.template device_context<platform::MKLDNNDeviceContext>(); const auto& onednn_engine = dev_ctx.GetEngine(); auto* x = ctx.Input<LoDTensor>("X"); auto* out = ctx.Output<LoDTensor>("Out"); framework::DDim x_dims, out_dims; InferInOutShape(ctx, x_dims, out_dims); auto x_vec_dims = phi::vectorize(x_dims); dnnl::memory::data_type x_type = framework::ToMKLDNNDataType(framework::TransToProtoVarType(x->dtype())); platform::ReorderMKLDNNHandler reorder_handler( x_vec_dims, framework::TransToProtoVarType(x->dtype()), x_type, onednn_engine); auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory( x->format(), platform::to_void_cast(x->data<T>())); out->Resize(x_dims); // to match x numel, format is changed later // reorder is done into a plain tag to allow usage with blocked formats auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory( out, getPlainFormatTag(x), ctx.GetPlace()); auto reorder_p = reorder_handler.AcquireReorder(reorder_src_memory_p, reorder_dst_memory_p); auto& astream = platform::MKLDNNDeviceContext::tls().get_stream(); reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p); astream.wait(); out->Resize(out_dims); out->set_layout(framework::DataLayout::kMKLDNN); out->set_format(GetMKLDNNFormat( reorder_dst_memory_p->get_desc().reshape(phi::vectorize(out_dims)))); } void InferInOutShape(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT switch (op_name) { case ReshapeKernelOpName::reshape: InferShapeReshapeOp(ctx, x_dims, out_dims); break; case ReshapeKernelOpName::reshape2: InferShapeReshape2Op(ctx, x_dims, out_dims); break; case ReshapeKernelOpName::squeeze: InferShapeSqueezeOp(ctx, x_dims, out_dims); break; case ReshapeKernelOpName::squeeze2: InferShapeSqueeze2Op(ctx, x_dims, out_dims); break; case ReshapeKernelOpName::flatten: InferShapeFlattenOp(ctx, x_dims, out_dims); break; case ReshapeKernelOpName::flatten2: InferShapeFlattenOp(ctx, x_dims, out_dims); break; default: PADDLE_THROW(paddle::platform::errors::OutOfRange( "Reshape kernel doesn not support that operator name")); } } void InferShapeReshapeOp(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto* x = ctx.Input<LoDTensor>("X"); auto* out = ctx.Output<LoDTensor>("Out"); x_dims = x->dims(); out_dims = out->dims(); ChangeReshapeOutDimsIfNeeded(ctx, x_dims, out_dims); } void InferShapeReshape2Op(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto* out = ctx.Output<LoDTensor>("Out"); auto* xshape = ctx.Output<LoDTensor>("XShape"); auto xshape_dims = xshape->dims(); x_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size()); out_dims = out->dims(); ChangeReshapeOutDimsIfNeeded(ctx, x_dims, out_dims); } // in reshape1/2 ops "ShapeTensor" has highest priority and "Shape" has // second highest priority void ChangeReshapeOutDimsIfNeeded( const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto list_new_shape_tensor = ctx.MultiInput<Tensor>("ShapeTensor"); if (list_new_shape_tensor.size() > 0) { auto new_shape = extract_shape(list_new_shape_tensor); out_dims = ValidateShape(new_shape, x_dims); } else if (ctx.HasInput("Shape")) { auto* shape_tensor = ctx.Input<framework::LoDTensor>("Shape"); auto* shape_data = shape_tensor->data<int>(); auto shape = std::vector<int>(shape_data, shape_data + shape_tensor->numel()); out_dims = ValidateShape(shape, x_dims); } } void InferShapeSqueezeOp(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto* x = ctx.Input<LoDTensor>("X"); x_dims = x->dims(); const auto& axes = ctx.Attr<std::vector<int>>("axes"); out_dims = GetOutputShape(axes, x_dims, true); } void InferShapeSqueeze2Op(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto* out = ctx.Output<LoDTensor>("Out"); auto* xshape = ctx.Output<LoDTensor>("XShape"); auto xshape_dims = xshape->dims(); x_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size()); out_dims = out->dims(); } void InferShapeFlattenOp(const framework::ExecutionContext& ctx, framework::DDim& x_dims, // NOLINT framework::DDim& out_dims) const { // NOLINT auto x = ctx.Input<LoDTensor>("X"); x_dims = x->dims(); auto axes = ctx.Attr<int>("axis"); out_dims = phi::make_ddim( FlattenKernel<platform::CPUDeviceContext, float>::GetOutputShape( axes, x_dims)); } protected: static dnnl::memory::format_tag getPlainFormatTag(const Tensor* tensor) { auto tensor_dims_size = tensor->dims().size(); PADDLE_ENFORCE_EQ( tensor_dims_size <= 6 && tensor_dims_size >= 1, true, platform::errors::InvalidArgument( "Dims for squeeze_grad oneDNN op must be in range <1, 6>")); switch (tensor_dims_size) { case 1: return dnnl::memory::format_tag::a; case 2: return dnnl::memory::format_tag::ab; case 3: return dnnl::memory::format_tag::abc; case 4: return dnnl::memory::format_tag::abcd; case 5: return dnnl::memory::format_tag::abcde; default: return dnnl::memory::format_tag::abcdef; } } static framework::DDim ValidateShape(const std::vector<int>& shape, const framework::DDim& in_dims) { const int64_t in_size = phi::product(in_dims); auto in_dims_vec = phi::vectorize(in_dims); bool all_positive = std::all_of(in_dims_vec.cbegin(), in_dims_vec.cend(), [](int64_t i) { return i > 0; }); // only one dimension can be set to -1, whose size will be automatically // infered const int64_t unk_dim_val = -1; const int64_t copy_dim_val = 0; std::vector<int64_t> output_shape(shape.size(), 0); int64_t capacity = 1; int unk_dim_idx = -1; for (size_t i = 0; i < shape.size(); ++i) { if (shape[i] == unk_dim_val) { PADDLE_ENFORCE_EQ( unk_dim_idx, -1, platform::errors::InvalidArgument( "Only one dimension value of 'shape' in ReshapeOp can " "be -1. But received shape = [%s], shape[%d] is also -1.", phi::make_ddim(shape), i)); unk_dim_idx = i; } else if (shape[i] == copy_dim_val) { PADDLE_ENFORCE_LT( static_cast<int>(i), in_dims.size(), platform::errors::InvalidArgument( "The index of 0 in `shape` must be less than " "the input tensor X's dimensions. " "But received shape = [%s], shape[%d] = 0, X's shape = [%s], " "X's dimensions = %d.", phi::make_ddim(shape), i, in_dims, in_dims.size())); } else { PADDLE_ENFORCE_GT( shape[i], 0, platform::errors::InvalidArgument( "Each dimension value of 'shape' in ReshapeOp must not " "be negative except one unknown dimension. " "But received shape = [%s], shape[%d] = %d.", phi::make_ddim(shape), i, shape[i])); } capacity *= (shape[i] ? shape[i] : in_dims[i]); output_shape[i] = (shape[i] ? static_cast<int64_t>(shape[i]) : in_dims[i]); } if (unk_dim_idx != -1) { if (all_positive) { // in_size < 0 and is un-determinate in compile time, skip the check, // for example, in_dims = [-1, 8, 1, 1], shape = [-1, 3, 8], // capacity = -24, in_size = -8, output_shape[0] = 0 // the following check will fail. output_shape[unk_dim_idx] = -in_size / capacity; PADDLE_ENFORCE_EQ( output_shape[unk_dim_idx] * capacity, -in_size, platform::errors::InvalidArgument( "The 'shape' attribute in ReshapeOp is invalid. " "The input tensor X'size must be divisible by known " "capacity of 'shape'. " "But received X's shape = [%s], X's size = %d, " "'shape' is [%s], known capacity of 'shape' is %d.", in_dims, in_size, phi::make_ddim(shape), capacity)); } else { output_shape[unk_dim_idx] = -1; } } else { if (all_positive) { PADDLE_ENFORCE_EQ( capacity, in_size, platform::errors::InvalidArgument( "The 'shape' in ReshapeOp is invalid. " "The input tensor X'size must be equal to the capacity of " "'shape'. " "But received X's shape = [%s], X's size = %d, 'shape' is " "[%s], the capacity of 'shape' is %d.", in_dims, in_size, phi::make_ddim(shape), capacity)); } } return phi::make_ddim(output_shape); } }; template <typename T, ReshapeKernelOpName op_name> class ReshapeGradMKLDNNKernel : public ReshapeMKLDNNKernel<T, op_name> { public: void Compute(const framework::ExecutionContext& ctx) const override { RunKernel(ctx); } private: void RunKernel(const framework::ExecutionContext& ctx) const { const auto& dev_ctx = ctx.template device_context<platform::MKLDNNDeviceContext>(); const auto& onednn_engine = dev_ctx.GetEngine(); auto* dout = ctx.Input<LoDTensor>(framework::GradVarName("Out")); auto* dx = ctx.Output<LoDTensor>(framework::GradVarName("X")); framework::DDim dx_dims; InferOutputShapeInGrad(ctx, dx_dims); auto dout_vec_dims = phi::vectorize(dout->dims()); dnnl::memory::data_type dout_type = framework::ToMKLDNNDataType( framework::TransToProtoVarType(dout->dtype())); platform::ReorderMKLDNNHandler reorder_handler( dout_vec_dims, framework::TransToProtoVarType(dout->dtype()), dout_type, onednn_engine); auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory( dout->format(), platform::to_void_cast(dout->data<T>())); auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory( dx, this->getPlainFormatTag(dout), ctx.GetPlace()); auto reorder_p = reorder_handler.AcquireReorder(reorder_src_memory_p, reorder_dst_memory_p); auto& astream = platform::MKLDNNDeviceContext::tls().get_stream(); reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p); astream.wait(); dx->Resize(dx_dims); dx->set_layout(framework::DataLayout::kMKLDNN); dx->set_format(GetMKLDNNFormat( reorder_dst_memory_p->get_desc().reshape(phi::vectorize(dx_dims)))); } void InferOutputShapeInGrad(const framework::ExecutionContext& ctx, framework::DDim& x_dims) const { // NOLINT switch (op_name) { case ReshapeKernelOpName::reshape: InferShapeReshapeSqueezeGradOp(ctx, x_dims); break; case ReshapeKernelOpName::reshape2: InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims); break; case ReshapeKernelOpName::squeeze: InferShapeReshapeSqueezeGradOp(ctx, x_dims); break; case ReshapeKernelOpName::squeeze2: InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims); break; case ReshapeKernelOpName::flatten: InferShapeFlattenGradOp(ctx, x_dims); break; case ReshapeKernelOpName::flatten2: InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims); break; default: PADDLE_THROW(paddle::platform::errors::OutOfRange( "Reshape grad kernel doesn not support that operator name")); } } void InferShapeReshapeSqueezeGradOp( const framework::ExecutionContext& ctx, framework::DDim& dx_dims) const { // NOLINT auto* dx = ctx.Output<LoDTensor>(framework::GradVarName("X")); dx_dims = dx->dims(); } void InferShapeReshape2Squeeze2Flatten2GradOp( const framework::ExecutionContext& ctx, framework::DDim& dx_dims) const { // NOLINT auto xshape_dims = ctx.Input<framework::LoDTensor>("XShape")->dims(); dx_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size()); } void InferShapeFlattenGradOp(const framework::ExecutionContext& ctx, framework::DDim& dx_dims) const { // NOLINT dx_dims = ctx.Input<LoDTensor>("X")->dims(); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL( squeeze, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::squeeze>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::squeeze>); REGISTER_OP_KERNEL( squeeze_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::squeeze>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::squeeze>); REGISTER_OP_KERNEL( squeeze2, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::squeeze2>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::squeeze2>); REGISTER_OP_KERNEL( squeeze2_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::squeeze2>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::squeeze2>); REGISTER_OP_KERNEL( reshape, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::reshape>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::reshape>); REGISTER_OP_KERNEL( reshape_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::reshape>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::reshape>); REGISTER_OP_KERNEL( reshape2, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::reshape2>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::reshape2>); REGISTER_OP_KERNEL( reshape2_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::reshape2>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::reshape2>); REGISTER_OP_KERNEL( flatten, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::flatten>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::flatten>); REGISTER_OP_KERNEL( flatten_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::flatten>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::flatten>); REGISTER_OP_KERNEL( flatten2, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::flatten2>, ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::flatten2>); REGISTER_OP_KERNEL( flatten2_grad, MKLDNN, paddle::platform::CPUPlace, ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::flatten2>, ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16, ReshapeKernelOpName::flatten2>);
[ "noreply@github.com" ]
noreply@github.com
d43b1ec570dc1ef5727ffecfddad46f84d027ab8
ad5b72656f0da99443003984c1e646cb6b3e67ea
/src/common/transformations/src/transformations/op_conversions/convert_gather_upgrade.cpp
5cb8d06d7f108dbd69e3ff2e4bdaf61d5505d4f7
[ "Apache-2.0" ]
permissive
novakale/openvino
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
544c1acd2be086c35e9f84a7b4359439515a0892
refs/heads/master
2022-12-31T08:04:48.124183
2022-12-16T09:05:34
2022-12-16T09:05:34
569,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
2,580
cpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/op_conversions/convert_gather_upgrade.hpp" #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/rt_info.hpp> #include <openvino/opsets/opset1.hpp> #include <openvino/opsets/opset7.hpp> #include <openvino/opsets/opset8.hpp> #include "itt.hpp" using namespace std; using namespace ov; pass::ConvertGather1ToGather7::ConvertGather1ToGather7() { MATCHER_SCOPE(ConvertGather1ToGather7); auto gather_v1_pattern = pattern::wrap_type<opset1::Gather>(); matcher_pass_callback callback = [=](pattern::Matcher& m) { auto gather_v1_node = std::dynamic_pointer_cast<opset1::Gather>(m.get_match_root()); if (!gather_v1_node) return false; auto gather_v7_node = make_shared<opset7::Gather>(gather_v1_node->input_value(0), gather_v1_node->input_value(1), gather_v1_node->input_value(2), 0); gather_v7_node->set_friendly_name(gather_v1_node->get_friendly_name()); ngraph::copy_runtime_info(gather_v1_node, gather_v7_node); ngraph::replace_node(gather_v1_node, gather_v7_node); return true; }; auto m = make_shared<pattern::Matcher>(gather_v1_pattern, matcher_name); register_matcher(m, callback); } pass::ConvertGather7ToGather8::ConvertGather7ToGather8() { MATCHER_SCOPE(ConvertGather7ToGather8); auto gather_v7_pattern = pattern::wrap_type<opset7::Gather>(); matcher_pass_callback callback = [=](pattern::Matcher& m) { auto gather_v7_node = std::dynamic_pointer_cast<opset7::Gather>(m.get_match_root()); if (!gather_v7_node) return false; auto gather_v8_node = make_shared<opset8::Gather>(gather_v7_node->input_value(0), gather_v7_node->input_value(1), gather_v7_node->input_value(2), gather_v7_node->get_batch_dims()); gather_v8_node->set_friendly_name(gather_v7_node->get_friendly_name()); ngraph::copy_runtime_info(gather_v7_node, gather_v8_node); ngraph::replace_node(gather_v7_node, gather_v8_node); return true; }; auto m = make_shared<pattern::Matcher>(gather_v7_pattern, matcher_name); register_matcher(m, callback); }
[ "noreply@github.com" ]
noreply@github.com
59d6e7d49e25f56cc11e9ddca74eb5773ea94dea
38e2a03b73fdaf0c5ef4a6311a763d1329feef00
/DataManage/DepartMng.h
9f0560d853f861a9537c830f49ba13e2751055a6
[]
no_license
lty1058861950/MyRepository
f95f9f73809c3076ef417648fc13c3aedc0a284a
ad97587a45a280b2b6e62437cf80e181c42f844a
refs/heads/master
2021-07-13T15:51:34.951548
2017-10-18T09:30:10
2017-10-18T09:30:10
107,383,590
0
1
null
null
null
null
GB18030
C++
false
false
1,595
h
#pragma once #include "afxcmn.h" #include "mylistctrl\editablelistctrl.h" #include "ShowDepart.h" // CDepartMng 对话框 class CDepartMng : public CDialog { DECLARE_DYNAMIC(CDepartMng) public: CDepartMng(CWnd* pParent = NULL); // 标准构造函数 virtual ~CDepartMng(); // 对话框数据 enum { IDD = IDD_GROUPMNG_DLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: StHrGroup m_CurSelDepart; CTreeCtrl m_DepartMngTree; CEditableListCtrl m_CurDepartUsrList; CImageList m_TreeImgList; public: CMenu m_PopupMenu1; CMenu m_PopupMenu2; void InitPopMenu1( ); //初始化菜单1 void InitPopMenu2( ); //初始化菜单2 public: void InitDepartTree(); void InitUsrList(); void InitContrlState(); void NotFindSetNull(); void ShowDepartInfo(); BOOL DeleteOneDepart(StHrGroup *pDepartInfo); BOOL AddNewDepart(StHrGroup *pDepartInfo); BOOL EditOneDepart(StHrGroup *pDepartInfo); void SetDepartTree(CString strText,int EditMode,int Param = 0,HTREEITEM NextItem = NULL); void AutoSize(); virtual BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnNMClickDepartMngTree(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedDepartAddBtn(); afx_msg void OnBnClickedDepartDelBtn(); afx_msg void OnBnClickedDepartEditBtn(); afx_msg void OnNMDblclkDepartMngTree(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnNMRClickDepartMngTree(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedRecoveryBtn(); };
[ "liutengya1991@qq.com" ]
liutengya1991@qq.com
9ba571795c59e27c63da3e9f12f622a03d76252b
420835dc0d8672fc1d620fd3f1d10f1197fa076c
/checkCheckState.cc
d509b5eaf510b53e9c6b6e3ee963d11c4934ea6a
[]
no_license
kota/dobutsu
5e5a245e07d85c69d58398268b685af692ae9dff
d45488632ff2f6f2883a4b90ba98c04b531b2fed
refs/heads/master
2021-01-18T21:31:56.082901
2011-12-23T14:30:01
2011-12-23T14:30:01
null
0
0
null
null
null
null
EUC-JP
C++
false
false
1,019
cc
/** * csa形式の盤面ファイルを読み込んで * 詰みの時にその後の終局までの読み筋を表示する * ファイルを指定しない時は最大手数(23手)の局面の読み筋を表示する. */ #include "dobutsu.h" #include "allStateTable.h" #include "winLoseTable.h" #include <fstream> void usage() { std::cerr << "Usage: checkCheckState csafile" << std::endl; } int main(int ac,char **ag) { if(ac<2){ AllStateTable allS("allstates.dat"); WinLoseTable winLoseCheck(allS,"winLossCheck.dat","winLossCheckCount.dat"); for(size_t i=0;i<allS.size();i++){ if(winLoseCheck.getWinLoseCount(i)==23){ State s(allS[i],BLACK); winLoseCheck.showSequence(s); } } } std::ifstream ifs(ag[1]); std::string all; std::string line; while( getline(ifs,line) ){ all += line; } State s(all); AllStateTable allS("allstates.dat"); WinLoseTable winLoseCheck(allS,"winLossCheck.dat","winLossCheckCount.dat"); winLoseCheck.showSequence(s); }
[ "fujiwara.kota@gmail.com" ]
fujiwara.kota@gmail.com
705df6bd29b23f5473d211be1da4dfd0188271ed
e43967d7d871492b177d2af832f4f88b5804b778
/pruebas/src/TarjetaCLStarcosTest.cpp
148941787fceb807f0f3a5498c86ce10c7c2478f
[]
no_license
jmnavarro/PKI_Cryptocard_Engine
1bb15f3c12337e9944335cc72f7625d9a632b7c0
f5c577f3c81f35041bb02a65048b2f95652b2ad8
refs/heads/master
2021-01-19T11:48:20.995926
2012-06-20T22:49:37
2012-06-20T22:49:37
4,732,410
0
1
null
null
null
null
WINDOWS-1250
C++
false
false
2,325
cpp
#include "../h/TarjetaCLStarcosTest.h" #include "TestSuite.h" #undef TEST_TARJETA_CERES #undef TEST_TARJETA_ETOKEN #undef TEST_TARJETA_SIEMENS #define TEST_TARJETA_STARCOS #include "../h/DatosTarjeta.h" TarjetaCLStarcosTest::TarjetaCLStarcosTest(std::string name) : TestCase(name) { } TarjetaCLStarcosTest::~TarjetaCLStarcosTest() { } void TarjetaCLStarcosTest::setUp() { obj = new TarjetaCLStarcos(); } void TarjetaCLStarcosTest::tearDown() { delete obj; } Test* TarjetaCLStarcosTest::suite() { TestSuite *suite = new TestSuite("TarjetaCLStarcos (requiere dos tarjetas cualquiera)"); suite->addTest( new TarjetaCLStarcosTestCaller("Conectar", &TarjetaCLStarcosTest::testConectar) ); suite->addTest( new TarjetaCLStarcosTestCaller("PedirPIN", &TarjetaCLStarcosTest::testPedirPIN) ); suite->addTest( new TarjetaCLStarcosTestCaller("CambioTarjeta", &TarjetaCLStarcosTest::testCambioTarjeta) ); return (suite); } void TarjetaCLStarcosTest::testConectar() { VALIDAR(obj->conectar()); // conecta __try { VALIDAR(obj->conectar()); // no hace nada } __finally { VALIDAR(obj->desconectar()); // desconecta VALIDAR(obj->desconectar()); // no hace nada } } void TarjetaCLStarcosTest::testPedirPIN() { bool pinOK; ArsCadena msg; VALIDAR( obj->conectar() ); __try { pinOK = obj->establecerPIN(PIN_ERRONEO, msg); VALIDAR_CON_MENSAJE( !pinOK, msg.cadena() ); pinOK = obj->establecerPIN(PIN_CORRECTO, msg); VALIDAR_CON_MENSAJE( pinOK, msg.cadena() ); // volver a establecer pinOK = obj->establecerPIN(PIN_CORRECTO, msg); VALIDAR_CON_MENSAJE( pinOK, msg.cadena() ); } __finally { VALIDAR( obj->desconectar() ); } } void TarjetaCLStarcosTest::testCambioTarjeta() { MessageBox(GetActiveWindow(), "Introduce una tarjeta...", "Test cambio tarjeta", MB_ICONINFORMATION); VALIDAR( obj->conectar() ); VALIDAR( obj->desconectar() ); MessageBox(GetActiveWindow(), "Ahora introduce otra tarjeta distinta...", "Test cambio tarjeta", MB_ICONINFORMATION); VALIDAR( obj->conectar() ); VALIDAR( obj->desconectar() ); MessageBox(GetActiveWindow(), "Y otra más...", "Test cambio tarjeta", MB_ICONINFORMATION); VALIDAR( obj->conectar() ); VALIDAR( obj->desconectar() ); }
[ "jmnavarro@gmail.com" ]
jmnavarro@gmail.com
7eabc1544d162463c53262b8dafd9d7e9764926b
83c0700a9b14dbd2eed4ad9abe7594a8ff12ce0a
/media/libstagefright/include/media/stagefright/MediaClock.h
dd1a8091c76e966f6aa500639d084644b6a9fd8f
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
PixelExperience/frameworks_av
e5ab74641a88237ac84ff698539c95033a3aa09f
10d08c030053cbcb30d114630b3276fddce96a45
refs/heads/oreo-mr1
2023-08-05T20:29:20.970331
2018-12-04T20:38:27
2018-12-04T20:38:27
130,521,429
8
167
NOASSERTION
2023-07-15T06:06:36
2018-04-22T00:10:21
C++
UTF-8
C++
false
false
2,220
h
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MEDIA_CLOCK_H_ #define MEDIA_CLOCK_H_ #include <media/stagefright/foundation/ABase.h> #include <utils/Mutex.h> #include <utils/RefBase.h> namespace android { struct AMessage; struct MediaClock : public RefBase { MediaClock(); void setStartingTimeMedia(int64_t startingTimeMediaUs); void clearAnchor(); // It's required to use timestamp of just rendered frame as // anchor time in paused state. void updateAnchor( int64_t anchorTimeMediaUs, int64_t anchorTimeRealUs, int64_t maxTimeMediaUs = INT64_MAX); void updateMaxTimeMedia(int64_t maxTimeMediaUs); void setPlaybackRate(float rate); float getPlaybackRate() const; // query media time corresponding to real time |realUs|, and save the // result in |outMediaUs|. status_t getMediaTime( int64_t realUs, int64_t *outMediaUs, bool allowPastMaxTime = false) const; // query real time corresponding to media time |targetMediaUs|. // The result is saved in |outRealUs|. status_t getRealTimeFor(int64_t targetMediaUs, int64_t *outRealUs) const; protected: virtual ~MediaClock(); private: status_t getMediaTime_l( int64_t realUs, int64_t *outMediaUs, bool allowPastMaxTime) const; mutable Mutex mLock; int64_t mAnchorTimeMediaUs; int64_t mAnchorTimeRealUs; int64_t mMaxTimeMediaUs; int64_t mStartingTimeMediaUs; float mPlaybackRate; DISALLOW_EVIL_CONSTRUCTORS(MediaClock); }; } // namespace android #endif // MEDIA_CLOCK_H_
[ "wjia@google.com" ]
wjia@google.com
7d1f64091b18782122ac6d6de0ee36a3576c43d7
978f4752c5dcb821193d19b757c6ae2e9d557cf4
/testSwap/Widget.cpp
066b470304af669d5fa05cc121b32802288e1234
[]
no_license
distanceNing/stlTest
2c2785bb3fed3b04c9ed5d1af9e414ac27c83451
b165186a7c0c36719dd2e60a449bdce38ccee870
refs/heads/master
2021-09-05T09:38:09.667473
2018-01-26T05:07:16
2018-01-26T05:07:16
104,046,487
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
#include "Widget.h" Widget::Widget(const Widget & rhs) { pImpl = rhs.pImpl; } Widget::Widget(int a) { pImpl = new WidgetImpl; pImpl->a = a; } Widget::~Widget() { delete pImpl; } void Widget::swap(Widget& other) { using std::swap; swap(pImpl, other.pImpl); }
[ "distancening@gmail.com" ]
distancening@gmail.com
27ed608efa673b9bbb974362204af17d5bddcb74
fd0774163ebfb6a9b25523e5ee8510c7cd9fefb7
/4050/project/ogltuto/01/LUtil.cpp
887cc90a7c2b1c1c5cb71832e9cea87a91d433fd
[]
no_license
wumetal/coursInClemson
54803ecb2f9e9180ef36039e334c6ad292026023
3e0fb562cecf61794e50eadf2010b9063f307f72
refs/heads/master
2021-09-13T17:03:17.964735
2018-05-02T11:28:53
2018-05-02T11:28:53
104,118,415
0
0
null
2018-02-14T01:00:38
2017-09-19T19:23:13
Python
UTF-8
C++
false
false
846
cpp
#include "LUtil.h" GLFWwindow* window; bool initGL( void ) { if( !glfwInit() ){ fprintf(stderr, "Failed to initialize GLFW .\n" ); getchar(); return false; } // 4x antialiasing glfwWindowHint( GLFW_SAMPLES, 4 ); // Set the context to be 2 glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 2 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 ); // Open a window and create its OpenGL context window = glfwCreateWindow( SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_TITLE, NULL, NULL ); if( window == NULL ) { fprintf(stderr, "Failed to open GLFW window.\n" ); getchar(); glfwTerminate(); return false; } glfwMakeContextCurrent( window ); // Init glew if( glewInit() != GLEW_OK ) { fprintf(stderr, "Failed to init GLEW\n" ); getchar(); glfwTerminate(); return false; } return true; }
[ "yupengw@ada6.cs.clemson.edu" ]
yupengw@ada6.cs.clemson.edu
3257fdd199e31168d42026486e8fdea6d0f98af2
eecf89b4c603f49f011bbd5b2c029dd6bebf4db7
/fboss/agent/hw/sai/switch/tests/PortManagerTest.cpp
e2f861a3703b05fcd877ed37ec87f971e9feba94
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
markkun/fboss
69570abf9feb943b3f9aed0b11d6385e5bf4cf3a
04bd5a28da927335e948e381e9578b16929a446e
refs/heads/master
2023-02-11T06:46:29.970427
2021-01-15T00:44:58
2021-01-15T00:46:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,598
cpp
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/FbossError.h" #include "fboss/agent/hw/HwPortFb303Stats.h" #include "fboss/agent/hw/StatsConstants.h" #include "fboss/agent/hw/sai/api/SaiApiTable.h" #include "fboss/agent/hw/sai/fake/FakeSai.h" #include "fboss/agent/hw/sai/store/SaiStore.h" #include "fboss/agent/hw/sai/switch/SaiManagerTable.h" #include "fboss/agent/hw/sai/switch/SaiPortManager.h" #include "fboss/agent/hw/sai/switch/tests/ManagerTestBase.h" #include "fboss/agent/platforms/sai/SaiPlatform.h" #include "fboss/agent/platforms/sai/SaiPlatformPort.h" #include "fboss/agent/state/Port.h" #include "fboss/agent/types.h" #include <fb303/ServiceData.h> #include <string> #include <gtest/gtest.h> using namespace facebook::fboss; class PortManagerTest : public ManagerTestBase { public: void SetUp() override { setupStage = SetupStage::BLANK; ManagerTestBase::SetUp(); p0 = testInterfaces[0].remoteHosts[0].port; p1 = testInterfaces[1].remoteHosts[0].port; } // TODO: make it properly handle different lanes/speeds for different // port ids... void checkPort( const PortID& swId, const SaiPortHandle* handle, bool enabled, sai_uint32_t mtu = 9412) { // Check SaiPortApi perspective auto& portApi = saiApiTable->portApi(); auto saiId = handle->port->adapterKey(); SaiPortTraits::Attributes::AdminState adminStateAttribute; SaiPortTraits::Attributes::HwLaneList hwLaneListAttribute; SaiPortTraits::Attributes::Speed speedAttribute; SaiPortTraits::Attributes::FecMode fecMode; SaiPortTraits::Attributes::InternalLoopbackMode ilbMode; SaiPortTraits::Attributes::Mtu mtuAttribute; auto gotAdminState = portApi.getAttribute(saiId, adminStateAttribute); EXPECT_EQ(enabled, gotAdminState); auto gotLanes = portApi.getAttribute(saiId, hwLaneListAttribute); EXPECT_EQ(1, gotLanes.size()); EXPECT_EQ(swId, gotLanes[0]); auto gotSpeed = portApi.getAttribute(saiId, speedAttribute); EXPECT_EQ(25000, gotSpeed); auto gotFecMode = portApi.getAttribute(saiId, fecMode); EXPECT_EQ(static_cast<int32_t>(SAI_PORT_FEC_MODE_NONE), gotFecMode); auto gotIlbMode = portApi.getAttribute(saiId, ilbMode); EXPECT_EQ( static_cast<int32_t>(SAI_PORT_INTERNAL_LOOPBACK_MODE_NONE), gotIlbMode); auto gotMtu = portApi.getAttribute(saiId, mtuAttribute); EXPECT_EQ(mtu, gotMtu); ASSERT_NE(handle->serdes.get(), nullptr); checkPortSerdes(handle->serdes.get(), saiId); } void checkPortSerdes(SaiPortSerdes* serdes, PortSaiId portId) { auto& portApi = saiApiTable->portApi(); EXPECT_EQ( portApi.getAttribute( serdes->adapterKey(), SaiPortSerdesTraits::Attributes::PortId{}), portId); } /** * DO NOT use this routine for adding ports. * This is only used to verify port consolidation logic in sai port * manager. It makes certain assumptions about the lane numbers and * also adds the port under the hood bypassing the port manager. */ PortSaiId addPort(const PortID& swId, cfg::PortSpeed portSpeed) { auto& portApi = saiApiTable->portApi(); std::vector<uint32_t> ls; if (portSpeed == cfg::PortSpeed::TWENTYFIVEG) { ls.push_back(swId); } else { ls.push_back(swId); ls.push_back(swId + 1); ls.push_back(swId + 2); ls.push_back(swId + 3); } SaiPortTraits::Attributes::AdminState adminState{true}; SaiPortTraits::Attributes::HwLaneList lanes(ls); SaiPortTraits::Attributes::Speed speed{static_cast<int>(portSpeed)}; SaiPortTraits::CreateAttributes a{ lanes, speed, adminState, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt}; return portApi.create<SaiPortTraits>(a, 0); } void checkSubsumedPorts( TestPort port, cfg::PortSpeed speed, std::vector<PortID> expectedPorts) { std::shared_ptr<Port> swPort = makePort(port); swPort->setSpeed(speed); saiManagerTable->portManager().addPort(swPort); SaiPlatformPort* platformPort = saiPlatform->getPort(swPort->getID()); EXPECT_TRUE(platformPort); auto subsumedPorts = platformPort->getSubsumedPorts(speed); EXPECT_EQ(subsumedPorts, expectedPorts); saiManagerTable->portManager().removePort(swPort); } TestPort p0; TestPort p1; }; enum class ExpectExport { NO_EXPORT, EXPORT }; TEST_F(PortManagerTest, addPort) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); auto handle = saiManagerTable->portManager().getPortHandle(swPort->getID()); checkPort(PortID(0), handle, true); } TEST_F(PortManagerTest, addTwoPorts) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); std::shared_ptr<Port> port2 = makePort(p1); saiManagerTable->portManager().addPort(port2); auto handle = saiManagerTable->portManager().getPortHandle(port2->getID()); checkPort(PortID(10), handle, true); } TEST_F(PortManagerTest, iterator) { std::set<PortSaiId> addedPorts; auto& portMgr = saiManagerTable->portManager(); std::shared_ptr<Port> swPort = makePort(p0); addedPorts.insert(portMgr.addPort(swPort)); std::shared_ptr<Port> port2 = makePort(p1); addedPorts.insert(portMgr.addPort(port2)); for (const auto& portIdAnHandle : portMgr) { auto& handle = portIdAnHandle.second; EXPECT_TRUE( addedPorts.find(handle->port->adapterKey()) != addedPorts.end()); addedPorts.erase(handle->port->adapterKey()); } EXPECT_EQ(0, addedPorts.size()); } TEST_F(PortManagerTest, addDupIdPorts) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); EXPECT_THROW(saiManagerTable->portManager().addPort(swPort), FbossError); } TEST_F(PortManagerTest, getBySwId) { std::shared_ptr<Port> swPort = makePort(p1); saiManagerTable->portManager().addPort(swPort); SaiPortHandle* port = saiManagerTable->portManager().getPortHandle(PortID(10)); EXPECT_TRUE(port); EXPECT_EQ(GET_OPT_ATTR(Port, AdminState, port->port->attributes()), true); EXPECT_EQ(GET_ATTR(Port, Speed, port->port->attributes()), 25000); auto hwLaneList = GET_ATTR(Port, HwLaneList, port->port->attributes()); EXPECT_EQ(hwLaneList.size(), 1); EXPECT_EQ(hwLaneList[0], 10); } TEST_F(PortManagerTest, getNonExistent) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); SaiPortHandle* port = saiManagerTable->portManager().getPortHandle(PortID(10)); EXPECT_FALSE(port); } TEST_F(PortManagerTest, removePort) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); SaiPortHandle* port = saiManagerTable->portManager().getPortHandle(PortID(0)); EXPECT_TRUE(port); saiManagerTable->portManager().removePort(swPort); port = saiManagerTable->portManager().getPortHandle(PortID(0)); EXPECT_FALSE(port); } TEST_F(PortManagerTest, removeNonExistentPort) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); SaiPortHandle* port = saiManagerTable->portManager().getPortHandle(PortID(0)); EXPECT_TRUE(port); TestPort p10; p10.id = 10; std::shared_ptr<Port> swPort10 = makePort(p10); EXPECT_THROW(saiManagerTable->portManager().removePort(swPort10), FbossError); } TEST_F(PortManagerTest, changePortAdminState) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); swPort->setAdminState(cfg::PortState::DISABLED); saiManagerTable->portManager().changePort(swPort, swPort); auto handle = saiManagerTable->portManager().getPortHandle(swPort->getID()); checkPort(swPort->getID(), handle, false); } TEST_F(PortManagerTest, changePortMtu) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); swPort->setMaxFrameSize(9000); saiManagerTable->portManager().changePort(swPort, swPort); auto handle = saiManagerTable->portManager().getPortHandle(swPort->getID()); checkPort(swPort->getID(), handle, true, 9000); } TEST_F(PortManagerTest, changePortNoChange) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); swPort->setSpeed(cfg::PortSpeed::TWENTYFIVEG); swPort->setAdminState(cfg::PortState::ENABLED); saiManagerTable->portManager().changePort(swPort, swPort); auto handle = saiManagerTable->portManager().getPortHandle(swPort->getID()); checkPort(swPort->getID(), handle, true); } TEST_F(PortManagerTest, changeNonExistentPort) { std::shared_ptr<Port> swPort = makePort(p0); std::shared_ptr<Port> swPort2 = makePort(p1); saiManagerTable->portManager().addPort(swPort); swPort2->setSpeed(cfg::PortSpeed::TWENTYFIVEG); EXPECT_THROW( saiManagerTable->portManager().changePort(swPort2, swPort2), FbossError); } TEST_F(PortManagerTest, portConsolidationAddPort) { PortID portId(0); // adds a port "behind the back of" PortManager auto saiId0 = addPort(portId, cfg::PortSpeed::TWENTYFIVEG); // loads the added port into SaiStore SaiStore::getInstance()->release(); SaiStore::getInstance()->reload(); // add a port with the same lanes through PortManager std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); auto handle1 = saiManagerTable->portManager().getPortHandle(PortID(0)); auto saiId1 = handle1->port->adapterKey(); checkPort(portId, handle1, true); // expect it to return the existing port rather than create a new one EXPECT_EQ(saiId0, saiId1); } void checkCounterExport( const std::string& portName, ExpectExport expectExport) { for (auto statKey : HwPortFb303Stats::kPortStatKeys()) { switch (expectExport) { case ExpectExport::EXPORT: EXPECT_TRUE(facebook::fbData->getStatMap()->contains( HwPortFb303Stats::statName(statKey, portName))); break; case ExpectExport::NO_EXPORT: EXPECT_FALSE(facebook::fbData->getStatMap()->contains( HwPortFb303Stats::statName(statKey, portName))); break; } } } TEST_F(PortManagerTest, changePortNameAndCheckCounters) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); for (auto statKey : HwPortFb303Stats::kPortStatKeys()) { EXPECT_TRUE(facebook::fbData->getStatMap()->contains( HwPortFb303Stats::statName(statKey, swPort->getName()))); } auto newPort = swPort->clone(); newPort->setName("eth1/1/1"); saiManagerTable->portManager().changePort(swPort, newPort); checkCounterExport(swPort->getName(), ExpectExport::NO_EXPORT); checkCounterExport(newPort->getName(), ExpectExport::EXPORT); } TEST_F(PortManagerTest, updateStats) { std::shared_ptr<Port> swPort = makePort(p0); saiManagerTable->portManager().addPort(swPort); auto handle = saiManagerTable->portManager().getPortHandle(swPort->getID()); checkPort(PortID(0), handle, true); saiManagerTable->portManager().updateStats(swPort->getID()); auto portStat = saiManagerTable->portManager().getLastPortStat(swPort->getID()); for (auto statKey : HwPortFb303Stats::kPortStatKeys()) { EXPECT_EQ( portStat->getCounterLastIncrement( HwPortFb303Stats::statName(statKey, swPort->getName())), 0); } } TEST_F(PortManagerTest, portDisableStopsCounterExport) { std::shared_ptr<Port> swPort = makePort(p0); CHECK(swPort->isEnabled()); saiManagerTable->portManager().addPort(swPort); checkCounterExport(swPort->getName(), ExpectExport::EXPORT); auto newPort = swPort->clone(); newPort->setAdminState(cfg::PortState::DISABLED); saiManagerTable->portManager().changePort(swPort, newPort); checkCounterExport(swPort->getName(), ExpectExport::NO_EXPORT); } TEST_F(PortManagerTest, portReenableRestartsCounterExport) { std::shared_ptr<Port> swPort = makePort(p0); CHECK(swPort->isEnabled()); saiManagerTable->portManager().addPort(swPort); checkCounterExport(swPort->getName(), ExpectExport::EXPORT); auto newPort = swPort->clone(); newPort->setAdminState(cfg::PortState::DISABLED); saiManagerTable->portManager().changePort(swPort, newPort); checkCounterExport(swPort->getName(), ExpectExport::NO_EXPORT); auto newNewPort = newPort->clone(); newNewPort->setAdminState(cfg::PortState::ENABLED); saiManagerTable->portManager().changePort(newPort, newNewPort); checkCounterExport(swPort->getName(), ExpectExport::EXPORT); } TEST_F(PortManagerTest, collectStatsAfterPortDisable) { std::shared_ptr<Port> swPort = makePort(p0); CHECK(swPort->isEnabled()); saiManagerTable->portManager().addPort(swPort); checkCounterExport(swPort->getName(), ExpectExport::EXPORT); auto newPort = swPort->clone(); newPort->setAdminState(cfg::PortState::DISABLED); saiManagerTable->portManager().changePort(swPort, newPort); saiManagerTable->portManager().updateStats(swPort->getID()); EXPECT_EQ(saiManagerTable->portManager().getPortStats().size(), 0); checkCounterExport(swPort->getName(), ExpectExport::NO_EXPORT); } TEST_F(PortManagerTest, subsumedPorts) { // Port P0 has a port ID 0 and only be configured with all speeds. checkSubsumedPorts(p0, cfg::PortSpeed::XG, {}); checkSubsumedPorts(p0, cfg::PortSpeed::TWENTYFIVEG, {}); checkSubsumedPorts(p0, cfg::PortSpeed::FIFTYG, {PortID(p0.id + 1)}); std::vector<PortID> expectedPortList = { PortID(p0.id + 1), PortID(p0.id + 2), PortID(p0.id + 3)}; checkSubsumedPorts(p0, cfg::PortSpeed::FORTYG, expectedPortList); checkSubsumedPorts(p0, cfg::PortSpeed::HUNDREDG, expectedPortList); // Port P1 has a port ID 10 and only be configured with 10, 25 and 50G modes. checkSubsumedPorts(p1, cfg::PortSpeed::XG, {}); checkSubsumedPorts(p1, cfg::PortSpeed::TWENTYFIVEG, {}); checkSubsumedPorts(p1, cfg::PortSpeed::FIFTYG, {PortID(p1.id + 1)}); } TEST_F(PortManagerTest, getTransceiverID) { std::vector<uint16_t> controllingPorts = {0, 4, 24}; std::vector<uint16_t> expectedTcvrIDs = {0, 1, 6}; for (auto i = 0; i < controllingPorts.size(); i++) { for (auto lane = 0; lane < 4; lane++) { uint16_t port = controllingPorts[i] + lane; SaiPlatformPort* platformPort = saiPlatform->getPort(PortID(port)); EXPECT_TRUE(platformPort); EXPECT_EQ(expectedTcvrIDs[i], platformPort->getTransceiverID().value()); } } } TEST_F(PortManagerTest, attributesFromSwPort) { std::shared_ptr<Port> swPort = makePort(p0); auto& portMgr = saiManagerTable->portManager(); portMgr.addPort(swPort); auto portHandle = portMgr.getPortHandle(PortID(0)); auto attrs = portMgr.attributesFromSwPort(swPort); EXPECT_EQ(attrs, portHandle->port->attributes()); } TEST_F(PortManagerTest, swPortFromAttributes) { std::shared_ptr<Port> swPort = makePort(p0); auto& portMgr = saiManagerTable->portManager(); portMgr.addPort(swPort); auto attrs = portMgr.attributesFromSwPort(swPort); auto newPort = portMgr.swPortFromAttributes(attrs); EXPECT_EQ(attrs, portMgr.attributesFromSwPort(newPort)); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
8a6fc3ef28e1af6830bd233b5ac0b8e0e4f11f3f
02792a66bbd66a1ffc31477e5ef10f9c38800773
/src/include/chest.hpp
4d47c7d8fd2cae2553813fa27989cdb4076eae14
[]
no_license
ProfessorChill/NCurses-RogueLike
a2d1a7671f5f8aebde94aef8968a4fff505a1995
b4947dfd6550eae14fe1b0342067aec1f50a0b2e
refs/heads/master
2021-01-02T11:09:32.803788
2020-04-27T19:51:30
2020-04-27T19:51:30
239,595,416
0
0
null
null
null
null
UTF-8
C++
false
false
283
hpp
#ifndef CHEST_HPP #define CHEST_HPP #include <ncurses.h> #include <random> #include <string> #include <vector> #include "functions.hpp" #include "item.hpp" class Chest { public: Chest(); int x; int y; std::vector<Item> loot; void displayLoot(WINDOW *pWin); }; #endif
[ "codezmusic@gmail.com" ]
codezmusic@gmail.com
af6eacc5f1d38bd5751374e70ac7c22ff9ec713b
597e09d2845616dea7e01ceaa4c0252d2adcd355
/XStack.hpp
66913fbb90951d11254837b4af936e5a1436ecc4
[]
no_license
CsloudX/xd_src
2e4282db005927740dda040450fd8f45b390dd1d
7282699d8a441f5efe47db507c2c0d97a78e4921
refs/heads/master
2020-04-18T18:43:53.725351
2019-02-14T12:13:03
2019-02-14T12:13:03
157,395,474
0
0
null
null
null
null
UTF-8
C++
false
false
301
hpp
#ifndef X_STACK_HPP #define X_STACK_HPP #include "XArray.hpp" template<typename T> class XStack : public XArray<T> { public: XStack(int bufferSize=0):XArray(bufferSize){} void push(const T& value) { append(value); } T pop() { T ret = last(); removeLast(); return ret; } }; #endif // X_STACK_HPP
[ "978028760@qq.com" ]
978028760@qq.com
b173b1bee9a9c06b6b7ed091db07bf0a19c8c5f9
1461d854afde6abea7b08824cbc6e345ff8c1e48
/src/bitcoinrpc.cpp
4fe053252d34496566f7d5a5a58c6133ec9f6fba
[ "MIT" ]
permissive
Nanotoken/nanotoken
5442bdba9b0030575f0d6db608dce79a4338c8f2
08127376fe24b0244229f0d2965e08cebd8617f7
refs/heads/master
2021-01-09T09:01:22.686297
2014-04-21T16:36:21
2014-04-21T16:36:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
116,552
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 The Litecoin Developers // Copyright (c) 2013 nanotoken Developers // nanotoken; no copyright. open source you bitch // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "wallet.h" #include "db.h" #include "walletdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; static int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern Value getconnectioncount(const Array& params, bool fHelp); // in rpcnet.cpp extern Value getpeerinfo(const Array& params, bool fHelp); extern Value dumpprivkey(const Array& params, bool fHelp); // in rpcdump.cpp extern Value importprivkey(const Array& params, bool fHelp); extern Value getrawtransaction(const Array& params, bool fHelp); // in rcprawtransaction.cpp extern Value listunspent(const Array& params, bool fHelp); extern Value createrawtransaction(const Array& params, bool fHelp); extern Value decoderawtransaction(const Array& params, bool fHelp); extern Value signrawtransaction(const Array& params, bool fHelp); extern Value sendrawtransaction(const Array& params, bool fHelp); const Object emptyobj; void ThreadRPCServer3(void* parg); Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (v.type() != t) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(-3, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (v.type() == null_type) throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str())); if (v.type() != t.second) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(-3, err); } } } double GetDifficulty(const CBlockIndex* blockindex = NULL) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(-3, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(-3, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (confirms) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(-11, "Invalid account name"); return strAccount; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } /// Note: This interface may still be subject to change. string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "stop\n" "Stop nanotoken server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "nanotoken server has now stopped running!"; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } // nanotoken: Return average network hashes per second based on last number of blocks. Value GetNetworkHashPS(int lookup) { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnetworkhashps [blocks]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120); } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); CService addrProxy; GetProxy(NET_IPV4, addrProxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new nanotoken address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current nanotoken address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <nanotokenaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid nanotoken address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <nanotokenaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid nanotoken address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <nanotokenaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid nanotoken address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <nanotokenaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(-4, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(-5, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <nanotokenaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(-5, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <nanotokenaddress> [minconf=1]\n" "Returns the total amount received by <nanotokenaddress> in transactions with at least [minconf] confirmations."); // nanotoken address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(-5, "Invalid nanotoken address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nGenerated, nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance += nGenerated - nSent - nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' should always return the same number. int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; nBalance += allGeneratedMature; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(-20, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(-20, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <tonanotokenaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid nanotoken address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(-5, string("Invalid nanotoken address:")+s.name_); if (setAddress.count(address)) throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(-6, "Insufficient funds"); throw JSONRPCError(-4, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(-4, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a nanotoken address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: nanotoken address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64 nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Generated blocks assigned to account "" if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == "")) { Object entry; entry.push_back(Pair("account", string(""))); if (nGeneratedImmature) { entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature))); } else { entry.push_back(Pair("category", "generate")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature))); } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString())); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString())); entry.push_back(Pair("category", "receive")); entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(-8, "Negative count"); if (nFrom < 0) throw JSONRPCError(-8, "Negative from"); Array ret; CWalletDB walletdb(pwalletMain->strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64, TxPair > TxItems; TxItems txByTime; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } // iterate backwards until we have nCount items to return: for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { mapAccountBalances[""] += nGeneratedMature; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(-8, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(-5, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); BackupWallet(*pwalletMain, strDest); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(-4, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); Sleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(-17, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); CreateThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); CreateThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(-16, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; nanotoken server stopping, restart to run with encrypted wallet"; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <nanotokenaddress>\n" "Return information about <nanotokenaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "nanotoken is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "nanotoken is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; printf("DEBUG: merkle size %i\n", merkle.size()); BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(-9, "nanotoken is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "nanotoken is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); result.push_back(Pair("algorithm", "scrypt:1024,1,1")); // nanotoken: specify that we should use the scrypt algorithm return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblocktemplate [params]\n" "If [params] does not contain a \"data\" key, returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "If [params] does contain a \"data\" key, tries to solve the block and returns null if it was successful (and \"rejected\" if not)\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); const Object& oparam = params[0].get_obj(); std::string strMode; { const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (find_value(oparam, "data").type() == null_type) strMode = "template"; else strMode = "submit"; } if (strMode == "template") { if (vNodes.empty()) throw JSONRPCError(-9, "nanotoken is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "nanotoken is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block if(pblock) delete pblock; pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } else if (strMode == "submit") { // Parse parameters CDataStream ssBlock(ParseHex(find_value(oparam, "data").get_str()), SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; ssBlock >> pblock; bool fAccepted = ProcessBlock(NULL, &pblock); return fAccepted ? Value::null : "rejected"; } throw JSONRPCError(-8, "Invalid mode"); } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblock <hash>\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(-5, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex); } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safe mode? // ------------------------ ----------------------- ---------- { "help", &help, true }, { "stop", &stop, true }, { "getblockcount", &getblockcount, true }, { "getconnectioncount", &getconnectioncount, true }, { "getpeerinfo", &getpeerinfo, true }, { "getdifficulty", &getdifficulty, true }, { "getnetworkhashps", &getnetworkhashps, true }, { "getgenerate", &getgenerate, true }, { "setgenerate", &setgenerate, true }, { "gethashespersec", &gethashespersec, true }, { "getinfo", &getinfo, true }, { "getmininginfo", &getmininginfo, true }, { "getnewaddress", &getnewaddress, true }, { "getaccountaddress", &getaccountaddress, true }, { "setaccount", &setaccount, true }, { "getaccount", &getaccount, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true }, { "sendtoaddress", &sendtoaddress, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false }, { "backupwallet", &backupwallet, true }, { "keypoolrefill", &keypoolrefill, true }, { "walletpassphrase", &walletpassphrase, true }, { "walletpassphrasechange", &walletpassphrasechange, false }, { "walletlock", &walletlock, true }, { "encryptwallet", &encryptwallet, false }, { "validateaddress", &validateaddress, true }, { "getbalance", &getbalance, false }, { "move", &movecmd, false }, { "sendfrom", &sendfrom, false }, { "sendmany", &sendmany, false }, { "addmultisigaddress", &addmultisigaddress, false }, { "getrawmempool", &getrawmempool, true }, { "getblock", &getblock, false }, { "getblockhash", &getblockhash, false }, { "gettransaction", &gettransaction, false }, { "listtransactions", &listtransactions, false }, { "signmessage", &signmessage, false }, { "verifymessage", &verifymessage, false }, { "getwork", &getwork, true }, { "getworkex", &getworkex, true }, { "listaccounts", &listaccounts, false }, { "settxfee", &settxfee, false }, { "setmininput", &setmininput, false }, { "getblocktemplate", &getblocktemplate, true }, { "listsinceblock", &listsinceblock, false }, { "dumpprivkey", &dumpprivkey, false }, { "importprivkey", &importprivkey, false }, { "listunspent", &listunspent, false }, { "getrawtransaction", &getrawtransaction, false }, { "createrawtransaction", &createrawtransaction, false }, { "decoderawtransaction", &decoderawtransaction, false }, { "signrawtransaction", &signrawtransaction, false }, { "sendrawtransaction", &sendrawtransaction, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: nanotoken-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == 401) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: nanotoken-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == 200) cStatus = "OK"; else if (nStatus == 400) cStatus = "Bad Request"; else if (nStatus == 403) cStatus = "Forbidden"; else if (nStatus == 404) cStatus = "Not Found"; else if (nStatus == 500) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %d\r\n" "Content-Type: application/json\r\n" "Server: nanotoken-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return 500; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return 500; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return strUserPass == strRPCUserColonPass; } // // JSON-RPC protocol. nanotoken speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = 500; int code = find_value(objError, "code").get_int(); if (code == -32600) nStatus = 400; else if (code == -32601) nStatus = 404; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Chech whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg)); // Make this thread recognisable as the RPC listener RenameThread("bitcoin-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're canceled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(403, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!CreateThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (mapArgs["-rpcpassword"] == "") { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use nanotokend"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=nanotokenrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "If the file does not exist, create it with owner-readable-only file permissions.\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 9578)); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); boost::signals2::signal<void ()> StopRequests; bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %i for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %i for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(-32600, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(-32600, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(-32600, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(-32600, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(-32700, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer3(parg)); // Make this thread recognisable as the RPC handler RenameThread("bitcoin-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; loop { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) Sleep(250); conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(-32700, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(-32700, "Top-level object parse error"); conn->stream() << HTTPReply(200, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(-32700, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(-32601, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(-2, string("Safe mode: ") + strWarning); try { // Execute Value result; { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } return result; } catch (std::exception& e) { throw JSONRPCError(-1, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "9578"))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == 401) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value) { if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); value = value2.get_value<T>(); } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
[ "thashephard@gmail.com" ]
thashephard@gmail.com
8fef9eb03daf9ea399b51144c4ee072446ab978b
1e5806e25745709e6f4f83ab5f63d18d81c138f0
/intent_recognition/intent_recognition/processing/add_class_mappings_calculator.cc
c75deaa09c008b1f91c6e381d1a4514dedd63825
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
jdetras/google-research
1a9b4b623b2fdb44b47af7ca86c2cd3c152e1431
4d906a25489bb7859a88d982a6c5e68dd890139b
refs/heads/master
2022-09-13T15:49:56.782410
2022-08-13T00:07:26
2022-08-13T00:11:18
156,620,198
0
0
Apache-2.0
2018-11-07T23:06:27
2018-11-07T23:06:27
null
UTF-8
C++
false
false
4,582
cc
// Copyright 2022 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mediapipe/framework/calculator_framework.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/substitute.h" #include "intent_recognition/annotated_recording_collection.pb.h" #include "intent_recognition/processing/class_mappings_provider.h" namespace ambient_sensing { namespace { using ::mediapipe::CalculatorContext; using ::mediapipe::CalculatorContract; constexpr char kInputAnnotatedRecordingCollectionTag[] = "INPUT_ANNOTATED_RECORDING_COLLECTION"; constexpr char kClassMappingsProvider[] = "CLASS_MAPPINGS_PROVIDER"; constexpr char kOutputAnnotatedRecordingCollectionTag[] = "OUTPUT_ANNOTATED_RECORDING_COLLECTION"; } // namespace // Calculator that adds label mappings to AnnotatedRecordingCollection samples. // Relies on the class mapping packet factory for receiving a class mapping // provider. class AddClassMappingsCalculator : public mediapipe::CalculatorBase { public: AddClassMappingsCalculator() = default; static absl::Status GetContract(CalculatorContract* cc) { cc->Inputs() .Tag(kInputAnnotatedRecordingCollectionTag) .Set<AnnotatedRecordingCollection>(); cc->Outputs() .Tag(kOutputAnnotatedRecordingCollectionTag) .Set<AnnotatedRecordingCollection>(); cc->InputSidePackets() .Tag(kClassMappingsProvider) .Set<std::unique_ptr<ClassMappingsProvider>>(); if (cc->Inputs().NumEntries() != cc->Outputs().NumEntries()) { return absl::InvalidArgumentError(absl::StrCat( "Number of input streams must match number of output streams: ", cc->Inputs().NumEntries(), " != ", cc->Outputs().NumEntries())); } if (cc->InputSidePackets().NumEntries() != 1) { return absl::InvalidArgumentError( absl::StrCat("Must receive exactly one input side packet: ", cc->InputSidePackets().NumEntries(), " != 1")); } return absl::OkStatus(); } absl::Status Open(CalculatorContext* cc) override { if (cc->InputSidePackets().HasTag(kClassMappingsProvider)) { label_mapping_provider_ = cc->InputSidePackets() .Tag(kClassMappingsProvider) .Get<std::unique_ptr<ClassMappingsProvider>>() .get(); } return absl::OkStatus(); } absl::Status Process(CalculatorContext* cc) override { auto result_arc = absl::make_unique<AnnotatedRecordingCollection>( cc->Inputs() .Tag(kInputAnnotatedRecordingCollectionTag) .Get<AnnotatedRecordingCollection>()); // Add prediction class + ID to sample for all mappings. absl::Status status = label_mapping_provider_->AddClassMappings(result_arc.get()); if (status != absl::OkStatus()) return status; for (const auto& annotation_group : result_arc->annotation_group()) { if (annotation_group.metadata().group_type() == AnnotationGroupMetadata::GROUND_TRUTH) { for (const auto& annotation_sequence : annotation_group.annotation_sequence()) { if (annotation_sequence.metadata().annotation_type() == AnnotationMetadata::CLASS_LABEL) { cc ->GetCounter(absl::Substitute( "class-mapping-$0-with-label-$1", annotation_sequence.metadata() .source_details() .identifier() .name(), annotation_sequence.annotation(0).label(0).name())) ->Increment(); } } } } cc->Outputs() .Tag(kOutputAnnotatedRecordingCollectionTag) .Add(result_arc.release(), cc->InputTimestamp()); return absl::OkStatus(); } private: const ClassMappingsProvider* label_mapping_provider_; }; REGISTER_CALCULATOR(AddClassMappingsCalculator); } // namespace ambient_sensing
[ "copybara-worker@google.com" ]
copybara-worker@google.com
d1c2f874eccfd2167bd5b7efe620fb0a91598787
d5dc7dd5ac995c290d9dce3af3024c73e5ad8e1a
/Arduino_Timer/Arduino_Timer.ino
965be4cf3228fa5f4f6b149eaeedf76674990dfc
[]
no_license
fusha62/Arduino
12877a6addedb2c32e411c235adf901e9d1e3128
049ad2be95da6b6b601c386a2cab20cd38d6c4ee
refs/heads/master
2020-06-04T16:29:47.126622
2013-11-15T03:20:49
2013-11-15T03:20:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
892
ino
#include <stdint.h> #include <stdio.h> #include <TouchScreen.h> #include <TFT.h> #ifdef SEEEDUINO #define YP A2 // must be an analog pin, use "An" notation! #define XM A1 // must be an analog pin, use "An" notation! #define YM 14 // can be a digital pin, this is A0 #define XP 17 // can be a digital pin, this is A3 #endif #ifdef MEGA #define YP A2 // must be an analog pin, use "An" notation! #define XM A1 // must be an analog pin, use "An" notation! #define YM 54 // can be a digital pin, this is A0 #define XP 57 // can be a digital pin, this is A3 #endif int N; char buf[5]; void setup() { Tft.init(); //init TFT library N = 300; sprintf(buf,"%d",N); Tft.drawString(buf,0,240,6,WHITE); } void loop() { delay(1000); N = N - 1; sprintf(buf,"%d",N); Tft.fillRectangle(0,240,200,60,BLACK); Tft.drawString(buf,0,240,6,WHITE); }
[ "fusha01@hotmail.com" ]
fusha01@hotmail.com
ca539cd505e8e8989ecde7c9580c185e56502910
d19377741d4e6e99f08d4aa8e147c77e3d385877
/2018/April/B. Messages.cpp
b29b5d9e37e0e5eb55a6b5a9ec8f20f5edfdaa1b
[]
no_license
enaim/Competitive_Programming
aad08716d33bfa598fe60934cd28552062577086
ae2eb7dc2f4934b49f6508e66c2e9ee04190c59e
refs/heads/master
2021-06-25T13:09:08.120578
2021-02-01T07:02:41
2021-02-01T07:02:41
205,707,800
10
4
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <algorithm> #include <iostream> #include <vector> #include <map> #include <set> #include <string> #include <sstream> #include <queue> #include <bitset> using namespace std; #define deb(a) cout<<__LINE__<<"# "<<#a<<" -> "<<a<<endl; #define pb push_back #define OO 2e9+10 typedef long long ll; typedef pair<int,int>pii; template<class T> T abs(T x){ if(x<0) return -x; return x; } template<class T>T sqr(T a){ return a*a; } const double pi = acos(-1.0); const double eps = 1e-8; int main() { // freopen("in.txt","r",stdin); // freopen("output.txt","w",stdout); ll n,a,b,c,t,sum; ll ar[1010]; while(5==scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&t)) { for(int i=0;i<n;i++) scanf("%lld",&ar[i]); sum = a*n; if(b<c) { for(int i=0;i<n;i++) sum += (t-ar[i])*(c-b); } printf("%lld\n",sum); } return 0; }
[ "naimelias56@gmail.com" ]
naimelias56@gmail.com
6a8562a266ae5a369eb600861754b67a81eec13c
13908983c960deab9ed7646ee1cf0a0535ddcf4f
/sender_lora.ino
5ed3b38d38247e55382689749791380114442401
[]
no_license
githubsmr/dic
ff51f2986198d7dc3ed25350bc54f52a70123544
ea21f90e0159a03f1707744151119de86c98e82a
refs/heads/master
2020-05-19T15:14:23.638774
2019-05-05T21:03:05
2019-05-05T21:03:05
185,081,117
0
0
null
null
null
null
UTF-8
C++
false
false
591
ino
#include <SPI.h> #include <LoRa.h> void setup() { Serial.begin(9600); while (!Serial); Serial.println("LoRa Receiver"); if (!LoRa.begin(915E6)) { Serial.println("Starting LoRa failed!"); while (1); } } void loop() { // try to parse packet int packetSize = LoRa.parsePacket(); if (packetSize) { // received a packet Serial.print("Received packet '"); // read packet while (LoRa.available()) { Serial.print((char)LoRa.read()); } // print RSSI of packet Serial.print("' with RSSI "); Serial.println(LoRa.packetRssi()); } }
[ "noreply@github.com" ]
noreply@github.com
43da36b491c17bd494b9ad9e23f73604b981e25e
514e53d25623da6f29dc9b95eb5d3f9a74e6b52c
/docs/examples/Paint_029.cpp
55fcde7275d1a3f2ec13db6b2c3478433bec021b
[ "BSD-3-Clause" ]
permissive
xiaofei2ivan/skia
f7230aa17f7f1cf11420a3c3d355ee8955794917
d95286de1dda8c1c0403de22151e1b2a9b7ddf96
refs/heads/master
2021-10-22T11:59:22.331872
2019-03-16T22:05:45
2019-03-16T23:04:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
#if 0 // Disabled until updated to use current API. // Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "fiddle/examples.h" // HASH=aa4781afbe3b90e7ef56a287e5b9ce1e REG_FIDDLE(Paint_029, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPaint paint; for (auto forceAutoHinting : { false, true} ) { paint.setAutohinted(forceAutoHinting); SkDebugf("paint.isAutohinted() %c=" " !!(paint.getFlags() & SkPaint::kAutoHinting_Flag)\n", paint.isAutohinted() == !!(paint.getFlags() & SkPaint::kAutoHinting_Flag) ? '=' : '!'); } } } // END FIDDLE #endif // Disabled until updated to use current API.
[ "halcanary@google.com" ]
halcanary@google.com
9a7af9cd8600eb0ac147d813b8f664f9787384a0
d7b009ff6fb9ef81ade9a96aa35cec74b89d7914
/LeetCode-Cpp/ReverseKGroup/src/Solution.cpp
0cb7fcaa1cfee270a5c529a341138d1fcafe236c
[]
no_license
dazhxu/CodeLib
18c73ac2ba2134674e2922cecd8ca8af898a7563
8691e7e2f5d8e2754f1278be6bba20ecfec041f5
refs/heads/master
2020-12-25T16:50:33.028277
2020-12-09T08:00:56
2020-12-09T08:00:56
41,577,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
/** * @author: xuyuzhuang - xuyuzhuang@buaa.edu.cn * @last modified 2016-08-18 15:02 * @file Solution.cpp * @description */ #include<iostream> using namespace std; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode dummy(0), *pre = &dummy; ListNode *p=head, *tmp = pre, *first; ListNode *cur_pre = pre; pre -> next = head; while(p) { ListNode *temp=p; for(int i=0;i<k;i++) { if(!temp) return dummy->next; temp=temp->next; } first = p; tmp = p; p=p->next; for(int i=0;i<(k-1);i++) { if(p) { cur_pre = p->next; p->next = tmp; tmp = p; p = cur->pre; } else { break; } } pre->next = tmp; first->next = p; pre = first; } return dummy.next; } }
[ "dazh_xu@163.com" ]
dazh_xu@163.com
abb5c568efef684273662fc895cb44fdadd7dd84
c38f2383a4e84d6e091ddaad1da67ad4105f2536
/tensorflow/lite/kernels/internal/optimized/sse_tensor_utils.h
6ab12304f9becbdf01d62b7a8b286e8eefc907c7
[ "Apache-2.0" ]
permissive
boylufeng20141007/tensorflow
3cfaa2308650e9387a057277ea9ed0cc695507b4
7c7d924821a8b1b20433c2f3f484bbd409873a84
refs/heads/master
2020-07-10T22:10:44.142272
2019-08-26T00:50:45
2019-08-26T00:58:39
204,379,347
1
0
Apache-2.0
2019-08-26T02:22:04
2019-08-26T02:22:03
null
UTF-8
C++
false
false
10,555
h
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_SSE_TENSOR_UTILS_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_SSE_TENSOR_UTILS_H_ // Note: This file is a copy-paste version of neon_tensor_utils.h, only // difference is in MatrixBatchVectorMultiplyAccumulate and // SparseMatrixBatchVectorMultiplyAccumulate (other functions do not have SSE // implementation yet). // Note: Most of the functions below use NEON_OR_PORTABLE, through the Intel // NEON_2_SSE translator library. If a native SSE version of a function is // implemented, replace the appropriate one to SSE_OR_PORTABLE. // TODO(ghodrat): Remove this header file and the dependency to internal data // structure. #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/optimized/neon_check.h" #include "tensorflow/lite/kernels/internal/optimized/neon_tensor_utils_impl.h" #include "tensorflow/lite/kernels/internal/optimized/sse_check.h" #include "tensorflow/lite/kernels/internal/optimized/sse_tensor_utils_impl.h" #include "tensorflow/lite/kernels/internal/reference/portable_tensor_utils_impl.h" namespace tflite { namespace tensor_utils { void MatrixBatchVectorMultiplyAccumulate(const float* matrix, int m_rows, int m_cols, const float* vector, int n_batch, float* result, int result_stride) { NEON_OR_PORTABLE(MatrixBatchVectorMultiplyAccumulate, matrix, m_rows, m_cols, vector, n_batch, result, result_stride); } void MatrixBatchVectorMultiplyAccumulate( const int8_t* __restrict__ matrix, const int m_rows, const int m_cols, const int8_t* __restrict__ vectors, const float* scaling_factors, int n_batch, float* __restrict__ result, int result_stride) { SSE_OR_PORTABLE(MatrixBatchVectorMultiplyAccumulate, matrix, m_rows, m_cols, vectors, scaling_factors, n_batch, result, result_stride); } void SparseMatrixBatchVectorMultiplyAccumulate( const float* __restrict__ matrix, const uint8_t* __restrict__ ledger, int m_rows, int m_cols, const float* __restrict__ vector, int n_batch, float* __restrict__ result, int result_stride) { NEON_OR_PORTABLE(SparseMatrixBatchVectorMultiplyAccumulate, matrix, ledger, m_rows, m_cols, vector, n_batch, result, result_stride); } void SparseMatrixBatchVectorMultiplyAccumulate( const int8_t* __restrict__ matrix, const uint8_t* ledger, const int m_rows, const int m_cols, const int8_t* __restrict__ vectors, const float* scaling_factors, int n_batch, float* __restrict__ result, int result_stride) { SSE_OR_PORTABLE(SparseMatrixBatchVectorMultiplyAccumulate, matrix, ledger, m_rows, m_cols, vectors, scaling_factors, n_batch, result, result_stride); } void MatrixBatchVectorMultiplyAccumulate( const int8_t* input, const int32_t* input_zeropoint_times_weights, const int8_t* input_to_gate_weights, int32_t multiplier, int32_t shift, int32_t n_batch, int32_t n_input, int32_t n_output, int32_t output_zp, int16_t* output) { PortableMatrixBatchVectorMultiplyAccumulate( input, input_zeropoint_times_weights, input_to_gate_weights, multiplier, shift, n_batch, n_input, n_output, output_zp, output); } void MatrixBatchVectorMultiplyAccumulate( const int8_t* input, const int32_t* input_zeropoint_times_weights, const int8_t* input_to_gate_weights, int32_t multiplier, int32_t shift, int32_t n_batch, int32_t n_input, int32_t n_output, int32_t output_zp, int8_t* output) { PortableMatrixBatchVectorMultiplyAccumulate( input, input_zeropoint_times_weights, input_to_gate_weights, multiplier, shift, n_batch, n_input, n_output, output_zp, output); } void ApplyLayerNorm(const int16_t* input, const int16_t* layer_norm_weights, const int32_t* bias, int32_t layer_norm_scale_a, int32_t layer_norm_scale_b, int32_t variance_limit, int n_batch, int n_input, int16_t* output) { PortableApplyLayerNorm(input, layer_norm_weights, bias, layer_norm_scale_a, layer_norm_scale_b, variance_limit, n_batch, n_input, output); } void ApplySigmoid(const int16_t* input, int32_t n_batch, int32_t n_input, int16_t* output) { PortableApplySigmoid(input, n_batch, n_input, output); } void ApplyTanh3(const int16_t* input, int32_t n_batch, int32_t n_input, int16_t* output) { PortableApplyTanh3(input, n_batch, n_input, output); } void ApplyTanh4(const int16_t* input, int32_t n_batch, int32_t n_input, int16_t* output) { PortableApplyTanh4(input, n_batch, n_input, output); } void CwiseMul(const int16_t* input_1, const int16_t* input_2, int n_batch, int n_input, int shift, int16_t* output) { PortableCwiseMul(input_1, input_2, n_batch, n_input, shift, output); } void CwiseMul(const int16_t* input_1, const int16_t* input_2, int n_batch, int n_input, int shift, int8_t* output) { PortableCwiseMul(input_1, input_2, n_batch, n_input, shift, output); } void CwiseAdd(const int16_t* input_1, const int16_t* input_2, int n_batch, int n_input, int16_t* output) { PortableCwiseAdd(input_1, input_2, n_batch, n_input, output); } void CwiseClipping(int16_t* input, const int16_t clipping_value, int32_t n_batch, int32_t n_input) { PortableCwiseClipping(input, clipping_value, n_batch, n_input); } void CwiseClipping(int8_t* input, const int8_t clipping_value, int32_t n_batch, int32_t n_input) { PortableCwiseClipping(input, clipping_value, n_batch, n_input); } void VectorVectorCwiseProduct(const float* vector1, const float* vector2, int v_size, float* result) { NEON_OR_PORTABLE(VectorVectorCwiseProduct, vector1, vector2, v_size, result); } void VectorVectorCwiseProductAccumulate(const float* vector1, const float* vector2, int v_size, float* result) { NEON_OR_PORTABLE(VectorVectorCwiseProductAccumulate, vector1, vector2, v_size, result); } void VectorBatchVectorCwiseProduct(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { NEON_OR_PORTABLE(VectorBatchVectorCwiseProduct, vector, v_size, batch_vector, n_batch, result); } void VectorBatchVectorCwiseProductAccumulate(const float* vector, int v_size, const float* batch_vector, int n_batch, float* result) { NEON_OR_PORTABLE(VectorBatchVectorCwiseProductAccumulate, vector, v_size, batch_vector, n_batch, result); } float VectorVectorDotProduct(const float* vector1, const float* vector2, int v_size) { return NEON_OR_PORTABLE(VectorVectorDotProduct, vector1, vector2, v_size); } void BatchVectorBatchVectorDotProduct(const float* vector1, const float* vector2, int v_size, int n_batch, float* result, int result_stride) { NEON_OR_PORTABLE(BatchVectorBatchVectorDotProduct, vector1, vector2, v_size, n_batch, result, result_stride); } void VectorBatchVectorAdd(const float* vector, int v_size, int n_batch, float* batch_vector) { PortableVectorBatchVectorAdd(vector, v_size, n_batch, batch_vector); } void ApplySigmoidToVector(const float* vector, int v_size, float* result) { PortableApplySigmoidToVector(vector, v_size, result); } void ApplyActivationToVector(const float* vector, int v_size, TfLiteFusedActivation activation, float* result) { PortableApplyActivationToVector(vector, v_size, activation, result); } void Sub1Vector(const float* vector, int v_size, float* result) { NEON_OR_PORTABLE(Sub1Vector, vector, v_size, result); } float Clip(float f, float abs_limit) { return PortableClip(f, abs_limit); } // Check if all entries of a vector are zero. bool IsZeroVector(const float* vector, int v_size) { return NEON_OR_PORTABLE(IsZeroVector, vector, v_size); } void VectorScalarMultiply(const int8_t* vector, int v_size, float scale, float* result) { NEON_OR_PORTABLE(VectorScalarMultiply, vector, v_size, scale, result); } void ClipVector(const float* vector, int v_size, float abs_limit, float* result) { NEON_OR_PORTABLE(ClipVector, vector, v_size, abs_limit, result); } void SymmetricQuantizeFloats(const float* values, const int size, int8_t* quantized_values, float* min_value, float* max_value, float* scaling_factor) { NEON_OR_PORTABLE(SymmetricQuantizeFloats, values, size, quantized_values, min_value, max_value, scaling_factor); } void ReductionSumVector(const float* input_vector, float* output_vector, int output_size, int reduction_size) { NEON_OR_PORTABLE(ReductionSumVector, input_vector, output_vector, output_size, reduction_size); } void MeanStddevNormalization(const float* input_vector, float* output_vector, int v_size, int n_batch, float normalization_epsilon) { PortableMeanStddevNormalization(input_vector, output_vector, v_size, n_batch, normalization_epsilon); } } // namespace tensor_utils } // namespace tflite #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_SSE_TENSOR_UTILS_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
0fb0009f607571e10386217a1cc5a4cd4141e1dd
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/multimedia/dshow/mfvideo/mswebdvd/mediahndlr.h
7ca89283e5bfdd473eff4c2b46f9c731c4cabbc8
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
h
// // Copyright (c) 1996 - 1999 Microsoft Corporation. All Rights Reserved. // #ifndef __CMediaHandler__h #define __CMediaHandler__h #include "msgwindow.h" class CMSWebDVD; // // Specific code // class CMediaHandler : public CMsgWindow { typedef CMsgWindow ParentClass ; public: CMediaHandler(); ~CMediaHandler() ; virtual LRESULT WndProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); bool WasEjected() const { return m_ejected; }; bool WasInserted() const { return m_inserted; }; void ClearFlags(); bool SetDrive( TCHAR tcDriveLetter ); // currently unused by the pump thread, but it will be required if the ejection // handler becomes a new thread HANDLE GetEventHandle() const; void SetDVD(CMSWebDVD* pDVD) {m_pDVD = pDVD;}; private: DWORD m_driveMask; bool m_ejected; bool m_inserted; CMSWebDVD* m_pDVD; }; #endif
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
ea5fdf92d0a11ba151c1b533c76e9b551f839208
48ad90c35ddcc016d3f5af6090df9491f31ea770
/test_pixpro/main.cpp
222f7b158c0bb9de8cc75b9b1bcdc9ac87d71e76
[]
no_license
liyang1999/realslam
6d205e1404b5fd5cde25b97d5235b46cd2d23a95
c25e58587b153d01983a68b9eda779a7e2b055c9
refs/heads/master
2023-05-06T08:46:37.251938
2020-03-10T06:40:02
2020-03-10T06:40:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,689
cpp
#include <opencv2/opencv.hpp> #include <time.h> #if _WIN64 #define LIB_PATH "D:/dev/lib64/" #define CV_LIB_PATH "D:/dev/lib64/" #else #define LIB_PATH "D:/dev/staticlib32/" #endif #ifdef _DEBUG #define LIB_EXT "d.lib" #else #define LIB_EXT ".lib" #endif #define CUDA_LIB_PATH "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.2/lib/x64/" #pragma comment(lib, CUDA_LIB_PATH "cudart.lib") #define CV_VER_NUM CVAUX_STR(CV_MAJOR_VERSION) CVAUX_STR(CV_MINOR_VERSION) CVAUX_STR(CV_SUBMINOR_VERSION) #pragma comment(lib, LIB_PATH "opencv_core" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_highgui" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_videoio" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_imgproc" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_calib3d" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_xfeatures2d" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_optflow" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_imgcodecs" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_features2d" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_tracking" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_flann" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_cudafeatures2d" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_cudaimgproc" CV_VER_NUM LIB_EXT) #pragma comment(lib, LIB_PATH "opencv_video" CV_VER_NUM LIB_EXT) int main() { // THETA S //cv::VideoCapture webcam1; //webcam1.open(0, cv::CAP_DSHOW); ///*webcam1.set(cv::CAP_PROP_FPS, 15); //webcam1.set(cv::CAP_PROP_FRAME_HEIGHT, 1440); //webcam1.set(cv::CAP_PROP_FRAME_WIDTH, 1440);*/ //for (;;) //{ // cv::Mat frame1, frame2; // webcam1 >> frame1; // cv::imshow("frame1", frame1); // //std::cout << frame1.cols << " " << frame1.rows << std::endl; // if (cv::waitKey(10) == 27) break; // stop capturing by pressing ESC //} //webcam1.release(); // PIXPRO cv::VideoCapture webcam1; cv::VideoCapture webcam2; webcam1.open(0, cv::CAP_DSHOW); webcam2.open(1, cv::CAP_DSHOW); webcam1.set(cv::CAP_PROP_FPS, 15); webcam1.set(cv::CAP_PROP_FRAME_HEIGHT, 1440); webcam1.set(cv::CAP_PROP_FRAME_WIDTH, 1440); webcam2.set(cv::CAP_PROP_FPS, 15); webcam2.set(cv::CAP_PROP_FRAME_HEIGHT, 1440); webcam2.set(cv::CAP_PROP_FRAME_WIDTH, 1440); for (;;) { cv::Mat frame1, frame2; webcam1 >> frame1; webcam2 >> frame2; cv::imshow("frame1", frame1); cv::imshow("frame2", frame2); //std::cout << frame1.cols << " " << frame1.rows << std::endl; if (cv::waitKey(10) == 27) break; // stop capturing by pressing ESC } webcam1.release(); webcam2.release(); return 0; }
[ "menandro.roxas@gmail.com" ]
menandro.roxas@gmail.com
12ddf27075befff6f2cba77185f7edef41538410
7e9b4eb951e9097a31c8705f1eda523c435565c6
/src/zLexParser.cpp
e780c4ef0cd98cac574ee226b957f4362e38cd93
[]
no_license
rcampion/cpp-tab-parser
c34741769e9cabfb3e141c0ff5d4117ff5090a0d
0b0ed2046394c62ee00a578a228c065b476a42e0
refs/heads/master
2022-11-16T23:43:10.536611
2020-07-19T01:11:25
2020-07-19T01:11:25
280,511,570
0
0
null
null
null
null
UTF-8
C++
false
false
21,111
cpp
/************************************************************************** * * zLexParser.cpp * * author: Richard Campion * **************************************************************************/ /************************************************************************** * * **************************************************************************/ /*! \file zLexParser.cpp */ #include <iostream> using namespace std; #include "zLexBase.h" #include "zLexError.h" #include "zLexParser.h" #include "zLexUtil.h" #include "BisonTabHdrLineParser.hpp" #include <string> #include <sstream> #include <math.h> /*************************************************************************** * * default constructor * ***************************************************************************/ ZLexParser::ZLexParser() { init(); } /*************************************************************************** * * construct using char* (buffer) * ***************************************************************************/ ZLexParser::ZLexParser(ZLexFile *zfile, ZLexFileBuffer *zbuf) { //todo: buffer is empty! whose responsibility is it to fill it? // also init(); //do we have anything to parse? if (zbuf->getSize() > 0) { //m_sTextBuffer = ""; //we are using a char* based buffer, nullify this //m_pLexCharBuffer = NULL; //we are using a char* based buffer, initialize m_eParseStatus = zbuf->prepareBufferFromBinary(); } else { m_eParseStatus = E_BufferEmpty; m_eParseError = E_LEX_BUFFER_EMPTY; } } /*************************************************************************** * * destructor * ***************************************************************************/ ZLexParser::~ZLexParser() { release(); } /*************************************************************************** * * init * ***************************************************************************/ StatusCode ZLexParser::init() { //initialize the error messages if (!gl_nErrInitialized) InitLexErrMsg(); m_pLexCharBuffer = NULL; m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; gl_nLexFirstTime = true; m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; //reset accumulators gl_nLexLineCount = 0; // reset number of lines in file gl_nLexRowCount = 0; // reset number of lines in section gl_nLexColumnCount = 0; // reset number of columns on this line gl_nLexFieldCount = 0; // reset number of fields on this line gl_nLexFileCharOffset = 0; // reset number of chars scanned in this file gl_nLexLineCharOffset = 0; // reset number of chars on this line //winging it gl_pLexCurrentToken = NULL; gl_pLexErrorList = NULL; //not sure if this is necessary - test //gl_nLexCurrentSection = LEXFILESECTION_ROOT; // create a default root token gl_pLexTokenList = new ZLexToken("<root\\>", // text gl_nLexLineCount, // line gl_nLexRowCount, // row gl_nLexColumnCount, // column gl_nLexLineCharOffset, // char offset from beginning of line gl_nLexFileCharOffset, // char offset from beginning of file LEXTOKEN_SECTION, // id, value, field LEXTOKEN_DATATYPE_STRING, // datatype representation LEXSCAN_COMPLETE, // scan status NULL); // parent token; gl_pLexCurrentToken = gl_pLexTokenList; //gl_bQuiet = gl_pContext->getQuiet(); //gl_nQuietLevel = gl_pContext->getQuietLevel(); //gl_bShowProgress = gl_pContext->getShowProgress(); //gl_bPrintResults = gl_pContext->getPrintResults(); //gl_bPrintTokens = gl_pContext->getPrintTokens(); //gl_bDebugMem = gl_pContext->getDebugMem(); //m_pLexCharBuffer = new ZLexFileBuffer(); return E_NoError; } /*************************************************************************** * * doLexHdr * ***************************************************************************/ StatusCode ZLexParser::doLexHeader() { m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; //fill the buffer and get ready to parse //m_eParseStatus = prepare(); //if(m_eParseStatus != E_NoError) // return m_eParseStatus; try { //call the lexer loop proc m_eParseError = doLexHeaderProc(); //rc = (LexError) zFile_parse(); } catch (...) { m_eParseError = E_LEX_EXCEPTION; return m_eParseStatus = E_Exception; } return m_eParseStatus; } /*************************************************************************** * * doLexData * ***************************************************************************/ StatusCode ZLexParser::doLexData() { m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; //fill the buffer and get ready to parse //m_eParseStatus = prepare(); //if(m_eParseStatus != E_NoError) // return m_eParseStatus; try { //call the lexer loop proc m_eParseError = doLexDataProc(); //rc = (LexError) zFile_parse(); } catch (...) { m_eParseError = E_LEX_EXCEPTION; return m_eParseStatus = E_Exception; } return m_eParseStatus; } /*************************************************************************** * * doLexHdrProc * ***************************************************************************/ LexError ZLexParser::doLexHeaderProc() { //lex the file std::string s = ""; int lexReturn = -1; while (lexReturn != END_OF_FILE) { lexReturn = zHdr_lex(); switch (lexReturn) { case LINE_NUMBER: s = "LINE_NUMBER"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case ALPHA_CELL: s = "ALPHA_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case ERROR_CELL: s = "ERROR_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case QUOTED_CELL: s = "QUOTED_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case DELIMITER: s = "DELIMITER"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case NEW_LINE: s = "NEW_LINE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case COMMENT_LINE: s = "COMMENT_LINE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case END_OF_FILE: s = "END_OF_FILE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; default: break; } } return (LexError) lexReturn; } /*************************************************************************** * * doLexDataProc * ***************************************************************************/ LexError ZLexParser::doLexDataProc() { //lex the file std::string s = ""; int lexReturn = -1; while (lexReturn != END_OF_FILE) { lexReturn = zData_lex(); switch (lexReturn) { case LINE_NUMBER: s = "LINE_NUMBER"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case ALPHA_CELL: s = "ALPHA_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case ERROR_CELL: s = "ERROR_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case QUOTED_CELL: s = "QUOTED_CELL"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case DELIMITER: s = "DELIMITER"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case NEW_LINE: s = "NEW_LINE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case COMMENT_LINE: s = "COMMENT_LINE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; case END_OF_FILE: s = "END_OF_FILE"; cout << s.c_str() << endl; cout << "gl_nLexLineCount.......:" << gl_nLexLineCount << endl; // count number of lines in file cout << "gl_nLexRowCount........:" << gl_nLexRowCount << endl; // count number of lines in section cout << "gl_nLexColumnCount.....:" << gl_nLexColumnCount << endl; // count number of columns on this line cout << "gl_nLexFieldCount......:" << gl_nLexFieldCount << endl; // count number of fields on this line cout << "gl_nLexFileCharOffset..:" << gl_nLexFileCharOffset << endl; // count number of chars scanned in this file cout << "gl_nLexLineCharOffset..:" << gl_nLexLineCharOffset << endl; // count number of chars on this line break; default: break; } } return (LexError) lexReturn; } /*************************************************************************** * * doParseHeader * ***************************************************************************/ StatusCode ZLexParser::doParseHeader() { m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; try { //call the lexer loop proc m_eParseError = (LexError) zHdr_parse(); } catch (...) { m_eParseError = E_LEX_EXCEPTION; return m_eParseStatus = E_Exception; } return m_eParseStatus; } /*************************************************************************** * * doParseData * ***************************************************************************/ StatusCode ZLexParser::doParseData() { m_eParseStatus = E_NoError; m_eParseError = E_LEX_OK; try { //call the lexer loop proc m_eParseError = (LexError) zData_parse(); } catch (...) { m_eParseError = E_LEX_EXCEPTION; return m_eParseStatus = E_Exception; } return m_eParseStatus; } /*************************************************************************** * * getTokenList * ***************************************************************************/ ZLexToken* ZLexParser::getTokenList() { return gl_pLexTokenList; } /*************************************************************************** * * release * ***************************************************************************/ StatusCode ZLexParser::release() { //destroy all parser memory // todo: copy global error info //LexDestroy(); //delete m_pLexCharBuffer; return E_NoError; } /*************************************************************************** * * showTokens * ***************************************************************************/ void ZLexParser::showTokens() { ZLexToken *z = gl_pLexTokenList; ZLexToken *c = z; while (c != NULL) { if (c->text_ != NULL) cout << c->text_ << endl; c = c->next_; } } /*************************************************************************** * fileOpen ***************************************************************************/ FILE* ZLexParser::fileOpen(const char *fileName) { FILE *fp; if (fileName != (char*) NULL) { fp = fopen(fileName, "rb"); } else { fp = (FILE*) NULL; } return (fp); } /*************************************************************************** * destroyTokenList ***************************************************************************/ void ZLexParser::destroyTokenList() { ZLexToken *tok = gl_pLexTokenList; ZLexToken *temp = NULL; while (tok != NULL) { temp = tok; destroyToken(temp); tok = tok->next_; } } /*************************************************************************** * destroyToken ***************************************************************************/ void ZLexParser::destroyToken(ZLexToken *tok) { ZLexToken *temp = tok; if (temp->text_) { free(temp->text_); //free(temp->text, temp->text); } if (temp->name_) { free(temp->name_); //free(temp->desc_, temp->text_); } free(temp); //free(temp, "ZLEXTOKEN *"); }
[ "campion.richard@gmail.com" ]
campion.richard@gmail.com
734d754c00c7e0fb25eb6d964c9270137d061391
2acd0652c2e2ad0961445b078b6a6f8b58c051a2
/FractalCreator.h
0b8be73bc4dd26b7016ec1e042d241900a6d9ffe
[]
no_license
meirwitt/Fractal-Creator
02370b7c4d1acc040f8a27042047ad88e994fe41
004868212bdf35f7b402d7628f50dea6d4504982
refs/heads/main
2023-01-03T14:19:00.748716
2020-10-06T09:35:41
2020-10-06T09:35:41
301,499,768
1
0
null
2020-10-06T09:35:43
2020-10-05T18:15:27
C++
UTF-8
C++
false
false
919
h
#pragma once #include <string> #include <iostream> #include "Mandelbrot.h" #include "ZoomList.h" #include "Bitmap.h" #include "Zoom.h" #include "Mandelbrot.h" #include <cstdint> #include <math.h> #include "RGB.h" #include <vector> using namespace std; namespace cave { class FractalCreator { private: int m_total{ 0 }; int m_height; int m_width; unique_ptr<int[]> m_histogram; unique_ptr<int[]> m_fractal; Bitmap m_bitmap; ZoomList m_zoomlist; vector<int> m_ranges; vector<RGB> m_color; vector<int> m_rangeTotals; bool m_bGotFirstRange{ false }; int getRange(int iterations) const; public: FractalCreator(int, int); ~FractalCreator() = default; void addRange(int rangeEnd, RGB rgb); void calculateIteration(); void drawFractal(); void addZoom(const Zoom&); void writeBitmap(string); void calculateRangeTotal(); }; }
[ "noreply@github.com" ]
noreply@github.com
4af28d353287e72752ece1f6cc7e37ca8e126512
acb46f8d4c56ad8569753e21995874642766e83b
/side-eye-gui/mainwindow.cpp
f78aa8c1b29bea2a1140afbe98e4dac365f80c28
[]
no_license
Mivialll/side-eye
033700c8ab03dbde121d573805016f998304d91a
d9907dc525f735b11ad017aa2ed4d315373f9197
refs/heads/master
2020-03-28T22:14:26.009621
2018-09-16T12:51:14
2018-09-16T12:51:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,593
cpp
#include "mainwindow.h" #include <QApplication> #include <QPushButton> #include <QVBoxLayout> #include <QWidget> #include <QPixmap> #include <QIcon> #include <QToolButton> #include <QSize> #include <QLabel> #include <QObject> #include <iostream> #include <QMainWindow> #include <QKeyEvent> #include <QtMultimedia/QCameraInfo> #include <QColor> #include <vector> #include "winsw.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { const int width = 1000; const int height = 500; this->setWindowTitle("Side-eye"); this->setGeometry(10, 10, width, height); QSize picSize(width, height); QVBoxLayout *topLayout = new QVBoxLayout; QHBoxLayout *buttonLayout = new QHBoxLayout; QHBoxLayout *textLayout = new QHBoxLayout; textLabel = new QLabel("Select a screen to begin the calibration\n\n\n"); /*if (QCameraInfo::availableCameras().count() > 0) { textLabel->setText("greater than 0"); } else { textLabel->setText("le 0"); }*/ textLabel->setAlignment(Qt::AlignCenter); textLabel->setFont(QFont("Segoe UI", 30)); textLabel->setUpdatesEnabled(true); textLabel->setWordWrap(true); textLayout->addWidget(textLabel); QPixmap pixmapL("C:\\nellemaple\\Coding\\htn2018\\pics\\Lgrey.png"); QIcon iconL(pixmapL); buttonL = new QToolButton; buttonL->setIcon(iconL); buttonL->setIconSize(picSize); buttonL->setFixedSize(width, height); buttonL->setCursor(Qt::PointingHandCursor); buttonL->setAutoFillBackground(true); buttonL->setStyleSheet("border: none"); connect(buttonL, SIGNAL(released()), this, SLOT(onLeftClick())); QPixmap pixmapR("C:\\nellemaple\\Coding\\htn2018\\pics\\Rgrey.png"); QIcon iconR(pixmapR); buttonR = new QToolButton; buttonR->setFixedSize(width, height); buttonR->setIcon(iconR); buttonR->setIconSize(picSize); buttonR->setCursor(Qt::PointingHandCursor); buttonR->setStyleSheet("border: none"); connect(buttonR, SIGNAL(released()), this, SLOT(onRightClick())); buttonLayout->addWidget(buttonL); buttonLayout->addWidget(buttonR); //int displays = query_display_ids().size(); int displays = 3; if (displays == 3) { QPixmap pixmapC("C:\\nellemaple\\Coding\\htn2018\\pics\\Cgrey.png"); QIcon iconC(pixmapC); buttonC = new QToolButton; buttonC->setFixedSize(width, height); buttonC->setIcon(iconC); buttonC->setIconSize(picSize); buttonC->setCursor(Qt::PointingHandCursor); buttonC->setStyleSheet("border: none"); connect(buttonC, SIGNAL(released()), this, SLOT(onCentreClick())); buttonLayout->addWidget(buttonC); } topLayout->addStretch(); topLayout->addLayout(buttonLayout); topLayout->addStretch(); topLayout->addLayout(textLayout); topLayout->addStretch(); topLayout->addStretch(); QWidget *window = new QWidget(); window->setLayout(topLayout); setCentralWidget(window); } void MainWindow::onLeftClick() { textLabel->setText("To calibrate the left screen, turn your head toward the left screen.\n Look at the top right corner, and press and hold 0 for five seconds.\n Repeat this process for the remaining three corners and the centre of the screen."); QPixmap pixmapLblue("C:\\nellemaple\\Coding\\htn2018\\pics\\Lblue.png"); QIcon iconLblue(pixmapLblue); buttonL->setIcon(iconLblue); } void MainWindow::onCentreClick() { textLabel->setText("To calibrate the centre screen, turn your head toward the centre screen.\n Look at the top right corner, and press and hold 0 for five seconds.\n Repeat this process for the remaining three corners and the centre of the screen."); QPixmap pixmapCblue("C:\\nellemaple\\Coding\\htn2018\\pics\\Cblue.png"); QIcon iconCblue(pixmapCblue); buttonC->setIcon(iconCblue); } void MainWindow::onRightClick() { textLabel->setText("To calibrate the right screen, turn your head toward the right screen.\n Look at the top right corner, and press and hold 0 for five seconds.\n Repeat this process for the remaining three corners and the centre of the screen."); QPixmap pixmapRblue("C:\\nellemaple\\Coding\\htn2018\\pics\\Rblue.png"); QIcon iconRblue(pixmapRblue); buttonR->setIcon(iconRblue); } void MainWindow::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_0) { textLabel->setText("Key pressed...\n\n\n"); } } void MainWindow::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_0) { textLabel->setText("Key released!\n\n\n"); } }
[ "me@shazz.me" ]
me@shazz.me
597033c780621f718f5e7834b562d458a71b8728
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.304/nut
2b64caab278f6adebcbf05f9daaf6c73abafba70
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
5,840
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.304"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 545 ( 6.18123 5.88617 5.4153 5.0091 4.73114 6.30093 5.89976 5.40089 4.9843 4.6847 6.50671 5.91079 5.36632 4.93284 4.60161 6.81789 5.90182 5.31084 4.85918 4.47458 7.27917 5.8511 5.247 4.78023 4.29561 4.5891 4.51154 4.48691 4.47919 4.47678 4.47604 4.47582 4.47575 4.47574 4.47574 4.47574 4.47575 4.47576 4.47576 4.47577 4.47578 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.55355 4.50067 4.48348 4.47811 4.47645 4.47594 4.47579 4.47574 4.47574 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47578 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47582 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.50183 4.48244 4.47763 4.47628 4.47588 4.47576 4.47573 4.47573 4.47573 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47578 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47582 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.43454 4.46117 4.47108 4.47425 4.47525 4.47557 4.47567 4.47571 4.47573 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.3561 4.44317 4.46587 4.47267 4.47476 4.47542 4.47562 4.47569 4.47572 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.36484 4.4377 4.46377 4.47199 4.47455 4.47535 4.4756 4.47569 4.47572 4.47573 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 7.27917 5.8511 5.247 4.78023 4.29561 6.81789 5.90182 5.31084 4.85918 4.47458 6.50671 5.91079 5.36632 4.93284 4.60161 6.30093 5.89976 5.40089 4.9843 4.6847 6.18123 5.88617 5.4153 5.0091 4.73114 4.35611 4.44317 4.46587 4.47267 4.47476 4.47542 4.47562 4.47569 4.47572 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.43454 4.46117 4.47108 4.47425 4.47525 4.47557 4.47567 4.47571 4.47573 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.50183 4.48244 4.47763 4.47628 4.47588 4.47576 4.47573 4.47573 4.47573 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47578 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47582 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.47587 4.55355 4.50067 4.48348 4.47811 4.47645 4.47594 4.47579 4.47574 4.47574 4.47574 4.47574 4.47575 4.47576 4.47577 4.47577 4.47578 4.47578 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47582 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 4.47587 4.47587 4.5891 4.51155 4.48691 4.47919 4.47678 4.47604 4.47582 4.47575 4.47574 4.47574 4.47574 4.47575 4.47576 4.47576 4.47577 4.47578 4.47578 4.47579 4.47579 4.4758 4.4758 4.47581 4.47581 4.47582 4.47582 4.47583 4.47583 4.47583 4.47584 4.47584 4.47584 4.47585 4.47585 4.47585 4.47585 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47586 4.47587 4.47587 ) ; boundaryField { AirInlet { type fixedValue; value uniform 0; } WaterInlet { type fixedValue; value uniform 0; } ChannelWall { type fixedValue; value uniform 0; } Outlet { type calculated; value nonuniform List<scalar> 11 ( 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 4.47587 ) ; } FrontAndBack { type empty; } } // ************************************************************************* //
[ "mizuha.watanabe@gmail.com" ]
mizuha.watanabe@gmail.com
032d0509d9f1e72c8a6b081895e5063a92570829
af9178d27cc2487f458f508a50901ae52acb0f75
/hashing_algorithms/generators/SHA1sslDigestGenerator.cpp
74fa2eb15c5562825800309ee1a51891667a9d87
[]
no_license
kpv15/hashing_algo_cuda
de6badb62da1f5d986c7187799cd4cef62c54011
667ede96a72865afe3ea6aa91dc2312ad6781091
refs/heads/master
2021-06-22T14:00:08.640198
2020-02-10T22:12:11
2020-02-10T22:12:11
219,962,072
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
// // Created by grzegorz on 19.01.2020. // #include "include/SHA1sslDigestGenerator.h" #include "include/SHA1_ssl.h" void SHA1sslDigestGenerator::generate() { sha1ssl.setDefaultWordLength(length_to_gen); initDigest(); for (unsigned int i = 0; i < n_to_gen; i++) sha1ssl.calculateHashSum(&digest[i], words[i]); length = length_to_gen; n = n_to_gen; } unsigned int SHA1sslDigestGenerator::getDigestLength() { return sha1ssl.getDigestLength(); } std::string SHA1sslDigestGenerator::getAlgorithmName() { return "sha1_ssl"; }
[ "kpv135@gmail.com" ]
kpv135@gmail.com
ebd39f1dfcc5696661c8c352b4689b01b48cb694
c20b459468fa359a6f4c545db72a211d38298909
/all_problems/Done/384_Shuffle_an_Array.cpp
da2cc7c6e2bd90296ae620ec4396a1fb3ab37614
[]
no_license
mycppfeed/Leetmap
e0340c6ecb85901c9555900a871e159a16940028
f1f31085de60adce9dabe5eb2e5c4d66a5ba1572
refs/heads/master
2021-11-04T00:13:19.882064
2019-04-26T21:18:30
2019-04-26T21:18:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,216
cpp
/* Problem Description * Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle(); Tags: Array */ #include"header.h" class Solution { private: vector<int> local_copy; vector<int> arrangement; int sz; public: Solution(vector<int> nums) { sz = nums.size(); local_copy.reserve(sz); arrangement.resize(sz); for(int i = 0 ; i < sz; i ++) { arrangement[i] = i; } local_copy = nums; } /** Resets the array to its original configuration and return it. */ vector<int> reset() { vector<int> local_copy2(sz); for(int i = 0 ; i < sz ; i++) { local_copy2[arrangement[i]] = local_copy[i]; } local_copy = local_copy2; for(int i = 0 ; i < sz; i ++) { arrangement[i] = i; } return local_copy2; } void swap(int* p, int*q) { if(p == q) return; *p = *p ^ *q; *q = *p ^ *q; *p = *p ^ *q; } /** Returns a random shuffling of the array. */ vector<int> shuffle() { for(int i = 0 ; i < sz ; i++ ) { //arrange each position i taking a random number from i to sz-1 int r = (rand() % (sz - i)); int random_idx = i + r; swap(&local_copy[i], &local_copy[random_idx]); swap(&arrangement[i], &arrangement[random_idx]); } return local_copy; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * vector<int> param_1 = obj.reset(); * vector<int> param_2 = obj.shuffle(); */ int main() { vector<int> D({1,2,3}); Solution S(D); cout << S.shuffle(); cout << S.reset(); cout << S.shuffle(); cout << S.reset(); return 0; }
[ "sdasgup3@illinois.edu" ]
sdasgup3@illinois.edu
85999104f285e6eeca78a5595fea8a22f501cb27
0af9d6da1f2386ddd9ee22268eeaa1fd7ee58c45
/4.5ec/main.cpp
0b5cd5aa2129601d1917b81d26840410ea13cd91
[]
no_license
adolphyang22/The-C-Programming-Language
0e53be7410addcba98e932654b29d7517f42c36e
62626f5a904d6a628d7dc3fb76075e0af4e4d978
refs/heads/master
2020-03-17T18:27:17.692353
2018-05-19T08:53:50
2018-05-19T08:53:50
133,823,814
0
0
null
null
null
null
UTF-8
C++
false
false
3,201
cpp
#include "test1.h" /* 4.5ec需求: 给逆波兰计算器程序增加访问sin、cos、exp与pow库函数的操作。 输入: 1.5707963 sin 输出: 1 (pi/2值约等于1.5707963,由于math.h提供的sin函数接口入参是弧度制, 可以自行定义宏先将入参的角度值转换为弧度值再计算#define j2h(x) (3.1415926*(x)/180.0) ) 输入: 0 cos 输出: 1 (cos0的值等于1) 输入: 1 exp 输出: 2.7182818 (math.h提供的exp函数对自然常数e求幂) 输入: 2 3 pow 输出:8 (math.h提供的pow函数求入参1的入参2次幂) */ /* reverse Polish calculator */ int main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case NAME: mathfunc(s); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error: unknown command %s\n", s); break; } } return 0; } /* mathfunc: check string s for supported math functions */ void mathfunc(char s[]) { double op2; if (strcmp(s, "sin") == 0) //push(sin(j2h(pop()))); //为角度值计算正弦时可使用j2h宏转换入参 push(sin(pop())); else if (strcmp(s, "cos") == 0) //push(cos(j2h(pop()))); //为角度值计算余弦时可使用j2h宏转换入参 push(cos(pop())); else if (strcmp(s, "exp") == 0) push(exp(pop())); else if (strcmp(s, "pow") == 0) { op2 = pop(); push(pow(pop(), op2)); //函数入参从左往右入栈,若直接pow(pop(),pop())则先将输入的幂作为底入栈 } else printf("error:%s not supported\n", s); } /* getop: get next operator, numeric operand, or math func */ int getop(char s[]) { int c = 0, i = 0; while ((s[0] = c = getch()) == ' ' || c == '\t') ; s[1] = '\0'; i = 0; if (islower(c)) /* command or NAME */ { while (islower(s[++i] = c = getch())) ; s[i] = '\0'; if (c != EOF) ungetch(c); /* went one char too far */ if (strlen(s) > 1) return NAME; /* >1 char; it is NAME */ else return c; /* it may be a command */ } if (!isdigit(c) && c != '.') return c; /* not a number */ if (isdigit(c)) /* collect integer part */ while (isdigit(s[++i] = c = getch())) ; if (c == '.') /* collect fraction part */ while (isdigit(s[++i] = c = getch())) ; s[i] = '\0'; if (c != EOF) ungetch(c); return NUMBER; } /* push: 把f压入栈中 */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else printf("error:栈满,不能将%g压栈\n", f); } /* pop: 弹出并返回栈顶的值 */ double pop(void) { if (sp > 0) { return val[--sp]; } else { printf("error:栈空\n"); return 0.0; } } int getch(void) /* 取一个字符(可能是压回的字符) */ { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) /* 将字符压回输入中 */ { if (bufp >= BUFSIZE) { printf("ungetch: 压回字符过多\n"); } else { buf[bufp++] = c; } }
[ "noreply@github.com" ]
noreply@github.com
30be3f713c08877be092d1d5c841f9502d40fd42
66aef70be6d68ff31784040f91cf0ab0007ea624
/オンライン/source/SocketClient.cpp
4c71064aadec4ff7bcd073a88cfd633e6f846a39
[]
no_license
kadHelp/kadHelp
aa5a1bb21a9e01ee6fa773ef11a70f59cf69b70e
8f0af125d7715f86e0bcdf741f5de711d0b4740d
refs/heads/master
2021-01-10T09:34:42.538120
2016-01-26T03:28:18
2016-01-26T03:28:18
50,400,269
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,863
cpp
#include "SocketClient.h" #pragma comment( lib, "wsock32.lib" ) // TCPクライアント初期化 bool SocketClient::InitializeTCP( WORD port, char* addr ) { // ポート&アドレス指定 ZeroMemory( &server, sizeof(server) ); server.sin_family = AF_INET; server.sin_port = htons(port); struct hostent *host = gethostbyname(addr); server.sin_addr.S_un.S_addr = *((ULONG*)host->h_addr_list[0]); // TCPソケット作成 sock = socket( AF_INET, SOCK_STREAM, 0 ); if( sock == INVALID_SOCKET ) return false; // タイムアウト設定(1000ms) int timeout = 1000; if( setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout) ) == SOCKET_ERROR ) return false; // サーバー接続 if( connect( sock, (sockaddr*)&server, sizeof(server) ) == SOCKET_ERROR ) return false; return true; } // UDPクライアント初期化 bool SocketClient::InitializeUDP( WORD port, char* addr ) { // サーバー情報設定 ZeroMemory( &server, sizeof(server) ); server.sin_family=AF_INET; server.sin_port = htons(port); struct hostent *host = gethostbyname(addr); server.sin_addr.S_un.S_addr = *((ULONG*)host->h_addr_list[0]); // UDPソケットの作成 sock = socket( AF_INET, SOCK_DGRAM, 0); if( sock == INVALID_SOCKET ) return false; // タイムアウト設定(1000ms) int timeout = 1000; if( setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout) ) == SOCKET_ERROR ) return false; return true; } // データ送信 void SocketClient::send( char *data, int size ) { sendto( sock, data, size, 0, (struct sockaddr *)&server, sizeof(server) ); } // データ受信 int SocketClient::receive( char *data, int size ) { int recvsize = recv( sock, data, size, 0 ); // エラー(タイムアウト)判定 if( recvsize == SOCKET_ERROR ) return 0; return recvsize; }
[ "wtpmjgdadgjptw@gmail.com" ]
wtpmjgdadgjptw@gmail.com
755f98f2622a53504a902a17f1295f66403dd71e
36fc46366f6e09ce553fd2a10d9cccf37e7b6195
/백준/10870_피보나치 수 5.cpp
b8ebec7af3df08c50cab58015aa99e007047a2bb
[]
no_license
Seoui/Algorithm
12e5cdd022d5989e0aa6a5ed09f7ada789614bef
6bce7081e72c94a74b4dceb41f267c1db0a4190e
refs/heads/master
2023-04-20T01:12:13.069113
2021-05-10T17:22:07
2021-05-10T17:22:07
290,984,289
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
#include <iostream> using namespace std; int fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; cout << fibonacci(n) << '\n'; system("pause"); return 0; }
[ "dusto@naver.com" ]
dusto@naver.com
9a4ad7e38f75b4fcfbff358285f92da92ff0b64e
767589b8fd0e3d1c64d4bf936a0920e66564a3ff
/old/EmbeddedAssignment4/EmbeddedAssignment4/Mode1.h
06969de54fdbdaed46d07722e4d4aeda1442f3d2
[]
no_license
DanielEjnar/EmbededProject
53d4793a1cbffa552a0daee7bcee06b94516c0b0
05f9f1e1642c6cf5489367641728b9cad7fa5596
refs/heads/master
2020-03-31T20:33:25.919736
2019-01-07T16:41:01
2019-01-07T16:41:01
152,545,320
1
0
null
null
null
null
UTF-8
C++
false
false
249
h
#pragma once #include "RealTimeLoop.h" class Mode1 : public ApplicationModeSetting { public: static Mode1* GetInstance(); void responseEventX() override; void responseEventY() override; private: static Mode1* _instance; Mode1(); ~Mode1(); };
[ "chr1000@gmail.com" ]
chr1000@gmail.com
aefd000f82721afef443f389f21a9088b79f6d49
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_2/processor19/20/phi
534f822cbee62eaf868241ea6661f412fdd131da
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
12,626
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "20"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 609 ( 3.3806e-06 3.32714e-06 1.11309e-07 3.21583e-06 8.72633e-06 1.72751e-07 3.04308e-06 7.81684e-07 8.1174e-06 1.23325e-05 2.37821e-07 2.80526e-06 1.04773e-06 7.30749e-06 2.56281e-06 1.08174e-05 1.31612e-05 3.06498e-07 2.49876e-06 1.32815e-06 6.28584e-06 3.21132e-06 8.93424e-06 6.1182e-06 1.02543e-05 1.00366e-05 3.78661e-07 2.1201e-06 1.62235e-06 5.04215e-06 3.89109e-06 6.6655e-06 7.36181e-06 6.7836e-06 1.22302e-05 5.16825e-06 1.57589e-06 4.54064e-07 1.92929e-06 3.56693e-06 4.59958e-06 3.99521e-06 8.65701e-06 2.72617e-06 1.43138e-05 -4.88505e-07 2.18039e-05 -5.91421e-06 -1.38329e-05 2.24742e-06 5.33318e-06 9.99706e-06 -1.93771e-06 1.64681e-05 -6.95954e-06 2.49988e-05 -1.44449e-05 3.58671e-05 -2.47012e-05 -3.80554e-05 1.13734e-05 1.86791e-05 -1.42653e-05 2.82756e-05 -2.40414e-05 4.04613e-05 -3.68869e-05 5.55641e-05 -5.31582e-05 -7.32336e-05 2.09303e-05 3.16091e-05 -3.47202e-05 4.51309e-05 -5.04087e-05 6.18458e-05 -6.98731e-05 8.21384e-05 -9.35261e-05 -0.000121804 3.49722e-05 4.98363e-05 -6.52728e-05 6.81673e-05 -8.82042e-05 9.03726e-05 -0.000115731 0.000116899 -0.000148331 -0.000186505 5.45373e-05 7.44717e-05 9.85678e-05 -0.000139828 0.000127294 -0.000177056 0.000161161 -0.000220372 -0.000270355 0.000106651 0.000137515 -0.00020792 0.000173825 -0.000256683 0.000216157 -0.000312687 0.000265138 -0.000376592 -0.000449097 0.000147476 0.000186115 0.000231053 -0.000357625 0.000282915 -0.000428454 0.000342373 -0.000508556 -0.000598721 0.00024531 0.000299815 0.000362105 -0.000570846 0.00043286 -0.000669475 -0.000779718 0.000380562 0.000453892 -0.000742805 0.000536363 -0.000862189 0.000628576 -0.000994718 -0.00114135 0.000473229 0.000557793 0.000651866 -0.00108879 0.000755833 -0.00124532 -0.00141722 0.000672573 0.000777504 0.000891971 -0.00153169 0.00101581 -0.00172923 -0.0019434 0.000910563 0.00103358 0.00116464 -0.00207445 -0.0023127 0.00117653 0.00131179 0.00145191 -0.00270688 -0.00297886 0.00159513 0.00145214 0.00159065 0.00131605 0.00244796 0.00145214 0.00270688 0.00297886 0.00159065 0.00104751 0.00185225 0.00117653 0.00207445 0.00131179 0.0023127 0.00145191 0.00159513 0.000910563 0.00153169 0.00103358 0.00172923 0.00116464 0.0019434 0.000672573 0.00108879 0.000777504 0.00124532 0.000891971 0.00141722 0.00101581 0.000473229 0.000742805 0.000557793 0.000862189 0.000651866 0.000994718 0.000755833 0.00114135 0.000315755 0.000482959 0.000380563 0.000570846 0.000453892 0.000669475 0.000536363 0.000779718 0.000628577 0.00024531 0.000357625 0.000299815 0.000428454 0.000362105 0.000508556 0.00043286 0.000598721 0.000147476 0.00020792 0.000186116 0.000256683 0.000231053 0.000312687 0.000282915 0.000376592 0.000342373 0.000106651 0.000139828 0.000137515 0.000177056 0.000173825 0.000220373 0.000216157 0.000270355 5.45373e-05 6.52728e-05 7.44717e-05 8.82042e-05 9.85679e-05 0.000115731 0.000127294 0.000148331 0.000161161 0.000186505 3.49722e-05 3.47202e-05 4.98363e-05 5.04087e-05 6.81673e-05 6.98731e-05 9.03726e-05 9.35261e-05 0.000116899 0.000121805 2.09303e-05 1.42653e-05 3.16091e-05 2.40414e-05 4.51309e-05 3.68869e-05 6.18459e-05 5.31582e-05 8.21384e-05 7.32336e-05 6.08724e-06 -9.09462e-07 1.13734e-05 1.9377e-06 1.86791e-05 6.95953e-06 2.82756e-05 1.44449e-05 4.04613e-05 2.47012e-05 5.55641e-05 3.80553e-05 2.24743e-06 -3.56693e-06 5.33318e-06 -3.99522e-06 9.99707e-06 -2.72618e-06 1.64681e-05 4.8849e-07 2.49988e-05 5.9142e-06 3.58671e-05 1.38329e-05 4.54065e-07 -2.1201e-06 1.92929e-06 -5.04216e-06 4.59958e-06 -6.66551e-06 8.65702e-06 -6.78361e-06 1.43138e-05 -5.16827e-06 2.18039e-05 -1.57592e-06 3.78661e-07 -2.49877e-06 1.62235e-06 -6.28585e-06 3.89109e-06 -8.93425e-06 7.36182e-06 -1.02543e-05 1.22302e-05 -1.00367e-05 3.06498e-07 -2.80526e-06 1.32815e-06 -7.3075e-06 3.21133e-06 -1.08174e-05 6.11821e-06 -1.31612e-05 2.37821e-07 -3.04309e-06 1.04773e-06 -8.11741e-06 2.56281e-06 -1.23325e-05 1.72751e-07 -3.21584e-06 7.81686e-07 -8.72634e-06 1.1131e-07 -3.32715e-06 -3.3806e-06 0.00045703 -0.00911701 0.000399124 -0.00910137 0.000341542 -0.00908768 0.000284232 -0.00907592 0.000227144 -0.00906605 0.000170226 -0.00905808 0.000113429 -0.00905199 5.67031e-05 -0.00904781 -0.00904556 0.00180644 -0.00829033 0.00195718 -0.00899174 0.00205287 -0.00947665 0.00209966 -0.00979921 0.00210666 -0.00999016 0.00208345 -0.0100828 0.00203886 -0.0101076 0.00198023 -0.0100887 0.00191316 -0.0100438 0.00184156 -0.00998509 0.00176804 -0.00992025 0.00169418 -0.00985385 0.0016209 -0.00978843 0.00154867 -0.00972529 0.00147771 -0.00966504 0.00140811 -0.0096079 0.00133986 -0.00955391 0.00127291 -0.00950302 0.00120721 -0.00945514 0.00114269 -0.00941015 0.00107927 -0.00936794 0.00101689 -0.00932842 0.000955474 -0.00929147 0.00089495 -0.009257 0.000835254 -0.00922492 0.000776322 -0.00919515 0.000718091 -0.00916762 0.000660503 -0.00914225 0.000603498 -0.009119 0.000547023 -0.00909781 0.000491021 -0.00907864 0.000435442 -0.00906143 0.000380233 -0.00904616 0.000325345 -0.00903279 0.000270728 -0.0090213 0.000216334 -0.00901166 0.000162113 -0.00900386 0.000108015 -0.00899789 5.39934e-05 -0.00899379 -0.00899157 0.00178652 -0.00848619 0.00192154 -0.00912677 0.00200283 -0.00955794 0.00203756 -0.00983394 0.00203532 -0.00998791 0.00200574 -0.0100532 0.00195738 0.0018971 0.00182997 0.00175945 0.00168775 0.00161618 0.00154548 0.00147599 0.00140786 0.00134112 0.00127575 0.00121169 0.00114888 0.00108723 0.00102667 0.000967137 0.000908552 0.000850849 0.000793961 0.000737824 0.000682378 0.000627563 0.000573323 0.000519603 0.000466351 0.000413515 0.000361046 0.000308895 0.000257014 0.000205356 0.000153874 0.000102518 5.12423e-05 0.0017599 0.00187917 0.00194647 0.00196985 0.00195923 0.0017599 0.00848619 0.00187917 0.00912677 0.00194647 0.00955794 0.00196985 0.00983394 0.00195923 0.00998791 0.00192416 0.0100532 0.00187279 0.0100592 0.00181147 0.0100284 0.00174476 0.00997666 0.00991457 0.00178652 0.00829033 0.00192154 0.00899175 0.00200283 0.00947665 0.00203756 0.00979921 0.00203532 0.00999016 0.00200574 0.0100828 0.00195738 0.0101076 0.0018971 0.0100887 0.00182997 0.0100438 0.00175945 0.00998509 0.00168775 0.00992025 0.00161618 0.00985385 0.00154548 0.00978843 0.00147599 0.00972529 0.00140786 0.00966504 0.00134112 0.0096079 0.00127575 0.00955391 0.00121169 0.00950302 0.00114888 0.00945514 0.00108723 0.00941015 0.00102667 0.00936794 0.000967137 0.00932842 0.000908552 0.00929147 0.000850849 0.009257 0.000793961 0.00922492 0.000737824 0.00919515 0.000682378 0.00916761 0.000627563 0.00914225 0.000573323 0.009119 0.000519603 0.00909781 0.000466351 0.00907864 0.000413515 0.00906143 0.000361046 0.00904616 0.000308895 0.00903279 0.000257014 0.0090213 0.000205356 0.00901166 0.000153873 0.00900386 0.000102518 0.00899789 5.12423e-05 0.00899379 0.00899157 0.00180644 0.00195718 0.00205287 0.00209966 0.00210666 0.00208345 0.00203886 0.00198023 0.00191316 0.00184156 0.00176804 0.00169418 0.0016209 0.00154867 0.00147771 0.00140811 0.00133986 0.00127291 0.00120721 0.00114269 0.00107927 0.00101689 0.000955474 0.00089495 0.000835254 0.000776322 0.000718091 0.000660503 0.000603498 0.000547023 0.000491021 0.000435442 0.000380233 0.000325345 0.000270728 0.000216334 0.000162113 0.000108015 5.39934e-05 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value uniform 0; } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } defaultFaces { type empty; value nonuniform 0(); } procBoundary19to18 { type processor; value nonuniform List<scalar> 160 ( 1.66604e-06 -5.32332e-07 1.85183e-06 9.09455e-07 -6.08724e-06 -7.22384e-06 -1.27759e-05 -2.24197e-05 -2.32039e-05 -4.64885e-05 -3.83374e-05 -8.14727e-05 -0.000108139 -8.07057e-05 -0.000165772 -0.000114557 -0.000240839 -0.000295322 -0.000197945 -0.00040499 -0.000482958 -0.000315755 -0.000635653 -0.000397699 -0.000818335 -0.000946753 -0.000577106 -0.00118426 -0.00135025 -0.000796182 -0.00164607 -0.00185225 -0.00104751 -0.00220348 -0.00244796 -0.00131605 -0.00284296 -0.00311738 -0.00158023 -0.00257996 -0.00284296 -0.00311738 -0.00158023 -0.00197403 -0.00118405 -0.00220348 -0.000925724 -0.00164607 -0.00118426 -0.000796182 -0.00135025 -0.000818335 -0.000577106 -0.000946753 -0.000539862 -0.0003977 -0.000635653 -0.000258852 -0.00040499 -0.000240839 -0.000197945 -0.000295322 -0.000114557 -0.000165772 -8.14727e-05 -8.07058e-05 -0.000108139 -3.83374e-05 -4.64885e-05 -2.3204e-05 -2.24197e-05 -2.60304e-06 -1.27759e-05 -7.22383e-06 -2.57474e-06 1.85184e-06 -5.32332e-07 1.66604e-06 -0.0100592 -0.0100284 -0.00997666 -0.00991457 -0.00984855 -0.00978229 -0.00971773 -0.0096558 -0.00959691 -0.00954117 -0.00948854 -0.00943896 -0.00939232 -0.0093485 -0.00930739 -0.00926888 -0.00923288 -0.00919929 -0.00916803 -0.00913901 -0.00911217 -0.00908744 -0.00906476 -0.00904409 -0.00902538 -0.0090086 -0.00899369 -0.00898064 -0.00896942 -0.00896 -0.00895237 -0.00894654 -0.00894251 -0.00894033 -0.00866586 -0.00924604 -0.00962524 -0.00985733 -0.00997729 0.00192416 -0.0100181 -0.00866586 -0.00924604 -0.00962524 -0.00985733 -0.00997729 -0.0100181 -0.0100079 -0.00996707 -0.00990994 -0.00984547 0.00167565 -0.00984855 -0.00978229 -0.00971773 -0.0096558 -0.00959691 -0.00954117 -0.00948854 -0.00943896 -0.00939232 -0.0093485 -0.00930739 -0.00926888 -0.00923288 -0.00919929 -0.00916803 -0.00913901 -0.00911217 -0.00908744 -0.00906476 -0.00904409 -0.00902538 -0.0090086 -0.00899369 -0.00898064 -0.00896942 -0.00896 -0.00895237 -0.00894654 -0.00894251 -0.00894033 ) ; } procBoundary19to20 { type processor; value nonuniform List<scalar> 169 ( -3.37965e-06 -9.50392e-10 5.3455e-08 -9.14522e-06 5.30198e-07 -1.34978e-05 1.947e-06 -1.55293e-05 4.93093e-06 -1.41469e-05 1.02285e-05 -8.05795e-06 1.87122e-05 4.25182e-06 3.1385e-05 2.4544e-05 4.93784e-05 5.48536e-05 7.39441e-05 9.75129e-05 0.00010643 0.000155169 0.000148235 0.000230786 0.00020073 0.000327612 0.000392785 0.00032145 0.00053094 0.000410153 0.000699791 0.000512787 0.000902504 0.00103885 0.000731082 0.00130312 0.000869938 0.00160539 0.00181067 0.00114854 0.00217458 0.00130276 0.00256676 0.00283564 0.00256676 0.00283564 0.00130276 0.00217458 0.00160539 0.00114854 0.00181067 0.000869938 0.00130312 0.000902505 0.000731082 0.00103885 0.000512787 0.000699791 0.000449098 0.000410154 0.00053094 0.000265138 0.000327612 0.00020073 0.000230786 0.000148235 0.000155169 0.00010643 9.75129e-05 7.39441e-05 5.48536e-05 4.93785e-05 2.4544e-05 3.1385e-05 4.25179e-06 1.87123e-05 -8.05798e-06 1.02285e-05 -1.41469e-05 4.93094e-06 -1.55293e-05 1.94701e-06 -1.34978e-05 5.302e-07 -9.14523e-06 5.34556e-08 -9.49863e-10 -3.37965e-06 0.00917529 0.00915928 0.00914526 0.00913323 0.00912314 0.009115 0.00910879 0.00910454 0.00910227 0.00807902 0.008841 0.00938096 0.00975242 0.00998316 0.010106 0.0101522 0.0101473 0.0101109 0.0100567 0.00999377 0.00992771 0.00986172 0.00979752 0.009736 0.00967751 0.00962217 0.00956997 0.00952083 0.00947467 0.00943136 0.0093908 0.00935289 0.00931752 0.00928461 0.00925408 0.00922585 0.00919984 0.00917601 0.00915429 -0.00051531 0.00913464 0.00807902 0.008841 0.00938096 0.00975242 0.00998316 0.010106 0.0101522 0.0101473 0.0101109 0.0100567 0.00999377 0.00992771 0.00986172 0.00979752 0.009736 0.00967751 0.00962217 0.00956997 0.00952083 0.00947467 0.00943136 0.0093908 0.00935289 0.00931752 0.00928461 0.00925408 0.00922585 0.00919984 0.00917601 0.00915429 0.00913464 0.00911701 0.00910137 0.00908768 0.00907592 0.00906605 0.00905808 0.00905199 0.00904781 0.00904556 ) ; } } // ************************************************************************* //
[ "chaseh13@login4.stampede2.tacc.utexas.edu" ]
chaseh13@login4.stampede2.tacc.utexas.edu
d1077d4a5f956593e3ef9a808bd4703e94e91813
8ed8027c1bf5483c189b27b485127b72cfd0f722
/glowdeck/fastled-3.1.3/fastspi_bitbang.h
4bb94047d457a77ae6a1a7ae57b5de4ac4fc1002
[ "Apache-2.0", "MIT" ]
permissive
PLSCO/Glowdeck_Xcode
30d6f691dc6c449d09288f88b3dd123a25443e8d
ef287b17fb634df6714d7a7e9ca5f9fd629d1f34
refs/heads/master
2021-05-05T19:01:12.913769
2017-09-16T23:10:43
2017-09-16T23:10:43
103,789,503
1
0
null
null
null
null
UTF-8
C++
false
false
18,315
h
#ifndef __INC_FASTSPI_BITBANG_H #define __INC_FASTSPI_BITBANG_H #include "FastLED.h" #include "fastled_delay.h" FASTLED_NAMESPACE_BEGIN ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Software SPI (aka bit-banging) support - with aggressive optimizations for when the clock and data pin are on the same port // // TODO: Replace the select pin definition with a set of pins, to allow using mux hardware for routing in the future // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <uint8_t DATA_PIN, uint8_t CLOCK_PIN, uint8_t SPI_SPEED> class AVRSoftwareSPIOutput { // The data types for pointers to the pin port - typedef'd here from the Pin definition because on avr these // are pointers to 8 bit values, while on arm they are 32 bit typedef typename FastPin<DATA_PIN>::port_ptr_t data_ptr_t; typedef typename FastPin<CLOCK_PIN>::port_ptr_t clock_ptr_t; // The data type for what's at a pin's port - typedef'd here from the Pin definition because on avr the ports // are 8 bits wide while on arm they are 32. typedef typename FastPin<DATA_PIN>::port_t data_t; typedef typename FastPin<CLOCK_PIN>::port_t clock_t; Selectable *m_pSelect; public: AVRSoftwareSPIOutput() { m_pSelect = NULL; } AVRSoftwareSPIOutput(Selectable *pSelect) { m_pSelect = pSelect; } void setSelect(Selectable *pSelect) { m_pSelect = pSelect; } void init() { // set the pins to output and make sure the select is released (which apparently means hi? This is a bit // confusing to me) FastPin<DATA_PIN>::setOutput(); FastPin<CLOCK_PIN>::setOutput(); release(); } // stop the SPI output. Pretty much a NOP with software, as there's no registers to kick static void stop() { } // wait until the SPI subsystem is ready for more data to write. A NOP when bitbanging static void wait() __attribute__((always_inline)) { } static void waitFully() __attribute__((always_inline)) { wait(); } static void writeByteNoWait(uint8_t b) __attribute__((always_inline)) { writeByte(b); } static void writeBytePostWait(uint8_t b) __attribute__((always_inline)) { writeByte(b); wait(); } static void writeWord(uint16_t w) __attribute__((always_inline)) { writeByte(w >> 8); writeByte(w & 0xFF); } // naive writeByte implelentation, simply calls writeBit on the 8 bits in the byte. static void writeByte(uint8_t b) { writeBit<7>(b); writeBit<6>(b); writeBit<5>(b); writeBit<4>(b); writeBit<3>(b); writeBit<2>(b); writeBit<1>(b); writeBit<0>(b); } private: // writeByte implementation with data/clock registers passed in. static void writeByte(uint8_t b, clock_ptr_t clockpin, data_ptr_t datapin) { writeBit<7>(b, clockpin, datapin); writeBit<6>(b, clockpin, datapin); writeBit<5>(b, clockpin, datapin); writeBit<4>(b, clockpin, datapin); writeBit<3>(b, clockpin, datapin); writeBit<2>(b, clockpin, datapin); writeBit<1>(b, clockpin, datapin); writeBit<0>(b, clockpin, datapin); } // writeByte implementation with the data register passed in and prebaked values for data hi w/clock hi and // low and data lo w/clock hi and lo. This is to be used when clock and data are on the same GPIO register, // can get close to getting a bit out the door in 2 clock cycles! static void writeByte(uint8_t b, data_ptr_t datapin, data_t hival, data_t loval, clock_t hiclock, clock_t loclock) { writeBit<7>(b, datapin, hival, loval, hiclock, loclock); writeBit<6>(b, datapin, hival, loval, hiclock, loclock); writeBit<5>(b, datapin, hival, loval, hiclock, loclock); writeBit<4>(b, datapin, hival, loval, hiclock, loclock); writeBit<3>(b, datapin, hival, loval, hiclock, loclock); writeBit<2>(b, datapin, hival, loval, hiclock, loclock); writeBit<1>(b, datapin, hival, loval, hiclock, loclock); writeBit<0>(b, datapin, hival, loval, hiclock, loclock); } // writeByte implementation with not just registers passed in, but pre-baked values for said registers for // data hi/lo and clock hi/lo values. Note: weird things will happen if this method is called in cases where // the data and clock pins are on the same port! Don't do that! static void writeByte(uint8_t b, clock_ptr_t clockpin, data_ptr_t datapin, data_t hival, data_t loval, clock_t hiclock, clock_t loclock) { writeBit<7>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<6>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<5>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<4>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<3>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<2>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<1>(b, clockpin, datapin, hival, loval, hiclock, loclock); writeBit<0>(b, clockpin, datapin, hival, loval, hiclock, loclock); } public: // We want to make sure that the clock pulse is held high for a nininum of 35ns. #define MIN_DELAY (NS(35) - 3) #define CLOCK_HI_DELAY delaycycles<MIN_DELAY>(); delaycycles<(((SPI_SPEED-6) / 2) - MIN_DELAY)>(); #define CLOCK_LO_DELAY delaycycles<(((SPI_SPEED-6) / 4))>(); // write the BIT'th bit out via spi, setting the data pin then strobing the clcok template <uint8_t BIT> __attribute__((always_inline, hot)) inline static void writeBit(uint8_t b) { //cli(); if (b & (1 << BIT)) { FastPin<DATA_PIN>::hi(); FastPin<CLOCK_PIN>::hi(); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::lo(); CLOCK_LO_DELAY; } else { FastPin<DATA_PIN>::lo(); FastPin<CLOCK_PIN>::hi(); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::lo(); CLOCK_LO_DELAY; } //sei(); } private: // write the BIT'th bit out via spi, setting the data pin then strobing the clock, using the passed in pin registers to accelerate access if needed template <uint8_t BIT> __attribute__((always_inline)) inline static void writeBit(uint8_t b, clock_ptr_t clockpin, data_ptr_t datapin) { if (b & (1 << BIT)) { FastPin<DATA_PIN>::hi(datapin); FastPin<CLOCK_PIN>::hi(clockpin); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::lo(clockpin); CLOCK_LO_DELAY; } else { FastPin<DATA_PIN>::lo(datapin); FastPin<CLOCK_PIN>::hi(clockpin); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::lo(clockpin); CLOCK_LO_DELAY; } } // the version of write to use when clock and data are on separate pins with precomputed values for setting // the clock and data pins template <uint8_t BIT> __attribute__((always_inline)) inline static void writeBit(uint8_t b, clock_ptr_t clockpin, data_ptr_t datapin, data_t hival, data_t loval, clock_t hiclock, clock_t loclock) { // // only need to explicitly set clock hi if clock and data are on different ports if (b & (1 << BIT)) { FastPin<DATA_PIN>::fastset(datapin, hival); FastPin<CLOCK_PIN>::fastset(clockpin, hiclock); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::fastset(clockpin, loclock); CLOCK_LO_DELAY; } else { // NOP; FastPin<DATA_PIN>::fastset(datapin, loval); FastPin<CLOCK_PIN>::fastset(clockpin, hiclock); CLOCK_HI_DELAY; FastPin<CLOCK_PIN>::fastset(clockpin, loclock); CLOCK_LO_DELAY; } } // the version of write to use when clock and data are on the same port with precomputed values for the various // combinations template <uint8_t BIT> __attribute__((always_inline)) inline static void writeBit(uint8_t b, data_ptr_t clockdatapin, data_t datahiclockhi, data_t dataloclockhi, data_t datahiclocklo, data_t dataloclocklo) { #if 0 writeBit<BIT>(b); #else if (b & (1 << BIT)) { FastPin<DATA_PIN>::fastset(clockdatapin, datahiclocklo); FastPin<DATA_PIN>::fastset(clockdatapin, datahiclockhi); CLOCK_HI_DELAY; FastPin<DATA_PIN>::fastset(clockdatapin, datahiclocklo); CLOCK_LO_DELAY; } else { // NOP; FastPin<DATA_PIN>::fastset(clockdatapin, dataloclocklo); FastPin<DATA_PIN>::fastset(clockdatapin, dataloclockhi); CLOCK_HI_DELAY; FastPin<DATA_PIN>::fastset(clockdatapin, dataloclocklo); CLOCK_LO_DELAY; } #endif } public: // select the SPI output (TODO: research whether this really means hi or lo. Alt TODO: move select responsibility out of the SPI classes // entirely, make it up to the caller to remember to lock/select the line?) void select() { if (m_pSelect != NULL) { m_pSelect->select(); } } // FastPin<SELECT_PIN>::hi(); } // release the SPI line void release() { if (m_pSelect != NULL) { m_pSelect->release(); } } // FastPin<SELECT_PIN>::lo(); } // Write out len bytes of the given value out over SPI. Useful for quickly flushing, say, a line of 0's down the line. void writeBytesValue(uint8_t value, int len) { select(); writeBytesValueRaw(value, len); release(); } static void writeBytesValueRaw(uint8_t value, int len) { #ifdef FAST_SPI_INTERRUPTS_WRITE_PINS // TODO: Weird things may happen if software bitbanging SPI output and other pins on the output reigsters are being twiddled. Need // to allow specifying whether or not exclusive i/o access is allowed during this process, and if i/o access is not allowed fall // back to the degenerative code below while (len--) { writeByte(value); } #else register data_ptr_t datapin = FastPin<DATA_PIN>::port(); if (FastPin<DATA_PIN>::port() != FastPin<CLOCK_PIN>::port()) { // If data and clock are on different ports, then writing a bit will consist of writing the value foor // the bit (hi or low) to the data pin port, and then two writes to the clock port to strobe the clock line register clock_ptr_t clockpin = FastPin<CLOCK_PIN>::port(); register data_t datahi = FastPin<DATA_PIN>::hival(); register data_t datalo = FastPin<DATA_PIN>::loval(); register clock_t clockhi = FastPin<CLOCK_PIN>::hival(); register clock_t clocklo = FastPin<CLOCK_PIN>::loval(); while (len--) { writeByte(value, clockpin, datapin, datahi, datalo, clockhi, clocklo); } } else { // If data and clock are on the same port then we can combine setting the data and clock pins register data_t datahi_clockhi = FastPin<DATA_PIN>::hival() | FastPin<CLOCK_PIN>::mask(); register data_t datalo_clockhi = FastPin<DATA_PIN>::loval() | FastPin<CLOCK_PIN>::mask(); register data_t datahi_clocklo = FastPin<DATA_PIN>::hival() & ~FastPin<CLOCK_PIN>::mask(); register data_t datalo_clocklo = FastPin<DATA_PIN>::loval() & ~FastPin<CLOCK_PIN>::mask(); while (len--) { writeByte(value, datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); } } #endif } // write a block of len uint8_ts out. Need to type this better so that explicit casts into the call aren't required. // note that this template version takes a class parameter for a per-byte modifier to the data. template <class D> void writeBytes(register uint8_t *data, int len) { select(); #ifdef FAST_SPI_INTERRUPTS_WRITE_PINS uint8_t *end = data + len; while (data != end) { writeByte(D::adjust(*data++)); } #else register clock_ptr_t clockpin = FastPin<CLOCK_PIN>::port(); register data_ptr_t datapin = FastPin<DATA_PIN>::port(); if (FastPin<DATA_PIN>::port() != FastPin<CLOCK_PIN>::port()) { // If data and clock are on different ports, then writing a bit will consist of writing the value foor // the bit (hi or low) to the data pin port, and then two writes to the clock port to strobe the clock line register data_t datahi = FastPin<DATA_PIN>::hival(); register data_t datalo = FastPin<DATA_PIN>::loval(); register clock_t clockhi = FastPin<CLOCK_PIN>::hival(); register clock_t clocklo = FastPin<CLOCK_PIN>::loval(); uint8_t *end = data + len; while (data != end) { writeByte(D::adjust(*data++), clockpin, datapin, datahi, datalo, clockhi, clocklo); } } else { // FastPin<CLOCK_PIN>::hi(); // If data and clock are on the same port then we can combine setting the data and clock pins register data_t datahi_clockhi = FastPin<DATA_PIN>::hival() | FastPin<CLOCK_PIN>::mask(); register data_t datalo_clockhi = FastPin<DATA_PIN>::loval() | FastPin<CLOCK_PIN>::mask(); register data_t datahi_clocklo = FastPin<DATA_PIN>::hival() & ~FastPin<CLOCK_PIN>::mask(); register data_t datalo_clocklo = FastPin<DATA_PIN>::loval() & ~FastPin<CLOCK_PIN>::mask(); uint8_t *end = data + len; while (data != end) { writeByte(D::adjust(*data++), datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); } // FastPin<CLOCK_PIN>::lo(); } #endif D::postBlock(len); release(); } // default version of writing a block of data out to the SPI port, with no data modifications being made void writeBytes(register uint8_t *data, int len) { writeBytes<DATA_NOP>(data, len); } // write a block of uint8_ts out in groups of three. len is the total number of uint8_ts to write out. The template // parameters indicate how many uint8_ts to skip at the beginning of each grouping, as well as a class specifying a per // byte of data modification to be made. (See DATA_NOP above) template <uint8_t FLAGS, class D, EOrder RGB_ORDER> __attribute__((noinline)) void writePixels(PixelController<RGB_ORDER> pixels) { select(); int len = pixels.mLen; #ifdef FAST_SPI_INTERRUPTS_WRITE_PINS // If interrupts or other things may be generating output while we're working on things, then we need // to use this block while (pixels.has(1)) { if (FLAGS & FLAG_START_BIT) { writeBit<0>(1); } writeByte(D::adjust(pixels.loadAndScale0())); writeByte(D::adjust(pixels.loadAndScale1())); writeByte(D::adjust(pixels.loadAndScale2())); pixels.advanceData(); pixels.stepDithering(); } #else // If we can guaruntee that no one else will be writing data while we are running (namely, changing the values of the PORT/PDOR pins) // then we can use a bunch of optimizations in here register data_ptr_t datapin = FastPin<DATA_PIN>::port(); if (FastPin<DATA_PIN>::port() != FastPin<CLOCK_PIN>::port()) { register clock_ptr_t clockpin = FastPin<CLOCK_PIN>::port(); // If data and clock are on different ports, then writing a bit will consist of writing the value foor // the bit (hi or low) to the data pin port, and then two writes to the clock port to strobe the clock line register data_t datahi = FastPin<DATA_PIN>::hival(); register data_t datalo = FastPin<DATA_PIN>::loval(); register clock_t clockhi = FastPin<CLOCK_PIN>::hival(); register clock_t clocklo = FastPin<CLOCK_PIN>::loval(); while (pixels.has(1)) { if (FLAGS & FLAG_START_BIT) { writeBit<0>(1, clockpin, datapin, datahi, datalo, clockhi, clocklo); } writeByte(D::adjust(pixels.loadAndScale0()), clockpin, datapin, datahi, datalo, clockhi, clocklo); writeByte(D::adjust(pixels.loadAndScale1()), clockpin, datapin, datahi, datalo, clockhi, clocklo); writeByte(D::adjust(pixels.loadAndScale2()), clockpin, datapin, datahi, datalo, clockhi, clocklo); pixels.advanceData(); pixels.stepDithering(); } } else { // If data and clock are on the same port then we can combine setting the data and clock pins register data_t datahi_clockhi = FastPin<DATA_PIN>::hival() | FastPin<CLOCK_PIN>::mask(); register data_t datalo_clockhi = FastPin<DATA_PIN>::loval() | FastPin<CLOCK_PIN>::mask(); register data_t datahi_clocklo = FastPin<DATA_PIN>::hival() & ~FastPin<CLOCK_PIN>::mask(); register data_t datalo_clocklo = FastPin<DATA_PIN>::loval() & ~FastPin<CLOCK_PIN>::mask(); while (pixels.has(1)) { if (FLAGS & FLAG_START_BIT) { writeBit<0>(1, datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); } writeByte(D::adjust(pixels.loadAndScale0()), datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); writeByte(D::adjust(pixels.loadAndScale1()), datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); writeByte(D::adjust(pixels.loadAndScale2()), datapin, datahi_clockhi, datalo_clockhi, datahi_clocklo, datalo_clocklo); pixels.advanceData(); pixels.stepDithering(); } } #endif D::postBlock(len); release(); } }; FASTLED_NAMESPACE_END #endif
[ "jmkauf@gmail.com" ]
jmkauf@gmail.com
f75d66f6d6ba670dc93879f2be0ebaa1b432cdeb
d270f93af93308a2a406ffa7cd8a9ba08a1b0830
/include/AStar.h
7edce2c4f95cc7591a6255bfbf50955ed4776670
[]
no_license
marija185/cspacevoroandrea
8d930f15a394ff4bc04afb1385df630117ba966d
a04edb239ec10b1f33fa4d71d43d32b471eb10a3
refs/heads/master
2021-01-21T13:44:03.024971
2016-05-01T21:26:59
2016-05-01T21:26:59
50,572,799
0
0
null
null
null
null
UTF-8
C++
false
false
502
h
/* * AStar.h * * Created on: Dec 14, 2012 * Author: sprunkc */ #ifndef ASTAR_H_ #define ASTAR_H_ #include "SearchNode.h" #include "bucketedqueue.h" class AStar { public: AStar(); virtual ~AStar(); std::vector<SearchNode*>* searchPath(SearchNode* start, SearchNode* goal); unsigned int getCurrentIteration(); private: void expandNode(SearchNode* n); unsigned int currentIteration; SearchNode* currentGoal; BucketPrioQueue<SearchNode*> queue; }; #endif /* ASTAR_H_ */
[ "marija.seder@gmail.com" ]
marija.seder@gmail.com
371dcc8a8d10a1cf69fd1062f0767c333f912a12
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/windows/appcompat/shims/specific/worms2.cpp
64d1e06b08cda7c9e06dd19ce0552fc4588c853f
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
3,385
cpp
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: Worms2.cpp Abstract: Extremely lame hack because we don't properly support full-screen MCI playback on NT. Notes: This is an app specific shim. History: 12/04/2000 linstev Created --*/ #include "precomp.h" #include <mmsystem.h> #include <digitalv.h> #include <mciavi.h> IMPLEMENT_SHIM_BEGIN(Worms2) #include "ShimHookMacro.h" APIHOOK_ENUM_BEGIN APIHOOK_ENUM_ENTRY(mciSendCommandA) APIHOOK_ENUM_END /*++ Do lots of lame stuff. --*/ MCIERROR APIHOOK(mciSendCommandA)( MCIDEVICEID IDDevice, UINT uMsg, DWORD fdwCommand, DWORD dwParam ) { if ((uMsg == MCI_PLAY) && (fdwCommand == (MCI_NOTIFY | MCI_WAIT | MCI_MCIAVI_PLAY_FULLSCREEN))) { DEVMODEA dm; dm.dmSize = sizeof(dm); dm.dmPelsWidth = 320; dm.dmPelsHeight = 200; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettingsA(&dm, CDS_FULLSCREEN); #define szWndClass "WORMS2_HACK_WINDOW" WNDCLASSA cls; HMODULE hModule = GetModuleHandle(0); if (!GetClassInfoA(hModule, szWndClass, &cls)) { cls.lpszClassName = szWndClass; cls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); cls.hInstance = hModule; cls.hIcon = NULL; cls.hCursor = NULL; cls.lpszMenuName = NULL; cls.style = CS_DBLCLKS; cls.lpfnWndProc = DefWindowProc; cls.cbWndExtra = sizeof(INT_PTR); cls.cbClsExtra = 0; if (RegisterClassA(&cls) == 0) { goto Fail; } } HWND hWnd = CreateWindowA( szWndClass, szWndClass, WS_OVERLAPPED|WS_POPUP|WS_VISIBLE, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), (HWND)NULL, NULL, hModule, (LPVOID)NULL); if (!hWnd) { goto Fail; } MCIERROR merr; MCI_DGV_WINDOW_PARMSA mciwnd; mciwnd.dwCallback = (DWORD)DefWindowProcA; mciwnd.hWnd = hWnd; mciwnd.lpstrText = 0; mciwnd.nCmdShow = 0; merr = mciSendCommandA(IDDevice, MCI_WINDOW, MCI_DGV_WINDOW_HWND, (DWORD)&mciwnd); if (merr != MMSYSERR_NOERROR) { DestroyWindow(hWnd); goto Fail; } ShowCursor(FALSE); MCI_PLAY_PARMS mciply; mciply.dwCallback = (DWORD)hWnd; mciply.dwFrom = 0x40000000; mciply.dwTo = 0; merr = mciSendCommandA(IDDevice, MCI_PLAY, MCI_NOTIFY | MCI_WAIT, (DWORD)&mciply); DestroyWindow(hWnd); ShowCursor(TRUE); if (merr != MMSYSERR_NOERROR) { goto Fail; } return 0; } Fail: return ORIGINAL_API(mciSendCommandA)( IDDevice, uMsg, fdwCommand, dwParam); } /*++ Register hooked functions --*/ HOOK_BEGIN APIHOOK_ENTRY(WINMM.DLL, mciSendCommandA) HOOK_END IMPLEMENT_SHIM_END
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
853bec57bd23180a56646bb1eb1c64b54ac6af9c
53f3c732806af13f696b7038b9bb4edacb5103ab
/BinaryTreeTemplate/BinaryTree.h
8fc1c8dc8df198713b2464d41afa7d5dbccb3b30
[]
no_license
deeppudasaini/BinaryTreeTemplate
7b5554efc5600e9c5e75eab1d7e3265dd43241d0
bdbae6023926b423c460c840c8a8e7601c0418f3
refs/heads/master
2021-12-02T01:11:57.627061
2014-04-17T22:22:27
2014-04-17T22:22:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,652
h
// Written by Zack Rosales // Advanced C++ Programming ITSE 2431 1001 // Program from page 1164, #1 // Class template definition file for BinaryTree #ifndef BINARYTREE_H #define BINARYTREE_H #include <iostream> // for cout and cin using namespace std; template <class T> class BinaryTree { private: // TreeNode struct definition struct TreeNode { T value; // value stored in node TreeNode *left, // pointer to left child node *right; // pointer to right child node }; // TreeNode struct end TreeNode *root; // pointer to root node // recursive insert method traverses tree to find correct location to add new node void insert(TreeNode *&nodePtr, TreeNode *&newNode) // insert method start { if (nodePtr == NULL) { nodePtr = newNode; // insert new node } // end if else if (newNode->value < nodePtr->value) { insert(nodePtr->left, newNode); } // end else if else { insert(nodePtr->right, newNode); } // end else } // insert method end // recursive destroySubTree is called by destructor to destroy tree void destroySubTree(TreeNode *nodePtr) // destroySubTree method start { if (nodePtr) { if (nodePtr->left) { destroySubTree(nodePtr->left); } // end if if (nodePtr->right) { destroySubTree(nodePtr->right); } // end if delete nodePtr; } // end if } // destroySubTree method end // recursive deleteNode method traverses tree to locate node to remove from tree void deleteNode(T val, TreeNode *&nodePtr) // deleteNode method start { if (val < nodePtr->value) { deleteNode(val, nodePtr->left); } // end if else if (val > nodePtr->value) { deleteNode(val, nodePtr->right); } // end else if else { makeDeletion(nodePtr); } // end else } // deleteNode method end // makeDeletion method removes the selected node and re-attaches any children to the tree void makeDeletion(TreeNode *&nodePtr) // makeDeletion method start { TreeNode *tempNodePtr; if (nodePtr == NULL) { throw EmptyNode(); } // end if else if (nodePtr->right == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->left; delete tempNodePtr; } // end else if else if (nodePtr->left == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->right; delete tempNodePtr; } // end else if else { tempNodePtr = nodePtr->right; while (tempNodePtr->left) { tempNodePtr = tempNodePtr->left; } // end while tempNodePtr->left = nodePtr->left; tempNodePtr = nodePtr; nodePtr = nodePtr->right; delete tempNodePtr; } // end else } // makeDeletion method end // recursive displayInOrder method displays the values of the tree in ascending order void displayInOrder(TreeNode *nodePtr) const // displayInOrder method start { if (nodePtr) { displayInOrder(nodePtr->left); cout << nodePtr->value << endl; displayInOrder(nodePtr->right); } // end if } //displayInOrder method end // recursive displayPreOrder method displays the values of the tree starting at the root and working down the branches void displayPreOrder(TreeNode *nodePtr) const // displayPreOrder method start { if (nodePtr) { cout << nodePtr->value << endl; displayPreOrder(nodePtr->right); displayPreOrder(nodePtr->left); } // end if } // displayPreOrder method end // recursive displayPostOrder method displays the values of the tree in postorder traversal void displayPostOrder(TreeNode *nodePtr) const // displayPostOrder method start { if (nodePtr) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout << nodePtr->value << endl; } // end if } // displayPostOrder method end // recursive countNodes method counts the number of nodes in the tree int countNodes(TreeNode *nodePtr, int count) // countNodes method start { if (nodePtr) { count++; countNodes(nodePtr->left, count); countNodes(nodePtr->right, count); } // end if return count; } // countNodes method end // recursive countLeaves method counts the number of leaves in the tree int countLeaves(TreeNode *nodePtr, int count) // countLeaves method start { if (nodePtr->right == NULL && nodePtr->left == NULL) { count++; } // end if if (nodePtr->left != NULL) { countLeaves(nodePtr->left, count); } // end if if (nodePtr->right != NULL) { countLeaves(nodePtr->right, count); } // end if return count; } // countLeaves method end // recursive copy method works with the copy constructor to copy a tree void copy(TreeNode *thisNode, TreeNode *sourceNode) // copy method start { if (sourceNode == NULL) { thisNode = NULL; } // end if else { thisNode = new TreeNode; thisNode->value = sourceNode->value; copy(thisNode->left, sourceNode->left); copy(thisNode->right, sourceNode->right); } // end else } // copy method end public: // exception class class EmptyNode {}; // constructor BinaryTree() { root = NULL; } // constructor end // copy constructor BinaryTree(BinaryTree<T> &tree) { if (tree.root == NULL) { root = NULL; } // end if else { copy(this->root, tree.root); } // end else } // copy constructor end // desctructor ~BinaryTree() { destroySubTree(root); } // destructor end // insertNode method creates a new node and passes it to insert method void insertNode(T val) // insertNode method start { TreeNode *newNode; newNode = new TreeNode; newNode->value = val; newNode->left = newNode->right = NULL; insert(root, newNode); } // insertNode method end // searchNode method searches tree for a value and returns true if found, false if not in tree bool searchNode(T val) // searchNode method start { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr->value = val) { return true; } // end if else if (val < nodePtr->value) { nodePtr = nodePtr->left; } // end else if else { nodePtr = nodePtr->right; } // end else } // end while return false; } // searchNode method end // remove method calls private deleteNode method to remove the node containing the passed value void remove(T val) // remove method start { deleteNode(val, root); } // remove method end // public displayInOrder calls private displayInOrder with root as argument void displayInOrder() // displayInOrder method start { displayInOrder(root); } // displayInOrder method end // public displayPreOrder calls private displayPreOrder with root as argument void displayPreOrder() // displayPreOrder method start { displayPreOrder(root); } // displayPreOrder method end // public displayPostOrder calls private displayPostOrder with root as argument void displayPostOrder() // displayPostOrder method start { displayPostOrder(root); } // displayPostOrder method end // isEmpty returns true if tree is empty, false otherwise bool isEmpty() // isEmpty methos start { if (root == NULL) { return true; } // end if else { return false; } // end else } // isEmpty method end // public countNodes method calls private countNodes method with root as argument int countNodes() // countNodes method start { // local variable int count = 0; count = countNodes(root, count); return count; } // countNodes method end // public countLeaves method calls private countLeaves method with root as argument int countLeaves() // countLeaves method start { int count = 0; count = countLeaves(root, count); return count; } // countLeaves method end }; #endif // !BINARYTREE_H
[ "nightphoenix13@hotmail.com" ]
nightphoenix13@hotmail.com
3ac61a6873a11d19839a8c7e12042af97d0843b3
b521694fb2a399dcfdbe196ffa66028fe14cc9d0
/Chapter07/structs/main.cpp
379bca0ebdffcab7d6585e24bdbe368e3f18498e
[]
no_license
nic-cs150-fall-2019/LectureCodes103
7eccddcba27a0add1e89fc19955dc4c95a019848
d5fa40d0dad00c1a88388dfb74ffdf27ee409ec3
refs/heads/master
2020-07-12T05:49:03.748666
2019-11-07T23:23:50
2019-11-07T23:23:50
204,734,593
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
#include<iostream> using namespace std; class Employee2 { public: string st_name; int st_numUsedDays; }; struct Employee { string st_name; int st_numUsedDays; Employee(string name = "", int usedDays = 0) { st_name = name; st_numUsedDays = usedDays; } }; int main() { Employee e1, e2("John", 3); cout << e1.st_name << '\n'; cout << e1.st_numUsedDays << '\n'; cout << e2.st_name << '\n'; cout << e2.st_numUsedDays << '\n'; return 0; }
[ "gabrieledcjr@gmail.com" ]
gabrieledcjr@gmail.com
c29790f4c2f32065d9d28dd57d2d01638aff07c2
884093beda0d245de7362c53d5f7896aa5e72527
/shared_function.h
2b67e313a7af6a3ee61168fe29c15c6852d28bad
[]
no_license
Visitor15/distributor
d3938415c7ef6e1274e900ebc9ce462dd66a3b88
50636b2557898dbf239ebc67db1833550b1f6c18
refs/heads/master
2016-09-03T06:54:49.777446
2014-06-10T00:34:54
2014-06-10T00:34:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
h
// // shared_function.h // Distributor // // Created by Nick C. on 6/1/14. // Copyright (c) 2014 fORGED. All rights reserved. // #ifndef Distributor_shared_function_h #define Distributor_shared_function_h #include "instruction_response.h" #include "instruction_data.h" #include "utils.h" typedef InstructionResponse (*functionPtr)(InstructionData data); typedef struct _sharedPtr { private: std::string _externalId; long _internalId; functionPtr _funcPtr; public: _sharedPtr() : _externalId(""), _internalId(-1) {} _sharedPtr(char* strId) : _externalId(strId), _internalId(0) {} _sharedPtr(char* strId, functionPtr ptr) : _externalId(strId), _internalId(0), _funcPtr(ptr) {} ~_sharedPtr() {} std::string getStringId() { return _externalId; } long getInternalId() { return _internalId; } void setStringId(std::string str) { _externalId.erase(_externalId.begin(), _externalId.end()); _externalId.append(str); } void setInternalId(long ptrId) { _internalId = ptrId; } bool validate() { // Sanity check to ensure we actually have a string id. Utils::TRIM_STRING(_externalId); if((_internalId >= 0) && (_externalId.length() > 0)) { return true; } return false; } InstructionResponse executeFunction(InstructionData &functionData) { return (*_funcPtr)(functionData); } } SharedFunction; #endif
[ "visitor15@gmail.com" ]
visitor15@gmail.com
80f0643194217964863930cf977bbbdbe6c96747
17b83a201a932f2b3d17a2c31a1d1f85ad222924
/bfs_ssp_header.h
db039e15dc8e95aad1c2bc815edf1511718cfe70
[]
no_license
stuti15P/Graph
5898953b53bbd2c615c9706713ef7b63eeb0a4c9
b2451b9fd3de6a9e09b815b4ea6f2ffffc5bb8b9
refs/heads/master
2022-11-29T06:29:05.507953
2020-08-11T08:24:01
2020-08-11T08:24:01
272,791,955
0
0
null
null
null
null
UTF-8
C++
false
false
343
h
#ifndef _BFS_SSP_H #define _BFS_SSP_H #include<iostream> #include<climits> #include<map> #include<list> #include<queue> using namespace std; template<typename T> class Graph { public: map<T, list<T> > m; void addEdge(T src, T dest, bool bidir =true); void printGraph(); void bfs_ssp(T start); }; #endif // _BFS_SSp_H
[ "noreply@github.com" ]
noreply@github.com
6e04875d22a7477a91998ada28b5060bba328460
b5af8a68e7b31355b0c500811a93dbbc7a43e9c7
/inc/sectorhistogram.h
3481b5f97030e33bf2d672795b086b6e259fd163
[]
no_license
ffboy/TKDetection
bdddc06569d5f9172df4c50f391037e2ec482327
8e6171bce55573f1de82100d662a2c193cbbadbc
refs/heads/master
2023-01-04T21:14:28.524599
2019-05-10T11:59:12
2019-05-10T11:59:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
#ifndef SECTORHISTOGRAM_H #define SECTORHISTOGRAM_H #include "histogram.h" #include "def/def_billon.h" class Pith; class SectorHistogram : public Histogram<qreal> { public: SectorHistogram(); virtual ~SectorHistogram(); void construct(const Billon &billon, const Interval<uint> &sliceInterval, const Interval<int> &intensity, const uint &zMotionMin, const int &radiusAroundPith ); void computeMaximumsAndIntervals( const uint &smoothingRadius, const int & minimumHeightPercentageOfMaximum, const int & derivativesPercentage, const int &minimumWidthOfIntervals, const uint &intervalGap, const bool & loop ); }; #endif // SECTORHISTOGRAM_H
[ "adrien.krahenbuhl@loria.fr" ]
adrien.krahenbuhl@loria.fr
5306d5628da39852666966796c37a2882a7b7ca9
222c3d2fd75c460e7c5cb9e01ee8af4a19f29804
/aula_18/ConteudoMinistrado.hpp
10a7891db8553bd1b020adf23510a76b442dc3c9
[ "MIT" ]
permissive
matheusalanojoenck/aula_cpp
e4b8883317fd8af5f2dea256e164228d99bf73f1
039bd4f4b11a736f1d800cad97a530e212b30375
refs/heads/master
2022-12-15T05:26:21.139261
2020-09-11T15:51:20
2020-09-11T15:51:20
257,736,518
0
0
null
null
null
null
UTF-8
C++
false
false
484
hpp
#ifndef CONTEUDO_MINISTRADO_HPP #define CONTEUDO_MINISTRADO_HPP #include<string> class ConteudoMinistrado{ public: ConteudoMinistrado(std::string descricao, unsigned short cargaHorariaConteudo); ~ConteudoMinistrado(); const std::string& getDescricao() const; unsigned short getCargaHorariaConteudo() const; unsigned int getId() const; private: static unsigned int proxId; std::string descricao; unsigned short cargaHorariaConteudo; unsigned int id; }; #endif
[ "matheusalanojoenck@gmail.com" ]
matheusalanojoenck@gmail.com
a72a0df72a26e079d5b733edaf4eba3b9a37e070
645379b56fc1468d52cd27ce4ded3895fd0f1fa1
/Cadriciel/Commun/Utilitaire/Vue/Projection.cpp
d81f4fd7696860d5c44c4f26926e5a3641779ff2
[]
no_license
kiwistaki/AsteroidShooter
7faba3dff36d124b42b8ac51bc361d236fdcc574
32f5ab9a73a5ef0c9b5a312cb0a3f0ddcb0ac7cd
refs/heads/master
2021-01-20T02:53:44.476126
2017-05-05T23:39:51
2017-05-05T23:39:51
83,821,917
0
0
null
null
null
null
IBM852
C++
false
false
3,887
cpp
//////////////////////////////////////////////////////////////////////////////////// /// @file Projection.cpp /// @author DGI /// @date 2006-12-15 /// @version 1.0 /// /// @addtogroup utilitaire Utilitaire /// @{ //////////////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <GL/gl.h> #include "Projection.h" #include "../EtatOpenGL.h" #include <string> using namespace std; namespace vue { //////////////////////////////////////////////////////////////////////// /// /// @fn Projection::Projection(int xMinCloture, int xMaxCloture, int yMinCloture, int yMaxCloture, double zAvant, double zArriere, double zoomInMax, double zoomOutMax, double incrementZoom, bool estPerspective) /// /// Constructeur d'une projection. Ne fait qu'assigner les variables /// membres. /// /// @param[in] xMinCloture : coordonnee minimale en @a x de la cl˘ture. /// @param[in] xMaxCloture : coordonnee maximale en @a x de la cl˘ture. /// @param[in] yMinCloture : coordonnee minimale en @a y de la cl˘ture. /// @param[in] yMaxCloture : coordonnee maximale en @a y de la cl˘ture. /// @param[in] zAvant : distance du plan avant (en @a z). /// @param[in] zArriere : distance du plan arriere (en @a z). /// @param[in] zoomInMax : facteur de zoom in maximal. /// @param[in] zoomOutMax : facteur de zoom out maximal. /// @param[in] incrementZoom : distance du plan arriere (en @a z). /// @param[in] estPerspective : vrai si la projection est perspective. /// /// @return Aucune (constructeur). /// //////////////////////////////////////////////////////////////////////// Projection::Projection(int xMinCloture, int xMaxCloture, int yMinCloture, int yMaxCloture, double zAvant, double zArriere, double zoomInMax, double zoomOutMax, double incrementZoom, bool estPerspective) : xMinCloture_(xMinCloture), xMaxCloture_(xMaxCloture), yMinCloture_(yMinCloture), yMaxCloture_(yMaxCloture), zAvant_(zAvant), zArriere_(zArriere), zoomInMax_(zoomInMax), zoomOutMax_(zoomOutMax), incrementZoom_(incrementZoom), estPerspective_(estPerspective) { } //////////////////////////////////////////////////////////////////////// /// /// @fn void Projection::mettreAJourCloture() const /// /// Specifie la cl˘ture de la fenetre a l'aide de la fonction glViewport() /// dans la machine a etats d'OpenGL. /// /// @return Aucune. /// //////////////////////////////////////////////////////////////////////// void Projection::mettreAJourCloture() const { glViewport( xMinCloture_, yMinCloture_, GLint( xMaxCloture_ - xMinCloture_ ), GLint( yMaxCloture_ - yMinCloture_ ) ); } //////////////////////////////////////////////////////////////////////// /// /// @fn void Projection::mettreAJourProjection() const /// /// Specifie la matrice de projection dans la machine a etats d'OpenGL. /// /// @return Aucune. /// //////////////////////////////////////////////////////////////////////// void Projection::mettreAJourProjection() const { // Sauvegarde du mode courant de matrice. GLint mode; glGetIntegerv(GL_MATRIX_MODE, &mode); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Application de la projection. appliquer(); EtatOpenGL etat; string state = etat.obtenirChaineGlProjectionMatrix(); glMatrixMode(mode); } }; // Fin du namespace vue. /////////////////////////////////////////////////////////////////////////// /// @} ///////////////////////////////////////////////////////////////////////////
[ "paquet.alex@gmail.com" ]
paquet.alex@gmail.com
a67efc2977f844828a044a0407501a121a8859aa
4107423e1351572068f7ea6df3b49bf85ea5a321
/Source/USemLog/Private/Individuals/Type/SLSkyIndividual.cpp
12e73e3a88362e30faa9a802b8e464540c0cf26a
[ "BSD-3-Clause" ]
permissive
mohGhazala96/USemLog
2fdb4c1eebd59eaa66adb7a16a76d492057fff38
f6aa50df82bee8052cb1196d16d26db621117392
refs/heads/master
2023-09-03T16:14:35.512074
2021-11-03T12:32:07
2021-11-03T12:32:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,592
cpp
// Copyright 2017-present, Institute for Artificial Intelligence - University of Bremen // Author: Andrei Haidu (http://haidu.eu) #include "Individuals/Type/SLSkyIndividual.h" #include "Atmosphere/AtmosphericFog.h" // Ctor USLSkyIndividual::USLSkyIndividual() { bIsMovable = false; } // Called before destroying the object. void USLSkyIndividual::BeginDestroy() { SetIsInit(false); Super::BeginDestroy(); } // Create and set the dynamic material, the owners visual component void USLSkyIndividual::PostInitProperties() { Super::PostInitProperties(); //Init(); } // Set pointer to the semantic owner bool USLSkyIndividual::Init(bool bReset) { if (bReset) { InitReset(); } if (IsInit()) { return true; } SetIsInit(Super::Init(bReset) && InitImpl()); return IsInit(); } // Load semantic data bool USLSkyIndividual::Load(bool bReset, bool bTryImport) { if (bReset) { LoadReset(); } if (IsLoaded()) { return true; } if (!IsInit()) { if (!Init(bReset)) { return false; } } SetIsLoaded(Super::Load(bReset, bTryImport) && LoadImpl(bTryImport)); return IsLoaded(); } // Apply visual mask material bool USLSkyIndividual::ApplyMaskMaterials(bool bIncludeChildren /*= false*/) { if (!IsInit()) { return false; } if (!bIsMaskMaterialOn) { #if WITH_EDITOR ParentActor->SetIsTemporarilyHiddenInEditor(true); #endif // WITH_EDITOR ParentActor->SetActorHiddenInGame(true); bIsMaskMaterialOn = true; return true; } return false; } // Apply original materials bool USLSkyIndividual::ApplyOriginalMaterials() { if (!IsInit()) { return false; } if (bIsMaskMaterialOn) { #if WITH_EDITOR ParentActor->SetIsTemporarilyHiddenInEditor(false); #endif // WITH_EDITOR ParentActor->SetActorHiddenInGame(false); bIsMaskMaterialOn = false; return true; } return false; } // Get class name, virtual since each invidiual type will have different name FString USLSkyIndividual::CalcDefaultClassValue() { if (IsInit()) { if (AAtmosphericFog* AAF = Cast<AAtmosphericFog>(ParentActor)) { return "AtmosphericFog"; } else if (ParentActor->GetName().Contains("SkySphere")) { return "SkySphere"; } } return GetTypeName(); } // Private init implementation bool USLSkyIndividual::InitImpl() { return true; } // Private load implementation bool USLSkyIndividual::LoadImpl(bool bTryImport) { return true; } // Clear all values of the individual void USLSkyIndividual::InitReset() { LoadReset(); SetIsInit(false); } // Clear all data of the individual void USLSkyIndividual::LoadReset() { SetIsLoaded(false); }
[ "andrei.haidu@yahoo.com" ]
andrei.haidu@yahoo.com
0be50315aa0a68951468dc06beb099415b5fa2a2
e5c0b38c9cc0c0e6155c9d626e299c7b03affd1e
/trunk/Code/Engine/PhysX/CharacterController/PhysicController.h
fe258c987262b50ac76eef8dba64d19bbdadfbaf
[]
no_license
BGCX261/zombigame-svn-to-git
4e5ec3ade52da3937e2b7d395424c40939657743
aa9fb16789f1721557085deae123771f5aefc4dd
refs/heads/master
2020-05-26T21:56:40.088036
2015-08-25T15:33:27
2015-08-25T15:33:27
41,597,035
0
0
null
null
null
null
UTF-8
C++
false
false
2,798
h
//---------------------------------------------------------------------------------- // CPhysicController class // Author: Enric Vergara // // Description: // Esta clase representa un controlador de caracter. //---------------------------------------------------------------------------------- #pragma once #ifndef INC_PHYSIC_CONTROLLER_H #define INC_PHYSIC_CONTROLLER_H #include "Jump.h" #include "Object3D/Object3D.h" //---Forward Declarations--- class NxController; class NxCapsuleControllerDesc; class NxScene; class CPhysicUserData; class CPhysicControllerReport; //-------------------------- class CPhysicController:public CObject3D { public: CPhysicController( float radius, float height, float slope, float skinwidth, float stepOffset, uint32 collisionGroups, CPhysicUserData* userData, const Vect3f& pos = Vect3f(0.f,0.f,0.f), float gravity = -9.8f, float m_VerticalVelocity = 0.0f); ~CPhysicController(); CPhysicUserData* GetUserData () {return m_pUserData;} void SetCollision (bool flag); void Move (const Vect3f& direction, float elapsedTime); void Jump (float ammount, float _directionX, float _directionZ); bool UpdateCharacterExtents (bool bent, float ammount); Vect3f GetPosition (); void SetPosition (const Vect3f& pos); float GetGravity () const {return m_fGravity;} void SetGravity (float gravity) {m_fGravity = gravity;} float GetTotalHeight () { return m_fHeight_Capsule + m_fRadius_Capsule * 2; } float GetHeight () { return m_fHeight_Capsule; } float GetRadius () { return m_fRadius_Capsule; } //---PhsX Info--- NxController* GetPhXController () {return m_pPhXController;} NxCapsuleControllerDesc* GetPhXControllerDesc () {return m_pPhXControllerDesc;} void CreateController (NxController* controller, NxScene* scene); unsigned short GetGroup (); private: CPhysicUserData* m_pUserData; uint32 m_uCollisionGroups; CJump m_Jump; float m_fGravity; float m_fRadius_Capsule; float m_fHeight_Capsule; float m_fSlopeLimit_Capsule; float m_fSkinWidth_Capsule; float m_fStepOffset_Capsule; float m_VerticalVelocity; float m_fJumpDirectionX; float m_fJumpDirectionZ; //--- PhysX-- NxCapsuleControllerDesc* m_pPhXControllerDesc; NxController* m_pPhXController; NxScene* m_pPhXScene; CPhysicControllerReport* m_PhXControllerHitEvent; }; #endif //INC_PHYSIC_CONTROLLER_H
[ "you@example.com" ]
you@example.com
754a6f6d2e124cafcf5c5d8cfd319021a1e7963b
5aa4d76fef6247d93b6500f73512cdc98143b25d
/00_C_Lang/API/SampleWIn/CCInput.h
0f599a984549f13c39d840aad8508298ee31cb7c
[]
no_license
leader1118/KHJ-Project
a854bc392991e24774ab0feca0bb49eb8593ef15
0eb0144bbd2b4d40156402a5994c8f782b558f6c
refs/heads/master
2020-04-05T20:44:07.339776
2019-02-01T10:11:45
2019-02-01T10:11:45
157,193,296
0
1
null
null
null
null
UHC
C++
false
false
620
h
#pragma once #include "STD.h" enum KeyState { KEY_FREE = 0, KEY_PUSH, KEY_UP, KEY_HOLD, }; class CCInput { public: std::vector<wstring> m_strList; TCHAR m_csBuffer[MAX_PATH]; DWORD m_dwKeyState[256]; DWORD m_dwMouseState[3]; RECT m_MovePt; public: DWORD KeyCheck(DWORD dwKey); //클래스 멤버 변수 초기화 bool Init(); //매 프레임에서 계산을 담당한다. bool Frame(); //매 프레임에서 드로우를 담당한다. bool Render(); //클래스 멤버 변수 소멸을 담당한다. bool Release(); void MsgEvent(MSG msg); public: CCInput(); virtual ~CCInput(); };
[ "hyunjin9173@gmail.com" ]
hyunjin9173@gmail.com
999e404f7167731800bdfd85a858677187d3c92e
3b91f36a97487bd5a49ab749614ca44a5b5d1b24
/0.8.0.0/CrossNetRuntime/includes/CrossNetRuntime/Internal/Cast.h
1280d0e37307d3b4a3c730c9d3b311a9f35aecf2
[ "MIT" ]
permissive
MavenRain/CrossNet
ec15ee191a99dff8c3f2af6357a4f397a469ba76
ab3d6c1afe8e8c5d69d14521bb94871e0e1524f4
refs/heads/master
2016-09-06T03:14:38.337404
2015-03-12T07:51:15
2015-03-12T07:51:15
32,064,166
0
0
null
null
null
null
UTF-8
C++
false
false
9,459
h
/* CrossNet - Copyright (c) 2007 Olivier Nallet Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __CROSSNET_CAST_H__ #define __CROSSNET_CAST_H__ #include "CrossNetRuntime/System/Object.h" namespace CrossNetRuntime { template <typename U, typename V> static CROSSNET_FINLINE U UnsafeCast(V other) { // A safer approach would be to use reinterpret_cast as it would almost cast anything even unrelated types // But in order to discover (and solve) tricky casting issue, we use static_cast // If your product doesn't compile here because of a cast not handled gracefully by CrossNet // Just change locally static_cast by reinterpret_cast // If one day, we find a case where static_cast doesn't work even with carefully specialized cast code // then we will switch definitively to reinterpret_cast. return static_cast<U>(other); } template <typename U, typename V> static CROSSNET_FINLINE U ReinterpretCast(V other) { return reinterpret_cast<U>(other); // For the moment use C cast, instead of reinterpret_cast... // The reason is that in one case (like for PointerWrapper) it seems we can't use reinterpret_cast // Even if a user conversion has been provided... // return (U)(other); } template <typename U, typename V> static CROSSNET_FINLINE U EnumCast(V other) { return static_cast<U>(other); } template <typename T> static CROSSNET_FINLINE T * Cast(System::Object * instance) { if (instance == NULL) { return (NULL); } void * pointer = instance->__Cast__(T::__GetId__()); CROSSNET_FATAL(pointer != NULL, STRINGIFY3("Could not cast the instance to the type ", T, "!")); return (T *)(pointer); } template <typename T> static CROSSNET_FINLINE T * Cast(CrossNetRuntime::IInterface * instance) { if (instance == NULL) { return (NULL); } void * pointer = ((System::Object *)instance)->__Cast__(T::__GetId__()); CROSSNET_FATAL(pointer != NULL, STRINGIFY3("Could not cast the instance to the type ", T, "!")); return (T *)(pointer); } // Those fast casts assume that the instance pointer and the cast pointer are actually the same address // Which is the case in CrossNet implementation (as well as .Net). template <typename T> static CROSSNET_FINLINE T * FastCast(System::Object * instance) { CROSSNET_FATAL((instance == NULL) || (instance->__Cast__(T::__GetId__()) != NULL), STRINGIFY3("Could not cast the instance to the type ", T, "!")); return (T *)(instance); } template <typename T> static CROSSNET_FINLINE T * FastCast(CrossNetRuntime::IInterface * instance) { CROSSNET_FATAL((instance == NULL) || (((System::Object *)instance)->__Cast__(T::__GetId__()) != NULL), STRINGIFY3("Could not cast the instance to the type ", T, "!")); return (T *)(instance); } // For the moment this is the same code as CrossNetRuntime::Cast // We might want to change that later... template <typename T> static CROSSNET_FINLINE T * InterfaceCast(System::Object * instance) { if (instance == NULL) { return (NULL); } void * pointer = instance->__Cast__(T::__GetId__()); CROSSNET_FATAL(pointer != NULL, STRINGIFY3("Could not cast the instance to the interface ", T, "!")); return (T *)(pointer); } template <typename T> static CROSSNET_FINLINE T * InterfaceCast(CrossNetRuntime::IInterface * instance) { if (instance == NULL) { return (NULL); } void * pointer = ((System::Object *)instance)->__Cast__(T::__GetId__()); CROSSNET_FATAL(pointer != NULL, STRINGIFY3("Could not cast the instance to the interface ", T, "!")); return (T *)(pointer); } template <typename T, typename U> static CROSSNET_FINLINE T * InterfaceCast(U instance) { return (Box<T>(instance)); } // This interface cast is used for NULL pointers passed. // NULL is actually passed as the integer 0 // This is actually hard-coded in the compiler that 0 can represent NULL pointer for any type! // We check in this function that the value passed corresponds to a NULL pointer. // Obviously nothing guarantees that the user did not pass 0 explicitly but this should help detect other issues. template <typename T> static CROSSNET_FINLINE T * InterfaceCast(int integer) { CROSSNET_FATAL(integer == NULL, "The value was not NULL!"); return (T *)(NULL); } template <typename T> class BaseTypeWrapper; // This is interface cast is used for primitive types used as generic parameter // The goal is to differentiate with the version above (with int as parameter for NULL pointers). template <typename T, typename U> static CROSSNET_FINLINE T * InterfaceCast(typename CrossNetRuntime::BaseTypeWrapper<U> value) { return (Box<T>((U)value)); } template <typename T> static CROSSNET_FINLINE T * AsCast(System::Object * instance) { if (instance == NULL) { return (NULL); } void * pointer = instance->__Cast__(T::__GetId__()); return (T *)(pointer); } template <typename T> static CROSSNET_FINLINE T * AsCast(CrossNetRuntime::IInterface * instance) { if (instance == NULL) { return (NULL); } void * pointer = ((System::Object *)(instance))->__Cast__(T::__GetId__()); return (T *)(pointer); } // "as" with a value type as right member instead of a reference // This is useful for generic code for example template <typename T, typename V> static CROSSNET_FINLINE T * AsCast(const V & o) { // First box the object (so we can get the corresponding interface map) // TODO: Get the interface map without having to box the object! System::Object * instance = Box<::System::Object>(o); if (instance == NULL) { // In some case like with generics, the object passed will actually be a NULL pointer // So after the boxing, it will still return NULL // We don't want to crash during the cast. // In this case we know that we cannot do the conversion return (NULL); } void * pointer = instance->__Cast__(T::__GetId__()); return (T *)(pointer); } template <typename T> static CROSSNET_FINLINE bool IsCast(System::Object * instance) { if (instance == NULL) { return (false); } void * pointer = instance->__Cast__(T::__GetId__()); return (pointer != NULL); } template <typename T> static CROSSNET_FINLINE bool IsCast(CrossNetRuntime::IInterface * instance) { if (instance == NULL) { return (false); } void * pointer = (System::Object *)(instance)->__Cast__(T::__GetId__()); return (pointer != NULL); } // "is" with a value type as right member instead of a reference // This is useful for generic code for example template <typename T, typename V> static CROSSNET_FINLINE bool IsCast(const V & o) { // First box the object (so we can get the corresponding interface map) // TODO: Get the interface map without having to box the object! System::Object * instance = Box<::System::Object>(o); if (instance == NULL) { // In some case like with generics, the object passed will actually be a NULL pointer // So after the boxing, it will still return NULL // We don't want to crash during the cast. // In this case we know that we cannot do the conversion return (false); } void * pointer = instance->__Cast__(T::__GetId__()); return (pointer != NULL); } } #endif
[ "v-oniobi@v-oniobi-1217.redmond.corp.microsoft.com" ]
v-oniobi@v-oniobi-1217.redmond.corp.microsoft.com
e7306c8e74374790636f26d47f2e72449954ad82
57165cc17e2e2a00a780f60c2c594fc2f2b6d24b
/umf_cylinder_detector/edges.h
5a4cf88fd0d2c69f5394dc119e6a8a45cea0e81f
[]
no_license
crosser87/umf_on_cylinder_final
6120678f1bf5b48dd3eee4afa0399982414f6f46
a770fb01b8915134163823d7f99de2efcf35585b
refs/heads/master
2021-01-10T21:15:04.226848
2013-05-06T22:35:14
2013-05-06T22:35:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,749
h
#ifndef DP_EDGES_H #define DP_EDGES_H #include <opencv2/opencv.hpp> #include <vector> /** * Třída CFindEdges * * Hledá hranové body na skenovacích přímkách. Hrany určuje podle adaptivního * prahování založeného na rozdílu hodnoty aktuálního bodu od průměrné hodnoty * bufferu předchozích bodů. * * @author Radim Kříž (xkrizr03@stud.fit.vutbr.cz) */ class CFindEdges { public: /** * Konstruktor CFindEdges * * @param int _scanlineStep vzdálenost mezi skenovacími přímkami * @param int _bufferSize velikost bufferu * @param int _adaptiveThreshold základ pro adaptivní práh */ CFindEdges(int _scanlineStep = 20, int _bufferSize = 15, int _adaptiveThreshold = 25); ~CFindEdges(){} /** * Metoda findEdges * * Hledá hranové body na skenovacích přímkách * * @param cv::Mat img zdrojový obraz * * @param std::vector<cv::Point2f>& &edges vektor nalezených hranových bodů */ void findEdges(cv::Mat img, std::vector<cv::Point2f>& edges); int adaptiveThreshold; // základ pro adaptivní práh int scanlineStep; // vzdálenost mezi skenovacími přímkami private: /** * Metoda scanLine * * Hladá hranové body na jedné skenovací přímce * * @param cv::Mat line sloupcový vektor všech bodů * * @param std::vector<cv::Point> &edges indexy nalezených bodů ve * sloupcovém vektoru */ void scanLine(cv::Mat line, std::vector<int>& edges); int bufferSize; // velikost bufferu pro vypočet adaptivního prahu }; #endif // DP_EDGES_H
[ "rk87@email.cz" ]
rk87@email.cz
54496751f38c5f5d4124546c43b7ccd4815f99a7
cc3dd76becae4605f6a2d173668f88e2b30ee2a8
/tutorial05Exercise2/tutorial05Exercise2/Main.cpp
93ec601ac3f95192ef76cb2cddf65bc5928e4b7b
[]
no_license
halasukkar97/tutorial05Exercise2
190320a7cf50d6c2dd614ac3a1a8b9d58a4c3d04
05d0389773546f11a102a7e5f8db76d399600ffb
refs/heads/master
2021-03-24T12:38:53.648337
2017-12-13T12:35:12
2017-12-13T12:35:12
114,118,611
0
0
null
null
null
null
UTF-8
C++
false
false
14,330
cpp
#include <windows.h> #include <d3d11.h> #include <d3dx11.h> #include <dxerr.h> #include <stdio.h> #define _XM_NO_INTRINSICS_ #define XM_NO_ALIGNMENT #include <xnamath.h> int (WINAPIV * __vsnprintf_s)(char *, size_t, const char*, va_list) = _vsnprintf; D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; ID3D11Device* g_pD3DDevice = NULL; ID3D11DeviceContext* g_pImmediateContext = NULL; IDXGISwapChain* g_pSwapChain = NULL; ID3D11RenderTargetView* g_pBackBufferRTView = NULL; ID3D11Buffer* g_pVertexBuffer; ID3D11VertexShader* g_pVertexShader; ID3D11PixelShader* g_pPixelShader; ID3D11InputLayout* g_pInputLayout; ID3D11Buffer* g_pConstantBuffer0; float rotationValue = 0; //define vertex structure struct POS_COL_VERTEX { XMFLOAT3 Pos; XMFLOAT4 Col; }; //const buffer structs. pack to 16 bytes. dont let any single element cross a 16 byte boundary struct CONSTANT_BUFFER0 { XMMATRIX WorldViewProjection; //64 bytes ( 4x4 = 16 floats x 4 bytes) float RedAmount; // 4 bytes float scale; //4 bytes XMFLOAT2 packing_bytes; //8 bytes // TOTAL SIZE = 80 BYTES }; HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; // Rename for each tutorial char g_TutorialName[100] = "Tutorial 01 Exercise 02\0"; // Forward declarations HRESULT InitialiseGraphics(void); HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); CONSTANT_BUFFER0 cb0_values; ////////////////////////////////////////////////////////////////////////////////////// // Create D3D device and swap chain ////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseD3D() { HRESULT hr = S_OK; RECT rc; GetClientRect(g_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, // comment out this line if you need to test D3D 11.0 functionality on hardware that doesn't support it D3D_DRIVER_TYPE_WARP, // comment this out also to use reference device D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE(driverTypes); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = true; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pD3DDevice, &g_featureLevel, &g_pImmediateContext); if (SUCCEEDED(hr)) break; } if (FAILED(hr)) return hr; // Get pointer to back buffer texture ID3D11Texture2D *pBackBufferTexture; hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBufferTexture); if (FAILED(hr)) return hr; // Use the back buffer texture pointer to create the render target view hr = g_pD3DDevice->CreateRenderTargetView(pBackBufferTexture, NULL, &g_pBackBufferRTView); pBackBufferTexture->Release(); if (FAILED(hr)) return hr; // Set the render target view g_pImmediateContext->OMSetRenderTargets(1, &g_pBackBufferRTView, NULL); // Set the viewport D3D11_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; g_pImmediateContext->RSSetViewports(1, &viewport); return S_OK; } void RenderFrame(void); ////////////////////////////////////////////////////////////////////////////////////// // Clean up D3D objects ////////////////////////////////////////////////////////////////////////////////////// void ShutdownD3D() { if (g_pVertexBuffer) g_pVertexBuffer->Release(); //03-01 if (g_pInputLayout)g_pInputLayout->Release(); //03-01 if (g_pVertexShader)g_pVertexShader->Release(); //03-01 if (g_pPixelShader)g_pPixelShader->Release(); //03-01 if (g_pBackBufferRTView) g_pBackBufferRTView->Release(); if (g_pSwapChain) g_pSwapChain->Release(); if (g_pConstantBuffer0) g_pConstantBuffer0->Release(); if (g_pImmediateContext) g_pImmediateContext->Release(); if (g_pD3DDevice) g_pD3DDevice->Release(); } HRESULT InitialiseD3D(); void ShutdownD3D(); ////////////////////////////////////////////////////////////////////////////////////// // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. ////////////////////////////////////////////////////////////////////////////////////// int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); if (FAILED(InitialiseWindow(hInstance, nCmdShow))) { DXTRACE_MSG("Failed to create Window"); return 0; } if (FAILED(InitialiseD3D())) { DXTRACE_MSG("Failed to create Device"); ShutdownD3D(); return 0; } //call initialiserGraphics if (FAILED(InitialiseGraphics())) //03-01 { DXTRACE_MSG("Failed to initialise graphics"); return 0; } // Main message loop MSG msg = { 0 }; while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { // do something RenderFrame(); } } ShutdownD3D(); return (int)msg.wParam; } ////////////////////////////////////////////////////////////////////////////////////// // Register class and create window ////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow) { // Give your app window your own name char Name[100] = "Tutorial 03 Exercise 02\0"; // Register class WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); // wcex.hbrBackground = (HBRUSH )( COLOR_WINDOW + 1); // Needed for non-D3D apps wcex.lpszClassName = Name; if (!RegisterClassEx(&wcex)) return E_FAIL; // Create window g_hInst = hInstance; RECT rc = { 0, 0, 640, 480 }; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); g_hWnd = CreateWindow(Name, g_TutorialName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL); if (!g_hWnd) return E_FAIL; ShowWindow(g_hWnd, nCmdShow); return S_OK; } ////////////////////////////////////////////////////////////////////////////////////// // Called every time the application receives a message ////////////////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) DestroyWindow(g_hWnd); else if (wParam == VK_UP) { //cb0_values.RedAmount -= 0.5f; //remove little bit of the redness //cb0_values.scale += 0.1f; // make it bigger //g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0); rotationValue += 0.5f; } else if (wParam == VK_DOWN) { //cb0_values.RedAmount += 0.5f; // add more redness //cb0_values.scale -= 0.1f; // make it smaller //g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0); rotationValue -= 0.5f; } return 0; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //init graphics //////////////////////////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseGraphics()//03-01 { HRESULT hr = S_OK; //create constant buffer //04-1 D3D11_BUFFER_DESC constant_buffer_desc; ZeroMemory(&constant_buffer_desc, sizeof(constant_buffer_desc)); constant_buffer_desc.Usage = D3D11_USAGE_DEFAULT; //can use updateSubresource() to update constant_buffer_desc.ByteWidth = 80; //must be a multiple of 16, calculate from CB struct constant_buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //use as a constant buffer hr = g_pD3DDevice->CreateBuffer(&constant_buffer_desc, NULL, &g_pConstantBuffer0); if (FAILED(hr)) return hr; //define vertices of a triangle - screen coordinates -1.0 to +1.0 POS_COL_VERTEX vertices[] = { { XMFLOAT3(0.9f, 0.9f, 0.0f),XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f) }, { XMFLOAT3(0.9f, -0.9f, 0.0f),XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f) }, { XMFLOAT3(-0.9f, -0.9f, 0.0f),XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f) } }; //set up and create vertex buffer D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(bufferDesc)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; //used by CPU and GPU bufferDesc.ByteWidth = sizeof(POS_COL_VERTEX) * 3; //total size of buffer, 3 vertices bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; //use as vertexbuffer bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; //allow CPU access hr = g_pD3DDevice->CreateBuffer(&bufferDesc, NULL, &g_pVertexBuffer);//create the buffer if (FAILED(hr))// return error code on dailure { return hr; } //copy the vertices into the buffer D3D11_MAPPED_SUBRESOURCE ms; //lock the buffer to allow writting g_pImmediateContext->Map(g_pVertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); //copy the data memcpy(ms.pData, vertices, sizeof(vertices)); //unlock the buffer g_pImmediateContext->Unmap(g_pVertexBuffer, NULL); //load and compile pixel and vertex shaders -use vs_5_0 to target DX11 hardware only ID3DBlob *VS, *PS, *error; hr = D3DX11CompileFromFile("shader.hlsl", 0, 0, "VShader", "vs_4_0", 0, 0, 0, &VS, &error, 0); if (error != 0)//check for shader compilation error { OutputDebugStringA((char*)error->GetBufferPointer()); error->Release(); if (FAILED(hr)) //dont fail if error is just a warning { return hr; }; } hr = D3DX11CompileFromFile("shader.hlsl", 0, 0, "PShader", "ps_4_0", 0, 0, 0, &PS, &error, 0); if (error != 0)//check for shader compilation error { OutputDebugStringA((char*)error->GetBufferPointer()); error->Release(); if (FAILED(hr)) //dont fail if error is just a warning { return hr; }; } //create shader objects hr = g_pD3DDevice->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &g_pVertexShader); if (FAILED(hr)) { return hr; } hr = g_pD3DDevice->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &g_pPixelShader); if (FAILED(hr)) { return hr; } //set the shader objects as active g_pImmediateContext->VSSetShader(g_pVertexShader, 0, 0); g_pImmediateContext->PSSetShader(g_pPixelShader, 0, 0); //create and set the input layout object D3D11_INPUT_ELEMENT_DESC iedesc[] = { { "POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0 }, { "COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA,0 }, }; hr = g_pD3DDevice->CreateInputLayout(iedesc, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &g_pInputLayout); if (FAILED(hr)) { return hr; } g_pImmediateContext->IASetInputLayout(g_pInputLayout); return S_OK; } // Render frame void RenderFrame(void) { // Clear the back buffer - choose a colour you like float rgba_clear_colour[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; g_pImmediateContext->ClearRenderTargetView(g_pBackBufferRTView, rgba_clear_colour); // RENDER HERE //set vertex buffer //03-01 UINT stride = sizeof(POS_COL_VERTEX); UINT offset = 0; g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); /*XMMATRIX rotation, translation, scale, world_transform; scale = XMMatrixScaling(1, 1, 2); //totate 45 degree around x axis , need to convert to radians rotation = XMMatrixRotationX(XMConvertToRadians(45.0)); translation = XMMatrixTranslation(0, 0, 5); world_transform = scale *rotation* translation;*/ cb0_values.RedAmount = 2.0f; // VERTEX red value cb0_values.scale = 1.0f; //upload the new values for the constant buffer g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer0); XMMATRIX projection, world, view; world = XMMatrixRotationX(XMConvertToRadians(rotationValue)); // the rotation degree world *= XMMatrixTranslation(0, 0, 15); // the place of the triangle projection = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0), 640.0 / 480.0, 1.0, 100.); view = XMMatrixIdentity(); cb0_values.WorldViewProjection = world * view * projection; //select which primtive type to use //03-01 g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //draw the vertex buffer to the back buffer //03-01 g_pImmediateContext->Draw(3, 0); // Display what has just been rendered g_pSwapChain->Present(0, 0); }
[ "noreply@github.com" ]
noreply@github.com
d5bb3cb34a6cc26b1f321670b86d8b1ec9dd3c12
ee174fbd6c109f3192dd6847de2f15d52f471394
/include/functions.hpp
bbc7642db715e5478d50d5b79825532b722e3a34
[ "MIT" ]
permissive
JustWhit3/SAFD-algorithm
61ad85c9f413e049125ec3492e88851d16bc0ea2
8d56a16d00f3f1bc765c830607318f501bd79778
refs/heads/main
2023-04-11T19:31:42.816513
2022-09-14T22:34:47
2022-09-14T22:34:47
445,794,125
20
5
MIT
2022-02-15T17:28:09
2022-01-08T10:56:32
C++
UTF-8
C++
false
false
2,333
hpp
//============================================ // Preprocessor directives //============================================ #ifndef FUNCTIONS_HPP #define FUNCTIONS_HPP //============================================ // Headers //============================================ //STD headers #include <complex> #include <string> #include <cmath> #include <functional> namespace safd { //============================================ // Type aliases definition //============================================ using two_param_func = std::function<double( const int&, const double& )>; using four_param_func = std::function<double( const std::string&, const int&, const int&, const double&, const double& )>; //============================================ // Global variables declaration //============================================ inline const double reciprocalPi = sqrt(1 / ( M_PI*4 ) ); //============================================ // Functions declaration //============================================ //Legendre polynomials function: extern double Leg_pol( const int& a, const double& x ); //Legendre associated function function: extern double Leg_func( const int& b, const int& a, const double& x ); //Spherical harmonics function: extern std::complex<double> sph_arm( const int& m, const int& l, const double& theta, const double& phi ); //Parsed function: extern double parsed_f( const std::string& expr, double theta, double phi ); //f(theta,phi) final function (which will be integrated), real part: extern double f_theta_phi_real( const std::string& expr, const int& m, const int& l, const double& theta, const double& phi ); //f(theta,phi) final function (which will be integrated), imaginary part: extern double f_theta_phi_imag( const std::string& expr, const int& m, const int& l, const double& theta, const double& phi ); //f_m_l coefficients representation: extern std::complex<double> f_m_l( const std::string& expr, const int& m, const int& l ); //Function used to display the final result of the main program: extern void displayer( const std::string& equation, const int& m, const int& l ); // Function used to plot the user-inserted function is input: extern void plotter( const std::string& func ); } #endif
[ "gianluca.bianco3@studio.unibo.it" ]
gianluca.bianco3@studio.unibo.it
b04c8d31c80159ca8b137336ced3757a3986620c
37f34381d6233d66318795d81533dbe73c5a1288
/src/qt/networkstyle.cpp
709e83db99da6f3dfc1759d560bedefbdd829ae4
[ "MIT" ]
permissive
alphapayofficial/alphapay
71b004be073c63140bec123982edf3ba35feb6a5
471c411ad03b20b49db4f80874a3eac21e1ca91a
refs/heads/master
2020-12-02T06:33:50.398581
2017-07-11T06:14:28
2017-07-11T06:14:28
96,849,989
0
0
null
null
null
null
UTF-8
C++
false
false
3,021
cpp
// Copyright (c) 2014-2016 The Alphapay Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "networkstyle.h" #include "guiconstants.h" #include <QApplication> static const struct { const char *networkId; const char *appName; const int iconColorHueShift; const int iconColorSaturationReduction; const char *titleAddText; } network_styles[] = { {"main", QAPP_APP_NAME_DEFAULT, 0, 0, ""}, {"test", QAPP_APP_NAME_TESTNET, 70, 30, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")}, {"regtest", QAPP_APP_NAME_TESTNET, 160, 30, "[regtest]"} }; static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles); // titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap(":/icons/bitcoin"); if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesen't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap #if QT_VERSION >= 0x040700 pixmap.convertFromImage(img); #else pixmap = QPixmap::fromImage(img); #endif } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap.scaled(QSize(256,256))); } const NetworkStyle *NetworkStyle::instantiate(const QString &networkId) { for (unsigned x=0; x<network_styles_count; ++x) { if (networkId == network_styles[x].networkId) { return new NetworkStyle( network_styles[x].appName, network_styles[x].iconColorHueShift, network_styles[x].iconColorSaturationReduction, network_styles[x].titleAddText); } } return 0; }
[ "alphapay@yandex.com" ]
alphapay@yandex.com
22f0a1171557b4cdf7af16dfbf4ed1f2c2b92a3b
b3fdba9c69aee6ea70c21feebecbb0d1066d77ff
/hphp/runtime/base/bespoke/monotype-vec.cpp
2dd98042e3992008c8a0928c706ff5571821437e
[ "Zend-2.0", "MIT", "PHP-3.01" ]
permissive
loulan97/hhvm
ca0743df7279b273fda27bab5238bd8d0b89f171
5c38f0d106eff779a151b2649bf4686e02886fd4
refs/heads/master
2023-01-24T05:00:09.842241
2020-12-03T09:15:50
2020-12-03T09:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,932
cpp
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/bespoke/monotype-vec.h" #include "hphp/runtime/base/bespoke/entry-types.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/memory-manager.h" #include "hphp/runtime/base/mixed-array-defs.h" #include "hphp/runtime/base/type-variant.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/vm/jit/irgen.h" #include "hphp/runtime/vm/jit/irgen-state.h" #include "hphp/runtime/vm/jit/ssa-tmp.h" #include "hphp/util/word-mem.h" namespace HPHP { namespace bespoke { namespace { ////////////////////////////////////////////////////////////////////////////// uint16_t packSizeIndexAndAuxBits(uint8_t idx, uint8_t aux) { return (static_cast<uint16_t>(idx) << 8) | aux; } inline constexpr uint32_t sizeClassParams2MonotypeVecCapacity( size_t index, size_t lg_grp, size_t lg_delta, size_t ndelta ) { static_assert(sizeof(MonotypeVec) <= kSizeIndex2Size[MonotypeVec::kMinSizeIndex]); if (index < MonotypeVec::kMinSizeIndex) return 0; return (((size_t{1} << lg_grp) + (ndelta << lg_delta)) - sizeof(MonotypeVec)) / sizeof(Value); } alignas(64) constexpr uint32_t kSizeIndex2MonotypeVecCapacity[] = { #define SIZE_CLASS(index, lg_grp, lg_delta, ndelta, lg_delta_lookup, ncontig) \ sizeClassParams2MonotypeVecCapacity(index, lg_grp, lg_delta, ndelta), SIZE_CLASSES #undef SIZE_CLASS }; ////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////// // Static initialization ////////////////////////////////////////////////////////////////////////////// namespace { using StaticVec = std::aligned_storage<sizeof(EmptyMonotypeVec), 16>::type; StaticVec s_emptyMonotypeVec; StaticVec s_emptyMonotypeVArray; StaticVec s_emptyMonotypeVecMarked; StaticVec s_emptyMonotypeVArrayMarked; static_assert(sizeof(DataType) == 1); constexpr LayoutIndex kBaseLayoutIndex = {1 << 9}; auto const s_monotypeVecVtable = fromArray<MonotypeVec>(); auto const s_emptyMonotypeVecVtable = fromArray<EmptyMonotypeVec>(); constexpr DataType kEmptyDataType = static_cast<DataType>(1); constexpr DataType kAbstractDataTypeMask = static_cast<DataType>(0x80); constexpr LayoutIndex getLayoutIndex(DataType type) { return LayoutIndex{uint16_t(kBaseLayoutIndex.raw + uint8_t(type))}; } constexpr LayoutIndex getEmptyLayoutIndex() { auto constexpr offset = (1 << 8); return LayoutIndex{uint16_t(kBaseLayoutIndex.raw) + offset}; } Layout::LayoutSet getAllEmptyOrMonotypeVecLayouts() { Layout::LayoutSet result; #define DT(name, value) { \ auto const type = KindOf##name; \ if (type == dt_modulo_persistence(type)) { \ result.insert(EmptyOrMonotypeVecLayout::Index(type)); \ } \ } DATATYPES #undef DT return result; } LayoutIndex getMonotypeParentLayout(DataType dt) { if (!hasPersistentFlavor(dt) || isRefcountedType(dt)) { return EmptyOrMonotypeVecLayout::Index(dt_modulo_persistence(dt)); } return MonotypeVecLayout::Index(dt_modulo_persistence(dt)); } } ////////////////////////////////////////////////////////////////////////////// // EmptyMonotypeVec ////////////////////////////////////////////////////////////////////////////// EmptyMonotypeVec* EmptyMonotypeVec::As(ArrayData* ad) { auto const ead = reinterpret_cast<EmptyMonotypeVec*>(ad); assertx(ead->checkInvariants()); return ead; } const EmptyMonotypeVec* EmptyMonotypeVec::As(const ArrayData* ad) { return EmptyMonotypeVec::As(const_cast<ArrayData*>(ad)); } EmptyMonotypeVec* EmptyMonotypeVec::GetVec(bool legacy) { auto const src = legacy ? &s_emptyMonotypeVecMarked : &s_emptyMonotypeVec; return reinterpret_cast<EmptyMonotypeVec*>(src); } EmptyMonotypeVec* EmptyMonotypeVec::GetVArray(bool legacy) { auto const src = legacy ? &s_emptyMonotypeVArrayMarked : &s_emptyMonotypeVArray; return reinterpret_cast<EmptyMonotypeVec*>(src); } bool EmptyMonotypeVec::checkInvariants() const { assertx(isStatic()); assertx(kindIsValid()); assertx(size() == 0); assertx(isVecType() || isVArray()); assertx(layoutIndex() == getEmptyLayoutIndex()); return true; } size_t EmptyMonotypeVec::HeapSize(const EmptyMonotypeVec* ead) { return sizeof(EmptyMonotypeVec); } void EmptyMonotypeVec::Scan(const EmptyMonotypeVec* ead, type_scan::Scanner&) { } ArrayData* EmptyMonotypeVec::EscalateToVanilla(const EmptyMonotypeVec* ead, const char* reason) { auto const legacy = ead->isLegacyArray(); return ead->isVecType() ? (legacy ? staticEmptyMarkedVec() : staticEmptyVec()) : (legacy ? staticEmptyMarkedVArray() : staticEmptyVArray()); } void EmptyMonotypeVec::ConvertToUncounted(EmptyMonotypeVec*, DataWalker::PointerMap*) { } void EmptyMonotypeVec::ReleaseUncounted(EmptyMonotypeVec* ead) { } void EmptyMonotypeVec::Release(EmptyMonotypeVec* ead) { // All EmptyMonotypeVecs are static, and should therefore never be released. always_assert(false); } bool EmptyMonotypeVec::IsVectorData(const EmptyMonotypeVec*) { return true; } TypedValue EmptyMonotypeVec::NvGetInt(const EmptyMonotypeVec*, int64_t) { return make_tv<KindOfUninit>(); } TypedValue EmptyMonotypeVec::NvGetStr(const EmptyMonotypeVec*, const StringData*) { return make_tv<KindOfUninit>(); } TypedValue EmptyMonotypeVec::GetPosKey(const EmptyMonotypeVec*, ssize_t) { always_assert(false); } TypedValue EmptyMonotypeVec::GetPosVal(const EmptyMonotypeVec*, ssize_t) { always_assert(false); } ssize_t EmptyMonotypeVec::GetIntPos(const EmptyMonotypeVec* ead, int64_t k) { return 0; } ssize_t EmptyMonotypeVec::GetStrPos(const EmptyMonotypeVec* ead, const StringData*) { return ead->size(); } arr_lval EmptyMonotypeVec::LvalInt(EmptyMonotypeVec* ead, int64_t k) { throwOOBArrayKeyException(k, ead); } arr_lval EmptyMonotypeVec::LvalStr(EmptyMonotypeVec* ead, StringData* k) { throwInvalidArrayKeyException(k, ead); } tv_lval EmptyMonotypeVec::ElemInt( tv_lval lval, int64_t k, bool throwOnMissing) { if (throwOnMissing) throwOOBArrayKeyException(k, lval.val().parr); return const_cast<TypedValue*>(&immutable_null_base); } tv_lval EmptyMonotypeVec::ElemStr( tv_lval lval, StringData* k, bool throwOnMissing) { if (throwOnMissing) throwInvalidArrayKeyException(k, lval.val().parr); return const_cast<TypedValue*>(&immutable_null_base); } ArrayData* EmptyMonotypeVec::SetInt(EmptyMonotypeVec* eadIn, int64_t k, TypedValue) { throwOOBArrayKeyException(k, eadIn); } ArrayData* EmptyMonotypeVec::SetStr(EmptyMonotypeVec* eadIn, StringData* k, TypedValue) { throwInvalidArrayKeyException(k, eadIn); } ArrayData* EmptyMonotypeVec::SetIntMove(EmptyMonotypeVec* eadIn, int64_t k, TypedValue) { throwOOBArrayKeyException(k, eadIn); } ArrayData* EmptyMonotypeVec::SetStrMove(EmptyMonotypeVec* eadIn, StringData* k, TypedValue) { throwInvalidArrayKeyException(k, eadIn); } ArrayData* EmptyMonotypeVec::RemoveInt(EmptyMonotypeVec* eadIn, int64_t) { return eadIn; } ArrayData* EmptyMonotypeVec::RemoveStr(EmptyMonotypeVec* eadIn, const StringData*) { return eadIn; } ssize_t EmptyMonotypeVec::IterBegin(const EmptyMonotypeVec*) { return 0; } ssize_t EmptyMonotypeVec::IterLast(const EmptyMonotypeVec*) { return 0; } ssize_t EmptyMonotypeVec::IterEnd(const EmptyMonotypeVec*) { return 0; } ssize_t EmptyMonotypeVec::IterAdvance(const EmptyMonotypeVec*, ssize_t) { return 0; } ssize_t EmptyMonotypeVec::IterRewind(const EmptyMonotypeVec*, ssize_t pos) { return 0; } ArrayData* EmptyMonotypeVec::Append(EmptyMonotypeVec* ead, TypedValue v) { auto const mad = MonotypeVec::MakeReserve( ead->m_kind, ead->isLegacyArray(), 1, type(v)); auto const res = MonotypeVec::Append(mad, v); assertx(mad == res); return res; } ArrayData* EmptyMonotypeVec::AppendMove(EmptyMonotypeVec* ead, TypedValue v) { auto const mad = MonotypeVec::MakeReserve( ead->m_kind, ead->isLegacyArray(), 1, type(v)); auto const res = MonotypeVec::AppendMove(mad, v); assertx(mad == res); return res; } ArrayData* EmptyMonotypeVec::Pop(EmptyMonotypeVec* ead, Variant& value) { value = uninit_null(); return ead; } ArrayData* EmptyMonotypeVec::ToDVArray(EmptyMonotypeVec* eadIn, bool copy) { assertx(copy); assertx(eadIn->isVecType()); return GetVArray(eadIn->isLegacyArray()); } ArrayData* EmptyMonotypeVec::ToHackArr(EmptyMonotypeVec* eadIn, bool copy) { assertx(copy); assertx(eadIn->isVArray()); return GetVec(false); } ArrayData* EmptyMonotypeVec::PreSort(EmptyMonotypeVec* ead, SortFunction sf) { always_assert(false); } ArrayData* EmptyMonotypeVec::PostSort(EmptyMonotypeVec* ead, ArrayData* vad) { always_assert(false); } ArrayData* EmptyMonotypeVec::SetLegacyArray(EmptyMonotypeVec* eadIn, bool copy, bool legacy) { if (eadIn->isVecType()) { return GetVec(legacy); } else { assertx(eadIn->isVArray()); return GetVArray(legacy); } } ////////////////////////////////////////////////////////////////////////////// // MonotypeVec ////////////////////////////////////////////////////////////////////////////// template <typename CountableFn, typename MaybeCountableFn> void MonotypeVec::forEachCountableValue(CountableFn c, MaybeCountableFn mc) { auto const dt = type(); if (isRefcountedType(dt)) { if (hasPersistentFlavor(dt)) { for (auto i = 0; i < m_size; i++) { mc(dt, valueRefUnchecked(i).pcnt); } } else { for (auto i = 0; i < m_size; i++) { c(dt, reinterpret_cast<Countable*>(valueRefUnchecked(i).pcnt)); } } } } void MonotypeVec::decRefValues() { forEachCountableValue( [&](auto t, auto v) { if (v->decReleaseCheck()) destructorForType(t)(v); }, [&](auto t, auto v) { if (v->decReleaseCheck()) destructorForType(t)(v); } ); } void MonotypeVec::incRefValues() { forEachCountableValue( [&](auto t, auto v) { v->incRefCount(); }, [&](auto t, auto v) { v->incRefCount(); } ); } template <bool Static> MonotypeVec* MonotypeVec::MakeReserve( HeaderKind hk, bool legacy, uint32_t capacity, DataType dt) { auto const bytes = sizeof(MonotypeVec) + capacity * sizeof(Value); auto const index = std::max(MemoryManager::size2Index(bytes), kMinSizeIndex); auto const alloc = [&]{ if (!Static) return tl_heap->objMallocIndex(index); auto const size = MemoryManager::sizeIndex2Size(index); return RO::EvalLowStaticArrays ? low_malloc(size) : uncounted_malloc(size); }(); auto const mad = static_cast<MonotypeVec*>(alloc); auto const aux = packSizeIndexAndAuxBits( index, legacy ? ArrayData::kLegacyArray : 0); mad->initHeader_16(hk, OneReference, aux); mad->setLayoutIndex(getLayoutIndex(dt)); mad->m_size = 0; assertx(mad->checkInvariants()); return mad; } MonotypeVec* MonotypeVec::MakeFromVanilla(ArrayData* ad, DataType dt) { assertx(ad->hasVanillaPackedLayout()); auto const kind = ad->isVArray() ? HeaderKind::BespokeVArray : HeaderKind::BespokeVec; auto result = ad->isStatic() ? MakeReserve<true>(kind, ad->isLegacyArray(), ad->size(), dt) : MakeReserve<false>(kind, ad->isLegacyArray(), ad->size(), dt); PackedArray::IterateVNoInc(ad, [&](auto v) { auto const next = Append(result, v); assertx(result == next); result = As(next); }); if (ad->isStatic()) { auto const aux = packSizeIndexAndAuxBits( result->sizeIndex(), result->auxBits()); result->initHeader_16(kind, StaticValue, aux); } assertx(result->checkInvariants()); return result; } Value* MonotypeVec::rawData() { return reinterpret_cast<Value*>(this + 1); } const Value* MonotypeVec::rawData() const { return const_cast<MonotypeVec*>(this)->rawData(); } Value& MonotypeVec::valueRefUnchecked(uint32_t idx) { return rawData()[idx]; } const Value& MonotypeVec::valueRefUnchecked(uint32_t idx) const { return const_cast<MonotypeVec*>(this)->valueRefUnchecked(idx); } TypedValue MonotypeVec::typedValueUnchecked(uint32_t idx) const { return { valueRefUnchecked(idx), type() }; } uint8_t MonotypeVec::sizeIndex() const { return m_aux16 >> 8; } size_t MonotypeVec::capacity() const { return kSizeIndex2MonotypeVecCapacity[sizeIndex()]; } MonotypeVec* MonotypeVec::copyHelper(uint8_t newSizeIndex, bool incRef) const { auto const mad = static_cast<MonotypeVec*>(tl_heap->objMallocIndex(newSizeIndex)); // Copy elements 16 bytes at a time. We may copy an extra value this way, // but our heap allocations are in multiples of 16 bytes, so it is safe. assertx(HeapSize(this) % 16 == 0); auto const bytes = sizeof(MonotypeVec) + m_size * sizeof(Value); memcpy16_inline(mad, this, size_t(bytes + 15) & ~size_t(15)); mad->initHeader_16(m_kind, OneReference, packSizeIndexAndAuxBits(newSizeIndex, auxBits())); if (incRef) mad->incRefValues(); return mad; } MonotypeVec* MonotypeVec::copy() const { return copyHelper(sizeIndex(), true); } MonotypeVec* MonotypeVec::grow() { auto const cow = cowCheck(); auto const mad = copyHelper(sizeIndex() + kSizeClassesPerDoubling, cow); if (!cow) m_size = 0; return mad; } DataType MonotypeVec::type() const { return DataType(int8_t(m_extra_hi16 & 0xff)); } MonotypeVec* MonotypeVec::prepareForInsert() { if (m_size == capacity()) return grow(); if (cowCheck()) return copy(); return this; } /* * Escalates the MonotypeVec to a vanilla PackedArray with the contents of the * current array and the specified capacity. The new array will match the * MonotypeVec in size, contents, and legacy bit status. */ ArrayData* MonotypeVec::escalateWithCapacity(size_t capacity) const { assertx(capacity >= size()); auto const ad = isVecType() ? PackedArray::MakeReserveVec(capacity) : PackedArray::MakeReserveVArray(capacity); for (uint32_t i = 0; i < size(); i++) { auto const tv = typedValueUnchecked(i); tvCopy(tv, PackedArray::LvalUncheckedInt(ad, i)); tvIncRefGen(tv); } ad->setLegacyArrayInPlace(isLegacyArray()); ad->m_size = size(); return ad; } bool MonotypeVec::checkInvariants() const { assertx(kindIsValid()); assertx(isVecType() || isVArray()); assertx(size() <= capacity()); assertx(sizeIndex() >= kMinSizeIndex); assertx(layoutIndex() != getEmptyLayoutIndex()); assertx(layoutIndex() == getLayoutIndex(type())); assertx(isRealType(type())); if (size() > 0) { assertx(tvIsPlausible(typedValueUnchecked(0))); } return true; } MonotypeVec* MonotypeVec::As(ArrayData* ad) { auto const mad = reinterpret_cast<MonotypeVec*>(ad); assertx(mad->checkInvariants()); return mad; } const MonotypeVec* MonotypeVec::As(const ArrayData* ad) { auto const mad = reinterpret_cast<const MonotypeVec*>(ad); assertx(mad->checkInvariants()); return mad; } size_t MonotypeVec::HeapSize(const MonotypeVec* mad) { return MemoryManager::sizeIndex2Size(mad->sizeIndex()); } void MonotypeVec::Scan(const MonotypeVec* mad, type_scan::Scanner& scan) { if (isRefcountedType(mad->type())) { static_assert(sizeof(MaybeCountable*) == sizeof(Value)); scan.scan(mad->rawData()->pcnt, mad->size() * sizeof(Value)); } } ArrayData* MonotypeVec::EscalateToVanilla(const MonotypeVec* mad, const char* reason) { return mad->escalateWithCapacity(mad->size()); } void MonotypeVec::ConvertToUncounted(MonotypeVec* madIn, DataWalker::PointerMap* seen) { auto const oldType = madIn->type(); for (uint32_t i = 0; i < madIn->size(); i++) { DataType dt = oldType; auto const lval = tv_lval(&dt, &madIn->rawData()[i]); ConvertTvToUncounted(lval, seen); assertx(equivDataTypes(dt, madIn->type())); } auto const newType = hasPersistentFlavor(oldType) ? dt_with_persistence(oldType) : oldType; madIn->setLayoutIndex(getLayoutIndex(newType)); } void MonotypeVec::ReleaseUncounted(MonotypeVec* mad) { for (uint32_t i = 0; i < mad->size(); i++) { auto tv = mad->typedValueUnchecked(i); ReleaseUncountedTv(&tv); } } void MonotypeVec::Release(MonotypeVec* mad) { mad->fixCountForRelease(); assertx(mad->isRefCounted()); assertx(mad->hasExactlyOneRef()); mad->decRefValues(); tl_heap->objFreeIndex(mad, mad->sizeIndex()); } bool MonotypeVec::IsVectorData(const MonotypeVec* mad) { return true; } TypedValue MonotypeVec::NvGetInt(const MonotypeVec* mad, int64_t k) { if (size_t(k) >= mad->size()) return make_tv<KindOfUninit>(); return mad->typedValueUnchecked(k); } TypedValue MonotypeVec::NvGetStr(const MonotypeVec* mad, const StringData*) { return make_tv<KindOfUninit>(); } TypedValue MonotypeVec::GetPosKey(const MonotypeVec* mad, ssize_t pos) { assertx(pos < mad->size()); return make_tv<KindOfInt64>(pos); } TypedValue MonotypeVec::GetPosVal(const MonotypeVec* mad, ssize_t pos) { assertx(size_t(pos) < mad->size()); return mad->typedValueUnchecked(pos); } ssize_t MonotypeVec::GetIntPos(const MonotypeVec* mad, int64_t k) { return LIKELY(size_t(k) < mad->size()) ? k : mad->size(); } ssize_t MonotypeVec::GetStrPos(const MonotypeVec* mad, const StringData*) { return mad->size(); } arr_lval MonotypeVec::LvalInt(MonotypeVec* mad, int64_t k) { auto const vad = EscalateToVanilla(mad, __func__); auto const res = vad->lval(k); assertx(res.arr == vad); return res; } arr_lval MonotypeVec::LvalStr(MonotypeVec* mad, StringData* k) { throwInvalidArrayKeyException(k, mad); } arr_lval MonotypeVec::elemImpl(int64_t k, bool throwOnMissing) { if (size_t(k) >= size()) { if (throwOnMissing) throwOOBArrayKeyException(k, this); return {this, const_cast<TypedValue*>(&immutable_null_base)}; } auto const dt = type(); if (dt == KindOfClsMeth) return LvalInt(this, k); auto const cow = cowCheck(); auto const mad = cow ? copy() : this; mad->setLayoutIndex(getLayoutIndex(dt_modulo_persistence(dt))); static_assert(folly::kIsLittleEndian); auto const type_ptr = reinterpret_cast<DataType*>(&mad->m_extra_hi16); assertx(*type_ptr == mad->type()); return arr_lval{mad, type_ptr, &mad->valueRefUnchecked(k)}; } tv_lval MonotypeVec::ElemInt(tv_lval lvalIn, int64_t k, bool throwOnMissing) { auto const madIn = As(lvalIn.val().parr); auto const lval = madIn->elemImpl(k, throwOnMissing); if (lval.arr != madIn) { lvalIn.type() = dt_with_rc(lvalIn.type()); lvalIn.val().parr = lval.arr; if (madIn->decReleaseCheck()) Release(madIn); } return lval; } tv_lval MonotypeVec::ElemStr(tv_lval lval, StringData* k, bool throwOnMissing) { if (throwOnMissing) throwInvalidArrayKeyException(k, lval.val().parr); return const_cast<TypedValue*>(&immutable_null_base); } template <bool Move> ArrayData* MonotypeVec::setIntImpl(int64_t k, TypedValue v) { assertx(cowCheck() || notCyclic(v)); if (UNLIKELY(size_t(k) >= size())) { throwOOBArrayKeyException(k, this); } auto const dt = type(); if (!equivDataTypes(dt, v.type())) { auto const vad = EscalateToVanilla(this, __func__); auto const res = vad->set(k, v); assertx(vad == res); if constexpr (Move) { if (decReleaseCheck()) Release(this); tvDecRefGen(v); } return res; } if constexpr (!Move) { tvIncRefGen(v); } auto const cow = cowCheck(); auto const mad = cow ? copy() : this; if (dt != v.type()) { mad->setLayoutIndex(getLayoutIndex(dt_with_rc(dt))); } mad->valueRefUnchecked(k) = val(v); if constexpr (Move) { if (cow && decReleaseCheck()) Release(this); } return mad; } ArrayData* MonotypeVec::SetInt(MonotypeVec* madIn, int64_t k, TypedValue v) { return madIn->setIntImpl<false>(k, v); } ArrayData* MonotypeVec::SetIntMove(MonotypeVec* madIn, int64_t k, TypedValue v) { return madIn->setIntImpl<true>(k, v); } ArrayData* MonotypeVec::SetStr(MonotypeVec* madIn, StringData* k, TypedValue) { throwInvalidArrayKeyException(k, madIn); } ArrayData* MonotypeVec::SetStrMove(MonotypeVec* madIn, StringData* k, TypedValue) { throwInvalidArrayKeyException(k, madIn); } ArrayData* MonotypeVec::RemoveInt(MonotypeVec* madIn, int64_t k) { if (UNLIKELY(size_t(k) >= madIn->m_size)) return madIn; if (LIKELY(size_t(k) + 1 == madIn->m_size)) { auto const mad = madIn->cowCheck() ? madIn->copy() : madIn; mad->m_size--; tvDecRefGen(mad->typedValueUnchecked(mad->m_size)); return mad; } if (madIn->isVecType()) { throwVecUnsetException(); } else { throwVarrayUnsetException(); } } ArrayData* MonotypeVec::RemoveStr(MonotypeVec* madIn, const StringData*) { return madIn; } ssize_t MonotypeVec::IterBegin(const MonotypeVec* mad) { return 0; } ssize_t MonotypeVec::IterLast(const MonotypeVec* mad) { return mad->size() > 0 ? mad->size() - 1 : 0; } ssize_t MonotypeVec::IterEnd(const MonotypeVec* mad) { return mad->size(); } ssize_t MonotypeVec::IterAdvance(const MonotypeVec* mad, ssize_t pos) { return pos < mad->size() ? pos + 1 : pos; } ssize_t MonotypeVec::IterRewind(const MonotypeVec* mad, ssize_t pos) { return pos > 0 ? pos - 1 : mad->size(); } template <bool Move> ArrayData* MonotypeVec::appendImpl(TypedValue v) { auto const dt = type(); if (!equivDataTypes(dt, v.type())) { auto const ad = escalateWithCapacity(size() + 1); auto const result = PackedArray::Append(ad, v); assertx(ad == result); return result; } auto const mad = prepareForInsert(); if (dt != v.type()) { mad->setLayoutIndex(getLayoutIndex(dt_with_rc(dt))); } mad->valueRefUnchecked(mad->m_size++) = val(v); if constexpr (Move) { if (mad != this && decReleaseCheck()) Release(this); } else { tvIncRefGen(v); } return mad; } ArrayData* MonotypeVec::Append(MonotypeVec* madIn, TypedValue v) { return madIn->appendImpl<false>(v); } ArrayData* MonotypeVec::AppendMove(MonotypeVec* madIn, TypedValue v) { return madIn->appendImpl<true>(v); } ArrayData* MonotypeVec::Pop(MonotypeVec* madIn, Variant& value) { auto const mad = madIn->cowCheck() ? madIn->copy() : madIn; if (UNLIKELY(mad->m_size) == 0) { value = uninit_null(); return mad; } auto const newSize = mad->size() - 1; TypedValue tv; tv.m_data = mad->valueRefUnchecked(newSize); tv.m_type = mad->type(); value = Variant::wrap(tv); tvDecRefGen(tv); mad->m_size = newSize; return mad; } ArrayData* MonotypeVec::ToDVArray(MonotypeVec* madIn, bool copy) { if (madIn->isVArray()) return madIn; auto const mad = copy ? madIn->copy() : madIn; mad->m_kind = HeaderKind::BespokeVArray; assertx(mad->checkInvariants()); return mad; } ArrayData* MonotypeVec::ToHackArr(MonotypeVec* madIn, bool copy) { if (madIn->isVecType()) return madIn; auto const mad = copy ? madIn->copy() : madIn; mad->setLegacyArrayInPlace(false); mad->m_kind = HeaderKind::BespokeVec; assertx(mad->checkInvariants()); return mad; } ArrayData* MonotypeVec::PreSort(MonotypeVec* mad, SortFunction sf) { return mad->escalateWithCapacity(mad->size()); } ArrayData* MonotypeVec::PostSort(MonotypeVec* mad, ArrayData* vad) { auto const result = MakeFromVanilla(vad, mad->type()); PackedArray::Release(vad); return result; } ArrayData* MonotypeVec::SetLegacyArray(MonotypeVec* madIn, bool copy, bool legacy) { auto const mad = copy ? madIn->copy() : madIn; mad->setLegacyArrayInPlace(legacy); return mad; } ////////////////////////////////////////////////////////////////////////////// // Layout creation and usage API ////////////////////////////////////////////////////////////////////////////// void MonotypeVec::InitializeLayouts() { auto const base = Layout::ReserveIndices(1 << 9); always_assert(base == kBaseLayoutIndex); new TopMonotypeVecLayout(); #define DT(name, value) { \ auto const type = KindOf##name; \ if (type == dt_modulo_persistence(type)) { \ new EmptyOrMonotypeVecLayout(type); \ } \ } DATATYPES #undef DT new EmptyMonotypeVecLayout(); // Create all the potentially internal concrete layouts first #define DT(name, value) { \ auto const type = KindOf##name; \ if (type == dt_modulo_persistence(type)) { \ new MonotypeVecLayout(type); \ } \ } DATATYPES #undef DT #define DT(name, value) { \ auto const type = KindOf##name; \ if (type != dt_modulo_persistence(type)) { \ new MonotypeVecLayout(type); \ } \ } DATATYPES #undef DT auto const init = [&](EmptyMonotypeVec* ead, HeaderKind hk, bool legacy) { auto const aux = packSizeIndexAndAuxBits(0, legacy ? ArrayData::kLegacyArray : 0); ead->initHeader_16(hk, StaticValue, aux); ead->m_size = 0; ead->setLayoutIndex(getEmptyLayoutIndex()); assertx(ead->checkInvariants()); }; init(EmptyMonotypeVec::GetVec(false), HeaderKind::BespokeVec, false); init(EmptyMonotypeVec::GetVArray(false), HeaderKind::BespokeVArray, false); init(EmptyMonotypeVec::GetVec(true), HeaderKind::BespokeVec, true); init(EmptyMonotypeVec::GetVArray(true), HeaderKind::BespokeVArray, true); } TopMonotypeVecLayout::TopMonotypeVecLayout() : AbstractLayout( Index(), "MonotypeVec<Top>", {AbstractLayout::GetBespokeTopIndex()}) {} LayoutIndex TopMonotypeVecLayout::Index() { auto const t = int8_t(kEmptyDataType) ^ int8_t(kAbstractDataTypeMask); return MonotypeVecLayout::Index(static_cast<DataType>(t)); } EmptyOrMonotypeVecLayout::EmptyOrMonotypeVecLayout(DataType type) : AbstractLayout( Index(type), folly::sformat("MonotypeVec<Empty|{}>", tname(type)), {TopMonotypeVecLayout::Index()}), m_fixedType(type) {} LayoutIndex EmptyOrMonotypeVecLayout::Index(DataType type) { assertx(type == dt_modulo_persistence(type)); auto const t = int8_t(type) ^ int8_t(kAbstractDataTypeMask); return MonotypeVecLayout::Index(static_cast<DataType>(t)); } EmptyMonotypeVecLayout::EmptyMonotypeVecLayout() : ConcreteLayout( Index(), "MonotypeVec<Empty>", &s_emptyMonotypeVecVtable, {getAllEmptyOrMonotypeVecLayouts()}) {} LayoutIndex EmptyMonotypeVecLayout::Index() { return getEmptyLayoutIndex(); } MonotypeVecLayout::MonotypeVecLayout(DataType type) : ConcreteLayout( Index(type), folly::sformat("MonotypeVec<{}>", tname(type)), &s_monotypeVecVtable, {getMonotypeParentLayout(type)}) , m_fixedType(type) {} LayoutIndex MonotypeVecLayout::Index(DataType type) { return getLayoutIndex(type); } bool isMonotypeVecLayout(LayoutIndex index) { return kBaseLayoutIndex.raw <= index.raw && index.raw < 2 * kBaseLayoutIndex.raw; } ////////////////////////////////////////////////////////////////////////////// // JIT implementations ////////////////////////////////////////////////////////////////////////////// using namespace jit; using namespace jit::irgen; namespace { SSATmp* emitMonotypeGet(IRGS& env, SSATmp* arr, SSATmp* key, Block* taken, const MonotypeVecLayout* nonEmptyLayout) { assertx(arr->type().subtypeOfAny(TVec, TVArr)); auto const sz = gen(env, Count, arr); auto const sf = gen(env, LtInt, key, sz); gen(env, JmpZero, taken, sf); if (nonEmptyLayout) { auto const nonEmptyType = arr->type().narrowToLayout(ArrayLayout(nonEmptyLayout->index())); gen(env, AssertType, nonEmptyType, arr); } auto const retType = nonEmptyLayout ? Type(nonEmptyLayout->m_fixedType) : TInitCell; return gen(env, LdMonotypeVecElem, retType, arr, key); } } SSATmp* TopMonotypeVecLayout::emitGet( IRGS& env, SSATmp* arr, SSATmp* key, Block* taken) const { return emitMonotypeGet(env, arr, key, taken, nullptr); } SSATmp* MonotypeVecLayout::emitGet( IRGS& env, SSATmp* arr, SSATmp* key, Block* taken) const { return emitMonotypeGet(env, arr, key, taken, this); } SSATmp* EmptyOrMonotypeVecLayout::emitGet( IRGS& env, SSATmp* arr, SSATmp* key, Block* taken) const { return emitMonotypeGet(env, arr, key, taken, getNonEmptyLayout()); } SSATmp* EmptyMonotypeVecLayout::emitGet( IRGS& env, SSATmp* arr, SSATmp* key, Block* taken) const { return gen(env, Jmp, taken); } }}
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
e7c5b4fce053e9086a6c7ac625d2890b842d6962
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-datasync/include/aws/datasync/model/DescribeLocationHdfsResult.h
9de291a63c2ddae4d18aac4431997cef6f5cc28e
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
17,963
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/datasync/DataSync_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/datasync/model/QopConfiguration.h> #include <aws/datasync/model/HdfsAuthenticationType.h> #include <aws/core/utils/DateTime.h> #include <aws/datasync/model/HdfsNameNode.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace DataSync { namespace Model { class DescribeLocationHdfsResult { public: AWS_DATASYNC_API DescribeLocationHdfsResult(); AWS_DATASYNC_API DescribeLocationHdfsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AWS_DATASYNC_API DescribeLocationHdfsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The ARN of the HDFS cluster location.</p> */ inline const Aws::String& GetLocationArn() const{ return m_locationArn; } /** * <p>The ARN of the HDFS cluster location.</p> */ inline void SetLocationArn(const Aws::String& value) { m_locationArn = value; } /** * <p>The ARN of the HDFS cluster location.</p> */ inline void SetLocationArn(Aws::String&& value) { m_locationArn = std::move(value); } /** * <p>The ARN of the HDFS cluster location.</p> */ inline void SetLocationArn(const char* value) { m_locationArn.assign(value); } /** * <p>The ARN of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationArn(const Aws::String& value) { SetLocationArn(value); return *this;} /** * <p>The ARN of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationArn(Aws::String&& value) { SetLocationArn(std::move(value)); return *this;} /** * <p>The ARN of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationArn(const char* value) { SetLocationArn(value); return *this;} /** * <p>The URI of the HDFS cluster location.</p> */ inline const Aws::String& GetLocationUri() const{ return m_locationUri; } /** * <p>The URI of the HDFS cluster location.</p> */ inline void SetLocationUri(const Aws::String& value) { m_locationUri = value; } /** * <p>The URI of the HDFS cluster location.</p> */ inline void SetLocationUri(Aws::String&& value) { m_locationUri = std::move(value); } /** * <p>The URI of the HDFS cluster location.</p> */ inline void SetLocationUri(const char* value) { m_locationUri.assign(value); } /** * <p>The URI of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationUri(const Aws::String& value) { SetLocationUri(value); return *this;} /** * <p>The URI of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationUri(Aws::String&& value) { SetLocationUri(std::move(value)); return *this;} /** * <p>The URI of the HDFS cluster location.</p> */ inline DescribeLocationHdfsResult& WithLocationUri(const char* value) { SetLocationUri(value); return *this;} /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline const Aws::Vector<HdfsNameNode>& GetNameNodes() const{ return m_nameNodes; } /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline void SetNameNodes(const Aws::Vector<HdfsNameNode>& value) { m_nameNodes = value; } /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline void SetNameNodes(Aws::Vector<HdfsNameNode>&& value) { m_nameNodes = std::move(value); } /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline DescribeLocationHdfsResult& WithNameNodes(const Aws::Vector<HdfsNameNode>& value) { SetNameNodes(value); return *this;} /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline DescribeLocationHdfsResult& WithNameNodes(Aws::Vector<HdfsNameNode>&& value) { SetNameNodes(std::move(value)); return *this;} /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline DescribeLocationHdfsResult& AddNameNodes(const HdfsNameNode& value) { m_nameNodes.push_back(value); return *this; } /** * <p>The NameNode that manage the HDFS namespace. </p> */ inline DescribeLocationHdfsResult& AddNameNodes(HdfsNameNode&& value) { m_nameNodes.push_back(std::move(value)); return *this; } /** * <p>The size of the data blocks to write into the HDFS cluster. </p> */ inline int GetBlockSize() const{ return m_blockSize; } /** * <p>The size of the data blocks to write into the HDFS cluster. </p> */ inline void SetBlockSize(int value) { m_blockSize = value; } /** * <p>The size of the data blocks to write into the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& WithBlockSize(int value) { SetBlockSize(value); return *this;} /** * <p>The number of DataNodes to replicate the data to when writing to the HDFS * cluster. </p> */ inline int GetReplicationFactor() const{ return m_replicationFactor; } /** * <p>The number of DataNodes to replicate the data to when writing to the HDFS * cluster. </p> */ inline void SetReplicationFactor(int value) { m_replicationFactor = value; } /** * <p>The number of DataNodes to replicate the data to when writing to the HDFS * cluster. </p> */ inline DescribeLocationHdfsResult& WithReplicationFactor(int value) { SetReplicationFactor(value); return *this;} /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline const Aws::String& GetKmsKeyProviderUri() const{ return m_kmsKeyProviderUri; } /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline void SetKmsKeyProviderUri(const Aws::String& value) { m_kmsKeyProviderUri = value; } /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline void SetKmsKeyProviderUri(Aws::String&& value) { m_kmsKeyProviderUri = std::move(value); } /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline void SetKmsKeyProviderUri(const char* value) { m_kmsKeyProviderUri.assign(value); } /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline DescribeLocationHdfsResult& WithKmsKeyProviderUri(const Aws::String& value) { SetKmsKeyProviderUri(value); return *this;} /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline DescribeLocationHdfsResult& WithKmsKeyProviderUri(Aws::String&& value) { SetKmsKeyProviderUri(std::move(value)); return *this;} /** * <p> The URI of the HDFS cluster's Key Management Server (KMS). </p> */ inline DescribeLocationHdfsResult& WithKmsKeyProviderUri(const char* value) { SetKmsKeyProviderUri(value); return *this;} /** * <p>The Quality of Protection (QOP) configuration specifies the Remote Procedure * Call (RPC) and data transfer protection settings configured on the Hadoop * Distributed File System (HDFS) cluster. </p> */ inline const QopConfiguration& GetQopConfiguration() const{ return m_qopConfiguration; } /** * <p>The Quality of Protection (QOP) configuration specifies the Remote Procedure * Call (RPC) and data transfer protection settings configured on the Hadoop * Distributed File System (HDFS) cluster. </p> */ inline void SetQopConfiguration(const QopConfiguration& value) { m_qopConfiguration = value; } /** * <p>The Quality of Protection (QOP) configuration specifies the Remote Procedure * Call (RPC) and data transfer protection settings configured on the Hadoop * Distributed File System (HDFS) cluster. </p> */ inline void SetQopConfiguration(QopConfiguration&& value) { m_qopConfiguration = std::move(value); } /** * <p>The Quality of Protection (QOP) configuration specifies the Remote Procedure * Call (RPC) and data transfer protection settings configured on the Hadoop * Distributed File System (HDFS) cluster. </p> */ inline DescribeLocationHdfsResult& WithQopConfiguration(const QopConfiguration& value) { SetQopConfiguration(value); return *this;} /** * <p>The Quality of Protection (QOP) configuration specifies the Remote Procedure * Call (RPC) and data transfer protection settings configured on the Hadoop * Distributed File System (HDFS) cluster. </p> */ inline DescribeLocationHdfsResult& WithQopConfiguration(QopConfiguration&& value) { SetQopConfiguration(std::move(value)); return *this;} /** * <p>The type of authentication used to determine the identity of the user. </p> */ inline const HdfsAuthenticationType& GetAuthenticationType() const{ return m_authenticationType; } /** * <p>The type of authentication used to determine the identity of the user. </p> */ inline void SetAuthenticationType(const HdfsAuthenticationType& value) { m_authenticationType = value; } /** * <p>The type of authentication used to determine the identity of the user. </p> */ inline void SetAuthenticationType(HdfsAuthenticationType&& value) { m_authenticationType = std::move(value); } /** * <p>The type of authentication used to determine the identity of the user. </p> */ inline DescribeLocationHdfsResult& WithAuthenticationType(const HdfsAuthenticationType& value) { SetAuthenticationType(value); return *this;} /** * <p>The type of authentication used to determine the identity of the user. </p> */ inline DescribeLocationHdfsResult& WithAuthenticationType(HdfsAuthenticationType&& value) { SetAuthenticationType(std::move(value)); return *this;} /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline const Aws::String& GetSimpleUser() const{ return m_simpleUser; } /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline void SetSimpleUser(const Aws::String& value) { m_simpleUser = value; } /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline void SetSimpleUser(Aws::String&& value) { m_simpleUser = std::move(value); } /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline void SetSimpleUser(const char* value) { m_simpleUser.assign(value); } /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline DescribeLocationHdfsResult& WithSimpleUser(const Aws::String& value) { SetSimpleUser(value); return *this;} /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline DescribeLocationHdfsResult& WithSimpleUser(Aws::String&& value) { SetSimpleUser(std::move(value)); return *this;} /** * <p>The user name used to identify the client on the host operating system. This * parameter is used if the <code>AuthenticationType</code> is defined as * <code>SIMPLE</code>.</p> */ inline DescribeLocationHdfsResult& WithSimpleUser(const char* value) { SetSimpleUser(value); return *this;} /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline const Aws::String& GetKerberosPrincipal() const{ return m_kerberosPrincipal; } /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline void SetKerberosPrincipal(const Aws::String& value) { m_kerberosPrincipal = value; } /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline void SetKerberosPrincipal(Aws::String&& value) { m_kerberosPrincipal = std::move(value); } /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline void SetKerberosPrincipal(const char* value) { m_kerberosPrincipal.assign(value); } /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline DescribeLocationHdfsResult& WithKerberosPrincipal(const Aws::String& value) { SetKerberosPrincipal(value); return *this;} /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline DescribeLocationHdfsResult& WithKerberosPrincipal(Aws::String&& value) { SetKerberosPrincipal(std::move(value)); return *this;} /** * <p>The Kerberos principal with access to the files and folders on the HDFS * cluster. This parameter is used if the <code>AuthenticationType</code> is * defined as <code>KERBEROS</code>.</p> */ inline DescribeLocationHdfsResult& WithKerberosPrincipal(const char* value) { SetKerberosPrincipal(value); return *this;} /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline const Aws::Vector<Aws::String>& GetAgentArns() const{ return m_agentArns; } /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline void SetAgentArns(const Aws::Vector<Aws::String>& value) { m_agentArns = value; } /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline void SetAgentArns(Aws::Vector<Aws::String>&& value) { m_agentArns = std::move(value); } /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& WithAgentArns(const Aws::Vector<Aws::String>& value) { SetAgentArns(value); return *this;} /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& WithAgentArns(Aws::Vector<Aws::String>&& value) { SetAgentArns(std::move(value)); return *this;} /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& AddAgentArns(const Aws::String& value) { m_agentArns.push_back(value); return *this; } /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& AddAgentArns(Aws::String&& value) { m_agentArns.push_back(std::move(value)); return *this; } /** * <p>The ARNs of the agents that are used to connect to the HDFS cluster. </p> */ inline DescribeLocationHdfsResult& AddAgentArns(const char* value) { m_agentArns.push_back(value); return *this; } /** * <p>The time that the HDFS location was created.</p> */ inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; } /** * <p>The time that the HDFS location was created.</p> */ inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTime = value; } /** * <p>The time that the HDFS location was created.</p> */ inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTime = std::move(value); } /** * <p>The time that the HDFS location was created.</p> */ inline DescribeLocationHdfsResult& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;} /** * <p>The time that the HDFS location was created.</p> */ inline DescribeLocationHdfsResult& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;} private: Aws::String m_locationArn; Aws::String m_locationUri; Aws::Vector<HdfsNameNode> m_nameNodes; int m_blockSize; int m_replicationFactor; Aws::String m_kmsKeyProviderUri; QopConfiguration m_qopConfiguration; HdfsAuthenticationType m_authenticationType; Aws::String m_simpleUser; Aws::String m_kerberosPrincipal; Aws::Vector<Aws::String> m_agentArns; Aws::Utils::DateTime m_creationTime; }; } // namespace Model } // namespace DataSync } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
fd7d8e9e052daddc29d5ef3393bdbfbe9fc9b258
e40d6030b1b618f80a16fc7ce99d67a36692b693
/Matrix-Clock.ino
0397b51788204b124ca209c9120da5228fe6a11b
[]
no_license
sam-e/32x8-Matrix-Clock
0a82a416648a565012e87e22a752a29840a0e5a3
49798fba5727ae1450f68ac768bd04efdfbabb94
refs/heads/main
2023-07-14T20:12:31.683161
2021-08-23T11:48:15
2021-08-23T11:48:15
361,559,474
0
0
null
null
null
null
UTF-8
C++
false
false
7,628
ino
#include <Adafruit_GFX.h> #include <WiFi.h> #include <TM1640.h> #include <TM16xxMatrixGFX.h> #include <ezTime.h> //--My libraries #include <Charconvert.h> #include "MatrixFonts.h" #include "Credentials.h" TM1640 module(23, 22); // For ESP8266/WeMos D1-mini: DIN=D7/13/MOSI, CLK=D5/14/SCK TM1640 module2(23, 21); TM16xx * modules[]={&module,&module2}; #define MYTIMEZONE "Australia/Brisbane" #define MATRIX_NUMCOLUMNS 16 #define MATRIX_NUMROWS 8 TM16xxMatrixGFX matrix(modules, MATRIX_NUMCOLUMNS, MATRIX_NUMROWS, 2, 1); //--Wifi credentials from Credentials.h const char *ssid = SID; const char *password = PW; Timezone myTZ; String lastDisplayedTime = ""; String lastDisplayedAmPm = ""; const int OFFSET_M0 = 26; const int OFFSET_M1 = 19; const int OFFSET_H0 = 9; const int OFFSET_H1 = 2; bool transitionFlag = false; bool isDots = true; bool fattyFont = false; int m0 = 0; int m1 = 0; int h0 = 0; int h1 = 0; int secs; int millisecs; int myMinutes; long interval = 1000; long previousMillis = 0; void setup() { Serial.begin(115200); //--Attempt to connect to Wifi network: Serial.print("Connecting Wifi: "); Serial.println(ssid); //--Set WiFi to station mode and disconnect from an AP if it was Previously WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //--setup matrix panels matrix.setIntensity(7); // Use a value between 0 and 7 for brightness matrix.setRotation(1); matrix.setMirror(true); // set X-mirror true when using the WeMOS D1 mini Matrix LED Shield (X0=Seg1/R1, Y0=GRD1/C1) matrix.fillScreen(LOW); matrix.write(); //--Setup EZ Time setDebug(INFO); waitForSync(); Serial.println(); Serial.println("UTC: " + UTC.dateTime()); myTZ.setLocation(F(MYTIMEZONE)); Serial.print(F("Time in your set timezone: ")); Serial.println(myTZ.dateTime()); } void clearDigit(int index) { int xOffset; //--Get which digit to clear switch (index) { case 0: xOffset = OFFSET_M0; break; case 1: xOffset = OFFSET_M1; break; case 2: xOffset = OFFSET_H0; break; case 3: xOffset = OFFSET_H1; break; } //--clear the digit for (int y = 0; y < 8; y++) { for (int x = 0; x < 6; x++) { matrix.drawPixel(x+xOffset, y, LOW); } } } void writeDigit(int index, int digit) { int xOffset; //--Get which digit to clear switch (index) { case 0: xOffset = OFFSET_M0; break; case 1: xOffset = OFFSET_M1; break; case 2: xOffset = OFFSET_H0; break; case 3: xOffset = OFFSET_H1; break; } //write first mins digit for (int y = 0; y < 8; y++) { for (int x = 0; x < 6; x++) { if (fattyFont) { if(fatFont[digit][y][x]) { matrix.drawPixel(x+xOffset, y, HIGH); } } else { if(skinnyFont[digit][y][x]) { matrix.drawPixel(x+xOffset, y, HIGH); } } } } } void transition(int index, int digit) { int offScreen = -8; int xOffset; int nextDig = 0; //--Get which digit to clear switch (index) { case 0: xOffset = OFFSET_M0; if (digit == 9) { nextDig = 0; } else nextDig = digit + 1; break; case 1: xOffset = OFFSET_M1; if (digit == 5) { nextDig = 0; } else nextDig = digit + 1; break; case 2: xOffset = OFFSET_H0; if (digit == 9) { nextDig = 0; } else nextDig = digit + 1; break; case 3: xOffset = OFFSET_H1; if (digit == 2) { nextDig = 0; } else nextDig = digit + 1; break; } for (int i=0; i < 16; i++) { //--Clear the screen for the next write clearDigit(index); //--Start displaying the digit offscreen //--Increment by one until the last write //--This will sample falling numbers if (offScreen<0) { offScreen++; } for (int y = 0; y < 8; y++) { for (int x = 0; x < 6; x++) { if(fattyFont) { if(fatFont[nextDig][y][x]) { matrix.drawPixel(x+xOffset, y+offScreen, HIGH); } } else { if(skinnyFont[nextDig][y][x]) { matrix.drawPixel(x+xOffset, y+offScreen, HIGH); } } } } delay(30); matrix.write(); } } void updateTime() { String timeString = ""; String AmPmString = ""; bool PM = isPM(); timeString = myTZ.dateTime("hisv"); m0 = charToInt(timeString[3]); m1 = charToInt(timeString[2]); h0 = charToInt(timeString[1]); h1 = charToInt(timeString[0]); secs = myTZ.dateTime("s").toInt(); millisecs = myTZ.dateTime("v").toInt(); myMinutes = myTZ.dateTime("i").toInt(); if (h0 == 6 && myTZ.isAM()) { matrix.setIntensity(5); } if (h0 == 8 && myTZ.isPM()) { matrix.setIntensity(0); } /*// Only update Time if its different if (lastDisplayedTime != timeString) { //Serial.println(m0); //Serial.println(m1); //Serial.println(timeString); //ial.println(myMinutes); lastDisplayedTime = timeString; }*/ //--clear then write first mins digit clearDigit(0); writeDigit(0, m0); //--clear then write clear second min digit clearDigit(1); writeDigit(1, m1); //--clear then write hr digit clearDigit(2); writeDigit(2, h0); //--clear then write 2nd hr digit clearDigit(3); writeDigit(3, h1); } void skinnydotdots() { //clear dot dots if (!isDots) { for (int y = 0; y < 8; y++) { for (int x = 0; x < 1; x++) { matrix.drawPixel(x+16, y, LOW); } } } if (isDots) { //--dots for (int y = 0; y < 8; y++) { for (int x = 0; x < 1; x++) { if(dots[y][x]) { matrix.drawPixel(x+16, y, HIGH); } } } } } void dotdots() { //clear dot dots if (!isDots) { for (int y = 0; y < 8; y++) { for (int x = 0; x < 2; x++) { matrix.drawPixel(x+16, y, LOW); } } } if (isDots) { //--dots for (int y = 0; y < 8; y++) { for (int x = 0; x < 2; x++) { if(dots[y][x]) { matrix.drawPixel(x+16, y, HIGH); } } } } } void loop() { //--update the time //--check and use the correct fontdots updateTime(); if (fattyFont) { dotdots(); } else skinnydotdots(); //Serial.println(s); //--set the animation transition flag before the time changes if (secs==59 && millisecs==999) { transitionFlag=true; transition(0, m0); } if (m0==9 && secs==59 && millisecs==999) { transitionFlag=true; transition(1, m1); } if (myMinutes==59 && secs==59 && millisecs==999) { transitionFlag=true; transition(2, h0); } if (h0==9 && myMinutes==59 && secs==59 && millisecs==999) { transitionFlag=true; transition(3, h1); } unsigned long currentMillis = millis(); //--change dot flag if(currentMillis - previousMillis > interval) { // save the last time you blinked the LED previousMillis = currentMillis; if (isDots) { isDots = false; } else isDots = true; } //--finally write to the matrix matrix.write(); }
[ "noreply@github.com" ]
noreply@github.com
074c05dc9e05037c2d520b36c2c9230c0550e545
514199b7d4dd04465092f4c9361a86937cc6903d
/lattices/LatticeMath/StatsTiledCollapser.h
13ef9f6483efff85f9b58a5ef4e257eeda2000b2
[]
no_license
ludwigschwardt/casacore
560c6eb07e0d24afa659d5e2ccaa4a0b5c2a38e7
2efa86a84c26eea4b70e66890401f8c11568440b
refs/heads/master
2023-06-04T15:31:39.946922
2015-04-08T11:30:33
2015-04-08T11:30:33
33,654,592
1
0
null
null
null
null
UTF-8
C++
false
false
6,521
h
//# Copyright (C) 1996,1997,1998,1999,2000,2001,2002,2003 //# Associated Universities, Inc. Washington DC, USA. //# //# This library is free software; you can redistribute it and/or modify it //# under the terms of the GNU Library General Public License as published by //# the Free Software Foundation; either version 2 of the License, or (at your //# option) any later version. //# //# This library is distributed in the hope that it will be useful, but WITHOUT //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public //# License for more details. //# //# You should have received a copy of the GNU Library General Public License //# along with this library; if not, write to the Free Software Foundation, //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be addressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# $Id: LatticeStatistics.h 20739 2009-09-29 01:15:15Z Malte.Marquarding $ #ifndef LATTICES_STATSTILEDCOLLAPSER_H #define LATTICES_STATSTILEDCOLLAPSER_H //# Includes #include <casacore/casa/aips.h> namespace casacore { // <summary> Generate statistics, tile by tile, from a masked lattice </summary> // NOTE this version was moved from LatticeStatistics (early Dec 2014 version) // and slightly modified mostly for style issues (no significant semantic differences // from that version). For a large number of statistics sets that need to be computed // simultaneously, this version is more efficient than using the new stats framework, // because creating large numbers of eg ClassicalStatistics objects is much less efficient // than the direct manipulation of pointers to primitive types that this class does. // // <use visibility=export> // // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos=""> // </reviewed> // // <prerequisite> // <li> <linkto class=LatticeApply>LatticeApply</linkto> // <li> <linkto class=TiledCollapser>TiledCollapser</linkto> // </prerequisite> // // <etymology> // This class is used by <src>LatticeStatistics</src> to generate // statistical sum from an input <src>MaskedLattice</src>. // The input lattice is iterated through in tile-sized chunks // and fed to an object of this class. // </etymology> // // <synopsis> // <src>StatsTiledCollapser</src> is derived from <src>TiledCollapser</src> which // is a base class used to define methods. Objects of this base class are // used by <src>LatticeApply</src> functions. In this particular case, // we are interested in <src>LatticeApply::tiledApply</src>. This function iterates // through a <src>MaskedLattice</src> and allows you to collapse one or more // axes, computing some values from it, and placing those values into // an output <src>MaskedLattice</src>. It iterates through the input // lattice in optimal tile-sized chunks. <src>LatticeStatistics</src> // uses a <src>StatsTiledCollapser</src> object which it gives to // <src>LatticeApply::tiledApply</src> for digestion. After it has // done its work, <src>LatticeStatistics</src> then accesses the output // <src>Lattice</src> that it made. // </synopsis> // // <example> // <srcblock> //// Create collapser. Control information is passed in via the constructor // // StatsTiledCollapser<T> collapser(range_p, noInclude_p, noExclude_p, // fixedMinMax_p, blcParent_p); // //// This is the first output axis getting collapsed values. In LatticeStatistics //// this is the last axis of the output lattice // // Int newOutAxis = outLattice.ndim()-1; // //// tiledApply does the work by passing the collapser data in chunks //// and by writing the results into the output lattice // // LatticeApply<T>::tiledApply(outLattice, inLattice, // collapser, collapseAxes, // newOutAxis); // // </srcblock> // In this example, a collapser is made and passed to LatticeApply. // Afterwards, the output Lattice is available for use. // The Lattices must all be the correct shapes on input to tiledApply // </example> // // <motivation> // The LatticeApply classes enable the ugly details of optimal // Lattice iteration to be hidden from the user. // </motivation> // // <todo asof="1998/05/10"> // <li> // </todo> template <class T, class U=T> class StatsTiledCollapser : public TiledCollapser<T, U> { public: // Constructor provides pixel selection range and whether that // range is an inclusion or exclusion range. If <src>fixedMinMax=True</src> // and an inclusion range is given, the min and max is set to // that inclusion range. StatsTiledCollapser( const Vector<T>& pixelRange, Bool noInclude, Bool noExclude, Bool fixedMinMax ); virtual ~StatsTiledCollapser() {} // Initialize process, making some checks virtual void init (uInt nOutPixelsPerCollapse); // Initialiaze the accumulator virtual void initAccumulator (uInt n1, uInt n3); // Process the data in the current chunk. virtual void process ( uInt accumIndex1, uInt accumIndex3, const T* inData, const Bool* inMask, uInt dataIncr, uInt maskIncr, uInt nrval, const IPosition& startPos, const IPosition& shape ); // End the accumulation process and return the result arrays virtual void endAccumulator(Array<U>& result, Array<Bool>& resultMask, const IPosition& shape); // Can handle null mask virtual Bool canHandleNullMask() const {return True;}; // Find the location of the minimum and maximum data values // in the input lattice. void minMaxPos(IPosition& minPos, IPosition& maxPos); private: Vector<T> _range; Bool _include, _exclude, _fixedMinMax, _isReal; IPosition _minpos, _maxpos; // Accumulators for sum, sum squared, number of points // minimum, and maximum CountedPtr<Block<U> > _sum, _sumSq, _npts, _mean, _variance, _nvariance; CountedPtr<Block<T> > _min, _max; CountedPtr<Block<Bool> > _initMinMax; uInt _n1, _n3; }; } #ifndef CASACORE_NO_AUTO_TEMPLATES #include <casacore/lattices/LatticeMath/StatsTiledCollapser.tcc> #endif #endif
[ "gervandiepen@gmail.com" ]
gervandiepen@gmail.com
9dc91bab0bff2365587817fa09b2d2214f836e2d
689837429bedfccaca60f41c23cb8e31d1fd2e6a
/include/wasp/binary/read/read_relocation_entry.h
2fc238ace7839edb956740a55820ca1dfc8e8f9f
[ "Apache-2.0" ]
permissive
jgravelle-google/wasp
411c0ed0ec9d7ac6fd74156cbf3fdf1e0727fa41
f4bb868997b7158e7224b309a4b6e81b1763f9f6
refs/heads/master
2020-05-16T14:56:03.817357
2019-04-23T07:47:24
2019-04-23T07:47:24
183,116,763
0
0
null
2019-04-24T00:36:48
2019-04-24T00:36:48
null
UTF-8
C++
false
false
1,214
h
// // Copyright 2019 WebAssembly Community Group participants // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef WASP_BINARY_READ_READ_RELOCATION_ENTRY_H_ #define WASP_BINARY_READ_READ_RELOCATION_ENTRY_H_ #include "wasp/base/optional.h" #include "wasp/base/span.h" #include "wasp/binary/read/read.h" #include "wasp/binary/relocation_entry.h" namespace wasp { class Features; namespace binary { class Errors; optional<RelocationEntry> Read(SpanU8*, const Features&, Errors&, Tag<RelocationEntry>); } // namespace binary } // namespace wasp #endif // WASP_BINARY_READ_READ_RELOCATION_ENTRY_H_
[ "binjimin@gmail.com" ]
binjimin@gmail.com
00007f8f39f56794ab9e9f4619f082896642ced7
37d37b85b14996ab91c69dc50feb35fa43fb5c07
/src/plotWidget/indicatorWidget/momentumWidget.h
63f14ffe1a514f95457c54b05bfe7a46448fdec1
[]
no_license
normelius/fts
5dea47a348d6a7ab1a1c6af9160d428a745417dc
b8095f205efa70ae0fdf47bc15fb0fb8f6ae42ee
refs/heads/master
2023-08-02T03:09:19.228870
2021-09-20T10:49:00
2021-09-20T10:49:00
408,396,805
0
0
null
null
null
null
UTF-8
C++
false
false
1,768
h
/* #ifndef MOMENTUM_WIDGET_H #define MOMENTUM_WIDGET_H #include <QDebug> #include <QWidget> #include <QString> #include <QVBoxLayout> #include <QLabel> #include <QFontDatabase> #include <QFrame> #include <QLineEdit> #include <QPushButton> #include <QObject> #include <QTreeWidget> #include "src/utilities.h" #include "src/plotWidget/activeWidget.h" #include "third-party/qcustomplot.h" #include "src/streamdata.h" #include "src/indicators/trend.h" #include "src/indicators/momentum.h" #include "src/plotWidget/indicatorWidget/baseOverlay.h" #include "src/plotWidget/plotWidget.h" class ActiveWidget; class MacdWidget : public QWidget { Q_OBJECT public: MacdWidget(QWidget *parent = 0, ActiveWidget *activeWidget = 0); QPushButton *button; private: QLineEdit *fastPeriodInput; QLabel *infoText; ActiveWidget *activeWidget; public slots: void addNewStudy(); }; class MacdIndicator : public QObject, public BaseOverlayIndicator { Q_OBJECT public: void newGraph(QCPGraph *graph, QCPDataContainer<QCPFinancialData> *data){}; void newSubplot(SubPlot *subplot, QCPDataContainer<QCPFinancialData> *data); void updateData(QCPDataContainer<QCPFinancialData> *data, const bool newPoint = false); void replaceData(QCPDataContainer<QCPFinancialData> *data); // Takes the macd histogram and returns the positive/negative vectors with histograms. std::tuple<QVector<double>, QVector<double>> getHistograms(QVector<double> histogram); int fastPeriod = 12; int slowPeriod = 26; int signalSmoothing = 9; private: QCPGraph *macdGraph; QCPGraph *macdSignalGraph; QCPBars *posMacdHistogram; QCPBars *negMacdHistogram; public slots: void fastPeriodChanged(QString text); }; #endif */
[ "a.normelius@gmail.com" ]
a.normelius@gmail.com
c2287ec894b97f3979cb4ebc59a9d23ccb6e8472
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/container_hash/test/hash_map_test.hpp
bed3fdd514d2ead16a2bcfc1a64344c78fccab2c
[ "BSL-1.0" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
2,560
hpp
// Copyright 2005-2009 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(CONTAINER_TYPE) #error "CONTAINER_TYPE not defined" #else #if defined(BOOST_MSVC) #pragma warning(push) #pragma warning(disable:4244) // conversion from 'int' to 'float' #pragma warning(disable:4245) // signed/unsigned mismatch #endif namespace HASH_TEST_CAT(CONTAINER_TYPE, _tests) { template <class T> void integer_tests(T* = 0) { const int number_of_containers = 10; T containers[number_of_containers]; typedef BOOST_DEDUCED_TYPENAME T::value_type pair; typedef BOOST_DEDUCED_TYPENAME T::key_type key; typedef BOOST_DEDUCED_TYPENAME T::mapped_type value; for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) containers[i].insert(pair(key(0), value(0))); } containers[6].insert(pair(key(1),value(0))); containers[7].insert(pair(key(1),value(0))); containers[7].insert(pair(key(1),value(0))); containers[8].insert(pair(key(-1),value(1))); containers[9].insert(pair(key(-1),value(3))); containers[9].insert(pair(key(-1),value(3))); BOOST_HASH_TEST_NAMESPACE::hash<T> hasher; for(int i2 = 0; i2 < number_of_containers; ++i2) { BOOST_TEST(hasher(containers[i2]) == hasher(containers[i2])); BOOST_TEST(hasher(containers[i2]) == BOOST_HASH_TEST_NAMESPACE::hash_value(containers[i2])); BOOST_TEST(hasher(containers[i2]) == BOOST_HASH_TEST_NAMESPACE::hash_range( containers[i2].begin(), containers[i2].end())); for(int j2 = i2 + 1; j2 < number_of_containers; ++j2) { BOOST_TEST( (containers[i2] == containers[j2]) == (hasher(containers[i2]) == hasher(containers[j2])) ); } } } void HASH_TEST_CAT(CONTAINER_TYPE, _hash_integer_tests()) { integer_tests((CONTAINER_TYPE<char, unsigned char>*) 0); integer_tests((CONTAINER_TYPE<int, float>*) 0); integer_tests((CONTAINER_TYPE<unsigned long, unsigned long>*) 0); integer_tests((CONTAINER_TYPE<double, short>*) 0); } } #if defined(BOOST_MSVC) #pragma warning(pop) #endif #undef CONTAINER_TYPE #endif
[ "james.pack@stardog.com" ]
james.pack@stardog.com
97f6a714988434b064e335b477230e851b306e43
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s04/CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ofstream_53c.cpp
325131e85ccd178e45ed2d2390681d71ae602b18
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,837
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ofstream_53c.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-53c.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Full path and file name * Sink: ofstream * BadSink : Open the file named in data using ofstream::open() * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #include <fstream> using namespace std; namespace CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ofstream_53 { /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void badSink_d(wchar_t * data); void badSink_c(wchar_t * data) { badSink_d(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_d(wchar_t * data); void goodG2BSink_c(wchar_t * data) { goodG2BSink_d(data); } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
73d05b77688395f733922a392ff6c112fce216d1
7171b6b3c26fff039d7d03c6c67f4b859c6fe202
/Project1-ArduinoML/doc/expected-output/scenario5_signaling_stuff_by_using_sounds.ino
6de37888657b9bb08c4ca27b95bddb0d5a5a4054
[]
no_license
Livelinndy/si5-dsl-team-a
a7194ca66cffc6b39b2b03eab84b09775d1b5a2b
a891f8830505bb7a4331a38d6bc5674493acb19d
refs/heads/main
2023-03-21T04:44:54.419629
2021-03-06T14:13:03
2021-03-06T14:13:03
329,268,591
0
0
null
null
null
null
UTF-8
C++
false
false
826
ino
const int buzzer = 2; void setup() { pinMode(buzzer, OUTPUT); } void loop() { for (int i = 0; i < 3; i++) { // repeating short beep 3 times shortBeep(); delay(200); // a short delay is necessary to be able to distinguish the beeps } delay(1000); longBeep(); delay(1000); } void shortBeep() { for(int i = 0; i < 80; i++) { // the range of for influences the length of the beep (here the short beep is 2 times shorter than the long beep) digitalWrite(buzzer, HIGH); delay(1); // delay between signals influences the sound frequency (the shorter the delay, the higher the sound) digitalWrite(buzzer, LOW); delay(1); } } void longBeep() { for(int i = 0; i < 160; i++) { digitalWrite(buzzer, HIGH); delay(2); digitalWrite(buzzer, LOW); delay(2); } }
[ "lydia.baraukova@etu.univ-cotedazur.fr" ]
lydia.baraukova@etu.univ-cotedazur.fr
00408da9d97e2185efaa10910709c86fbe9bdc00
f242d3af58f45a388d94f1ae0330b033c3ffcef8
/2D/core/src/Actor.cpp
f100a9c5debd1c16fe848d739c43111552e95765
[]
no_license
csx0987/LearnCPPGame
9a7c06a818327a22a3f4086f861061ceb6b43b6a
b94065293ccc4e0bdd96d4ee82aa836092fa53b2
refs/heads/master
2023-09-05T04:57:52.867492
2021-11-07T17:35:36
2021-11-07T17:35:36
421,646,639
0
0
null
null
null
null
UTF-8
C++
false
false
1,175
cpp
#include "Actor.h" #include "Game.h" #include "Component.h" #include <algorithm> Actor::Actor(Game *game) :mState(EActive) ,mPosition(Vector2::Zero) ,mScale(1.0f) ,mRotation(0.0f) ,mGame(game) { mGame->AddActor(this); } Actor::~Actor() { mGame->RemoveActor(this); while (!mComponents.empty()) { delete mComponents.back(); } } void Actor::Update(float deltaTime) { if (mState == EActive) { UpdateComponents(deltaTime); UpdateActor(deltaTime); } } void Actor::UpdateComponents(float deltaTime) { for (auto comp : mComponents) { comp->Update(deltaTime); } } void Actor::UpdateActor(float deltaTime) { } void Actor::AddComponent(Component *component) { int myOrder = component->GetUpdateOrder(); auto it = mComponents.begin(); for (; it != mComponents.end(); it++) { if (myOrder < (*it)->GetUpdateOrder()) break; } mComponents.insert(it, component); } void Actor::RemoveComponent(Component *component) { auto it = std::find(mComponents.begin(), mComponents.end(), component); if (it != mComponents.end()) { mComponents.erase(it); } }
[ "chenshengxin@bytedance.com" ]
chenshengxin@bytedance.com
e4c9ed11f6f7362d6e9037bbf767e683f4d5aab4
019904382caeb8c49e24f1101927ba0d9e137801
/uva 231.cpp
b1cb8d6682d99f0d9113b3867f11135f5c1f3a53
[]
no_license
faiem/UVA-Online-Judge
bdf0f073cfe641422e17a5fe82e1ce41148606eb
4e56df804f36dace60db8829fb3ea5d133b12389
refs/heads/main
2023-04-12T17:05:21.605237
2021-04-29T07:19:35
2021-04-29T07:19:35
362,724,665
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
#include<iostream> #include<cstdio> #include<vector> #include<stack> using namespace std; #define MAX 33000 #define inf 1000000 int seq[MAX],check[MAX]; int LIS(int N){ int I,J,high,low,mid,LIS_length=0; check[0]=-inf; //L[0]=inf; for(I=1;I<=N;I++){ check[I]=inf; //L[I]=0; } for(int I=1;I<=N;I++){ low=0; high=LIS_length; while(low<=high){ mid=(low+high)/2; if(check[mid]<seq[I]) low=mid+1; else high=mid-1; } check[low]=seq[I]; // L[I]=low; if(LIS_length<low) LIS_length=low; } return LIS_length; } int main(){ int in,in2,I,C=1; //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); while(cin>>in){ if(in==-1) continue; stack<int> s; s.push(in); while(cin>>in2 && in2!=-1){ s.push(in2); } I=1; while(s.size()){ seq[I]=s.top(); s.pop(); I++; } if(C>1) printf("\n"); printf("Test #%d:\n maximum possible interceptions: %d\n",C,LIS(I-1)); C++; } return 0; }
[ "faiem@overseasecurity.com" ]
faiem@overseasecurity.com
24c854091bfe12a1fec04d2ec63bdab5c4438c91
019c446b2c8f8e902226851db1b31eb1e3c850d5
/oneEngine/oneGame/source/engine-common/cutscene/NodeEnd.h
8857039560b8138fb3ef8935be722ac737b2691d
[ "BSD-3-Clause", "FTL" ]
permissive
skarik/1Engine
cc9b6f7cf81903b75663353926a23224b81d1389
9f53b4cb19a6b8bb3bf2e3a4104c73614ffd4359
refs/heads/master
2023-09-04T23:12:50.706308
2023-08-29T05:28:21
2023-08-29T05:28:21
109,445,379
9
2
BSD-3-Clause
2021-08-30T06:48:27
2017-11-03T21:41:51
C++
UTF-8
C++
false
false
805
h
#ifndef ENGINE_CUTSCENE_NODE_END_H_ #define ENGINE_CUTSCENE_NODE_END_H_ #include "engine-common/cutscene/Node.h" namespace common { namespace cts { // NodeEnd - ending node action that signals the cutscene system should rpobably end. class NodeEnd : public Node { public: explicit NodeEnd ( void ) : Node() {} virtual ~NodeEnd ( void ) {} virtual ENodeType GetNodeType ( void ) { return kNodeTypeEnd; } virtual int GetOutputNodeCount ( void ) { return 0; } virtual Node* GetOutputNode ( const int index ) { return NULL; } public: // IOSetOutputNode( IGNORED, IGNORED ) : Sets the output node in the output node list at index. // Ignored for Ending nodes void IOSetOutputNode ( const int, Node* ) override {} }; }} #endif//ENGINE_CUTSCENE_NODE_END_H_
[ "joshua.boren@borenlabs.com" ]
joshua.boren@borenlabs.com
908274a087ece95cc9b77593767c518d7721251c
90db83e7fb4d95400e62fa2ce48bd371754987e0
/src/remoting/protocol/ssl_hmac_channel_authenticator.cc
82c03e6a6f568260fdbb7738d9a4df57d101e0be
[ "BSD-3-Clause" ]
permissive
FinalProjectNEG/NEG-Browser
5bf10eb1fb8b414313d5d4be6b5af863c4175223
66c824bc649affa8f09e7b1dc9d3db38a3f0dfeb
refs/heads/main
2023-05-09T05:40:37.994363
2021-06-06T14:07:21
2021-06-06T14:07:21
335,742,507
2
4
null
null
null
null
UTF-8
C++
false
false
16,543
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/ssl_hmac_channel_authenticator.h" #include <stdint.h> #include <iostream> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback_helpers.h" #include "base/logging.h" #include "build/build_config.h" #include "crypto/secure_util.h" #include "net/base/host_port_pair.h" #include "net/base/io_buffer.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/cert/cert_status_flags.h" #include "net/cert/cert_verifier.h" #include "net/cert/cert_verify_result.h" #include "net/cert/ct_policy_enforcer.h" #include "net/cert/ct_policy_status.h" #include "net/cert/do_nothing_ct_verifier.h" #include "net/cert/signed_certificate_timestamp_and_status.h" #include "net/cert/x509_certificate.h" #include "net/http/transport_security_state.h" #include "net/log/net_log_with_source.h" #include "net/socket/client_socket_factory.h" #include "net/socket/ssl_client_socket.h" #include "net/socket/ssl_server_socket.h" #include "net/socket/stream_socket.h" #include "net/ssl/ssl_config_service.h" #include "net/ssl/ssl_server_config.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "remoting/base/rsa_key_pair.h" #include "remoting/protocol/auth_util.h" #include "remoting/protocol/p2p_stream_socket.h" namespace remoting { namespace protocol { namespace { constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("ssl_hmac_channel_authenticator", R"( semantics { sender: "Chrome Remote Desktop" description: "Performs the required authentication to start a Chrome Remote " "Desktop connection." trigger: "Initiating a Chrome Remote Desktop connection." data: "No user data." destination: OTHER destination_other: "The Chrome Remote Desktop client/host that user is connecting to." } policy { cookies_allowed: NO setting: "This request cannot be stopped in settings, but will not be sent " "if user does not use Chrome Remote Desktop." policy_exception_justification: "Not implemented. 'RemoteAccessHostClientDomainList' and " "'RemoteAccessHostDomainList' policies can limit the domains to " "which a connection can be made, but they cannot be used to block " "the request to all domains. Please refer to help desk for other " "approaches to manage this feature." })"); // A CertVerifier which rejects every certificate. class FailingCertVerifier : public net::CertVerifier { public: FailingCertVerifier() = default; ~FailingCertVerifier() override = default; int Verify(const RequestParams& params, net::CertVerifyResult* verify_result, net::CompletionOnceCallback callback, std::unique_ptr<Request>* out_req, const net::NetLogWithSource& net_log) override { verify_result->verified_cert = params.certificate(); verify_result->cert_status = net::CERT_STATUS_INVALID; return net::ERR_CERT_INVALID; } void SetConfig(const Config& config) override {} }; // Implements net::StreamSocket interface on top of P2PStreamSocket to be passed // to net::SSLClientSocket and net::SSLServerSocket. class NetStreamSocketAdapter : public net::StreamSocket { public: NetStreamSocketAdapter(std::unique_ptr<P2PStreamSocket> socket) : socket_(std::move(socket)) {} ~NetStreamSocketAdapter() override = default; int Read(net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback callback) override { return socket_->Read(buf, buf_len, std::move(callback)); } int Write( net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback callback, const net::NetworkTrafficAnnotationTag& traffic_annotation) override { return socket_->Write(buf, buf_len, std::move(callback), traffic_annotation); } int SetReceiveBufferSize(int32_t size) override { NOTREACHED(); return net::ERR_FAILED; } int SetSendBufferSize(int32_t size) override { NOTREACHED(); return net::ERR_FAILED; } int Connect(net::CompletionOnceCallback callback) override { NOTREACHED(); return net::ERR_FAILED; } void Disconnect() override { socket_.reset(); } bool IsConnected() const override { return true; } bool IsConnectedAndIdle() const override { return true; } int GetPeerAddress(net::IPEndPoint* address) const override { // SSL sockets call this function so it must return some result. *address = net::IPEndPoint(net::IPAddress::IPv4AllZeros(), 0); return net::OK; } int GetLocalAddress(net::IPEndPoint* address) const override { NOTREACHED(); return net::ERR_FAILED; } const net::NetLogWithSource& NetLog() const override { return net_log_; } bool WasEverUsed() const override { NOTREACHED(); return true; } bool WasAlpnNegotiated() const override { NOTREACHED(); return false; } net::NextProto GetNegotiatedProtocol() const override { NOTREACHED(); return net::kProtoUnknown; } bool GetSSLInfo(net::SSLInfo* ssl_info) override { NOTREACHED(); return false; } void GetConnectionAttempts(net::ConnectionAttempts* out) const override { NOTREACHED(); } void ClearConnectionAttempts() override { NOTREACHED(); } void AddConnectionAttempts(const net::ConnectionAttempts& attempts) override { NOTREACHED(); } int64_t GetTotalReceivedBytes() const override { NOTIMPLEMENTED(); return 0; } void ApplySocketTag(const net::SocketTag& tag) override { NOTIMPLEMENTED(); } private: std::unique_ptr<P2PStreamSocket> socket_; net::NetLogWithSource net_log_; }; } // namespace // Implements P2PStreamSocket interface on top of net::StreamSocket. class SslHmacChannelAuthenticator::P2PStreamSocketAdapter : public P2PStreamSocket { public: P2PStreamSocketAdapter(SslSocketContext socket_context, std::unique_ptr<net::StreamSocket> socket) : socket_context_(std::move(socket_context)), socket_(std::move(socket)) {} ~P2PStreamSocketAdapter() override = default; int Read(const scoped_refptr<net::IOBuffer>& buf, int buf_len, net::CompletionOnceCallback callback) override { return socket_->Read(buf.get(), buf_len, std::move(callback)); } int Write( const scoped_refptr<net::IOBuffer>& buf, int buf_len, net::CompletionOnceCallback callback, const net::NetworkTrafficAnnotationTag& traffic_annotation) override { return socket_->Write(buf.get(), buf_len, std::move(callback), traffic_annotation); } private: // The socket_context_ must outlive any associated sockets. SslSocketContext socket_context_; std::unique_ptr<net::StreamSocket> socket_; }; SslHmacChannelAuthenticator::SslSocketContext::SslSocketContext() = default; SslHmacChannelAuthenticator::SslSocketContext::SslSocketContext( SslSocketContext&&) = default; SslHmacChannelAuthenticator::SslSocketContext::~SslSocketContext() = default; SslHmacChannelAuthenticator::SslSocketContext& SslHmacChannelAuthenticator::SslSocketContext::operator=(SslSocketContext&&) = default; // static std::unique_ptr<SslHmacChannelAuthenticator> SslHmacChannelAuthenticator::CreateForClient(const std::string& remote_cert, const std::string& auth_key) { std::unique_ptr<SslHmacChannelAuthenticator> result( new SslHmacChannelAuthenticator(auth_key)); result->remote_cert_ = remote_cert; return result; } std::unique_ptr<SslHmacChannelAuthenticator> SslHmacChannelAuthenticator::CreateForHost(const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, const std::string& auth_key) { std::unique_ptr<SslHmacChannelAuthenticator> result( new SslHmacChannelAuthenticator(auth_key)); result->local_cert_ = local_cert; result->local_key_pair_ = key_pair; return result; } SslHmacChannelAuthenticator::SslHmacChannelAuthenticator( const std::string& auth_key) : auth_key_(auth_key) { } SslHmacChannelAuthenticator::~SslHmacChannelAuthenticator() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void SslHmacChannelAuthenticator::SecureAndAuthenticate( std::unique_ptr<P2PStreamSocket> socket, DoneCallback done_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); done_callback_ = std::move(done_callback); int result; if (is_ssl_server()) { scoped_refptr<net::X509Certificate> cert = net::X509Certificate::CreateFromBytes(local_cert_.data(), local_cert_.length()); if (!cert) { LOG(ERROR) << "Failed to parse X509Certificate"; NotifyError(net::ERR_FAILED); return; } net::SSLServerConfig ssl_config; ssl_config.require_ecdhe = true; socket_context_.server_context = net::CreateSSLServerContext( cert.get(), *local_key_pair_->private_key(), ssl_config); std::unique_ptr<net::SSLServerSocket> server_socket = socket_context_.server_context->CreateSSLServerSocket( std::make_unique<NetStreamSocketAdapter>(std::move(socket))); net::SSLServerSocket* raw_server_socket = server_socket.get(); socket_ = std::move(server_socket); result = raw_server_socket->Handshake(base::BindOnce( &SslHmacChannelAuthenticator::OnConnected, base::Unretained(this))); } else { socket_context_.transport_security_state = std::make_unique<net::TransportSecurityState>(); socket_context_.cert_verifier = std::make_unique<FailingCertVerifier>(); socket_context_.ct_verifier = std::make_unique<net::DoNothingCTVerifier>(); socket_context_.ct_policy_enforcer = std::make_unique<net::DefaultCTPolicyEnforcer>(); socket_context_.client_context = std::make_unique<net::SSLClientContext>( nullptr /* default config */, socket_context_.cert_verifier.get(), socket_context_.transport_security_state.get(), socket_context_.ct_verifier.get(), socket_context_.ct_policy_enforcer.get(), nullptr /* no session caching */, nullptr /* no sct auditing */); net::SSLConfig ssl_config; ssl_config.require_ecdhe = true; scoped_refptr<net::X509Certificate> cert = net::X509Certificate::CreateFromBytes(remote_cert_.data(), remote_cert_.length()); if (!cert) { LOG(ERROR) << "Failed to parse X509Certificate"; NotifyError(net::ERR_FAILED); return; } ssl_config.allowed_bad_certs.emplace_back( std::move(cert), net::CERT_STATUS_AUTHORITY_INVALID); net::HostPortPair host_and_port(kSslFakeHostName, 0); std::unique_ptr<net::StreamSocket> stream_socket = std::make_unique<NetStreamSocketAdapter>(std::move(socket)); socket_ = net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( socket_context_.client_context.get(), std::move(stream_socket), host_and_port, ssl_config); STD::COUT<<"\nSSL_HMAC_CHANNEL_AUTHENTICATOR\n"; result = socket_->Connect(base::BindOnce( &SslHmacChannelAuthenticator::OnConnected, base::Unretained(this))); } if (result == net::ERR_IO_PENDING) return; OnConnected(result); } bool SslHmacChannelAuthenticator::is_ssl_server() { return local_key_pair_.get() != nullptr; } void SslHmacChannelAuthenticator::OnConnected(int result) { if (result != net::OK) { LOG(WARNING) << "Failed to establish SSL connection. Error: " << net::ErrorToString(result); NotifyError(result); return; } // Generate authentication digest to write to the socket. std::string auth_bytes = GetAuthBytes( socket_.get(), is_ssl_server() ? kHostAuthSslExporterLabel : kClientAuthSslExporterLabel, auth_key_); if (auth_bytes.empty()) { NotifyError(net::ERR_FAILED); return; } // Allocate a buffer to write the digest. auth_write_buf_ = base::MakeRefCounted<net::DrainableIOBuffer>( base::MakeRefCounted<net::StringIOBuffer>(auth_bytes), auth_bytes.size()); // Read an incoming token. auth_read_buf_ = base::MakeRefCounted<net::GrowableIOBuffer>(); auth_read_buf_->SetCapacity(kAuthDigestLength); // If WriteAuthenticationBytes() results in |done_callback_| being // called then we must not do anything else because this object may // be destroyed at that point. bool callback_called = false; WriteAuthenticationBytes(&callback_called); if (!callback_called) ReadAuthenticationBytes(); } void SslHmacChannelAuthenticator::WriteAuthenticationBytes( bool* callback_called) { while (true) { int result = socket_->Write( auth_write_buf_.get(), auth_write_buf_->BytesRemaining(), base::BindOnce(&SslHmacChannelAuthenticator::OnAuthBytesWritten, base::Unretained(this)), kTrafficAnnotation); if (result == net::ERR_IO_PENDING) break; if (!HandleAuthBytesWritten(result, callback_called)) break; } } void SslHmacChannelAuthenticator::OnAuthBytesWritten(int result) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (HandleAuthBytesWritten(result, nullptr)) WriteAuthenticationBytes(nullptr); } bool SslHmacChannelAuthenticator::HandleAuthBytesWritten( int result, bool* callback_called) { if (result <= 0) { LOG(ERROR) << "Error writing authentication: " << result; if (callback_called) *callback_called = false; NotifyError(result); return false; } auth_write_buf_->DidConsume(result); if (auth_write_buf_->BytesRemaining() > 0) return true; auth_write_buf_ = nullptr; CheckDone(callback_called); return false; } void SslHmacChannelAuthenticator::ReadAuthenticationBytes() { while (true) { int result = socket_->Read( auth_read_buf_.get(), auth_read_buf_->RemainingCapacity(), base::BindOnce(&SslHmacChannelAuthenticator::OnAuthBytesRead, base::Unretained(this))); if (result == net::ERR_IO_PENDING) break; if (!HandleAuthBytesRead(result)) break; } } void SslHmacChannelAuthenticator::OnAuthBytesRead(int result) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (HandleAuthBytesRead(result)) ReadAuthenticationBytes(); } bool SslHmacChannelAuthenticator::HandleAuthBytesRead(int read_result) { if (read_result <= 0) { NotifyError(read_result); return false; } auth_read_buf_->set_offset(auth_read_buf_->offset() + read_result); if (auth_read_buf_->RemainingCapacity() > 0) return true; if (!VerifyAuthBytes(std::string( auth_read_buf_->StartOfBuffer(), auth_read_buf_->StartOfBuffer() + kAuthDigestLength))) { LOG(WARNING) << "Mismatched authentication"; NotifyError(net::ERR_FAILED); return false; } auth_read_buf_ = nullptr; CheckDone(nullptr); return false; } bool SslHmacChannelAuthenticator::VerifyAuthBytes( const std::string& received_auth_bytes) { DCHECK(received_auth_bytes.length() == kAuthDigestLength); // Compute expected auth bytes. std::string auth_bytes = GetAuthBytes( socket_.get(), is_ssl_server() ? kClientAuthSslExporterLabel : kHostAuthSslExporterLabel, auth_key_); if (auth_bytes.empty()) return false; return crypto::SecureMemEqual(received_auth_bytes.data(), &(auth_bytes[0]), kAuthDigestLength); } void SslHmacChannelAuthenticator::CheckDone(bool* callback_called) { if (auth_write_buf_.get() == nullptr && auth_read_buf_.get() == nullptr) { DCHECK(socket_.get() != nullptr); if (callback_called) *callback_called = true; std::move(done_callback_) .Run(net::OK, std::make_unique<P2PStreamSocketAdapter>( std::move(socket_context_), std::move(socket_))); } } void SslHmacChannelAuthenticator::NotifyError(int error) { std::move(done_callback_).Run(error, nullptr); } } // namespace protocol } // namespace remoting
[ "edenda2@ac.sce.ac.il" ]
edenda2@ac.sce.ac.il
5c39ec4a8d065141fac5f075d6a8636850b645b4
cc9aaf54eb999849550a9d60791ade202aa4383e
/Code/Game/GameCamera.hpp
2d15bbd769537e5ad05d78827936e3c6eac3df19
[]
no_license
jamesmdale/ProtoGame3D
d21122edf9fa42c8faa319e7fbcd36236dfcba13
d0b9f4cb4c6151d307a7381ceb9c9438c90fc9e6
refs/heads/master
2020-04-21T22:14:00.321179
2019-02-09T19:30:14
2019-02-09T19:30:14
169,904,239
0
0
null
null
null
null
UTF-8
C++
false
false
397
hpp
#pragma once #include "Engine\Math\Vector3.hpp" #include "Engine\Math\Matrix44.hpp" class GameCamera { public: GameCamera(); ~GameCamera(); void CreateFliippedViewMatrix(Matrix44& outMatrix); void Translate(Vector3 translation); public: float m_rollDegreesX = 0.0f; //roll float m_pitchDegreesY = 0.0f; //pitch float m_yawDegreesZ = 0.0f; //yaw Vector3 m_position = Vector3::ZERO; };
[ "jmdale@smu.edu" ]
jmdale@smu.edu
2315190cbf9996e73aea45d3e88e05bed76e7c99
57cd15afbcf9c19176eede61d613a59db9a09f4a
/ShipGameModeBase.cpp
1aa65c889e60b1e26d620d830084df64d9c82298
[]
no_license
CZARNY77/Cosmo-Ship
8ca67e868f6e2d0342203e89d62fa0c1c500ba24
193526fb840b706975c17072b1bac7a2d52cf9f9
refs/heads/main
2023-07-27T12:26:30.257937
2021-09-12T17:21:50
2021-09-12T17:21:50
405,706,610
0
0
null
null
null
null
UTF-8
C++
false
false
84
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "ShipGameModeBase.h"
[ "60876248+CZARNY77@users.noreply.github.com" ]
60876248+CZARNY77@users.noreply.github.com
41ff7aafe04a883c0d8aba63793409293ec84fb2
15661f0075c5bf54b9fd9e275ecd7d19caf602e6
/parallel_test.cpp
9d2a2ceaf622ab51fc4d7d0d8b444b644b17bac1
[]
no_license
huangjiahua/concurrency
d0f777e7be7b4eb6a81fac64aa118965635174ec
fd37f575dbe15984009ebadb4430c7db98d0d6b4
refs/heads/master
2020-04-27T20:47:29.296645
2019-03-20T10:10:23
2019-03-20T10:10:23
174,670,924
0
0
null
null
null
null
UTF-8
C++
false
false
873
cpp
// // Created by jiahua on 2019/3/8. // #include <iostream> #include "ParallelTestSuite.h" #include <string> #include <cstdlib> #include <fstream> using namespace std; int main(int argc, const char *argv[]) { int td = 1; if (argc > 4) { exit(EXIT_FAILURE); } if (argc == 2) { td = stoi(string(argv[1])); } ParallelTestSuite pts(static_cast<ParallelTestSuite::ST>(td)); size_t tm = pts.getTime(); if (argc == 3) { cout << fixed << tm << endl; } else if (argc == 2){ cout << "Thread count: " << td << endl; cout << "Time: " << fixed << tm << endl; ofstream of("result.txt", ios_base::app); of << fixed << tm << endl; } else if (argc == 4) { ofstream of("result.txt", ios_base::app); of << fixed << tm << endl; cout << "done" << endl; } }
[ "hjh4477@outlook.com" ]
hjh4477@outlook.com
7f6d970b151c1dae8b7f1effe8aaea6374bcadd4
5bcfd299db34189ceae6bf5cda00677fc5dced34
/mooc/1C语言/第5周测验/002陶陶摘苹果.cpp
bab3e951f29281cf51004f28e6317f28d397d1d2
[]
no_license
aidandan/algorithm
40617151cbffb2279aabe4bdbc57a34ac6f722de
b29cca383654324c4004c6f5fc5ca358f3d51a92
refs/heads/master
2023-01-05T00:31:58.006399
2020-11-04T13:22:43
2020-11-04T13:22:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
199
cpp
#include<cstdio> main() { int i,a[101]= {0},s=0,n=10,m; for(i=0; i<n; i++) { scanf("%d",&a[i]); } scanf("%d",&m); m+=30; for(i=0; i<n; i++) { if(a[i]<=m) { s++; } } printf("%d",s); }
[ "a@gaojs.cn" ]
a@gaojs.cn
a2862accf88de59d4111245fe73f8709ac20d618
a8597563c1349d1ff2820cfc528d3d8d05b74bc7
/Webkit-owb/generated_sources/WebCore/JSHTMLParamElement.cpp
0dae7c756f12cc092fde9633618788ebc447ae90
[]
no_license
lentinic/EAWebKit
68f8288b96d3b629f0466e94287ece37820a322d
132ee635f9cd4cfce92ad4da823c83d54b95e993
refs/heads/master
2021-01-15T22:09:35.942573
2011-06-28T16:41:01
2011-06-28T16:41:01
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,765
cpp
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This file was modified by Electronic Arts Inc Copyright © 2009 */ #include "config.h" #include "JSHTMLParamElement.h" #include <wtf/GetPtr.h> #include "HTMLParamElement.h" #include "KURL.h" using namespace KJS; namespace WebCore { /* Hash table */ static const HashTableValue JSHTMLParamElementTableValues[6] = { { "name", (intptr_t)JSHTMLParamElement::NameAttrNum, DontDelete, 0 }, { "type", (intptr_t)JSHTMLParamElement::TypeAttrNum, DontDelete, 0 }, { "value", (intptr_t)JSHTMLParamElement::ValueAttrNum, DontDelete, 0 }, { "valueType", (intptr_t)JSHTMLParamElement::ValueTypeAttrNum, DontDelete, 0 }, { "constructor", (intptr_t)JSHTMLParamElement::ConstructorAttrNum, DontEnum, 0 }, { 0, 0, 0, 0 } }; static const HashTable JSHTMLParamElementTable = { 127, JSHTMLParamElementTableValues, 0 }; /* Hash table for constructor */ static const HashTableValue JSHTMLParamElementConstructorTableValues[1] = { { 0, 0, 0, 0 } }; static const HashTable JSHTMLParamElementConstructorTable = { 0, JSHTMLParamElementConstructorTableValues, 0 }; class JSHTMLParamElementConstructor : public DOMObject { public: JSHTMLParamElementConstructor(ExecState* exec) : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) { putDirect(exec->propertyNames().prototype, JSHTMLParamElementPrototype::self(exec), None); } virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&); JSValue* getValueProperty(ExecState*, int token) const; virtual const ClassInfo* classInfo() const { return &s_info; } static const ClassInfo s_info; virtual bool implementsHasInstance() const { return true; } }; const ClassInfo JSHTMLParamElementConstructor::s_info = { "HTMLParamElementConstructor", 0, &JSHTMLParamElementConstructorTable, 0 }; bool JSHTMLParamElementConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSHTMLParamElementConstructor, DOMObject>(exec, &JSHTMLParamElementConstructorTable, this, propertyName, slot); } JSValue* JSHTMLParamElementConstructor::getValueProperty(ExecState* exec, int token) const { // The token is the numeric value of its associated constant return jsNumber(exec, token); } /* Hash table for prototype */ static const HashTableValue JSHTMLParamElementPrototypeTableValues[1] = { { 0, 0, 0, 0 } }; static const HashTable JSHTMLParamElementPrototypeTable = { 0, JSHTMLParamElementPrototypeTableValues, 0 }; const ClassInfo JSHTMLParamElementPrototype::s_info = { "HTMLParamElementPrototype", 0, &JSHTMLParamElementPrototypeTable, 0 }; JSObject* JSHTMLParamElementPrototype::self(ExecState* exec) { // Changed by Paul Pedriana (1/2009), as the static new was creating a memory leak. If this gets called a lot then we can consider making it a static pointer that's freed on shutdown. const Identifier prototypeIdentifier(exec, "[[JSHTMLParamElement.prototype]]"); return KJS::cacheGlobalObject<JSHTMLParamElementPrototype>(exec, prototypeIdentifier); } const ClassInfo JSHTMLParamElement::s_info = { "HTMLParamElement", &JSHTMLElement::s_info, &JSHTMLParamElementTable , 0 }; JSHTMLParamElement::JSHTMLParamElement(JSObject* prototype, HTMLParamElement* impl) : JSHTMLElement(prototype, impl) { } bool JSHTMLParamElement::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSHTMLParamElement, Base>(exec, &JSHTMLParamElementTable, this, propertyName, slot); } JSValue* JSHTMLParamElement::getValueProperty(ExecState* exec, int token) const { switch (token) { case NameAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); return jsString(exec, imp->name()); } case TypeAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); return jsString(exec, imp->type()); } case ValueAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); return jsString(exec, imp->value()); } case ValueTypeAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); return jsString(exec, imp->valueType()); } case ConstructorAttrNum: return getConstructor(exec); } return 0; } void JSHTMLParamElement::put(ExecState* exec, const Identifier& propertyName, JSValue* value) { lookupPut<JSHTMLParamElement, Base>(exec, propertyName, value, &JSHTMLParamElementTable, this); } void JSHTMLParamElement::putValueProperty(ExecState* exec, int token, JSValue* value) { switch (token) { case NameAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); imp->setName(valueToStringWithNullCheck(exec, value)); break; } case TypeAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); imp->setType(valueToStringWithNullCheck(exec, value)); break; } case ValueAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); imp->setValue(valueToStringWithNullCheck(exec, value)); break; } case ValueTypeAttrNum: { HTMLParamElement* imp = static_cast<HTMLParamElement*>(impl()); imp->setValueType(valueToStringWithNullCheck(exec, value)); break; } } } JSValue* JSHTMLParamElement::getConstructor(ExecState* exec) { // Changed by Paul Pedriana (1/2009), as the static new was creating a memory leak. If this gets called a lot then we can consider making it a static pointer that's freed on shutdown. const Identifier constructorIdentifier(exec, "[[HTMLParamElement.constructor]]"); return KJS::cacheGlobalObject<JSHTMLParamElementConstructor>(exec, constructorIdentifier); } }
[ "nanashi4129@gmail.com" ]
nanashi4129@gmail.com
a8ef70edbc0dee6570d9240b4b952e8b32fd5740
a851b6c4fc4321a7a99bd9205e18747c7066beea
/Character/Enemy/Enemy.cc
bd2f745bcf5fcfe7148efab51f802b5b93296c86
[]
no_license
rutpatel/DragonCrawl
7069887a3b320a2f586d529cd7d881de37776414
b15b417d9aa17c13b1bb23b5295d84d3ae372e99
refs/heads/master
2020-03-17T12:44:47.135755
2018-05-17T03:08:25
2018-05-17T03:08:25
133,601,173
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
cc
#include "Enemy.h" using namespace std; //Enemy::Enemy() {} Enemy::Enemy(int atk, int def, int hp, char symbol, bool isHostile): Character(atk, def, hp, symbol), isHostile(isHostile) {} bool Enemy::isEnemyHostile() { return isHostile; } void Enemy::attackPlayer(Player* player) { int i = rand() % 2; string newAction; if (!player) {}//cout << "No enemy to attack at that position!" << endl; else if (i) { int damageDealt = ceil((100/(100 + float(player->getDef())))* float(this->getAtk())); newAction = player->getAction() + "Damage done by " + this->getSymbol() + " to " + player->getSymbol() + ": " + to_string(damageDealt) + "HP. "; player->setAction(newAction); player->setHp(player->getHp() - damageDealt ); } else{ newAction = player->getAction() + " " + this->getSymbol()+ " missed its attack! "; player->setAction(newAction); } } string Enemy::getRace() { return "Enemy"; } void Enemy::makeHostile() {} void Enemy::onDeath(Player* player) { getCurrCell()->leave(); int i = rand() % 2; if (i) player->setScore(player->getScore() + 1); else player->setScore(player->getScore() + 2); } Enemy::~Enemy() {}
[ "rutpatel010@gmail.com" ]
rutpatel010@gmail.com
d59170c31f169be135dfefec1a65fb8a4c9d7aeb
59c24806d80beb7825985ec5006a43708e417d27
/Project/Sources/Internal/Transformations/LegendrePolynomialProvider.h
186f25e8c0f65758826edcb1e484e955ed4a6839
[]
no_license
TIS2017/SpektroskopickeData
7e56847da7a0c8030b8cc415958becfe2c4d6497
e6c61af6be0ad64fe767a1433a13d5b7230aa25b
refs/heads/master
2021-09-07T06:22:16.138281
2018-02-18T20:34:52
2018-02-18T20:34:52
106,039,068
0
0
null
2018-02-18T20:34:53
2017-10-06T18:46:43
C++
UTF-8
C++
false
false
2,044
h
#pragma once #include "IRecursivePolynomialProvider.h" namespace DataAnalysis { namespace Transformations { /* Provider for Legendre polynomials Generates polynomials of given degree based on this recursive formula: P_0(x) = 1 P_1(x) = x P_i(x) = (1/i) * ( (2(i-1) + 1)x * P_[i-1](x) - (i-1) * P_[i-2](x) ) */ template <class BaseType = double> class LegendrePolynomialProvider: public IRecursivePolynomialProvider<BaseType> { public: LegendrePolynomialProvider() { AddInitialPolynomials(); }; ~LegendrePolynomialProvider() {}; virtual shared_ptr<Polynomial<BaseType>> GetPolynomial( __in const uint degree ) { if ( degree < m_polynomials.size() ) { return m_polynomials[degree]; } // get P_i-1 and P_i-2 shared_ptr<Polynomial<BaseType>> spP1 = GetPolynomial( degree - 1 ); shared_ptr<Polynomial<BaseType>> spP2 = GetPolynomial( degree - 2 ); // (i-1) * P_[i-2] shared_ptr<Polynomial<BaseType>> spP2Multiplied( new Polynomial<BaseType>( spP2 ) ); spP2Multiplied->Multiply( static_cast<BaseType> ( degree - 1 ) ); // ( 2( i - 1 ) + 1 )x * P_[i - 1] shared_ptr<Polynomial<BaseType>> spP1Multiplied( new Polynomial<BaseType>( spP1 ) ); spP1Multiplied->Multiply( static_cast<BaseType> ( ((degree - 1) << 1) + 1 ), 1 ); // (spP1Multiplied - spP2Multiplied) spP1Multiplied->Subtract( spP2Multiplied ); shared_ptr<Polynomial<BaseType>> spNew( new Polynomial<BaseType>( spP1Multiplied ) ); // (1/i) * (spP1Multiplied - spP2Multiplied) spNew->Multiply( static_cast<BaseType> ( 1 / degree ) ); // memoize new polynomial m_polynomials.push_back( spNew ); return spNew; }; protected: /* Adds base cases P0 and P1 */ void AddInitialPolynomials() { //P_0(x) = 1 shared_ptr< Polynomial<BaseType> > spP0( new Polynomial<BaseType>( { 1 } ) ); // P_1( x ) = x shared_ptr< Polynomial<BaseType> > spP1( new Polynomial<BaseType>( { 0, 1 } ) ); m_polynomials.push_back( spP0 ); m_polynomials.push_back( spP1 ); }; }; } }
[ "bordac6@uniba.sk" ]
bordac6@uniba.sk
b7e0296a0c2bb4ca51f15887f5edd4e39674a0c3
74eca3c14f658e34bc9dba8368d4e6e1e4fb1d5d
/DS_ALGO_PROJECT/DS_ALGO_PROJECT/Dynamic_Graph.cpp
e8d265a7a047013b6c9cb0a4c4beade3ae88bd5d
[]
no_license
Bilchuk/Test2
ead1ca778b3e6ad5a8f2c0598dc7236e0b6529ce
ea51bf74435e486700b782cc51fa09dc9dc7578a
refs/heads/master
2020-11-29T01:54:18.141036
2019-12-24T17:52:19
2019-12-24T17:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
73
cpp
// // Created by rom_k on 23-Dec-19. // #include "Dynamic_Graph.h"
[ "noreply@github.com" ]
noreply@github.com
172cd368018f39110f4908ca52f25275acbe1677
03f12cf9df09e302a009363b5d39a58cc654d1cb
/util/file_utils.cpp
a6ffa7972e1942dbdb0f6a8dc8455544be14b5cc
[]
no_license
cfreebuf/prediction
35b3596214468d5f304edfc422a8892fa48044f3
3feb5d416ac0f672105f909c2062fc50e994043c
refs/heads/master
2020-09-05T02:14:17.031785
2019-11-07T08:51:22
2019-11-07T08:51:22
219,954,447
0
0
null
null
null
null
UTF-8
C++
false
false
2,607
cpp
// CopyRight 2019 360. All rights reserved. // File file_utils.cpp // Date 2019-10-28 16:32:37 // Brief #include "util/file_utils.h" #include <sys/types.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <dirent.h> #include <fstream> namespace prediction { namespace util { std::vector<std::string> FileUtils::ListDir(const std::string& dir_name) { char buf[512] = { '\0' }; memset(buf, 0, sizeof(buf)); std::vector<std::string> res; DIR* dir; struct dirent* ptr; dir = opendir(dir_name.c_str()); if (dir != NULL) { while ((ptr = readdir(dir)) != NULL) { if (std::string(".") == ptr->d_name || std::string("..") == ptr->d_name) { continue; } // FIXME(lidm):check! // std::string path = dir_name + "/" + std::string(ptr->d_name); snprintf(buf, sizeof(buf), "%s/%s", dir_name.c_str(), ptr->d_name); std::string path = buf; // LOG_DEBUG("list file path:%s file:%s path:%s", // dir_name.c_str(), ptr->d_name, path.c_str()); res.push_back(path); } closedir(dir); } else { // LOG_WARNING("open dir [%s] error, errorno=%d", dir_name.c_str(), errno); } return res; } std::string FileUtils::BaseName(const std::string& file_name) { // return std::string(basename((char*)file_name.c_str())); std::string f = basename((char*)file_name.c_str()); auto it = f.find('.'); if (it != std::string::npos) { return f.substr(0, it); } else { return f; } } bool FileUtils::FileExists(const std::string& file_name) { if (access(file_name.c_str(), R_OK|W_OK|F_OK) != -1) { return true; } return false; } int FileUtils::SaveFile(const std::string& file_name, const char* buf, int len) { if (file_name.empty() || !buf || len <= 0) return -1; FILE* f = fopen(file_name.c_str(), "w+"); if (f == NULL) { return -1; } fwrite(buf, len, 1, f); fclose(f); return 0; } int FileUtils::CopyFile(const std::string& srcfile, const std::string& newfile) { std::ifstream in; std::ofstream out; in.open(srcfile.c_str()); if (in.fail()) { in.close(); out.close(); return -1; } out.open(newfile.c_str(), std::ios::trunc); if (out.fail()) { out.close(); in.close(); return -1; } else { out << in.rdbuf(); out.close(); in.close(); return 0; } } } // namespace util } // namespace prediction
[ "cfreebuf@icloud.com" ]
cfreebuf@icloud.com
6bd99feeeeef707002cfd5cf636ffae90f5d1cbc
e66a1727ee6ffb55eccd535a7498834585dcb6a8
/trafficlights/unittest.h
0d21418b090392f8eb5f3478be2d5439a2783c4a
[]
no_license
maunhb/trafficlights
5abd413638c0b8ce1c6ed639a522157a630142d1
ea849568641bca809f6b70e6fc5428d402df917e
refs/heads/master
2021-10-23T08:07:53.211295
2019-03-15T11:46:37
2019-03-15T11:46:37
174,554,834
0
0
null
null
null
null
UTF-8
C++
false
false
131
h
#ifndef UNITTEST_H #define UNITTEST_H //#include<gtest/gtest.h> class unittest { public: unittest(); }; #endif // UNITTEST_H
[ "lottie.d.roman@gmail.com" ]
lottie.d.roman@gmail.com
772c9d2e63f11c249d844d06e34699e899cd260b
2ef6a773dd5288e6526b70e484fb0ec0104529f4
/acm.timus.ru/C. Lemon Tale/Memory_limit exceeded_1443572.cpp
fc83a516c2167ab0580eba540f92a6f13d61f88c
[]
no_license
thebeet/online_judge_solution
f09426be6b28f157b1e5fd796c2eef99fb9978d8
7e8c25ff2e1f42cc9835e9cc7e25869a9dbbc0a1
refs/heads/master
2023-08-31T15:19:26.619898
2023-08-28T10:51:24
2023-08-28T10:51:24
60,448,261
1
0
null
null
null
null
UTF-8
C++
false
false
1,158
cpp
#include <stdio.h> #include <memory.h> #define d 1000000 long hp[10011][1000]; void hp_double(long p1,long p2) { long i; for (i=1;i<=hp[p1][0];i++) hp[p2][i]=hp[p1][i]+hp[p1][i]; hp[p2][0]=hp[p1][0]; for (i=1;i<=hp[p2][0];i++) if (hp[p2][i]>=d) { hp[p2][i]-=d; hp[p2][i+1]++; } while (hp[p2][hp[p2][0]+1]>0) hp[p2][0]++; } void hp_dec_hp(long p1,long p2) { long i; for (i=1;i<=hp[p1][0];i++) hp[p1][i]-=hp[p2][i]; for (i=1;i<=hp[p1][0];i++) if (hp[p1][i]<0) { hp[p1][i]+=d; hp[p1][i+1]--; } while (hp[p1][hp[p1][0]]==0) hp[p1][0]--; } void out(long p1) { long i; printf("%d",hp[p1][hp[p1][0]]); for (i=hp[p1][0]-1;i>0;i--) { if (hp[p1][i]<100000) printf("0"); if (hp[p1][i]<10000) printf("0"); if (hp[p1][i]<1000) printf("0"); if (hp[p1][i]<100) printf("0"); if (hp[p1][i]<10) printf("0"); printf("%d",hp[p1][i]); } printf("\n"); } int main() { long i,n,m,t; scanf("%d%d",&n,&m); memset(hp,0,sizeof(hp)); hp[0][0]=1; hp[0][1]=1; t=0; for (i=1;i<=m+1;i++) hp_double(i-1,i); hp[m+1][1]--; for (i=m+2;i<=n;i++) { hp_double(i-1,i); hp_dec_hp(i,t); t++; } out(n); return 0; }
[ "项光特" ]
项光特
6c9067b8aa263f3760e45f2d35a764f903ef412b
977fe6d2f721ca965676d0d4f9080d5324d17db4
/raymini/RotationMatrix.h
cfba9acfd79609cd8869912bca94426f6af16853
[]
no_license
pierr/Projet3D
4001471ff7704c561e9f821e3974545270f8bac9
0ce12aa16bc29f8d411a80d51916dd39406c1f26
refs/heads/master
2021-01-23T14:47:49.236743
2011-05-08T14:37:56
2011-05-08T14:37:56
1,589,189
2
1
null
null
null
null
UTF-8
C++
false
false
936
h
/* * RotationMatrix.h * * Created on: 27 avril 2011 * Author: pierr */ #ifndef ROTATIONMATRIX_H_ #define ROTATIONMATRIX_H_ #include "Matrix.h" #include <cmath> #include "Vec3D.h" class RotationMatrix: public Matrix { public: double teta; RotationMatrix(double _teta, Matrix::Axis axis); RotationMatrix(double _teta, Vec3Df axis); RotationMatrix( double l0v0,double l0v1, double l0v2, double l0v3, double l1v0,double l1v1, double l1v2, double l1v3, double l2v0,double l2v1, double l2v2, double l2v3, double l3v0,double l3v1, double l3v2, double l3v3, double _teta ); virtual ~RotationMatrix(); private: void initAxisX(double teta); void initAxisY(double teta); void initAxisZ(double teta); void initAxisOther(double teta); }; #endif /* ROTATIONMATRIX_H_ */
[ "pierre.besson7@gmail.com" ]
pierre.besson7@gmail.com
b8327c19632f6e4f603dbb0712643fd8ad3990ab
8c7af9fedd99d385089aa13d9cfb6c932a64aac1
/MFC14-2/MFC14-2/MyDlg0.cpp
8042f83f1311ada33a1d4af3b15361d0d08f3c70
[]
no_license
zhang1-meili/Test2
9355592fc11ec75ebfc863e2d92a791ee813031c
676db7f31192bbaa74a3bd8bd60350dcf004e294
refs/heads/master
2021-05-23T20:00:20.265851
2020-05-26T07:47:48
2020-06-02T06:21:23
253,441,721
0
0
null
null
null
null
GB18030
C++
false
false
537
cpp
// MyDlg0.cpp : 实现文件 // #include "stdafx.h" #include "MFC14-2.h" #include "MyDlg0.h" #include "afxdialogex.h" // MyDlg0 对话框 IMPLEMENT_DYNAMIC(MyDlg0, CDialogEx) MyDlg0::MyDlg0(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_DIALOG1, pParent) , r1(0) , r2(0) { } MyDlg0::~MyDlg0() { } void MyDlg0::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, r1); DDX_Text(pDX, IDC_EDIT2, r2); } BEGIN_MESSAGE_MAP(MyDlg0, CDialogEx) END_MESSAGE_MAP() // MyDlg0 消息处理程序
[ "1031601344@qq.com" ]
1031601344@qq.com
495e507c66d48b7af8f6d2012dad6ce3a242abeb
a3aea84503dc87243efc317e21b93c86f07c3f40
/2020_Exercise_Files/Chap08/time.cpp
d2d63e1e59443a9a75a5bb49a94745a2a016cf3b
[]
no_license
krishnakumarg1984/Cpp_Essential_Training_Bill_Weinman
84bf4f922ac46a2fd8b478984caaaa6239465379
37f7087ee6e4a82ba9c245fe29f943677c63e92d
refs/heads/master
2021-06-17T02:37:12.056790
2021-04-13T15:56:43
2021-04-13T15:56:43
194,319,121
0
1
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
// time.cpp by Bill Weinman <http://bw.org/> // updated 2002-06-24 #include <cstdio> #include <ctime> int main() { const static size_t bufsize = 128; time_t t = time(nullptr); // the current time printf("On this system, size of time_t is %ld bits.\n", sizeof(time_t) * 8); struct tm gmt = *gmtime(&t); // structured time in GMT struct tm localt = *localtime(&t); // structured time local printf("direct from struct tm:\n"); printf("universal time is now %04d-%02d-%02d %02d:%02d:%02d\n", gmt.tm_year + 1900, gmt.tm_mon + 1, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec); printf("local time is now %04d-%02d-%02d %02d:%02d:%02d\n", localt.tm_year + 1900, localt.tm_mon + 1, localt.tm_mday, localt.tm_hour, localt.tm_min, localt.tm_sec); char buf[bufsize]; // buffer for strftime size_t len = strftime(buf, bufsize, "%Y-%m-%d %H:%M:%S", &gmt); printf("from strftime (gmt):\n"); printf("universal time is now %s (%ld characters)\n", buf, len); len = strftime(buf, bufsize, "%Y-%m-%d %H:%M:%S %Z", &localt); printf("from strftime (localt):\n"); printf("local time is now %s (%ld characters)\n", buf, len); return 0; }
[ "krishna.kumar@ucl.ac.uk" ]
krishna.kumar@ucl.ac.uk
5ca263f9fa17e9435dd49b0c5a79ad960d56f305
e3e9afeb5297c47925408626e8482c37295185da
/Algorithm/과제1(Bowling Score)/bowling.cpp
584409b15270c1e0bc1a74133b067c5309e41369
[]
no_license
dkdlel/DongA-University
4424874a8d1c05493ac4a605ae0bd322b8510ece
3e69b7f566efaeba0db1f9c49517417116a22da5
refs/heads/master
2023-02-27T02:29:04.790015
2021-02-06T16:18:17
2021-02-06T16:18:17
230,419,155
0
0
null
null
null
null
UTF-8
C++
false
false
1,749
cpp
#include<bits/stdc++.h> using namespace std; ifstream fcin("bowling.inp"); ofstream fcout("bowling.out"); typedef struct score { int first, second, third; }score; class Bowling { public: vector<score> board; int total_score; void reset(); void Input(); void Cal_Score(); }; void Bowling::reset() { board.resize(10); for (int i = 0; i < 10; i++) { board[i].first = board[i].second = board[i].third = -1; } } void Bowling::Input() { for (int i = 0; i < 10; i++) { int num; fcin >> num; board[i].first = num; if (num != 10) { // not strike fcin >> num; board[i].second = num; } if (board[9].first == 10) { fcin >> num; board[i].second = num; fcin >> num; board[i].third = num; } if (board[9].first + board[9].second == 10) { // last frame fcin >> num; board[i].third = num; } } } void Bowling::Cal_Score() { total_score = 0; for (int i = 0; i < 9; i++) { int cnt = 0, tmp = 0; if (board[i].first == 10) { // strike for (int j = i + 1; ; j++) { if (board[j].first != -1) { cnt++; tmp += board[j].first; } if (cnt == 2) break; if (board[j].second != -1) { cnt++; tmp += board[j].second; } if (cnt == 2) break; } total_score += tmp + 10; } else if (board[i].first + board[i].second == 10) { // spare total_score += board[i + 1].first + 10; } else { // etc total_score += board[i].first + board[i].second; } } total_score += board[9].first + board[9].second; if (board[9].third != -1) total_score += board[9].third; fcout << total_score << "\n"; } int main() { Bowling bowling; int total; fcin >> total; for (int i = 0; i < total; i++) { bowling.reset(); bowling.Input(); bowling.Cal_Score(); } return 0; }
[ "leejj1082@icloud.com" ]
leejj1082@icloud.com
c239e38b3295149e55a46d08bb23f450c27a87ed
05d0cdf14776f0ba714996d86ef92e4fef50516a
/libs/directag/pwiz-src/pwiz/data/msdata/obo.hpp
b621e5a450839454046e505dac13e196b23d3ea7
[ "MIT", "Apache-2.0" ]
permissive
buotex/BICEPS
5a10396374da2e70e262c9304cf9710a147da484
10ed3938af8b05e372758ebe01dcb012a671a16a
refs/heads/master
2020-05-30T20:20:55.378536
2014-01-06T21:31:56
2014-01-06T21:31:56
1,382,740
2
2
null
null
null
null
UTF-8
C++
false
false
2,057
hpp
// // obo.hpp // // // Original author: Darren Kessner <Darren.Kessner@cshs.org> // // Copyright 2007 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef _OBO_HPP_ #define _OBO_HPP_ #include "utility/misc/Export.hpp" #include <vector> #include <string> #include <limits> namespace pwiz { namespace msdata { /// a single controlled vocabulary term struct PWIZ_API_DECL Term { typedef unsigned int id_type; typedef std::vector<id_type> id_list; std::string prefix; id_type id; std::string name; std::string def; id_list parentsIsA; id_list parentsPartOf; std::vector<std::string> exactSynonyms; bool isObsolete; Term() : id(std::numeric_limits<int>::max()), isObsolete(false) {} }; /// /// Represents a selectively parsed OBO file. /// /// Note that the following are currently ignored during parsing: /// - comments /// - dbxrefs /// - synonym tags other than exact_synonym /// - non-Term stanzas /// - obsolete Terms /// struct PWIZ_API_DECL OBO { std::string filename; std::vector<std::string> header; std::string prefix; // e.g. "MS", "UO" std::vector<Term> terms; OBO(){} OBO(const std::string& filename); }; PWIZ_API_DECL std::ostream& operator<<(std::ostream& os, const Term& term); PWIZ_API_DECL std::ostream& operator<<(std::ostream& os, const OBO& obo); } // namespace msdata } // namespace pwiz #endif // _OBO_HPP_
[ "Buote.Xu@gmail.com" ]
Buote.Xu@gmail.com
72ff2880f66a00f5070962c5f890493e96ba2b26
8a57eb0993bdd61746246c815faae725b22e9547
/src/net_processing.h
78b1ca090577dd64678286ce5e5f774e6e2d0ef0
[ "MIT" ]
permissive
bastiencaillot/BitcoinCloud
1596b9be8c8a3a5afba852dfbcc2d1dc89282978
c519c4e87e80330fa23eb68d63c6a2d387507261
refs/heads/master
2022-02-13T23:21:16.217680
2019-07-23T12:52:20
2019-07-23T12:52:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,716
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOINCLOUD_NET_PROCESSING_H #define BITCOINCLOUD_NET_PROCESSING_H #include <net.h> #include <validationinterface.h> #include <consensus/params.h> /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */ static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100; /** Default number of orphan+recently-replaced txn to keep around for block reconstruction */ static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN = 100; /** Default for BIP61 (sending reject messages) */ static constexpr bool DEFAULT_ENABLE_BIP61 = true; class PeerLogicValidation final : public CValidationInterface, public NetEventsInterface { private: CConnman* const connman; public: explicit PeerLogicValidation(CConnman* connman, CScheduler& scheduler, bool enable_bip61); /** * Overridden from CValidationInterface. */ void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected, const std::vector<CTransactionRef>& vtxConflicted) override; /** * Overridden from CValidationInterface. */ void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override; /** * Overridden from CValidationInterface. */ void BlockChecked(const CBlock& block, const CValidationState& state) override; /** * Overridden from CValidationInterface. */ void NewPoWValidBlock(const CBlockIndex* pindex, const std::shared_ptr<const CBlock>& pblock) override; /** Initialize a peer by adding it to mapNodeState and pushing a message requesting its version */ void InitializeNode(CNode* pnode) override; /** Handle removal of a peer by updating various state and removing it from mapNodeState */ void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) override; /** * Process protocol messages received from a given node * * @param[in] pfrom The node which we have received messages from. * @param[in] interrupt Interrupt condition for processing threads */ bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override; /** * Send queued protocol messages to be sent to a give node. * * @param[in] pto The node which we are sending messages to. * @return True if there is more work to be done */ bool SendMessages(CNode* pto) override EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing); /** Consider evicting an outbound peer based on the amount of time they've been behind our tip */ void ConsiderEviction(CNode* pto, int64_t time_in_seconds); /** Evict extra outbound peers. If we think our tip may be stale, connect to an extra outbound */ void CheckForStaleTipAndEvictPeers(const Consensus::Params& consensusParams); /** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */ void EvictExtraOutboundPeers(int64_t time_in_seconds); private: int64_t m_stale_tip_check_time; //! Next time to check for stale tip /** Enable BIP61 (sending reject messages) */ const bool m_enable_bip61; }; struct CNodeStateStats { int nMisbehavior = 0; int nSyncHeight = -1; int nCommonHeight = -1; std::vector<int> vHeightInFlight; }; /** Get statistics from node state */ bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats); #endif // BITCOINCLOUD_NET_PROCESSING_H
[ "dev@bitcoincloud.email" ]
dev@bitcoincloud.email
fc906969b98601ab82110a5dc3e76765f5a961f1
9b7fd21af089f96b07e0f3e7bbcea0ec99c69b30
/src/ofApp.cpp
227d2fce8b12025c0b129aae25b0600ee88babf8
[]
no_license
ebernitsas/RebelBot
2a180f5a9da9d271818d468c29627d0ac11cd844
45dbd12418f46b7729aeefe48f53f9240b03e056
refs/heads/master
2021-01-09T21:45:47.988081
2016-02-22T06:54:42
2016-02-22T06:54:42
52,252,965
0
0
null
null
null
null
UTF-8
C++
false
false
14,378
cpp
#include "ofApp.h" string codes[36] = {"01", "1000", "1010", "100", "0", "0010", "110", "0000", "00", "0111", "101", "0100", "11", "10", "111", "0110", "1101", "010", "000", "1", "001", "0001", "011", "1001", "1011", "1100", "01111", "00111", "00011", "00001", "00000", "10000", "11000", "11100", "11110", "11111"}; char letters[36] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; string msg; //establish message string reversemsg; int unit = 10; int xStart = 50; int yStart = 300; //-------------------------------------------------------------- void ofApp::setup(){ //------------Serial Setup-------------// ofSetVerticalSync(true); bSendSerialMessage = false; ofBackground(255); ofSetLogLevel(OF_LOG_VERBOSE); font.load("DIN.otf", 14); serial.listDevices(); vector <ofSerialDeviceInfo> deviceList = serial.getDeviceList(); // this should be set to whatever com port your serial device is connected to. // (ie, COM4 on a pc, /dev/tty.... on linux, /dev/tty... on a mac) // arduino users check in arduino app.... int baud = 9600; //serial.setup(0, baud); //open the first device //serial.setup("COM4", baud); // windows example serial.setup("/dev/tty.usbmodem1411", baud); // mac osx example //serial.setup("/dev/ttyUSB0", baud); //linux example //------------------------------------// ofSetColor(100,0,0); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ int x = xStart; int y = yStart; int offset = 0; //msg += ""; //msg += "nBytes read " + ofToString(nBytesRead) + "\n"; font.drawString(msg, 50, 200); for (int i = 0; i < msg.length(); i++){ offset++; for (int j = 0; j <=36; j++){ if (letters[j] == msg[i]){ if ((x + unit*i + offset*unit + unit*codes[j].length()*2) > ofGetWindowWidth() - 100){ x = 0; y += 100; offset = 0; } for (int k = 0; k < codes[j].length(); k++){ if (codes[j][k] == '0'){ offset++; ofDrawCircle(x + unit*i + offset*unit , y, unit/2); offset++; } else { offset++; ofDrawRectangle(x + unit*i + offset*unit, y-unit/2, unit*3, unit); offset += 3; } } } } if (msg[i] == ' '){ offset += 3; //cout << "space" << endl; } } } //-------------------------------------------------------------- string ofxGetSerialString(ofSerial &serial, char until) { static string str; stringstream ss; char ch; int ttl=1000; while ((ch=serial.readByte())>0 && ttl-->0 && ch!=until) { ss << ch; } str+=ss.str(); if (ch==until) { string tmp=str; str=""; return tmp; } else { return ""; } } //-------------------------------------------------------------- void ofApp::keyPressed (int key){ if (isalpha(key) || isdigit(key) || (key ==S ' ')){ ofSetColor(100,0,0); msg += key; } else if (key == 127){ //delete button msg.pop_back(); } else if (key == 13) { //enter int len = msg.length() - 1; for(int i = 0; i <= len; i++){ reversemsg += msg[len - i]; } writingSerial(serial); ofSetColor(0,0,200); cout << "enter" << " " << reversemsg << endl; } else if (key == 61){ //plus sign //writingSerial(serial); string x = ofxGetSerialString(serial, '@'); cout << x << endl; } cout << key << endl; } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::writingSerial(ofSerial &serial){ //0 = dot //1 = line //2 = letter over //3 = word space cout << reversemsg << " message" << reversemsg.length() << endl; for (int i = 0; i < reversemsg.length(); i++){ switch(reversemsg[i]){ case('a'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('b'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('c'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('d'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('e'): serial.writeByte('0'); serial.writeByte('2'); break; case('f'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('g'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('h'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('i'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('j'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('k'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('l'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('m'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('n'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('o'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('p'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('q'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('r'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('s'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('t'): serial.writeByte('1'); serial.writeByte('2'); break; case('u'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('v'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('w'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('x'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('y'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('z'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('0'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('1'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('2'); break; case('2'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('3'): serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('4'): serial.writeByte('1'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('5'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('2'); break; case('6'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('2'); break; case('7'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('8'): serial.writeByte('0'); serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case('9'): serial.writeByte('0'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('1'); serial.writeByte('2'); break; case(' '): serial.writeByte('3'); break; } serial.writeByte('#'); serial.writeByte('%'); //signify end } } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "ebernitsas@gmail.com" ]
ebernitsas@gmail.com
0242cd0cb4aff04240b9fd113da3e438c1b99ada
2927e5cf4ba72ce038457477cb0bc92aaf25c76f
/problemQueen.cpp
15ff1dbd8a86076b80b898f31476be0cb88b8b2e
[]
no_license
phooeniix/algorithms
0a47ef976f9be881963127dc4da14a7f9d7e02cb
cb360fe5bbd10757e0415b1228406d16dffef7ef
refs/heads/master
2021-01-17T13:35:50.965808
2017-03-06T13:43:22
2017-03-06T13:43:22
84,076,366
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include <iostream> #include <cmath> using namespace std; int main(){ unsigned long int totalGraos=1; totalGraos=1; for (int i=0; i<63;i++){ totalGraos+= pow(2,i); // cout<<totalGraos; } cout<<"A rainha pagará no total "<<totalGraos; return 0; }
[ "ahcarvalho01@gmail.com" ]
ahcarvalho01@gmail.com
6147a64894c85b921bd99fba0e0676c8d9f421fc
af5f45b32f0c1bea15cb8541f2634e8e9bff07fc
/include/abb_libegm/egm_common.h
bd0e32a57551c5cda468b2abcd641dfd1ab587c3
[ "BSD-3-Clause" ]
permissive
liangdt98/abb_libegm
d2b44e373f05ff0c9a6366e225c74335909fa335
5efd20a32456f5bdc78e0fda56261ddb44e0e1a5
refs/heads/master
2021-03-28T13:57:29.449792
2020-03-13T07:25:56
2020-03-13T07:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,484
h
/*********************************************************************************************************************** * * Copyright (c) 2015, ABB Schweiz AG * 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 ABB 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. * *********************************************************************************************************************** */ #ifndef EGM_COMMON_H #define EGM_COMMON_H #include "abb_libegm_export.h" namespace abb { namespace egm { /** * \brief Enum for the number of axes of the robot. */ enum RobotAxes { Six = 6, ///< \brief A six axes robot. Seven = 7 ///< \brief A seven axes robot. }; /** * \brief Enum for the supported EGM modes (i.e. the corresponding RAPID instructions). */ enum EGMModes { EGMJoint, ///< \brief The EGM joint mode. EGMPose ///< \brief The EGM pose mode. }; /** * \brief Struct containing various constant values. */ struct Constants { /** * \brief Constants related to the robot controller system. */ struct ABB_LIBEGM_EXPORT RobotController { /** * \brief Lowest sample time [s] used in EGM communication. */ static const double LOWEST_SAMPLE_TIME; /** * \brief Default port number assumed for EGM communication. */ static const unsigned short DEFAULT_PORT_NUMBER; /** * \brief Default number of robot joints. */ static const int DEFAULT_NUMBER_OF_ROBOT_JOINTS; /** * \brief Default number of external joints. */ static const int DEFAULT_NUMBER_OF_EXTERNAL_JOINTS; /** * \brief Maximum number of joints. */ static const int MAX_NUMBER_OF_JOINTS; }; /** * \brief Constants related to the conversions between units. */ struct ABB_LIBEGM_EXPORT Conversion { /** * \brief Conversion value from radians to degrees. */ static const double RAD_TO_DEG; /** * \brief Conversion value from degrees to radians. */ static const double DEG_TO_RAD; /** * \brief Conversion value from millimeter to meter. */ static const double MM_TO_M; /** * \brief Conversion value from milliseconds to seconds. */ static const double MS_TO_S; /** * \brief Conversion value from seconds to microseconds. */ static const double S_TO_US; }; }; /** * \brief Struct for an EGM user interface's base configuration. */ struct BaseConfiguration { /** * \brief Default constructor. */ BaseConfiguration() : axes(Six), use_demo_outputs(false), use_velocity_outputs(false), use_logging(false), max_logging_duration(60.0) {} /** * \brief Value specifying if a six or seven axes robot is used. * * Note: If set to a seven axes robot, then an implicit mapping of joint values is performed. */ RobotAxes axes; /** * \brief Flag indicating if demo outputs should be used. * * Note: Overrides any other execution mode. Mainly used to verify that the EGM communication channel * works as intended. */ bool use_demo_outputs; /** * \brief Flag indicating if the messages, sent to the robot controller, should include velocity outputs. * * Note: If set to false, then no velocity values are sent (they are optional). */ bool use_velocity_outputs; /** * \brief Flag indicating if the interface should log data. */ bool use_logging; /** * \brief Maximum duration [s] to log data. */ double max_logging_duration; }; /** * \brief Struct for the EGM trajectory user interface's configuration. */ struct TrajectoryConfiguration { /** * \brief Enum for the available spline ploynomial interpolation methods. * * Note: Cartesian orientation uses Slerp interpolation instead. * * Boundary conditions (between trajectory points): * | * |--Linear: * | |-- Start and goal positions. * | * |--Square: * | |-- Start and goal positions. * | |-- Start velocity. * | * |--Cubic: * | |-- Start and goal positions. * | |-- Start and goal velocities. * | * |--Quintic: * |-- Start and goal positions. * |-- Start and goal velocities. * |-- Start and goal accelerations. */ enum SplineMethod { Linear, ///< \brief Use a first degree polynomial. Square, ///< \brief Use a second degree polynomial. Cubic, ///< \brief Use a third degree polynomial Quintic ///< \brief Use a fifth degree polynomial. }; /** * \brief A constructor. * * \param base_configuration specifying the base configurations. */ TrajectoryConfiguration(const BaseConfiguration& base_configuration = BaseConfiguration()) : base(base_configuration), spline_method(Quintic) {} /** * \brief The base configurations. */ BaseConfiguration base; /** * \brief Value specifying which spline method to use in the interpolation. */ SplineMethod spline_method; }; } // end namespace egm } // end namespace abb #endif // EGM_COMMON_H
[ "jon.tjerngren@se.abb.com" ]
jon.tjerngren@se.abb.com
9ea0d417c2cb3f9f5d01dbfe20ea7f397e1498e9
c23b42b301b365f6c074dd71fdb6cd63a7944a54
/contest/ASC/ASC31/a.cpp
8b74784518482d371b1380dc2ec4482204b2a23c
[]
no_license
NTUwanderer/PECaveros
6c3b8a44b43f6b72a182f83ff0eb908c2e944841
8d068ea05ee96f54ee92dffa7426d3619b21c0bd
refs/heads/master
2020-03-27T22:15:49.847016
2019-01-04T14:20:25
2019-01-04T14:20:25
147,217,616
1
0
null
2018-09-03T14:40:49
2018-09-03T14:40:49
null
UTF-8
C++
false
false
892
cpp
#include <bits/stdc++.h> using namespace std; #define N 55 int n , m , s; double ans; void init(){ cin >> n >> m >> s; //n = 50; //m = 20; //s = 100; } double dp[ N ] , ndp[ N ] , win[ N ]; int p[ N ] , w[ N ]; void cal(){ dp[ n + 1 ] = 1.; for( int i = 0 ; i < 1e5 ; i ++ ){ for( int j = 1 ; j <= n ; j ++ ) for( int k = 0 ; k < m ; k ++ ){ double bst = win[ k ] * dp[ min( n + 1 , j + w[ k ] ) ] + ( 1 - win[ k ] ) * dp[ j - 1 ]; dp[ j ] = max( dp[ j ] , bst ); } } ans = dp[ n ]; } void solve(){ for( int i = 0 ; i < m ; i ++ ){ cin >> p[ i ] >> w[ i ]; //p[ i ] = 50; //w[ i ] = 2; win[ i ] = (double)p[ i ] / s; } cal(); printf( "%.12f\n" , ans ); } int main(){ #ifdef ONLINE_JUDGE freopen( "casino.in" , "r" , stdin ); freopen( "casino.out" , "w" , stdout ); #endif init(); solve(); }
[ "c.c.hsu01@gmail.com" ]
c.c.hsu01@gmail.com
8ddd21d7e7be7bd576fd0597553a615dddb81de4
5e4e2ae5c863dee1003c064ef70d74c9165fc65e
/h_rank/staircase.cpp
417444c4b096fa052e75391e3a668b18c3af04b0
[]
no_license
rootid/fft
3ec6f0e6ae1be96d531119b2571610646a7256e9
af187df0eafee37f69d6be95dc22685a96b96742
refs/heads/master
2020-12-14T09:24:18.915482
2019-07-25T23:52:21
2019-07-25T23:52:21
46,454,112
1
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
#include<iostream> using namespace std; //https://www.hackerrank.com/challenges/staircase //Problem Statement // //Your teacher has given you the task of drawing a staircase structure. Being //an expert programmer, you decided to make a program to draw it for you //instead. Given the required height, can you print a staircase as shown in the //example? // //Input //You are given an integer N depicting the height of the staircase. // //Output //Print a staircase of height N that consists of # symbols and spaces. For //example for N=6, here's a staircase of that height: // // # // ## // ### // #### // ##### //###### //Note: The last line has 0 spaces before it. int main () { int n cin >> n; for (int i=1;i<=n;i++) { for (int k=1;k<=(n-i);k++) { cout << " "; } for (int j=1;j<=i;j++) { cout << "#"; } cout << endl; } return 0; }
[ "vsinhsawant@gmail.com" ]
vsinhsawant@gmail.com
edfa3f9b62b521e2ef594e47c15a67d1c81a4ac1
e1567f40e50c50b17b9da2c9a532553e2adf3ee3
/PuyoPuyo FINAL/PuyoPuyo/State.cpp
b56853200063b433eb08d66b8027c9be3341a1a6
[]
no_license
leninP93/PPuyo
f9a1c1a4b80297b9065078d6bf30f136a9b588f0
eca1bb9afb7dc2656865ffd0028dc3a0e4be74a2
refs/heads/master
2021-01-22T08:28:33.123132
2017-05-27T18:48:14
2017-05-27T18:48:14
92,617,748
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
#include "State.h" State::State() { init(); } State::~State() { FreeText(); } bool State::update(std::string textureText) { const Uint8 *keys = SDL_GetKeyboardState(NULL); textoOver->loadFromRenderedText(50, 10, textureText); if (keys[SDL_SCANCODE_RETURN]) { return true; } else return false; } void State::draw() { textoOver->Draw(); } void State::FreeText() { if (textoOver) { delete textoOver; textoOver = NULL; } } void State::init() { textoOver = new Label(); }
[ "lenin_66@hotmail.com" ]
lenin_66@hotmail.com
fa0cdf6c3988af7efc42ced1e14deb6e373699bd
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/admin/snapin/eventlog/src/filter.cxx
66ac2d5ac475ef9d8a9417efdedb47f298a0363d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
30,803
cxx
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 1997. // // File: filter.cxx // // Contents: Filter property sheet page. // // Classes: CFilterPage // // History: 12-19-1996 DavidMun Created // //--------------------------------------------------------------------------- #include "headers.hxx" #pragma hdrstop #define MAX_STATIC_TEXT_STRING MAX_PATH DEBUG_DECLARE_INSTANCE_COUNTER(CFilter) DEBUG_DECLARE_INSTANCE_COUNTER(CFilterPage) static ULONG s_aulHelpIds[] = { filter_from_lbl, Hfilter_from_lbl, filter_from_combo, Hfilter_from_combo, filter_from_date_dp, Hfilter_from_date_dp, filter_from_time_dp, Hfilter_from_time_dp, filter_to_lbl, Hfilter_to_lbl, filter_to_combo, Hfilter_to_combo, filter_to_date_dp, Hfilter_to_date_dp, filter_to_time_dp, Hfilter_to_time_dp, filter_types_grp, Hfilter_types_grp, filter_information_ckbox, Hfilter_information_ckbox, filter_warning_ckbox, Hfilter_warning_ckbox, filter_error_ckbox, Hfilter_error_ckbox, filter_success_ckbox, Hfilter_success_ckbox, filter_failure_ckbox, Hfilter_failure_ckbox, filter_source_lbl, Hfilter_source_lbl, filter_source_combo, Hfilter_source_combo, filter_category_lbl, Hfilter_category_lbl, filter_category_combo, Hfilter_category_combo, filter_user_lbl, Hfilter_user_lbl, filter_user_edit, Hfilter_user_edit, filter_computer_lbl, Hfilter_computer_lbl, filter_computer_edit, Hfilter_computer_edit, filter_eventid_lbl, Hfilter_eventid_lbl, filter_eventid_edit, Hfilter_eventid_edit, filter_clear_pb, Hfilter_clear_pb, filter_view_lbl, Hfilter_view_lbl, 0,0 }; //=========================================================================== // // CFilter implementation // //=========================================================================== //+-------------------------------------------------------------------------- // // Member: CFilter::CFilter // // Synopsis: ctor // // History: 1-20-1997 DavidMun Created // //--------------------------------------------------------------------------- CFilter::CFilter() { DEBUG_INCREMENT_INSTANCE_COUNTER(CFilter); Reset(); } //+-------------------------------------------------------------------------- // // Member: CFilter::CFilter // // Synopsis: copy ctor // // History: 5-25-1999 davidmun Created // //--------------------------------------------------------------------------- CFilter::CFilter( const CFilter &ToCopy): _ulFrom(ToCopy._ulFrom), _ulTo(ToCopy._ulTo) { DEBUG_INCREMENT_INSTANCE_COUNTER(CFilter); _ulType = ToCopy._ulType; _usCategory = ToCopy._usCategory; _fEventIDSpecified = ToCopy._fEventIDSpecified; _ulEventID = ToCopy._ulEventID; lstrcpy(_wszSource, ToCopy._wszSource); lstrcpy(_wszUser, ToCopy._wszUser); lstrcpy(_wszUserLC, ToCopy._wszUserLC); lstrcpy(_wszComputer, ToCopy._wszComputer); } //+-------------------------------------------------------------------------- // // Member: CFilter::~CFilter // // Synopsis: dtor // // History: 1-20-1997 DavidMun Created // //--------------------------------------------------------------------------- CFilter::~CFilter() { DEBUG_DECREMENT_INSTANCE_COUNTER(CFilter); } //+-------------------------------------------------------------------------- // // Member: CFilter::Load // // Synopsis: Initialize from stream. // // Arguments: [pStm] - stream opened for reading // // Returns: HRESULT // // History: 3-20-1997 DavidMun Created // //--------------------------------------------------------------------------- HRESULT CFilter::Load( IStream *pStm) { HRESULT hr = S_OK; do { ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Read(&_ulType, sizeof _ulType, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(USHORT)); pStm->Read(&_usCategory, sizeof _usCategory, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(BOOL)); pStm->Read(&_fEventIDSpecified, sizeof _fEventIDSpecified, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); pStm->Read(&_ulEventID, sizeof _ulEventID, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = ReadString(pStm, _wszSource, ARRAYLEN(_wszSource)); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = ReadString(pStm, _wszUser, ARRAYLEN(_wszUser)); BREAK_ON_FAIL_HRESULT(hr); lstrcpy(_wszUserLC, _wszUser); CharLowerBuff(_wszUserLC, lstrlen(_wszUserLC)); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = ReadString(pStm, _wszComputer, ARRAYLEN(_wszComputer)); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Read(&_ulFrom, sizeof _ulFrom, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Read(&_ulTo, sizeof _ulTo, NULL); BREAK_ON_FAIL_HRESULT(hr); } while (0); return hr; } //+-------------------------------------------------------------------------- // // Member: CFilter::Save // // Synopsis: Persist this object in the stream [pStm]. // // Arguments: [pStm] - stream opened for writing // // Returns: HRESULT // // History: 3-20-1997 DavidMun Created // //--------------------------------------------------------------------------- HRESULT CFilter::Save( IStream *pStm) { HRESULT hr = S_OK; do { ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Write(&_ulType, sizeof _ulType, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(USHORT)); pStm->Write(&_usCategory, sizeof _usCategory, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(BOOL)); pStm->Write(&_fEventIDSpecified, sizeof _fEventIDSpecified, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); pStm->Write(&_ulEventID, sizeof _ulEventID, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = WriteString(pStm, _wszSource); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = WriteString(pStm, _wszUser); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(WCHAR)); hr = WriteString(pStm, _wszComputer); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Write(&_ulFrom, sizeof _ulFrom, NULL); BREAK_ON_FAIL_HRESULT(hr); ALIGN_PTR(pStm, __alignof(ULONG)); hr = pStm->Write(&_ulTo, sizeof _ulTo, NULL); BREAK_ON_FAIL_HRESULT(hr); } while (0); return hr; } //+-------------------------------------------------------------------------- // // Member: CFilter::Passes // // Synopsis: Return TRUE if [pelr] meets the restrictions set by this // filter. // // Arguments: [pResultRecs] - positioned at record to check // // Returns: TRUE or FALSE // // History: 1-11-1997 DavidMun Created // //--------------------------------------------------------------------------- BOOL CFilter::Passes( CFFProvider *pFFP) { // // For better performance, do the quicker comparisons first in // hopes of rejecting a record before the string comparisons have // to be done. // // Start with items specific to filtering. // if (FromSpecified()) { if (pFFP->GetTimeGenerated() < _ulFrom) { return FALSE; } } if (ToSpecified()) { if (pFFP->GetTimeGenerated() > _ulTo) { return FALSE; } } // // Check the items common to both filter and find // return CFindFilterBase::Passes(pFFP); } //+-------------------------------------------------------------------------- // // Member: CFilter::GetFrom // // Synopsis: Return filter from date in [pst]. // // Arguments: [pst] - filled with from date, if any. // // Returns: S_FALSE - not being filtered by from date // S_OK - [pst] contains filtered by from date value // // Modifies: *[pst] // // History: 1-20-1997 DavidMun Created // //--------------------------------------------------------------------------- HRESULT CFilter::GetFrom( SYSTEMTIME *pst) { if (!_ulFrom) { return S_FALSE; } SecondsSince1970ToSystemTime(_ulFrom, pst); return S_OK; } //+-------------------------------------------------------------------------- // // Member: CFilter::GetTo // // Synopsis: Return filter to date in [pst]. // // Arguments: [pst] - filled with to date, if any. // // Returns: S_FALSE - not being filtered by to date // S_OK - [pst] contains filtered by to date value // // Modifies: *[pst] // // History: 1-20-1997 DavidMun Created // //--------------------------------------------------------------------------- HRESULT CFilter::GetTo( SYSTEMTIME *pst) { if (!_ulTo) { return S_FALSE; } SecondsSince1970ToSystemTime(_ulTo, pst); return S_OK; } //+-------------------------------------------------------------------------- // // Member: CFilter::SetFrom // // Synopsis: Set the filter from date to [pst]. // // Arguments: [pst] - valid date, or NULL to turn off from date filtering // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilter::SetFrom( SYSTEMTIME *pst) { if (pst) { SystemTimeToSecondsSince1970(pst, &_ulFrom); } else { _ulFrom = 0; } } //+-------------------------------------------------------------------------- // // Member: CFilter::SetFrom // // Synopsis: Set the filter to date to [pst]. // // Arguments: [pst] - valid date, or NULL to turn off to date filtering // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilter::SetTo( SYSTEMTIME *pst) { if (pst) { SystemTimeToSecondsSince1970(pst, &_ulTo); } else { _ulTo = 0; } } //+-------------------------------------------------------------------------- // // Member: CFilter::Reset // // Synopsis: Clear all filtering (set members so that any event record // would pass this filter). // // History: 1-24-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilter::Reset() { CFindFilterBase::_Reset(); _ulFrom = 0; _ulTo = 0; } //=========================================================================== // // CFilterPage implementation // //=========================================================================== //+-------------------------------------------------------------------------- // // Member: CFilterPage::CFilterPage // // Synopsis: ctor // // History: 3-27-1997 DavidMun Created // //--------------------------------------------------------------------------- CFilterPage::CFilterPage( IStream *pstm, CLogInfo *pli): _pstm(pstm), _pnpa(NULL), _pli(pli) { TRACE_CONSTRUCTOR(CFilterPage); DEBUG_INCREMENT_INSTANCE_COUNTER(CFilterPage); ASSERT(_pstm); ASSERT(_pli); // // Do not unmarshal the stream here; see comments in CGeneralPage ctor // } //+-------------------------------------------------------------------------- // // Member: CFilterPage::~CFilterPage // // Synopsis: dtor // // History: 3-27-1997 DavidMun Created // //--------------------------------------------------------------------------- CFilterPage::~CFilterPage() { TRACE_DESTRUCTOR(CFilterPage); DEBUG_DECREMENT_INSTANCE_COUNTER(CFilterPage); if (_pstm) { PVOID pvnpa; HRESULT hr; hr = CoGetInterfaceAndReleaseStream(_pstm, IID_INamespacePrshtActions, &pvnpa); CHECK_HRESULT(hr); } } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_EnableDateTime // // Synopsis: Enable or disable the specified date and time datepicker // controls. // // Arguments: [FromOrTo] - FROM or TO, to indicate which set of controls // [fEnable] - TRUE to enable, FALSE to disable // // History: 1-24-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilterPage::_EnableDateTime( FROMTO FromOrTo, BOOL fEnable) { // JonN 12/04/01 500639 int iDate = (FromOrTo == FROM) ? filter_from_date_dp : filter_to_date_dp; int iTime = (FromOrTo == FROM) ? filter_from_time_dp : filter_to_time_dp; HWND hwndFocus = ::GetFocus(); if (_hCtrl(iDate) == hwndFocus || _hCtrl(iTime) == hwndFocus) { ::SetFocus(_hCtrl( (FromOrTo == FROM) ? filter_from_combo : filter_to_combo) ); } EnableWindow(_hCtrl(iDate), fEnable); EnableWindow(_hCtrl(iTime), fEnable); } VOID CFilterPage::_OnHelp( UINT message, WPARAM wParam, LPARAM lParam) { InvokeWinHelp(message, wParam, lParam, HELP_FILENAME, s_aulHelpIds); } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnInit // // Synopsis: Initialize the controls in the property sheet page. // // Arguments: [pPSP] - pointer to prop sheet page structure used to // create this. // // History: 1-24-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilterPage::_OnInit( LPPROPSHEETPAGE pPSP) { TRACE_METHOD(CFilterPage, _OnInit); // // Unmarshal the private interface // // // Unmarshal the private interface to the CComponentData object // PVOID pvnpa; HRESULT hr; hr = CoGetInterfaceAndReleaseStream(_pstm, IID_INamespacePrshtActions, &pvnpa); _pstm = NULL; if (SUCCEEDED(hr)) { _pnpa = (INamespacePrshtActions *)pvnpa; } else { DBG_OUT_HRESULT(hr); } // // Tell the cookie that there is a property page open on it // _pli->SetPropSheetWindow(_hwnd); WCHAR wszInitStr[MAX_STATIC_TEXT_STRING]; // // Stuff the comboboxes for view from/to. Note these comboboxes // do not have the CBS_SORT style, so, regardless of the locale, // the "Events On" string will always be the second string in // both comboboxes. // LoadStr(IDS_FIRST_EVENT, wszInitStr, ARRAYLEN(wszInitStr)); ComboBox_AddString(_hCtrl(filter_from_combo), wszInitStr); LoadStr(IDS_LAST_EVENT, wszInitStr, ARRAYLEN(wszInitStr)); ComboBox_AddString(_hCtrl(filter_to_combo), wszInitStr); LoadStr(IDS_EVENTS_ON, wszInitStr, ARRAYLEN(wszInitStr)); ComboBox_AddString(_hCtrl(filter_from_combo), wszInitStr); ComboBox_AddString(_hCtrl(filter_to_combo), wszInitStr); SYSTEMTIME times[2]; memset(times, 0, sizeof(times)); times[0].wYear = 1970; times[0].wMonth = 1; // January times[0].wDay = 1; times[1].wYear = 2105; times[1].wMonth = 1; // January times[1].wDay = 1; VERIFY( DateTime_SetRange( _hCtrl(filter_from_date_dp), GDTR_MIN | GDTR_MAX, times)); VERIFY( DateTime_SetRange( _hCtrl(filter_from_time_dp), GDTR_MIN | GDTR_MAX, times)); VERIFY( DateTime_SetRange( _hCtrl(filter_to_date_dp), GDTR_MIN | GDTR_MAX, times)); VERIFY( DateTime_SetRange( _hCtrl(filter_to_time_dp), GDTR_MIN | GDTR_MAX, times)); // // Set the From/To date/time controls // SYSTEMTIME st; CFilter *pFilter = _pli->GetFilter(); hr = pFilter->GetFrom(&st); if (S_FALSE == hr) { _SetFromTo(FROM, NULL); } else { _SetFromTo(FROM, &st); } hr = pFilter->GetTo(&st); if (S_FALSE == hr) { _SetFromTo(TO, NULL); } else { _SetFromTo(TO, &st); } InitFindOrFilterDlg(_hwnd, _pli->GetSources(), pFilter); } void CFilterPage::_OnSettingChange(WPARAM wParam, LPARAM lParam) { ::SendMessage(_hCtrl(filter_to_date_dp), WM_SETTINGCHANGE, wParam, lParam); ::SendMessage(_hCtrl(filter_to_time_dp), WM_SETTINGCHANGE, wParam, lParam); ::SendMessage(_hCtrl(filter_from_date_dp), WM_SETTINGCHANGE, wParam, lParam); ::SendMessage(_hCtrl(filter_from_time_dp), WM_SETTINGCHANGE, wParam, lParam); } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnSetActive // // Synopsis: Handle notification that this property page is becoming // active (visible). // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnSetActive() { TRACE_METHOD(CFilterPage, _OnSetActive); return 0; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnApply // // Synopsis: Save settings if valid, otherwise complain and prevent page // from changing. // // Returns: PSNRET_NOERROR or PSNRET_INVALID_NOCHANGEPAGE // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnApply() { TRACE_METHOD(CFilterPage, _OnApply); ULONG ulRet = PSNRET_NOERROR; if (!_IsFlagSet(PAGE_IS_DIRTY)) { Dbg(DEB_TRACE, "CFilterPage: page not dirty; ignoring Apply\n"); return PSNRET_NOERROR; } _pli->Filter(TRUE); CFilter *pFilter = _pli->GetFilter(); BOOL fOk = ReadFindOrFilterValues(_hwnd, _pli->GetSources(), pFilter); if (fOk) { _ClearFlag(PAGE_IS_DIRTY); // // If the log we're filtering is currently being displayed, then it // should be redisplayed. Ping the snapins so they can check. // g_SynchWnd.Post(ELSM_LOG_DATA_CHANGED, LDC_FILTER_CHANGE, reinterpret_cast<LPARAM>(_pli)); } else { // JonN 4/12/01 367216 // MsgBox(_hwnd, IDS_INVALID_EVENTID, MB_TOPMOST | MB_ICONERROR | MB_OK); ulRet = PSNRET_INVALID_NOCHANGEPAGE; } return ulRet; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_Validate // // Synopsis: Return TRUE if all settings on the page are valid, FALSE // otherwise. // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- BOOL CFilterPage::_Validate() { if (!_IsFlagSet(PAGE_IS_DIRTY)) { return TRUE; } CFilter *pFilter = _pli->GetFilter(); // // Get the From/To values // if (ComboBox_GetCurSel(_hCtrl(filter_from_combo))) { SYSTEMTIME stDate; SYSTEMTIME st; DateTime_GetSystemtime(_hCtrl(filter_from_date_dp), &stDate); DateTime_GetSystemtime(_hCtrl(filter_from_time_dp), &st); st.wMonth = stDate.wMonth; st.wDay = stDate.wDay; st.wYear = stDate.wYear; pFilter->SetFrom(&st); } else { pFilter->SetFrom(NULL); } if (ComboBox_GetCurSel(_hCtrl(filter_to_combo))) { SYSTEMTIME stDate; SYSTEMTIME st; DateTime_GetSystemtime(_hCtrl(filter_to_date_dp), &stDate); DateTime_GetSystemtime(_hCtrl(filter_to_time_dp), &st); st.wMonth = stDate.wMonth; st.wDay = stDate.wDay; st.wYear = stDate.wYear; pFilter->SetTo(&st); } else { pFilter->SetTo(NULL); } // // Now we can do validation. // // Enforce rule that From date <= To date // if (!pFilter->FromToValid()) { pFilter->SetFrom(NULL); pFilter->SetTo(NULL); MsgBox(_hwnd, MB_TOPMOST | IDS_INVALID_FROM_TO, MB_OK | MB_ICONERROR); return FALSE; } return TRUE; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnCommand // // Synopsis: Handle a notification that the user has touched one of the // controls. // // Arguments: [wParam] - identifies control // [lParam] - unused // // Returns: 0 // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnCommand( WPARAM wParam, LPARAM lParam) { TRACE_METHOD(CFilterPage, _OnCommand); switch (LOWORD(wParam)) { case filter_source_combo: { if (HIWORD(wParam) != CBN_SELCHANGE) { break; } _EnableApply(TRUE); // // get source value from filter combo // HWND hwndSourceCombo = _hCtrl(filter_source_combo); WCHAR wszSource[CCH_SOURCE_NAME_MAX]; ComboBox_GetText(hwndSourceCombo, wszSource, CCH_SOURCE_NAME_MAX); // // Set category combo contents according to new source, and set // category filter selection to (All). // SetCategoryCombobox(_hwnd, _pli->GetSources(), wszSource, 0); // // turn off type filtering // SetTypesCheckboxes(_hwnd, _pli->GetSources(), ALL_LOG_TYPE_BITS); break; } case filter_from_combo: case filter_to_combo: if (HIWORD(wParam) == CBN_SELCHANGE) { _EnableApply(TRUE); _EnableDateTimeControls(LOWORD(wParam)); } break; case filter_category_combo: if (HIWORD(wParam) == CBN_SELCHANGE) { _EnableApply(TRUE); } break; case filter_user_edit: case filter_computer_edit: case filter_eventid_edit: if (HIWORD(wParam) == EN_CHANGE) { _EnableApply(TRUE); } break; case filter_information_ckbox: case filter_warning_ckbox: case filter_error_ckbox: case filter_success_ckbox: case filter_failure_ckbox: _EnableApply(TRUE); break; case filter_clear_pb: _EnableApply(TRUE); _OnClear(); break; } return 0; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnClear // // Synopsis: Reset all controls to default state // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilterPage::_OnClear() { TRACE_METHOD(CFilterPage, _OnClear); // // Set the date/time for from/to to be the first and last event // times in the log. // _SetFromTo(FROM, NULL); _SetFromTo(TO, NULL); // // Reset all the controls which are common to both find and filter // ClearFindOrFilterDlg(_hwnd, _pli->GetSources()); // // Clearing the filter dirties it (this has already been done // because the above set commands generated notifications of // control changes). // } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_SetFromTo // // Synopsis: Set the combobox, date control, and time control of either // the filter from or the filter to fields. // // Arguments: [FromOrTo] - identifies which set of controls to change // [pst] - NULL or date/time value to set // // History: 4-25-1997 DavidMun Created // // Notes: If [pst] is NULL, the control is set to the oldest event // record timestamp, if filtering FROM, or the newest time- // stamp, if filtering TO. // //--------------------------------------------------------------------------- VOID CFilterPage::_SetFromTo( FROMTO FromOrTo, SYSTEMTIME *pst) { HWND hwndCombo; HWND hwndDate; HWND hwndTime; if (FromOrTo == FROM) { hwndCombo = _hCtrl(filter_from_combo); hwndDate = _hCtrl(filter_from_date_dp); hwndTime = _hCtrl(filter_from_time_dp); } else { hwndCombo = _hCtrl(filter_to_combo); hwndDate = _hCtrl(filter_to_date_dp); hwndTime = _hCtrl(filter_to_time_dp); } SYSTEMTIME st; SYSTEMTIME *pstToUse; if (pst) { pstToUse = pst; } else { HRESULT hr; if (FromOrTo == FROM) { hr = _pli->GetOldestTimestamp(&st); } else { hr = _pli->GetNewestTimestamp(&st); } if (FAILED(hr)) { GetLocalTime(&st); } pstToUse = &st; } VERIFY(DateTime_SetSystemtime(hwndDate, GDT_VALID, pstToUse)); VERIFY(DateTime_SetSystemtime(hwndTime, GDT_VALID, pstToUse)); ComboBox_SetCurSel(hwndCombo, pst != NULL); _EnableDateTime(FromOrTo, pst != NULL); } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnNotify // // Synopsis: Handle control notification // // Arguments: [pnmh] - standard notification header // // Returns: 0 // // History: 4-25-1997 DavidMun Created // // Notes: This is only necessary to detect when the user has touched // the filter from/to date or time controls. // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnNotify( LPNMHDR pnmh) { switch (pnmh->idFrom) { case filter_from_date_dp: case filter_from_time_dp: case filter_to_date_dp: case filter_to_time_dp: if (pnmh->code == DTN_DATETIMECHANGE) { _EnableApply(TRUE); } break; } return 0; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnKillActive // // Synopsis: Return bool indicating whether it is permissible for this // page to no longer be the active page. // // Returns: FALSE if page contains valid data, TRUE otherwise // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnKillActive() { TRACE_METHOD(CFilterPage, _OnKillActive); // // FALSE allows page to lose focus, TRUE prevents it. // return !_Validate(); } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnQuerySiblings // // Synopsis: Handle notification from other page. // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- ULONG CFilterPage::_OnQuerySiblings( WPARAM wParam, LPARAM lParam) { TRACE_METHOD(CFilterPage, _OnQuerySiblings); return 0; } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_OnDestroy // // Synopsis: Notify the loginfo on which this page is open that the // sheet is closing. // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilterPage::_OnDestroy() { TRACE_METHOD(CFilterPage, _OnDestroy); // // Tell cookie its prop sheet is closing // _pli->SetPropSheetWindow(NULL); } //+-------------------------------------------------------------------------- // // Member: CFilterPage::_EnableDateTimeControls // // Synopsis: Enable or disable the filter from or to date/time controls // according to the current selection in the combobox with // control id [idCombo]. // // Arguments: [idCombo] - filter_from_combo or filter_to_combo. // // History: 4-25-1997 DavidMun Created // //--------------------------------------------------------------------------- VOID CFilterPage::_EnableDateTimeControls( ULONG idCombo) { FROMTO FromOrTo; if (idCombo == filter_from_combo) { FromOrTo = FROM; } else { FromOrTo = TO; } // // If the selection is the first item, (item 0), disable the controls, // since it is either "first event" or "Last event". If it is item 1, // enable the controls, since it is "events on". // _EnableDateTime(FromOrTo, ComboBox_GetCurSel(_hCtrl(idCombo))); }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
405fb37c329b5d68808c9e7c3a8d0fedd63f4fd2
f7cff98e341bb22590c7042d84df728eeecea8f1
/2017 beijing onsite/J.cc
c806a4f7cdda8ecfa5dc9226e457cb7db04efd24
[]
no_license
thirtiseven/ACM
4a8200e235d6eb1098362d0f32d52b5a81c33b4d
5f679781dc4abbf5443b220f6a500cc6acebfae5
refs/heads/master
2021-06-05T02:37:02.475028
2021-05-31T01:08:06
2021-05-31T01:08:06
93,225,718
2
0
null
null
null
null
UTF-8
C++
false
false
1,074
cc
/* * @Author: Simon * @Date: 2018-08-20 13:30:43 * @Last Modified by: Simon * @Last Modified time: 2018-08-20 14:43:25 */ #include <iostream> #include <cstdio> using namespace std; typedef int Int; #define int long long #define INF 0x3f3f3f3f #define maxn 105 int a[maxn]; int dp[maxn][maxn][maxn]; Int main() { ios::sync_with_stdio(false); cin.tie(0); int n,l,r; while(cin>>n>>l>>r) { memset(dp,INF,sizeof(dp)); for(int i=1;i<=n;i++) { dp[i][i][1]=0; cin>>a[i]; a[i]+=a[i-1]; } for(int x=l-1;x<r;x++) { for(int i=1;i+x<=n;i++) { int j=x+i; dp[i][j][x+1]=0; dp[i][j][1]=a[j]-a[i-1]; } } for(int x=1;x<n;x++) { for(int i=1;i+x<=n;i++) { int j=x+i; for(int k=i;k<j;k++) { for(int c=2;c<=x+1;c++) { dp[i][j][c]=min(dp[i][j][c],dp[i][k][c-1]+dp[k+1][j][1]); } } for(int c=l;c<=r;c++) dp[i][j][1]=min(dp[i][j][1],dp[i][j][c]+a[j]-a[i-1]); } } if(dp[1][n][1]>=INF) { cout<<0<<endl; } else cout<<dp[1][n][1]<<endl; } cin.get(),cin.get(); return 0; }
[ "ntlihy@gmail.com" ]
ntlihy@gmail.com
d806d49e012162bab2a267bdd8a4c801d340f9d0
33841dc85bc0ec7ef3eba6bef98ecd41ca86a3d5
/editor/echo/Editor/UI/ShaderEditor/DataModel/Math/Functions/AbsDataModel.h
730e66b3ec83110b03cacce32351371bbdea2494
[ "MIT" ]
permissive
haiyangfenghuo/echo
02511bdd46f3950ca3747106eb81f0932e4e09e0
10d7cea46b15ce807b92041c5ffe0a8daac22c46
refs/heads/master
2023-01-19T07:19:09.355206
2020-11-11T18:19:55
2020-11-11T18:19:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
h
#pragma once #include <QtCore/QObject> #include <QtWidgets/QLineEdit> #include <nodeeditor/NodeDataModel> #include <iostream> #include "ShaderDataModel.h" #include "DataFloat.h" #include "DataAny.h" #include "ShaderData.h" using QtNodes::PortType; using QtNodes::PortIndex; using QtNodes::NodeData; using QtNodes::NodeDataType; using QtNodes::NodeDataModel; using QtNodes::NodeValidationState; namespace DataFlowProgramming { class AbsDataModel : public ShaderDataModel { Q_OBJECT public: AbsDataModel(); virtual ~AbsDataModel() {} // caption QString caption() const override { return QStringLiteral("Abs"); } // is caption visible bool captionVisible() const override { return true; } // name QString name() const override { return QStringLiteral("Abs"); } // generate code virtual bool generateCode(ShaderCompiler& compiler) override; public: // load|save virtual QJsonObject save() const override; virtual void restore(QJsonObject const &p) override; public: // when input changed void setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) override; // widget QWidget* embeddedWidget() override { return nullptr; } }; }
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
13fdd5a482960aba073692c07ee9cf11cb7e6278
d413ef64e69fced8cf592f655a65b5ad3d2f3bb1
/MarkovGenerator.h
3e318d22c95ed114532b716342db569dc2ef794b
[]
no_license
polezhaev-ds/markov
6406e6ca9fd20c490c59bafe5648e4fd9d69fda5
08072c82f17bee8f45b0395f0f0422e6def59c94
refs/heads/master
2022-05-25T16:00:47.202549
2020-05-03T18:32:19
2020-05-03T18:32:19
259,901,102
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
h
// // Created by datas on 4/28/2020. // #ifndef MARKOV_MARKOVGENERATOR_H #define MARKOV_MARKOVGENERATOR_H #include "MarkovSelector.h" #include <unordered_map> #include <vector> #include <string> #include <fstream> class MarkovGenerator { public: explicit MarkovGenerator(std::size_t order): order(order), isTrainingFinished(false) { if (order == 0) throw std::invalid_argument(u8"Error! Invalid argument order! It should be greater than zero!"); } MarkovGenerator(const MarkovGenerator& generator) = default; MarkovGenerator(MarkovGenerator&& generator) = default; MarkovGenerator& operator = (const MarkovGenerator& generator) = default; MarkovGenerator& operator = (MarkovGenerator&& generator) = default; void train(const std::vector<std::wstring>& text); std::wstring generateText(const std::vector<std::wstring>& startingTextWords, std::size_t length); void serialize(const std::string& fileName) const; static MarkovGenerator deserialize(const std::string& fileName); void switchToGenerationMode(); void switchToTrainingMode(); [[nodiscard]] std::size_t getOrder() const { return order; } private: std::size_t order; bool isTrainingFinished; std::unordered_map<std::wstring, MarkovSelector> selectionMap; }; #endif //MARKOV_MARKOVGENERATOR_H
[ "polezhaev.ds@gmail.com" ]
polezhaev.ds@gmail.com
6a68744502946e33fb5baae4b6884494a5777be8
01b07ada565366b1a77406dfd7087d9751ba0152
/assignments/Assignment_4/Assignment_4_linux/src/main.cpp
aaf79c26a2a21728dc4d997f1a448671a3d4ef81
[ "MIT" ]
permissive
jamestiotio/gnv
92dbb9f5b1c55bc66a075b2cd1df4546dc07444a
2247c6eec6fee1a46a7c216f23ee61549570693b
refs/heads/main
2023-09-04T22:04:57.700519
2022-08-11T20:45:04
2022-08-11T20:45:04
492,712,727
0
1
null
null
null
null
UTF-8
C++
false
false
4,426
cpp
//////////////////////////////////////////////////////////////////////// // // // Assignment 4 of SUTD Course 50.017 (May-Aug Term, 2022) // // Ray Tracing // // 2022-July-07 // // //////////////////////////////////////////////////////////////////////// #include <iostream> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include "SceneParser.h" #include "Image.h" #include "Camera.h" #include <string.h> #include "bitmap_image.hpp" using namespace std; int main(int argc, char *argv[]) { // This loop loops over each of the input arguments. // argNum is initialized to 1 because the first "argument" provided to the program is // actually the name of the executable (in our case, "Assignment_4"). assert(argc > 1); for (int argNum = 1; argNum < argc; ++argNum) { std::cout << "Argument " << argNum << " is: " << argv[argNum] << std::endl; } ////////////////////////////////////////////////////////////////////////////////////////// // 1. Parse the scene using SceneParser. ////////////////////////////////////////////////////////////////////////////////////////// cout << "Running program..." << endl; // parsing using sceneParser char *inputFile = nullptr; char *outFile = nullptr; int windowWidth = 0; int windowHeight = 0; for (int i = 1; i < argc; i++) { // cout << "This argument is " << argv[i] << endl; if (strcmp(argv[i], "-input") == 0) { cout << "This argument is " << argv[i] << endl; inputFile = argv[i + 1]; i++; } else if (strcmp(argv[i], "-size") == 0) { cout << "This argument is " << argv[i] << endl; windowWidth = atoi(argv[i + 1]); windowHeight = atoi(argv[i + 2]); i++; i++; } else if (strcmp(argv[i], "-output") == 0) { cout << "This argument is " << argv[i] << endl; outFile = argv[i + 1]; i++; } else { cerr << "Usage: -input filename -size min max -output filename" << endl; return -1; } } //// parse the input txt file SceneParser scene = SceneParser(inputFile); ////////////////////////////////////////////////////////////////////////////////////////// // 2. Generate image by ray tracing ////////////////////////////////////////////////////////////////////////////////////////// Image img = Image(windowWidth, windowHeight); // Loop over each pixel in the image, shooting a ray through that pixel and finding its intersection with the scene. // Write the color at the intersection to that pixel in your output image. for (int i = 0; i < windowWidth; i++) { for (int j = 0; j < windowHeight; j++) { //// making p from -1 to 1 in x, and -1 to 1 in y. Multiply y with inv aspect to not distort the image. vec2 p = vec2(((float(i) / (windowWidth - 1))) * 2 - 1, (((float(j) / (windowHeight - 1))) * 2 - 1) * (windowHeight / windowWidth)); // cout << "xcoordinate " << p[0] << " ycoordinate " << p[1] << endl; Ray r = scene.getCamera()->generateRay(p); Hit hit = Hit(); if (scene.getGroup()->intersect(r, hit, scene.getCamera()->getTMin())) { vec3 colorPerPix = vec3(0, 0, 0); Material *mat = hit.getMaterial(); // loop through the lights to get specular and diffuse color for (int k = 0; k < scene.getNumLights(); k++) { Light *light = scene.getLight(k); vec3 lightDir; vec3 lightColor; float distance; light->getIllumination(r.pointAtParameter(hit.getT()), lightDir, lightColor, distance); vec3 addColor = mat->Shade(r, hit, lightDir, lightColor); colorPerPix += addColor; } colorPerPix += mat->getDiffuseColor() * scene.getAmbientLight(); img.SetPixel(i, j, colorPerPix); } else { img.SetPixel(i, j, scene.getBackgroundColor()); } } } img.SaveImage(outFile); return 0; }
[ "jamestiotio@gmail.com" ]
jamestiotio@gmail.com
18b4fe596f953df83b33c05d2e0b8d3e416da594
8ead33955285de594502c56b0c5699be31be3946
/Plugins/AirSim/Source/AirLib/include/vehicles/multirotor/api/MultirotorCommon.hpp
f35942747631906e0fcf30d9e611bc269166349b
[]
no_license
ece496-Telecopter/PointFollow
e936d13adc51fc72b4b446fac24fb829658172f1
f39da461528f2ff91d38c2a882b7ad420e9d2d53
refs/heads/master
2023-01-18T21:07:43.304981
2020-11-25T19:42:34
2020-11-25T19:42:34
316,028,953
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:8a2427302a7b4b6138b256b2ac0ab83118607e1663346d11552c5bd9f17d25a7 size 3131
[ "me@sarhad.me" ]
me@sarhad.me
1875775fa2b808677293f14ba430de1953c5b178
cbacf4b8fa09be96e88b6a8a86840cd504bdb1b1
/asg1/stringset.h
b61c1e1c6316bc34640481c39bea3374a2fca8b1
[]
no_license
mttan08/CMPS-104A
35e963c285733fd70cd6ab994f3fb42278996e81
e1957d47841db1eb061b5cb6e6fbf7e830a6c45b
refs/heads/master
2021-08-31T14:49:39.492482
2017-12-21T19:19:20
2017-12-21T19:19:20
114,690,736
0
4
null
null
null
null
UTF-8
C++
false
false
467
h
// Matthew Tan // cmps104a // mxtan // Wesley Mackey // asg1: stringset.h -- header file // for stringset.cpp // code credits goes to Professor Mackey #ifndef __STRING_SET__ #define __STRING_SET__ #include <string> #include <unordered_set> using namespace std; #include <stdio.h> struct string_set { string_set(); static unordered_set<string> set; static const string* intern_stringset(const char*); static void dump_stringset(FILE*); }; #endif
[ "noreply@github.com" ]
noreply@github.com
4ca0dc4962aae63c89724f5aaa7023ee01df1922
ab513fbacf6f85853cccaa04e295cc8083f51482
/2nd Semester/Object Oriented Programming /Laboratory/Proper Trench Coats Updated/Proper Trench Coats Lab 8-9/CSVBasket.hpp
de3e8ea674ad310fa41a2a1a80befcd506b267d3
[]
no_license
galoscar07/college2k16-2k19
1ee23e6690e4e5ac3ab9a8ed9792ebbeaecddbf6
a944bdbc13977aa6782e9eb83a97000aa58a9a93
refs/heads/master
2023-01-09T15:59:07.882933
2019-06-24T12:06:32
2019-06-24T12:06:32
167,170,983
1
1
null
2023-01-04T18:21:31
2019-01-23T11:22:29
Python
UTF-8
C++
false
false
345
hpp
// // CVSBasket.hpp // Proper Trench Coats Lab 8-9 // // Created by Gal Oscar on 15/05/2017. // Copyright © 2017 Gal Oscar. All rights reserved. // #pragma once #include "FileBasket.hpp" #include <string> class CSVBasket: public FileBasket{ public: CSVBasket(); void writeToFile() override; void displayBasket() override; };
[ "galoscar@Gals-MacBook-Pro.local" ]
galoscar@Gals-MacBook-Pro.local
21d1d3eb89e1ff0078d1a87694d0419d928843a8
4b5b7ae805203d53bfd5be327aba30edfedfa6db
/DrawingLots2.0/ManDrawDlg.h
6ea2bf3cebaa800a28c75001c71f39ec1b58537e
[]
no_license
kinglin/DrawingLots
f19eb9a949f4022f8b571cfd37cb6f2d9dc5c798
44417fa006732e0e3e745875a59720c6f510450b
refs/heads/master
2016-09-06T16:41:39.466652
2015-03-16T01:50:06
2015-03-16T01:50:06
32,294,978
0
0
null
null
null
null
GB18030
C++
false
false
974
h
#pragma once // CManDrawDlg 对话框 class CManDrawDlg : public CDialogEx { DECLARE_DYNAMIC(CManDrawDlg) public: CManDrawDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CManDrawDlg(); // 对话框数据 enum { IDD = IDD_DIALOG_ManDraw }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString m_ManDrawCrew11; CString m_ManDrawCrew12; CString m_ManDrawCrew13; CString m_ManDrawCrew14; CString m_ManDrawCrew15; CString m_ManDrawCrew16; CString m_ManDrawCrew17; CString m_ManDrawCrew21; CString m_ManDrawCrew22; CString m_ManDrawCrew23; CString m_ManDrawCrew24; CString m_ManDrawCrew25; CString m_ManDrawCrew26; CString m_ManDrawCrew27; CString m_ManDrawCrew31; CString m_ManDrawCrew32; CString m_ManDrawCrew33; CString m_ManDrawCrew34; CString m_ManDrawCrew35; CString m_ManDrawCrew36; CString m_ManDrawCrew37; void makeItDisabled(int groupNum,int crewNum); };
[ "lince110@163.com" ]
lince110@163.com
97a01ab9c8b10996e6b63a61714557a9fb2ad86a
db5664467043ecdf04304ad6e285251c137a803c
/cci/CheckPermutation/src/utests.cpp
c7724798aa2f54debe8120b155022a24d0f0ec18
[]
no_license
sifaserdarozen/CodeTrain
0cea53ca59bd0583f878f81680b816681c06a5af
1e7aba7383cfba5e3aa55eceab25edf9bfed3499
refs/heads/master
2023-04-07T01:30:20.505660
2023-04-03T18:02:06
2023-04-03T18:02:06
61,748,291
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cpp
/** @file utests.cpp * * Unit tests are performed with Catch v1.3.5 * More information about catch may be seen at their site https://github.com/philsquared/Catch */ // 3rd party libraries #define CATCH_CONFIG_MAIN // provides creation of executable, should be above catch.hpp #include "catch.hpp" #include <utility> #include <string> #include <vector> #include <iostream> extern bool checkPermutation(const std::string& strA, const std::string& strB); extern bool checkPermutationWithoutContainer(std::string strA, std::string strB); TEST_CASE( "tests case", "[solution]" ) { std::vector<std::pair<std::pair<std::string, std::string>, bool>> testStrings{ { {"abc", "abc"}, true} , { {"A", "A"}, true }, { {"Abv", "Ab"}, false}, { {"aboOaa", "aabaOo"}, true }, {{"aliveli", "veliilb" }, false}, { {"ii", "ii"}, true }, { {"aAbBcCdDeEfFgGhHa", "abcdeABCDEfFGghaH"}, true} }; SECTION( "solution with extra container" ) { for (const auto& s : testStrings) { REQUIRE( s.second == checkPermutation(s.first.first, s.first.second)); } } SECTION( "solution without using extra container" ) { for (const auto& s : testStrings) { REQUIRE( s.second == checkPermutationWithoutContainer(s.first.first, s.first.second)); } } }
[ "sifa.serder.ozen@gmail.com" ]
sifa.serder.ozen@gmail.com
42b97d437d237bf036e3346e5cc79a3fef867dc1
2beb02a1416a22ac6e223afa3097c570c2252fbe
/Minigin/SceneObject.h
02f909c682161bad9986735aa23aed1cb109b0e8
[]
no_license
JarneBeaufays/2DAE01_Engine_Beaufays_Jarne
d33614fb9aaa538d651a464a8bc1e47614d8a2bd
e4c2b7f4908f0c25c173224c977932ae5ee12e95
refs/heads/master
2022-10-18T09:05:24.249637
2020-06-14T18:58:12
2020-06-14T18:58:12
271,798,698
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
#pragma once namespace dae { class SceneObject { public: virtual void Delete() { m_Delete = true; } virtual void Update() = 0; virtual void Render() const = 0; virtual bool GetDelete() const { return m_Delete; } SceneObject() = default; virtual ~SceneObject() = default; SceneObject(const SceneObject& other) = delete; SceneObject(SceneObject&& other) = delete; SceneObject& operator=(const SceneObject& other) = delete; SceneObject& operator=(SceneObject&& other) = delete; private: bool m_Delete{ false }; }; }
[ "j.beaufays@outlook.com" ]
j.beaufays@outlook.com