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
3f0217288c93076502654147272db412d38888fe
07478f79bfa443322e0d3ff75c3fbc5b81c31032
/sources/mainExpLVMODGT.cpp
3b233dcfcd0d9b2608a546b81d2c61e3a98180f8
[]
no_license
rsantiago-ufsc/ModularityDensity
9ba8062ac946263dffa4ab34e6cfbc57bc9d063d
c9589359e1d40c2702bc13dbb012d8df45e5bc8a
refs/heads/master
2020-09-20T14:51:18.718425
2020-05-26T21:56:34
2020-05-26T21:56:34
224,514,569
1
0
null
null
null
null
UTF-8
C++
false
false
2,041
cpp
#include <iostream> #include <chrono> //define the solution construction #define GROUND_TRUTH #include "../../utils/modularitylg.h" #include "../../graph/largegraph.h" #include "../../graph/solution.h" #include "../../heuristics/hybrid/louvain/louvain.h" using namespace std; using namespace std::chrono; #define TYPE_PRI_NOW TYPE_PRI int main(int argc, char *argv[]) { chrono::system_clock::time_point before; before = chrono::system_clock::now(); srand(time(NULL)); string fileInstance = argv[1]; string filepath = "../../instances/"+fileInstance; string opt = argv[2]; string exp = argv[3]; LargeGraph lg(filepath); long long int totalTime; //construindo a solucao ModularityLG mlg(&lg); //before = chrono::system_clock::now(); Louvain hlv(&lg,TYPE_PRI_NOW); hlv.execute(); totalTime = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now()-before).count(); vector<string> ix = Utils::splitString(fileInstance,'.'); string instance= ix[ix.size()-2]; ix = Utils::splitString(instance,'/'); instance= ix[ix.size()-1]; //This following procedure calculates the number of communities Solution * sol= hlv.bestToSolution(); unsigned numberCom = 0; for (unsigned com=0;com <sol->comunidades.size();com++){ if (sol->comunidades[com]->qtd > 0){ numberCom++; } } // cout<<"\n"<<sol->serialize(); // cout<<"\n"<<mlg.calculateDensity(sol); //storing the data string expFile="../data/GT.csv"; ofstream f(expFile, std::fstream::app); f<<"Louvain;"<<instance<<";"<<lg.numberOfNodes<<";"<<lg.numberOfEdges<<";" <<exp<<";" <<hlv.it<<";"<<hlv.it<<";" <<opt<<";"<< mlg.calculateDensity(sol) << ";" <<hlv.bestDensity<<";" <<numberCom<<";" <<hlv.it<<";"<<hlv.it<<";" <<totalTime<<";"<<hlv.totalTime<<";"<<hlv.totalTime <<";"<<hlv.bestCommunityStr <<"\n"; f.close(); return 0; }
[ "r.santiago@ufsc.br" ]
r.santiago@ufsc.br
3327181a7f089bccc5f1830916ee3675b5a32335
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/perfetto/src/trace_processor/importers/proto/statsd_module.h
430b7a25c59b84e225a0fa3bcae5db72cc15cfa9
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
3,105
h
/* * Copyright (C) 2022 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 SRC_TRACE_PROCESSOR_IMPORTERS_PROTO_STATSD_MODULE_H_ #define SRC_TRACE_PROCESSOR_IMPORTERS_PROTO_STATSD_MODULE_H_ #include <cstdint> #include <optional> #include "perfetto/ext/base/flat_hash_map.h" #include "protos/perfetto/trace/trace_packet.pbzero.h" #include "src/trace_processor/importers/common/async_track_set_tracker.h" #include "src/trace_processor/importers/common/trace_parser.h" #include "src/trace_processor/importers/proto/proto_importer_module.h" #include "src/trace_processor/storage/trace_storage.h" #include "src/trace_processor/tables/slice_tables_py.h" #include "src/trace_processor/tables/track_tables_py.h" #include "src/trace_processor/types/trace_processor_context.h" #include "src/trace_processor/util/descriptors.h" #include "src/trace_processor/util/proto_to_args_parser.h" namespace perfetto { namespace trace_processor { // Wraps a DescriptorPool and a pointer into that pool. This prevents // common bugs where moving/changing the pool invalidates the pointer. class PoolAndDescriptor { public: PoolAndDescriptor(const uint8_t* data, size_t size, const char* name); virtual ~PoolAndDescriptor(); const DescriptorPool* pool() const { return &pool_; } const ProtoDescriptor* descriptor() const { return descriptor_; } private: PoolAndDescriptor(const PoolAndDescriptor&) = delete; PoolAndDescriptor& operator=(const PoolAndDescriptor&) = delete; PoolAndDescriptor(PoolAndDescriptor&&) = delete; PoolAndDescriptor& operator=(PoolAndDescriptor&&) = delete; DescriptorPool pool_; const ProtoDescriptor* descriptor_{}; }; class StatsdModule : public ProtoImporterModule { public: explicit StatsdModule(TraceProcessorContext* context); ~StatsdModule() override; void ParseTracePacketData(const protos::pbzero::TracePacket_Decoder& decoder, int64_t ts, const TracePacketData&, uint32_t field_id) override; private: void ParseAtom(int64_t ts, protozero::ConstBytes bytes); StringId GetAtomName(uint32_t atom_field_id); AsyncTrackSetTracker::TrackSetId InternAsyncTrackSetId(); TraceProcessorContext* context_; base::FlatHashMap<uint32_t, StringId> atom_names_; PoolAndDescriptor pool_; util::ProtoToArgsParser args_parser_; std::optional<AsyncTrackSetTracker::TrackSetId> track_set_id_; }; } // namespace trace_processor } // namespace perfetto #endif // SRC_TRACE_PROCESSOR_IMPORTERS_PROTO_STATSD_MODULE_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
5b3cbae00b7be0ee39f5f4f3e3d2c241faccb3a9
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/skia/include/core/SkMatrix.h
da6bd1567908be824fdb510e59e438e016fe7112
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
68,848
h
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkMatrix_DEFINED #define SkMatrix_DEFINED #include "include/core/SkRect.h" #include "include/private/SkMacros.h" #include "include/private/SkTo.h" struct SkRSXform; struct SkPoint3; class SkString; /** \class SkMatrix SkMatrix holds a 3x3 matrix for transforming coordinates. This allows mapping SkPoint and vectors with translation, scaling, skewing, rotation, and perspective. SkMatrix elements are in row major order. SkMatrix does not have a constructor, so it must be explicitly initialized. setIdentity() initializes SkMatrix so it has no effect. setTranslate(), setScale(), setSkew(), setRotate(), set9 and setAll() initializes all SkMatrix elements with the corresponding mapping. SkMatrix includes a hidden variable that classifies the type of matrix to improve performance. SkMatrix is not thread safe unless getType() is called first. */ SK_BEGIN_REQUIRE_DENSE class SK_API SkMatrix { public: /** Creates an identity SkMatrix: | 1 0 0 | | 0 1 0 | | 0 0 1 | */ constexpr SkMatrix() : SkMatrix(1,0,0, 0,1,0, 0,0,1, kIdentity_Mask | kRectStaysRect_Mask) {} /** Sets SkMatrix to scale by (sx, sy). Returned matrix is: | sx 0 0 | | 0 sy 0 | | 0 0 1 | @param sx horizontal scale factor @param sy vertical scale factor @return SkMatrix with scale */ static SkMatrix SK_WARN_UNUSED_RESULT MakeScale(SkScalar sx, SkScalar sy) { SkMatrix m; m.setScale(sx, sy); return m; } /** Sets SkMatrix to scale by (scale, scale). Returned matrix is: | scale 0 0 | | 0 scale 0 | | 0 0 1 | @param scale horizontal and vertical scale factor @return SkMatrix with scale */ static SkMatrix SK_WARN_UNUSED_RESULT MakeScale(SkScalar scale) { SkMatrix m; m.setScale(scale, scale); return m; } /** Sets SkMatrix to translate by (dx, dy). Returned matrix is: | 1 0 dx | | 0 1 dy | | 0 0 1 | @param dx horizontal translation @param dy vertical translation @return SkMatrix with translation */ static SkMatrix SK_WARN_UNUSED_RESULT MakeTrans(SkScalar dx, SkScalar dy) { SkMatrix m; m.setTranslate(dx, dy); return m; } /** Sets SkMatrix to: | scaleX skewX transX | | skewY scaleY transY | | pers0 pers1 pers2 | @param scaleX horizontal scale factor @param skewX horizontal skew factor @param transX horizontal translation @param skewY vertical skew factor @param scaleY vertical scale factor @param transY vertical translation @param pers0 input x-axis perspective factor @param pers1 input y-axis perspective factor @param pers2 perspective scale factor @return SkMatrix constructed from parameters */ static SkMatrix SK_WARN_UNUSED_RESULT MakeAll(SkScalar scaleX, SkScalar skewX, SkScalar transX, SkScalar skewY, SkScalar scaleY, SkScalar transY, SkScalar pers0, SkScalar pers1, SkScalar pers2) { SkMatrix m; m.setAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2); return m; } /** \enum SkMatrix::TypeMask Enum of bit fields for mask returned by getType(). Used to identify the complexity of SkMatrix, to optimize performance. */ enum TypeMask { kIdentity_Mask = 0, //!< identity SkMatrix; all bits clear kTranslate_Mask = 0x01, //!< translation SkMatrix kScale_Mask = 0x02, //!< scale SkMatrix kAffine_Mask = 0x04, //!< skew or rotate SkMatrix kPerspective_Mask = 0x08, //!< perspective SkMatrix }; /** Returns a bit field describing the transformations the matrix may perform. The bit field is computed conservatively, so it may include false positives. For example, when kPerspective_Mask is set, all other bits are set. @return kIdentity_Mask, or combinations of: kTranslate_Mask, kScale_Mask, kAffine_Mask, kPerspective_Mask */ TypeMask getType() const { if (fTypeMask & kUnknown_Mask) { fTypeMask = this->computeTypeMask(); } // only return the public masks return (TypeMask)(fTypeMask & 0xF); } /** Returns true if SkMatrix is identity. Identity matrix is: | 1 0 0 | | 0 1 0 | | 0 0 1 | @return true if SkMatrix has no effect */ bool isIdentity() const { return this->getType() == 0; } /** Returns true if SkMatrix at most scales and translates. SkMatrix may be identity, contain only scale elements, only translate elements, or both. SkMatrix form is: | scale-x 0 translate-x | | 0 scale-y translate-y | | 0 0 1 | @return true if SkMatrix is identity; or scales, translates, or both */ bool isScaleTranslate() const { return !(this->getType() & ~(kScale_Mask | kTranslate_Mask)); } /** Returns true if SkMatrix is identity, or translates. SkMatrix form is: | 1 0 translate-x | | 0 1 translate-y | | 0 0 1 | @return true if SkMatrix is identity, or translates */ bool isTranslate() const { return !(this->getType() & ~(kTranslate_Mask)); } /** Returns true SkMatrix maps SkRect to another SkRect. If true, SkMatrix is identity, or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all cases, SkMatrix may also have translation. SkMatrix form is either: | scale-x 0 translate-x | | 0 scale-y translate-y | | 0 0 1 | or | 0 rotate-x translate-x | | rotate-y 0 translate-y | | 0 0 1 | for non-zero values of scale-x, scale-y, rotate-x, and rotate-y. Also called preservesAxisAlignment(); use the one that provides better inline documentation. @return true if SkMatrix maps one SkRect into another */ bool rectStaysRect() const { if (fTypeMask & kUnknown_Mask) { fTypeMask = this->computeTypeMask(); } return (fTypeMask & kRectStaysRect_Mask) != 0; } /** Returns true SkMatrix maps SkRect to another SkRect. If true, SkMatrix is identity, or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all cases, SkMatrix may also have translation. SkMatrix form is either: | scale-x 0 translate-x | | 0 scale-y translate-y | | 0 0 1 | or | 0 rotate-x translate-x | | rotate-y 0 translate-y | | 0 0 1 | for non-zero values of scale-x, scale-y, rotate-x, and rotate-y. Also called rectStaysRect(); use the one that provides better inline documentation. @return true if SkMatrix maps one SkRect into another */ bool preservesAxisAlignment() const { return this->rectStaysRect(); } /** Returns true if the matrix contains perspective elements. SkMatrix form is: | -- -- -- | | -- -- -- | | perspective-x perspective-y perspective-scale | where perspective-x or perspective-y is non-zero, or perspective-scale is not one. All other elements may have any value. @return true if SkMatrix is in most general form */ bool hasPerspective() const { return SkToBool(this->getPerspectiveTypeMaskOnly() & kPerspective_Mask); } /** Returns true if SkMatrix contains only translation, rotation, reflection, and uniform scale. Returns false if SkMatrix contains different scales, skewing, perspective, or degenerate forms that collapse to a line or point. Describes that the SkMatrix makes rendering with and without the matrix are visually alike; a transformed circle remains a circle. Mathematically, this is referred to as similarity of a Euclidean space, or a similarity transformation. Preserves right angles, keeping the arms of the angle equal lengths. @param tol to be deprecated @return true if SkMatrix only rotates, uniformly scales, translates */ bool isSimilarity(SkScalar tol = SK_ScalarNearlyZero) const; /** Returns true if SkMatrix contains only translation, rotation, reflection, and scale. Scale may differ along rotated axes. Returns false if SkMatrix skewing, perspective, or degenerate forms that collapse to a line or point. Preserves right angles, but not requiring that the arms of the angle retain equal lengths. @param tol to be deprecated @return true if SkMatrix only rotates, scales, translates */ bool preservesRightAngles(SkScalar tol = SK_ScalarNearlyZero) const; /** SkMatrix organizes its values in row order. These members correspond to each value in SkMatrix. */ static constexpr int kMScaleX = 0; //!< horizontal scale factor static constexpr int kMSkewX = 1; //!< horizontal skew factor static constexpr int kMTransX = 2; //!< horizontal translation static constexpr int kMSkewY = 3; //!< vertical skew factor static constexpr int kMScaleY = 4; //!< vertical scale factor static constexpr int kMTransY = 5; //!< vertical translation static constexpr int kMPersp0 = 6; //!< input x perspective factor static constexpr int kMPersp1 = 7; //!< input y perspective factor static constexpr int kMPersp2 = 8; //!< perspective bias /** Affine arrays are in column major order to match the matrix used by PDF and XPS. */ static constexpr int kAScaleX = 0; //!< horizontal scale factor static constexpr int kASkewY = 1; //!< vertical skew factor static constexpr int kASkewX = 2; //!< horizontal skew factor static constexpr int kAScaleY = 3; //!< vertical scale factor static constexpr int kATransX = 4; //!< horizontal translation static constexpr int kATransY = 5; //!< vertical translation /** Returns one matrix value. Asserts if index is out of range and SK_DEBUG is defined. @param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2 @return value corresponding to index */ SkScalar operator[](int index) const { SkASSERT((unsigned)index < 9); return fMat[index]; } /** Returns one matrix value. Asserts if index is out of range and SK_DEBUG is defined. @param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2 @return value corresponding to index */ SkScalar get(int index) const { SkASSERT((unsigned)index < 9); return fMat[index]; } /** Returns scale factor multiplied by x-axis input, contributing to x-axis output. With mapPoints(), scales SkPoint along the x-axis. @return horizontal scale factor */ SkScalar getScaleX() const { return fMat[kMScaleX]; } /** Returns scale factor multiplied by y-axis input, contributing to y-axis output. With mapPoints(), scales SkPoint along the y-axis. @return vertical scale factor */ SkScalar getScaleY() const { return fMat[kMScaleY]; } /** Returns scale factor multiplied by x-axis input, contributing to y-axis output. With mapPoints(), skews SkPoint along the y-axis. Skewing both axes can rotate SkPoint. @return vertical skew factor */ SkScalar getSkewY() const { return fMat[kMSkewY]; } /** Returns scale factor multiplied by y-axis input, contributing to x-axis output. With mapPoints(), skews SkPoint along the x-axis. Skewing both axes can rotate SkPoint. @return horizontal scale factor */ SkScalar getSkewX() const { return fMat[kMSkewX]; } /** Returns translation contributing to x-axis output. With mapPoints(), moves SkPoint along the x-axis. @return horizontal translation factor */ SkScalar getTranslateX() const { return fMat[kMTransX]; } /** Returns translation contributing to y-axis output. With mapPoints(), moves SkPoint along the y-axis. @return vertical translation factor */ SkScalar getTranslateY() const { return fMat[kMTransY]; } /** Returns factor scaling input x-axis relative to input y-axis. @return input x-axis perspective factor */ SkScalar getPerspX() const { return fMat[kMPersp0]; } /** Returns factor scaling input y-axis relative to input x-axis. @return input y-axis perspective factor */ SkScalar getPerspY() const { return fMat[kMPersp1]; } /** Returns writable SkMatrix value. Asserts if index is out of range and SK_DEBUG is defined. Clears internal cache anticipating that caller will change SkMatrix value. Next call to read SkMatrix state may recompute cache; subsequent writes to SkMatrix value must be followed by dirtyMatrixTypeCache(). @param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2 @return writable value corresponding to index */ SkScalar& operator[](int index) { SkASSERT((unsigned)index < 9); this->setTypeMask(kUnknown_Mask); return fMat[index]; } /** Sets SkMatrix value. Asserts if index is out of range and SK_DEBUG is defined. Safer than operator[]; internal cache is always maintained. @param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2 @param value scalar to store in SkMatrix */ void set(int index, SkScalar value) { SkASSERT((unsigned)index < 9); fMat[index] = value; this->setTypeMask(kUnknown_Mask); } /** Sets horizontal scale factor. @param v horizontal scale factor to store */ void setScaleX(SkScalar v) { this->set(kMScaleX, v); } /** Sets vertical scale factor. @param v vertical scale factor to store */ void setScaleY(SkScalar v) { this->set(kMScaleY, v); } /** Sets vertical skew factor. @param v vertical skew factor to store */ void setSkewY(SkScalar v) { this->set(kMSkewY, v); } /** Sets horizontal skew factor. @param v horizontal skew factor to store */ void setSkewX(SkScalar v) { this->set(kMSkewX, v); } /** Sets horizontal translation. @param v horizontal translation to store */ void setTranslateX(SkScalar v) { this->set(kMTransX, v); } /** Sets vertical translation. @param v vertical translation to store */ void setTranslateY(SkScalar v) { this->set(kMTransY, v); } /** Sets input x-axis perspective factor, which causes mapXY() to vary input x-axis values inversely proportional to input y-axis values. @param v perspective factor */ void setPerspX(SkScalar v) { this->set(kMPersp0, v); } /** Sets input y-axis perspective factor, which causes mapXY() to vary input y-axis values inversely proportional to input x-axis values. @param v perspective factor */ void setPerspY(SkScalar v) { this->set(kMPersp1, v); } /** Sets all values from parameters. Sets matrix to: | scaleX skewX transX | | skewY scaleY transY | | persp0 persp1 persp2 | @param scaleX horizontal scale factor to store @param skewX horizontal skew factor to store @param transX horizontal translation to store @param skewY vertical skew factor to store @param scaleY vertical scale factor to store @param transY vertical translation to store @param persp0 input x-axis values perspective factor to store @param persp1 input y-axis values perspective factor to store @param persp2 perspective scale factor to store */ void setAll(SkScalar scaleX, SkScalar skewX, SkScalar transX, SkScalar skewY, SkScalar scaleY, SkScalar transY, SkScalar persp0, SkScalar persp1, SkScalar persp2) { fMat[kMScaleX] = scaleX; fMat[kMSkewX] = skewX; fMat[kMTransX] = transX; fMat[kMSkewY] = skewY; fMat[kMScaleY] = scaleY; fMat[kMTransY] = transY; fMat[kMPersp0] = persp0; fMat[kMPersp1] = persp1; fMat[kMPersp2] = persp2; this->setTypeMask(kUnknown_Mask); } /** Copies nine scalar values contained by SkMatrix into buffer, in member value ascending order: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2. @param buffer storage for nine scalar values */ void get9(SkScalar buffer[9]) const { memcpy(buffer, fMat, 9 * sizeof(SkScalar)); } /** Sets SkMatrix to nine scalar values in buffer, in member value ascending order: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1, kMPersp2. Sets matrix to: | buffer[0] buffer[1] buffer[2] | | buffer[3] buffer[4] buffer[5] | | buffer[6] buffer[7] buffer[8] | In the future, set9 followed by get9 may not return the same values. Since SkMatrix maps non-homogeneous coordinates, scaling all nine values produces an equivalent transformation, possibly improving precision. @param buffer nine scalar values */ void set9(const SkScalar buffer[9]); /** Sets SkMatrix to identity; which has no effect on mapped SkPoint. Sets SkMatrix to: | 1 0 0 | | 0 1 0 | | 0 0 1 | Also called setIdentity(); use the one that provides better inline documentation. */ void reset(); /** Sets SkMatrix to identity; which has no effect on mapped SkPoint. Sets SkMatrix to: | 1 0 0 | | 0 1 0 | | 0 0 1 | Also called reset(); use the one that provides better inline documentation. */ void setIdentity() { this->reset(); } /** Sets SkMatrix to translate by (dx, dy). @param dx horizontal translation @param dy vertical translation */ void setTranslate(SkScalar dx, SkScalar dy); /** Sets SkMatrix to translate by (v.fX, v.fY). @param v vector containing horizontal and vertical translation */ void setTranslate(const SkVector& v) { this->setTranslate(v.fX, v.fY); } /** Sets SkMatrix to scale by sx and sy, about a pivot point at (px, py). The pivot point is unchanged when mapped with SkMatrix. @param sx horizontal scale factor @param sy vertical scale factor @param px pivot on x-axis @param py pivot on y-axis */ void setScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py); /** Sets SkMatrix to scale by sx and sy about at pivot point at (0, 0). @param sx horizontal scale factor @param sy vertical scale factor */ void setScale(SkScalar sx, SkScalar sy); /** Sets SkMatrix to rotate by degrees about a pivot point at (px, py). The pivot point is unchanged when mapped with SkMatrix. Positive degrees rotates clockwise. @param degrees angle of axes relative to upright axes @param px pivot on x-axis @param py pivot on y-axis */ void setRotate(SkScalar degrees, SkScalar px, SkScalar py); /** Sets SkMatrix to rotate by degrees about a pivot point at (0, 0). Positive degrees rotates clockwise. @param degrees angle of axes relative to upright axes */ void setRotate(SkScalar degrees); /** Sets SkMatrix to rotate by sinValue and cosValue, about a pivot point at (px, py). The pivot point is unchanged when mapped with SkMatrix. Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1). Vector length specifies scale. @param sinValue rotation vector x-axis component @param cosValue rotation vector y-axis component @param px pivot on x-axis @param py pivot on y-axis */ void setSinCos(SkScalar sinValue, SkScalar cosValue, SkScalar px, SkScalar py); /** Sets SkMatrix to rotate by sinValue and cosValue, about a pivot point at (0, 0). Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1). Vector length specifies scale. @param sinValue rotation vector x-axis component @param cosValue rotation vector y-axis component */ void setSinCos(SkScalar sinValue, SkScalar cosValue); /** Sets SkMatrix to rotate, scale, and translate using a compressed matrix form. Vector (rsxForm.fSSin, rsxForm.fSCos) describes the angle of rotation relative to (0, 1). Vector length specifies scale. Mapped point is rotated and scaled by vector, then translated by (rsxForm.fTx, rsxForm.fTy). @param rsxForm compressed SkRSXform matrix @return reference to SkMatrix */ SkMatrix& setRSXform(const SkRSXform& rsxForm); /** Sets SkMatrix to skew by kx and ky, about a pivot point at (px, py). The pivot point is unchanged when mapped with SkMatrix. @param kx horizontal skew factor @param ky vertical skew factor @param px pivot on x-axis @param py pivot on y-axis */ void setSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py); /** Sets SkMatrix to skew by kx and ky, about a pivot point at (0, 0). @param kx horizontal skew factor @param ky vertical skew factor */ void setSkew(SkScalar kx, SkScalar ky); /** Sets SkMatrix to SkMatrix a multiplied by SkMatrix b. Either a or b may be this. Given: | A B C | | J K L | a = | D E F |, b = | M N O | | G H I | | P Q R | sets SkMatrix to: | A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR | a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR | | G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR | @param a SkMatrix on left side of multiply expression @param b SkMatrix on right side of multiply expression */ void setConcat(const SkMatrix& a, const SkMatrix& b); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from translation (dx, dy). This can be thought of as moving the point to be mapped before applying SkMatrix. Given: | A B C | | 1 0 dx | Matrix = | D E F |, T(dx, dy) = | 0 1 dy | | G H I | | 0 0 1 | sets SkMatrix to: | A B C | | 1 0 dx | | A B A*dx+B*dy+C | Matrix * T(dx, dy) = | D E F | | 0 1 dy | = | D E D*dx+E*dy+F | | G H I | | 0 0 1 | | G H G*dx+H*dy+I | @param dx x-axis translation before applying SkMatrix @param dy y-axis translation before applying SkMatrix */ void preTranslate(SkScalar dx, SkScalar dy); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from scaling by (sx, sy) about pivot point (px, py). This can be thought of as scaling about a pivot point before applying SkMatrix. Given: | A B C | | sx 0 dx | Matrix = | D E F |, S(sx, sy, px, py) = | 0 sy dy | | G H I | | 0 0 1 | where dx = px - sx * px dy = py - sy * py sets SkMatrix to: | A B C | | sx 0 dx | | A*sx B*sy A*dx+B*dy+C | Matrix * S(sx, sy, px, py) = | D E F | | 0 sy dy | = | D*sx E*sy D*dx+E*dy+F | | G H I | | 0 0 1 | | G*sx H*sy G*dx+H*dy+I | @param sx horizontal scale factor @param sy vertical scale factor @param px pivot on x-axis @param py pivot on y-axis */ void preScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from scaling by (sx, sy) about pivot point (0, 0). This can be thought of as scaling about the origin before applying SkMatrix. Given: | A B C | | sx 0 0 | Matrix = | D E F |, S(sx, sy) = | 0 sy 0 | | G H I | | 0 0 1 | sets SkMatrix to: | A B C | | sx 0 0 | | A*sx B*sy C | Matrix * S(sx, sy) = | D E F | | 0 sy 0 | = | D*sx E*sy F | | G H I | | 0 0 1 | | G*sx H*sy I | @param sx horizontal scale factor @param sy vertical scale factor */ void preScale(SkScalar sx, SkScalar sy); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from rotating by degrees about pivot point (px, py). This can be thought of as rotating about a pivot point before applying SkMatrix. Positive degrees rotates clockwise. Given: | A B C | | c -s dx | Matrix = | D E F |, R(degrees, px, py) = | s c dy | | G H I | | 0 0 1 | where c = cos(degrees) s = sin(degrees) dx = s * py + (1 - c) * px dy = -s * px + (1 - c) * py sets SkMatrix to: | A B C | | c -s dx | | Ac+Bs -As+Bc A*dx+B*dy+C | Matrix * R(degrees, px, py) = | D E F | | s c dy | = | Dc+Es -Ds+Ec D*dx+E*dy+F | | G H I | | 0 0 1 | | Gc+Hs -Gs+Hc G*dx+H*dy+I | @param degrees angle of axes relative to upright axes @param px pivot on x-axis @param py pivot on y-axis */ void preRotate(SkScalar degrees, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from rotating by degrees about pivot point (0, 0). This can be thought of as rotating about the origin before applying SkMatrix. Positive degrees rotates clockwise. Given: | A B C | | c -s 0 | Matrix = | D E F |, R(degrees, px, py) = | s c 0 | | G H I | | 0 0 1 | where c = cos(degrees) s = sin(degrees) sets SkMatrix to: | A B C | | c -s 0 | | Ac+Bs -As+Bc C | Matrix * R(degrees, px, py) = | D E F | | s c 0 | = | Dc+Es -Ds+Ec F | | G H I | | 0 0 1 | | Gc+Hs -Gs+Hc I | @param degrees angle of axes relative to upright axes */ void preRotate(SkScalar degrees); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from skewing by (kx, ky) about pivot point (px, py). This can be thought of as skewing about a pivot point before applying SkMatrix. Given: | A B C | | 1 kx dx | Matrix = | D E F |, K(kx, ky, px, py) = | ky 1 dy | | G H I | | 0 0 1 | where dx = -kx * py dy = -ky * px sets SkMatrix to: | A B C | | 1 kx dx | | A+B*ky A*kx+B A*dx+B*dy+C | Matrix * K(kx, ky, px, py) = | D E F | | ky 1 dy | = | D+E*ky D*kx+E D*dx+E*dy+F | | G H I | | 0 0 1 | | G+H*ky G*kx+H G*dx+H*dy+I | @param kx horizontal skew factor @param ky vertical skew factor @param px pivot on x-axis @param py pivot on y-axis */ void preSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix constructed from skewing by (kx, ky) about pivot point (0, 0). This can be thought of as skewing about the origin before applying SkMatrix. Given: | A B C | | 1 kx 0 | Matrix = | D E F |, K(kx, ky) = | ky 1 0 | | G H I | | 0 0 1 | sets SkMatrix to: | A B C | | 1 kx 0 | | A+B*ky A*kx+B C | Matrix * K(kx, ky) = | D E F | | ky 1 0 | = | D+E*ky D*kx+E F | | G H I | | 0 0 1 | | G+H*ky G*kx+H I | @param kx horizontal skew factor @param ky vertical skew factor */ void preSkew(SkScalar kx, SkScalar ky); /** Sets SkMatrix to SkMatrix multiplied by SkMatrix other. This can be thought of mapping by other before applying SkMatrix. Given: | A B C | | J K L | Matrix = | D E F |, other = | M N O | | G H I | | P Q R | sets SkMatrix to: | A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR | Matrix * other = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR | | G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR | @param other SkMatrix on right side of multiply expression */ void preConcat(const SkMatrix& other); /** Sets SkMatrix to SkMatrix constructed from translation (dx, dy) multiplied by SkMatrix. This can be thought of as moving the point to be mapped after applying SkMatrix. Given: | J K L | | 1 0 dx | Matrix = | M N O |, T(dx, dy) = | 0 1 dy | | P Q R | | 0 0 1 | sets SkMatrix to: | 1 0 dx | | J K L | | J+dx*P K+dx*Q L+dx*R | T(dx, dy) * Matrix = | 0 1 dy | | M N O | = | M+dy*P N+dy*Q O+dy*R | | 0 0 1 | | P Q R | | P Q R | @param dx x-axis translation after applying SkMatrix @param dy y-axis translation after applying SkMatrix */ void postTranslate(SkScalar dx, SkScalar dy); /** Sets SkMatrix to SkMatrix constructed from scaling by (sx, sy) about pivot point (px, py), multiplied by SkMatrix. This can be thought of as scaling about a pivot point after applying SkMatrix. Given: | J K L | | sx 0 dx | Matrix = | M N O |, S(sx, sy, px, py) = | 0 sy dy | | P Q R | | 0 0 1 | where dx = px - sx * px dy = py - sy * py sets SkMatrix to: | sx 0 dx | | J K L | | sx*J+dx*P sx*K+dx*Q sx*L+dx+R | S(sx, sy, px, py) * Matrix = | 0 sy dy | | M N O | = | sy*M+dy*P sy*N+dy*Q sy*O+dy*R | | 0 0 1 | | P Q R | | P Q R | @param sx horizontal scale factor @param sy vertical scale factor @param px pivot on x-axis @param py pivot on y-axis */ void postScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix constructed from scaling by (sx, sy) about pivot point (0, 0), multiplied by SkMatrix. This can be thought of as scaling about the origin after applying SkMatrix. Given: | J K L | | sx 0 0 | Matrix = | M N O |, S(sx, sy) = | 0 sy 0 | | P Q R | | 0 0 1 | sets SkMatrix to: | sx 0 0 | | J K L | | sx*J sx*K sx*L | S(sx, sy) * Matrix = | 0 sy 0 | | M N O | = | sy*M sy*N sy*O | | 0 0 1 | | P Q R | | P Q R | @param sx horizontal scale factor @param sy vertical scale factor */ void postScale(SkScalar sx, SkScalar sy); /** Sets SkMatrix to SkMatrix constructed from scaling by (1/divx, 1/divy), about pivot point (px, py), multiplied by SkMatrix. Returns false if either divx or divy is zero. Given: | J K L | | sx 0 0 | Matrix = | M N O |, I(divx, divy) = | 0 sy 0 | | P Q R | | 0 0 1 | where sx = 1 / divx sy = 1 / divy sets SkMatrix to: | sx 0 0 | | J K L | | sx*J sx*K sx*L | I(divx, divy) * Matrix = | 0 sy 0 | | M N O | = | sy*M sy*N sy*O | | 0 0 1 | | P Q R | | P Q R | @param divx integer divisor for inverse scale in x @param divy integer divisor for inverse scale in y @return true on successful scale */ bool postIDiv(int divx, int divy); /** Sets SkMatrix to SkMatrix constructed from rotating by degrees about pivot point (px, py), multiplied by SkMatrix. This can be thought of as rotating about a pivot point after applying SkMatrix. Positive degrees rotates clockwise. Given: | J K L | | c -s dx | Matrix = | M N O |, R(degrees, px, py) = | s c dy | | P Q R | | 0 0 1 | where c = cos(degrees) s = sin(degrees) dx = s * py + (1 - c) * px dy = -s * px + (1 - c) * py sets SkMatrix to: |c -s dx| |J K L| |cJ-sM+dx*P cK-sN+dx*Q cL-sO+dx+R| R(degrees, px, py) * Matrix = |s c dy| |M N O| = |sJ+cM+dy*P sK+cN+dy*Q sL+cO+dy*R| |0 0 1| |P Q R| | P Q R| @param degrees angle of axes relative to upright axes @param px pivot on x-axis @param py pivot on y-axis */ void postRotate(SkScalar degrees, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix constructed from rotating by degrees about pivot point (0, 0), multiplied by SkMatrix. This can be thought of as rotating about the origin after applying SkMatrix. Positive degrees rotates clockwise. Given: | J K L | | c -s 0 | Matrix = | M N O |, R(degrees, px, py) = | s c 0 | | P Q R | | 0 0 1 | where c = cos(degrees) s = sin(degrees) sets SkMatrix to: | c -s dx | | J K L | | cJ-sM cK-sN cL-sO | R(degrees, px, py) * Matrix = | s c dy | | M N O | = | sJ+cM sK+cN sL+cO | | 0 0 1 | | P Q R | | P Q R | @param degrees angle of axes relative to upright axes */ void postRotate(SkScalar degrees); /** Sets SkMatrix to SkMatrix constructed from skewing by (kx, ky) about pivot point (px, py), multiplied by SkMatrix. This can be thought of as skewing about a pivot point after applying SkMatrix. Given: | J K L | | 1 kx dx | Matrix = | M N O |, K(kx, ky, px, py) = | ky 1 dy | | P Q R | | 0 0 1 | where dx = -kx * py dy = -ky * px sets SkMatrix to: | 1 kx dx| |J K L| |J+kx*M+dx*P K+kx*N+dx*Q L+kx*O+dx+R| K(kx, ky, px, py) * Matrix = |ky 1 dy| |M N O| = |ky*J+M+dy*P ky*K+N+dy*Q ky*L+O+dy*R| | 0 0 1| |P Q R| | P Q R| @param kx horizontal skew factor @param ky vertical skew factor @param px pivot on x-axis @param py pivot on y-axis */ void postSkew(SkScalar kx, SkScalar ky, SkScalar px, SkScalar py); /** Sets SkMatrix to SkMatrix constructed from skewing by (kx, ky) about pivot point (0, 0), multiplied by SkMatrix. This can be thought of as skewing about the origin after applying SkMatrix. Given: | J K L | | 1 kx 0 | Matrix = | M N O |, K(kx, ky) = | ky 1 0 | | P Q R | | 0 0 1 | sets SkMatrix to: | 1 kx 0 | | J K L | | J+kx*M K+kx*N L+kx*O | K(kx, ky) * Matrix = | ky 1 0 | | M N O | = | ky*J+M ky*K+N ky*L+O | | 0 0 1 | | P Q R | | P Q R | @param kx horizontal skew factor @param ky vertical skew factor */ void postSkew(SkScalar kx, SkScalar ky); /** Sets SkMatrix to SkMatrix other multiplied by SkMatrix. This can be thought of mapping by other after applying SkMatrix. Given: | J K L | | A B C | Matrix = | M N O |, other = | D E F | | P Q R | | G H I | sets SkMatrix to: | A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR | other * Matrix = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR | | G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR | @param other SkMatrix on left side of multiply expression */ void postConcat(const SkMatrix& other); /** \enum SkMatrix::ScaleToFit ScaleToFit describes how SkMatrix is constructed to map one SkRect to another. ScaleToFit may allow SkMatrix to have unequal horizontal and vertical scaling, or may restrict SkMatrix to square scaling. If restricted, ScaleToFit specifies how SkMatrix maps to the side or center of the destination SkRect. */ enum ScaleToFit { kFill_ScaleToFit, //!< scales in x and y to fill destination SkRect kStart_ScaleToFit, //!< scales and aligns to left and top kCenter_ScaleToFit, //!< scales and aligns to center kEnd_ScaleToFit, //!< scales and aligns to right and bottom }; /** Sets SkMatrix to scale and translate src SkRect to dst SkRect. stf selects whether mapping completely fills dst or preserves the aspect ratio, and how to align src within dst. Returns false if src is empty, and sets SkMatrix to identity. Returns true if dst is empty, and sets SkMatrix to: | 0 0 0 | | 0 0 0 | | 0 0 1 | @param src SkRect to map from @param dst SkRect to map to @param stf one of: kFill_ScaleToFit, kStart_ScaleToFit, kCenter_ScaleToFit, kEnd_ScaleToFit @return true if SkMatrix can represent SkRect mapping */ bool setRectToRect(const SkRect& src, const SkRect& dst, ScaleToFit stf); /** Returns SkMatrix set to scale and translate src SkRect to dst SkRect. stf selects whether mapping completely fills dst or preserves the aspect ratio, and how to align src within dst. Returns the identity SkMatrix if src is empty. If dst is empty, returns SkMatrix set to: | 0 0 0 | | 0 0 0 | | 0 0 1 | @param src SkRect to map from @param dst SkRect to map to @param stf one of: kFill_ScaleToFit, kStart_ScaleToFit, kCenter_ScaleToFit, kEnd_ScaleToFit @return SkMatrix mapping src to dst */ static SkMatrix MakeRectToRect(const SkRect& src, const SkRect& dst, ScaleToFit stf) { SkMatrix m; m.setRectToRect(src, dst, stf); return m; } /** Sets SkMatrix to map src to dst. count must be zero or greater, and four or less. If count is zero, sets SkMatrix to identity and returns true. If count is one, sets SkMatrix to translate and returns true. If count is two or more, sets SkMatrix to map SkPoint if possible; returns false if SkMatrix cannot be constructed. If count is four, SkMatrix may include perspective. @param src SkPoint to map from @param dst SkPoint to map to @param count number of SkPoint in src and dst @return true if SkMatrix was constructed successfully */ bool setPolyToPoly(const SkPoint src[], const SkPoint dst[], int count); /** Sets inverse to reciprocal matrix, returning true if SkMatrix can be inverted. Geometrically, if SkMatrix maps from source to destination, inverse SkMatrix maps from destination to source. If SkMatrix can not be inverted, inverse is unchanged. @param inverse storage for inverted SkMatrix; may be nullptr @return true if SkMatrix can be inverted */ bool SK_WARN_UNUSED_RESULT invert(SkMatrix* inverse) const { // Allow the trivial case to be inlined. if (this->isIdentity()) { if (inverse) { inverse->reset(); } return true; } return this->invertNonIdentity(inverse); } /** Fills affine with identity values in column major order. Sets affine to: | 1 0 0 | | 0 1 0 | Affine 3 by 2 matrices in column major order are used by OpenGL and XPS. @param affine storage for 3 by 2 affine matrix */ static void SetAffineIdentity(SkScalar affine[6]); /** Fills affine in column major order. Sets affine to: | scale-x skew-x translate-x | | skew-y scale-y translate-y | If SkMatrix contains perspective, returns false and leaves affine unchanged. @param affine storage for 3 by 2 affine matrix; may be nullptr @return true if SkMatrix does not contain perspective */ bool SK_WARN_UNUSED_RESULT asAffine(SkScalar affine[6]) const; /** Sets SkMatrix to affine values, passed in column major order. Given affine, column, then row, as: | scale-x skew-x translate-x | | skew-y scale-y translate-y | SkMatrix is set, row, then column, to: | scale-x skew-x translate-x | | skew-y scale-y translate-y | | 0 0 1 | @param affine 3 by 2 affine matrix */ void setAffine(const SkScalar affine[6]); /** Maps src SkPoint array of length count to dst SkPoint array of equal or greater length. SkPoint are mapped by multiplying each SkPoint by SkMatrix. Given: | A B C | | x | Matrix = | D E F |, pt = | y | | G H I | | 1 | where for (i = 0; i < count; ++i) { x = src[i].fX y = src[i].fY } each dst SkPoint is computed as: |A B C| |x| Ax+By+C Dx+Ey+F Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I src and dst may point to the same storage. @param dst storage for mapped SkPoint @param src SkPoint to transform @param count number of SkPoint to transform */ void mapPoints(SkPoint dst[], const SkPoint src[], int count) const; /** Maps pts SkPoint array of length count in place. SkPoint are mapped by multiplying each SkPoint by SkMatrix. Given: | A B C | | x | Matrix = | D E F |, pt = | y | | G H I | | 1 | where for (i = 0; i < count; ++i) { x = pts[i].fX y = pts[i].fY } each resulting pts SkPoint is computed as: |A B C| |x| Ax+By+C Dx+Ey+F Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I @param pts storage for mapped SkPoint @param count number of SkPoint to transform */ void mapPoints(SkPoint pts[], int count) const { this->mapPoints(pts, pts, count); } /** Maps src SkPoint3 array of length count to dst SkPoint3 array, which must of length count or greater. SkPoint3 array is mapped by multiplying each SkPoint3 by SkMatrix. Given: | A B C | | x | Matrix = | D E F |, src = | y | | G H I | | z | each resulting dst SkPoint is computed as: |A B C| |x| Matrix * src = |D E F| |y| = |Ax+By+Cz Dx+Ey+Fz Gx+Hy+Iz| |G H I| |z| @param dst storage for mapped SkPoint3 array @param src SkPoint3 array to transform @param count items in SkPoint3 array to transform */ void mapHomogeneousPoints(SkPoint3 dst[], const SkPoint3 src[], int count) const; /** Maps SkPoint (x, y) to result. SkPoint is mapped by multiplying by SkMatrix. Given: | A B C | | x | Matrix = | D E F |, pt = | y | | G H I | | 1 | result is computed as: |A B C| |x| Ax+By+C Dx+Ey+F Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I @param x x-axis value of SkPoint to map @param y y-axis value of SkPoint to map @param result storage for mapped SkPoint */ void mapXY(SkScalar x, SkScalar y, SkPoint* result) const; /** Returns SkPoint (x, y) multiplied by SkMatrix. Given: | A B C | | x | Matrix = | D E F |, pt = | y | | G H I | | 1 | result is computed as: |A B C| |x| Ax+By+C Dx+Ey+F Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I @param x x-axis value of SkPoint to map @param y y-axis value of SkPoint to map @return mapped SkPoint */ SkPoint mapXY(SkScalar x, SkScalar y) const { SkPoint result; this->mapXY(x,y, &result); return result; } /** Maps src vector array of length count to vector SkPoint array of equal or greater length. Vectors are mapped by multiplying each vector by SkMatrix, treating SkMatrix translation as zero. Given: | A B 0 | | x | Matrix = | D E 0 |, src = | y | | G H I | | 1 | where for (i = 0; i < count; ++i) { x = src[i].fX y = src[i].fY } each dst vector is computed as: |A B 0| |x| Ax+By Dx+Ey Matrix * src = |D E 0| |y| = |Ax+By Dx+Ey Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I src and dst may point to the same storage. @param dst storage for mapped vectors @param src vectors to transform @param count number of vectors to transform */ void mapVectors(SkVector dst[], const SkVector src[], int count) const; /** Maps vecs vector array of length count in place, multiplying each vector by SkMatrix, treating SkMatrix translation as zero. Given: | A B 0 | | x | Matrix = | D E 0 |, vec = | y | | G H I | | 1 | where for (i = 0; i < count; ++i) { x = vecs[i].fX y = vecs[i].fY } each result vector is computed as: |A B 0| |x| Ax+By Dx+Ey Matrix * vec = |D E 0| |y| = |Ax+By Dx+Ey Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I @param vecs vectors to transform, and storage for mapped vectors @param count number of vectors to transform */ void mapVectors(SkVector vecs[], int count) const { this->mapVectors(vecs, vecs, count); } /** Maps vector (dx, dy) to result. Vector is mapped by multiplying by SkMatrix, treating SkMatrix translation as zero. Given: | A B 0 | | dx | Matrix = | D E 0 |, vec = | dy | | G H I | | 1 | each result vector is computed as: |A B 0| |dx| A*dx+B*dy D*dx+E*dy Matrix * vec = |D E 0| |dy| = |A*dx+B*dy D*dx+E*dy G*dx+H*dy+I| = ----------- , ----------- |G H I| | 1| G*dx+H*dy+I G*dx+*dHy+I @param dx x-axis value of vector to map @param dy y-axis value of vector to map @param result storage for mapped vector */ void mapVector(SkScalar dx, SkScalar dy, SkVector* result) const { SkVector vec = { dx, dy }; this->mapVectors(result, &vec, 1); } /** Returns vector (dx, dy) multiplied by SkMatrix, treating SkMatrix translation as zero. Given: | A B 0 | | dx | Matrix = | D E 0 |, vec = | dy | | G H I | | 1 | each result vector is computed as: |A B 0| |dx| A*dx+B*dy D*dx+E*dy Matrix * vec = |D E 0| |dy| = |A*dx+B*dy D*dx+E*dy G*dx+H*dy+I| = ----------- , ----------- |G H I| | 1| G*dx+H*dy+I G*dx+*dHy+I @param dx x-axis value of vector to map @param dy y-axis value of vector to map @return mapped vector */ SkVector mapVector(SkScalar dx, SkScalar dy) const { SkVector vec = { dx, dy }; this->mapVectors(&vec, &vec, 1); return vec; } /** Sets dst to bounds of src corners mapped by SkMatrix. Returns true if mapped corners are dst corners. Returned value is the same as calling rectStaysRect(). @param dst storage for bounds of mapped SkPoint @param src SkRect to map @return true if dst is equivalent to mapped src */ bool mapRect(SkRect* dst, const SkRect& src) const; /** Sets rect to bounds of rect corners mapped by SkMatrix. Returns true if mapped corners are computed rect corners. Returned value is the same as calling rectStaysRect(). @param rect rectangle to map, and storage for bounds of mapped corners @return true if result is equivalent to mapped rect */ bool mapRect(SkRect* rect) const { return this->mapRect(rect, *rect); } /** Returns bounds of src corners mapped by SkMatrix. @param src rectangle to map @return mapped bounds */ SkRect mapRect(const SkRect& src) const { SkRect dst; (void)this->mapRect(&dst, src); return dst; } /** Maps four corners of rect to dst. SkPoint are mapped by multiplying each rect corner by SkMatrix. rect corner is processed in this order: (rect.fLeft, rect.fTop), (rect.fRight, rect.fTop), (rect.fRight, rect.fBottom), (rect.fLeft, rect.fBottom). rect may be empty: rect.fLeft may be greater than or equal to rect.fRight; rect.fTop may be greater than or equal to rect.fBottom. Given: | A B C | | x | Matrix = | D E F |, pt = | y | | G H I | | 1 | where pt is initialized from each of (rect.fLeft, rect.fTop), (rect.fRight, rect.fTop), (rect.fRight, rect.fBottom), (rect.fLeft, rect.fBottom), each dst SkPoint is computed as: |A B C| |x| Ax+By+C Dx+Ey+F Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , ------- |G H I| |1| Gx+Hy+I Gx+Hy+I @param dst storage for mapped corner SkPoint @param rect SkRect to map */ void mapRectToQuad(SkPoint dst[4], const SkRect& rect) const { // This could potentially be faster if we only transformed each x and y of the rect once. rect.toQuad(dst); this->mapPoints(dst, 4); } /** Sets dst to bounds of src corners mapped by SkMatrix. If matrix contains elements other than scale or translate: asserts if SK_DEBUG is defined; otherwise, results are undefined. @param dst storage for bounds of mapped SkPoint @param src SkRect to map */ void mapRectScaleTranslate(SkRect* dst, const SkRect& src) const; /** Returns geometric mean radius of ellipse formed by constructing circle of size radius, and mapping constructed circle with SkMatrix. The result squared is equal to the major axis length times the minor axis length. Result is not meaningful if SkMatrix contains perspective elements. @param radius circle size to map @return average mapped radius */ SkScalar mapRadius(SkScalar radius) const; /** Returns true if a unit step on x-axis at some y-axis value mapped through SkMatrix can be represented by a constant vector. Returns true if getType() returns kIdentity_Mask, or combinations of: kTranslate_Mask, kScale_Mask, and kAffine_Mask. May return true if getType() returns kPerspective_Mask, but only when SkMatrix does not include rotation or skewing along the y-axis. @return true if SkMatrix does not have complex perspective */ bool isFixedStepInX() const; /** Returns vector representing a unit step on x-axis at y mapped through SkMatrix. If isFixedStepInX() is false, returned value is undefined. @param y position of line parallel to x-axis @return vector advance of mapped unit step on x-axis */ SkVector fixedStepInX(SkScalar y) const; /** Returns true if SkMatrix equals m, using an efficient comparison. Returns false when the sign of zero values is the different; when one matrix has positive zero value and the other has negative zero value. Returns true even when both SkMatrix contain NaN. NaN never equals any value, including itself. To improve performance, NaN values are treated as bit patterns that are equal if their bit patterns are equal. @param m SkMatrix to compare @return true if m and SkMatrix are represented by identical bit patterns */ bool cheapEqualTo(const SkMatrix& m) const { return 0 == memcmp(fMat, m.fMat, sizeof(fMat)); } /** Compares a and b; returns true if a and b are numerically equal. Returns true even if sign of zero values are different. Returns false if either SkMatrix contains NaN, even if the other SkMatrix also contains NaN. @param a SkMatrix to compare @param b SkMatrix to compare @return true if SkMatrix a and SkMatrix b are numerically equal */ friend SK_API bool operator==(const SkMatrix& a, const SkMatrix& b); /** Compares a and b; returns true if a and b are not numerically equal. Returns false even if sign of zero values are different. Returns true if either SkMatrix contains NaN, even if the other SkMatrix also contains NaN. @param a SkMatrix to compare @param b SkMatrix to compare @return true if SkMatrix a and SkMatrix b are numerically not equal */ friend SK_API bool operator!=(const SkMatrix& a, const SkMatrix& b) { return !(a == b); } /** Writes text representation of SkMatrix to standard output. Floating point values are written with limited precision; it may not be possible to reconstruct original SkMatrix from output. */ void dump() const; /** Returns the minimum scaling factor of SkMatrix by decomposing the scaling and skewing elements. Returns -1 if scale factor overflows or SkMatrix contains perspective. @return minimum scale factor */ SkScalar getMinScale() const; /** Returns the maximum scaling factor of SkMatrix by decomposing the scaling and skewing elements. Returns -1 if scale factor overflows or SkMatrix contains perspective. @return maximum scale factor */ SkScalar getMaxScale() const; /** Sets scaleFactors[0] to the minimum scaling factor, and scaleFactors[1] to the maximum scaling factor. Scaling factors are computed by decomposing the SkMatrix scaling and skewing elements. Returns true if scaleFactors are found; otherwise, returns false and sets scaleFactors to undefined values. @param scaleFactors storage for minimum and maximum scale factors @return true if scale factors were computed correctly */ bool SK_WARN_UNUSED_RESULT getMinMaxScales(SkScalar scaleFactors[2]) const; /** Decomposes SkMatrix into scale components and whatever remains. Returns false if SkMatrix could not be decomposed. Sets scale to portion of SkMatrix that scale axes. Sets remaining to SkMatrix with scaling factored out. remaining may be passed as nullptr to determine if SkMatrix can be decomposed without computing remainder. Returns true if scale components are found. scale and remaining are unchanged if SkMatrix contains perspective; scale factors are not finite, or are nearly zero. On success: Matrix = scale * Remaining. @param scale axes scaling factors; may be nullptr @param remaining SkMatrix without scaling; may be nullptr @return true if scale can be computed */ bool decomposeScale(SkSize* scale, SkMatrix* remaining = nullptr) const; /** Returns reference to const identity SkMatrix. Returned SkMatrix is set to: | 1 0 0 | | 0 1 0 | | 0 0 1 | @return const identity SkMatrix */ static const SkMatrix& I(); /** Returns reference to a const SkMatrix with invalid values. Returned SkMatrix is set to: | SK_ScalarMax SK_ScalarMax SK_ScalarMax | | SK_ScalarMax SK_ScalarMax SK_ScalarMax | | SK_ScalarMax SK_ScalarMax SK_ScalarMax | @return const invalid SkMatrix */ static const SkMatrix& InvalidMatrix(); /** Returns SkMatrix a multiplied by SkMatrix b. Given: | A B C | | J K L | a = | D E F |, b = | M N O | | G H I | | P Q R | sets SkMatrix to: | A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR | a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR | | G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR | @param a SkMatrix on left side of multiply expression @param b SkMatrix on right side of multiply expression @return SkMatrix computed from a times b */ static SkMatrix Concat(const SkMatrix& a, const SkMatrix& b) { SkMatrix result; result.setConcat(a, b); return result; } /** Sets internal cache to unknown state. Use to force update after repeated modifications to SkMatrix element reference returned by operator[](int index). */ void dirtyMatrixTypeCache() { this->setTypeMask(kUnknown_Mask); } /** Initializes SkMatrix with scale and translate elements. | sx 0 tx | | 0 sy ty | | 0 0 1 | @param sx horizontal scale factor to store @param sy vertical scale factor to store @param tx horizontal translation to store @param ty vertical translation to store */ void setScaleTranslate(SkScalar sx, SkScalar sy, SkScalar tx, SkScalar ty) { fMat[kMScaleX] = sx; fMat[kMSkewX] = 0; fMat[kMTransX] = tx; fMat[kMSkewY] = 0; fMat[kMScaleY] = sy; fMat[kMTransY] = ty; fMat[kMPersp0] = 0; fMat[kMPersp1] = 0; fMat[kMPersp2] = 1; unsigned mask = 0; if (sx != 1 || sy != 1) { mask |= kScale_Mask; } if (tx || ty) { mask |= kTranslate_Mask; } this->setTypeMask(mask | kRectStaysRect_Mask); } /** Returns true if all elements of the matrix are finite. Returns false if any element is infinity, or NaN. @return true if matrix has only finite elements */ bool isFinite() const { return SkScalarsAreFinite(fMat, 9); } private: /** Set if the matrix will map a rectangle to another rectangle. This can be true if the matrix is scale-only, or rotates a multiple of 90 degrees. This bit will be set on identity matrices */ static constexpr int kRectStaysRect_Mask = 0x10; /** Set if the perspective bit is valid even though the rest of the matrix is Unknown. */ static constexpr int kOnlyPerspectiveValid_Mask = 0x40; static constexpr int kUnknown_Mask = 0x80; static constexpr int kORableMasks = kTranslate_Mask | kScale_Mask | kAffine_Mask | kPerspective_Mask; static constexpr int kAllMasks = kTranslate_Mask | kScale_Mask | kAffine_Mask | kPerspective_Mask | kRectStaysRect_Mask; SkScalar fMat[9]; mutable uint32_t fTypeMask; constexpr SkMatrix(SkScalar sx, SkScalar kx, SkScalar tx, SkScalar ky, SkScalar sy, SkScalar ty, SkScalar p0, SkScalar p1, SkScalar p2, uint32_t typeMask) : fMat{sx, kx, tx, ky, sy, ty, p0, p1, p2} , fTypeMask(typeMask) {} static void ComputeInv(SkScalar dst[9], const SkScalar src[9], double invDet, bool isPersp); uint8_t computeTypeMask() const; uint8_t computePerspectiveTypeMask() const; void setTypeMask(int mask) { // allow kUnknown or a valid mask SkASSERT(kUnknown_Mask == mask || (mask & kAllMasks) == mask || ((kUnknown_Mask | kOnlyPerspectiveValid_Mask) & mask) == (kUnknown_Mask | kOnlyPerspectiveValid_Mask)); fTypeMask = SkToU8(mask); } void orTypeMask(int mask) { SkASSERT((mask & kORableMasks) == mask); fTypeMask = SkToU8(fTypeMask | mask); } void clearTypeMask(int mask) { // only allow a valid mask SkASSERT((mask & kAllMasks) == mask); fTypeMask = fTypeMask & ~mask; } TypeMask getPerspectiveTypeMaskOnly() const { if ((fTypeMask & kUnknown_Mask) && !(fTypeMask & kOnlyPerspectiveValid_Mask)) { fTypeMask = this->computePerspectiveTypeMask(); } return (TypeMask)(fTypeMask & 0xF); } /** Returns true if we already know that the matrix is identity; false otherwise. */ bool isTriviallyIdentity() const { if (fTypeMask & kUnknown_Mask) { return false; } return ((fTypeMask & 0xF) == 0); } inline void updateTranslateMask() { if ((fMat[kMTransX] != 0) | (fMat[kMTransY] != 0)) { fTypeMask |= kTranslate_Mask; } else { fTypeMask &= ~kTranslate_Mask; } } typedef void (*MapXYProc)(const SkMatrix& mat, SkScalar x, SkScalar y, SkPoint* result); static MapXYProc GetMapXYProc(TypeMask mask) { SkASSERT((mask & ~kAllMasks) == 0); return gMapXYProcs[mask & kAllMasks]; } MapXYProc getMapXYProc() const { return GetMapXYProc(this->getType()); } typedef void (*MapPtsProc)(const SkMatrix& mat, SkPoint dst[], const SkPoint src[], int count); static MapPtsProc GetMapPtsProc(TypeMask mask) { SkASSERT((mask & ~kAllMasks) == 0); return gMapPtsProcs[mask & kAllMasks]; } MapPtsProc getMapPtsProc() const { return GetMapPtsProc(this->getType()); } bool SK_WARN_UNUSED_RESULT invertNonIdentity(SkMatrix* inverse) const; static bool Poly2Proc(const SkPoint[], SkMatrix*); static bool Poly3Proc(const SkPoint[], SkMatrix*); static bool Poly4Proc(const SkPoint[], SkMatrix*); static void Identity_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void Trans_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void Scale_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void ScaleTrans_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void Rot_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void RotTrans_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static void Persp_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*); static const MapXYProc gMapXYProcs[]; static void Identity_pts(const SkMatrix&, SkPoint[], const SkPoint[], int); static void Trans_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int); static void Scale_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int); static void ScaleTrans_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int count); static void Persp_pts(const SkMatrix&, SkPoint dst[], const SkPoint[], int); static void Affine_vpts(const SkMatrix&, SkPoint dst[], const SkPoint[], int); static const MapPtsProc gMapPtsProcs[]; // return the number of bytes written, whether or not buffer is null size_t writeToMemory(void* buffer) const; /** * Reads data from the buffer parameter * * @param buffer Memory to read from * @param length Amount of memory available in the buffer * @return number of bytes read (must be a multiple of 4) or * 0 if there was not enough memory available */ size_t readFromMemory(const void* buffer, size_t length); friend class SkPerspIter; friend class SkMatrixPriv; friend class SkReader32; friend class SerializationTest; }; SK_END_REQUIRE_DENSE #endif
[ "42931768+uzair-jaleel@users.noreply.github.com" ]
42931768+uzair-jaleel@users.noreply.github.com
470ee3f174a753ed299cf0db0ba6eb43fcfae769
1e865fc059b0fc625bd34606f3da68328baf33ef
/src/darksend.cpp
9d1787c73d233e852dd1d0de25933a06f8bf1eca
[ "MIT" ]
permissive
airincoin/airin_old
94228c86b1825578057ec79536829756cf2f8973
4930ccbf166130156ab2641179800d4e84b36b33
refs/heads/master
2020-03-14T06:54:36.628450
2018-05-02T00:56:41
2018-05-02T00:56:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
99,323
cpp
// Copyright (c) 2014-2017 The Airin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "coincontrol.h" #include "consensus/validation.h" #include "darksend.h" #include "governance.h" #include "init.h" #include "instantx.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "script/sign.h" #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" #include <boost/lexical_cast.hpp> int nPrivateSendRounds = DEFAULT_PRIVATESEND_ROUNDS; int nPrivateSendAmount = DEFAULT_PRIVATESEND_AMOUNT; int nLiquidityProvider = DEFAULT_PRIVATESEND_LIQUIDITY; bool fEnablePrivateSend = false; bool fPrivateSendMultiSession = DEFAULT_PRIVATESEND_MULTISESSION; CDarksendPool darkSendPool; CDarkSendSigner darkSendSigner; std::map<uint256, CDarksendBroadcastTx> mapDarksendBroadcastTxes; std::vector<CAmount> vecPrivateSendDenominations; void CDarksendPool::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if(fLiteMode) return; // ignore all Airin related functionality if(!masternodeSync.IsBlockchainSynced()) return; if(strCommand == NetMsgType::DSACCEPT) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSACCEPT -- incompatible version! nVersion: %d\n", pfrom->nVersion); PushStatus(pfrom, STATUS_REJECTED, ERR_VERSION); return; } if(!fMasterNode) { LogPrintf("DSACCEPT -- not a Masternode!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_NOT_A_MN); return; } if(IsSessionReady()) { // too many users in this session already, reject new ones LogPrintf("DSACCEPT -- queue is already full!\n"); PushStatus(pfrom, STATUS_ACCEPTED, ERR_QUEUE_FULL); return; } int nDenom; CTransaction txCollateral; vRecv >> nDenom >> txCollateral; LogPrint("privatesend", "DSACCEPT -- nDenom %d (%s) txCollateral %s", nDenom, GetDenominationsToString(nDenom), txCollateral.ToString()); CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if(pmn == NULL) { PushStatus(pfrom, STATUS_REJECTED, ERR_MN_LIST); return; } if(vecSessionCollaterals.size() == 0 && pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5 > mnodeman.nDsqCount) { LogPrintf("DSACCEPT -- last dsq too recent, must wait: addr=%s\n", pfrom->addr.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_RECENT); return; } PoolMessage nMessageID = MSG_NOERR; bool fResult = nSessionID == 0 ? CreateNewSession(nDenom, txCollateral, nMessageID) : AddUserToExistingSession(nDenom, txCollateral, nMessageID); if(fResult) { LogPrintf("DSACCEPT -- is compatible, please submit!\n"); PushStatus(pfrom, STATUS_ACCEPTED, nMessageID); return; } else { LogPrintf("DSACCEPT -- not compatible with existing transactions!\n"); PushStatus(pfrom, STATUS_REJECTED, nMessageID); return; } } else if(strCommand == NetMsgType::DSQUEUE) { TRY_LOCK(cs_darksend, lockRecv); if(!lockRecv) return; if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSQUEUE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } CDarksendQueue dsq; vRecv >> dsq; // process every dsq only once BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q == dsq) { // LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString()); return; } } LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString()); if(dsq.IsExpired() || dsq.nTime > GetTime() + PRIVATESEND_QUEUE_TIMEOUT) return; CMasternode* pmn = mnodeman.Find(dsq.vin); if(pmn == NULL) return; if(!dsq.CheckSignature(pmn->pubKeyMasternode)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.vin); return; } // if the queue is ready, submit if we can if(dsq.fReady) { if(!pSubmittedToMasternode) return; if((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pmn->addr) { LogPrintf("DSQUEUE -- message doesn't match current Masternode: pSubmittedToMasternode=%s, addr=%s\n", pSubmittedToMasternode->addr.ToString(), pmn->addr.ToString()); return; } if(nState == POOL_STATE_QUEUE) { LogPrint("privatesend", "DSQUEUE -- PrivateSend queue (%s) is ready on masternode %s\n", dsq.ToString(), pmn->addr.ToString()); SubmitDenominate(); } } else { BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q.vin == dsq.vin) { // no way same mn can send another "not yet ready" dsq this soon LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", pmn->addr.ToString()); return; } } int nThreshold = pmn->nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5; LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", pmn->nLastDsq, nThreshold, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process if(pmn->nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", pmn->addr.ToString()); return; } mnodeman.nDsqCount++; pmn->nLastDsq = mnodeman.nDsqCount; pmn->fAllowMixingTx = true; LogPrint("privatesend", "DSQUEUE -- new PrivateSend queue (%s) from masternode %s\n", dsq.ToString(), pmn->addr.ToString()); if(pSubmittedToMasternode && pSubmittedToMasternode->vin.prevout == dsq.vin.prevout) { dsq.fTried = true; } vecDarksendQueue.push_back(dsq); dsq.Relay(); } } else if(strCommand == NetMsgType::DSVIN) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSVIN -- incompatible version! nVersion: %d\n", pfrom->nVersion); PushStatus(pfrom, STATUS_REJECTED, ERR_VERSION); return; } if(!fMasterNode) { LogPrintf("DSVIN -- not a Masternode!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_NOT_A_MN); return; } //do we have enough users in the current session? if(!IsSessionReady()) { LogPrintf("DSVIN -- session not complete!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_SESSION); return; } CDarkSendEntry entry; vRecv >> entry; LogPrint("privatesend", "DSVIN -- txCollateral %s", entry.txCollateral.ToString()); //do we have the same denominations as the current session? if(!IsOutputsCompatibleWithSessionDenom(entry.vecTxDSOut)) { LogPrintf("DSVIN -- not compatible with existing transactions!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_EXISTING_TX); return; } //check it like a transaction { CAmount nValueIn = 0; CAmount nValueOut = 0; CMutableTransaction tx; BOOST_FOREACH(const CTxOut txout, entry.vecTxDSOut) { nValueOut += txout.nValue; tx.vout.push_back(txout); if(txout.scriptPubKey.size() != 25) { LogPrintf("DSVIN -- non-standard pubkey detected! scriptPubKey=%s\n", ScriptToAsmStr(txout.scriptPubKey)); PushStatus(pfrom, STATUS_REJECTED, ERR_NON_STANDARD_PUBKEY); return; } if(!txout.scriptPubKey.IsNormalPaymentScript()) { LogPrintf("DSVIN -- invalid script! scriptPubKey=%s\n", ScriptToAsmStr(txout.scriptPubKey)); PushStatus(pfrom, STATUS_REJECTED, ERR_INVALID_SCRIPT); return; } } BOOST_FOREACH(const CTxIn txin, entry.vecTxDSIn) { tx.vin.push_back(txin); LogPrint("privatesend", "DSVIN -- txin=%s\n", txin.ToString()); CTransaction txPrev; uint256 hash; if(GetTransaction(txin.prevout.hash, txPrev, Params().GetConsensus(), hash, true)) { if(txPrev.vout.size() > txin.prevout.n) nValueIn += txPrev.vout[txin.prevout.n].nValue; } else { LogPrintf("DSVIN -- missing input! tx=%s", tx.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_MISSING_TX); return; } } if(nValueIn > PRIVATESEND_POOL_MAX) { LogPrintf("DSVIN -- more than PrivateSend pool max! nValueIn: %lld, tx=%s", nValueIn, tx.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_MAXIMUM); return; } // Allow lowest denom (at max) as a a fee. Normally shouldn't happen though. // TODO: Or do not allow fees at all? if(nValueIn - nValueOut > vecPrivateSendDenominations.back()) { LogPrintf("DSVIN -- fees are too high! fees: %lld, tx=%s", nValueIn - nValueOut, tx.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_FEES); return; } { LOCK(cs_main); CValidationState validationState; mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), 1000, 0.1*COIN); if(!AcceptToMemoryPool(mempool, validationState, CTransaction(tx), false, NULL, false, true, true)) { LogPrintf("DSVIN -- transaction not valid! tx=%s", tx.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_INVALID_TX); return; } } } PoolMessage nMessageID = MSG_NOERR; if(AddEntry(entry, nMessageID)) { PushStatus(pfrom, STATUS_ACCEPTED, nMessageID); CheckPool(); RelayStatus(STATUS_ACCEPTED); } else { PushStatus(pfrom, STATUS_REJECTED, nMessageID); SetNull(); } } else if(strCommand == NetMsgType::DSSTATUSUPDATE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSSTATUSUPDATE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(fMasterNode) { // LogPrintf("DSSTATUSUPDATE -- Can't run on a Masternode!\n"); return; } if(!pSubmittedToMasternode) return; if((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("DSSTATUSUPDATE -- message doesn't match current Masternode: pSubmittedToMasternode %s addr %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgState; int nMsgEntriesCount; int nMsgStatusUpdate; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgState >> nMsgEntriesCount >> nMsgStatusUpdate >> nMsgMessageID; LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d\n", nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID); if(nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgState is out of bounds: %d\n", nMsgState); return; } if(nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d\n", nMsgStatusUpdate); return; } if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } LogPrint("privatesend", "DSSTATUSUPDATE -- GetMessageByID: %s\n", GetMessageByID(PoolMessage(nMsgMessageID))); if(!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) { LogPrint("privatesend", "DSSTATUSUPDATE -- CheckPoolStateUpdate failed\n"); } } else if(strCommand == NetMsgType::DSSIGNFINALTX) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSSIGNFINALTX -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!fMasterNode) { LogPrintf("DSSIGNFINALTX -- not a Masternode!\n"); return; } std::vector<CTxIn> vecTxIn; vRecv >> vecTxIn; LogPrint("privatesend", "DSSIGNFINALTX -- vecTxIn.size() %s\n", vecTxIn.size()); int nTxInIndex = 0; int nTxInsCount = (int)vecTxIn.size(); BOOST_FOREACH(const CTxIn txin, vecTxIn) { nTxInIndex++; if(!AddScriptSig(txin)) { LogPrint("privatesend", "DSSIGNFINALTX -- AddScriptSig() failed at %d/%d, session: %d\n", nTxInIndex, nTxInsCount, nSessionID); RelayStatus(STATUS_REJECTED); return; } LogPrint("privatesend", "DSSIGNFINALTX -- AddScriptSig() %d/%d success\n", nTxInIndex, nTxInsCount); } // all is good CheckPool(); } else if(strCommand == NetMsgType::DSFINALTX) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSFINALTX -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(fMasterNode) { // LogPrintf("DSFINALTX -- Can't run on a Masternode!\n"); return; } if(!pSubmittedToMasternode) return; if((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("DSFINALTX -- message doesn't match current Masternode: pSubmittedToMasternode %s addr %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; CTransaction txNew; vRecv >> nMsgSessionID >> txNew; if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSFINALTX -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSFINALTX -- txNew %s", txNew.ToString()); //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom); } else if(strCommand == NetMsgType::DSCOMPLETE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSCOMPLETE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(fMasterNode) { // LogPrintf("DSCOMPLETE -- Can't run on a Masternode!\n"); return; } if(!pSubmittedToMasternode) return; if((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current Masternode: pSubmittedToMasternode=%s addr=%s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgMessageID; if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", darkSendPool.nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s)\n", nMsgSessionID, nMsgMessageID, GetMessageByID(PoolMessage(nMsgMessageID))); CompletedTransaction(PoolMessage(nMsgMessageID)); } } void CDarksendPool::InitDenominations() { vecPrivateSendDenominations.clear(); /* Denominations A note about convertability. Within mixing pools, each denomination is convertable to another. For example: 1DRK+1000 == (.1DRK+100)*10 10DRK+10000 == (1DRK+1000)*10 */ /* Disabled vecPrivateSendDenominations.push_back( (100 * COIN)+100000 ); */ vecPrivateSendDenominations.push_back( (10 * COIN)+10000 ); vecPrivateSendDenominations.push_back( (1 * COIN)+1000 ); vecPrivateSendDenominations.push_back( (.1 * COIN)+100 ); vecPrivateSendDenominations.push_back( (.01 * COIN)+10 ); /* Disabled till we need them vecPrivateSendDenominations.push_back( (.001 * COIN)+1 ); */ } void CDarksendPool::ResetPool() { nCachedLastSuccessBlock = 0; txMyCollateral = CMutableTransaction(); vecMasternodesUsed.clear(); UnlockCoins(); SetNull(); } void CDarksendPool::SetNull() { // MN side vecSessionCollaterals.clear(); // Client side nEntriesCount = 0; fLastEntryAccepted = false; pSubmittedToMasternode = NULL; // Both sides nState = POOL_STATE_IDLE; nSessionID = 0; nSessionDenom = 0; vecEntries.clear(); finalMutableTransaction.vin.clear(); finalMutableTransaction.vout.clear(); nTimeLastSuccessfulStep = GetTimeMillis(); } // // Unlock coins after mixing fails or succeeds // void CDarksendPool::UnlockCoins() { while(true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if(!lockWallet) {MilliSleep(50); continue;} BOOST_FOREACH(COutPoint outpoint, vecOutPointLocked) pwalletMain->UnlockCoin(outpoint); break; } vecOutPointLocked.clear(); } std::string CDarksendPool::GetStateString() const { switch(nState) { case POOL_STATE_IDLE: return "IDLE"; case POOL_STATE_QUEUE: return "QUEUE"; case POOL_STATE_ACCEPTING_ENTRIES: return "ACCEPTING_ENTRIES"; case POOL_STATE_SIGNING: return "SIGNING"; case POOL_STATE_ERROR: return "ERROR"; case POOL_STATE_SUCCESS: return "SUCCESS"; default: return "UNKNOWN"; } } std::string CDarksendPool::GetStatus() { static int nStatusMessageProgress = 0; nStatusMessageProgress += 10; std::string strSuffix = ""; if((pCurrentBlockIndex && pCurrentBlockIndex->nHeight - nCachedLastSuccessBlock < nMinBlockSpacing) || !masternodeSync.IsBlockchainSynced()) return strAutoDenomResult; switch(nState) { case POOL_STATE_IDLE: return _("PrivateSend is idle."); case POOL_STATE_QUEUE: if( nStatusMessageProgress % 70 <= 30) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix);; case POOL_STATE_ACCEPTING_ENTRIES: if(nEntriesCount == 0) { nStatusMessageProgress = 0; return strAutoDenomResult; } else if(fLastEntryAccepted) { if(nStatusMessageProgress % 10 > 8) { fLastEntryAccepted = false; nStatusMessageProgress = 0; } return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!"); } else { if( nStatusMessageProgress % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, GetMaxPoolTransactions()); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, GetMaxPoolTransactions(), strSuffix); } case POOL_STATE_SIGNING: if( nStatusMessageProgress % 70 <= 40) return _("Found enough users, signing ..."); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix); case POOL_STATE_ERROR: return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry..."); case POOL_STATE_SUCCESS: return _("PrivateSend request complete:") + " " + strLastMessage; default: return strprintf(_("Unknown state: id = %u"), nState); } } // // Check the mixing progress and send client updates if a Masternode // void CDarksendPool::CheckPool() { if(fMasterNode) { LogPrint("privatesend", "CDarksendPool::CheckPool -- entries count %lu\n", GetEntriesCount()); // If entries are full, create finalized transaction if(nState == POOL_STATE_ACCEPTING_ENTRIES && GetEntriesCount() >= GetMaxPoolTransactions()) { LogPrint("privatesend", "CDarksendPool::CheckPool -- FINALIZE TRANSACTIONS\n"); CreateFinalTransaction(); return; } // If we have all of the signatures, try to compile the transaction if(nState == POOL_STATE_SIGNING && IsSignaturesComplete()) { LogPrint("privatesend", "CDarksendPool::CheckPool -- SIGNING\n"); CommitFinalTransaction(); return; } } // reset if we're here for 10 seconds if((nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) && GetTimeMillis() - nTimeLastSuccessfulStep >= 10000) { LogPrint("privatesend", "CDarksendPool::CheckPool -- timeout, RESETTING\n"); UnlockCoins(); SetNull(); } } void CDarksendPool::CreateFinalTransaction() { LogPrint("privatesend", "CDarksendPool::CreateFinalTransaction -- FINALIZE TRANSACTIONS\n"); CMutableTransaction txNew; // make our new transaction for(int i = 0; i < GetEntriesCount(); i++) { BOOST_FOREACH(const CTxDSOut& txdsout, vecEntries[i].vecTxDSOut) txNew.vout.push_back(txdsout); BOOST_FOREACH(const CTxDSIn& txdsin, vecEntries[i].vecTxDSIn) txNew.vin.push_back(txdsin); } // BIP69 https://github.com/kristovatlas/bips/blob/master/bip-0069.mediawiki sort(txNew.vin.begin(), txNew.vin.end()); sort(txNew.vout.begin(), txNew.vout.end()); finalMutableTransaction = txNew; LogPrint("privatesend", "CDarksendPool::CreateFinalTransaction -- finalMutableTransaction=%s", txNew.ToString()); // request signatures from clients RelayFinalTransaction(finalMutableTransaction); SetState(POOL_STATE_SIGNING); } void CDarksendPool::CommitFinalTransaction() { if(!fMasterNode) return; // check and relay final tx only on masternode CTransaction finalTransaction = CTransaction(finalMutableTransaction); uint256 hashTx = finalTransaction.GetHash(); LogPrint("privatesend", "CDarksendPool::CommitFinalTransaction -- finalTransaction=%s", finalTransaction.ToString()); { // See if the transaction is valid TRY_LOCK(cs_main, lockMain); CValidationState validationState; mempool.PrioritiseTransaction(hashTx, hashTx.ToString(), 1000, 0.1*COIN); if(!lockMain || !AcceptToMemoryPool(mempool, validationState, finalTransaction, false, NULL, false, true, true)) { LogPrintf("CDarksendPool::CommitFinalTransaction -- AcceptToMemoryPool() error: Transaction not valid\n"); SetNull(); // not much we can do in this case, just notify clients RelayCompletedTransaction(ERR_INVALID_TX); return; } } LogPrintf("CDarksendPool::CommitFinalTransaction -- CREATING DSTX\n"); // create and sign masternode dstx transaction if(!mapDarksendBroadcastTxes.count(hashTx)) { CDarksendBroadcastTx dstx(finalTransaction, activeMasternode.vin, GetAdjustedTime()); dstx.Sign(); mapDarksendBroadcastTxes.insert(std::make_pair(hashTx, dstx)); } LogPrintf("CDarksendPool::CommitFinalTransaction -- TRANSMITTING DSTX\n"); CInv inv(MSG_DSTX, hashTx); RelayInv(inv); // Tell the clients it was successful RelayCompletedTransaction(MSG_SUCCESS); // Randomly charge clients ChargeRandomFees(); // Reset LogPrint("privatesend", "CDarksendPool::CommitFinalTransaction -- COMPLETED -- RESETTING\n"); SetNull(); } // // Charge clients a fee if they're abusive // // Why bother? PrivateSend uses collateral to ensure abuse to the process is kept to a minimum. // The submission and signing stages are completely separate. In the cases where // a client submits a transaction then refused to sign, there must be a cost. Otherwise they // would be able to do this over and over again and bring the mixing to a hault. // // How does this work? Messages to Masternodes come in via NetMsgType::DSVIN, these require a valid collateral // transaction for the client to be able to enter the pool. This transaction is kept by the Masternode // until the transaction is either complete or fails. // void CDarksendPool::ChargeFees() { if(!fMasterNode) return; //we don't need to charge collateral for every offence. if(GetRandInt(100) > 33) return; std::vector<CTransaction> vecOffendersCollaterals; if(nState == POOL_STATE_ACCEPTING_ENTRIES) { BOOST_FOREACH(const CTransaction& txCollateral, vecSessionCollaterals) { bool fFound = false; BOOST_FOREACH(const CDarkSendEntry& entry, vecEntries) if(entry.txCollateral == txCollateral) fFound = true; // This queue entry didn't send us the promised transaction if(!fFound) { LogPrintf("CDarksendPool::ChargeFees -- found uncooperative node (didn't send transaction), found offence\n"); vecOffendersCollaterals.push_back(txCollateral); } } } if(nState == POOL_STATE_SIGNING) { // who didn't sign? BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) { BOOST_FOREACH(const CTxDSIn txdsin, entry.vecTxDSIn) { if(!txdsin.fHasSig) { LogPrintf("CDarksendPool::ChargeFees -- found uncooperative node (didn't sign), found offence\n"); vecOffendersCollaterals.push_back(entry.txCollateral); } } } } // no offences found if(vecOffendersCollaterals.empty()) return; //mostly offending? Charge sometimes if((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions() - 1 && GetRandInt(100) > 33) return; //everyone is an offender? That's not right if((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions()) return; //charge one of the offenders randomly std::random_shuffle(vecOffendersCollaterals.begin(), vecOffendersCollaterals.end()); if(nState == POOL_STATE_ACCEPTING_ENTRIES || nState == POOL_STATE_SIGNING) { LogPrintf("CDarksendPool::ChargeFees -- found uncooperative node (didn't %s transaction), charging fees: %s\n", (nState == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0].ToString()); LOCK(cs_main); CValidationState state; bool fMissingInputs; if(!AcceptToMemoryPool(mempool, state, vecOffendersCollaterals[0], false, &fMissingInputs, false, true)) { // should never really happen LogPrintf("CDarksendPool::ChargeFees -- ERROR: AcceptToMemoryPool failed!\n"); } else { RelayTransaction(vecOffendersCollaterals[0]); } } } /* Charge the collateral randomly. Mixing is completely free, to pay miners we randomly pay the collateral of users. Collateral Fee Charges: Being that mixing has "no fees" we need to have some kind of cost associated with using it to stop abuse. Otherwise it could serve as an attack vector and allow endless transaction that would bloat Airin and make it unusable. To stop these kinds of attacks 1 in 10 successful transactions are charged. This adds up to a cost of 0.001DRK per transaction on average. */ void CDarksendPool::ChargeRandomFees() { if(!fMasterNode) return; LOCK(cs_main); BOOST_FOREACH(const CTransaction& txCollateral, vecSessionCollaterals) { if(GetRandInt(100) > 10) return; LogPrintf("CDarksendPool::ChargeRandomFees -- charging random fees, txCollateral=%s", txCollateral.ToString()); CValidationState state; bool fMissingInputs; if(!AcceptToMemoryPool(mempool, state, txCollateral, false, &fMissingInputs, false, true)) { // should never really happen LogPrintf("CDarksendPool::ChargeRandomFees -- ERROR: AcceptToMemoryPool failed!\n"); } else { RelayTransaction(txCollateral); } } } // // Check for various timeouts (queue objects, mixing, etc) // void CDarksendPool::CheckTimeout() { { TRY_LOCK(cs_darksend, lockDS); if(!lockDS) return; // it's ok to fail here, we run this quite frequently // check mixing queue objects for timeouts std::vector<CDarksendQueue>::iterator it = vecDarksendQueue.begin(); while(it != vecDarksendQueue.end()) { if((*it).IsExpired()) { LogPrint("privatesend", "CDarksendPool::CheckTimeout -- Removing expired queue (%s)\n", (*it).ToString()); it = vecDarksendQueue.erase(it); } else ++it; } } if(!fEnablePrivateSend && !fMasterNode) return; // catching hanging sessions if(!fMasterNode) { switch(nState) { case POOL_STATE_ERROR: LogPrint("privatesend", "CDarksendPool::CheckTimeout -- Pool error -- Running CheckPool\n"); CheckPool(); break; case POOL_STATE_SUCCESS: LogPrint("privatesend", "CDarksendPool::CheckTimeout -- Pool success -- Running CheckPool\n"); CheckPool(); break; default: break; } } int nLagTime = fMasterNode ? 0 : 10000; // if we're the client, give the server a few extra seconds before resetting. int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT; bool fTimeout = GetTimeMillis() - nTimeLastSuccessfulStep >= nTimeout*1000 + nLagTime; if(nState != POOL_STATE_IDLE && fTimeout) { LogPrint("privatesend", "CDarksendPool::CheckTimeout -- %s timed out (%ds) -- restting\n", (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); ChargeFees(); UnlockCoins(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = _("Session timed out."); } } /* Check to see if we're ready for submissions from clients After receiving multiple dsa messages, the queue will switch to "accepting entries" which is the active state right before merging the transaction */ void CDarksendPool::CheckForCompleteQueue() { if(!fEnablePrivateSend && !fMasterNode) return; if(nState == POOL_STATE_QUEUE && IsSessionReady()) { SetState(POOL_STATE_ACCEPTING_ENTRIES); CDarksendQueue dsq(nSessionDenom, activeMasternode.vin, GetTime(), true); LogPrint("privatesend", "CDarksendPool::CheckForCompleteQueue -- queue is ready, signing and relaying (%s)\n", dsq.ToString()); dsq.Sign(); dsq.Relay(); } } // Check to make sure a given input matches an input in the pool and its scriptSig is valid bool CDarksendPool::IsInputScriptSigValid(const CTxIn& txin) { CMutableTransaction txNew; txNew.vin.clear(); txNew.vout.clear(); int i = 0; int nTxInIndex = -1; CScript sigPubKey = CScript(); BOOST_FOREACH(CDarkSendEntry& entry, vecEntries) { BOOST_FOREACH(const CTxDSOut& txdsout, entry.vecTxDSOut) txNew.vout.push_back(txdsout); BOOST_FOREACH(const CTxDSIn& txdsin, entry.vecTxDSIn) { txNew.vin.push_back(txdsin); if(txdsin.prevout == txin.prevout) { nTxInIndex = i; sigPubKey = txdsin.prevPubKey; } i++; } } if(nTxInIndex >= 0) { //might have to do this one input at a time? txNew.vin[nTxInIndex].scriptSig = txin.scriptSig; LogPrint("privatesend", "CDarksendPool::IsInputScriptSigValid -- verifying scriptSig %s\n", ScriptToAsmStr(txin.scriptSig).substr(0,24)); if(!VerifyScript(txNew.vin[nTxInIndex].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, nTxInIndex))) { LogPrint("privatesend", "CDarksendPool::IsInputScriptSigValid -- VerifyScript() failed on input %d\n", nTxInIndex); return false; } } else { LogPrint("privatesend", "CDarksendPool::IsInputScriptSigValid -- Failed to find matching input in pool, %s\n", txin.ToString()); return false; } LogPrint("privatesend", "CDarksendPool::IsInputScriptSigValid -- Successfully validated input and scriptSig\n"); return true; } // check to make sure the collateral provided by the client is valid bool CDarksendPool::IsCollateralValid(const CTransaction& txCollateral) { if(txCollateral.vout.empty()) return false; if(txCollateral.nLockTime != 0) return false; CAmount nValueIn = 0; CAmount nValueOut = 0; bool fMissingTx = false; BOOST_FOREACH(const CTxOut txout, txCollateral.vout) { nValueOut += txout.nValue; if(!txout.scriptPubKey.IsNormalPaymentScript()) { LogPrintf ("CDarksendPool::IsCollateralValid -- Invalid Script, txCollateral=%s", txCollateral.ToString()); return false; } } BOOST_FOREACH(const CTxIn txin, txCollateral.vin) { CTransaction txPrev; uint256 hash; if(GetTransaction(txin.prevout.hash, txPrev, Params().GetConsensus(), hash, true)) { if(txPrev.vout.size() > txin.prevout.n) nValueIn += txPrev.vout[txin.prevout.n].nValue; } else { fMissingTx = true; } } if(fMissingTx) { LogPrint("privatesend", "CDarksendPool::IsCollateralValid -- Unknown inputs in collateral transaction, txCollateral=%s", txCollateral.ToString()); return false; } //collateral transactions are required to pay out PRIVATESEND_COLLATERAL as a fee to the miners if(nValueIn - nValueOut < PRIVATESEND_COLLATERAL) { LogPrint("privatesend", "CDarksendPool::IsCollateralValid -- did not include enough fees in transaction: fees: %d, txCollateral=%s", nValueOut - nValueIn, txCollateral.ToString()); return false; } LogPrint("privatesend", "CDarksendPool::IsCollateralValid -- %s", txCollateral.ToString()); { LOCK(cs_main); CValidationState validationState; if(!AcceptToMemoryPool(mempool, validationState, txCollateral, false, NULL, false, true, true)) { LogPrint("privatesend", "CDarksendPool::IsCollateralValid -- didn't pass AcceptToMemoryPool()\n"); return false; } } return true; } // // Add a clients transaction to the pool // bool CDarksendPool::AddEntry(const CDarkSendEntry& entryNew, PoolMessage& nMessageIDRet) { if(!fMasterNode) return false; BOOST_FOREACH(CTxIn txin, entryNew.vecTxDSIn) { if(txin.prevout.IsNull()) { LogPrint("privatesend", "CDarksendPool::AddEntry -- input not valid!\n"); nMessageIDRet = ERR_INVALID_INPUT; return false; } } if(!IsCollateralValid(entryNew.txCollateral)) { LogPrint("privatesend", "CDarksendPool::AddEntry -- collateral not valid!\n"); nMessageIDRet = ERR_INVALID_COLLATERAL; return false; } if(GetEntriesCount() >= GetMaxPoolTransactions()) { LogPrint("privatesend", "CDarksendPool::AddEntry -- entries is full!\n"); nMessageIDRet = ERR_ENTRIES_FULL; return false; } BOOST_FOREACH(CTxIn txin, entryNew.vecTxDSIn) { LogPrint("privatesend", "looking for txin -- %s\n", txin.ToString()); BOOST_FOREACH(const CDarkSendEntry& entry, vecEntries) { BOOST_FOREACH(const CTxDSIn& txdsin, entry.vecTxDSIn) { if(txdsin.prevout == txin.prevout) { LogPrint("privatesend", "CDarksendPool::AddEntry -- found in txin\n"); nMessageIDRet = ERR_ALREADY_HAVE; return false; } } } } vecEntries.push_back(entryNew); LogPrint("privatesend", "CDarksendPool::AddEntry -- adding entry\n"); nMessageIDRet = MSG_ENTRIES_ADDED; nTimeLastSuccessfulStep = GetTimeMillis(); return true; } bool CDarksendPool::AddScriptSig(const CTxIn& txinNew) { LogPrint("privatesend", "CDarksendPool::AddScriptSig -- scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); BOOST_FOREACH(const CDarkSendEntry& entry, vecEntries) { BOOST_FOREACH(const CTxDSIn& txdsin, entry.vecTxDSIn) { if(txdsin.scriptSig == txinNew.scriptSig) { LogPrint("privatesend", "CDarksendPool::AddScriptSig -- already exists\n"); return false; } } } if(!IsInputScriptSigValid(txinNew)) { LogPrint("privatesend", "CDarksendPool::AddScriptSig -- Invalid scriptSig\n"); return false; } LogPrint("privatesend", "CDarksendPool::AddScriptSig -- scriptSig=%s new\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); BOOST_FOREACH(CTxIn& txin, finalMutableTransaction.vin) { if(txinNew.prevout == txin.prevout && txin.nSequence == txinNew.nSequence) { txin.scriptSig = txinNew.scriptSig; txin.prevPubKey = txinNew.prevPubKey; LogPrint("privatesend", "CDarksendPool::AddScriptSig -- adding to finalMutableTransaction, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); } } for(int i = 0; i < GetEntriesCount(); i++) { if(vecEntries[i].AddScriptSig(txinNew)) { LogPrint("privatesend", "CDarksendPool::AddScriptSig -- adding to entries, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); return true; } } LogPrintf("CDarksendPool::AddScriptSig -- Couldn't set sig!\n" ); return false; } // Check to make sure everything is signed bool CDarksendPool::IsSignaturesComplete() { BOOST_FOREACH(const CDarkSendEntry& entry, vecEntries) BOOST_FOREACH(const CTxDSIn& txdsin, entry.vecTxDSIn) if(!txdsin.fHasSig) return false; return true; } // // Execute a mixing denomination via a Masternode. // This is only ran from clients // bool CDarksendPool::SendDenominate(const std::vector<CTxIn>& vecTxIn, const std::vector<CTxOut>& vecTxOut) { if(fMasterNode) { LogPrintf("CDarksendPool::SendDenominate -- PrivateSend from a Masternode is not supported currently.\n"); return false; } if(txMyCollateral == CMutableTransaction()) { LogPrintf("CDarksendPool:SendDenominate -- PrivateSend collateral not set\n"); return false; } // lock the funds we're going to use BOOST_FOREACH(CTxIn txin, txMyCollateral.vin) vecOutPointLocked.push_back(txin.prevout); BOOST_FOREACH(CTxIn txin, vecTxIn) vecOutPointLocked.push_back(txin.prevout); // we should already be connected to a Masternode if(!nSessionID) { LogPrintf("CDarksendPool::SendDenominate -- No Masternode has been selected yet.\n"); UnlockCoins(); SetNull(); return false; } if(!CheckDiskSpace()) { UnlockCoins(); SetNull(); fEnablePrivateSend = false; LogPrintf("CDarksendPool::SendDenominate -- Not enough disk space, disabling PrivateSend.\n"); return false; } SetState(POOL_STATE_ACCEPTING_ENTRIES); strLastMessage = ""; LogPrintf("CDarksendPool::SendDenominate -- Added transaction to pool.\n"); //check it against the memory pool to make sure it's valid { CValidationState validationState; CMutableTransaction tx; BOOST_FOREACH(const CTxIn& txin, vecTxIn) { LogPrint("privatesend", "CDarksendPool::SendDenominate -- txin=%s\n", txin.ToString()); tx.vin.push_back(txin); } BOOST_FOREACH(const CTxOut& txout, vecTxOut) { LogPrint("privatesend", "CDarksendPool::SendDenominate -- txout=%s\n", txout.ToString()); tx.vout.push_back(txout); } LogPrintf("CDarksendPool::SendDenominate -- Submitting partial tx %s", tx.ToString()); mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), 1000, 0.1*COIN); TRY_LOCK(cs_main, lockMain); if(!lockMain || !AcceptToMemoryPool(mempool, validationState, CTransaction(tx), false, NULL, false, true, true)) { LogPrintf("CDarksendPool::SendDenominate -- AcceptToMemoryPool() failed! tx=%s", tx.ToString()); UnlockCoins(); SetNull(); return false; } } // store our entry for later use CDarkSendEntry entry(vecTxIn, vecTxOut, txMyCollateral); vecEntries.push_back(entry); RelayIn(entry); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } // Incoming message from Masternode updating the progress of mixing bool CDarksendPool::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew) { if(fMasterNode) return false; // do not update state when mixing client state is one of these if(nState == POOL_STATE_IDLE || nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) return false; strAutoDenomResult = _("Masternode:") + " " + GetMessageByID(nMessageID); // if rejected at any state if(nStatusUpdate == STATUS_REJECTED) { LogPrintf("CDarksendPool::CheckPoolStateUpdate -- entry is rejected by Masternode\n"); UnlockCoins(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = GetMessageByID(nMessageID); return true; } if(nStatusUpdate == STATUS_ACCEPTED && nState == nStateNew) { if(nStateNew == POOL_STATE_QUEUE && nSessionID == 0 && nSessionIDNew != 0) { // new session id should be set only in POOL_STATE_QUEUE state nSessionID = nSessionIDNew; nTimeLastSuccessfulStep = GetTimeMillis(); LogPrintf("CDarksendPool::CheckPoolStateUpdate -- set nSessionID to %d\n", nSessionID); return true; } else if(nStateNew == POOL_STATE_ACCEPTING_ENTRIES && nEntriesCount != nEntriesCountNew) { nEntriesCount = nEntriesCountNew; nTimeLastSuccessfulStep = GetTimeMillis(); fLastEntryAccepted = true; LogPrintf("CDarksendPool::CheckPoolStateUpdate -- new entry accepted!\n"); return true; } } // only situations above are allowed, fail in any other case return false; } // // After we receive the finalized transaction from the Masternode, we must // check it to make sure it's what we want, then sign it if we agree. // If we refuse to sign, it's possible we'll be charged collateral // bool CDarksendPool::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode) { if(fMasterNode || pnode == NULL) return false; finalMutableTransaction = finalTransactionNew; LogPrintf("CDarksendPool::SignFinalTransaction -- finalMutableTransaction=%s", finalMutableTransaction.ToString()); std::vector<CTxIn> sigs; //make sure my inputs/outputs are present, otherwise refuse to sign BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) { BOOST_FOREACH(const CTxDSIn txdsin, entry.vecTxDSIn) { /* Sign my transaction and all outputs */ int nMyInputIndex = -1; CScript prevPubKey = CScript(); CTxIn txin = CTxIn(); for(unsigned int i = 0; i < finalMutableTransaction.vin.size(); i++) { if(finalMutableTransaction.vin[i] == txdsin) { nMyInputIndex = i; prevPubKey = txdsin.prevPubKey; txin = txdsin; } } if(nMyInputIndex >= 0) { //might have to do this one input at a time? int nFoundOutputsCount = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for(unsigned int i = 0; i < finalMutableTransaction.vout.size(); i++) { BOOST_FOREACH(const CTxOut& txout, entry.vecTxDSOut) { if(finalMutableTransaction.vout[i] == txout) { nFoundOutputsCount++; nValue1 += finalMutableTransaction.vout[i].nValue; } } } BOOST_FOREACH(const CTxOut txout, entry.vecTxDSOut) nValue2 += txout.nValue; int nTargetOuputsCount = entry.vecTxDSOut.size(); if(nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CDarksendPool::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d\n", nFoundOutputsCount, nTargetOuputsCount); UnlockCoins(); SetNull(); return false; } const CKeyStore& keystore = *pwalletMain; LogPrint("privatesend", "CDarksendPool::SignFinalTransaction -- Signing my input %i\n", nMyInputIndex); if(!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig LogPrint("privatesend", "CDarksendPool::SignFinalTransaction -- Unable to sign my own transaction!\n"); // not sure what to do here, it will timeout...? } sigs.push_back(finalMutableTransaction.vin[nMyInputIndex]); LogPrint("privatesend", "CDarksendPool::SignFinalTransaction -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s\n", nMyInputIndex, (int)sigs.size(), ScriptToAsmStr(finalMutableTransaction.vin[nMyInputIndex].scriptSig)); } } } if(sigs.empty()) { LogPrintf("CDarksendPool::SignFinalTransaction -- can't sign anything!\n"); UnlockCoins(); SetNull(); return false; } // push all of our signatures to the Masternode LogPrintf("CDarksendPool::SignFinalTransaction -- pushing sigs to the masternode, finalMutableTransaction=%s", finalMutableTransaction.ToString()); pnode->PushMessage(NetMsgType::DSSIGNFINALTX, sigs); SetState(POOL_STATE_SIGNING); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } void CDarksendPool::NewBlock() { static int64_t nTimeNewBlockReceived = 0; //we we're processing lots of blocks, we'll just leave if(GetTime() - nTimeNewBlockReceived < 10) return; nTimeNewBlockReceived = GetTime(); LogPrint("privatesend", "CDarksendPool::NewBlock\n"); CheckTimeout(); } // mixing transaction was completed (failed or successful) void CDarksendPool::CompletedTransaction(PoolMessage nMessageID) { if(fMasterNode) return; if(nMessageID == MSG_SUCCESS) { LogPrintf("CompletedTransaction -- success\n"); nCachedLastSuccessBlock = pCurrentBlockIndex->nHeight; } else { LogPrintf("CompletedTransaction -- error\n"); } UnlockCoins(); SetNull(); strLastMessage = GetMessageByID(nMessageID); } // // Passively run mixing in the background to anonymize funds based on the given configuration. // bool CDarksendPool::DoAutomaticDenominating(bool fDryRun) { if(!fEnablePrivateSend || fMasterNode || !pCurrentBlockIndex) return false; if(!pwalletMain || pwalletMain->IsLocked(true)) return false; if(nState != POOL_STATE_IDLE) return false; if(!masternodeSync.IsMasternodeListSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } switch(nWalletBackups) { case 0: LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- Automatic backups disabled, no mixing available.\n"); strAutoDenomResult = _("Automatic backups disabled") + ", " + _("no mixing available."); fEnablePrivateSend = false; // stop mixing pwalletMain->nKeysLeftSinceAutoBackup = 0; // no backup, no "keys since last backup" return false; case -1: // Automatic backup failed, nothing else we can do until user fixes the issue manually. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- ERROR! Failed to create automatic backup.\n"); strAutoDenomResult = _("ERROR! Failed to create automatic backup") + ", " + _("see debug.log for details."); return false; case -2: // We were able to create automatic backup but keypool was not replenished because wallet is locked. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- WARNING! Failed to create replenish keypool, please unlock your wallet to do so.\n"); strAutoDenomResult = _("WARNING! Failed to replenish keypool, please unlock your wallet to do so.") + ", " + _("see debug.log for details."); return false; } if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) { // We should never get here via mixing itself but probably smth else is still actively using keypool LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- Very low number of keys left: %d, no mixing available.\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + ", " + _("no mixing available."), pwalletMain->nKeysLeftSinceAutoBackup); // It's getting really dangerous, stop mixing fEnablePrivateSend = false; return false; } else if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) { // Low number of keys left but it's still more or less safe to continue LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- Very low number of keys left: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), pwalletMain->nKeysLeftSinceAutoBackup); if(fCreateAutoBackups) { LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- Trying to create new backup.\n"); std::string warningString; std::string errorString; if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { if(!warningString.empty()) { // There were some issues saving backup but yet more or less safe to continue LogPrintf("CDarksendPool::DoAutomaticDenominating -- WARNING! Something went wrong on automatic backup: %s\n", warningString); } if(!errorString.empty()) { // Things are really broken LogPrintf("CDarksendPool::DoAutomaticDenominating -- ERROR! Failed to create automatic backup: %s\n", errorString); strAutoDenomResult = strprintf(_("ERROR! Failed to create automatic backup") + ": %s", errorString); return false; } } } else { // Wait for someone else (e.g. GUI action) to create automatic backup for us return false; } } LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- Keys left since latest backup: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); if(GetEntriesCount() > 0) { strAutoDenomResult = _("Mixing in progress..."); return false; } TRY_LOCK(cs_darksend, lockDS); if(!lockDS) { strAutoDenomResult = _("Lock is already in place."); return false; } if(!fDryRun && pwalletMain->IsLocked(true)) { strAutoDenomResult = _("Wallet is locked."); return false; } if(!fPrivateSendMultiSession && pCurrentBlockIndex->nHeight - nCachedLastSuccessBlock < nMinBlockSpacing) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Last successful PrivateSend action was too recent\n"); strAutoDenomResult = _("Last successful PrivateSend action was too recent."); return false; } if(mnodeman.size() == 0) { LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- No Masternodes detected\n"); strAutoDenomResult = _("No Masternodes detected."); return false; } CAmount nValueMin = vecPrivateSendDenominations.back(); // if there are no confirmed DS collateral inputs yet if(!pwalletMain->HasCollateralInputs()) { // should have some additional amount for them nValueMin += PRIVATESEND_COLLATERAL*4; } // including denoms but applying some restrictions CAmount nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin); // anonymizable balance is way too small if(nBalanceNeedsAnonymized < nValueMin) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Not enough funds to anonymize\n"); strAutoDenomResult = _("Not enough funds to anonymize."); return false; } // excluding denoms CAmount nBalanceAnonimizableNonDenom = pwalletMain->GetAnonymizableBalance(true); // denoms CAmount nBalanceDenominatedConf = pwalletMain->GetDenominatedBalance(); CAmount nBalanceDenominatedUnconf = pwalletMain->GetDenominatedBalance(true); CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf; LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- nValueMin: %f, nBalanceNeedsAnonymized: %f, nBalanceAnonimizableNonDenom: %f, nBalanceDenominatedConf: %f, nBalanceDenominatedUnconf: %f, nBalanceDenominated: %f\n", (float)nValueMin/COIN, (float)nBalanceNeedsAnonymized/COIN, (float)nBalanceAnonimizableNonDenom/COIN, (float)nBalanceDenominatedConf/COIN, (float)nBalanceDenominatedUnconf/COIN, (float)nBalanceDenominated/COIN); if(fDryRun) return true; // Check if we have should create more denominated inputs i.e. // there are funds to denominate and denominated balance does not exceed // max amount to mix yet. if(nBalanceAnonimizableNonDenom >= nValueMin + PRIVATESEND_COLLATERAL && nBalanceDenominated < nPrivateSendAmount*COIN) return CreateDenominated(); //check if we have the collateral sized inputs if(!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(); if(nSessionID) { strAutoDenomResult = _("Mixing in progress..."); return false; } // Initial phase, find a Masternode // Clean if there is anything left from previous session UnlockCoins(); SetNull(); // should be no unconfirmed denoms in non-multi-session mode if(!fPrivateSendMultiSession && nBalanceDenominatedUnconf > 0) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); return false; } //check our collateral and create new if needed std::string strReason; if(txMyCollateral == CMutableTransaction()) { if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- create collateral error:%s\n", strReason); return false; } } else { if(!IsCollateralValid(txMyCollateral)) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- invalid collateral, recreating...\n"); if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- create collateral error: %s\n", strReason); return false; } } } int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); // If we've used 90% of the Masternode list then drop the oldest first ~30% int nThreshold_high = nMnCountEnabled * 0.9; int nThreshold_low = nThreshold_high * 0.7; LogPrint("privatesend", "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); if((int)vecMasternodesUsed.size() > nThreshold_high) { vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low); LogPrint("privatesend", " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); } bool fUseQueue = GetRandInt(100) > 33; // don't use the queues all of the time for mixing unless we are a liquidity provider if(nLiquidityProvider || fUseQueue) { // Look through the queues and see if anything matches BOOST_FOREACH(CDarksendQueue& dsq, vecDarksendQueue) { // only try each queue once if(dsq.fTried) continue; dsq.fTried = true; if(dsq.IsExpired()) continue; CMasternode* pmn = mnodeman.Find(dsq.vin); if(pmn == NULL) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- dsq masternode is not in masternode list, masternode=%s\n", dsq.vin.prevout.ToStringShort()); continue; } if(pmn->nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue; std::vector<int> vecBits; if(!GetDenominationsBits(dsq.nDenom, vecBits)) { // incompatible denom continue; } // mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage // in order for dsq to get into vecDarksendQueue, so we should be safe to mix already, // no need for additional verification here LogPrint("privatesend", "CDarksendPool::DoAutomaticDenominating -- found valid queue: %s\n", dsq.ToString()); CAmount nValueInTmp = 0; std::vector<CTxIn> vecTxInTmp; std::vector<COutput> vCoinsTmp; // Try to match their denominations if possible, select at least 1 denominations if(!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, vecPrivateSendDenominations[vecBits.front()], nBalanceNeedsAnonymized, vecTxInTmp, vCoinsTmp, nValueInTmp, 0, nPrivateSendRounds)) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Couldn't match denominations %d %d (%s)\n", vecBits.front(), dsq.nDenom, GetDenominationsToString(dsq.nDenom)); continue; } vecMasternodesUsed.push_back(dsq.vin); CNode* pnodeFound = NULL; { LOCK(cs_vNodes); pnodeFound = FindNode(pmn->addr); if(pnodeFound) { if(pnodeFound->fDisconnect) { continue; } else { pnodeFound->AddRef(); } } } LogPrintf("CDarksendPool::DoAutomaticDenominating -- attempt to connect to masternode from queue, addr=%s\n", pmn->addr.ToString()); // connect to Masternode and submit the queue request CNode* pnode = (pnodeFound && pnodeFound->fMasternode) ? pnodeFound : ConnectNode((CAddress)pmn->addr, NULL, true); if(pnode) { pSubmittedToMasternode = pmn; nSessionDenom = dsq.nDenom; pnode->PushMessage(NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CDarksendPool::DoAutomaticDenominating -- connected (from queue), sending DSACCEPT: nSessionDenom: %d (%s), addr=%s\n", nSessionDenom, GetDenominationsToString(nSessionDenom), pnode->addr.ToString()); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); if(pnodeFound) { pnodeFound->Release(); } return true; } else { LogPrintf("CDarksendPool::DoAutomaticDenominating -- can't connect, addr=%s\n", pmn->addr.ToString()); strAutoDenomResult = _("Error connecting to Masternode."); continue; } } } // do not initiate queue if we are a liquidity provider to avoid useless inter-mixing if(nLiquidityProvider) return false; int nTries = 0; // ** find the coins we'll use std::vector<CTxIn> vecTxIn; CAmount nValueInTmp = 0; if(!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, nPrivateSendRounds)) { // this should never happen LogPrintf("CDarksendPool::DoAutomaticDenominating -- Can't mix: no compatible inputs found!\n"); strAutoDenomResult = _("Can't mix: no compatible inputs found!"); return false; } // otherwise, try one randomly while(nTries < 10) { CMasternode* pmn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, MIN_PRIVATESEND_PEER_PROTO_VERSION); if(pmn == NULL) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; } vecMasternodesUsed.push_back(pmn->vin); if(pmn->nLastDsq != 0 && pmn->nLastDsq + nMnCountEnabled/5 > mnodeman.nDsqCount) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- Too early to mix on this masternode!" " masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n", pmn->vin.prevout.ToStringShort(), pmn->addr.ToString(), pmn->nLastDsq, nMnCountEnabled/5, mnodeman.nDsqCount); nTries++; continue; } CNode* pnodeFound = NULL; { LOCK(cs_vNodes); pnodeFound = FindNode(pmn->addr); if(pnodeFound) { if(pnodeFound->fDisconnect) { nTries++; continue; } else { pnodeFound->AddRef(); } } } LogPrintf("CDarksendPool::DoAutomaticDenominating -- attempt %d connection to Masternode %s\n", nTries, pmn->addr.ToString()); CNode* pnode = (pnodeFound && pnodeFound->fMasternode) ? pnodeFound : ConnectNode((CAddress)pmn->addr, NULL, true); if(pnode) { LogPrintf("CDarksendPool::DoAutomaticDenominating -- connected, addr=%s\n", pmn->addr.ToString()); pSubmittedToMasternode = pmn; std::vector<CAmount> vecAmounts; pwalletMain->ConvertList(vecTxIn, vecAmounts); // try to get a single random denom out of vecAmounts while(nSessionDenom == 0) { nSessionDenom = GetDenominationsByAmounts(vecAmounts); } pnode->PushMessage(NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CDarksendPool::DoAutomaticDenominating -- connected, sending DSACCEPT, nSessionDenom: %d (%s)\n", nSessionDenom, GetDenominationsToString(nSessionDenom)); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); if(pnodeFound) { pnodeFound->Release(); } return true; } else { LogPrintf("CDarksendPool::DoAutomaticDenominating -- can't connect, addr=%s\n", pmn->addr.ToString()); nTries++; continue; } } strAutoDenomResult = _("No compatible Masternode found."); return false; } bool CDarksendPool::SubmitDenominate() { std::string strError; std::vector<CTxIn> vecTxInRet; std::vector<CTxOut> vecTxOutRet; // Submit transaction to the pool if we get here // Try to use only inputs with the same number of rounds starting from lowest number of rounds possible for(int i = 0; i < nPrivateSendRounds; i++) { if(PrepareDenominate(i, i+1, strError, vecTxInRet, vecTxOutRet)) { LogPrintf("CDarksendPool::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success\n", i); return SendDenominate(vecTxInRet, vecTxOutRet); } LogPrintf("CDarksendPool::SubmitDenominate -- Running PrivateSend denominate for %d rounds, error: %s\n", i, strError); } // We failed? That's strange but let's just make final attempt and try to mix everything if(PrepareDenominate(0, nPrivateSendRounds, strError, vecTxInRet, vecTxOutRet)) { LogPrintf("CDarksendPool::SubmitDenominate -- Running PrivateSend denominate for all rounds, success\n"); return SendDenominate(vecTxInRet, vecTxOutRet); } // Should never actually get here but just in case LogPrintf("CDarksendPool::SubmitDenominate -- Running PrivateSend denominate for all rounds, error: %s\n", strError); strAutoDenomResult = strError; return false; } bool CDarksendPool::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxIn>& vecTxInRet, std::vector<CTxOut>& vecTxOutRet) { if (pwalletMain->IsLocked(true)) { strErrorRet = "Wallet locked, unable to create transaction!"; return false; } if (GetEntriesCount() > 0) { strErrorRet = "Already have pending entries in the PrivateSend pool"; return false; } // make sure returning vectors are empty before filling them up vecTxInRet.clear(); vecTxOutRet.clear(); // ** find the coins we'll use std::vector<CTxIn> vecTxIn; std::vector<COutput> vCoins; CAmount nValueIn = 0; CReserveKey reservekey(pwalletMain); /* Select the coins we'll use if nMinRounds >= 0 it means only denominated inputs are going in and coming out */ std::vector<int> vecBits; if (!GetDenominationsBits(nSessionDenom, vecBits)) { strErrorRet = "Incorrect session denom"; return false; } bool fSelected = pwalletMain->SelectCoinsByDenominations(nSessionDenom, vecPrivateSendDenominations[vecBits.front()], PRIVATESEND_POOL_MAX, vecTxIn, vCoins, nValueIn, nMinRounds, nMaxRounds); if (nMinRounds >= 0 && !fSelected) { strErrorRet = "Can't select current denominated inputs"; return false; } LogPrintf("CDarksendPool::PrepareDenominate -- max value: %f\n", (double)nValueIn/COIN); { LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxIn) { pwalletMain->LockCoin(txin.prevout); } } CAmount nValueLeft = nValueIn; // Try to add every needed denomination, repeat up to 5-9 times. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { BOOST_FOREACH(int nBit, vecBits) { CAmount nValueDenom = vecPrivateSendDenominations[nBit]; if (nValueLeft - nValueDenom < 0) continue; // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vecTxIn.begin(); std::vector<COutput>::iterator it2 = vCoins.begin(); while (it2 != vCoins.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == nValueDenom) { // add new input in resulting vector vecTxInRet.push_back(*it); // remove corresponting items from initial vectors vecTxIn.erase(it); vCoins.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut txout(nValueDenom, scriptChange); vecTxOutRet.push_back(txout); // subtract denomination amount nValueLeft -= nValueDenom; // step is complete break; } ++it; ++it2; } } if(nValueLeft == 0) break; nStep++; } { // unlock unused coins LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxIn) { pwalletMain->UnlockCoin(txin.prevout); } } if (GetDenominations(vecTxOutRet) != nSessionDenom) { // unlock used coins on failure LOCK(pwalletMain->cs_wallet); BOOST_FOREACH(CTxIn txin, vecTxInRet) { pwalletMain->UnlockCoin(txin.prevout); } strErrorRet = "Can't make current denominated outputs"; return false; } // We also do not care about full amount as long as we have right denominations return true; } // Create collaterals by looping through inputs grouped by addresses bool CDarksendPool::MakeCollateralAmounts() { std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false)) { LogPrint("privatesend", "CDarksendPool::MakeCollateralAmounts -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!MakeCollateralAmounts(item)) continue; return true; } LogPrintf("CDarksendPool::MakeCollateralAmounts -- failed!\n"); return false; } // Split up large inputs or create fee sized inputs bool CDarksendPool::MakeCollateralAmounts(const CompactTallyItem& tallyItem) { CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; std::vector<CRecipient> vecSend; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); vecSend.push_back((CRecipient){scriptCollateral, PRIVATESEND_COLLATERAL*4, false}); // try to use non-denominated and not mn-like funds first, select them explicitly CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.address.Get(); BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED_NOT1000IFMN); if(!fSuccess) { // if we failed (most likeky not enough funds), try to use all coins instead - // MN-like funds should not be touched in any case and we can't mix denominated without collaterals anyway LogPrintf("CDarksendPool::MakeCollateralAmounts -- ONLY_NONDENOMINATED_NOT1000IFMN Error: %s\n", strFail); CCoinControl *coinControlNull = NULL; fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, coinControlNull, true, ONLY_NOT1000IFMN); if(!fSuccess) { LogPrintf("CDarksendPool::MakeCollateralAmounts -- ONLY_NOT1000IFMN Error: %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; } } reservekeyCollateral.KeepKey(); LogPrintf("CDarksendPool::MakeCollateralAmounts -- txid=%s\n", wtx.GetHash().GetHex()); // use the same nCachedLastSuccessBlock as for DS mixinx to prevent race if(!pwalletMain->CommitTransaction(wtx, reservekeyChange)) { LogPrintf("CDarksendPool::MakeCollateralAmounts -- CommitTransaction failed!\n"); return false; } nCachedLastSuccessBlock = pCurrentBlockIndex->nHeight; return true; } // Create denominations by looping through inputs grouped by addresses bool CDarksendPool::CreateDenominated() { std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally)) { LogPrint("privatesend", "CDarksendPool::CreateDenominated -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } bool fCreateMixingCollaterals = !pwalletMain->HasCollateralInputs(); BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!CreateDenominated(item, fCreateMixingCollaterals)) continue; return true; } LogPrintf("CDarksendPool::CreateDenominated -- failed!\n"); return false; } // Create denominations bool CDarksendPool::CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals) { std::vector<CRecipient> vecSend; CAmount nValueLeft = tallyItem.nAmount; nValueLeft -= PRIVATESEND_COLLATERAL; // leave some room for fees LogPrintf("CreateDenominated0 nValueLeft: %f\n", (float)nValueLeft/COIN); // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); // ****** Add collateral outputs ************ / if(fCreateMixingCollaterals) { vecSend.push_back((CRecipient){scriptCollateral, PRIVATESEND_COLLATERAL*4, false}); nValueLeft -= PRIVATESEND_COLLATERAL*4; } // ****** Add denoms ************ / // make our denom addresses CReserveKey reservekeyDenom(pwalletMain); // try few times - skipping smallest denoms first if there are too much already, if failed - use them int nOutputsTotal = 0; bool fSkip = true; do { BOOST_REVERSE_FOREACH(CAmount nDenomValue, vecPrivateSendDenominations) { if(fSkip) { // Note: denoms are skipped if there are already DENOMS_COUNT_MAX of them // and there are still larger denoms which can be used for mixing // check skipped denoms if(IsDenomSkipped(nDenomValue)) continue; // find new denoms to skip if any (ignore the largest one) if(nDenomValue != vecPrivateSendDenominations[0] && pwalletMain->CountInputsWithAmount(nDenomValue) > DENOMS_COUNT_MAX) { strAutoDenomResult = strprintf(_("Too many %f denominations, removing."), (float)nDenomValue/COIN); LogPrintf("CDarksendPool::CreateDenominated -- %s\n", strAutoDenomResult); vecDenominationsSkipped.push_back(nDenomValue); continue; } } int nOutputs = 0; // add each output up to 10 times until it can't be added again while(nValueLeft - nDenomValue >= 0 && nOutputs <= 10) { CScript scriptDenom; CPubKey vchPubKey; //use a unique change address assert(reservekeyDenom.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptDenom = GetScriptForDestination(vchPubKey.GetID()); // TODO: do not keep reservekeyDenom here reservekeyDenom.KeepKey(); vecSend.push_back((CRecipient){ scriptDenom, nDenomValue, false }); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= nDenomValue; LogPrintf("CreateDenominated1: nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f\n", nOutputsTotal, nOutputs, (float)nValueLeft/COIN); } nOutputsTotal += nOutputs; if(nValueLeft == 0) break; } LogPrintf("CreateDenominated2: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if there were no outputs added, start over without skipping fSkip = !fSkip; } while (nOutputsTotal == 0 && !fSkip); LogPrintf("CreateDenominated3: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if we have anything left over, it will be automatically send back as change - there is no need to send it manually CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.address.Get(); BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; // make our change address CReserveKey reservekeyChange(pwalletMain); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED_NOT1000IFMN); if(!fSuccess) { LogPrintf("CDarksendPool::CreateDenominated -- Error: %s\n", strFail); // TODO: return reservekeyDenom here reservekeyCollateral.ReturnKey(); return false; } // TODO: keep reservekeyDenom here reservekeyCollateral.KeepKey(); if(!pwalletMain->CommitTransaction(wtx, reservekeyChange)) { LogPrintf("CDarksendPool::CreateDenominated -- CommitTransaction failed!\n"); return false; } // use the same nCachedLastSuccessBlock as for DS mixing to prevent race nCachedLastSuccessBlock = pCurrentBlockIndex->nHeight; LogPrintf("CDarksendPool::CreateDenominated -- txid=%s\n", wtx.GetHash().GetHex()); return true; } bool CDarksendPool::IsOutputsCompatibleWithSessionDenom(const std::vector<CTxDSOut>& vecTxDSOut) { if(GetDenominations(vecTxDSOut) == 0) return false; BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) { LogPrintf("CDarksendPool::IsOutputsCompatibleWithSessionDenom -- vecTxDSOut denom %d, entry.vecTxDSOut denom %d\n", GetDenominations(vecTxDSOut), GetDenominations(entry.vecTxDSOut)); if(GetDenominations(vecTxDSOut) != GetDenominations(entry.vecTxDSOut)) return false; } return true; } bool CDarksendPool::IsAcceptableDenomAndCollateral(int nDenom, CTransaction txCollateral, PoolMessage& nMessageIDRet) { if(!fMasterNode) return false; // is denom even smth legit? std::vector<int> vecBits; if(!GetDenominationsBits(nDenom, vecBits)) { LogPrint("privatesend", "CDarksendPool::IsAcceptableDenomAndCollateral -- denom not valid!\n"); nMessageIDRet = ERR_DENOM; return false; } // check collateral if(!fUnitTest && !IsCollateralValid(txCollateral)) { LogPrint("privatesend", "CDarksendPool::IsAcceptableDenomAndCollateral -- collateral not valid!\n"); nMessageIDRet = ERR_INVALID_COLLATERAL; return false; } return true; } bool CDarksendPool::CreateNewSession(int nDenom, CTransaction txCollateral, PoolMessage& nMessageIDRet) { if(!fMasterNode || nSessionID != 0) return false; // new session can only be started in idle mode if(nState != POOL_STATE_IDLE) { nMessageIDRet = ERR_MODE; LogPrintf("CDarksendPool::CreateNewSession -- incompatible mode: nState=%d\n", nState); return false; } if(!IsAcceptableDenomAndCollateral(nDenom, txCollateral, nMessageIDRet)) { return false; } // start new session nMessageIDRet = MSG_NOERR; nSessionID = GetRandInt(999999)+1; nSessionDenom = nDenom; SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); if(!fUnitTest) { //broadcast that I'm accepting entries, only if it's the first entry through CDarksendQueue dsq(nDenom, activeMasternode.vin, GetTime(), false); LogPrint("privatesend", "CDarksendPool::CreateNewSession -- signing and relaying new queue: %s\n", dsq.ToString()); dsq.Sign(); dsq.Relay(); vecDarksendQueue.push_back(dsq); } vecSessionCollaterals.push_back(txCollateral); LogPrintf("CDarksendPool::CreateNewSession -- new session created, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d\n", nSessionID, nSessionDenom, GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); return true; } bool CDarksendPool::AddUserToExistingSession(int nDenom, CTransaction txCollateral, PoolMessage& nMessageIDRet) { if(!fMasterNode || nSessionID == 0 || IsSessionReady()) return false; if(!IsAcceptableDenomAndCollateral(nDenom, txCollateral, nMessageIDRet)) { return false; } // we only add new users to an existing session when we are in queue mode if(nState != POOL_STATE_QUEUE) { nMessageIDRet = ERR_MODE; LogPrintf("CDarksendPool::AddUserToExistingSession -- incompatible mode: nState=%d\n", nState); return false; } if(nDenom != nSessionDenom) { LogPrintf("CDarksendPool::AddUserToExistingSession -- incompatible denom %d (%s) != nSessionDenom %d (%s)\n", nDenom, GetDenominationsToString(nDenom), nSessionDenom, GetDenominationsToString(nSessionDenom)); nMessageIDRet = ERR_DENOM; return false; } // count new user as accepted to an existing session nMessageIDRet = MSG_NOERR; nTimeLastSuccessfulStep = GetTimeMillis(); vecSessionCollaterals.push_back(txCollateral); LogPrintf("CDarksendPool::AddUserToExistingSession -- new user accepted, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d\n", nSessionID, nSessionDenom, GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); return true; } /* Create a nice string to show the denominations Function returns as follows (for 4 denominations): ( bit on if present ) bit 0 - 100 bit 1 - 10 bit 2 - 1 bit 3 - .1 bit 4 and so on - out-of-bounds none of above - non-denom */ std::string CDarksendPool::GetDenominationsToString(int nDenom) { std::string strDenom = ""; int nMaxDenoms = vecPrivateSendDenominations.size(); if(nDenom >= (1 << nMaxDenoms)) { return "out-of-bounds"; } for (int i = 0; i < nMaxDenoms; ++i) { if(nDenom & (1 << i)) { strDenom += (strDenom.empty() ? "" : "+") + FormatMoney(vecPrivateSendDenominations[i]); } } if(strDenom.empty()) { return "non-denom"; } return strDenom; } int CDarksendPool::GetDenominations(const std::vector<CTxDSOut>& vecTxDSOut) { std::vector<CTxOut> vecTxOut; BOOST_FOREACH(CTxDSOut out, vecTxDSOut) vecTxOut.push_back(out); return GetDenominations(vecTxOut); } /* Return a bitshifted integer representing the denominations in this list Function returns as follows (for 4 denominations): ( bit on if present ) 100 - bit 0 10 - bit 1 1 - bit 2 .1 - bit 3 non-denom - 0, all bits off */ int CDarksendPool::GetDenominations(const std::vector<CTxOut>& vecTxOut, bool fSingleRandomDenom) { std::vector<std::pair<CAmount, int> > vecDenomUsed; // make a list of denominations, with zero uses BOOST_FOREACH(CAmount nDenomValue, vecPrivateSendDenominations) vecDenomUsed.push_back(std::make_pair(nDenomValue, 0)); // look for denominations and update uses to 1 BOOST_FOREACH(CTxOut txout, vecTxOut) { bool found = false; BOOST_FOREACH (PAIRTYPE(CAmount, int)& s, vecDenomUsed) { if(txout.nValue == s.first) { s.second = 1; found = true; } } if(!found) return 0; } int nDenom = 0; int c = 0; // if the denomination is used, shift the bit on BOOST_FOREACH (PAIRTYPE(CAmount, int)& s, vecDenomUsed) { int bit = (fSingleRandomDenom ? GetRandInt(2) : 1) & s.second; nDenom |= bit << c++; if(fSingleRandomDenom && bit) break; // use just one random denomination } return nDenom; } bool CDarksendPool::GetDenominationsBits(int nDenom, std::vector<int> &vecBitsRet) { // ( bit on if present, 4 denominations example ) // bit 0 - 100AIRIN+1 // bit 1 - 10AIRIN+1 // bit 2 - 1AIRIN+1 // bit 3 - .1AIRIN+1 int nMaxDenoms = vecPrivateSendDenominations.size(); if(nDenom >= (1 << nMaxDenoms)) return false; vecBitsRet.clear(); for (int i = 0; i < nMaxDenoms; ++i) { if(nDenom & (1 << i)) { vecBitsRet.push_back(i); } } return !vecBitsRet.empty(); } int CDarksendPool::GetDenominationsByAmounts(const std::vector<CAmount>& vecAmount) { CScript scriptTmp = CScript(); std::vector<CTxOut> vecTxOut; BOOST_REVERSE_FOREACH(CAmount nAmount, vecAmount) { CTxOut txout(nAmount, scriptTmp); vecTxOut.push_back(txout); } return GetDenominations(vecTxOut, true); } std::string CDarksendPool::GetMessageByID(PoolMessage nMessageID) { switch (nMessageID) { case ERR_ALREADY_HAVE: return _("Already have that input."); case ERR_DENOM: return _("No matching denominations found for mixing."); case ERR_ENTRIES_FULL: return _("Entries are full."); case ERR_EXISTING_TX: return _("Not compatible with existing transactions."); case ERR_FEES: return _("Transaction fees are too high."); case ERR_INVALID_COLLATERAL: return _("Collateral not valid."); case ERR_INVALID_INPUT: return _("Input is not valid."); case ERR_INVALID_SCRIPT: return _("Invalid script detected."); case ERR_INVALID_TX: return _("Transaction not valid."); case ERR_MAXIMUM: return _("Value more than PrivateSend pool maximum allows."); case ERR_MN_LIST: return _("Not in the Masternode list."); case ERR_MODE: return _("Incompatible mode."); case ERR_NON_STANDARD_PUBKEY: return _("Non-standard public key detected."); case ERR_NOT_A_MN: return _("This is not a Masternode."); case ERR_QUEUE_FULL: return _("Masternode queue is full."); case ERR_RECENT: return _("Last PrivateSend was too recent."); case ERR_SESSION: return _("Session not complete!"); case ERR_MISSING_TX: return _("Missing input transaction information."); case ERR_VERSION: return _("Incompatible version."); case MSG_NOERR: return _("No errors detected."); case MSG_SUCCESS: return _("Transaction created successfully."); case MSG_ENTRIES_ADDED: return _("Your entries added successfully."); default: return _("Unknown response."); } } bool CDarkSendSigner::IsVinAssociatedWithPubkey(const CTxIn& txin, const CPubKey& pubkey) { CScript payee; payee = GetScriptForDestination(pubkey.GetID()); CTransaction tx; uint256 hash; if(GetTransaction(txin.prevout.hash, tx, Params().GetConsensus(), hash, true)) { BOOST_FOREACH(CTxOut out, tx.vout) if(out.nValue == 1000*COIN && out.scriptPubKey == payee) return true; } return false; } bool CDarkSendSigner::GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet) { CBitcoinSecret vchSecret; if(!vchSecret.SetString(strSecret)) return false; keyRet = vchSecret.GetKey(); pubkeyRet = keyRet.GetPubKey(); return true; } bool CDarkSendSigner::SignMessage(std::string strMessage, std::vector<unsigned char>& vchSigRet, CKey key) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; return key.SignCompact(ss.GetHash(), vchSigRet); } bool CDarkSendSigner::VerifyMessage(CPubKey pubkey, const std::vector<unsigned char>& vchSig, std::string strMessage, std::string& strErrorRet) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkeyFromSig; if(!pubkeyFromSig.RecoverCompact(ss.GetHash(), vchSig)) { strErrorRet = "Error recovering public key."; return false; } if(pubkeyFromSig.GetID() != pubkey.GetID()) { strErrorRet = strprintf("Keys don't match: pubkey=%s, pubkeyFromSig=%s, strMessage=%s, vchSig=%s", pubkey.GetID().ToString(), pubkeyFromSig.GetID().ToString(), strMessage, EncodeBase64(&vchSig[0], vchSig.size())); return false; } return true; } bool CDarkSendEntry::AddScriptSig(const CTxIn& txin) { BOOST_FOREACH(CTxDSIn& txdsin, vecTxDSIn) { if(txdsin.prevout == txin.prevout && txdsin.nSequence == txin.nSequence) { if(txdsin.fHasSig) return false; txdsin.scriptSig = txin.scriptSig; txdsin.prevPubKey = txin.prevPubKey; txdsin.fHasSig = true; return true; } } return false; } bool CDarksendQueue::Sign() { if(!fMasterNode) return false; std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(nTime) + boost::lexical_cast<std::string>(fReady); if(!darkSendSigner.SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CDarksendQueue::Sign -- SignMessage() failed, %s\n", ToString()); return false; } return CheckSignature(activeMasternode.pubKeyMasternode); } bool CDarksendQueue::CheckSignature(const CPubKey& pubKeyMasternode) { std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nDenom) + boost::lexical_cast<std::string>(nTime) + boost::lexical_cast<std::string>(fReady); std::string strError = ""; if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendQueue::CheckSignature -- Got bad Masternode queue signature: %s; error: %s\n", ToString(), strError); return false; } return true; } bool CDarksendQueue::Relay() { std::vector<CNode*> vNodesCopy = CopyNodeVector(); BOOST_FOREACH(CNode* pnode, vNodesCopy) if(pnode->nVersion >= MIN_PRIVATESEND_PEER_PROTO_VERSION) pnode->PushMessage(NetMsgType::DSQUEUE, (*this)); ReleaseNodeVector(vNodesCopy); return true; } bool CDarksendBroadcastTx::Sign() { if(!fMasterNode) return false; std::string strMessage = tx.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime); if(!darkSendSigner.SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CDarksendBroadcastTx::Sign -- SignMessage() failed\n"); return false; } return CheckSignature(activeMasternode.pubKeyMasternode); } bool CDarksendBroadcastTx::CheckSignature(const CPubKey& pubKeyMasternode) { std::string strMessage = tx.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime); std::string strError = ""; if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CDarksendBroadcastTx::CheckSignature -- Got bad dstx signature, error: %s\n", strError); return false; } return true; } void CDarksendPool::RelayFinalTransaction(const CTransaction& txFinal) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_PRIVATESEND_PEER_PROTO_VERSION) pnode->PushMessage(NetMsgType::DSFINALTX, nSessionID, txFinal); } void CDarksendPool::RelayIn(const CDarkSendEntry& entry) { if(!pSubmittedToMasternode) return; CNode* pnode = FindNode(pSubmittedToMasternode->addr); if(pnode != NULL) { LogPrintf("CDarksendPool::RelayIn -- found master, relaying message to %s\n", pnode->addr.ToString()); pnode->PushMessage(NetMsgType::DSVIN, entry); } } void CDarksendPool::PushStatus(CNode* pnode, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID) { if(!pnode) return; pnode->PushMessage(NetMsgType::DSSTATUSUPDATE, nSessionID, (int)nState, (int)vecEntries.size(), (int)nStatusUpdate, (int)nMessageID); } void CDarksendPool::RelayStatus(PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_PRIVATESEND_PEER_PROTO_VERSION) PushStatus(pnode, nStatusUpdate, nMessageID); } void CDarksendPool::RelayCompletedTransaction(PoolMessage nMessageID) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= MIN_PRIVATESEND_PEER_PROTO_VERSION) pnode->PushMessage(NetMsgType::DSCOMPLETE, nSessionID, (int)nMessageID); } void CDarksendPool::SetState(PoolState nStateNew) { if(fMasterNode && (nStateNew == POOL_STATE_ERROR || nStateNew == POOL_STATE_SUCCESS)) { LogPrint("privatesend", "CDarksendPool::SetState -- Can't set state to ERROR or SUCCESS as a Masternode. \n"); return; } LogPrintf("CDarksendPool::SetState -- nState: %d, nStateNew: %d\n", nState, nStateNew); nState = nStateNew; } void CDarksendPool::UpdatedBlockTip(const CBlockIndex *pindex) { pCurrentBlockIndex = pindex; LogPrint("privatesend", "CDarksendPool::UpdatedBlockTip -- pCurrentBlockIndex->nHeight: %d\n", pCurrentBlockIndex->nHeight); if(!fLiteMode && masternodeSync.IsMasternodeListSynced()) { NewBlock(); } } //TODO: Rename/move to core void ThreadCheckDarkSendPool() { if(fLiteMode) return; // disable all Airin specific functionality static bool fOneThread; if(fOneThread) return; fOneThread = true; // Make this thread recognisable as the PrivateSend thread RenameThread("airin-privatesend"); unsigned int nTick = 0; unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN; while (true) { MilliSleep(1000); // try to sync from all available nodes, one step at a time masternodeSync.ProcessTick(); if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { nTick++; // make sure to check all masternodes first mnodeman.Check(); // check if we should activate or ping every few minutes, // slightly postpone first run to give net thread a chance to connect to some peers if(nTick % MASTERNODE_MIN_MNP_SECONDS == 15) activeMasternode.ManageState(); if(nTick % 60 == 0) { mnodeman.ProcessMasternodeConnections(); mnodeman.CheckAndRemove(); mnpayments.CheckAndRemove(); instantsend.CheckAndRemove(); } if(fMasterNode && (nTick % (60 * 5) == 0)) { mnodeman.DoFullVerificationStep(); } if(nTick % (60 * 5) == 0) { governance.DoMaintenance(); } darkSendPool.CheckTimeout(); darkSendPool.CheckForCompleteQueue(); if(nDoAutoNextRun == nTick) { darkSendPool.DoAutomaticDenominating(); nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); } } } }
[ "airincoin@gmail.com" ]
airincoin@gmail.com
a97d0f3e5f2037cdf3e6a97c0e8e40eba1dc3421
f15d6c870d51ffa4a7e6151c42ceb5de0eedf46a
/ThirdParty/paraEllip3d_DEM_PD/src/InputOutput/Parameter.h
ec3f8d3cb63f6a179559d6b9d10a6feb484b8b11
[]
no_license
pinebai/ParSim
1a5ee3687bd1582f31be9dbd88b3914769549095
f787523ae6c47c87ff1a74e199c7068ca45dc780
refs/heads/master
2021-01-24T07:45:12.923015
2017-04-22T04:34:44
2017-04-22T04:34:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,335
h
/* In general, built-in C++ types (ints, floats, characters, etc.) can be transmitted over MPI directly. For types defined by the standard library (such as std::string or std::vector) and some types in Boost (such as boost::variant), the Boost.Serialization library already contains all of the required serialization code. In these cases, you need only include the appropriate header from the boost/serialization directory. For types that do not already have a serialization header, you will first need to implement serialization code before the types can be transmitted using Boost.MPI. */ #ifndef PARAMETER_H #define PARAMETER_H #include <Core/Types/realtypes.h> #include <boost/mpi.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/utility.hpp> #include <boost/serialization/vector.hpp> #include <map> #include <string> #include <utility> #include <vector> namespace dem { class Parameter { public: // static function is part of the class, not part of the object, so it is used // like Parameter::get(). it can only access static members. // it is public so that it can be called by others like // Parameter::get() // and it can implicitly call private constructor Parameter(). static Parameter& get() { static Parameter instance; // instantiated on first use, // guaranteed to be destroyed return instance; } void readIn(const char* input); bool readInXML(const std::string& inputFileName); void writeOut(); void writeOutXML(); private: // constructor must be private to avoid instantiation by others because // singleton // should only be instantiated by itself Parameter() = default; ~Parameter() = default; // make sure these two are unaccessable to avoid copies of singelton Parameter(Parameter const&) = delete; // don't implement void operator=(Parameter const&) = delete; // don't implement public: std::map<std::string, REAL> param; std::vector<std::pair<REAL, REAL>> gradation; std::map<std::string, std::string> datafile; std::vector<REAL> sigmaPath; private: friend class boost::serialization::access; template <class ArchiveType> void serialize(ArchiveType& ar, const unsigned int version) { ar& param; ar& sigmaPath; } }; } #endif
[ "b.banerjee.nz@gmail.com" ]
b.banerjee.nz@gmail.com
5812c28b07d22846dc52c26a161449727c4e4c04
951b69aae583da24134fac00e8ca39fb684fc577
/arduino/opencr_develop/opencr_fw_template/opencr_fw_arduino/src/arduino/libraries/turtlebot3/turtlebot_burger/turtlebot3_core/turtlebot3_motor_driver.cpp
eaa21499e9435f42c67fb9a5aeed0455ad92d432
[ "Apache-2.0" ]
permissive
ROBOTIS-Will/OpenCR
6bb9281030c389fc40669ab8d2ea921ac8a4545e
0787393e189fd790eca6402c9c72574024123450
refs/heads/master
2021-06-06T04:33:29.635094
2021-05-17T09:32:55
2021-05-17T09:32:55
138,265,877
2
0
Apache-2.0
2018-06-22T06:51:25
2018-06-22T06:49:31
C
UTF-8
C++
false
false
5,041
cpp
/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * 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. *******************************************************************************/ /* Authors: Yoonseok Pyo, Leon Jung, Darby Lim, HanCheol Cho */ #include "turtlebot3_motor_driver.h" Turtlebot3MotorDriver::Turtlebot3MotorDriver() : baudrate_(BAUDRATE), protocol_version_(PROTOCOL_VERSION), left_wheel_id_(DXL_LEFT_ID), right_wheel_id_(DXL_RIGHT_ID) { } Turtlebot3MotorDriver::~Turtlebot3MotorDriver() { closeDynamixel(); } bool Turtlebot3MotorDriver::init(void) { portHandler_ = dynamixel::PortHandler::getPortHandler(DEVICENAME); packetHandler_ = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION); // Open port if (portHandler_->openPort()) { #ifdef DEBUG sprintf(log_msg, "Port is Opened"); nh.loginfo(log_msg); #endif } else { return false; } // Set port baudrate if (portHandler_->setBaudRate(baudrate_)) { #ifdef DEBUG sprintf(log_msg, "Baudrate is set"); nh.loginfo(log_msg); #endif } else { return false; } // Enable Dynamixel Torque setTorque(left_wheel_id_, true); setTorque(right_wheel_id_, true); groupSyncWriteVelocity_ = new dynamixel::GroupSyncWrite(portHandler_, packetHandler_, ADDR_X_GOAL_VELOCITY, LEN_X_GOAL_VELOCITY); groupSyncReadEncoder_ = new dynamixel::GroupSyncRead(portHandler_, packetHandler_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION); return true; } bool Turtlebot3MotorDriver::setTorque(uint8_t id, bool onoff) { uint8_t dxl_error = 0; int dxl_comm_result = COMM_TX_FAIL; dxl_comm_result = packetHandler_->write1ByteTxRx(portHandler_, id, ADDR_X_TORQUE_ENABLE, onoff, &dxl_error); if(dxl_comm_result != COMM_SUCCESS) { packetHandler_->printTxRxResult(dxl_comm_result); } else if(dxl_error != 0) { packetHandler_->printRxPacketError(dxl_error); } } void Turtlebot3MotorDriver::closeDynamixel(void) { // Disable Dynamixel Torque setTorque(left_wheel_id_, false); setTorque(right_wheel_id_, false); // Close port portHandler_->closePort(); } bool Turtlebot3MotorDriver::readEncoder(int32_t &left_value, int32_t &right_value) { int dxl_comm_result = COMM_TX_FAIL; // Communication result bool dxl_addparam_result = false; // addParam result bool dxl_getdata_result = false; // GetParam result // Set parameter dxl_addparam_result = groupSyncReadEncoder_->addParam(left_wheel_id_); if (dxl_addparam_result != true) return false; dxl_addparam_result = groupSyncReadEncoder_->addParam(right_wheel_id_); if (dxl_addparam_result != true) return false; // Syncread present position dxl_comm_result = groupSyncReadEncoder_->txRxPacket(); if (dxl_comm_result != COMM_SUCCESS) packetHandler_->printTxRxResult(dxl_comm_result); // Check if groupSyncRead data of Dynamixels are available dxl_getdata_result = groupSyncReadEncoder_->isAvailable(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION); if (dxl_getdata_result != true) return false; dxl_getdata_result = groupSyncReadEncoder_->isAvailable(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION); if (dxl_getdata_result != true) return false; // Get data left_value = groupSyncReadEncoder_->getData(left_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION); right_value = groupSyncReadEncoder_->getData(right_wheel_id_, ADDR_X_PRESENT_POSITION, LEN_X_PRESENT_POSITION); groupSyncReadEncoder_->clearParam(); return true; } bool Turtlebot3MotorDriver::speedControl(int64_t left_wheel_value, int64_t right_wheel_value) { bool dxl_addparam_result_; int8_t dxl_comm_result_; dxl_addparam_result_ = groupSyncWriteVelocity_->addParam(left_wheel_id_, (uint8_t*)&left_wheel_value); if (dxl_addparam_result_ != true) return false; dxl_addparam_result_ = groupSyncWriteVelocity_->addParam(right_wheel_id_, (uint8_t*)&right_wheel_value); if (dxl_addparam_result_ != true) return false; dxl_comm_result_ = groupSyncWriteVelocity_->txPacket(); if (dxl_comm_result_ != COMM_SUCCESS) { packetHandler_->printTxRxResult(dxl_comm_result_); return false; } groupSyncWriteVelocity_->clearParam(); return true; }
[ "willson@robotis.com" ]
willson@robotis.com
c9071880866cfd0e8f7f053f6b16fbd5590f054e
532dbcf3ea9aca0a414646246c2b0dc4bf650876
/Game Engine Framework/GameEngine/GameEngine/Vector2D.h
1dbe021752757568a7966a1a96e4122f87fdd534
[]
no_license
mindmastre/DX11-Framework
625d02135794f8fb9945ac83934f0375155bcc63
e7f4390c4f5781046ae487db3338e10aad534faa
refs/heads/master
2016-09-06T19:28:47.409948
2013-02-27T05:18:36
2013-02-27T05:18:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,997
h
#ifndef VECTOR2D_H #define VECTOR2D_H //default template Vector2D template<class T> struct Vector2D { T x, y; //T constructors Vector2D() { //do nothing } Vector2D(T val) { x = val; y = val; } Vector2D(T x, T y) { this->x = x; this->y = y; } ~Vector2D() { //do nothing } //Vector2D operators T operator[] (unsigned i) { if(i == 0) return x; else return y; } bool operator== (const Vector2D& rhs) { if(x != rhs.x) { return false; } else if(y != rhs.y) { return false; } else { return true; } } bool operator!= (const Vector2D& rhs) { if(x != rhs.x) { return true; } else if(y != rhs.y) { return true; } else { return false; } } bool operator== (const T& rhs) { if(x != rhs) { return false; } else if(y != rhs) { return false; } else { return true; } } bool operator!= (const T& rhs) { if(x != rhs) { return true; } else if(y != rhs) { return true; } else { return false; } } }; //float specific Vector2D template<> struct Vector2D<float> { float x, y; //float constructors Vector2D(); Vector2D(float val); Vector2D(float x, float y); ~Vector2D(); //Vector2D array operator float operator[] (unsigned i); //Vector2D - Vector2D operators Vector2D operator+ (const Vector2D& rhs); Vector2D operator- (const Vector2D& rhs); Vector2D operator* (const Vector2D& rhs); Vector2D operator/ (const Vector2D& rhs); Vector2D operator+= (const Vector2D& rhs); Vector2D operator-= (const Vector2D& rhs); Vector2D operator*= (const Vector2D& rhs); Vector2D operator/= (const Vector2D& rhs); bool operator== (const Vector2D& rhs); bool operator!= (const Vector2D& rhs); //Vector2D - float operators Vector2D operator+ (const float& rhs); Vector2D operator- (const float& rhs); Vector2D operator* (const float& rhs); Vector2D operator/ (const float& rhs); Vector2D operator+= (const float& rhs); Vector2D operator-= (const float& rhs); Vector2D operator*= (const float& rhs); Vector2D operator/= (const float& rhs); bool operator== (const float& rhs); bool operator!= (const float& rhs); //Vector2D math functions float Dot(const Vector2D<float>& rhs); float Cross(const Vector2D<float>& rhs); float Magnitude(); float MagnitudeSquared(); void Normalize(); Vector2D Normalized(); void Invert(); Vector2D Inverted(); }; //double specific Vector2D template<> struct Vector2D<double> { double x, y; //float constructors Vector2D(); Vector2D(double val); Vector2D(double x, double y); ~Vector2D(); //Vector2D array operator double operator[] (unsigned i); //Vector2D - Vector2D operators Vector2D operator+ (const Vector2D& rhs); Vector2D operator- (const Vector2D& rhs); Vector2D operator* (const Vector2D& rhs); Vector2D operator/ (const Vector2D& rhs); Vector2D operator+= (const Vector2D& rhs); Vector2D operator-= (const Vector2D& rhs); Vector2D operator*= (const Vector2D& rhs); Vector2D operator/= (const Vector2D& rhs); bool operator== (const Vector2D& rhs); bool operator!= (const Vector2D& rhs); //Vector2D - float operators Vector2D operator+ (const double& rhs); Vector2D operator- (const double& rhs); Vector2D operator* (const double& rhs); Vector2D operator/ (const double& rhs); Vector2D operator+= (const double& rhs); Vector2D operator-= (const double& rhs); Vector2D operator*= (const double& rhs); Vector2D operator/= (const double& rhs); bool operator== (const double& rhs); bool operator!= (const double& rhs); //Vector2D math functions double Dot(const Vector2D<double>& rhs); double Cross(const Vector2D<double>& rhs); double Magnitude(); double MagnitudeSquared(); void Normalize(); Vector2D Normalized(); void Invert(); Vector2D Inverted(); }; #endif //VECTOR2D_H
[ "mind_mastre@yahoo.com" ]
mind_mastre@yahoo.com
71e8b31e74595af1beb4915f5a9411dab7e65e98
c08da7b27f736da6c9861e4aacf871fb0bac6010
/SDL-OpenGL-Tests-2/perlinMap/perlinNoise.cpp
775c0408987f5874b0df2ead35c54475000b4784
[]
no_license
Kuechenzwiebel/SDL-OpenGL-Tests-2
ea3b364cb396b123d3715c973e3b7883043a7cf8
b92d72d98ad44641f175507aa7db874135bb6097
refs/heads/master
2020-06-28T23:46:34.195213
2020-01-08T18:23:46
2020-01-08T18:23:46
200,374,046
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
// // perlinNoise.cpp // SDL-OpenGL-Tests-2 // // Created by Tobias Pflüger on 26.09.19. // Copyright © 2019 Tobias Pflüger. All rights reserved. // #include "perlinNoise.hpp" PerlinNoise::PerlinNoise(unsigned int seed): perlinNoise(seed), frequency(2.0f), multiplier(1.0f), octaves(1), seed(seed), offset(0.0f) { } float PerlinNoise::octaveNoise(float x, float y) { return perlinNoise.octaveNoise(x / frequency, y / frequency, octaves) * multiplier + offset; }
[ "tobiaspflueger@t-online.de" ]
tobiaspflueger@t-online.de
b8724de523bfb626c0b4e52b2380276f21a395d6
7182b78c0ecf8b99d9e5db315b34b7c7577b779b
/old_complete/dynamol/trunk/Main_Build/dynamol/license.h
8683a687523c502e5afec063b43fba3fe03d0c32
[]
no_license
gnulnx/dynamol
cbc85abf3d23c9af508576731d06f8ba372449db
88a1000563f1d49793df8a404eff0fe8768b46b4
refs/heads/master
2016-09-06T11:20:54.279297
2015-04-09T14:02:42
2015-04-09T14:02:42
32,398,825
0
0
null
null
null
null
UTF-8
C++
false
false
11,158
h
//  // // # ##### ### -= License library =-  // // # # # # License.h - License key coder  // // # # #  // // # # # Encodes and decodes 5x5 digit license keys  // // # # # #  // // ##### ##### ### R1 (C)2003 Markus Ewald -> License.txt  // //  // #ifndef LIC_LICENSE_H #define LIC_LICENSE_H #include <string> #include <vector> #include <iostream> #include <iomanip> using namespace std; namespace LicenseKey { #ifndef LIC_NO_ENCODER /// Encode a license key from 4 longs inline std::string encode(const unsigned long pnData[4]); /// Encode a license key with bit mixing inline std::string encode( const unsigned long pnData[4], const unsigned char pcBitPositions[128] ); #endif #ifndef LIC_NO_DECODER /// Decode a license key into 4 longs inline void decode(const std::string &sCoded, unsigned long pnData[4]); /// Decode a license key with bit mixing inline void decode( const std::string &sCoded, unsigned long pnData[4], const unsigned char pcBitPositions[128] ); #endif }; #ifndef LIC_NO_ENCODER // ####################################################################### // // # LicenseKey::encode() # // // ####################################################################### // /** Encodes the 4 longs into a license key @param pnData 4 long integer values to encode @return The encoded license key */ inline std::string LicenseKey::encode(const unsigned long pnData[4]) { static const unsigned char pcBitPositions[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127 }; return encode(pnData, pcBitPositions); } // ####################################################################### // // # LicenseKey::encode() # // // ####################################################################### // /** Encodes the 4 longs into a license key and performs bit-mixing on the individual bits to make the data less traceable. @param pnData 4 long integer values to encode @param pcBitPositions Bit positions, has to contain each number from 0 to 127 exactly once @return The encoded license number */ inline std::string LicenseKey::encode( const unsigned long pnData[4], const unsigned char pcBitPositions[128] ) { typedef std::vector<bool> BoolVector; static const char pcEncodeTable[] = {"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; static const unsigned long pn2Powers[32][2] = { { 0, 1 }, { 0, 2 }, { 0, 4 }, { 0, 8 }, { 0, 16 }, { 0, 32 }, { 0, 64 }, { 0, 128 }, { 0, 256 }, { 0, 512 }, { 0, 1024 }, { 0, 2048 }, { 0, 4096 }, { 0, 8192 }, { 0, 16384 }, { 0, 32768 }, { 0, 65536 }, { 0, 131072 }, { 0, 262144 }, { 0, 524288 }, { 0, 1048576 }, { 0, 2097152 }, { 0, 4194304 }, { 0, 8388608 }, { 0, 16777216 }, { 0, 33554432 }, { 0, 67108864 }, { 0, 134217728 }, { 0, 268435456 }, { 0, 536870912 }, { 0, 1073741824 }, { 0, 2147483648 } }; BoolVector Data(128); // Build a bit array from the input data for(unsigned int j = 0; j < 4; j++) for(unsigned int i = 0; i < 32; i++) Data[pcBitPositions[j * 32 + i]] = (pnData[j] & pn2Powers[i][1]) != 0; // Build 4 sequences of 6 characters from the first 124 bits std::string sResult; for(unsigned int i = 0; i < 4; i++) { unsigned long nSequence = 0; for(unsigned int j = 0; j < 31; j++) nSequence |= pn2Powers[j][Data[i * 31 + j] ^ ((i * 31 + j) & 1)]; sResult += pcEncodeTable[nSequence % 36]; cout << pcEncodeTable[nSequence % 36] << endl; nSequence /= 36; sResult += pcEncodeTable[nSequence % 36]; nSequence /= 36; sResult += pcEncodeTable[nSequence % 36]; nSequence /= 36; sResult += pcEncodeTable[nSequence % 36]; nSequence /= 36; sResult += pcEncodeTable[nSequence % 36]; nSequence /= 36; sResult += pcEncodeTable[nSequence % 36]; cout <<"sResult: "<< sResult << endl; } // Use the remaining 4 bits to build the final character unsigned long nSequence = pn2Powers[4][ Data[124]] | pn2Powers[3][!Data[125]] | pn2Powers[2][ Data[126]] | pn2Powers[1][!Data[127]] | pn2Powers[0][1]; return sResult.substr( 0, 5) + "-" + sResult.substr( 5, 5) + "-" + sResult.substr(10, 5) + "-" + sResult.substr(15, 5) + "-" + sResult.substr(20, 5) + pcEncodeTable[nSequence]; }; #endif // LIC_NO_ENCODER #ifndef LIC_NO_DECODER // ####################################################################### // // # License::decode() # // // ####################################################################### // /** Decodes a license key into 4 longs @param sCoded Coded license key @param pnData 4 long integer values to receive the decoded data */ inline void LicenseKey::decode(const std::string &sCoded, unsigned long pnData[4]) { //cout <<"HERE 1: " << endl; static const unsigned char pcBitPositions[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127 }; //cout <<"HERE 2"<<endl; decode(sCoded, pnData, pcBitPositions); } // ####################################################################### // // # LicenseKey::decode() # // // ####################################################################### // /** Decodes a license key into 4 longs and resolves bit-mixing performed on the individual bits @param sCoded Coded license key @param pnData 4 long integer values to receive the decoded data @param pcBitPositions Bit positions, has to contain each number from 0 to 127 exactly once */ inline void LicenseKey::decode( const std::string &sCoded, unsigned long pnData[4], const unsigned char pcBitPositions[128] ) { //cout <<"HERE 1"<<endl; typedef std::vector<bool> BoolVector; static const unsigned long pn2Powers[32][2] = { { 0, 1 }, { 0, 2 }, { 0, 4 }, { 0, 8 }, { 0, 16 }, { 0, 32 }, { 0, 64 }, { 0, 128 }, { 0, 256 }, { 0, 512 }, { 0, 1024 }, { 0, 2048 }, { 0, 4096 }, { 0, 8192 }, { 0, 16384 }, { 0, 32768 }, { 0, 65536 }, { 0, 131072 }, { 0, 262144 }, { 0, 524288 }, { 0, 1048576 }, { 0, 2097152 }, { 0, 4194304 }, { 0, 8388608 }, { 0, 16777216 }, { 0, 33554432 }, { 0, 67108864 }, { 0, 134217728 }, { 0, 268435456 }, { 0, 536870912 }, { 0, 1073741824 }, { 0, 2147483648 } }; static const unsigned char pcDecodeTable[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; BoolVector Data(128); // Remove all minus signs from the string std::string sTemp(sCoded); while(std::string::size_type Pos = sTemp.find_first_of(" -")) { if(Pos == std::string::npos) break; sTemp.erase(Pos, 1); } // Convert the first 4 sequences of 6 chars into 124 bits for(int j = 0; j < 4; j++) { unsigned long nSequence = pcDecodeTable[sTemp[j * 6 + 5]] * 60466176 + pcDecodeTable[sTemp[j * 6 + 4]] * 1679616 + pcDecodeTable[sTemp[j * 6 + 3]] * 46656 + pcDecodeTable[sTemp[j * 6 + 2]] * 1296 + pcDecodeTable[sTemp[j * 6 + 1]] * 36 + pcDecodeTable[sTemp[j * 6 + 0]]; for(unsigned int i = 0; i < 31; i++) Data[j * 31 + i] = ((nSequence & pn2Powers[i][1]) != 0) ^ ((j * 31 + i) & 1); } // Append the remaining character's 4 bits unsigned long nSequence = pcDecodeTable[sTemp[24]]; Data[124] = (nSequence & pn2Powers[4][1]) != 0; Data[125] = (nSequence & pn2Powers[3][1]) == 0; Data[126] = (nSequence & pn2Powers[2][1]) != 0; Data[127] = (nSequence & pn2Powers[1][1]) == 0; // Convert the bit array into the desired output data for(int i = 0; i < 4; i++) { pnData[i] = 0; for(int j = 0; j < 32; j++) pnData[i] |= pn2Powers[j][Data[pcBitPositions[i * 32 + j]]]; } return; } #endif // LIC_NO_DECODER #endif // LIC_LI
[ "jfurr@Johns-MacBook-Pro.local" ]
jfurr@Johns-MacBook-Pro.local
1ecbc51350c3ce9ec7f593d485bcf59cf77cb263
0ce732dd213eacaf9d23a798c6fb4028afe7cceb
/src/model.cc
6354b9f3a1c4e5cf3a1e95a39438de7a3189cd53
[]
no_license
iftekhar-hc/uDNN
c329eb69f70f9e9a2726f2a684507c80b5c88702
177b5324aaf496feee121b9fef359f8f312ff71a
refs/heads/master
2023-02-11T04:13:29.520138
2021-01-10T21:21:04
2021-01-10T21:21:04
328,480,800
0
0
null
null
null
null
UTF-8
C++
false
false
994
cc
#include "model.hh" void Model::add_layer(const std::string &name, LayerBase *layer) { // the name has to be unique if (names_.find(name) != names_.end()) throw std::invalid_argument("A layer with name " + name + " already exists"); layer->name = name; if (!layers_.empty()) { // connect them together auto pre = layers_.back(); pre->connect(layer); } layers_.emplace_back(layer); } void Model::predict(const TensorBase *tensor) { if (layers_.empty()) return; auto layer = layers_.front(); do { // we don't do any copy here layer->forward(tensor->ptr()); tensor = layer->out_base(); layer = layer->next(); } while (layer != nullptr); } const TensorBase * Model::out() const { if (!layers_.empty()) return layers_.back()->out_base(); else return nullptr; } DType Model::out_type() const { // default float if (layers_.empty()) return DType::Float; return layers_.back()->out_type(); }
[ "keyi@stanford.edu" ]
keyi@stanford.edu
46fe36bae58c90c2a0f87a2d3d0cc9320ccf0f52
cbaccb1ab5d17954b2f657ed9cdebe8f44397c59
/GetFactory.cpp
6ce20cc34d6fc520b0079956cb80c54885469bd3
[]
no_license
yonglinhan/GBD0505
6f95a4f43a1ded51385e6c82853b108f455e1b2a
2b72537d1d4bc4690c80a529e1dbedc21aca60a5
refs/heads/master
2020-05-19T11:29:33.943545
2019-05-07T03:35:15
2019-05-07T03:35:15
184,993,432
0
1
null
null
null
null
UTF-8
C++
false
false
1,835
cpp
#include "GetFactory.h" #include "RecordControlFactory.h" #include "AlarmControlFactory.h" #include "CameraControlFactory.h" #include "DeviceControlFactory.h" #include "RequestFactory.h" #include "InviteFactory.h" #include "registfactory.h" GetFactory::GetFactory() { } GetFactory::~GetFactory() { if (cameraControl != nullptr) { delete cameraControl; cameraControl = nullptr; } if (recordControl != nullptr) { delete recordControl; recordControl = nullptr; } if (alarmControl != nullptr) { delete alarmControl; alarmControl = nullptr; } if (deviceControl != nullptr) { delete deviceControl; deviceControl = nullptr; } if (requestControl != nullptr) { delete requestControl; requestControl = nullptr; } if (invite != nullptr) { delete invite; invite = nullptr; } } CommFactory * GetFactory::GetCameraControlFactory() { if(cameraControl == nullptr) cameraControl = new CameraControlFactory(); return cameraControl; } CommFactory * GetFactory::GetRecordControlFactory() { if (recordControl == nullptr) recordControl = new RecordControlFactory(); return recordControl; } CommFactory * GetFactory::GetAlarmControlFactory() { if (alarmControl == nullptr) alarmControl = new AlarmControlFactory(); return alarmControl; } CommFactory * GetFactory::GetDeviceControlFactory() { if (deviceControl == nullptr) deviceControl = new DeviceControlFactory(); return deviceControl; } CommFactory * GetFactory::GetRequestFactory() { if (requestControl == nullptr) requestControl = new RequestFactory(); return requestControl; } CommFactory * GetFactory::GetInviteFactory() { if (invite == nullptr) invite = new InviteFactory(); return invite; } CommFactory * GetFactory::GetRegistFactory() { if (regist == nullptr) regist = new RegistFactory(); return regist; }
[ "857729584@qq.com" ]
857729584@qq.com
9c608ae0204934668d05c3fbdc8039fb21ae0ec8
dbec0d5c77b82e87de1d161d3b7f3563128bba88
/fundamentals/variable.cpp
4789133d733a8db853834a1cee0bdd9aede5096a
[]
no_license
abe-jr/teaching-cpp-for-friends
b4d619e8821a3f98a3d277ba6950b64e7b184b5f
04d554f121aa974185a2728d0d7e35908b3e70a4
refs/heads/master
2023-01-05T07:55:41.477253
2020-11-03T04:07:14
2020-11-03T04:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <iostream> #include <cstdio> int main() { // type receives a value double price = 99.80; double tax = 0.08; // right here one expression // price * (1 + tax); double finalPrice = price * (1 + tax); printf("The final price is %f.", finalPrice); return 0; } // %f. for float numbers // %d for check then
[ "abelardobandeirajr@gmail.com" ]
abelardobandeirajr@gmail.com
be821345e458ca62b807ba8dba557dc16d1df3b0
0ab065c90eb7d83962a50c5883bb5ee306fd9f9a
/ShogiGUI_Try3/board.h
428708e97d951d27b5eb0990808eb689d137af83
[]
no_license
toonst5/NetProg
2b8399886e2dbf4a4ec76bf50b451c5c82df040b
37cdc5cd772bee129d64ec529e2ed860c040164b
refs/heads/main
2023-06-04T07:43:01.663183
2021-05-30T19:45:07
2021-05-30T19:45:07
352,420,037
0
0
null
null
null
null
UTF-8
C++
false
false
603
h
#ifndef BOARD_H #define BOARD_H #include <QList> #include "pion.h" #include "rect.h" #include "space.h" #include "kinggeneral.h" #include "footsoldier.h" #include "flyingchariot.h" namespace Shogi { class game; class board { private: void creatPionColm(int x, int y, int numPionen, QString player, QString soort); QList<pion*> Pionen; game* P; const unsigned char SHIFT=110; public: board(); board(game* W); ~board(); QList<pion*> getPionen(); void placePionen(int x, int y/*, int cols, int rows*/); }; } #endif // BOARD_H
[ "noreply@github.com" ]
noreply@github.com
97266cc570ca6ff58b0268da35acdf10b1ba3c5b
31669c6d3fbacd1ecce867b79473213e7ab879f6
/Analyzer/Rate/TriggerRateTool.h
093e2ef43cf57b269838d41d1060b49937d2ba7d
[]
no_license
snucms/TSNtuple
3e4ba9946333cebfcf8af742394688279e5d3d69
45e65a4a57c6a5c2f94c4eca1f3eb8e57b9e539c
refs/heads/master
2021-05-06T06:01:47.905182
2018-07-25T08:29:07
2018-07-25T08:29:07
113,805,339
0
4
null
2018-07-24T13:05:32
2017-12-11T03:00:03
Python
UTF-8
C++
false
false
23,265
h
#include <TChain.h> #include <TFile.h> #include <TH1D.h> #include <TH2D.h> #include <TLorentzVector.h> #include <TStopwatch.h> #include <TTimeStamp.h> #include <TString.h> #include <TLegend.h> #include <THStack.h> #include <TPad.h> #include <TCanvas.h> #include <TColor.h> #include <TAttMarker.h> #include <TF1.h> #include <TStyle.h> #include <TROOT.h> #include <TApplication.h> #include <vector> #include <TMath.h> #include <TSystem.h> #include <Include/NtupleHandle.h> #include <Include/Object.h> #define nMaxLumiBlock 5000 #define LumiBlockTime 23.31 // -- HLT_Physics_part[0-7]_v7 -- // // -- 7.5e33: 320 // -- 1.0e34: 400 // -- 1.2e34: 500 // -- 1.4e34: 580 // -- 1.6e34: 580 vector<Int_t> vec_Prescale_Run301567 = {400, 320}; vector<Double_t> vec_LS_Run301567 = {20, 267, 99999}; vector<Int_t> vec_Prescale_Run301627 = {400, 320, 400, 320}; vector<Double_t> vec_LS_Run301627 = {45, 63, 82, 264, 99999}; vector<Int_t> vec_Prescale_Run301664 = {320, 400, 320}; vector<Double_t> vec_LS_Run301664 = {27, 49, 203, 99999}; vector<Int_t> vec_Prescale_Run301665 = {320}; vector<Double_t> vec_LS_Run301665 = {1, 99999}; vector<Int_t> vec_Prescale_Run301694 = {580, 580}; vector<Double_t> vec_LS_Run301694 = {27, 64, 99999}; vector<Int_t> vec_Prescale_Run301912 = {320}; vector<Double_t> vec_LS_Run301912 = {43, 99999}; vector<Int_t> vec_Prescale_Run301913 = {320}; vector<Double_t> vec_LS_Run301913 = {1, 99999}; vector<Int_t> vec_Prescale_Run301914 = {320}; vector<Double_t> vec_LS_Run301914 = {1, 99999}; vector<Int_t> vec_Prescale_Run301941 = {580, 320}; vector<Double_t> vec_LS_Run301941 = {11, 32, 99999}; vector<Int_t> vec_Prescale_Run301959 = {400, 320, 0}; vector<Double_t> vec_LS_Run301959 = {23, 433, 1061, 99999}; Int_t Find_PrescaleValue( Int_t RunNum, Int_t LumiBlockNum ) { vector<Int_t> vec_Prescale; vector<Double_t> vec_LS; if( RunNum == 301567 ) { vec_Prescale = vec_Prescale_Run301567; vec_LS = vec_LS_Run301567; } else if( RunNum == 301627 ) { vec_Prescale = vec_Prescale_Run301627; vec_LS = vec_LS_Run301627; } else if( RunNum == 301664 ) { vec_Prescale = vec_Prescale_Run301664; vec_LS = vec_LS_Run301664; } else if( RunNum == 301665 ) { vec_Prescale = vec_Prescale_Run301665; vec_LS = vec_LS_Run301665; } else if( RunNum == 301694 ) { vec_Prescale = vec_Prescale_Run301694; vec_LS = vec_LS_Run301694; } else if( RunNum == 301912 ) { vec_Prescale = vec_Prescale_Run301912; vec_LS = vec_LS_Run301912; } else if( RunNum == 301913 ) { vec_Prescale = vec_Prescale_Run301913; vec_LS = vec_LS_Run301913; } else if( RunNum == 301914 ) { vec_Prescale = vec_Prescale_Run301914; vec_LS = vec_LS_Run301914; } else if( RunNum == 301941 ) { vec_Prescale = vec_Prescale_Run301941; vec_LS = vec_LS_Run301941; } else if( RunNum == 301959 ) { vec_Prescale = vec_Prescale_Run301959; vec_LS = vec_LS_Run301959; } // -- find pre-scale value -- // Double_t Prescale = 0; Int_t nBin = (Int_t)vec_Prescale.size(); for(Int_t i=0; i<nBin; i++) { Double_t LowerEdge = vec_LS[i]; Double_t UpperEdge = vec_LS[i+1]; if( LumiBlockNum >= LowerEdge && LumiBlockNum < UpperEdge ) { Prescale = vec_Prescale[i]; break; } } // printf("[Run = %d, LS = %d] -> Prescale = %.0lf\n", RunNum, LumiBlockNum, Prescale); return Prescale; } // Int_t Find_PrescaleValue( Double_t InstLumi ) // { // Int_t Prescale = 0; // UInt_t nBin = (Int_t)vec_Prescale.size(); // if( InstLumi > vec_LumiEdge[nBin] ) // -- extrapolation to higher lumi. -- // // Prescale = vec_Prescale[nBin-1]; // else // { // for(UInt_t i=0; i<nBin; i++) // { // Double_t LowerEdge = vec_LumiEdge[i]; // Double_t UpperEdge = vec_LumiEdge[i+1]; // if( InstLumi > LowerEdge && InstLumi < UpperEdge ) // { // Prescale = vec_Prescale[i]; // break; // } // } // } // // printf("[Inst.Lumi = %lf] -> Prescale = %.0lf\n", InstLumi, Prescale); // return Prescale; // } class LumiBlockInfo { public: Int_t LumiBlockNum; Double_t nEvent; Double_t nFiredEvent; Double_t nEvent_UnPS; Double_t nFiredEvent_UnPS; Double_t nFiredEvent_UnPS_Scaled2e34; Double_t Sum_InstLumi; Double_t Mean_InstLumi; Double_t Sum_nVertices; Double_t Mean_nVertices; Double_t Rate; Double_t Rate_UnPS; Double_t Rate_UnPS_Scaled2e34; LumiBlockInfo( Int_t _Num ) { this->LumiBlockNum = _Num; this->Init(); } void Fill( KPEvent &event, TString TriggerTag ) { Double_t Prescale = Find_PrescaleValue( event.RunNum, event.LumiBlockNum ); this->nEvent += 1; this->nEvent_UnPS += Prescale; this->Sum_InstLumi = Sum_InstLumi + event.InstLumi; this->Sum_nVertices = Sum_nVertices + event.nVertices; if( std::find(event.vec_FiredTrigger->begin(), event.vec_FiredTrigger->end(), TriggerTag) != event.vec_FiredTrigger->end() ) // -- if trigger is fired -- // { this->nFiredEvent += 1; this->nFiredEvent_UnPS += Prescale; } } void Calc_Rate() { if( this->nEvent == 0 ) { this->Mean_InstLumi = 0; this->Mean_nVertices = 0; this->Rate = 0; this->Rate_UnPS = 0; this->Rate_UnPS_Scaled2e34 = 0; } else { this->Mean_InstLumi = this->Sum_InstLumi / this->nEvent; // -- divided by total # events, not only # fired events! -- // this->Mean_nVertices = this->Sum_nVertices / this->nEvent; // -- normalized to the # datasets included: HLTPhysicsN datasets -- // this->nEvent = this->nEvent / (Double_t)nDataset; this->nEvent_UnPS = this->nEvent_UnPS / (Double_t)nDataset; this->nFiredEvent = this->nFiredEvent / (Double_t)nDataset; this->nFiredEvent_UnPS = this->nFiredEvent_UnPS / (Double_t)nDataset; this->nFiredEvent_UnPS_Scaled2e34 = this->nFiredEvent_UnPS_Scaled2e34 / (Double_t)nDataset; /////////////////////////////////////////////////////////////////////// this->Rate = this->nFiredEvent / LumiBlockTime; // -- unit: Hz -- // this->Rate_UnPS = this->nFiredEvent_UnPS / LumiBlockTime; Double_t SF_Lumi = 20000.0 / this->Mean_InstLumi; this->nFiredEvent_UnPS_Scaled2e34 = this->nFiredEvent_UnPS * SF_Lumi; this->Rate_UnPS_Scaled2e34 = this->nFiredEvent_UnPS_Scaled2e34 / LumiBlockTime; // printf("[%d lumi-block] (# fired events, # fired rate, un-prescaled # rate, scaled to 2e34 rate) = (%d, %lf, %lf, %lf)\n", // this->LumiBlockNum, this->nFiredEvent, this->Rate, this->Rate_UnPS, this->Rate_UnPS_Scaled2e34); } } private: void Init() { this->nEvent = 0; this->nFiredEvent = 0; this->nEvent_UnPS = 0; this->nFiredEvent_UnPS = 0; this->nFiredEvent_UnPS_Scaled2e34 = 0; this->Sum_InstLumi = 0; this->Mean_InstLumi = 0; this->Sum_nVertices = 0; this->Mean_nVertices = 0; this->Rate = 0; this->Rate_UnPS = 0; this->Rate_UnPS_Scaled2e34 = 0; } }; class RunInfo { public: Int_t RunNum; vector< LumiBlockInfo* > vec_LumiBlockInfo; RunInfo( Int_t _RunNum ) { this->Init(); this->RunNum = _RunNum; } void Fill( KPEvent &event, TString TriggerTag ) { Int_t LumiBlockNum = event.LumiBlockNum; vec_LumiBlockInfo[LumiBlockNum]->Fill( event, TriggerTag ); } void CalcRate_EachLumiBlock() { for( auto& Info : this->vec_LumiBlockInfo ) Info->Calc_Rate(); } private: void Init() { this->RunNum = 0; // -- 0-th content: dummy (to have consistent between vector index and exact lumi-block number) -- // for(Int_t i=0; i<nMaxLumiBlock+1; i++) { LumiBlockInfo* Info = new LumiBlockInfo( i ); vec_LumiBlockInfo.push_back( Info ); } } }; class RunHistContainer { public: TString Tag; vector<TH1D*> vec_Hist; TH1D* h_LumiBlock_vs_nEvent; TH1D* h_LumiBlock_vs_nFiredEvent; TH1D* h_LumiBlock_vs_InstLumiMean; TH1D* h_LumiBlock_vs_nVerticesMean; TH1D* h_LumiBlock_vs_Rate; TH1D* h_LumiBlock_vs_nFiredEvent_UnPS; TH1D* h_LumiBlock_vs_Rate_UnPS; TH1D* h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34; TH1D* h_LumiBlock_vs_Rate_UnPS_Scaled2e34; // -- just 1 bin -- // TH1D* h_TotalRate; TH1D* h_TotalRate_UnPS; TH1D* h_TotalRate_UnPS_Scaled2e34; Double_t nFiredEvent; Double_t nFiredEvent_UnPS; Double_t nFiredEvent_UnPS_Scaled2e34; Int_t nLumiBlock; Double_t TotalRate; Double_t TotalRate_UnPS; Double_t TotalRate_UnPS_Scaled2e34; RunHistContainer( TString _Tag ) { this->Tag = _Tag; this->Init(); } void Fill( LumiBlockInfo* Info ) { Int_t LumiBlockNum = Info->LumiBlockNum; // -- same with bin number -- // this->h_LumiBlock_vs_nEvent->SetBinContent(LumiBlockNum, Info->nEvent ); this->h_LumiBlock_vs_nEvent->SetBinError(LumiBlockNum, sqrt(Info->nEvent) ); this->h_LumiBlock_vs_nFiredEvent->SetBinContent(LumiBlockNum, Info->nFiredEvent ); this->h_LumiBlock_vs_nFiredEvent->SetBinError(LumiBlockNum, sqrt(Info->nFiredEvent) ); this->h_LumiBlock_vs_InstLumiMean->SetBinContent(LumiBlockNum, Info->Mean_InstLumi ); this->h_LumiBlock_vs_InstLumiMean->SetBinError(LumiBlockNum, 0 ); this->h_LumiBlock_vs_nVerticesMean->SetBinContent(LumiBlockNum, Info->Mean_nVertices ); this->h_LumiBlock_vs_nVerticesMean->SetBinError(LumiBlockNum, 0 ); this->h_LumiBlock_vs_Rate->SetBinContent(LumiBlockNum, Info->Rate ); this->h_LumiBlock_vs_Rate->SetBinError(LumiBlockNum, Info->Rate * (1.0 / sqrt(Info->nFiredEvent)) ); // -- un-prescaled -- // this->h_LumiBlock_vs_nFiredEvent_UnPS->SetBinContent(LumiBlockNum, Info->nFiredEvent_UnPS ); this->h_LumiBlock_vs_nFiredEvent_UnPS->SetBinError(LumiBlockNum, 0); this->h_LumiBlock_vs_Rate_UnPS->SetBinContent(LumiBlockNum, Info->Rate_UnPS ); this->h_LumiBlock_vs_Rate_UnPS->SetBinError(LumiBlockNum, 0); // -- scaled to 2e34 -- // this->h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34->SetBinContent(LumiBlockNum, Info->nFiredEvent_UnPS_Scaled2e34 ); this->h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34->SetBinError(LumiBlockNum, 0); this->h_LumiBlock_vs_Rate_UnPS_Scaled2e34->SetBinContent(LumiBlockNum, Info->Rate_UnPS_Scaled2e34 ); this->h_LumiBlock_vs_Rate_UnPS_Scaled2e34->SetBinError(LumiBlockNum, 0); this->nFiredEvent += Info->nFiredEvent; this->nFiredEvent_UnPS += Info->nFiredEvent_UnPS; this->nFiredEvent_UnPS_Scaled2e34 += Info->nFiredEvent_UnPS_Scaled2e34; this->nLumiBlock += 1; } void Save( TFile *f_output ) { // -- fill histogram for total rate -- // if( this->nLumiBlock == 0 ) { this->TotalRate = 0; this->TotalRate_UnPS = 0; this->TotalRate_UnPS_Scaled2e34 = 0; } else { this->TotalRate = this->nFiredEvent / (this->nLumiBlock * LumiBlockTime); this->TotalRate_UnPS = this->nFiredEvent_UnPS / (this->nLumiBlock * LumiBlockTime); this->TotalRate_UnPS_Scaled2e34 = this->nFiredEvent_UnPS_Scaled2e34 / (this->nLumiBlock * LumiBlockTime); } this->h_TotalRate->SetBinContent(1, this->TotalRate); this->h_TotalRate->SetBinError(1, 0); this->h_TotalRate_UnPS->SetBinContent(1, this->TotalRate_UnPS); this->h_TotalRate_UnPS->SetBinError(1, 0); this->h_TotalRate_UnPS_Scaled2e34->SetBinContent(1, this->TotalRate_UnPS_Scaled2e34); this->h_TotalRate_UnPS_Scaled2e34->SetBinError(1, 0); f_output->cd(); for( const auto& h : this->vec_Hist ) h->Write(); } private: void Init() { this->h_LumiBlock_vs_nEvent = new TH1D("h_LumiBlock_vs_nEvent_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_nEvent ); this->h_LumiBlock_vs_nFiredEvent = new TH1D("h_LumiBlock_vs_nFiredEvent_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_nFiredEvent ); this->h_LumiBlock_vs_InstLumiMean = new TH1D("h_LumiBlock_vs_InstLumiMean_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_InstLumiMean ); this->h_LumiBlock_vs_nVerticesMean = new TH1D("h_LumiBlock_vs_nVerticesMean_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_nVerticesMean ); this->h_LumiBlock_vs_Rate = new TH1D("h_LumiBlock_vs_Rate_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_Rate ); this->h_LumiBlock_vs_nFiredEvent_UnPS = new TH1D("h_LumiBlock_vs_nFiredEvent_UnPS_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_nFiredEvent_UnPS ); this->h_LumiBlock_vs_Rate_UnPS = new TH1D("h_LumiBlock_vs_Rate_UnPS_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_Rate_UnPS ); this->h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34 = new TH1D("h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_nFiredEvent_UnPS_Scaled2e34 ); this->h_LumiBlock_vs_Rate_UnPS_Scaled2e34 = new TH1D("h_LumiBlock_vs_Rate_UnPS_Scaled2e34_"+this->Tag, "", nMaxLumiBlock, 1, nMaxLumiBlock+1 ); // -- starts at 1 -- // this->vec_Hist.push_back( this->h_LumiBlock_vs_Rate_UnPS_Scaled2e34 ); this->h_TotalRate = new TH1D("h_TotalRate_"+this->Tag, "", 1, 0, 1); this->vec_Hist.push_back( this->h_TotalRate ); this->h_TotalRate_UnPS = new TH1D("h_TotalRate_UnPS_"+this->Tag, "", 1, 0, 1); this->vec_Hist.push_back( this->h_TotalRate_UnPS ); this->h_TotalRate_UnPS_Scaled2e34 = new TH1D("h_TotalRate_UnPS_Scaled2e34_"+this->Tag, "", 1, 0, 1); this->vec_Hist.push_back( this->h_TotalRate_UnPS_Scaled2e34 ); this->nFiredEvent = 0; this->nFiredEvent_UnPS = 0; this->nFiredEvent_UnPS_Scaled2e34 = 0; this->nLumiBlock = 0; this->TotalRate = 0; this->TotalRate_UnPS = 0; this->TotalRate_UnPS_Scaled2e34 = 0; } }; class RateHistContainer { public: TString Tag; vector<TH1D*> vec_Hist; TH1D* h_TotalRate; TH1D* h_TotalRate_UnPS; TH1D* h_TotalRate_UnPS_Scaled2e34; Double_t nFiredEvent; Double_t nFiredEvent_UnPS; Double_t nFiredEvent_UnPS_Scaled2e34; Int_t nLumiBlock; Double_t TotalRate; Double_t TotalRate_UnPS; Double_t TotalRate_UnPS_Scaled2e34; vector<TH2D*> vec_2DHist; TH2D* h2D_Lumi_Rate; TH2D* h2D_Lumi_Rate_UnPS; TH2D* h2D_Lumi_Rate_UnPS_Scaled2e34; TH2D* h2D_nVertices_Rate; TH2D* h2D_nVertices_Rate_UnPS; TH2D* h2D_nVertices_Rate_UnPS_Scaled2e34; RateHistContainer( TString _Tag ) { this->Tag = _Tag; this->Init(); } void Fill( LumiBlockInfo *Info ) { this->nFiredEvent += Info->nFiredEvent; this->nFiredEvent_UnPS += Info->nFiredEvent_UnPS; this->nFiredEvent_UnPS_Scaled2e34 += Info->nFiredEvent_UnPS_Scaled2e34; this->nLumiBlock += 1; this->h2D_Lumi_Rate->Fill( Info->Mean_InstLumi, Info->Rate ); this->h2D_Lumi_Rate_UnPS->Fill( Info->Mean_InstLumi, Info->Rate_UnPS ); this->h2D_Lumi_Rate_UnPS_Scaled2e34->Fill( Info->Mean_InstLumi, Info->Rate_UnPS_Scaled2e34 ); this->h2D_nVertices_Rate->Fill( Info->Mean_nVertices, Info->Rate ); this->h2D_nVertices_Rate_UnPS->Fill( Info->Mean_nVertices, Info->Rate_UnPS ); this->h2D_nVertices_Rate_UnPS_Scaled2e34->Fill( Info->Mean_nVertices, Info->Rate_UnPS_Scaled2e34 ); } void Save( TFile *f_output ) { // -- fill histogram for total rate -- // if( this->nLumiBlock == 0 ) { this->TotalRate = 0; this->TotalRate_UnPS = 0; this->TotalRate_UnPS_Scaled2e34 = 0; } else { this->TotalRate = this->nFiredEvent / (this->nLumiBlock * LumiBlockTime); this->TotalRate_UnPS = this->nFiredEvent_UnPS / (this->nLumiBlock * LumiBlockTime); this->TotalRate_UnPS_Scaled2e34 = this->nFiredEvent_UnPS_Scaled2e34 / (this->nLumiBlock * LumiBlockTime); } this->h_TotalRate->SetBinContent(1, this->TotalRate); this->h_TotalRate->SetBinError(1, 0); this->h_TotalRate_UnPS->SetBinContent(1, this->TotalRate_UnPS); this->h_TotalRate_UnPS->SetBinError(1, 0); this->h_TotalRate_UnPS_Scaled2e34->SetBinContent(1, this->TotalRate_UnPS_Scaled2e34); this->h_TotalRate_UnPS_Scaled2e34->SetBinError(1, 0); f_output->cd(); for( const auto* h : this->vec_Hist ) h->Write(); for( const auto& h_2D : this->vec_2DHist ) h_2D->Write(); } private: void Init() { this->h_TotalRate = new TH1D("h_TotalRate_"+this->Tag, "", 1, 0, 1 ); this->vec_Hist.push_back( this->h_TotalRate ); this->h_TotalRate_UnPS = new TH1D("h_TotalRate_UnPS_"+this->Tag, "", 1, 0, 1 ); this->vec_Hist.push_back( this->h_TotalRate_UnPS ); this->h_TotalRate_UnPS_Scaled2e34 = new TH1D("h_TotalRate_UnPS_Scaled2e34_"+this->Tag, "", 1, 0, 1 ); this->vec_Hist.push_back( this->h_TotalRate_UnPS_Scaled2e34 ); this->h2D_Lumi_Rate = new TH2D("h2D_Lumi_Rate_"+this->Tag, "", 2000, 1000 ,20000, 200, 0, 200 ); this->vec_2DHist.push_back( this->h2D_Lumi_Rate ); this->h2D_Lumi_Rate_UnPS = new TH2D("h2D_Lumi_Rate_UnPS_"+this->Tag, "", 2000, 1000 ,20000, 200, 0, 200 ); this->vec_2DHist.push_back( this->h2D_Lumi_Rate_UnPS ); this->h2D_Lumi_Rate_UnPS_Scaled2e34 = new TH2D("h2D_Lumi_Rate_UnPS_Scaled2e34_"+this->Tag, "", 2000, 1000 ,20000, 200, 0, 200 ); this->vec_2DHist.push_back( this->h2D_Lumi_Rate_UnPS_Scaled2e34 ); this->h2D_nVertices_Rate = new TH2D("h2D_nVertices_Rate_"+this->Tag, "", 100, 0, 100, 100, 0, 100 ); this->vec_2DHist.push_back( this->h2D_nVertices_Rate ); this->h2D_nVertices_Rate_UnPS = new TH2D("h2D_nVertices_Rate_UnPS_"+this->Tag, "", 100, 0, 100, 100, 0, 100 ); this->vec_2DHist.push_back( this->h2D_nVertices_Rate_UnPS ); this->h2D_nVertices_Rate_UnPS_Scaled2e34 = new TH2D("h2D_nVertices_Rate_UnPS_Scaled2e34_"+this->Tag, "", 100, 0, 100, 100, 0, 100 ); this->vec_2DHist.push_back( this->h2D_nVertices_Rate_UnPS_Scaled2e34 ); this->nFiredEvent = 0; this->nFiredEvent_UnPS = 0; this->nFiredEvent_UnPS_Scaled2e34 = 0; this->nLumiBlock = 0; } }; class TriggerRateTool { public: vector<TString> vec_DataPath; vector<Int_t> vec_RunNumList; vector< RunHistContainer* > vec_RunHist; TString TriggerTag; // -- exact trigger expression -- // TString TriggerName; Bool_t debug; TFile *f_output; TriggerRateTool() { this->debug = kFALSE; this->TriggerTag = ""; this->TriggerName = ""; this->f_output = NULL; } void Set_DataList( vector<TString> _vec ) { this->vec_DataPath = _vec; } void Set_RunNumList( vector<Int_t> _vec ) { this->vec_RunNumList = _vec; // -- histogram for each run -- // cout << "Run list" << endl; Int_t nRun = (Int_t)this->vec_RunNumList.size(); for(Int_t i=0; i<nRun; i++) { Int_t RunNum = vec_RunNumList[i]; cout << RunNum << endl; TString Tag = TString::Format("Run%d", RunNum); RunHistContainer* Hist = new RunHistContainer( Tag ); this->vec_RunHist.push_back( Hist ); } } void Set_Trigger( TString _TriggerTag ) { this->TriggerTag = _TriggerTag; } void Set_Output( TFile *_f_output ) { this->f_output = _f_output; } void Analyze() { if( TriggerTag == "" || this->f_output == NULL || this->vec_DataPath.size() == 0 || this->vec_RunNumList.size() == 0 ) { cout << "Setup is not done accordingly!" << endl; return; } TChain *chain = new TChain("ntupler/ntuple"); for( const auto& DataPath : this->vec_DataPath ) { if( debug ) cout << DataPath << endl; chain->Add( DataPath ); } NtupleHandle *ntuple = new NtupleHandle( chain ); ntuple->TurnOffBranches_All(); // ntuple->TurnOnBranches_GenParticle(); ntuple->TurnOnBranches_Event(); ntuple->TurnOnBranches_HLT(); // ntuple->TurnOnBranches_Muon(); // ntuple->TurnOnBranches_HLTRerunObject(); // -- initialize RunInfo -- // vector< RunInfo* > vec_RunInfo; Int_t nRun = (Int_t)this->vec_RunNumList.size(); for(Int_t i=0; i<nRun; i++) { RunInfo* Info = new RunInfo( vec_RunNumList[i] ); vec_RunInfo.push_back( Info ); } RateHistContainer* RateHist = new RateHistContainer( TriggerTag ); Bool_t Flag_IsMC = kFALSE; Int_t nEvent = chain->GetEntries(); std::cout << "[Total event: " << nEvent << "]" << std::endl; // nEvent = 1000; for(Int_t i_ev=0; i_ev<nEvent; i_ev++) { loadBar(i_ev+1, nEvent, 100, 100); // if( debug ) cout << "1" << endl; ntuple->GetEvent( i_ev ); if( debug ) printf("[%d event]\n", i_ev); KPEvent event( ntuple, Flag_IsMC ); if( debug ) printf("(run, lumi, event) = (%d, %d, %llu)\n", event.RunNum, event.LumiBlockNum, event.EventNum ); for(Int_t i=0; i<nRun; i++) { if( this->vec_RunNumList[i] == event.RunNum ) { if( debug ) cout << "Find corresponding run number: " << this->vec_RunNumList[i] << endl; vec_RunInfo[i]->Fill( event, TriggerTag ); break; } } if( debug ) cout << endl; } // -- end of event iteration -- // // -- fill histograms -- // for(Int_t i=0; i<nRun; i++) { vec_RunInfo[i]->CalcRate_EachLumiBlock(); for( auto& LumiBlockInfo : vec_RunInfo[i]->vec_LumiBlockInfo ) { // -- only for meaningful lumi-block -- // if( LumiBlockInfo->nEvent > 0 ) { if( debug ) printf("[Run=%d, LumiBlock=%d] (nEvent, nFiredEvent, Rate, Rate_UnPS, Rate_UnPS_Scaled2e34) = (%.1lf, %.1lf, %lf, %lf, %lf)\n", vec_RunInfo[i]->RunNum, LumiBlockInfo->LumiBlockNum, LumiBlockInfo->nEvent, LumiBlockInfo->nFiredEvent, LumiBlockInfo->Rate, LumiBlockInfo->Rate_UnPS, LumiBlockInfo->Rate_UnPS_Scaled2e34); // -- fill histogram for each run -- // vec_RunHist[i]->Fill( LumiBlockInfo ); // -- fill histogram accumulated for all runs -- // RateHist->Fill( LumiBlockInfo ); } } // -- iteration over all lumi-block in a run -- // } // -- iteration over all runs -- // this->f_output->cd(); RateHist->Save( f_output ); for(const auto& RunHist : vec_RunHist ) RunHist->Save( f_output ); // -- total run rates are calculated after save! -- // for( const auto& RunHist : vec_RunHist ) { Double_t RunRate = RunHist->TotalRate; Double_t RunRate_UnPS = RunHist->TotalRate_UnPS; Double_t RunRate_UnPS_Scaled2e34 = RunHist->TotalRate_UnPS_Scaled2e34; printf("[%s] (# fired events, run rate, un-prescaled run rate, un-prescaled run rate scaled w.r.t 2e34) = (%.1lf, %lf, %lf, %lf)\n", RunHist->Tag.Data(), RunHist->nFiredEvent, RunRate, RunRate_UnPS, RunRate_UnPS_Scaled2e34); } Double_t TotalRate = RateHist->TotalRate; Double_t TotalRate_UnPS = RateHist->TotalRate_UnPS; Double_t TotalRate_UnPS_Scaled2e34 = RateHist->TotalRate_UnPS_Scaled2e34; printf("[Total] (# fired events, rate, un-prescaled rate, un-prescaled rate scaled w.r.t 2e34) = (%.1lf, %lf, %lf, %lf)\n", RateHist->nFiredEvent, TotalRate, TotalRate_UnPS, TotalRate_UnPS_Scaled2e34); cout << "finished" << endl; } private: void Init() { } static inline void loadBar(int x, int n, int r, int w) { // Only update r times. if( x == n ) cout << endl; if ( x % (n/r +1) != 0 ) return; // Calculuate the ratio of complete-to-incomplete. float ratio = x/(float)n; int c = ratio * w; // Show the percentage complete. printf("%3d%% [", (int)(ratio*100) ); // Show the load bar. for (int x=0; x<c; x++) cout << "="; for (int x=c; x<w; x++) cout << " "; // ANSI Control codes to go back to the // previous line and clear it. cout << "]\r" << flush; } };
[ "kplee@cern.ch" ]
kplee@cern.ch
52b2e457bf41e52de36e824ca191cf77d1ab0237
427d18c0872465394931829982860d0948383c9c
/pgadmin/frm/frmMainConfig.cpp
d11656c0edf471ec4663781776058dc611cc8c0d
[ "PostgreSQL" ]
permissive
jcjc79/pgadmin3
6e4b68b051ce86c831dd8e4dd320755fe12d230e
be0f94786bf5b8138c9e6ec1b0b295308f8f89b6
refs/heads/master
2021-10-22T23:00:01.924934
2019-03-13T10:51:22
2019-03-13T10:51:22
273,088,849
0
1
NOASSERTION
2020-06-17T22:15:54
2020-06-17T22:15:54
null
UTF-8
C++
false
false
17,421
cpp
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // // Copyright (C) 2002 - 2013, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // frmMainConfig.cpp - Backend configuration tool // ////////////////////////////////////////////////////////////////////////// #include "pgAdmin3.h" #ifdef __WXMSW__ #include <io.h> #include <fcntl.h> #endif #include <wx/imaglist.h> #include "ctl/ctlMenuToolbar.h" #include "frm/frmMainConfig.h" #include "frm/frmMain.h" #include "dlg/dlgMainConfig.h" #include "utils/utffile.h" #include "schema/pgServer.h" #include "frm/menu.h" #include "utils/pgfeatures.h" #include <wx/arrimpl.cpp> WX_DEFINE_OBJARRAY(pgConfigOrgLineArray); #define CTL_CFGVIEW 345 BEGIN_EVENT_TABLE(frmMainConfig, frmConfig) EVT_MENU(MNU_UNDO, frmMainConfig::OnUndo) EVT_MENU(MNU_CONTENTS, frmMainConfig::OnContents) EVT_LIST_ITEM_ACTIVATED(CTL_CFGVIEW, frmMainConfig::OnEditSetting) EVT_LIST_ITEM_SELECTED(CTL_CFGVIEW, frmMainConfig::OnSelectSetting) END_EVENT_TABLE() #define BCE_TITLE _("Backend Configuration Editor") frmMainConfig::frmMainConfig(frmMain *parent, pgServer *server) : frmConfig(parent, BCE_TITLE, 0) { wxString applicationname = appearanceFactory->GetLongAppName() + _(" - Configuration Editor"); if (server) conn = server->CreateConn(wxEmptyString, 0, applicationname); InitForm(); Init(); if (conn) { if (serverFileName.IsEmpty()) serverFileName = wxT("postgresql.conf"); wxString txt; txt.Printf(_(" - %s on %s (%s:%d)"), serverFileName.c_str(), server->GetDescription().c_str(), server->GetName().c_str(), server->GetPort()); SetTitle(BCE_TITLE + txt); wxString str; str = conn->ExecuteScalar(wxT("SELECT pg_file_read('") + serverFileName + wxT("', 0, ") wxT("pg_file_length('") + serverFileName + wxT("'))")); DisplayFile(str); statusBar->SetStatusText(wxString::Format(_(" Configuration read from %s"), conn->GetHost().c_str())); } } frmMainConfig::frmMainConfig(const wxString &title, const wxString &configFile) : frmConfig(title + wxT(" - ") + _("Backend Configuration Editor"), configFile) { InitForm(); Init(); OpenLastFile(); } frmMainConfig::~frmMainConfig() { options.clear(); categories.clear(); lines.Clear(); } void frmMainConfig::Init(pgSettingReader *reader) { pgSettingItem *item; do { item = reader->GetNextItem(); if (item) { if (item->context == pgSettingItem::PGC_INTERNAL) delete item; else { if (options[item->name]) delete item; else { options[item->name] = item; wxArrayString *category = categories[item->category]; if (!category) { category = new wxArrayString; categories[item->category] = category; } category->Add(item->name); } } } } while (item); editMenu->Enable(MNU_DELETE, false); toolBar->EnableTool(MNU_DELETE, false); } void frmMainConfig::Init() { // Cleanup first, in case we're re-initing options.clear(); categories.clear(); lines.Clear(); pgSettingReader *reader; if (conn) { // read settings from server reader = new pgSettingDbReader(conn); } else { // read settings from file. First, use localized file... reader = new pgSettingFileReader(true); if (reader->IsValid()) Init(reader); delete reader; // ... then add default file reader = new pgSettingFileReader(false); } if (reader->IsValid()) Init(reader); delete reader; } void frmMainConfig::InitForm() { appearanceFactory->SetIcons(this); InitFrame(wxT("frmMainConfig")); RestorePosition(50, 50, 600, 600, 300, 200); cfgList = new ctlListView(this, CTL_CFGVIEW, wxDefaultPosition, wxDefaultSize, wxSIMPLE_BORDER); cfgList->SetImageList(configImageList, wxIMAGE_LIST_SMALL); cfgList->AddColumn(_("Setting name"), 120); cfgList->AddColumn(_("Value"), 80); if (conn) cfgList->AddColumn(_("Current value"), 80); cfgList->AddColumn(_("Comment"), 400); } void frmMainConfig::OnSelectSetting(wxListEvent &event) { // Disable undo because we don't want to undo the wrong line. editMenu->Enable(MNU_UNDO, false); toolBar->EnableTool(MNU_UNDO, false); } void frmMainConfig::OnEditSetting(wxListEvent &event) { wxString name = cfgList->GetText(event.GetIndex()); if (!name.IsEmpty()) { pgSettingItem *item = options[name]; wxASSERT(item); dlgMainConfig dlg(this, item); dlg.Go(); if (item->orgLine && !item->newLine->Differs(item->orgLine)) { delete item->newLine; item->newLine = 0; } else { changed = true; fileMenu->Enable(MNU_SAVE, true); editMenu->Enable(MNU_UNDO, true); toolBar->EnableTool(MNU_SAVE, true); toolBar->EnableTool(MNU_UNDO, true); } UpdateLine(event.GetIndex()); } } void frmMainConfig::OnContents(wxCommandEvent &event) { DisplayHelp(wxT("index"), HELP_PGADMIN); } wxString frmMainConfig::GetHelpPage() const { wxString page; if (page.IsEmpty()) page = wxT("runtime-config"); return page; } void frmMainConfig::OnUndo(wxCommandEvent &ev) { wxString name = cfgList->GetText(cfgList->GetSelection()); if (!name.IsEmpty()) { pgSettingItem *item = options[name]; if (item->newLine) { delete item->newLine; item->newLine = 0; UpdateLine(cfgList->GetSelection()); } } } void frmMainConfig::UpdateLine(int pos) { wxString name = cfgList->GetText(pos); if (!name.IsEmpty()) { pgSettingItem *item = options[name]; pgConfigLine *line = item->newLine; if (!line) line = item->orgLine; wxString value, comment; int imgIndex = 0; if (line) { value = line->value; comment = line->comment; if (!line->isComment) imgIndex = 1; } cfgList->SetItem(pos, 1, value); if (conn) cfgList->SetItem(pos, 3, comment); else cfgList->SetItem(pos, 2, comment); cfgList->SetItemImage(pos, imgIndex, imgIndex); } } void frmMainConfig::WriteFile(pgConn *conn) { size_t i; wxString str; for (i = 0 ; i < lines.GetCount() ; i++) str.Append(lines.Item(i).GetNewText() + wxT("\n")); for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++) { pgSettingItem *item = options[cfgList->GetText(i)]; if (item && item->newLine && item->newLine->item && !item->orgLine) str.Append(item->newLine->GetNewText() + wxT("\n")); } if (DoWriteFile(str, conn)) { changed = false; fileMenu->Enable(MNU_SAVE, false); editMenu->Enable(MNU_UNDO, false); toolBar->EnableTool(MNU_SAVE, false); toolBar->EnableTool(MNU_UNDO, false); size_t i; for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++) { pgSettingItem *item = options[cfgList->GetText(i)]; if (item && item->newLine) { if (!item->orgLine) { item->orgLine = new pgConfigOrgLine(item->newLine); lines.Add(item->orgLine); item->orgLine->item = item; } else { item->orgLine->comment = item->newLine->comment; item->orgLine->isComment = item->newLine->isComment; item->orgLine->value = item->newLine->value; item->orgLine->text = item->orgLine->GetNewText(); } } } for (i = 0 ; i < lines.GetCount() ; i++) { pgConfigOrgLine &line = lines.Item(i); if (line.item && line.item->newLine) { line.text = line.GetNewText(); delete line.item->newLine; line.item->newLine = 0; } } } } void frmMainConfig::DisplayFile(const wxString &str) { Init(); filetype = wxTextFileType_Unix; wxStringTokenizer strtok; wxArrayString *unknownCategory = 0; if (str.Find('\r') >= 0) { if (str.Find(wxT("\n\r")) >= 0 || str.Find(wxT("\r\n"))) filetype = wxTextFileType_Dos; else filetype = wxTextFileType_Mac; strtok.SetString(wxTextBuffer::Translate(str, wxTextFileType_Unix), wxT("\n"), wxTOKEN_RET_EMPTY); } else strtok.SetString(str, wxT("\n"), wxTOKEN_RET_EMPTY); while (strtok.HasMoreTokens()) { pgConfigOrgLine *line = new pgConfigOrgLine(strtok.GetNextToken()); lines.Add(line); // identify option bool isComment = false; const wxChar *p = line->text.c_str(); // identify keywords while (*p && wxStrchr(wxT("# \n"), *p)) { if (*p == '#') isComment = true; p++; } if (!*p) isComment = true; line->isComment = isComment; const wxChar *p2 = p; while (*p2 && *p2 != '#' && *p2 != ' ' && *p2 != '\t' && *p2 != '=') p2++; if (p2 != p) { wxString keyword = line->text.Mid(p - line->text.c_str(), p2 - p); pgSettingItemHashmap::iterator it = options.find(keyword); pgSettingItem *item; if (it == options.end()) { if (isComment) continue; item = new pgSettingItem; item->name = keyword; item->category = _("Unknown"); item->short_desc = _("Unknown option"); item->extra_desc = _("This option is present in the configuration file, but not known to the configuration tool."); item->SetType(wxT("string")); options[item->name] = item; if (!unknownCategory) { unknownCategory = new wxArrayString; categories[item->category] = unknownCategory; } unknownCategory->Add(item->name); } else item = it->second; if (!isComment || !item->orgLine || item->orgLine->isComment) { line->item = item; if (item->orgLine) item->orgLine->item = 0; item->orgLine = line; } while (*p2 && *p2 != '=') p2++; p2++; // skip = while (*p2 && wxStrchr(wxT(" \t"), *p2)) p2++; wxChar quoteChar = 0; if (wxStrchr(wxT("'\""), *p2)) quoteChar = *p2++; const wxChar *p3 = p2; while (*p3) { if (*p3 == quoteChar || (!quoteChar && wxStrchr(wxT(" \t#"), *p3))) break; p3++; } if (p2 != p3) { line->value = line->text.Mid(p2 - line->text.c_str(), p3 - p2); if (quoteChar) p3++; const wxChar *p4 = p3; while (*p4 && wxStrchr(wxT(" \t#"), *p4)) p4++; line->commentIndent = line->text.Mid(p3 - line->text.c_str(), p4 - p3); line->comment = p4; } } } cfgList->DeleteAllItems(); // we want to show options ordered by category/name // category might be localized, and we want a distinct category ordering FillList(wxT("listen_addresses")); // Connections and Authentication / Connection Settings FillList(wxT("authentication_timeout")); // Connections and Authentication / Security and Authentication FillList(wxT("check_function_bodies")); // Client Connection Defaults / Statement Behaviour FillList(wxT("lc_messages")); // Client Connection Defaults / Locale and Formatting FillList(wxT("explain_pretty_print")); // Client Connection Defaults / Other Defaults FillList(wxT("enable_hashjoin")); // Query Tuning / Planner Method Configuration FillList(wxT("cpu_operator_cost")); // Query Tuning / Planner Cost Constants if (!conn || !conn->GetIsGreenplum()) // Greenplum doesn't have the Genetic Query Optimizer FillList(wxT("geqo")); // Query Tuning / Genetic Query Optimizer FillList(wxT("default_statistics_target")); // Query Tuning / Other Planner Options FillList(wxT("deadlock_timeout")); // Lock Management FillList(wxT("shared_buffers")); // Resource Usage / Memory FillList(wxT("max_fsm_pages")); // Resource Usage / Free Space Map FillList(wxT("bgwriter_delay")); // Resource Usage FillList(wxT("max_files_per_process")); // Resource Usage / Kernel Resources FillList(wxT("log_connections")); // Reporting and Logging / What to Log FillList(wxT("client_min_messages")); // Reporting and Logging / When to Log FillList(wxT("log_destination")); // Reporting and Logging / Where to Log FillList(wxT("stats_command_string"), wxT("track_activities")); // Statistics / Query and Index Statistics Collector FillList(wxT("log_executor_stats")); // Statistics / Monitoring FillList(wxT("fsync")); // Write-Ahead Log / Settings FillList(wxT("checkpoint_segments")); // Write-Ahead Log / Checkpoints FillList(wxT("add_missing_from")); // Version and Platform Compatibility / Previous PostgreSQL Version FillList(wxT("transform_null_equals")); // Version and Platform Compatibility / Other Platforms and Clients if (!conn || !conn->GetIsGreenplum()) // Greenplum doesn't have trace_notify visible FillList(wxT("trace_notify")); // Developer Options FillList(wxT("hba_file")); // Ungrouped // for all we didn't get while (!categories.empty()) { pgCategoryHashmap::iterator it = categories.begin(); wxString missed = it->first; FillList(it->second); categories.erase(it); } } void frmMainConfig::FillList(const wxString &categoryMember, const wxString &altCategoryMember) { pgSettingItem *categoryItem = options[categoryMember]; if (!categoryItem && !altCategoryMember.IsEmpty()) categoryItem = options[altCategoryMember]; wxASSERT_MSG(categoryItem, wxString::Format(wxT("%s/%s"), categoryMember.c_str(), altCategoryMember.c_str())); if (categoryItem) { FillList(categories[categoryItem->category]); categories.erase(categoryItem->category); } } void frmMainConfig::FillList(wxArrayString *category) { if (category) { size_t i; for (i = 0 ; i < category->GetCount() ; i++) { pgSettingItem *item = options[category->Item(i)]; wxASSERT(item); wxString value; wxString comment; int imgIndex = 0; if (item->orgLine) { if (!item->orgLine->isComment) imgIndex = 1; value = item->orgLine->value; comment = item->orgLine->comment; comment.Replace(wxT("\t"), wxT(" ")); } long pos = cfgList->AppendItem(imgIndex, item->name, value); if (conn) { cfgList->SetItem(pos, 2, item->value); cfgList->SetItem(pos, 3, comment); } else cfgList->SetItem(pos, 2, comment); } delete category; } } enum { HINT_LISTEN_ADDRESSES, HINT_AUTOVACUUM_CFG }; const wxChar *hintString[] = { _("The PostgreSQL server engine is currently configured to listen for local connections only.\nYou might want to check \"listen_addresses\" to enable accessing the server over the network too."), _("The autovacuum backend process is not running.\nIt is recommended to enable it by setting 'track_counts' and 'autovacuum' to 'on' in PostgreSQL 8.3 and above or 'stats_start_collector', 'stats_row_level' and 'autovacuum' to 'on' in earlier versions.") }; wxString frmMainConfig::GetHintString() { wxArrayInt hints; size_t i; int autovacuum = 0; bool autovacuumPresent = false; for (i = 0 ; i < (size_t)cfgList->GetItemCount() ; i++) { pgSettingItem *item = options[cfgList->GetText(i)]; if (item) { wxString name = item->name; wxString value = item->GetActiveValue(); if (name == wxT("listen_addresses")) { if (value.IsEmpty() || value == wxT("localhost")) hints.Add(HINT_LISTEN_ADDRESSES); } else if (name == wxT("autovacuum")) { autovacuumPresent = true; if (StrToBool(value)) autovacuum++; } else if (name == wxT("stats_start_collector") || name == wxT("stats_row_level")) { if (StrToBool(value)) autovacuum++; } else if (name == wxT("track_counts")) { // Double increment, because track_counts in 8.3 is worth both previous options. if (StrToBool(value)) autovacuum = autovacuum + 2; } } } if (autovacuumPresent && autovacuum < 3) hints.Add(HINT_AUTOVACUUM_CFG); wxString str; for (i = 0 ; i < hints.GetCount() ; i++) { if (i) str.Append(wxT("\n\n")); str.Append(hintString[hints.Item(i)]); } return str; } void frmMainConfig::OnOpen(wxCommandEvent &event) { if (CheckChanged(true)) return; #ifdef __WXMSW__ wxFileDialog dlg(this, _("Open configuration file"), lastDir, wxT(""), _("Configuration files (*.conf)|*.conf|All files (*.*)|*.*"), wxFD_OPEN); #else wxFileDialog dlg(this, _("Open configuration file"), lastDir, wxT(""), _("Configuration files (*.conf)|*.conf|All files (*)|*"), wxFD_OPEN); #endif if (dlg.ShowModal() == wxID_OK) { Init(); lastFilename = dlg.GetFilename(); lastDir = dlg.GetDirectory(); lastPath = dlg.GetPath(); OpenLastFile(); UpdateRecentFiles(); } } mainConfigFactory::mainConfigFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : actionFactory(list) { mnu->Append(id, wxT("postgresql.conf"), _("Edit general server configuration file.")); } wxWindow *mainConfigFactory::StartDialog(frmMain *form, pgObject *obj) { pgServer *server = obj->GetServer(); if (server) { frmConfig *frm = new frmMainConfig(form, server); frm->Go(); return frm; } return 0; } bool mainConfigFactory::CheckEnable(pgObject *obj) { if (obj) { pgServer *server = obj->GetServer(); if (server) { pgConn *conn = server->GetConnection(); return conn && server->GetSuperUser() && conn->HasFeature(FEATURE_FILEREAD); } } return false; } mainConfigFileFactory::mainConfigFileFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : actionFactory(list) { mnu->Append(id, _("Open postgresql.conf..."), _("Open configuration editor with postgresql.conf.")); } wxWindow *mainConfigFileFactory::StartDialog(frmMain *form, pgObject *obj) { frmConfig *dlg = new frmMainConfig(form); dlg->Go(); dlg->DoOpen(); return dlg; }
[ "miaochen@mail.ustc.edu.cn" ]
miaochen@mail.ustc.edu.cn
52053d28a55b03d86af010b175b476ea57dfeaf9
9b4f4ad42b82800c65f12ae507d2eece02935ff6
/src/IO/BTScannerWin.cpp
a2168b4cb0ec037a8d5e6680dee7118fbf724e02
[]
no_license
github188/SClass
f5ef01247a8bcf98d64c54ee383cad901adf9630
ca1b7efa6181f78d6f01a6129c81f0a9dd80770b
refs/heads/main
2023-07-03T01:25:53.067293
2021-08-06T18:19:22
2021-08-06T18:19:22
393,572,232
0
1
null
2021-08-07T03:57:17
2021-08-07T03:57:16
null
UTF-8
C++
false
false
226
cpp
#include "Stdafx.h" #include "IO/BTScanner.h" #include "Win32/WindowsBTScanner.h" IO::BTScanner *IO::BTScanner::CreateScanner() { Win32::WindowsBTScanner *bt; NEW_CLASS(bt, Win32::WindowsBTScanner()); return bt; }
[ "simon.wong@stone-road.net" ]
simon.wong@stone-road.net
76b85d239b798f91a19f8399a98c34f210716212
522531191916a26a82c7fdafe09374657bc93c13
/tests/core_tests/block_reward.cpp
58a14be261858a35573436437f08dd2ab1275d64
[]
no_license
tedchain/tedcoin-secure
3f312c3a86164d0957c28776b90a4122610cda4c
d6850d0b6d32b4e0d8ae50f7246e717e47290478
refs/heads/master
2020-03-18T03:15:04.883715
2018-07-15T13:36:41
2018-07-15T13:36:41
134,230,503
5
5
null
null
null
null
UTF-8
C++
false
false
9,043
cpp
#include "chaingen.h" #include "chaingen_tests_list.h" #include "block_reward.h" using namespace epee; using namespace cryptonote; namespace { bool construct_miner_tx_by_size(transaction& miner_tx, uint64_t height, uint64_t already_generated_coins, const account_public_address& miner_address, std::vector<size_t>& block_sizes, size_t target_tx_size, size_t target_block_size, uint64_t fee = 0) { if (!construct_miner_tx(height, misc_utils::median(block_sizes), already_generated_coins, target_block_size, fee, miner_address, miner_tx)) return false; size_t current_size = get_object_blobsize(miner_tx); size_t try_count = 0; while (target_tx_size != current_size) { ++try_count; if (10 < try_count) return false; if (target_tx_size < current_size) { size_t diff = current_size - target_tx_size; if (diff <= miner_tx.extra.size()) miner_tx.extra.resize(miner_tx.extra.size() - diff); else return false; } else { size_t diff = target_tx_size - current_size; miner_tx.extra.resize(miner_tx.extra.size() + diff); } current_size = get_object_blobsize(miner_tx); } return true; } bool construct_max_size_block(test_generator& generator, block& blk, const block& blk_prev, const account_base& miner_account, size_t median_block_count = CRYPTONOTE_REWARD_BLOCKS_WINDOW) { std::vector<size_t> block_sizes; generator.get_last_n_block_sizes(block_sizes, get_block_hash(blk_prev), median_block_count); size_t median = misc_utils::median(block_sizes); median = std::max(median, static_cast<size_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE)); transaction miner_tx; bool r = construct_miner_tx_by_size(miner_tx, get_block_height(blk_prev) + 1, generator.get_already_generated_coins(blk_prev), miner_account.get_keys().m_account_address, block_sizes, 2 * median, 2 * median); if (!r) return false; return generator.construct_block_manually(blk, blk_prev, miner_account, test_generator::bf_miner_tx, 0, 0, 0, crypto::hash(), 0, miner_tx); } bool rewind_blocks(std::vector<test_event_entry>& events, test_generator& generator, block& blk, const block& blk_prev, const account_base& miner_account, size_t block_count) { blk = blk_prev; for (size_t i = 0; i < block_count; ++i) { block blk_i; if (!construct_max_size_block(generator, blk_i, blk, miner_account)) return false; events.push_back(blk_i); blk = blk_i; } return true; } uint64_t get_tx_out_amount(const transaction& tx) { uint64_t amount = 0; BOOST_FOREACH(auto& o, tx.vout) amount += o.amount; return amount; } } gen_block_reward::gen_block_reward() : m_invalid_block_index(0) { REGISTER_CALLBACK_METHOD(gen_block_reward, mark_invalid_block); REGISTER_CALLBACK_METHOD(gen_block_reward, mark_checked_block); REGISTER_CALLBACK_METHOD(gen_block_reward, check_block_rewards); } bool gen_block_reward::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); DO_CALLBACK(events, "mark_checked_block"); MAKE_ACCOUNT(events, bob_account); // Test: miner transactions without outputs (block reward == 0) block blk_0r; if (!rewind_blocks(events, generator, blk_0r, blk_0, miner_account, CRYPTONOTE_REWARD_BLOCKS_WINDOW)) return false; // Test: block reward is calculated using median of the latest CRYPTONOTE_REWARD_BLOCKS_WINDOW blocks DO_CALLBACK(events, "mark_invalid_block"); block blk_1_bad_1; if (!construct_max_size_block(generator, blk_1_bad_1, blk_0r, miner_account, CRYPTONOTE_REWARD_BLOCKS_WINDOW + 1)) return false; events.push_back(blk_1_bad_1); DO_CALLBACK(events, "mark_invalid_block"); block blk_1_bad_2; if (!construct_max_size_block(generator, blk_1_bad_2, blk_0r, miner_account, CRYPTONOTE_REWARD_BLOCKS_WINDOW - 1)) return false; events.push_back(blk_1_bad_2); block blk_1; if (!construct_max_size_block(generator, blk_1, blk_0r, miner_account)) return false; events.push_back(blk_1); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MAKE_NEXT_BLOCK(events, blk_2, blk_1, miner_account); DO_CALLBACK(events, "mark_checked_block"); MAKE_NEXT_BLOCK(events, blk_3, blk_2, miner_account); DO_CALLBACK(events, "mark_checked_block"); MAKE_NEXT_BLOCK(events, blk_4, blk_3, miner_account); DO_CALLBACK(events, "mark_checked_block"); MAKE_NEXT_BLOCK(events, blk_5, blk_4, miner_account); DO_CALLBACK(events, "mark_checked_block"); block blk_5r; if (!rewind_blocks(events, generator, blk_5r, blk_5, miner_account, CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW)) return false; // Test: fee increases block reward transaction tx_0(construct_tx_with_fee(events, blk_5, miner_account, bob_account, MK_COINS(1), 3 * TESTS_DEFAULT_FEE)); MAKE_NEXT_BLOCK_TX1(events, blk_6, blk_5r, miner_account, tx_0); DO_CALLBACK(events, "mark_checked_block"); // Test: fee from all block transactions increase block reward std::list<transaction> txs_0; txs_0.push_back(construct_tx_with_fee(events, blk_5, miner_account, bob_account, MK_COINS(1), 5 * TESTS_DEFAULT_FEE)); txs_0.push_back(construct_tx_with_fee(events, blk_5, miner_account, bob_account, MK_COINS(1), 7 * TESTS_DEFAULT_FEE)); MAKE_NEXT_BLOCK_TX_LIST(events, blk_7, blk_6, miner_account, txs_0); DO_CALLBACK(events, "mark_checked_block"); // Test: block reward == transactions fee { transaction tx_1 = construct_tx_with_fee(events, blk_5, miner_account, bob_account, MK_COINS(1), 11 * TESTS_DEFAULT_FEE); transaction tx_2 = construct_tx_with_fee(events, blk_5, miner_account, bob_account, MK_COINS(1), 13 * TESTS_DEFAULT_FEE); size_t txs_1_size = get_object_blobsize(tx_1) + get_object_blobsize(tx_2); uint64_t txs_fee = get_tx_fee(tx_1) + get_tx_fee(tx_2); std::vector<size_t> block_sizes; generator.get_last_n_block_sizes(block_sizes, get_block_hash(blk_7), CRYPTONOTE_REWARD_BLOCKS_WINDOW); size_t median = misc_utils::median(block_sizes); transaction miner_tx; bool r = construct_miner_tx_by_size(miner_tx, get_block_height(blk_7) + 1, generator.get_already_generated_coins(blk_7), miner_account.get_keys().m_account_address, block_sizes, 2 * median - txs_1_size, 2 * median, txs_fee); if (!r) return false; std::vector<crypto::hash> txs_1_hashes; txs_1_hashes.push_back(get_transaction_hash(tx_1)); txs_1_hashes.push_back(get_transaction_hash(tx_2)); block blk_8; generator.construct_block_manually(blk_8, blk_7, miner_account, test_generator::bf_miner_tx | test_generator::bf_tx_hashes, 0, 0, 0, crypto::hash(), 0, miner_tx, txs_1_hashes, txs_1_size); events.push_back(blk_8); DO_CALLBACK(events, "mark_checked_block"); } DO_CALLBACK(events, "check_block_rewards"); return true; } bool gen_block_reward::check_block_verification_context(const cryptonote::block_verification_context& bvc, size_t event_idx, const cryptonote::block& /*blk*/) { if (m_invalid_block_index == event_idx) { m_invalid_block_index = 0; return bvc.m_verifivation_failed; } else { return !bvc.m_verifivation_failed; } } bool gen_block_reward::mark_invalid_block(cryptonote::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_invalid_block_index = ev_index + 1; return true; } bool gen_block_reward::mark_checked_block(cryptonote::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_checked_blocks_indices.push_back(ev_index - 1); return true; } bool gen_block_reward::check_block_rewards(cryptonote::core& /*c*/, size_t /*ev_index*/, const std::vector<test_event_entry>& events) { DEFINE_TESTS_ERROR_CONTEXT("gen_block_reward_without_txs::check_block_rewards"); std::array<uint64_t, 7> blk_rewards; blk_rewards[0] = MONEY_SUPPLY >> 18; uint64_t cumulative_reward = blk_rewards[0]; for (size_t i = 1; i < blk_rewards.size(); ++i) { blk_rewards[i] = (MONEY_SUPPLY - cumulative_reward) >> 18; cumulative_reward += blk_rewards[i]; } for (size_t i = 0; i < 5; ++i) { block blk_i = boost::get<block>(events[m_checked_blocks_indices[i]]); CHECK_EQ(blk_rewards[i], get_tx_out_amount(blk_i.miner_tx)); } block blk_n1 = boost::get<block>(events[m_checked_blocks_indices[5]]); CHECK_EQ(blk_rewards[5] + 3 * TESTS_DEFAULT_FEE, get_tx_out_amount(blk_n1.miner_tx)); block blk_n2 = boost::get<block>(events[m_checked_blocks_indices[6]]); CHECK_EQ(blk_rewards[6] + (5 + 7) * TESTS_DEFAULT_FEE, get_tx_out_amount(blk_n2.miner_tx)); block blk_n3 = boost::get<block>(events[m_checked_blocks_indices[7]]); CHECK_EQ((11 + 13) * TESTS_DEFAULT_FEE, get_tx_out_amount(blk_n3.miner_tx)); return true; }
[ "development@daybreak.coffee" ]
development@daybreak.coffee
f5c0b5f415170aab3e029e2d16c44b1e75482911
45aa26d42dafe3609dbb463b7d81941106a9bc07
/pc_app/qt_tftp/socketmonitor.h
3e11e647a0ee4ae67f0e8235a1abcf22c0b38437
[]
no_license
vijayandra/logger_v1
3d0e0fb20d96cdb57130b18d1050fe85f08c6793
663a86bb6e1485149aabd489278ad7774ee74bea
refs/heads/master
2020-06-13T04:40:03.659358
2017-01-25T02:41:18
2017-01-25T02:41:18
75,447,181
0
0
null
null
null
null
UTF-8
C++
false
false
2,500
h
/* Monitor de datos en el socket. Equivalente a select() y las macros relacionadas. */ #ifndef SOCKETMONITOR_H #define SOCKETMONITOR_H #include <QDebug> #include <set> #include <time.h> #include <sys/select.h> #include <string.h> #include <errno.h> #include "socket.h" typedef std::set<Socket *, SockComp> sockset; // Definiendo el tipo de conjunto de sockets. enum fdSet {READ, WRITE, EXCEPTION}; // Conjuntos a los que se pueden agregar sockets class SocketMonitor { private: int max_fd; // Valor más alto de alguno de los descriptores de archivo. fd_set readfds; // Conjunto de descriptores a leer. fd_set writefds; // Conjunto de descriptores a escribir. fd_set exceptfds; // Conjunto de descriptores a de excepción. struct timeval * utimeout; // Estructura para timeout (select()). // Instancias para la gestión a más alto nivel. sockset readSet; // Conjunto de sockets para lectura. sockset writeSet; // Conjunto de sockets para escritura. sockset exceptSet; // Conjunto de sockets exepción. (errores). sockset::const_iterator it; // Iterador sobre los conjuntos de sockets. public: SocketMonitor(); void clearFrom(Socket & s, fdSet set); // Remueve el socket especificado del conjunto dado. bool isSet(Socket & s, fdSet set); // Verifica si un socket ha tenido cambios. void set(Socket & s, fdSet set); // Asigna un socket al conjunto. void zeroSet(fdSet set); // Inicializa el conjunto a cero. El constructor por // defecto inicializa todos los conjuntos. // int select(sockset & readSocks, // Llena el los conjuntos de sockets, con los // sockset & writeSocks, // sockets disponibles para las respectivas // sockset & excepSocks, // operaciones. // struct timeval * timeout = NULL); int select(struct timeval * timeout = NULL); // Hace la operación de select sobre los descriptores // que previamente se añadieron con set(). void setTimeout(struct timeval * timeout); // Asigna el timeout para la operación select. private: void getMaxFd(); // Actualiza max_fd, tras haberse elminiado el socket // de valor más alto. void init_sets(); // Inicializa los conjuntos de descriptores tras cada // llamada a select(). }; #endif // SOCKETMONITOR_H
[ "vsingh.usa@gmail.com" ]
vsingh.usa@gmail.com
d62ff99affccb0435109dbf854090cde9c4c3e53
f7c91de664c982a5b3f7c3dc6462e79bd3e6e080
/Inheritance/48.cpp
6eefa3d35097685d5967d7edfb8e60e2696f23ac
[]
no_license
Abhisht23/basic.cpp
d50868b01c42fdacf09ed3f687a2ba0f82c66be1
0e0798d3f11fe0fd06c20bf3ba47a72dd61e6a6c
refs/heads/main
2023-03-15T20:25:38.372988
2021-03-09T18:01:44
2021-03-09T18:01:44
332,486,152
0
0
null
null
null
null
UTF-8
C++
false
false
392
cpp
#include<iostream> using namespace std; class Base { public: void fun1() { cout<<"fun1 of Base "<<endl; } }; class Derived: public Base { public: void fun2() { cout<<"fun2 of Derived"<<endl; } }; int main() { Derived d; d.fun2(); d.fun1(); Base b; // b.fun2(); //This will give error as not belongs to base class b.fun1(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
5f2c7098e7dc62ac530fb653c16106d45826198f
612325535126eaddebc230d8c27af095c8e5cc2f
/src/base/trace_event/heap_profiler_stack_frame_deduplicator.h
6791a7fd5c2f0b1114e2154a033690d4ff5458e8
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,989
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TRACE_EVENT_HEAP_PROFILER_STACK_FRAME_DEDUPLICATOR_H_ #define BASE_TRACE_EVENT_HEAP_PROFILER_STACK_FRAME_DEDUPLICATOR_H_ #include <map> #include <string> #include <vector> #include "base/base_export.h" #include "base/macros.h" #include "base/trace_event/heap_profiler_allocation_context.h" #include "base/trace_event/trace_event_impl.h" namespace base { namespace trace_event { class TraceEventMemoryOverhead; // A data structure that allows grouping a set of backtraces in a space- // efficient manner by creating a call tree and writing it as a set of (node, // parent) pairs. The tree nodes reference both parent and children. The parent // is referenced by index into |frames_|. The children are referenced via a map // of |StackFrame|s to index into |frames_|. So there is a trie for bottum-up // lookup of a backtrace for deduplication, and a tree for compact storage in // the trace log. class BASE_EXPORT StackFrameDeduplicator : public ConvertableToTraceFormat { public: // A node in the call tree. struct FrameNode { FrameNode(StackFrame frame, int parent_frame_index); FrameNode(const FrameNode& other); ~FrameNode(); size_t EstimateMemoryUsage() const; StackFrame frame; // The index of the parent stack frame in |frames_|, or -1 if there is no // parent frame (when it is at the bottom of the call stack). int parent_frame_index; // Indices into |frames_| of frames called from the current frame. std::map<StackFrame, int> children; }; using ConstIterator = std::vector<FrameNode>::const_iterator; StackFrameDeduplicator(); ~StackFrameDeduplicator() override; // Inserts a backtrace where |beginFrame| is a pointer to the bottom frame // (e.g. main) and |endFrame| is a pointer past the top frame (most recently // called function), and returns the index of its leaf node in |frames_|. // Returns -1 if the backtrace is empty. int Insert(const StackFrame* beginFrame, const StackFrame* endFrame); // Iterators over the frame nodes in the call tree. ConstIterator begin() const { return frames_.begin(); } ConstIterator end() const { return frames_.end(); } // Writes the |stackFrames| dictionary as defined in https://goo.gl/GerkV8 to // the trace log. void AppendAsTraceFormat(std::string* out) const override; // Estimates memory overhead including |sizeof(StackFrameDeduplicator)|. void EstimateTraceMemoryOverhead(TraceEventMemoryOverhead* overhead) override; private: std::map<StackFrame, int> roots_; std::vector<FrameNode> frames_; DISALLOW_COPY_AND_ASSIGN(StackFrameDeduplicator); }; } // namespace trace_event } // namespace base #endif // BASE_TRACE_EVENT_HEAP_PROFILER_STACK_FRAME_DEDUPLICATOR_H_
[ "2100639007@qq.com" ]
2100639007@qq.com
5201fbbf310e115826a52d84c66b231cf0013c1b
067e6852adfb005abd2fbf3eef2998853dd52b77
/parser.hpp
d7ddd9b1b4b5adbc5032bac486e6b47e28fd85f4
[]
no_license
darcykimball/ss
881df7d95c278bf63ee322c4b40729992f89efc5
f1f3dba3ef25b5ede9d88ae19fdabf466095e082
refs/heads/master
2021-05-03T18:33:24.144326
2018-02-22T06:34:48
2018-02-22T06:34:48
120,413,152
0
0
null
null
null
null
UTF-8
C++
false
false
361
hpp
#ifndef PARSER_HPP #define PARSER_HPP #include <exception> #include "http.hpp" namespace http { struct parse_error : std::runtime_error { parse_error(std::string const& msg) : std::runtime_error{msg} {} }; // Parse an HTTP/1.0 request, crudely request parse_request(std::vector<uint8_t> const& raw_req); } // namespace http #endif // PARSER_HPP
[ "kevinzbao@gmail.com" ]
kevinzbao@gmail.com
02a484e8983ed491984707453902deb803767ff7
2b5908fc625abca08da813d1ac8a7759c298a40e
/src/selection.hpp
4733fdf2ff280b3636e75dfb0f4772f186b337d0
[]
no_license
zgsxwsdxg/haarselector
25185eae1929202201b98cee8ad2e02432053807
253aa6e7db14d5ac3d6146078b04c4d0acbf6aeb
refs/heads/master
2021-01-01T19:37:31.294557
2013-11-24T19:22:14
2013-11-24T19:22:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
812
hpp
/* * selection.hpp * * Created on: Nov 5, 2013 * Author: Peter Borkuti */ #ifndef SELECTION_HPP_ #define SELECTION_HPP_ #include "opencv2/core/core.hpp" #include <ostream> class Selection { public: int type; int subtype; cv::Rect rect; Selection(); Selection(cv::Rect r); Selection(int _type, int _subtype, cv::Rect r); Selection(std::string stype, std::string ssubtype, std::vector<std::string> rect); int getValue(const std::string s, const std::string arr[]); std::string toString(); std::string toString(int type_, int subtype_); void incType(); void incSubtype(); std::string getKey(); std::string getKey(std::string separator); friend std::ostream& operator<<(std::ostream &strm, Selection sel); }; typedef std::vector<Selection> VecSelection; #endif /* SELECTION_HPP_ */
[ "peter@debian" ]
peter@debian
79e5ba1434cd479e695c66920f80229c847d249c
15825b461f87c8824981b9c1eda656341ca7bfc3
/ApplicationsA/ROCKCLIENT_OLD2/rocklibs/RockInterface/Rui.h
3ff0ab33bcb10197d91c0f79afb68c50cf5295e3
[]
no_license
Blkheat/AbsoluteDec
65426bb64d48ddcf62a36d814aba36005b6d33e8
e738f47a8f0fd43507f4148b38326f75f77a09eb
refs/heads/master
2022-12-20T14:09:30.164732
2020-10-22T18:23:54
2020-10-22T18:23:54
306,420,364
0
0
null
null
null
null
UHC
C++
false
false
17,449
h
/////////////////////////////////////////////////////////////////////////////// /// /// File : Rui.h /// Desc : /// /// Author : Park Soo-Hyun /// Team : Program - Client Team /// Date : /// /// Copyright(c) 2004, Rocksoft Co., Ltd. ALL RIGHTS RESERVED /// /////////////////////////////////////////////////////////////////////////////// #ifndef __RUI_H__ #define __RUI_H__ //----------------------------------------------------------------------------- #include "..\\RockPCH.h" #include "Define.h" #include "DefineHID.h" #include "..\\..\\CLogo2DEffect.h" #include "Util.h" #include "Render.h" #include "Resource.h" #include "Chain.h" #include "Container.h" #include "Input.h" #include "Fontman.h" #include "Wnd.h" #include "Slot.h" #include "HelpStringTip.h" #include "HelpItemTip.h" #include "DlgBalloon.h" #include "NonPlayerInfoMiniBar.h" #include "Combo2DTimingEffect.h" #include "BZoneIN2DEffect.h" #include "CharIdRenderer.h" //#include "..\\..\\pc.h" #include ".\\..\\bravolibs\\obj\\player_manager.h" #include "..\\..\\bravolibs\\obj\\player.h" #include "..\\..\\bravolibs\\obj\\nonplayer.h" #include "defineHID_ID.h" enum NEnterFlag { n_nfUIEnter, n_nfEditEnter }; enum NEffect { n_efNone, n_efFadeIn, n_efFadeOut }; enum NVIEW_PCID { n_VIEW_NONE_PCID, n_VIEW_ALL_PCID, n_VIEW_PICK_PCID }; enum N_RESOLUTION { n_800X600, n_1024X768 }; enum N_EVENTRESULT { n_ERESULT_NONE, n_ERESULT_UIPROC, n_ERESULT_ITEM_DROP, n_ERESULT_ERROR }; struct SPanel { bool IsAction; NEffect Effect; TEXID Img; ISIZE Size; D3DCOLOR Color; }; struct SMessageStr { TCHAR Text[256]; int x; int y; D3DCOLOR Color; }; struct MopInfo { int Number; int PosX; int PosY; float fMopSkill; float fMopAttack; float fMopAttacked; float fMopWait; float fMopDie; float fMopMove; }; struct KeyData { bool bflag; DWORD dwTime; KeyData() { Clear(); } void Clear() { bflag =false; dwTime = 0; } void SetLock(DWORD Time) { dwTime = Time; bflag = true; } void SetUnLock() { Clear(); } bool GetCheckTime(DWORD dwCurTime) { if(bflag) { if( SAFE_TIME_COMPARE( dwCurTime , > , SAFE_TIME_ADD( dwTime , 3000 ) ) ) { SetUnLock(); return true; } return false; } else { return true; } } }; struct KeyLock { KeyData QuickSlotKey; KeyData Inventory; KeyData Warehouse; KeyData GuildInven; }; #define CHT_IMEFILENAME1 "TINTLGNT.IME" // New Phonetic #define CHT_IMEFILENAME2 "CINTLGNT.IME" // New Chang Jie #define CHT_IMEFILENAME3 "MSTCIPHA.IME" // Phonetic 5.1 #define CHS_IMEFILENAME1 "PINTLGNT.IME" // MSPY1.5/2/3 #define CHS_IMEFILENAME2 "MSSCIPYA.IME" // MSPY3 for OfficeXP #define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL) #define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) #define _CHT_HKL ( (HKL)(INT_PTR)0xE0080404 ) // New Phonetic #define _CHT_HKL2 ( (HKL)(INT_PTR)0xE0090404 ) // New Chang Jie #define _CHS_HKL ( (HKL)(INT_PTR)0xE00E0804 ) // MSPY #define MAKEIMEVERSION( major, minor ) \ ( (DWORD)( ( (BYTE)( major ) << 24 ) | ( (BYTE)( minor ) << 16 ) ) ) #define IMEID_CHT_VER42 ( LANG_CHT | MAKEIMEVERSION( 4, 2 ) ) // New(Phonetic/ChanJie)IME98 : 4.2.x.x // Win98 #define IMEID_CHT_VER43 ( LANG_CHT | MAKEIMEVERSION( 4, 3 ) ) // New(Phonetic/ChanJie)IME98a : 4.3.x.x // Win2k #define IMEID_CHT_VER44 ( LANG_CHT | MAKEIMEVERSION( 4, 4 ) ) // New ChanJie IME98b : 4.4.x.x // WinXP #define IMEID_CHT_VER50 ( LANG_CHT | MAKEIMEVERSION( 5, 0 ) ) // New(Phonetic/ChanJie)IME5.0 : 5.0.x.x // WinME #define IMEID_CHT_VER51 ( LANG_CHT | MAKEIMEVERSION( 5, 1 ) ) // New(Phonetic/ChanJie)IME5.1 : 5.1.x.x // IME2002(w/OfficeXP) #define IMEID_CHT_VER52 ( LANG_CHT | MAKEIMEVERSION( 5, 2 ) ) // New(Phonetic/ChanJie)IME5.2 : 5.2.x.x // IME2002a(w/Whistler) #define IMEID_CHT_VER60 ( LANG_CHT | MAKEIMEVERSION( 6, 0 ) ) // New(Phonetic/ChanJie)IME6.0 : 6.0.x.x // IME XP(w/WinXP SP1) #define IMEID_CHS_VER41 ( LANG_CHS | MAKEIMEVERSION( 4, 1 ) ) // MSPY1.5 // SCIME97 or MSPY1.5 (w/Win98, Office97) #define IMEID_CHS_VER42 ( LANG_CHS | MAKEIMEVERSION( 4, 2 ) ) // MSPY2 // Win2k/WinME #define IMEID_CHS_VER53 ( LANG_CHS | MAKEIMEVERSION( 5, 3 ) ) // MSPY3 // WinXP #define LCID_INVARIANT MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT) const WORD c_Max_ItemDelayInfo( 50 ); ///-- Mini_game Class class CMiniGame_Elda; ///--------------------------------------------------------------------------- ///-- CRui ///--------------------------------------------------------------------------- extern int g_nCandidate_Page_Size; class CRui { public: CRui(){} #ifdef DIRECT_VERSION_9_MJH CRui( LPDIRECT3DDEVICE9 D3DDevice ); #else CRui( LPDIRECT3DDEVICE8 D3DDevice ); #endif // DIRECT_VERSION_9_MJH ~CRui(); //------------------------------------------------------------------------- bool CreateDesktop( HINSTANCE hInst, HWND hWnd, int Width, int Height, int Bits ); bool CreateWnd(); CWnd* CreateWnd( NWindowType WType, WNDID Iid, WNDID Pid, float Xpos, float Ypos, int Width, int Height, bool isRatio ); #ifdef UI_CONTROL_RENEWAL CWnd* CreateControl( DWORD Defineid ); CWnd* CreateControlRepeetY( DWORD Defineid, DWORD Count, DWORD Num ); CWnd* CreateControlRepeetX( DWORD Defineid, DWORD Count, DWORD Num ); CWnd* CreateControlGetID( DWORD Defineid, WNDID Pid ); #endif // UI_CONTROL_RENEWAL N_EVENTRESULT EventProc( SKeys* Keys, SMouse* Mouse ); void BillUIRenderProc(); //by simwoosung 빌보드 UI 렌더링하는 함수 void LastRenderProc(); //by simwoosung 플리핑 이전에 바로 렌더링할 함수 - 커서렌더링 void RenderProc(); void RenderLogo(int nAlpha); IRESULT SendEvent( WNDID Wid, NEventMessage Event, EPARAM fParam, EPARAM sParam, EPARAM xParam, EPARAM exParam ); IRESULT ReceiveEvent( NEventMessage Event, EPARAM fParam, EPARAM sParam, EPARAM xParam, EPARAM exParam ); //------------------------------------------------------------------------- void ModeInitialize( DWORD gamemode ); void TextOut( void* str, int x, int y, D3DCOLOR color ); void TextOutChat( void* str, D3DCOLOR color ); void MessageBox( int msg_id, TCHAR* text, TCHAR* caption, TEXID icon_type ); void SetDlgBalloon( NCHARTYPE ctype, DWORD id ); void DeleteDlgBalloon( NCHARTYPE ctype, DWORD id ); //------------------------------------------------------------------------- WNDID IsFocus( int Mx, int My ); bool IsEditFocus(); HWND GetWndHandle(); HWND GetCurrentWndHandle(); N_RESOLUTION GetResolution();//해상도 얻어오기 //------------------------------------------------------------------------- //그룹화.... void SetGroupWnd( int Count, WNDID SelectedWnd, ... ); void SetEnterFlag( NEnterFlag EnterFlag ); void SetEnterWndID( WNDID EnterWndID ); //MessageBox void SetModal( WNDID modal_wid ); // UIData Update void Update2DEffect(); void UpdatePcData(); // PcData void InitMyPcData();//SPcDataParam, SPcDataInven의 데이타 초기화.... void SetMyPcData( SRpdPCData* pcdata, int pcdata_size );// 게임 접속시 전송받은 캐릭터 데이터를 저장한다. void SetPcInfo( SPcInfo* pcinfo ); void SetPickPcIdx( int index ); SPcInfo* GetPcInfo(); SPcDataParam* GetPcParamInfo(); SPcDataInven* GetPcInvenInfo(); // void SetCursorType( NCursorType cursor_type ); void SetCursorItem( SPcItem* pcitem ); SPcItem* GetCursorItem(); //by simwoosung #ifdef DIRECT_VERSION_9_MJH LPDIRECT3DSURFACE9 m_pCursorBitmap; #else LPDIRECT3DSURFACE8 m_pCursorBitmap; #endif // DIRECT_VERSION_9_MJH bool SetDeviceCursor(UINT Tid, bool IsItem); void SetItemSelectedSlot( CSlot* slot ); CSlot* GetItemSelectedSlot(); void ResetCursorItem(); /// 임시 : by sooree void EnableBGround( bool aFlag ) { theBGround.IsAction = aFlag; } void EnableFGround( bool aFlag ) { theBGround.IsAction = aFlag; } void MiniGameStartUp( const int ai_game_num, const int ai_arg1, BYTE theGameTimeRatio = 100 ); ///-- MiniGame Start void MiniGameEnd( const int ai_arg1 ); ///-- MiniGame End void ItemPickUp(); bool m_IsSurpportHCursor; BYTE m_WorldIndex; BYTE m_ChannelIndex; // dongs NPC 모든 정보를 출력 하기 위해 .. int thePcinfoCount; int TestNumFame; //bool LoadStoreTable( char* file_pos ); SDesktop Desktop; SPcItem* thePcItem; #ifdef HHM_USER_RESOLUTION_SELECT// 해상도 변경(2009/04/22) float m_fResolutionRateW;// 1024 를 기준으로 클라이언트 영역의 폭 변동율 float m_fResolutionRateH;// 768 를 기준으로 클라이언트 영역의 높이 변동율 #endif // #ifdef HHM_USER_RESOLUTION_SELECT// 해상도 변경(2009/04/22) //SStoreList theStoreList; SPcInfo* thePcInfo; SPcInfo thePickedPcInfo; int thePickPcIdx; NVIEW_PCID theViewPcInfo; CChain Chain; //커서 상태 BYTE theCursorState; void SetCursorState(); // 다른 유저 정보 바 CNonPlayerInfoMiniBar theNonPlayerInfoMiniBar; CSlot theSlot; //ItemSelectedSlot ///-- Mini_Game bool m_bOnMiniGame; ///-- flag CMiniGame_Elda *theMiniGame; ///-- Pointer of Instance void Refresh_ItemHelpTip(){ theItemTip->Refresh(); }; //콤보타이밍 연출 CCombo2DTimingEffect m_Combo2DTimingEffect; //배틀존 진입 이펙트 연출 CBZoneIn2DEffect m_BZoneIn2DEffect; //캐릭터 아이디 렌더러 CCharIdRenderer m_CharIdRenderer; bool m_bIsShowUI; MopInfo m_BugMop; //요거 몬스터 말소리 랜던 확률 .. //특정 키 및 서버와 통신할때 .. 락을 걸어서 서버에서 오기전까지 다른처리는 하지 말자 . KeyLock m_KeyLock; SPcDataParam * GetPcParam() { return &thePcParam; } SPcDataInven * GetPcInven() { return &thePcInven; } SPcDataParam thePcParam;// 캐릭터 속성, 스탯 등 SPcDataInven thePcInven; CLogo2DEffect m_Logo2DEffect; private: #ifdef DIRECT_VERSION_9_MJH LPDIRECT3DDEVICE9 theD3DDevice; #else LPDIRECT3DDEVICE8 theD3DDevice; #endif // DIRECT_VERSION_9_MJH N_RESOLUTION theResolution;//해상도 //------------------------------------------------------------------------- SPanel theBGround; SPanel theFGround; NCursorType theCursorType; int theCursorAniIdx; SCursor* theCursor; SDlgBorder* theBorder; SEventMessage theEMsg; //------------------------------------------------------------------------- WNDID DurationWnd; //유지 윈도우 WNDID ModalWnd; //모달 윈도우 WNDID ActiveWnd; //활성 윈도우 WNDID FocusWnd; //현재 마우스 위치의 포커스 윈도우 WNDID FocusPwnd; //IsFocus( int Mx, int My ) 용....현재...Event .... Focus Parents Wnd //포커스 체크는 단순히..최상위 윈도우만 검사하기 때문.... bool isDragging; bool isShowInfo; NEnterFlag theEnterFlag; WNDID theEnterWndID; SMessageStr theMessage[256]; int theNumMsg; CFontg* theFontg1; CFontg* theFontg2; CFontg* theFontg3; CHelpTip* theHelpTip; CHelpItem* theItemTip; int theNumDlg; CDlgBalloon* theDlgBalloon[MAX_DLGBALLOON]; //------------------------------------------------------------------------- WNDID FindFocusWindow( int Mx, int My, bool IsChildCheck ); void MakeEventMessage( SKeys* Keys, SMouse* Mouse, WNDID FocusWnd ); void KeyEventProc(); void UserKeyProc(); //유져가 사용하는키 void CtrlUserKeyProc(bool& IsWnd); //컨트롤 + X 챗창과 겹칩 void TestKeyProc(bool& IsWnd); //개발자가 사용하는키 //------------------------------------------------------------------------- void SortDlgBalloon(); void GetTimeFlag(); //------------------------------------------------------------------------- void DrawPoint(); void DrawPcItem(); void DrawWindows(); void DrawToolTip(); void DrawMessage(); void DrawInfo(); void DrawBackGround(); void DrawForeGround(); void DrawSystemMsg(); void DrawAutoHelpTip(); //------------------------------------------------------------------------- //------------------------------------------------------------------------- void ShowInfo( bool ShowFlag ); void ShowCursor( bool ShowFlag ); void ShowBackGround( bool ActionFlag ); void ShowForeGround( bool ActionFlag ); //------------------------------------------------------------------------- public: void DrawCursor(); void DrawCharacterID(); //by simwoosung void DrawCharacterDetailInfoBillId(int index); //빌보드 렌더 - 캐릭터 정보 void DrawCharacterDetailInfoUIId(int index); //RHW-UI 렌더 - 캐릭터 정보 void DrawDlgBalloon(); //말풍선 void DrawGameUI(); void UpdateMaxGage(WORD aSkill_Code, bool IsGet); protected: void UpdateGetMaxGage(int nGageStep, int nGageIndex); void UpdatePutMaxGage(int nGageStep, int nGageIndex); public: long theItemDalayTime[c_Max_ItemDelayInfo]; // 아이템 사용 딜레이 체크 50가지 float realItemDelayTime[c_Max_ItemDelayInfo]; // 실제 딜레이 타임 float cumItemDelayTime[c_Max_ItemDelayInfo]; // 누적 딜레이 타임 bool enableDelayTime[c_Max_ItemDelayInfo]; // 딜레이 타임 사용가능여부 bool useCheckDelayTime[c_Max_ItemDelayInfo]; // 그룹 딜레이 사용체크여부 float useCheckCumDelayTime[c_Max_ItemDelayInfo]; // 그룹 딜레이 사용체크누적타임 void InitDlgBalloon(); //by simwoosung WNDID GetFocusWnd() { return FocusWnd; } NCursorType GetCursorType() { return theCursorType; } SCursor * GetCursor() { return theCursor; } CHelpTip* GetHelpTip() { return theHelpTip; } SEventMessage* GetEMsg() { return &theEMsg; } CFontg* GetFontg() { return theFontg2; } void GetUserKeyProc() {UserKeyProc();} //by dongs BOOL GetIsKeepUpFindSKill(const int Code); void LogOff(); void SetState(); void ReleaseState(); ///--------------------------------------------------------------------------- ///-- Japan IME 작업 시 추가. ///--------------------------------------------------------------------------- public: void DrawIMECovert(); void GetIMEAttrPos( HIMC ahIMC ); int GetDrawStrWidth( CFontg* pFontg, TCHAR* pStr, long aNumStr ); int GetDrawStrHeight( CFontg* pFontg, TCHAR* pStr ); int GetStrWidthMax(CFontg* pFontg , void *pStr , int &RealSize,int MaxSize); bool Get_Cdi_visible() const { return mb_candidate; }; int Get_Cdi_start_idx() const { return ml_candi_start_idx; }; int Get_Cdi_sel_idx() const { return ml_candi_sel_idx; }; int Get_Cdi_count() const { return ml_candi_count; }; const char * const Get_Cid_Str( const int al_idx ) const { return mac_candi_str[al_idx]; }; const char * const Get_Cid_cmpStr( const int al_idx ) const { return mac_comp_str; }; int Get_Language(){ return ml_language; }; void Set_Cdi_Str( const int al_index, char * apc_str ); void Set_Cdi_cmpStr( char * apc_str ); void Set_Cdi_visible( const bool ab_flag ) { mb_candidate = ab_flag; }; void Set_Cdi_Values( const int al_count, const int al_st_idx, const int al_sel_idx ); void Render_Candidate(); void Set_Language( int al_language ){ ml_language = al_language;}; void Set_Cdi_Pos( const int x, const int y ) { ml_candi_x = x, ml_candi_y = y; }; void Complete_Cdi_List(); ///-- Candidate List 지정 완료 Render 준비 void ReSetTIDImage(); //NewIME std::wstring m_reading; DWORD m_dwId[2]; HKL m_hkl; HINSTANCE m_hDllIme; LANGID m_langId; WORD m_codePage; bool m_bUnicodeIme; bool m_bVerticalReading; bool m_bCheckChinaCHS; int GetCharsetFromLang(LANGID langid); int GetCodePageFromLang( LANGID langid ); int GetCodePageFromCharset(int charset); bool GetCheckIME_Unicode(); bool GetReadingWindowOrientation(); void GetImeID(); void SetupImeApi(HWND hWnd); void GetPrivateReadingString(HWND hEdit); void LanguageChange(HWND hWnd , WPARAM wParam, LPARAM lParam); UINT (WINAPI * _GetReadingString)( HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT ); BOOL (WINAPI * _ShowReadingWindow)( HIMC, BOOL ); bool bVerticalReading; void SetReadingStr(RTCHAR *Str); void SetReadingVisible(bool bFlag){ bVerticalReading = bFlag;}; void Render_Reading(); bool ReadingProcess(); WCHAR StrTextReading[128]; WCHAR StrTextReadingTemp[4][20]; void SetStringReset(){m_reading.resize(0);}; private: ///-- !!!!JIME ///-- RockClient.h 에도 있다. 설정은 rockclient.cpp int ml_language; ///-- 0 : Korean / 1 : Japan / 2 : Reserved / 3 : Reserved char mac_comp_str[1024]; ///-- 조합중인 String char mac_candi_str[10][100]; ///-- Candidate List //국내,일본 페이지사이즈 9 중국 10 bool mb_candidate; ///-- Candidate 창 열림 판단. int ml_candi_start_idx; ///-- 현재 보여줄 Page 의 첫 idx int ml_candi_sel_idx; ///-- 현재 선택된 idx int ml_candi_count; ///-- Candidate Character Count int ml_candi_x, ml_candi_y; ///-- Candidate Coordinate int ml_width_max; ///-- List 의 너비 int ml_page_y; ///-- List Page 번호 int ml_list_y; ///-- List 의 세로좌표 CFontg* mc_font_candi; CFontg* mc_font_candisel; int m_convertedPos[2]; long m_lEdPrevtime; }; extern CRui *nRui; //----------------------------------------------------------------------------- #endif __RUI_H__
[ "takemyrequiem@gmail.com" ]
takemyrequiem@gmail.com
9f52d15ad466ad22e4732785b6e8d8db1e699562
db7d3b55142acad88a535d61ae54101ada2470e2
/l5r/Followers/bushido.h
a68b7d2b011b51efb09e34077c6eace03ade7ef4
[ "MIT" ]
permissive
SKefalidis/legend_of_di
b9e0baf7f618a3db2f30f2a7bc4cb2b42c04976b
f1f54b7a6b7fdd9f1de1671a6a2dcdc2462ea0fb
refs/heads/master
2022-04-20T11:08:46.678897
2020-04-09T22:22:47
2020-04-09T22:22:47
243,939,029
0
0
null
null
null
null
UTF-8
C++
false
false
156
h
#ifndef BUSHIDO_H #define BUSHIDO_H #include "../follower.h" class Bushido : public Follower { public: Bushido(string iName); }; #endif // BUSHIDO_H
[ "megistios@gmail.com" ]
megistios@gmail.com
18d6acd8d027e6456c3953a1a1211087ac418d6a
d102336347e340aa979c3cd01de8be029ce63114
/tests/src/algorithmTest.cpp
5eb4a0634db29af79d3dcf50053607930384fb45
[]
no_license
ageev-aleksey/compilers-lab2
41938fca63bd4b31508ee25832d955ed2f8aea60
1b39f641f22854f6969dca66e97431cf5f3d10e3
refs/heads/master
2022-04-23T00:11:09.159362
2020-04-25T14:20:01
2020-04-25T14:20:01
258,755,223
0
0
null
null
null
null
UTF-8
C++
false
false
7,025
cpp
// // Created by nrx on 16.04.2020. // #include "grammar/algorithm.h" #include "gtest/gtest.h" Grammar getGrammar1() { Grammar::Builder b; b.setAxiom({"axiom", "S"}); b.addNonTerminal({"A", "A"}); b.addNonTerminal({"B", "B"}); b.addTerminal({"a", "a"}); b.addTerminal({"b", "b"}); b.addProduction({{ {"axiom", "S"} }}, {{ {"a", "a"} }}); b.addProduction({{ {"axiom", "S"} }}, {{ {"A", "A"} }}); b.addProduction({{ {"A", "A"} }}, {{ {"A", "A"}, {"B", "B"} }}); b.addProduction({{ {"B", "B"} }}, {{ {"b", "b"} }}); return b.build(); } Grammar getGrammar2() { Grammar::Builder b; b.setAxiom({"axiom", "S"}); b.addNonTerminal({"A", "A"}); b.addNonTerminal({"B", "B"}); b.addTerminal({"a", "a"}); b.addTerminal({"b", "b"}); b.addProduction({{{"axiom", "S"}}}, {{{"A", "A"}}}); b.addProduction({{{"axiom", "S"}}}, {{{"B", "B"}}}); b.addProduction({{{"A", "A"}}}, {{{"a", "a"}, {"B", "B"}}}); b.addProduction({{{"A", "A"}}}, {{{"b", "b"}, {"axiom", "S"}}}); b.addProduction({{{"A", "A"}}}, {{{"b", "b"}}}); b.addProduction({{{"B", "B"}}}, {{{"A", "A"}, {"B", "B"}}}); b.addProduction({{{"B", "B"}}}, {{{"B", "B"}, {"a", "a"}}}); b.addProduction({{{"B", "B"}}}, {{{"A", "A"}, {"axiom", "S"}}}); b.addProduction({{{"B", "B"}}}, {{{"b", "b"}}}); return b.build(); } TEST(RemoveBelong, AhoExample2_22_Page172) { Grammar g = getGrammar1(); auto res = algorithm::removeBarrenSymbols(g); ASSERT_EQ(res, (std::unordered_set<Symbol>{{"axiom", "S"}, {"B", "B"}})); } TEST(RemoveBelongSymbolsTest, AhoExercise2_4_6_Page189) { Grammar g = getGrammar2(); auto res = algorithm::removeBarrenSymbols(g); ASSERT_EQ(res, std::unordered_set<Symbol>({{"axiom", "S"}, {"A", "A"}, {"B", "B"}})); } TEST(RemoveUnrechebleSymbolsTest, AhoExample2_22_Page172) { Grammar::Builder b; b.setAxiom({"axiom", "S"}); b.addNonTerminal({"B", "B"}); b.addTerminal({"a", "a"}); b.addTerminal({"b", "b"}); b.addProduction({{ {"axiom", "S"} }},{{ {"a", "a"} }} ); b.addProduction({{ {"B", "B"} }},{{ {"b", "b"} }} ); Grammar g = b.build(); auto res = algorithm::removeUnreachableSymbols(g); ASSERT_EQ(res, std::unordered_set<Symbol>({{"axiom", "S"}, {"a", "a"}})); } TEST(deleteDummySymbolsTest, AhoExample2_22_Page172) { Grammar g = getGrammar1(); Grammar res = algorithm::deleteDummySymbols(g); Grammar::Builder b; b.setAxiom({"axiom", "S"}); b.addTerminal({"a", "a"}); b.addProduction({{ {"axiom", "S"} }}, {{ {"a", "a"} }}); Grammar ok = b.build(); ASSERT_EQ(res, ok); } TEST(removeDirectRecursion, oneRecursion) { Symbol S{"S", "S"}; Symbol Ss{"S'", "S'"}; Symbol b{"b", "b"}; Symbol a{"a", "a"}; Symbol e{"e", "e"}; std::list<Production> p{ Production(ProductionPart({ S }), ProductionPart({ S, a })), Production(ProductionPart({ S }), ProductionPart({ b, a })) }; algorithm::removeDirectRecursion({S}, p, e, S); std::unordered_set<Production> ok { Production(ProductionPart({S}), ProductionPart({b, a, Ss})), Production(ProductionPart({Ss}), ProductionPart({ a, Ss })), Production(ProductionPart({Ss}), ProductionPart({ e })) }; std::unordered_set<Production> resSet; for(const Production & prod : p) { resSet.insert(prod); } ASSERT_EQ(resSet, ok); } TEST(removeDirectRecursion, withoutRecursion) { Symbol S{"S", "S"}; Symbol b{"b", "b"}; Symbol a{"a", "a"}; Symbol e{"e", "e"}; std::list<Production> p{ Production(ProductionPart({ S }), ProductionPart({ a, a })), Production(ProductionPart({ S }), ProductionPart({ b, a })) }; std::unordered_set<Production> ok; for(const Production & prod : p) { ok.insert(prod); } algorithm::removeDirectRecursion({S}, p, e, S); std::unordered_set<Production> resSet; for(const Production & prod : p) { resSet.insert(prod); } ASSERT_EQ(resSet, ok); } TEST(removeDirectRecursion, rulesWithRecursionAndWithoutRecursion) { Symbol S{"S", "S"}; Symbol Ss{"S'", "S'"}; Symbol b{"b", "b"}; Symbol a{"a", "a"}; Symbol e{"e", "e"}; std::list<Production> p{ Production(ProductionPart({ S }), ProductionPart({ a, a })), Production(ProductionPart({ S }), ProductionPart({ b, a })), Production(ProductionPart({ S }), ProductionPart({S, b, b })), Production(ProductionPart({ S }), ProductionPart({S, a, b })), Production(ProductionPart({ S }), ProductionPart({S, a, a })) }; algorithm::removeDirectRecursion({S}, p, e, S); std::unordered_set<Production> resSet; std::unordered_set<Production> ok{ Production(ProductionPart({ S }), ProductionPart({ a, a, Ss})), Production(ProductionPart({ S }), ProductionPart({ b, a, Ss})), Production(ProductionPart({ Ss }), ProductionPart({ b, b, Ss })), Production(ProductionPart({ Ss }), ProductionPart({ a, b, Ss })), Production(ProductionPart({ Ss }), ProductionPart({ a, a, Ss })), Production(ProductionPart({ Ss }), ProductionPart({ e })) }; for(const Production & prod : p) { resSet.insert(prod); } ASSERT_EQ(resSet, ok); } TEST(deleteRecurionTest, test) { Symbol A("A", "A"); Symbol B("B", "B"); Symbol C("C", "C"); Symbol a("a", "a"); Symbol b("b", "b"); Grammar::Builder builder; builder.setAxiom(A); builder.setEpsilon({"e", "e"}); builder.addNonTerminal(B); builder.addNonTerminal(C); builder.addTerminal(a); builder.addTerminal(b); builder.addProduction(ProductionPart({A}), ProductionPart({B, C})); builder.addProduction(ProductionPart({A}), ProductionPart({a})); builder.addProduction(ProductionPart({B}), ProductionPart({C, A})); builder.addProduction(ProductionPart({B}), ProductionPart({A, b})); builder.addProduction(ProductionPart({C}), ProductionPart({A, B})); builder.addProduction(ProductionPart({C}), ProductionPart({C, C})); builder.addProduction(ProductionPart({C}), ProductionPart({a})); Grammar g = builder.build(); Grammar res = algorithm::deleteRecursion(g); std::cout << std::endl; } TEST(deleteRecurionTest, simple) { Symbol A("A", "A"); Symbol S("S", "S"); Symbol a("a", "a"); Symbol b("b", "b"); Grammar::Builder builder; builder.setAxiom(A); builder.setEpsilon({"e", "e"}); builder.addNonTerminal(S); builder.addTerminal(a); builder.addTerminal(b); builder.addProduction(ProductionPart({A}), ProductionPart({S, a})); builder.addProduction(ProductionPart({S}), ProductionPart({A, b})); builder.addProduction(ProductionPart({S}), ProductionPart({b})); Grammar g = builder.build(); Grammar res = algorithm::deleteRecursion(g); std::cout << std::endl; } TEST(deleteRecurionTest, simple2) { }
[ "ageevav97@gmail.com" ]
ageevav97@gmail.com
cb048069d8bfb266c39cf91d5c378025bf89d8fa
17de782236016310839e8cd79ca2033cf8603a5b
/vendor/nanogui/tabheader.cpp
f689b914872039ddc9d8be29ab78084112d30676
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
johnlunney/Avara-1
8da2beb8e9e164f19677934ba7302869d74e2679
9bdb46307d2750c18b7ec10b9efbc3078937aca4
refs/heads/master
2020-03-28T11:00:19.943162
2018-09-10T01:08:28
2018-09-10T01:08:28
148,167,767
1
0
MIT
2018-09-10T14:26:15
2018-09-10T14:26:15
null
UTF-8
C++
false
false
17,584
cpp
/* nanogui/tabheader.cpp -- Widget used to control tabs. The tab header widget was contributed by Stefan Ivanov. NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>. The widget drawing code is based on the NanoVG demo application by Mikko Mononen. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include <nanogui/tabheader.h> #include <nanogui/theme.h> #include <nanogui/opengl.h> #include <numeric> #include <algorithm> NAMESPACE_BEGIN(nanogui) TabHeader::TabButton::TabButton(TabHeader &header, const std::string &label) : mHeader(&header), mLabel(label) { } Vector2i TabHeader::TabButton::preferredSize(NVGcontext *ctx) const { // No need to call nvg font related functions since this is done by the tab header implementation float bounds[4]; int labelWidth = nvgTextBounds(ctx, 0, 0, mLabel.c_str(), nullptr, bounds); int buttonWidth = labelWidth + 2 * mHeader->theme()->mTabButtonHorizontalPadding; int buttonHeight = bounds[3] - bounds[1] + 2 * mHeader->theme()->mTabButtonVerticalPadding; return Vector2i(buttonWidth, buttonHeight); } void TabHeader::TabButton::calculateVisibleString(NVGcontext *ctx) { // The size must have been set in by the enclosing tab header. NVGtextRow displayedText; nvgTextBreakLines(ctx, mLabel.c_str(), nullptr, mSize.x, &displayedText, 1); // Check to see if the text need to be truncated. if (displayedText.next[0]) { auto truncatedWidth = nvgTextBounds(ctx, 0.0f, 0.0f, displayedText.start, displayedText.end, nullptr); auto dotsWidth = nvgTextBounds(ctx, 0.0f, 0.0f, dots, nullptr, nullptr); while ((truncatedWidth + dotsWidth + mHeader->theme()->mTabButtonHorizontalPadding) > mSize.x && displayedText.end != displayedText.start) { --displayedText.end; truncatedWidth = nvgTextBounds(ctx, 0.0f, 0.0f, displayedText.start, displayedText.end, nullptr); } // Remember the truncated width to know where to display the dots. mVisibleWidth = truncatedWidth; mVisibleText.last = displayedText.end; } else { mVisibleText.last = nullptr; mVisibleWidth = 0; } mVisibleText.first = displayedText.start; } void TabHeader::TabButton::drawAtPosition(NVGcontext *ctx, const Vector2i& position, bool active) { int xPos = position.x; int yPos = position.y; int width = mSize.x; int height = mSize.y; auto theme = mHeader->theme(); nvgSave(ctx); nvgIntersectScissor(ctx, xPos, yPos, width+1, height); if (!active) { // Background gradients NVGcolor gradTop = theme->mButtonGradientTopPushed; NVGcolor gradBot = theme->mButtonGradientBotPushed; // Draw the background. nvgBeginPath(ctx); nvgRoundedRect(ctx, xPos + 1, yPos + 1, width - 1, height + 1, theme->mButtonCornerRadius); NVGpaint backgroundColor = nvgLinearGradient(ctx, xPos, yPos, xPos, yPos + height, gradTop, gradBot); nvgFillPaint(ctx, backgroundColor); nvgFill(ctx); } if (active) { nvgBeginPath(ctx); nvgStrokeWidth(ctx, 1.0f); nvgRoundedRect(ctx, xPos + 0.5f, yPos + 1.5f, width, height + 1, theme->mButtonCornerRadius); nvgStrokeColor(ctx, theme->mBorderLight); nvgStroke(ctx); nvgBeginPath(ctx); nvgRoundedRect(ctx, xPos + 0.5f, yPos + 0.5f, width, height + 1, theme->mButtonCornerRadius); nvgStrokeColor(ctx, theme->mBorderDark); nvgStroke(ctx); } else { nvgBeginPath(ctx); nvgRoundedRect(ctx, xPos + 0.5f, yPos + 1.5f, width, height, theme->mButtonCornerRadius); nvgStrokeColor(ctx, theme->mBorderDark); nvgStroke(ctx); } nvgResetScissor(ctx); nvgRestore(ctx); // Draw the text with some padding int textX = xPos + mHeader->theme()->mTabButtonHorizontalPadding; int textY = yPos + mHeader->theme()->mTabButtonVerticalPadding; NVGcolor textColor = mHeader->theme()->mTextColor; nvgBeginPath(ctx); nvgFillColor(ctx, textColor); nvgText(ctx, textX, textY, mVisibleText.first, mVisibleText.last); if (mVisibleText.last != nullptr) nvgText(ctx, textX + mVisibleWidth, textY, dots, nullptr); } void TabHeader::TabButton::drawActiveBorderAt(NVGcontext *ctx, const Vector2i &position, float offset, const Color &color) { int xPos = position.x; int yPos = position.y; int width = mSize.x; int height = mSize.y; nvgBeginPath(ctx); nvgLineJoin(ctx, NVG_ROUND); nvgMoveTo(ctx, xPos + offset, yPos + height + offset); nvgLineTo(ctx, xPos + offset, yPos + offset); nvgLineTo(ctx, xPos + width - offset, yPos + offset); nvgLineTo(ctx, xPos + width - offset, yPos + height + offset); nvgStrokeColor(ctx, color); nvgStrokeWidth(ctx, mHeader->theme()->mTabBorderWidth); nvgStroke(ctx); } void TabHeader::TabButton::drawInactiveBorderAt(NVGcontext *ctx, const Vector2i &position, float offset, const Color& color) { int xPos = position.x; int yPos = position.y; int width = mSize.x; int height = mSize.y; nvgBeginPath(ctx); nvgRoundedRect(ctx, xPos + offset, yPos + offset, width - offset, height - offset, mHeader->theme()->mButtonCornerRadius); nvgStrokeColor(ctx, color); nvgStroke(ctx); } TabHeader::TabHeader(Widget* parent, const std::string& font) : Widget(parent), mFont(font) { } void TabHeader::setActiveTab(int tabIndex) { assert(tabIndex < tabCount()); mActiveTab = tabIndex; if (mCallback) mCallback(tabIndex); } int TabHeader::activeTab() const { return mActiveTab; } bool TabHeader::isTabVisible(int index) const { return index >= mVisibleStart && index < mVisibleEnd; } void TabHeader::addTab(const std::string & label) { addTab(tabCount(), label); } void TabHeader::addTab(int index, const std::string &label) { assert(index <= tabCount()); mTabButtons.insert(std::next(mTabButtons.begin(), index), TabButton(*this, label)); setActiveTab(index); } int TabHeader::removeTab(const std::string &label) { auto element = std::find_if(mTabButtons.begin(), mTabButtons.end(), [&](const TabButton& tb) { return label == tb.label(); }); int index = (int) std::distance(mTabButtons.begin(), element); if (element == mTabButtons.end()) return -1; mTabButtons.erase(element); if (index == mActiveTab && index != 0) setActiveTab(index - 1); return index; } void TabHeader::removeTab(int index) { assert(index < tabCount()); mTabButtons.erase(std::next(mTabButtons.begin(), index)); if (index == mActiveTab && index != 0) setActiveTab(index - 1); } const std::string& TabHeader::tabLabelAt(int index) const { assert(index < tabCount()); return mTabButtons[index].label(); } int TabHeader::tabIndex(const std::string &label) { auto it = std::find_if(mTabButtons.begin(), mTabButtons.end(), [&](const TabButton& tb) { return label == tb.label(); }); if (it == mTabButtons.end()) return -1; return (int) (it - mTabButtons.begin()); } void TabHeader::ensureTabVisible(int index) { auto visibleArea = visibleButtonArea(); auto visibleWidth = visibleArea.second.x - visibleArea.first.x; int allowedVisibleWidth = mSize.x - 2 * theme()->mTabControlWidth; assert(allowedVisibleWidth >= visibleWidth); assert(index >= 0 && index < (int) mTabButtons.size()); auto first = visibleBegin(); auto last = visibleEnd(); auto goal = tabIterator(index); // Reach the goal tab with the visible range. if (goal < first) { do { --first; visibleWidth += first->size().x; } while (goal < first); while (allowedVisibleWidth < visibleWidth) { --last; visibleWidth -= last->size().x; } } else if (goal >= last) { do { visibleWidth += last->size().x; ++last; } while (goal >= last); while (allowedVisibleWidth < visibleWidth) { visibleWidth -= first->size().x; ++first; } } // Check if it is possible to expand the visible range on either side. while (first != mTabButtons.begin() && std::next(first, -1)->size().x < allowedVisibleWidth - visibleWidth) { --first; visibleWidth += first->size().x; } while (last != mTabButtons.end() && last->size().x < allowedVisibleWidth - visibleWidth) { visibleWidth += last->size().x; ++last; } mVisibleStart = (int) std::distance(mTabButtons.begin(), first); mVisibleEnd = (int) std::distance(mTabButtons.begin(), last); } std::pair<Vector2i, Vector2i> TabHeader::visibleButtonArea() const { if (mVisibleStart == mVisibleEnd) return { Vector2i(), Vector2i() }; auto topLeft = mPos + Vector2i(theme()->mTabControlWidth, 0); auto width = std::accumulate(visibleBegin(), visibleEnd(), theme()->mTabControlWidth, [](int acc, const TabButton& tb) { return acc + tb.size().x; }); auto bottomRight = mPos + Vector2i(width, mSize.y); return { topLeft, bottomRight }; } std::pair<Vector2i, Vector2i> TabHeader::activeButtonArea() const { if (mVisibleStart == mVisibleEnd || mActiveTab < mVisibleStart || mActiveTab >= mVisibleEnd) return { Vector2i(), Vector2i() }; auto width = std::accumulate(visibleBegin(), activeIterator(), theme()->mTabControlWidth, [](int acc, const TabButton& tb) { return acc + tb.size().x; }); auto topLeft = mPos + Vector2i(width, 0); auto bottomRight = mPos + Vector2i(width + activeIterator()->size().x, mSize.y); return { topLeft, bottomRight }; } void TabHeader::performLayout(NVGcontext* ctx) { Widget::performLayout(ctx); Vector2i currentPosition = Vector2i(); // Place the tab buttons relative to the beginning of the tab header. for (auto& tab : mTabButtons) { auto tabPreferred = tab.preferredSize(ctx); if (tabPreferred.x < theme()->mTabMinButtonWidth) tabPreferred.x = theme()->mTabMinButtonWidth; else if (tabPreferred.x > theme()->mTabMaxButtonWidth) tabPreferred.x = theme()->mTabMaxButtonWidth; tab.setSize(tabPreferred); tab.calculateVisibleString(ctx); currentPosition.x += tabPreferred.x; } calculateVisibleEnd(); if (mVisibleStart != 0 || mVisibleEnd != tabCount()) mOverflowing = true; } Vector2i TabHeader::preferredSize(NVGcontext* ctx) const { // Set up the nvg context for measuring the text inside the tab buttons. nvgFontFace(ctx, mFont.c_str()); nvgFontSize(ctx, fontSize()); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_TOP); Vector2i size = Vector2i(2*theme()->mTabControlWidth, 0); for (auto& tab : mTabButtons) { auto tabPreferred = tab.preferredSize(ctx); if (tabPreferred.x < theme()->mTabMinButtonWidth) tabPreferred.x = theme()->mTabMinButtonWidth; else if (tabPreferred.x > theme()->mTabMaxButtonWidth) tabPreferred.x = theme()->mTabMaxButtonWidth; size.x += tabPreferred.x; size.y = std::max(size.y, tabPreferred.y); } return size; } bool TabHeader::mouseButtonEvent(const Vector2i &p, int button, bool down, int modifiers) { Widget::mouseButtonEvent(p, button, down, modifiers); if (button == SDL_BUTTON_LEFT && down) { switch (locateClick(p)) { case ClickLocation::LeftControls: onArrowLeft(); return true; case ClickLocation::RightControls: onArrowRight(); return true; case ClickLocation::TabButtons: auto first = visibleBegin(); auto last = visibleEnd(); int currentPosition = theme()->mTabControlWidth; int endPosition = p.x; auto firstInvisible = std::find_if(first, last, [&currentPosition, endPosition](const TabButton& tb) { currentPosition += tb.size().x; return currentPosition > endPosition; }); // Did not click on any of the tab buttons if (firstInvisible == last) return true; // Update the active tab and invoke the callback. setActiveTab((int) std::distance(mTabButtons.begin(), firstInvisible)); return true; } } return false; } void TabHeader::draw(NVGcontext* ctx) { // Draw controls. Widget::draw(ctx); if (mOverflowing) drawControls(ctx); // Set up common text drawing settings. nvgFontFace(ctx, mFont.c_str()); nvgFontSize(ctx, fontSize()); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_TOP); auto current = visibleBegin(); auto last = visibleEnd(); auto active = std::next(mTabButtons.begin(), mActiveTab); Vector2i currentPosition = mPos + Vector2i(theme()->mTabControlWidth, 0); // Flag to draw the active tab last. Looks a little bit better. bool drawActive = false; Vector2i activePosition = Vector2i(); // Draw inactive visible buttons. while (current != last) { if (current == active) { drawActive = true; activePosition = currentPosition; } else { current->drawAtPosition(ctx, currentPosition, false); } currentPosition.x += current->size().x; ++current; } // Draw active visible button. if (drawActive) active->drawAtPosition(ctx, activePosition, true); } void TabHeader::calculateVisibleEnd() { auto first = visibleBegin(); auto last = mTabButtons.end(); int currentPosition = theme()->mTabControlWidth; int lastPosition = mSize.x - theme()->mTabControlWidth; auto firstInvisible = std::find_if(first, last, [&currentPosition, lastPosition](const TabButton& tb) { currentPosition += tb.size().x; return currentPosition > lastPosition; }); mVisibleEnd = (int) std::distance(mTabButtons.begin(), firstInvisible); } void TabHeader::drawControls(NVGcontext* ctx) { // Left button. bool active = mVisibleStart != 0; // Draw the arrow. nvgBeginPath(ctx); auto iconLeft = utf8(mTheme->mTabHeaderLeftIcon); int fontSize = mFontSize == -1 ? mTheme->mButtonFontSize : mFontSize; float ih = fontSize; ih *= icon_scale(); nvgFontSize(ctx, ih); nvgFontFace(ctx, "icons"); NVGcolor arrowColor; if (active) arrowColor = mTheme->mTextColor; else arrowColor = mTheme->mButtonGradientBotPushed; nvgFillColor(ctx, arrowColor); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); float yScaleLeft = 0.5f; float xScaleLeft = 0.2f; Vector2f leftIconPos = (Vector2f)mPos + Vector2f(xScaleLeft*theme()->mTabControlWidth, yScaleLeft*(float)mSize.y); nvgText(ctx, leftIconPos.x, leftIconPos.y + 1, iconLeft.data(), nullptr); // Right button. active = mVisibleEnd != tabCount(); // Draw the arrow. nvgBeginPath(ctx); auto iconRight = utf8(mTheme->mTabHeaderRightIcon); fontSize = mFontSize == -1 ? mTheme->mButtonFontSize : mFontSize; ih = fontSize; ih *= icon_scale(); nvgFontSize(ctx, ih); nvgFontFace(ctx, "icons"); float rightWidth = nvgTextBounds(ctx, 0, 0, iconRight.data(), nullptr, nullptr); if (active) arrowColor = mTheme->mTextColor; else arrowColor = mTheme->mButtonGradientBotPushed; nvgFillColor(ctx, arrowColor); nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); float yScaleRight = 0.5f; float xScaleRight = 1.0f - xScaleLeft - rightWidth / theme()->mTabControlWidth; Vector2f rightIconPos = (Vector2f)mPos + Vector2f((float)mSize.x, (float)mSize.y*yScaleRight) - Vector2f(xScaleRight*theme()->mTabControlWidth + rightWidth, 0); nvgText(ctx, rightIconPos.x, rightIconPos.y + 1, iconRight.data(), nullptr); } TabHeader::ClickLocation TabHeader::locateClick(const Vector2i& p) { /* auto leftDistance = (p - mPos).array(); bool hitLeft = (leftDistance >= 0).all() && (leftDistance < Vector2i(theme()->mTabControlWidth, mSize.y).array()).all(); if (hitLeft) return ClickLocation::LeftControls; auto rightDistance = (p - (mPos + Vector2i(mSize.x - theme()->mTabControlWidth, 0))).array(); bool hitRight = (rightDistance >= 0).all() && (rightDistance < Vector2i(theme()->mTabControlWidth, mSize.y).array()).all(); if (hitRight) return ClickLocation::RightControls; */ return ClickLocation::TabButtons; } void TabHeader::onArrowLeft() { if (mVisibleStart == 0) return; --mVisibleStart; calculateVisibleEnd(); } void TabHeader::onArrowRight() { if (mVisibleEnd == tabCount()) return; ++mVisibleStart; calculateVisibleEnd(); } NAMESPACE_END(nanogui)
[ "dcwatson@gmail.com" ]
dcwatson@gmail.com
5e7efa13e7383aa37c504b488820e017eb34c23f
d78ab1e4cb8a669fbd4b5346683345c3926f4e07
/Editor/scintilla/src/LexAsn1.cxx
a4b0861714845e3ba04ce712b5552af8e16b600b
[ "LicenseRef-scancode-unknown-license-reference", "Artistic-2.0", "LicenseRef-scancode-scintilla" ]
permissive
sonneveld/ags
4baca2321a1c1a13621322eb107d5338e9231fbf
539a40a25f4caa7b7cec678084cfcde252418c77
refs/heads/ags3--sdl2
2022-04-30T19:38:51.480211
2019-07-27T11:08:38
2019-11-03T06:53:44
40,235,193
2
0
NOASSERTION
2022-02-20T11:15:37
2015-08-05T08:54:39
C
UTF-8
C++
false
false
5,353
cxx
// Scintilla source code edit control /** @file LexAsn1.cxx ** Lexer for ASN.1 **/ // Copyright 2004 by Herr Pfarrer rpfarrer <at> yahoo <dot> de // Last Updated: 20/07/2004 // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" // Some char test functions static bool isAsn1Number(int ch) { return (ch >= '0' && ch <= '9'); } static bool isAsn1Letter(int ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); } static bool isAsn1Char(int ch) { return (ch == '-' ) || isAsn1Number(ch) || isAsn1Letter (ch); } // // Function determining the color of a given code portion // Based on a "state" // static void ColouriseAsn1Doc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[], Accessor &styler) { // The keywords WordList &Keywords = *keywordLists[0]; WordList &Attributes = *keywordLists[1]; WordList &Descriptors = *keywordLists[2]; WordList &Types = *keywordLists[3]; // Parse the whole buffer character by character using StyleContext StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // The state engine switch (sc.state) { case SCE_ASN1_DEFAULT: // Plain characters asn1_default: if (sc.ch == '-' && sc.chNext == '-') // A comment begins here sc.SetState(SCE_ASN1_COMMENT); else if (sc.ch == '"') // A string begins here sc.SetState(SCE_ASN1_STRING); else if (isAsn1Number (sc.ch)) // A number starts here (identifier should start with a letter in ASN.1) sc.SetState(SCE_ASN1_SCALAR); else if (isAsn1Char (sc.ch)) // An identifier starts here (identifier always start with a letter) sc.SetState(SCE_ASN1_IDENTIFIER); else if (sc.ch == ':') // A ::= operator starts here sc.SetState(SCE_ASN1_OPERATOR); break; case SCE_ASN1_COMMENT: // A comment if (sc.ch == '\r' || sc.ch == '\n') // A comment ends here sc.SetState(SCE_ASN1_DEFAULT); break; case SCE_ASN1_IDENTIFIER: // An identifier (keyword, attribute, descriptor or type) if (!isAsn1Char (sc.ch)) { // The end of identifier is here: we can look for it in lists by now and change its state char s[100]; sc.GetCurrent(s, sizeof(s)); if (Keywords.InList(s)) // It's a keyword, change its state sc.ChangeState(SCE_ASN1_KEYWORD); else if (Attributes.InList(s)) // It's an attribute, change its state sc.ChangeState(SCE_ASN1_ATTRIBUTE); else if (Descriptors.InList(s)) // It's a descriptor, change its state sc.ChangeState(SCE_ASN1_DESCRIPTOR); else if (Types.InList(s)) // It's a type, change its state sc.ChangeState(SCE_ASN1_TYPE); // Set to default now sc.SetState(SCE_ASN1_DEFAULT); } break; case SCE_ASN1_STRING: // A string delimited by "" if (sc.ch == '"') { // A string ends here sc.ForwardSetState(SCE_ASN1_DEFAULT); // To correctly manage a char sticking to the string quote goto asn1_default; } break; case SCE_ASN1_SCALAR: // A plain number if (!isAsn1Number (sc.ch)) // A number ends here sc.SetState(SCE_ASN1_DEFAULT); break; case SCE_ASN1_OPERATOR: // The affectation operator ::= and wath follows (eg: ::= { org 6 } OID or ::= 12 trap) if (sc.ch == '{') { // An OID definition starts here: enter the sub loop for (; sc.More(); sc.Forward()) { if (isAsn1Number (sc.ch) && (!isAsn1Char (sc.chPrev) || isAsn1Number (sc.chPrev))) // The OID number is highlighted sc.SetState(SCE_ASN1_OID); else if (isAsn1Char (sc.ch)) // The OID parent identifier is plain sc.SetState(SCE_ASN1_IDENTIFIER); else sc.SetState(SCE_ASN1_DEFAULT); if (sc.ch == '}') // Here ends the OID and the operator sub loop: go back to main loop break; } } else if (isAsn1Number (sc.ch)) { // A trap number definition starts here: enter the sub loop for (; sc.More(); sc.Forward()) { if (isAsn1Number (sc.ch)) // The trap number is highlighted sc.SetState(SCE_ASN1_OID); else { // The number ends here: go back to main loop sc.SetState(SCE_ASN1_DEFAULT); break; } } } else if (sc.ch != ':' && sc.ch != '=' && sc.ch != ' ') // The operator doesn't imply an OID definition nor a trap, back to main loop goto asn1_default; // To be sure to handle actually the state change break; } } sc.Complete(); } static void FoldAsn1Doc(unsigned int, int, int, WordList *[], Accessor &styler) { // No folding enabled, no reason to continue... if( styler.GetPropertyInt("fold") == 0 ) return; // No folding implemented: doesn't make sense for ASN.1 } static const char * const asn1WordLists[] = { "Keywords", "Attributes", "Descriptors", "Types", 0, }; LexerModule lmAns1(SCLEX_ASN1, ColouriseAsn1Doc, "asn1", FoldAsn1Doc, asn1WordLists);
[ "tobias.han@gmx.de" ]
tobias.han@gmx.de
e6bf9c14848b672405598f62dda448a7dcb398a6
07e76572d1756407cf36f3d4d78b9a991ded29cb
/client/lisql/lisql.cc
64205a9a7ee93e19fb0e76e8e283fd8712dbfc72
[]
no_license
northhurricane/lsql
e53613ec58e13be084a830de9c70fec6f055abea
a405c20e53980c40c203ce1c71dedf8da7512299
refs/heads/master
2021-01-18T21:19:26.973075
2017-11-03T09:48:12
2017-11-03T09:48:12
24,048,515
0
0
null
null
null
null
UTF-8
C++
false
false
547
cc
#include "lpi.h" #include "lsql.h" lpi_henv_t env; lpi_hdbc_t dbc; lpi_hstmt_t stmt; lret lisql_connect() { lpi_return_t r; r = lpi_alloc_env(&env); r = lpi_alloc_dbc(env, &dbc); r = lpi_set_dbc_attr(dbc, LPI_ATTR_PORT, (lpi_pointer_t)5966, 0); r = lpi_connect(dbc, (lpi_char_t*)"127.0.0.1", 0, (lpi_char_t*)"2", 0, (lpi_char_t*)"3", 0); } lret lisql_disconnect() { return LSQL_SUCCESS; } int main(int argc, char *argv[]) { lret r = LSQL_ERROR; r = lisql_connect(); r = lisql_disconnect(); return 0; }
[ "jiangyx@ctrip.com" ]
jiangyx@ctrip.com
7cc08bebe05636b477e392a82443d1c2ed01df1a
cd8abfb87e558f05b13fce74dbc27ea6375e45af
/fboss/agent/state/SwitchSettings.cpp
d5387ae0b225f9820d81073ca1d3c9d9b3450035
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nanWave/fboss
4e355915e6ae80452c579104b534397812e1b42b
b920e54c6919800f915222b6ba7a63757ecdc8bf
refs/heads/master
2022-08-13T22:44:10.869514
2022-07-25T05:30:57
2022-07-25T05:30:57
105,797,491
0
0
null
2017-10-04T17:31:02
2017-10-04T17:31:02
null
UTF-8
C++
false
false
9,631
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/state/SwitchSettings.h" #include "common/network/if/gen-cpp2/Address_types.h" #include "fboss/agent/AddressUtil.h" #include "fboss/agent/state/SwitchState.h" #include "fboss/agent/state/NodeBase-defs.h" #include "folly/dynamic.h" #include "folly/json.h" namespace { constexpr auto kL2LearningMode = "l2LearningMode"; constexpr auto kQcmEnable = "qcmEnable"; constexpr auto kPtpTcEnable = "ptpTcEnable"; constexpr auto kL2AgeTimerSeconds = "l2AgeTimerSeconds"; constexpr auto kMaxRouteCounterIDs = "maxRouteCounterIDs"; constexpr auto kBlockNeighbors = "blockNeighbors"; constexpr auto kBlockNeighborVlanID = "blockNeighborVlanID"; constexpr auto kBlockNeighborIP = "blockNeighborIP"; constexpr auto kMacAddrsToBlock = "macAddrsToBlock"; constexpr auto kMacAddrToBlockVlanID = "macAddrToBlockVlanID"; constexpr auto kMacAddrToBlockAddr = "macAddrToBlockAddr"; } // namespace namespace facebook::fboss { folly::dynamic SwitchSettingsFields::toFollyDynamicLegacy() const { folly::dynamic switchSettings = folly::dynamic::object; switchSettings[kL2LearningMode] = static_cast<int>(l2LearningMode); switchSettings[kQcmEnable] = static_cast<bool>(qcmEnable); switchSettings[kPtpTcEnable] = static_cast<bool>(ptpTcEnable); switchSettings[kL2AgeTimerSeconds] = static_cast<int>(l2AgeTimerSeconds); switchSettings[kMaxRouteCounterIDs] = static_cast<int>(maxRouteCounterIDs); switchSettings[kBlockNeighbors] = folly::dynamic::array; for (const auto& [vlanID, ipAddress] : blockNeighbors) { folly::dynamic jsonEntry = folly::dynamic::object; jsonEntry[kBlockNeighborVlanID] = folly::to<std::string>(vlanID); jsonEntry[kBlockNeighborIP] = folly::to<std::string>(ipAddress); switchSettings[kBlockNeighbors].push_back(jsonEntry); } switchSettings[kMacAddrsToBlock] = folly::dynamic::array; for (const auto& [vlanID, macAddr] : macAddrsToBlock) { folly::dynamic jsonEntry = folly::dynamic::object; jsonEntry[kMacAddrToBlockVlanID] = folly::to<std::string>(vlanID); jsonEntry[kMacAddrToBlockAddr] = folly::to<std::string>(macAddr); switchSettings[kMacAddrsToBlock].push_back(jsonEntry); } return switchSettings; } SwitchSettingsFields SwitchSettingsFields::fromFollyDynamicLegacy( const folly::dynamic& json) { SwitchSettingsFields switchSettings = SwitchSettingsFields(); if (json.find(kL2LearningMode) != json.items().end()) { switchSettings.l2LearningMode = cfg::L2LearningMode(json[kL2LearningMode].asInt()); } if (json.find(kQcmEnable) != json.items().end()) { switchSettings.qcmEnable = json[kQcmEnable].asBool(); } if (json.find(kPtpTcEnable) != json.items().end()) { switchSettings.ptpTcEnable = json[kPtpTcEnable].asBool(); } if (json.find(kL2AgeTimerSeconds) != json.items().end()) { switchSettings.l2AgeTimerSeconds = json[kL2AgeTimerSeconds].asInt(); } if (json.find(kMaxRouteCounterIDs) != json.items().end()) { switchSettings.maxRouteCounterIDs = json[kMaxRouteCounterIDs].asInt(); } if (json.find(kBlockNeighbors) != json.items().end()) { for (const auto& entry : json[kBlockNeighbors]) { switchSettings.blockNeighbors.emplace_back( entry[kBlockNeighborVlanID].asInt(), entry[kBlockNeighborIP].asString()); } } if (json.find(kMacAddrsToBlock) != json.items().end()) { for (const auto& entry : json[kMacAddrsToBlock]) { switchSettings.macAddrsToBlock.emplace_back( entry[kMacAddrToBlockVlanID].asInt(), entry[kMacAddrToBlockAddr].asString()); } } return switchSettings; } SwitchSettings* SwitchSettings::modify(std::shared_ptr<SwitchState>* state) { if (!isPublished()) { CHECK(!(*state)->isPublished()); return this; } SwitchState::modify(state); auto newSwitchSettings = clone(); auto* ptr = newSwitchSettings.get(); (*state)->resetSwitchSettings(std::move(newSwitchSettings)); return ptr; } bool SwitchSettings::operator==(const SwitchSettings& switchSettings) const { return ( (getFields()->l2LearningMode == switchSettings.getL2LearningMode()) && (getFields()->qcmEnable == switchSettings.isQcmEnable()) && (getFields()->ptpTcEnable == switchSettings.isPtpTcEnable()) && (getFields()->qcmEnable == switchSettings.isQcmEnable()) && (getFields()->l2AgeTimerSeconds == switchSettings.getL2AgeTimerSeconds()) && (getFields()->maxRouteCounterIDs == switchSettings.getMaxRouteCounterIDs()) && getFields()->blockNeighbors == switchSettings.getBlockNeighbors() && getFields()->macAddrsToBlock == switchSettings.getMacAddrsToBlock()); } state::SwitchSettingsFields SwitchSettingsFields::toThrift() const { state::SwitchSettingsFields thriftFields{}; thriftFields.l2LearningMode() = l2LearningMode; thriftFields.qcmEnable() = qcmEnable; thriftFields.ptpTcEnable() = ptpTcEnable; thriftFields.l2AgeTimerSeconds() = l2AgeTimerSeconds; thriftFields.maxRouteCounterIDs() = maxRouteCounterIDs; for (auto neighbor : blockNeighbors) { auto [vlan, ip] = neighbor; state::BlockedNeighbor blockedNeighbor; blockedNeighbor.blockNeighborVlanID() = vlan; blockedNeighbor.blockNeighborIP() = facebook::network::toBinaryAddress(ip); thriftFields.blockNeighbors()->push_back(blockedNeighbor); } for (auto macAddr : macAddrsToBlock) { auto [vlan, mac] = macAddr; state::BlockedMacAddress blockedMac; blockedMac.macAddrToBlockVlanID() = vlan; blockedMac.macAddrToBlockAddr() = mac.toString(); thriftFields.macAddrsToBlock()->push_back(blockedMac); } return thriftFields; } SwitchSettingsFields SwitchSettingsFields::fromThrift( state::SwitchSettingsFields const& fields) { SwitchSettingsFields settings{}; settings.l2LearningMode = *fields.l2LearningMode(); settings.qcmEnable = *fields.qcmEnable(); settings.ptpTcEnable = *fields.ptpTcEnable(); settings.l2AgeTimerSeconds = *fields.l2AgeTimerSeconds(); settings.maxRouteCounterIDs = *fields.maxRouteCounterIDs(); for (auto blockedNeighbor : *fields.blockNeighbors()) { auto ip = facebook::network::toIPAddress(*blockedNeighbor.blockNeighborIP()); auto vlan = static_cast<VlanID>(*blockedNeighbor.blockNeighborVlanID()); settings.blockNeighbors.push_back(std::make_pair(vlan, ip)); } for (auto macAddr : *fields.macAddrsToBlock()) { auto mac = folly::MacAddress(*macAddr.macAddrToBlockAddr()); auto vlan = static_cast<VlanID>(*macAddr.macAddrToBlockVlanID()); settings.macAddrsToBlock.push_back(std::make_pair(vlan, mac)); } return settings; } folly::dynamic SwitchSettingsFields::migrateToThrifty( folly::dynamic const& dynLegacy) { folly::dynamic newDynamic = dynLegacy; folly::dynamic blockedNeighborsDynamic = folly::dynamic::array; for (auto neighborDynLegacy : dynLegacy["blockNeighbors"]) { auto addr = facebook::network::toBinaryAddress( folly::IPAddress(neighborDynLegacy["blockNeighborIP"].asString())); std::string jsonStr; apache::thrift::SimpleJSONSerializer::serialize(addr, &jsonStr); folly::dynamic neighborDyn = folly::dynamic::object; neighborDyn["blockNeighborIP"] = folly::parseJson(jsonStr); neighborDyn["blockNeighborVlanID"] = static_cast<int16_t>(neighborDynLegacy["blockNeighborVlanID"].asInt()); blockedNeighborsDynamic.push_back(neighborDyn); } newDynamic["blockNeighbors"] = blockedNeighborsDynamic; folly::dynamic macAddrsToBlockDynamic = folly::dynamic::array; if (dynLegacy.find("macAddrsToBlock") != dynLegacy.items().end()) { for (auto macDynLegacy : dynLegacy["macAddrsToBlock"]) { folly::dynamic macDyn = folly::dynamic::object; macDyn["macAddrToBlockVlanID"] = static_cast<int16_t>(macDynLegacy["macAddrToBlockVlanID"].asInt()); macDyn["macAddrToBlockAddr"] = macDynLegacy["macAddrToBlockAddr"].asString(); macAddrsToBlockDynamic.push_back(macDyn); } } newDynamic["macAddrsToBlock"] = macAddrsToBlockDynamic; return newDynamic; } void SwitchSettingsFields::migrateFromThrifty(folly::dynamic& dyn) { folly::dynamic& blockedNeighborsDynamic = dyn["blockNeighbors"]; folly::dynamic& blockedMacAddrsDynamic = dyn["macAddrsToBlock"]; folly::dynamic blockedNeighborsLegacy = folly::dynamic::array; for (auto& neighborDyn : blockedNeighborsDynamic) { auto vlan = static_cast<uint16_t>(neighborDyn["blockNeighborVlanID"].asInt()); auto jsonStr = folly::toJson(neighborDyn["blockNeighborIP"]); auto inBuf = folly::IOBuf::wrapBufferAsValue(jsonStr.data(), jsonStr.size()); auto addr = facebook::network::toIPAddress( apache::thrift::SimpleJSONSerializer::deserialize< facebook::network::thrift::BinaryAddress>( folly::io::Cursor{&inBuf})); folly::dynamic blockedNeighborLegacy = folly::dynamic::object; neighborDyn["blockNeighborIP"] = addr.str(); neighborDyn["blockNeighborVlanID"] = vlan; } for (auto& macDyn : blockedMacAddrsDynamic) { auto vlan = static_cast<uint16_t>(macDyn["macAddrToBlockVlanID"].asInt()); macDyn["macAddrToBlockVlanID"] = vlan; } } template class ThriftyBaseT< state::SwitchSettingsFields, SwitchSettings, SwitchSettingsFields>; } // namespace facebook::fboss
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
65470f7677459e2c57d65660fcbc81746c198c6a
fd4d96c3d60039223e5d9f99d8e8b1875f1d0c37
/Gearmo 16/src/Commands/POV.cpp
ac1510e4ed371ed43d5febc05f949b0e8a1b148d
[]
no_license
Team-931/gearmo-16
89c16cd8dd609b57f323d40918ab080696b395bb
1414e1c28ae58a2eaf1df78172e32b66b97f1a64
refs/heads/master
2021-01-11T16:46:30.882617
2018-02-14T22:05:43
2018-02-14T22:05:43
79,669,745
0
0
null
null
null
null
UTF-8
C++
false
false
800
cpp
#include "POV.h" #include "Facer.h" POV::POV() { // Use Requires() here to declare subsystem dependencies // eg. Requires(Robot::chassis.get()); } // Called just before this Command runs the first time void POV::Initialize() { } // Called repeatedly when this Command is scheduled to run void POV::Execute() { Joystick &joy = oi->DriveStick(); if(joy.GetPOV(0)>=0) { if(joy.GetPOV(0)%90==0) { float faced = (joy.GetPOV(0)); (new Facer(faced))->Start(); }; }; } // Make this return true when this Command no longer needs to run execute() bool POV::IsFinished() { return false; } // Called once after isFinished returns true void POV::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void POV::Interrupted() { }
[ "rharrington.170@gmail.com" ]
rharrington.170@gmail.com
6667c1bf2605ad7fa7dba06d7314fc631fec4010
d023bf2410098dcb9f7b6cad8eef621b6e3c3be3
/TodoList.h
32abf86831eb4dff202ab33235c393b7be422d44
[]
no_license
moriahweaver12/Lab1-1
8602d0ce302b8b48d2cb09ff0a2419f4b4896f2e
ac01a994443d197fd99313d5dff7eedd0db67be9
refs/heads/master
2023-03-12T08:04:36.614592
2021-02-27T05:47:31
2021-02-27T05:47:31
342,773,702
0
0
null
null
null
null
UTF-8
C++
false
false
1,999
h
#ifndef TODO_LIST_H #define TODO_LIST_H #include <iostream> #include <string> #include "TodoListInterface.h" #include <fstream> using namespace std; class TodoList: public TodoListInterface { public: vector<string> tasks; TodoList() { cout << "In Constructor"; ifstream infile ("TODOList.txt"); string line; if (infile.is_open()) { while (getline (infile,line)) { cout << line << '\n'; tasks.push_back(line); } infile.close(); } } virtual ~TodoList() { cout << "In Destructor" << endl; ofstream outfile; outfile.open("TODOList.txt", ofstream::out | ofstream::trunc); for(int i = 0; i < tasks.size(); i++) { cout << tasks[i] << '\n'; outfile << tasks[i] << endl; } outfile.close(); } /* * Adds an item to the todo list with the data specified by the string "_duedate" and the task specified by "_task" */ virtual void add(string _duedate, string _task) { cout << "In add " << _duedate << " " << _task << endl; tasks.push_back(_duedate + " " + _task); } /* * Removes an item from the todo list with the specified task name * * Returns 1 if it removes an item, 0 otherwise */ virtual int remove(string _task) { cout << "In remove"; for(int i = 0; i < tasks.size(); i++){ cout << endl << i << endl; if(tasks[i].find(_task) != std::string::npos){ cout << "I am in the process of erasing!!!"; tasks.erase (tasks.begin()+ i); return 1; } else { cout << "not it" << endl; //return 0; } } } /* * Prints out the full todo list to the console */ virtual void printTodoList() { cout << "In list" << endl; } /* * Prints out all items of a todo list with a particular due date (specified by _duedate) */ virtual void printDaysTasks(string _date) { cout << "In daystacks" << endl; } }; #endif
[ "moriah.weaver12@gmail.com" ]
moriah.weaver12@gmail.com
fbaf074e10fadfcb7bbe6c2654bcbff4f7e12139
53bbb4c891d5e992506f884a23091db541cbd80e
/BFS/bfs.cpp
7a76ce41c1dc3c78a8f231755f9d8c1dcb4853c4
[]
no_license
williamzhou-hust/Algorithm-Problem
dcfb7df4306d23af71cfdef4510e3888dfed6386
1973eeebc8e736c44715ce2de94812266dafd21e
refs/heads/master
2021-01-19T22:52:24.555232
2017-08-27T04:45:49
2017-08-27T04:45:49
88,875,353
0
0
null
null
null
null
UTF-8
C++
false
false
2,165
cpp
/************************************************************************* > File Name: bfs.cpp > Author: williamzhou > Mail: williamzhou.0330@foxmail.com > Created Time: Tue 28 Mar 2017 05:58:01 AM PDT ************************************************************************/ #include <iostream> #include <queue> #include <vector> using namespace std; enum color{WHITE=1,GRAY=2,BLACK=3}; typedef color nodeColor; class Node{ public: Node(int rvalue):value(rvalue),d(0),pi(-1),clr(WHITE){}; Node():value(-1),d(0),pi(-1),clr(WHITE){}; //set data void setValue(int rvalue){value=rvalue;}; void setDistance(int rd){d=rd;}; void setFatherNode(int rpi){pi=rpi;}; void setColor(nodeColor rclr){clr=rclr;}; //get data int getValue(){return value;}; int getDistance(){return d;}; int getFatherNode(){return pi;}; nodeColor getColor(){return clr;}; //print property void printProperty(){ cout<<value<<"th Node, "<<"distance: "<<d<<" ,fatherNode: "<<pi<<" ,color: "<<clr<<endl; }; private: int value;//the value th node int d;//distance int pi;//father node nodeColor clr; }; int Table[7][7]={{0,1,1,1,1,0,0}, {1,0,1,0,0,1,0}, {1,1,0,1,0,1,0}, {1,0,1,0,1,1,1}, {1,0,0,1,0,0,1}, {0,1,1,1,0,0,1}, {0,0,0,1,1,1,0}}; int main(int argc,char* argv[]){ cout<<"color test: "<<"WHITE: "<<WHITE<<" GRAY: "<<GRAY<<" BLACK: "<<BLACK<<endl; vector<Node> mvec(7); cout<<"initial Node:"<<endl; for(int i=0;i<7;i++){ mvec[i].setValue(i); mvec[i].printProperty(); } int startNode=0; mvec[startNode].setColor(GRAY); queue<Node> mqueue; mqueue.push(mvec[startNode]); while(!mqueue.empty()){ Node u=mqueue.front(); cout<<"u: "; u.printProperty(); mqueue.pop(); int uValue=u.getValue(); cout<<"uValue: "<<uValue<<endl; for(int i=0;i<7;i++){ if(Table[uValue][i]){ if(mvec[i].getColor()==WHITE){ mvec[i].setColor(GRAY); mvec[i].setDistance(u.getDistance()+1); mvec[i].setFatherNode(u.getValue()); mqueue.push(mvec[i]); } } } mvec[uValue].setColor(BLACK); } //after bfs cout<<"After BFS:"<<endl; for(int i=0;i<7;i++){ mvec[i].printProperty(); } return 0; }
[ "williamzhou.0330@gmail.com" ]
williamzhou.0330@gmail.com
809a0dbea70f5aace0aa059ee4f7a62d801bd251
87b638fedd7a5070a1741b523263f764561e18a8
/tlx/sort/parallel_mergesort.hpp
a53b74b42a6847c943944eb2e4da4edd6094b789
[ "BSL-1.0" ]
permissive
mwidmoser/tlx
6bf747fd1cd92089b44dfccc25dbd8f8caf8b58a
6eec6b2d9d99af28284a9af8b8da13b47ad23591
refs/heads/master
2023-08-20T22:40:23.168059
2021-10-01T12:45:54
2021-10-01T12:45:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,942
hpp
/******************************************************************************* * tlx/sort/parallel_mergesort.hpp * * **EXPERIMENTAL** Parallel multiway mergesort **EXPERIMENTAL** * * Copied and modified from STXXL, see http://stxxl.org, which itself extracted * it from MCSTL http://algo2.iti.uni-karlsruhe.de/singler/mcstl/. Both are * distributed under the Boost Software License, Version 1.0. * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2007 Johannes Singler <singler@ira.uka.de> * Copyright (C) 2014-2018 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #ifndef TLX_SORT_PARALLEL_MERGESORT_HEADER #define TLX_SORT_PARALLEL_MERGESORT_HEADER #include <algorithm> #include <functional> #include <thread> #include <utility> #if defined(_OPENMP) #include <omp.h> #endif #include <tlx/algorithm/multisequence_selection.hpp> #include <tlx/algorithm/parallel_multiway_merge.hpp> #include <tlx/simple_vector.hpp> #include <tlx/thread_barrier_mutex.hpp> namespace tlx { //! \addtogroup tlx_sort //! \{ namespace parallel_mergesort_detail { //! Subsequence description. template <typename DiffType> struct PMWMSPiece { //! Begin of subsequence. DiffType begin; //! End of subsequence. DiffType end; }; /*! * Data accessed by all threads. * * PMWMS = parallel multiway mergesort */ template <typename RandomAccessIterator> struct PMWMSSortingData { using ValueType = typename std::iterator_traits<RandomAccessIterator>::value_type; using DiffType = typename std::iterator_traits<RandomAccessIterator>::difference_type; //! Input begin. RandomAccessIterator source; //! Start indices, per thread. simple_vector<DiffType> starts; /** Storage in which to sort. */ simple_vector<ValueType*> temporary; /** Samples. */ simple_vector<ValueType> samples; /** Offsets to add to the found positions. */ simple_vector<DiffType> offsets; /** PMWMSPieces of data to merge \c [thread][sequence] */ simple_vector<simple_vector<PMWMSPiece<DiffType> > > pieces; explicit PMWMSSortingData(size_t num_threads) : starts(num_threads + 1), temporary(num_threads), offsets(num_threads - 1), pieces(num_threads) { } }; /*! * Select samples from a sequence. * \param sd Pointer to sorting data struct. Result will be placed in \c sd->samples. * \param num_samples Number of samples to select. * \param iam my thread number * \param num_threads number of threads in group */ template <typename RandomAccessIterator, typename DiffType> void determine_samples(PMWMSSortingData<RandomAccessIterator>* sd, DiffType& num_samples, size_t iam, size_t num_threads) { num_samples = parallel_multiway_merge_oversampling * num_threads - 1; simple_vector<DiffType> es(num_samples + 2); multiway_merge_detail::equally_split( sd->starts[iam + 1] - sd->starts[iam], static_cast<size_t>(num_samples + 1), es.begin()); for (DiffType i = 0; i < num_samples; i++) { sd->samples[iam * num_samples + i] = sd->source[sd->starts[iam] + es[i + 1]]; } } /*! * PMWMS code executed by each thread. * \param sd Pointer to sorting data struct. * \param iam my thread number * \param num_threads number of threads in group * \param barrier thread barrier from main function * \param comp Comparator. * \param mwmsa MultiwayMergeSplittingAlgorithm to use. */ template <bool Stable, typename RandomAccessIterator, typename Comparator> void parallel_sort_mwms_pu(PMWMSSortingData<RandomAccessIterator>* sd, size_t iam, size_t num_threads, ThreadBarrierMutex& barrier, Comparator& comp, MultiwayMergeSplittingAlgorithm mwmsa) { using ValueType = typename std::iterator_traits<RandomAccessIterator>::value_type; using DiffType = typename std::iterator_traits<RandomAccessIterator>::difference_type; // length of this thread's chunk, before merging DiffType length_local = sd->starts[iam + 1] - sd->starts[iam]; using SortingPlacesIterator = ValueType *; // sort in temporary storage, leave space for sentinel sd->temporary[iam] = static_cast<ValueType*>( ::operator new (sizeof(ValueType) * (length_local + 1))); // copy there std::uninitialized_copy(sd->source + sd->starts[iam], sd->source + sd->starts[iam] + length_local, sd->temporary[iam]); // sort locally if (Stable) std::stable_sort(sd->temporary[iam], sd->temporary[iam] + length_local, comp); else std::sort(sd->temporary[iam], sd->temporary[iam] + length_local, comp); // invariant: locally sorted subsequence in sd->temporary[iam], // sd->temporary[iam] + length_local if (mwmsa == MWMSA_SAMPLING) { DiffType num_samples; determine_samples(sd, num_samples, iam, num_threads); barrier.wait( [&]() { std::sort(sd->samples.begin(), sd->samples.end(), comp); }); for (size_t s = 0; s < num_threads; s++) { // for each sequence if (num_samples * iam > 0) sd->pieces[iam][s].begin = std::lower_bound(sd->temporary[s], sd->temporary[s] + sd->starts[s + 1] - sd->starts[s], sd->samples[num_samples * iam], comp) - sd->temporary[s]; else // absolute beginning sd->pieces[iam][s].begin = 0; if ((num_samples * (iam + 1)) < (num_samples * num_threads)) sd->pieces[iam][s].end = std::lower_bound(sd->temporary[s], sd->temporary[s] + sd->starts[s + 1] - sd->starts[s], sd->samples[num_samples * (iam + 1)], comp) - sd->temporary[s]; else // absolute end sd->pieces[iam][s].end = sd->starts[s + 1] - sd->starts[s]; } } else if (mwmsa == MWMSA_EXACT) { barrier.wait(); simple_vector<std::pair<SortingPlacesIterator, SortingPlacesIterator> > seqs(num_threads); for (size_t s = 0; s < num_threads; s++) seqs[s] = std::make_pair( sd->temporary[s], sd->temporary[s] + sd->starts[s + 1] - sd->starts[s]); simple_vector<SortingPlacesIterator> offsets(num_threads); // if not last thread if (iam < num_threads - 1) multisequence_partition(seqs.begin(), seqs.end(), sd->starts[iam + 1], offsets.begin(), comp); for (size_t seq = 0; seq < num_threads; seq++) { // for each sequence if (iam < (num_threads - 1)) sd->pieces[iam][seq].end = offsets[seq] - seqs[seq].first; else // absolute end of this sequence sd->pieces[iam][seq].end = sd->starts[seq + 1] - sd->starts[seq]; } barrier.wait(); for (size_t seq = 0; seq < num_threads; seq++) { // for each sequence if (iam > 0) sd->pieces[iam][seq].begin = sd->pieces[iam - 1][seq].end; else // absolute beginning sd->pieces[iam][seq].begin = 0; } } // offset from target begin, length after merging DiffType offset = 0, length_am = 0; for (size_t s = 0; s < num_threads; s++) { length_am += sd->pieces[iam][s].end - sd->pieces[iam][s].begin; offset += sd->pieces[iam][s].begin; } // merge directly to target simple_vector<std::pair<SortingPlacesIterator, SortingPlacesIterator> > seqs(num_threads); for (size_t s = 0; s < num_threads; s++) { seqs[s] = std::make_pair( sd->temporary[s] + sd->pieces[iam][s].begin, sd->temporary[s] + sd->pieces[iam][s].end); } multiway_merge_base<Stable, /* Sentinels */ false>( seqs.begin(), seqs.end(), sd->source + offset, length_am, comp); barrier.wait(); operator delete (sd->temporary[iam]); } } // namespace parallel_mergesort_detail //! \name Parallel Sorting Algorithms //! \{ /*! * Parallel multiway mergesort main call. * * \param begin Begin iterator of sequence. * \param end End iterator of sequence. * \param comp Comparator. * \param num_threads Number of threads to use. * \param mwmsa MultiwayMergeSplittingAlgorithm to use. * \tparam Stable Stable sorting. */ template <bool Stable, typename RandomAccessIterator, typename Comparator> void parallel_mergesort_base( RandomAccessIterator begin, RandomAccessIterator end, Comparator comp, size_t num_threads = std::thread::hardware_concurrency(), MultiwayMergeSplittingAlgorithm mwmsa = MWMSA_DEFAULT) { using namespace parallel_mergesort_detail; using DiffType = typename std::iterator_traits<RandomAccessIterator>::difference_type; DiffType n = end - begin; if (n <= 1) return; // at least one element per thread if (num_threads > static_cast<size_t>(n)) num_threads = static_cast<size_t>(n); PMWMSSortingData<RandomAccessIterator> sd(num_threads); sd.source = begin; if (mwmsa == MWMSA_SAMPLING) { sd.samples.resize( num_threads * (parallel_multiway_merge_oversampling * num_threads - 1)); } for (size_t s = 0; s < num_threads; s++) sd.pieces[s].resize(num_threads); DiffType* starts = sd.starts.data(); DiffType chunk_length = n / num_threads, split = n % num_threads, start = 0; for (size_t i = 0; i < num_threads; i++) { starts[i] = start; start += (i < static_cast<size_t>(split)) ? (chunk_length + 1) : chunk_length; } starts[num_threads] = start; // now sort in parallel ThreadBarrierMutex barrier(num_threads); #if defined(_OPENMP) #pragma omp parallel num_threads(num_threads) { size_t iam = omp_get_thread_num(); parallel_sort_mwms_pu<Stable>( &sd, iam, num_threads, barrier, comp, mwmsa); } #else simple_vector<std::thread> threads(num_threads); for (size_t iam = 0; iam < num_threads; ++iam) { threads[iam] = std::thread( [&, iam]() { parallel_sort_mwms_pu<Stable>( &sd, iam, num_threads, barrier, comp, mwmsa); }); } for (size_t i = 0; i < num_threads; i++) { threads[i].join(); } #endif // defined(_OPENMP) } /*! * Parallel multiway mergesort. * * \param begin Begin iterator of sequence. * \param end End iterator of sequence. * \param comp Comparator. * \param num_threads Number of threads to use. * \param mwmsa MultiwayMergeSplittingAlgorithm to use. */ template <typename RandomAccessIterator, typename Comparator = std::less< typename std::iterator_traits<RandomAccessIterator>::value_type> > void parallel_mergesort( RandomAccessIterator begin, RandomAccessIterator end, Comparator comp = Comparator(), size_t num_threads = std::thread::hardware_concurrency(), MultiwayMergeSplittingAlgorithm mwmsa = MWMSA_DEFAULT) { return parallel_mergesort_base</* Stable */ false>( begin, end, comp, num_threads, mwmsa); } /*! * Stable parallel multiway mergesort. * * \param begin Begin iterator of sequence. * \param end End iterator of sequence. * \param comp Comparator. * \param num_threads Number of threads to use. * \param mwmsa MultiwayMergeSplittingAlgorithm to use. */ template <typename RandomAccessIterator, typename Comparator = std::less< typename std::iterator_traits<RandomAccessIterator>::value_type> > void stable_parallel_mergesort( RandomAccessIterator begin, RandomAccessIterator end, Comparator comp = Comparator(), size_t num_threads = std::thread::hardware_concurrency(), MultiwayMergeSplittingAlgorithm mwmsa = MWMSA_DEFAULT) { return parallel_mergesort_base</* Stable */ true>( begin, end, comp, num_threads, mwmsa); } //! \} //! \} } // namespace tlx #endif // !TLX_SORT_PARALLEL_MERGESORT_HEADER /******************************************************************************/
[ "tbgit@panthema.net" ]
tbgit@panthema.net
5f700d329b848eead2765368bfd8ddf03d6a871d
8cd51b4885680c073566f16236cd68d3f4296399
/src/controls/QskBoxSkinlet.cpp
181af0b7564bab086cad7cbb872df6f3903fc072
[ "BSD-3-Clause" ]
permissive
uwerat/qskinny
0e0c6552afa020382bfa08453a5636b19ae8ff49
bf2c2b981e3a6ea1187826645da4fab75723222c
refs/heads/master
2023-08-21T16:27:56.371179
2023-08-10T17:54:06
2023-08-10T17:54:06
97,966,439
1,074
226
BSD-3-Clause
2023-08-10T17:12:01
2017-07-21T16:16:18
C++
UTF-8
C++
false
false
1,621
cpp
/****************************************************************************** * QSkinny - Copyright (C) 2016 Uwe Rathmann * SPDX-License-Identifier: BSD-3-Clause *****************************************************************************/ #include "QskBoxSkinlet.h" #include "QskBox.h" QskBoxSkinlet::QskBoxSkinlet( QskSkin* skin ) : Inherited( skin ) { setNodeRoles( { PanelRole } ); } QskBoxSkinlet::~QskBoxSkinlet() { } QRectF QskBoxSkinlet::subControlRect( const QskSkinnable* skinnable, const QRectF& contentsRect, QskAspect::Subcontrol subControl ) const { if ( subControl == QskBox::Panel ) { return contentsRect; } return Inherited::subControlRect( skinnable, contentsRect, subControl ); } QSGNode* QskBoxSkinlet::updateSubNode( const QskSkinnable* skinnable, quint8 nodeRole, QSGNode* node ) const { const auto box = static_cast< const QskBox* >( skinnable ); switch ( nodeRole ) { case PanelRole: { if ( !box->hasPanel() ) return nullptr; return updateBoxNode( skinnable, node, QskBox::Panel ); } } return Inherited::updateSubNode( skinnable, nodeRole, node ); } QSizeF QskBoxSkinlet::sizeHint( const QskSkinnable* skinnable, Qt::SizeHint which, const QSizeF& constraint ) const { const auto box = static_cast< const QskBox* >( skinnable ); if ( box->hasPanel() && which == Qt::PreferredSize ) return box->strutSizeHint( QskBox::Panel ); return Inherited::sizeHint( skinnable, which, constraint ); } #include "moc_QskBoxSkinlet.cpp"
[ "Uwe.Rathmann@tigertal.de" ]
Uwe.Rathmann@tigertal.de
f28c5193ca2b140fa23ef4e0937c8c5b0d7ef702
2c47c8f763c8b71fd26a8cd97c529391d1c01a22
/src/vlCore/AABB.hpp
5f2851ed26413e628bf98a24502bb25bfa9f2879
[ "BSD-2-Clause" ]
permissive
MicBosi/VisualizationLibrary
6780a30431085397ce1de4e8d57e618da5585408
d2a0e321288152008957e29a0bc270ad192f75be
refs/heads/master
2023-08-24T15:10:28.381277
2022-01-04T21:48:24
2022-01-04T21:48:24
32,726,740
324
92
NOASSERTION
2023-08-04T09:18:11
2015-03-23T10:57:58
C++
UTF-8
C++
false
false
9,211
hpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2020, Michele Bosi */ /* 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. */ /* */ /* 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 AABB_INCLUDE_ONCE #define AABB_INCLUDE_ONCE #include <vlCore/Vector3.hpp> #include <vlCore/Matrix4.hpp> namespace vl { //----------------------------------------------------------------------------- // AABB //----------------------------------------------------------------------------- /** The AABB class implements an axis-aligned bounding box using vl::real precision. */ class VLCORE_EXPORT AABB { public: /** Constructs a null AABB. */ AABB(); /** Constructs an AABB large enough to contain a sphere with the specified \p radius and \p center. */ AABB( const vec3& center, real radius ); /** Constructs an AABB large enough to contain the two specified points and enlarged by the amount specified by \p displace. */ AABB( const vec3& pt1, const vec3& pt2, real displace=0); /** Sets ths AABB as null, that is, empty. */ void setNull() { mMin = 1; mMax = -1; } /** Returns true if the AABB is null. */ bool isNull() const { return mMin.x() > mMax.x() || mMin.y() > mMax.y() || mMin.z() > mMax.z(); } /** Returns true if the AABB contains a single point, that is, if the min and max corners of the AABB are equal. */ bool isPoint() const { return mMin == mMax; } /** Enlarges the AABB in all directions by \p displace amount. As a result every edge of the AABB will be \p displace*2 longer. */ void enlarge(real displace); /** Returns true if an AABB intersects with the given AABB. */ bool intersects(const AABB & bb) const; /** Clips the position of the given \p p point to be inside an AABB. */ vec3 clip(const vec3& p, bool clipx=true, bool clipy=true, bool clipz=true) const; /** Returns true if the given point is inside the AABB. This method allows you to restrict the test to any of the x, y, z axes. */ bool isInside(const vec3& p, bool clipx, bool clipy, bool clipz) const; /** Returns true if the given point is inside the AABB. */ bool isInside(const vec3& p) const; /** Returns the width of the AABB computed as max.x - min.x */ real width() const; /** Returns the height of the AABB computed as max.y - min.y */ real height() const; /** Returns the depth of the AABB computed as max.z - min.z */ real depth() const; /** Returns true if two AABB are identical. */ bool operator==(const AABB& aabb) const { return mMin == aabb.mMin && mMax == aabb.mMax; } /** Returns true if two AABB are not identical. */ bool operator!=(const AABB& aabb) const { return !operator==(aabb); } /** Returns an AABB which contains the two source AABB. */ AABB operator+(const AABB& aabb) const; /** Enlarges (if necessary) an AABB so that it contains the given AABB. */ AABB& operator+=(const AABB& other) { *this = *this + other; return *this; } /** Returns an AABB which contains the source AABB and the given point. */ AABB operator+(const vec3& p) { AABB aabb = *this; aabb += p; return aabb; } /** Enlarges (if necessary) an AABB to contain the given point. */ const AABB& operator+=(const vec3& p) { addPoint(p); return *this; } /** Returns the center of the AABB. */ vec3 center() const; /** Returns the longest dimension of the AABB. */ real longestSideLength() const { real side = width(); if (height() > side) side = height(); if (depth() > side) side = depth(); return side; } /** Updates the AABB to contain the given point. The point can represent a sphere if \p radius > 0. */ void addPoint(const vec3& p, real radius); /** Updates the AABB to contain the given point. */ void addPoint(const vec3& p) { if (isNull()) { mMax = p; mMin = p; return; } if ( mMax.x() < p.x() ) mMax.x() = p.x(); if ( mMax.y() < p.y() ) mMax.y() = p.y(); if ( mMax.z() < p.z() ) mMax.z() = p.z(); if ( mMin.x() > p.x() ) mMin.x() = p.x(); if ( mMin.y() > p.y() ) mMin.y() = p.y(); if ( mMin.z() > p.z() ) mMin.z() = p.z(); } /** Transforms an AABB by the given matrix and returns it into the \p out parameter. */ void transformed(AABB& out, const mat4& mat) const { out.setNull(); if ( !isNull() ) { out.addPoint( mat * vec3(minCorner().x(), minCorner().y(), minCorner().z()) ); out.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), minCorner().z()) ); out.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), minCorner().z()) ); out.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), minCorner().z()) ); out.addPoint( mat * vec3(minCorner().x(), minCorner().y(), maxCorner().z()) ); out.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), maxCorner().z()) ); out.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), maxCorner().z()) ); out.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), maxCorner().z()) ); } } /** Returns the AABB transformed by the given matrix. */ AABB transformed(const mat4& mat) const { AABB aabb; transformed(aabb, mat); return aabb; } /** Returns the corner of the AABB with the minimum x y z coordinates. */ const vec3& minCorner() const { return mMin; } /** Returns the corner of the AABB with the maximum x y z coordinates. */ const vec3& maxCorner() const { return mMax; } /** Sets the corner of the AABB with the minimum x y z coordinates. */ void setMinCorner(real x, real y, real z) { mMin.x() = x; mMin.y() = y; mMin.z() = z; } /** Sets the corner of the AABB with the minimum x y z coordinates. */ void setMinCorner(const vec3& v) { mMin = v; } /** Sets the corner of the AABB with the maximum x y z coordinates. */ void setMaxCorner(real x, real y, real z) { mMax.x() = x; mMax.y() = y; mMax.z() = z; } /** Sets the corner of the AABB with the maximum x y z coordinates. */ void setMaxCorner(const vec3& v) { mMax = v; } /** Returns the volume of the AABB. */ real volume() const { return width() * height() * depth(); } protected: vec3 mMin; vec3 mMax; }; } #endif
[ "hello@michelebosi.com" ]
hello@michelebosi.com
d6d65a8c88f5f79b5a23bd5d24e9d80eb29fe17d
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/ITK_include/itkSimilarity2DTransform.h
ab05d6686a8f6ecce5d3f8a0d3601140f9bc5e4b
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
8,297
h
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 __itkSimilarity2DTransform_h #define __itkSimilarity2DTransform_h #include <iostream> #include "itkRigid2DTransform.h" namespace itk { /** \class Similarity2DTransform * \brief Similarity2DTransform of a vector space (e.g. space coordinates) * * This transform applies a homogenous scale and rigid transform in * 2D space. The transform is specified as a scale and rotation around * a arbitrary center and is followed by a translation. * given one angle for rotation, a homogeneous scale and a 2D offset for translation. * * The parameters for this transform can be set either using * individual Set methods or in serialized form using * SetParameters() and SetFixedParameters(). * * The serialization of the optimizable parameters is an array of 3 elements * ordered as follows: * p[0] = scale * p[1] = angle * p[2] = x component of the translation * p[3] = y component of the translation * * The serialization of the fixed parameters is an array of 2 elements * ordered as follows: * p[0] = x coordinate of the center * p[1] = y coordinate of the center * * Access methods for the center, translation and underlying matrix * offset vectors are documented in the superclass MatrixOffsetTransformBase. * * Access methods for the angle are documented in superclass Rigid2DTransform. * * \sa Transform * \sa MatrixOffsetTransformBase * \sa Rigid2DTransform * * \ingroup ITKTransform */ template< typename TScalar = double > // Data type for scalars (float or double) class Similarity2DTransform : public Rigid2DTransform< TScalar > { public: /** Standard class typedefs. */ typedef Similarity2DTransform Self; typedef Rigid2DTransform< TScalar > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** New macro for creation of through a Smart Pointer. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(Similarity2DTransform, Rigid2DTransform); /** Dimension of parameters. */ itkStaticConstMacro(SpaceDimension, unsigned int, 2); itkStaticConstMacro(InputSpaceDimension, unsigned int, 2); itkStaticConstMacro(OutputSpaceDimension, unsigned int, 2); itkStaticConstMacro(ParametersDimension, unsigned int, 4); /** Scalar type. */ typedef typename Superclass::ScalarType ScalarType; typedef TScalar ScaleType; /** Parameters type. */ typedef typename Superclass::ParametersType ParametersType; typedef typename Superclass::ParametersValueType ParametersValueType; /** Jacobian type. */ typedef typename Superclass::JacobianType JacobianType; /** Offset type. */ typedef typename Superclass::OffsetType OffsetType; typedef typename Superclass::OffsetValueType OffsetValueType; /** Matrix type. */ typedef typename Superclass::MatrixType MatrixType; typedef typename Superclass::MatrixValueType MatrixValueType; /** Point type. */ typedef typename Superclass::InputPointType InputPointType; typedef typename Superclass::OutputPointType OutputPointType; /** Vector type. */ typedef typename Superclass::InputVectorType InputVectorType; typedef typename Superclass::OutputVectorType OutputVectorType; /** CovariantVector type. */ typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; /** VnlVector type. */ typedef typename Superclass::InputVnlVectorType InputVnlVectorType; typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; /** Base inverse transform type. This type should not be changed to the * concrete inverse transform type or inheritance would be lost. */ typedef typename Superclass::InverseTransformBaseType InverseTransformBaseType; typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; /** Set the Scale part of the transform. */ void SetScale(ScaleType scale); itkGetConstReferenceMacro(Scale, ScaleType); /** Set the transformation from a container of parameters * This is typically used by optimizers. * There are 4 parameters. The first one represents the * scale, the second represents the angle of rotation * and the last two represent the translation. * The center of rotation is fixed. * * \sa Transform::SetParameters() * \sa Transform::SetFixedParameters() */ void SetParameters(const ParametersType & parameters); /** Get the parameters that uniquely define the transform * This is typically used by optimizers. * There are 4 parameters. The first one represents the * scale, the second represents the angle of rotation, * and the last two represent the translation. * The center of rotation is fixed. * * \sa Transform::GetParameters() * \sa Transform::GetFixedParameters() */ const ParametersType & GetParameters(void) const; /** This method computes the Jacobian matrix of the transformation * at a given input point. */ virtual void ComputeJacobianWithRespectToParameters( const InputPointType & p, JacobianType & jacobian) const; /** Set the transformation to an identity. */ virtual void SetIdentity(void); /** * This method creates and returns a new Similarity2DTransform object * which is the inverse of self. */ void CloneInverseTo(Pointer & newinverse) const; /** Get an inverse of this transform. */ bool GetInverse(Self *inverse) const; /** Return an inverse of this transform. */ virtual InverseTransformBasePointer GetInverseTransform() const; /** * This method creates and returns a new Similarity2DTransform object * which has the same parameters. */ void CloneTo(Pointer & clone) const; /** * Set the rotation Matrix of a Similarity 2D Transform * * This method sets the 2x2 matrix representing a similarity * transform. The Matrix is expected to be a valid * similarity transform with a certain tolerance. * * \warning This method will throw an exception if the matrix * provided as argument is not valid. * * \sa MatrixOffsetTransformBase::SetMatrix() * */ virtual void SetMatrix(const MatrixType & matrix); protected: Similarity2DTransform(unsigned int outputSpaceDimension, unsigned int parametersDimension); Similarity2DTransform(unsigned int parametersDimension); Similarity2DTransform(); ~Similarity2DTransform() { } void PrintSelf(std::ostream & os, Indent indent) const; /** Compute matrix from angle and scale. This is used in Set methods * to update the underlying matrix whenever a transform parameter * is changed. */ virtual void ComputeMatrix(void); /** Compute the angle and scale from the matrix. This is used to compute * transform parameters from a given matrix. This is used in * MatrixOffsetTransformBase::Compose() and * MatrixOffsetTransformBase::GetInverse(). */ virtual void ComputeMatrixParameters(void); /** Set the scale without updating underlying variables. */ void SetVarScale(ScaleType scale) { m_Scale = scale; } private: Similarity2DTransform(const Self &); // purposely not implemented void operator=(const Self &); // purposely not implemented ScaleType m_Scale; }; // class Similarity2DTransform } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkSimilarity2DTransform.hxx" #endif #endif /* __itkSimilarity2DTransform_h */
[ "amos.sironi@gmail.com" ]
amos.sironi@gmail.com
36547b859172d78700f582aa85735dc607605ec1
89514fc56df1db2074b1dc79ab35d775e9605f5e
/Test/MainMenu.h
f5b847bed354e8263b491e722a164403ba322fd0
[]
no_license
EthanShimooka/BAA
aa4117be9944b61553fd45b14b709670d7ab1716
49e5cd4ef608d9f630b03edaa8912632087986f0
refs/heads/master
2021-01-18T22:48:39.371732
2016-06-04T07:20:36
2016-06-04T07:20:36
49,625,246
6
2
null
2016-06-04T07:20:36
2016-01-14T05:36:26
C++
UTF-8
C++
false
false
416
h
#pragma once #include "Scene.h" class MainMenu : public Scene { public: MainMenu(); ~MainMenu(); int runScene(); private: void createButtons(); int checkButtons(); void removeButtons(); //int konamiCode[10]; std::vector<int> *konamiCode;// (10, 0); int konamiIndex; SystemGameObjectQueue sysQueue; ButtonObjectFactory bFactory; GameObject* playButt; GameObject* quitButt; void checkKonami(); };
[ "sohbati.pourya@gmail.com" ]
sohbati.pourya@gmail.com
bce9019bbc2f737c2b58ef076f05f1af53d85619
73ee941896043f9b3e2ab40028d24ddd202f695f
/external/chromium_org/ui/views/widget/tooltip_manager_aura.h
dd4b5ade439bdc948314dd5ed2ce76b6a3fb3ce9
[ "BSD-3-Clause" ]
permissive
CyFI-Lab-Public/RetroScope
d441ea28b33aceeb9888c330a54b033cd7d48b05
276b5b03d63f49235db74f2c501057abb9e79d89
refs/heads/master
2022-04-08T23:11:44.482107
2016-09-22T20:15:43
2016-09-22T20:15:43
58,890,600
5
3
null
null
null
null
UTF-8
C++
false
false
1,337
h
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_ #define UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_ #include "base/compiler_specific.h" #include "base/strings/string16.h" #include "ui/gfx/point.h" #include "ui/views/widget/tooltip_manager.h" namespace aura { class RootWindow; class Window; } namespace views { class Widget; // TooltipManager implementation for Aura. class TooltipManagerAura : public TooltipManager { public: TooltipManagerAura(aura::Window* window, Widget* widget); virtual ~TooltipManagerAura(); // TooltipManager. virtual void UpdateTooltip() OVERRIDE; virtual void TooltipTextChanged(View* view) OVERRIDE; virtual void ShowKeyboardTooltip(View* view) OVERRIDE; virtual void HideKeyboardTooltip() OVERRIDE; private: View* GetViewUnderPoint(const gfx::Point& point); void UpdateTooltipForTarget(View* target, const gfx::Point& point, aura::RootWindow* root_window); aura::Window* window_; Widget* widget_; string16 tooltip_text_; DISALLOW_COPY_AND_ASSIGN(TooltipManagerAura); }; } // namespace views #endif // UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_
[ "ProjectRetroScope@gmail.com" ]
ProjectRetroScope@gmail.com
11f267f7be78b3439ab98cdd7a9c04244b281654
1b60b1776df95e5769c868927840acf813fdd4f0
/beginner/Selection_Test_1.cpp
a878f9c6ffa410a86bf5c96530df4cbdec8e061e
[]
no_license
paolocarrara/uri
6d6bd6a06335b8a0ca9cf0278c40e4772a886ca1
3cd7f291a7dffcbeba85cf28015351a3863f0f5b
refs/heads/master
2020-06-04T07:44:14.766159
2014-10-07T18:48:06
2014-10-07T18:48:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
#include <stdio.h> int main (void) { int a, b, c, d; int ok = 0; scanf ("%i %i %i %i", &a, &b, &c, &d); if ( ( b>c ) && ( d>a ) && ( (c+d)>(a+b) ) && ( c>0 ) && ( d>0 ) && ( a%2 == 0 ) ) ok = 1; if (ok) printf ("Valores aceitos\n"); else printf ("Valores nao aceitos\n"); return 0; }
[ "paolocarraratux@gmail.com" ]
paolocarraratux@gmail.com
18fda9d340d1f82a59f7b9591ecf3f7c214ddcd7
76bda60bb20d6e400d5443dcbcf1ff370350df3e
/fiveDchess.cc
1463f5adc01de09be97f174a66ac254259c7e1f5
[]
no_license
mikezom/fiveDchess-cpp
1e9afd39db12aa7533f221f883d475237fbb77d4
5a2fed9a45a5fe9a7630ea30c688bb134f66e8cc
refs/heads/master
2023-01-20T13:40:42.280849
2020-11-30T17:53:28
2020-11-30T17:53:28
316,140,058
4
0
null
null
null
null
UTF-8
C++
false
false
4,860
cc
#include "fiveDchess.h" FiveDChess::FiveDChess(std::string w_name, std::string b_name){ white_name_ = w_name; black_name_ = b_name; now_playing_ = white; furthest_time_ = 1; furthest_multiverse_ = 0; } Node* FiveDChess::get_root(){ Node *temp = &root_; return temp; } Node* FiveDChess::get_node(int time, int multiverse, Node* root){ // search the whole tree to find correct node // if unable to find node, return NULL Node *temp = root; if(temp == NULL) return NULL; if(temp->get_chessboard().get_time() == time && temp->get_chessboard().get_multiverse() == multiverse){ return temp; } else { for(int i = 0; i < root->get_child().size(); i++){ if((temp = get_node(time, multiverse, root->get_child()[i])) != NULL){ return temp; } } } return NULL; } Chessboard FiveDChess::get_board(int time, int multiverse){ // search the whole tree to find correct chessboard return get_node(time, multiverse, get_root())->get_chessboard(); } Piece FiveDChess::get_piece(Position position){ return get_board(position.time, position.multiverse).get_piece(position.row, position.column); } Action FiveDChess::action_parser(std::string ac){ char* temp; strcpy(temp, ac.c_str()); Position new_start_position = {1, 1, 0, 0}; Position new_end_position = {3, 1, 0, 0}; Action new_action = {w_pawn, new_start_position, new_end_position, white}; return new_action; } bool FiveDChess::is_valid(Action action){ // Check if the piece is correct if(get_piece(action.start_position) != action.piece_to_move) return false; // Check if start position and end position are in bound if(action.start_position.column > 7 || action.start_position.column < 0) return false; if(action.start_position.row > 7 || action.start_position.row < 0) return false; if(action.end_position.column > 7 || action.end_position.column < 0) return false; if(action.end_position.row > 7 || action.end_position.row < 0) return false; // Check if the color is correct if(action.player == white){ if(action.piece_to_move < 7) return false; } else { if(action.piece_to_move > 6 || action.piece_to_move == 0) return false; } // TODO: rules of each pieces // TODO: start position need to be valid (board need to be active) return true; } void FiveDChess::move(Action action){ if(is_valid(action)){ // TODO: Check if is_check after the move // Create a new node int end_time = action.end_position.time; int end_multiverse = action.end_position.multiverse; Node* new_node = new Node(get_board(end_time, end_multiverse)); if(action.start_position.time == action.end_position.time && action.start_position.multiverse == action.end_position.multiverse){ // not time traveling new_node->get_chessboard().add_piece(action.piece_to_move, action.end_position.row, action.end_position.column); new_node->get_chessboard().remove_piece(action.start_position.row, action.start_position.column); new_node->get_chessboard().change_player(); } new_node->get_chessboard().set_time(end_time + 1); // add the new node to the child get_node(end_time, end_multiverse, get_root())->add_child(new_node); // set original board to inactive // TODO: check condition to increment max time and multiverse increment_furthest_time(); } else { printf("Action invalid!\n"); } } void FiveDChess::submit(){ // TODO: already move necessary moves if(now_playing_ == white){ now_playing_ = black; } else { now_playing_ = white; ++turn_; } } void FiveDChess::print(){ // print the whole tree printf("white name: %s\n", white_name_.c_str()); printf("black name: %s\n", black_name_.c_str()); for(int multiverse = furthest_multiverse_; multiverse >= 0; --multiverse){ for(int time = 0; time < furthest_time_; ++time){ if(get_node(time, multiverse, get_root()) != NULL){ std::cout << "╔" << time << "," << multiverse << "═════╗"; } else { std::cout << " "; } } std::cout << std::endl; for(int row = 7; row >= 0; --row){ for(int time = 0; time < furthest_time_; ++time){ if(get_node(time, multiverse, get_root()) != NULL){ std::cout << "║"; get_node(time, multiverse, get_root())->get_chessboard().print_row(row); std::cout << "║"; } else { std::cout << " "; } } std::cout << std::endl; } for(int time = 0; time < furthest_time_; ++time){ if(get_node(time, multiverse, get_root()) != NULL){ std::cout << "╚════════╝"; } else { std::cout << " "; } } std::cout << std::endl; } }
[ "wanxx201@umn.edu" ]
wanxx201@umn.edu
20471eb6b9e2a30bb796bbfba279132d946d4959
a963c60751372f4c2381647ff4fb979ee377d5eb
/dictionarylearningbox/kSVD/kSVD.h
9b77945e509090bd30c9be0b2362f8cd961a0074
[]
no_license
trungmanhhuynh/LCKSVD_faceRecognition
f1cb5bd7fd47577d939baae419e516c57d9a2a35
286027c24df9faf6126f7a9f0d89ebc5699fb2e2
refs/heads/master
2021-01-21T23:28:43.979672
2017-06-23T22:36:52
2017-06-23T22:36:52
95,244,614
0
0
null
null
null
null
UTF-8
C++
false
false
2,226
h
#include <iostream> #include <opencv2/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "config.h" #ifndef KSVD_H #define KSVD_H struct kSVDParameters{ int iterations ; int nAtoms ; //number of atoms of dictionary int featureSize ; //number of rows of dictionary int debug ; int sparsityThres; }; //********************************************************* // INIT DICTIONARY MATRIX // We initialize dictionary by select randomly 441 patches [8x8] // from the training patches // Input: // + Training patches // Output: // + D [featureDim x nInputs] = [64 x 500] // + D is stored in collum vector (1D) // ***************************************************** std::vector<float> kSVD_initialize_dictionary(const std::vector<float> trainPatches, kSVDParameters param); //*************************************************************************** // * Updating dictionary using K-SVD Algorithm // Input + inputData (nInput x featureSize) // + sparseCode (nInput x dictionarySize) // + dictioanry (dictionarySize x featureSIze) // +atomUsedbyInput // Output + dictionary (dictionarySIze x featureSize) // * ************************************************************************ void kSVD_update_dictionary(std::vector<float> inputData,std::vector<float> &sparseCode, std::vector<float> &dictionary, kSVDParameters param) ; //*************************************************************** // * kSVD algorithm // * CPU version // * ************************************************************** void kSVD(std::vector<float> &sparseCode, std::vector<float> &dictionary, std::vector<float> inputData, kSVDParameters param); //************************************************************ // Compute resconstruction error ||Y -DX|| // Input: + InputData Y [featureSize * nInput] // + SparseCode X [DicSize * nInput // + Dictionary D [featureSize * DicSize] //************************************************************ float kSVD_compute_rescontruction_error(std::vector<float> Y,std::vector<float> D,std::vector<float> X, kSVDParameters param) ; #endif
[ "trungmanhhuynh@users.noreply.github.com" ]
trungmanhhuynh@users.noreply.github.com
6042c2144800d10344fd5c99180321a0b063f13c
272274a37c6f4ea031dea803cf8fc8ee689ac471
/components/viz/service/display_embedder/gpu_display_provider.cc
7cf787f31dc5398df5a9d4b58f652ad1e4f57510
[ "BSD-3-Clause" ]
permissive
zjh19861014/chromium
6db9890f3b2981df3e8a0a56883adc93f6761fd5
8d48b756239d336d8724f8f593a7b22959c506b4
refs/heads/master
2023-01-09T06:34:30.549622
2019-04-13T06:55:11
2019-04-13T06:55:11
181,134,794
1
0
NOASSERTION
2019-04-13T07:12:06
2019-04-13T07:12:06
null
UTF-8
C++
false
false
13,537
cc
// Copyright 2017 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 "components/viz/service/display_embedder/gpu_display_provider.h" #include <utility> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/threading/thread_task_runner_handle.h" #include "cc/base/switches.h" #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/service/display/display.h" #include "components/viz/service/display/display_scheduler.h" #include "components/viz/service/display_embedder/gl_output_surface.h" #include "components/viz/service/display_embedder/gl_output_surface_offscreen.h" #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/display_embedder/skia_output_surface_impl.h" #include "components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h" #include "components/viz/service/display_embedder/software_output_surface.h" #include "components/viz/service/display_embedder/viz_process_context_provider.h" #include "components/viz/service/gl/gpu_service_impl.h" #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h" #include "gpu/command_buffer/client/shared_memory_limits.h" #include "gpu/command_buffer/service/image_factory.h" #include "gpu/command_buffer/service/mailbox_manager_factory.h" #include "gpu/config/gpu_finch_features.h" #include "gpu/ipc/command_buffer_task_executor.h" #include "gpu/ipc/common/surface_handle.h" #include "gpu/ipc/service/gpu_channel_manager_delegate.h" #include "gpu/ipc/service/image_transport_surface.h" #include "ui/base/ui_base_switches.h" #include "ui/gl/gl_context.h" #include "ui/gl/init/gl_factory.h" #if defined(OS_WIN) #include "components/viz/service/display_embedder/gl_output_surface_win.h" #include "components/viz/service/display_embedder/software_output_device_win.h" #endif #if defined(OS_ANDROID) #include "components/viz/service/display_embedder/gl_output_surface_android.h" #include "components/viz/service/display_embedder/gl_output_surface_buffer_queue_android.h" #endif #if defined(OS_MACOSX) #include "components/viz/service/display_embedder/gl_output_surface_mac.h" #include "components/viz/service/display_embedder/software_output_device_mac.h" #include "ui/base/cocoa/remote_layer_api.h" #endif #if defined(USE_X11) #include "components/viz/service/display_embedder/software_output_device_x11.h" #endif #if defined(USE_OZONE) #include "components/viz/service/display_embedder/gl_output_surface_ozone.h" #include "components/viz/service/display_embedder/software_output_device_ozone.h" #include "ui/ozone/public/ozone_platform.h" #include "ui/ozone/public/platform_window_surface.h" #include "ui/ozone/public/surface_factory_ozone.h" #include "ui/ozone/public/surface_ozone_canvas.h" #endif namespace viz { GpuDisplayProvider::GpuDisplayProvider( uint32_t restart_id, GpuServiceImpl* gpu_service_impl, gpu::CommandBufferTaskExecutor* task_executor, gpu::GpuChannelManagerDelegate* gpu_channel_manager_delegate, std::unique_ptr<gpu::GpuMemoryBufferManager> gpu_memory_buffer_manager, gpu::ImageFactory* image_factory, ServerSharedBitmapManager* server_shared_bitmap_manager, bool headless, bool wait_for_all_pipeline_stages_before_draw) : restart_id_(restart_id), gpu_service_impl_(gpu_service_impl), task_executor_(task_executor), gpu_channel_manager_delegate_(gpu_channel_manager_delegate), gpu_memory_buffer_manager_(std::move(gpu_memory_buffer_manager)), image_factory_(image_factory), server_shared_bitmap_manager_(server_shared_bitmap_manager), task_runner_(base::ThreadTaskRunnerHandle::Get()), headless_(headless), wait_for_all_pipeline_stages_before_draw_( wait_for_all_pipeline_stages_before_draw) {} GpuDisplayProvider::GpuDisplayProvider( uint32_t restart_id, ServerSharedBitmapManager* server_shared_bitmap_manager, bool headless, bool wait_for_all_pipeline_stages_before_draw) : GpuDisplayProvider(restart_id, /*gpu_service_impl=*/nullptr, /*task_executor=*/nullptr, /*gpu_channel_manager_delegate=*/nullptr, /*gpu_memory_buffer_manager=*/nullptr, /*image_factory=*/nullptr, server_shared_bitmap_manager, headless, wait_for_all_pipeline_stages_before_draw) {} GpuDisplayProvider::~GpuDisplayProvider() = default; std::unique_ptr<Display> GpuDisplayProvider::CreateDisplay( const FrameSinkId& frame_sink_id, gpu::SurfaceHandle surface_handle, bool gpu_compositing, mojom::DisplayClient* display_client, ExternalBeginFrameSource* external_begin_frame_source, SyntheticBeginFrameSource* synthetic_begin_frame_source, const RendererSettings& renderer_settings, bool send_swap_size_notifications) { BeginFrameSource* begin_frame_source = synthetic_begin_frame_source ? static_cast<BeginFrameSource*>(synthetic_begin_frame_source) : static_cast<BeginFrameSource*>(external_begin_frame_source); // TODO(penghuang): Merge two output surfaces into one when GLRenderer and // software compositor is removed. std::unique_ptr<OutputSurface> output_surface; SkiaOutputSurface* skia_output_surface = nullptr; if (!gpu_compositing) { output_surface = std::make_unique<SoftwareOutputSurface>( CreateSoftwareOutputDeviceForPlatform(surface_handle, display_client), synthetic_begin_frame_source); } else if (renderer_settings.use_skia_renderer || renderer_settings.use_skia_renderer_non_ddl) { #if defined(OS_MACOSX) || defined(OS_WIN) // TODO(penghuang): Support SkiaRenderer for all platforms. NOTIMPLEMENTED(); return nullptr; #else if (renderer_settings.use_skia_renderer_non_ddl) { DCHECK_EQ(gl::GetGLImplementation(), gl::kGLImplementationEGLGLES2) << "SkiaRendererNonDDL is only supported with GLES2."; auto gl_surface = gpu::ImageTransportSurface::CreateNativeSurface( nullptr, surface_handle, gl::GLSurfaceFormat()); if (!shared_context_state_) { auto gl_share_group = base::MakeRefCounted<gl::GLShareGroup>(); auto gl_context = gl::init::CreateGLContext( gl_share_group.get(), gl_surface.get(), gl::GLContextAttribs()); gl_context->MakeCurrent(gl_surface.get()); shared_context_state_ = base::MakeRefCounted<gpu::SharedContextState>( std::move(gl_share_group), gl_surface, std::move(gl_context), false /* use_virtualized_gl_contexts */, base::DoNothing::Once(), nullptr /* vulkan_context_provider */); shared_context_state_->InitializeGrContext( gpu::GpuDriverBugWorkarounds(), nullptr /* gr_shader_cache */); mailbox_manager_ = gpu::gles2::CreateMailboxManager( gpu_service_impl_->gpu_preferences()); DCHECK(mailbox_manager_->UsesSync()); } output_surface = std::make_unique<SkiaOutputSurfaceImplNonDDL>( std::move(gl_surface), shared_context_state_, mailbox_manager_.get(), gpu_service_impl_->shared_image_manager(), gpu_service_impl_->sync_point_manager(), true /* need_swapbuffers_ack */); } else { output_surface = std::make_unique<SkiaOutputSurfaceImpl>( gpu_service_impl_, surface_handle, synthetic_begin_frame_source, renderer_settings); } skia_output_surface = static_cast<SkiaOutputSurface*>(output_surface.get()); #endif } else { DCHECK(task_executor_); scoped_refptr<VizProcessContextProvider> context_provider; // Retry creating and binding |context_provider| on transient failures. gpu::ContextResult context_result = gpu::ContextResult::kTransientFailure; while (context_result != gpu::ContextResult::kSuccess) { // We are about to exit the GPU process so don't try to create a context. // It will be recreated after the GPU process restarts. The same check // also happens on the GPU thread before the context gets initialized // there. If GPU process starts to exit after this check but before // context initialization we'll encounter a transient error, loop and hit // this check again. if (gpu_channel_manager_delegate_->IsExiting()) return nullptr; context_provider = base::MakeRefCounted<VizProcessContextProvider>( task_executor_, surface_handle, gpu_memory_buffer_manager_.get(), image_factory_, gpu_channel_manager_delegate_, renderer_settings); context_result = context_provider->BindToCurrentThread(); if (IsFatalOrSurfaceFailure(context_result)) { #if defined(OS_ANDROID) display_client->OnFatalOrSurfaceContextCreationFailure(context_result); #elif defined(OS_CHROMEOS) || defined(IS_CHROMECAST) // TODO(kylechar): Chrome OS can't disable GPU compositing. This needs // to be handled similar to Android. CHECK(false); #else gpu_service_impl_->DisableGpuCompositing(); #endif return nullptr; } } if (surface_handle == gpu::kNullSurfaceHandle) { output_surface = std::make_unique<GLOutputSurfaceOffscreen>( std::move(context_provider), synthetic_begin_frame_source); } else if (context_provider->ContextCapabilities().surfaceless) { #if defined(USE_OZONE) output_surface = std::make_unique<GLOutputSurfaceOzone>( std::move(context_provider), surface_handle, synthetic_begin_frame_source, gpu_memory_buffer_manager_.get(), renderer_settings.overlay_strategies); #elif defined(OS_MACOSX) output_surface = std::make_unique<GLOutputSurfaceMac>( std::move(context_provider), surface_handle, synthetic_begin_frame_source, gpu_memory_buffer_manager_.get(), renderer_settings.allow_overlays); #elif defined(OS_ANDROID) auto buffer_format = context_provider->UseRGB565PixelFormat() ? gfx::BufferFormat::BGR_565 : gfx::BufferFormat::RGBA_8888; output_surface = std::make_unique<GLOutputSurfaceBufferQueueAndroid>( std::move(context_provider), surface_handle, synthetic_begin_frame_source, gpu_memory_buffer_manager_.get(), buffer_format); #else NOTREACHED(); #endif } else { #if defined(OS_WIN) const auto& capabilities = context_provider->ContextCapabilities(); const bool use_overlays_for_sw_protected_video = base::FeatureList::IsEnabled( features::kUseDCOverlaysForSoftwareProtectedVideo); const bool use_overlays = capabilities.dc_layers && (capabilities.use_dc_overlays_for_video || use_overlays_for_sw_protected_video); output_surface = std::make_unique<GLOutputSurfaceWin>( std::move(context_provider), synthetic_begin_frame_source, use_overlays); #elif defined(OS_ANDROID) output_surface = std::make_unique<GLOutputSurfaceAndroid>( std::move(context_provider), synthetic_begin_frame_source); #else output_surface = std::make_unique<GLOutputSurface>( std::move(context_provider), synthetic_begin_frame_source); #endif } } // If we need swap size notifications tell the output surface now. output_surface->SetNeedsSwapSizeNotifications(send_swap_size_notifications); int max_frames_pending = output_surface->capabilities().max_frames_pending; DCHECK_GT(max_frames_pending, 0); auto scheduler = std::make_unique<DisplayScheduler>( begin_frame_source, task_runner_.get(), max_frames_pending, wait_for_all_pipeline_stages_before_draw_); return std::make_unique<Display>( server_shared_bitmap_manager_, renderer_settings, frame_sink_id, std::move(output_surface), std::move(scheduler), task_runner_, skia_output_surface); } uint32_t GpuDisplayProvider::GetRestartId() const { return restart_id_; } std::unique_ptr<SoftwareOutputDevice> GpuDisplayProvider::CreateSoftwareOutputDeviceForPlatform( gpu::SurfaceHandle surface_handle, mojom::DisplayClient* display_client) { if (headless_) return std::make_unique<SoftwareOutputDevice>(); #if defined(OS_WIN) return CreateSoftwareOutputDeviceWinGpu( surface_handle, &output_device_backing_, display_client); #elif defined(OS_MACOSX) return std::make_unique<SoftwareOutputDeviceMac>(task_runner_); #elif defined(OS_ANDROID) // Android does not do software compositing, so we can't get here. NOTREACHED(); return nullptr; #elif defined(USE_OZONE) ui::SurfaceFactoryOzone* factory = ui::OzonePlatform::GetInstance()->GetSurfaceFactoryOzone(); std::unique_ptr<ui::PlatformWindowSurface> platform_window_surface = factory->CreatePlatformWindowSurface(surface_handle); std::unique_ptr<ui::SurfaceOzoneCanvas> surface_ozone = factory->CreateCanvasForWidget(surface_handle); CHECK(surface_ozone); return std::make_unique<SoftwareOutputDeviceOzone>( std::move(platform_window_surface), std::move(surface_ozone)); #elif defined(USE_X11) return std::make_unique<SoftwareOutputDeviceX11>(surface_handle); #endif } } // namespace viz
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0746d5a144a1ed7219710eb6d7669cc496c87cf1
209b328a41e2ea3b40bcd9c96c14f4d4f2893a7c
/src/QtIntermediate05_ExploringQDebug/logger.h
2792a879a66fc27f16017d84488cb68f0ab3f661
[]
no_license
sheraium/CppPractice
0fe8db8456609f8914f0a3d8b36640eb1bc39ab0
0938fdf5ef54780e9d5f09ff46e8a814d2f1b578
refs/heads/master
2023-08-12T05:39:37.667401
2021-10-13T03:09:56
2021-10-13T03:09:56
336,550,865
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
#ifndef LOGGER_H #define LOGGER_H #include <QObject> #include <QDir> #include <QTextStream> #include <QDateTime> #include <QLoggingCategory> class logger : public QObject { Q_OBJECT public: explicit logger(QObject *parent = nullptr); static bool logging; static bool showInConsole; static QString filename; static void attach(); static void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg); signals: }; #endif // LOGGER_H
[ "sheraium@gmail.com" ]
sheraium@gmail.com
3378625d98d4ca3026973b782914854ed181ba0a
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.h
d74c08e016fabfdf82fccd9787e58b147c3ee584
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
3,992
h
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 THIRD_PARTY_BLINK_RENDERER_MODULES_STORAGE_INSPECTOR_DOM_STORAGE_AGENT_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_STORAGE_INSPECTOR_DOM_STORAGE_AGENT_H_ #include "third_party/blink/renderer/core/inspector/inspector_base_agent.h" #include "third_party/blink/renderer/core/inspector/protocol/DOMStorage.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/storage/storage_area.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class InspectedFrames; class MODULES_EXPORT InspectorDOMStorageAgent final : public InspectorBaseAgent<protocol::DOMStorage::Metainfo> { public: explicit InspectorDOMStorageAgent(InspectedFrames*); ~InspectorDOMStorageAgent() override; void Trace(Visitor*) override; void DidDispatchDOMStorageEvent(const String& key, const String& old_value, const String& new_value, StorageArea::StorageType, const SecurityOrigin*); private: void InnerEnable(); // InspectorBaseAgent overrides. void Restore() override; // protocol::Dispatcher::DOMStorageCommandHandler overrides. protocol::Response enable() override; protocol::Response disable() override; protocol::Response clear( std::unique_ptr<protocol::DOMStorage::StorageId>) override; protocol::Response getDOMStorageItems( std::unique_ptr<protocol::DOMStorage::StorageId>, std::unique_ptr<protocol::Array<protocol::Array<String>>>* entries) override; protocol::Response setDOMStorageItem( std::unique_ptr<protocol::DOMStorage::StorageId>, const String& key, const String& value) override; protocol::Response removeDOMStorageItem( std::unique_ptr<protocol::DOMStorage::StorageId>, const String& key) override; protocol::Response FindStorageArea( std::unique_ptr<protocol::DOMStorage::StorageId>, StorageArea*&); std::unique_ptr<protocol::DOMStorage::StorageId> GetStorageId( const SecurityOrigin*, bool is_local_storage); Member<InspectedFrames> inspected_frames_; InspectorAgentState::Boolean enabled_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_STORAGE_INSPECTOR_DOM_STORAGE_AGENT_H_
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
2c11b6abaa068c961c410f2e311d8276fa0258fe
bf4e88770beb734b660680375365172796150301
/LppWeb_Compiler/LppWeb_Compiler/Parser/Statements/statementreturnnode.cpp
e2dcb47cb459c9e78b0cc6d9769de90437748e6c
[]
no_license
Siwady/LppWeb-Compiler
01ddece1e527cae723098bba604e5b34bd571d9a
32c7921696baa3eb5c470cae42840da3431a575f
refs/heads/master
2021-01-21T03:56:10.739218
2015-09-27T04:51:23
2015-09-27T04:51:23
39,653,794
0
0
null
null
null
null
UTF-8
C++
false
false
1,065
cpp
#include "statementreturnnode.h" #include "../../helper.h" #include "../../Semantic/symboltable.h" StatementReturnNode::~StatementReturnNode() { delete Expression; } void StatementReturnNode::Interpret() { SymbolTable::GetInstance()->ReturnValue = Expression->Interpret(); } StatementReturnNode::StatementReturnNode(ExpressionNode *expr, int row, int column) { this->Expression=expr; this->Row=row; this->Column=column; } string StatementReturnNode::ToXML(int i) { string re=Helper::GetIdentation(i)+"<StatementReturn>\n"; re+=Expression->ToXML(i+1); re+=Helper::GetIdentation(i)+"</StatementReturn>\n"; return re; } void StatementReturnNode::ValidateSemantic() { Type* type=Expression->ValidateSemantic(); if (SymbolTable::GetInstance()->ReturnType != nullptr){ if (SymbolTable::GetInstance()->ReturnType->Name != type->Name) { throw SemanticException("Valor de retorno deberia ser de tipo " + SymbolTable::GetInstance()->ReturnType->Name + ",Fila:" + to_string(Row) + ",Columna:" + to_string(Column)); } } }
[ "siwady0908@unitec.edu" ]
siwady0908@unitec.edu
2830694af2abd7b333144261332218a62fd439f3
c4fcddc2c5f0b02bbf3602f6f9b0c89484a2662b
/src/LightInk3D/UI/Button.cpp
6396dfb93108cacd59da8e976515aa0bf11d77cf
[ "MIT" ]
permissive
ternence-li/LightInk3D
a54971ccd50fb15be8a4c019a038655ed9b1b9ea
7b35419d164c9c939359f9106264841dc8c283a2
refs/heads/master
2021-06-11T20:21:44.810389
2017-01-20T09:59:44
2017-01-20T09:59:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,683
cpp
// // Copyright (c) 2008-2016 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Core/Context.h" #include "Input/InputEvents.h" #include "UI/Button.h" #include "UI/UI.h" #include "UI/UIEvents.h" #include "DebugNew.h" namespace Urho3D { extern const char* UI_CATEGORY; Button::Button(Context* context) : BorderImage(context), pressedOffset_(IntVector2::ZERO), pressedChildOffset_(IntVector2::ZERO), repeatDelay_(1.0f), repeatRate_(0.0f), repeatTimer_(0.0f), pressed_(false) { SetEnabled(true); focusMode_ = FM_FOCUSABLE; } Button::~Button() { } void Button::RegisterObject(Context* context) { context->RegisterFactory<Button>(UI_CATEGORY); URHO3D_COPY_BASE_ATTRIBUTES(BorderImage); URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Is Enabled", true); URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Focus Mode", FM_FOCUSABLE); URHO3D_ACCESSOR_ATTRIBUTE("Pressed Image Offset", GetPressedOffset, SetPressedOffset, IntVector2, IntVector2::ZERO, AM_FILE); URHO3D_ACCESSOR_ATTRIBUTE("Pressed Child Offset", GetPressedChildOffset, SetPressedChildOffset, IntVector2, IntVector2::ZERO, AM_FILE); URHO3D_ACCESSOR_ATTRIBUTE("Repeat Delay", GetRepeatDelay, SetRepeatDelay, float, 1.0f, AM_FILE); URHO3D_ACCESSOR_ATTRIBUTE("Repeat Rate", GetRepeatRate, SetRepeatRate, float, 0.0f, AM_FILE); } void Button::Update(float timeStep) { if (!hovering_ && pressed_) SetPressed(false); // Send repeat events if pressed if (pressed_ && repeatRate_ > 0.0f) { repeatTimer_ -= timeStep; if (repeatTimer_ <= 0.0f) { repeatTimer_ += 1.0f / repeatRate_; using namespace Pressed; VariantMap& eventData = GetEventDataMap(); eventData[P_ELEMENT] = this; SendEvent(E_PRESSED, eventData); } } } void Button::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor) { IntVector2 offset(IntVector2::ZERO); if (hovering_ || HasFocus()) offset += hoverOffset_; if (pressed_ || selected_) offset += pressedOffset_; BorderImage::GetBatches(batches, vertexData, currentScissor, offset); } void Button::OnClickBegin(const IntVector2& position, const IntVector2& screenPosition, int button, int buttons, int qualifiers, Cursor* cursor) { if (button == MOUSEB_LEFT) { SetPressed(true); repeatTimer_ = repeatDelay_; hovering_ = true; using namespace Pressed; VariantMap& eventData = GetEventDataMap(); eventData[P_ELEMENT] = this; SendEvent(E_PRESSED, eventData); } } void Button::OnClickEnd(const IntVector2& position, const IntVector2& screenPosition, int button, int buttons, int qualifiers, Cursor* cursor, UIElement* beginElement) { if (pressed_ && button == MOUSEB_LEFT) { SetPressed(false); // If mouse was released on top of the element, consider it hovering on this frame yet (see issue #1453) if (IsInside(screenPosition, true)) hovering_ = true; using namespace Released; VariantMap& eventData = GetEventDataMap(); eventData[P_ELEMENT] = this; SendEvent(E_RELEASED, eventData); } } void Button::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, const IntVector2& deltaPos, int buttons, int qualifiers, Cursor* cursor) { SetPressed(true); } void Button::OnKey(int key, int buttons, int qualifiers) { if (HasFocus() && (key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER || key == KEY_SPACE)) { // Simulate LMB click OnClickBegin(IntVector2(), IntVector2(), MOUSEB_LEFT, 0, 0, 0); OnClickEnd(IntVector2(), IntVector2(), MOUSEB_LEFT, 0, 0, 0, 0); } } void Button::SetPressedOffset(const IntVector2& offset) { pressedOffset_ = offset; } void Button::SetPressedOffset(int x, int y) { pressedOffset_ = IntVector2(x, y); } void Button::SetPressedChildOffset(const IntVector2& offset) { pressedChildOffset_ = offset; } void Button::SetPressedChildOffset(int x, int y) { pressedChildOffset_ = IntVector2(x, y); } void Button::SetRepeat(float delay, float rate) { SetRepeatDelay(delay); SetRepeatRate(rate); } void Button::SetRepeatDelay(float delay) { repeatDelay_ = Max(delay, 0.0f); } void Button::SetRepeatRate(float rate) { repeatRate_ = Max(rate, 0.0f); } void Button::SetPressed(bool enable) { pressed_ = enable; SetChildOffset(pressed_ ? pressedChildOffset_ : IntVector2::ZERO); } }
[ "baisaichen@live.com" ]
baisaichen@live.com
6db5a2f9785e974a1219baaaffcb1d47857358ea
2314d4320b475563e79a66731381c1a76ddf071a
/WVSSSeverity/TrackPoint.h
19fc64704d028b349d1d2ddec4d6b6d7e221dd56
[]
no_license
avppro71/WVSS
6c7eb7c3b2c6f7461172fa7a4d6f45c656a31a56
fe86b7030c57d608f8ea458bccb428fe7a225e75
refs/heads/master
2022-12-14T21:24:12.371845
2020-09-18T09:21:50
2020-09-18T09:21:50
294,733,820
0
0
null
null
null
null
UTF-8
C++
false
false
1,051
h
#pragma once namespace WVSS { class CTrackPoint { public: char m_CallSign[32]; SYSTEMTIME m_CreationTime; SYSTEMTIME m_CreationTimeOrig; LARGE_INTEGER m_CTLE; double m_dLifetime; char m_ACModel[16]; double m_dLatDeg, m_dLongDeg; double m_dAltitude100Ft; short m_nAltitudeM; double m_dAzimuth, m_dAzimuthDeg, m_dAzimuthBack, m_dAzimuthBackDeg; double m_dDistSphere, m_dDistKm; double m_dTimeSpanS; double m_dAveSpeedMS, m_dVSpeedMS; DWORD m_lStartIndex, m_lPoints; bool m_bFirstPoint, m_bLastPoint; short m_nAircraftOrdinal; double m_dAccel; double m_dSpeedMS; double m_dInitialLegSpeedMS; double m_dAttitudeAngleDeg; char m_DepartureAirport[16]; char m_ArrivalAirport[16]; double m_dBankDeg; double m_dWeightKg; double m_dWDRT; double m_dWindSpeedMS; bool m_bInterpolate; double m_dElevation; long m_lTimeShift_s; public: CTrackPoint() { Init(); } void Init() { memset(this, 0, sizeof(CTrackPoint)); m_dWDRT = AVP_BAD_WIND_VALUE; m_dWindSpeedMS = AVP_BAD_WIND_VALUE; } bool operator < (CTrackPoint &p_Pt); }; }
[ "tolstuk71@gmail.com" ]
tolstuk71@gmail.com
ef80223111f60951188a76372ee473a4204daf9c
1c1540c47fc960aae76864a5609d85088122dba8
/include/anfibio_nativo.h
5b7accbc9b1b1dd52e5629dbf6d25f54d5169687
[]
no_license
claudiocsjunior/projetoPetFera
394c33396926c72350678cdf16494d4916f25e32
a3965d966957debd76ed05920cd19628f7185f9a
refs/heads/master
2020-03-22T06:36:16.325423
2018-07-07T09:30:23
2018-07-07T09:30:23
139,645,646
0
0
null
null
null
null
UTF-8
C++
false
false
1,581
h
/** * @file anfibio_nativo.h * @brief Classe responsável por gerenciar os anfibios nativos pertencentes ao PETFera * @author Claudio da Cruz Silva Junior * @since 27/06/2018 * @date 27/06/2018 */ #ifndef _ANFIBIO_NATIVO_H_ /**< Verifica se a variável _ANFIBIO_NATIVO_H_ foi definida*/ #define _ANFIBIO_NATIVO_H_ /**< Define a variável _ANFIBIO_NATIVO_H_*/ #include "anfibio.h" /**< Inclusão da classe anfibio.h*/ #include "nativo.h" /**< Inclusão da classe anfibio.h*/ class AnfibioNativo : public Anfibio, Nativo { public: AnfibioNativo(); /**< Construtor padrão da Classe*/ AnfibioNativo(int id, std::string nome, std::string cientifico, std::string classe, char sexo, float tamanho, std::string natureza, std::string dieta, std::string batismo, Veterinario veterinario, Tratador tratador, int total_mudas, std::string ultima_muda, std::string uf_origem, std::string autorizacao, std::string ibama); ~AnfibioNativo(); /**< Destrutor da Classe*/ /** * @brief Efetua a sobrecarga do operador >> * @param[in] variável para o >> * @param[in] Constante para guardar o objeto * @return valor do cin */ friend istream& operator>>(istream &i, AnfibioNativo &a); /** * @brief Efetua a sobrecarga do operador << * @param[in] variável para o << * @param[in] Constante para guardar o objeto * @return valor do cout */ friend ostream& operator<<(ostream &e, AnfibioNativo &a); /** * @brief Efetua a impressão de dados no formato para arquivo * @return string para impressão */ std::string escreverArquivo(); }; #endif
[ "claudio_junior15@github" ]
claudio_junior15@github
1986fc07fcd34ea5c3ab65f06f891ee41bc73a09
c4aa092e45dc943ed3932a796a0870ce84714500
/Slider/ICatalogStorage.h
63fb9f530f16bba4d27c36bbd7478435a30af97c
[]
no_license
15831944/DevTools
d07897dd7a36afa6d287cac72a54589da15f968d
50723004dc9c705e8f095d6f503beeb4096e4987
refs/heads/master
2022-11-21T05:41:56.927474
2020-07-24T12:30:59
2020-07-24T12:30:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,998
h
#ifndef ICatalogStorage_h #define ICatalogStorage_h #pragma once #include "utl/ErrorHandler.h" #include "utl/FlexPath.h" #include "utl/StructuredStorage.h" #include "ModelSchema.h" #include <hash_set> class CCatalogStorageService; class CImagesModel; class CCachedThumbBitmap; EXTERN_C const IID IID_ICatalogStorage; MIDL_INTERFACE("C5078A69-FF1C-4B13-9202-1EEF0532258D") ICatalogStorage : public IUnknown { public: virtual fs::CStructuredStorage* GetDocStorage( void ) = 0; virtual app::ModelSchema GetDocModelSchema( void ) const = 0; virtual void StoreDocModelSchema( app::ModelSchema docModelSchema ) = 0; virtual const std::tstring& GetPassword( void ) const = 0; virtual void StorePassword( const std::tstring& password ) = 0; virtual void CreateImageArchiveFile( const fs::CPath& docStgPath, CCatalogStorageService* pCatalogSvc ) throws_( CException* ) = 0; virtual bool SavePasswordStream( void ) = 0; virtual bool LoadPasswordStream( void ) = 0; virtual bool LoadAlbumMap( std::tstring* pAlbumMapText ) = 0; // "_Album.sld" stream (with .sld file format) virtual bool SaveAlbumStream( CObject* pAlbumDoc ) = 0; virtual bool LoadAlbumStream( CObject* pAlbumDoc ) = 0; virtual bool EnumerateImages( CImagesModel& rImagesModel ) = 0; virtual CCachedThumbBitmap* LoadThumbnail( const fs::CFlexPath& imageComplexPath ) throws_() = 0; // caller must delete the image }; #include "utl/UI/Thumbnailer_fwd.h" class CCatalogStorageFactory : public CErrorHandler , public fs::IThumbProducer , private utl::noncopyable { CCatalogStorageFactory( void ) : CErrorHandler( utl::CheckMode ) {} ~CCatalogStorageFactory(); public: static CCatalogStorageFactory* Instance( void ); static CComPtr< ICatalogStorage > CreateStorageObject( void ); static bool HasCatalogExt( const TCHAR* pFilePath ); static bool IsVintageCatalog( const TCHAR* pFilePath ); static const TCHAR* GetDefaultExtension( void ) { return s_imageStorageExts[ CatStg_ias ]; } ICatalogStorage* FindStorage( const fs::CPath& docStgPath ) const; CComPtr< ICatalogStorage > AcquireStorage( const fs::CPath& docStgPath, DWORD mode = STGM_READ ); // for password-protected storage reading: also prompts user to verify password, returning NULL if not verified std::auto_ptr< CFile > OpenFlexImageFile( const fs::CFlexPath& flexImagePath, DWORD mode = CFile::modeRead ); // either physical or storage-based image file // fs::IThumbProducer interface virtual bool ProducesThumbFor( const fs::CFlexPath& srcImagePath ) const; virtual CCachedThumbBitmap* ExtractThumb( const fs::CFlexPath& srcImagePath ); virtual CCachedThumbBitmap* GenerateThumb( const fs::CFlexPath& srcImagePath ); private: static bool IsPasswordVerified( const fs::CPath& docStgPath ); static bool HasSameOpenMode( ICatalogStorage* pCatalogStorage, DWORD mode ); private: enum ExtensionType { CatStg_ias, CatStg_cid, CatStg_icf }; static const TCHAR* s_imageStorageExts[]; // file extension for compound-files (".icf") }; class CCatalogPasswordStore : private utl::noncopyable { CCatalogPasswordStore( void ) {} public: static CCatalogPasswordStore* Instance( void ); bool SavePassword( ICatalogStorage* pCatalogStorage ); bool LoadPasswordVerify( ICatalogStorage* pCatalogStorage, std::tstring* pOutPassword = NULL ); bool CacheVerifiedPassword( const std::tstring& password ); bool IsPasswordVerified( const fs::CPath& docStgPath ) const; private: stdext::hash_set< std::tstring > m_verifiedPasswords; }; class CCatalogStorageHost; class CMirrorCatalogSave : public fs::stg::CMirrorStorageSave { public: CMirrorCatalogSave( const fs::CPath& docStgPath, const fs::CPath& oldDocStgPath, CCatalogStorageHost* pStorageHost ) : fs::stg::CMirrorStorageSave( docStgPath, oldDocStgPath ) , m_pStorageHost( pStorageHost ) { ASSERT_PTR( m_pStorageHost ); } protected: virtual bool CloseStorage( void ); private: CCatalogStorageHost* m_pStorageHost; }; #endif // ICatalogStorage_h
[ "phc.2nd@gmail.com" ]
phc.2nd@gmail.com
30585b54af25bacfc5ea286cba4a1f04ead92241
273942207c0c355d9f6c7987008f2881256e505b
/finding second largest element from an array.cpp
7050bb1d397813eaa5a52d9b89d17e29285ba630
[]
no_license
imsashwat/Competitive-coding-handbook
68fffa87a7e64ef68ade8c426096f82ee9c20563
9189029cddb71d36a42b85393dd2ed8f5e836165
refs/heads/master
2020-05-19T11:13:35.715376
2019-05-05T05:56:58
2019-05-05T05:56:58
184,985,383
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
#include<iostream> using namespace std; void arrange(int arr[],int n){ /* Don't write main(). Don't read input, it is passed as function argument. Arrange elements in the array "arr" given as input. Taking input and printing output is handled automatically. */ for(int j=0;j<n;j++) { if(n%2==0) { for(int i=1;i<n;i=i+2) { arr[j]=i; j++; } for(int i=n;i>1;i--) { arr[j]=i; i--; j++; } } else if(n%2==1) { for(int i=1;i<=n;i++) { arr[j]=i; i++; j++; } for(int i=n-1;i>1;i--) { arr[j]=i; i--; j++; } } } } int main() { int arr[10]; int n; cin>>n; arrange(arr,n); }
[ "star1shashwat@gmail.com" ]
star1shashwat@gmail.com
a029769c6764c67143e398131fd394d3af32abc7
5f3ab0477f34e966990aac4987e0b0d8009666df
/src/debug.cpp
0c92575c525e10b67c2bfc01a5b96d02adbadd49
[]
no_license
whj0401/le
12d4080065c2c30b3fa67676a6f84ea9e2275a00
5e41f873db1636b3b0352732dcb3aaca01bf1f48
refs/heads/master
2020-03-19T22:02:00.357323
2018-06-25T01:44:09
2018-06-25T01:44:09
136,957,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,422
cpp
// // Created by whj on 6/13/18. // #include "debug.h" #include "Path.h" namespace le { using namespace std; void print_statement(SgStatement* s) { cout << s->unparseToString() << endl; } void print_err_statement(SgStatement* stmt) { cout << "Unsupported statement: " << endl; cout << stmt->class_name() << " : " << stmt->unparseToString() << endl; } void print_whole_node(SgNode* s, stringstream& ss, unsigned int tab_num) { if(s == nullptr) return; auto list = s->get_traversalSuccessorContainer(); ss << generate_tab(tab_num); ss << s->unparseToString() << " : " << s->class_name() << endl; for(auto i : list) { print_whole_node(i, ss, tab_num + 1); } } void print_whole_node(SgNode* s) { stringstream ss; print_whole_node(s, ss); cout << ss.str() << endl; } void print_err_use_variable_without_declaration(const string &var_name, const Path &path) { cout << "no correspond variable in this path" << endl; cout << "reference name: " << var_name << endl; cout << "path: " << path.to_string() << endl; } void print_warning_function_no_definition(SgFunctionDeclaration* decl) { cout << decl->unparseToString() << " has no definition block!" << endl; } }
[ "huaijinwang95@qq.com" ]
huaijinwang95@qq.com
7c5038908221f711462f0bf0f4f601f6f30020e0
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
/chromium/components/metrics/persisted_logs.h
4d49946c2796eabf77edb51a6d25dc7ea01ba2b6
[ "BSD-3-Clause" ]
permissive
Csineneo/Vivaldi
4eaad20fc0ff306ca60b400cd5fad930a9082087
d92465f71fb8e4345e27bd889532339204b26f1e
refs/heads/master
2022-11-23T17:11:50.714160
2019-05-25T11:45:11
2019-05-25T11:45:11
144,489,531
5
4
BSD-3-Clause
2022-11-04T05:55:33
2018-08-12T18:04:37
null
UTF-8
C++
false
false
5,274
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_METRICS_PERSISTED_LOGS_H_ #define COMPONENTS_METRICS_PERSISTED_LOGS_H_ #include <stddef.h> #include <memory> #include <string> #include <vector> #include "base/logging.h" #include "base/macros.h" #include "base/values.h" #include "components/metrics/log_store.h" class PrefService; namespace metrics { class PersistedLogsMetrics; // Maintains a list of unsent logs that are written and restored from disk. class PersistedLogs : public LogStore { public: // Constructs a PersistedLogs that stores data in |local_state| under the // preference |pref_name|. // Calling code is responsible for ensuring that the lifetime of |local_state| // is longer than the lifetime of PersistedLogs. // // When saving logs to disk, stores either the first |min_log_count| logs, or // at least |min_log_bytes| bytes of logs, whichever is greater. // // If the optional |max_log_size| parameter is non-zero, all logs larger than // that limit will be skipped when writing to disk. // // |signing_key| is used to produce an HMAC-SHA256 signature of the logged // data, which will be uploaded with the log and used to validate data // integrity. PersistedLogs(std::unique_ptr<PersistedLogsMetrics> metrics, PrefService* local_state, const char* pref_name, size_t min_log_count, size_t min_log_bytes, size_t max_log_size, const std::string& signing_key); ~PersistedLogs(); // LogStore: bool has_unsent_logs() const override; bool has_staged_log() const override; const std::string& staged_log() const override; const std::string& staged_log_hash() const override; const std::string& staged_log_signature() const override; void StageNextLog() override; void DiscardStagedLog() override; void PersistUnsentLogs() const override; void LoadPersistedUnsentLogs() override; // Adds a log to the list. void StoreLog(const std::string& log_data); // Delete all logs, in memory and on disk. void Purge(); // Returns the timestamp of the element in the front of the list. const std::string& staged_log_timestamp() const; // The number of elements currently stored. size_t size() const { return list_.size(); } private: // Writes the list to the ListValue. void WriteLogsToPrefList(base::ListValue* list) const; // Reads the list from the ListValue. void ReadLogsFromPrefList(const base::ListValue& list); // An object for recording UMA metrics. std::unique_ptr<PersistedLogsMetrics> metrics_; // A weak pointer to the PrefService object to read and write the preference // from. Calling code should ensure this object continues to exist for the // lifetime of the PersistedLogs object. PrefService* local_state_; // The name of the preference to serialize logs to/from. const char* pref_name_; // We will keep at least this |min_log_count_| logs or |min_log_bytes_| bytes // of logs, whichever is greater, when writing to disk. These apply after // skipping logs greater than |max_log_size_|. const size_t min_log_count_; const size_t min_log_bytes_; // Logs greater than this size will not be written to disk. const size_t max_log_size_; // Used to create a signature of log data, in order to verify reported data is // authentic. const std::string signing_key_; struct LogInfo { LogInfo(); LogInfo(const LogInfo& other); ~LogInfo(); // Initializes the members based on uncompressed |log_data|, // |log_timestamp|, and |signing_key|. |log_data| is the uncompressed // serialized log protobuf. A hash and a signature are computed from // |log_data|. The signature is produced using |signing_key|. |log_data| // will be compressed and storred in |compressed_log_data|. |log_timestamp| // is stored as is. // |metrics| is the parent's metrics_ object, and should not be held. void Init(PersistedLogsMetrics* metrics, const std::string& log_data, const std::string& log_timestamp, const std::string& signing_key); // Compressed log data - a serialized protobuf that's been gzipped. std::string compressed_log_data; // The SHA1 hash of the log. Computed in Init and stored to catch errors // from memory corruption. std::string hash; // The HMAC-SHA256 signature of the log, used to validate the log came from // Chrome. It's computed in Init and stored, instead of computed on demand, // to catch errors from memory corruption. std::string signature; // The timestamp of when the log was created as a time_t value. std::string timestamp; }; // A list of all of the stored logs, stored with SHA1 hashes to check for // corruption while they are stored in memory. std::vector<LogInfo> list_; // The index and type of the log staged for upload. If nothing has been // staged, the index will be -1. int staged_log_index_; DISALLOW_COPY_AND_ASSIGN(PersistedLogs); }; } // namespace metrics #endif // COMPONENTS_METRICS_PERSISTED_LOGS_H_
[ "csineneo@gmail.com" ]
csineneo@gmail.com
172b6d6b5cfb4e6eb4c1522a3006e0c71e85c51d
3d4e9699eba01914bedc279cabe546e2616f4c28
/common/inc/Process.h
587cdd1cdd475e6840dc6972dd776ce9c953b514
[]
no_license
liyandong1/WebServer
b5c411209784eedd8d3c1fae2f058f54b065b99b
65ce01b36edf4c307b19dec6572955f06871687c
refs/heads/master
2020-04-29T16:52:48.812358
2019-03-18T12:15:58
2019-03-18T12:15:58
176,272,752
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
#ifndef _PROCESS_H_ #define _PROCESS_H_ #include <string> class Process { public: int create_daemon(); //创建守护进程 void set_proc_name(char* argv, std::string proc_name);//设置进程标题 }; #endif
[ "416620418@qq.com" ]
416620418@qq.com
56f6fda0ddec8dd64b284b588ff8fce2336f73c9
754b3898d584c6074abeef63e72669e2d90451b1
/project 6/Files/node.cpp
3fe5f04ddfd52c699f4f516ecdab67726628fc26
[]
no_license
JamesGrom/coen-79
2d2932f8de47b9f2e4ddc09ade7170293220f4e2
5185dd19ca2b98fe251261dd819affd84ee71614
refs/heads/master
2021-01-09T12:28:55.897448
2020-02-22T08:04:04
2020-02-22T08:04:04
242,300,758
0
0
null
null
null
null
UTF-8
C++
false
false
15,676
cpp
// //FILE: node.cpp // James Grom lab 6 // // COEN 79 // --- Behnam Dezfouli, COEN, SCU --- // // // IMPLEMENTS: The functions of the node class and the // linked list toolkit (see node1.h for documentation). // // INVARIANT for the node class: // The data of a node is stored in data_field // and the link to the next node is stored in link_field. #include "node.h" #include <cassert> // Provides assert #include <cstdlib> // Provides NULL and size_t #include <iostream> using namespace std; namespace coen79_lab6 { //Precondition: head_ptr is the head pointer of a linked list. //Postcondition: The value returned is the number of nodes in the linked list. size_t list_length(const node* head_ptr) // Library facilities used: cstdlib { //create a temp node to traverse list const node *cursor; //holds list size size_t answer; //initialize list size answer = 0; //count number of nodes for (cursor = head_ptr; cursor != NULL; cursor = cursor->link( )) ++answer; //return number of nodes return answer; } // Precondition: head_ptr is the head pointer of a linked list. // Postcondition: A new node containing the given entry has been added at // the head of the linked list; head_ptr now points to the head of the new, // longer linked list. void list_head_insert(node*& head_ptr, const node::value_type& entry) { head_ptr = new node(entry, head_ptr); } // void list_insert(node* previous_ptr, const node::value_type& entry) // Precondition: previous_ptr points to a node in a linked list. // Postcondition: A new node containing the given entry has been added // after the node that previous_ptr points to. void list_insert(node* previous_ptr, const node::value_type& entry) { node *insert_ptr; insert_ptr = new node(entry, previous_ptr->link( )); previous_ptr->set_link(insert_ptr); } // Precondition: head_ptr is the head pointer of a linked list. // Postcondition: The pointer returned points to the first node containing // the specified target in its data member. If there is no such node, the // null pointer is returned. node* list_search(node* head_ptr, const node::value_type& target) // Library facilities used: cstdlib { node *cursor; for (cursor = head_ptr; cursor != NULL; cursor = cursor->link( )) if (target == cursor->data( )) return cursor; return NULL; } // Precondition: head_ptr is the head pointer of a linked list. // Postcondition: The pointer returned points to the first node containing // the specified target in its data member. If there is no such node, the // null pointer is returned. const node* list_search(const node* head_ptr, const node::value_type& target) // Library facilities used: cstdlib { const node *cursor; for (cursor = head_ptr; cursor != NULL; cursor = cursor->link( )) if (target == cursor->data( )) return cursor; return NULL; } // Precondition: head_ptr is the head pointer of a linked list, and // position > 0. // Postcondition: The pointer returned points to the node at the specified // position in the list. (The head node is position 1, the next node is // position 2, and so on). If there is no such position, then the null // pointer is returned. node* list_locate(node* head_ptr, size_t position) // Library facilities used: cassert, cstdlib { node *cursor; size_t i; assert (0 < position); cursor = head_ptr; for (i = 1; (i < position) && (cursor != NULL); i++) cursor = cursor->link( ); return cursor; } // Precondition: head_ptr is the head pointer of a linked list, and // position > 0. // Postcondition: The pointer returned points to the node at the specified // position in the list. (The head node is position 1, the next node is // position 2, and so on). If there is no such position, then the null // pointer is returned. const node* list_locate(const node* head_ptr, size_t position) // Library facilities used: cassert, cstdlib { const node *cursor; size_t i; assert (0 < position); cursor = head_ptr; for (i = 1; (i < position) && (cursor != NULL); i++) cursor = cursor->link( ); return cursor; } // void list_head_remove(node*& head_ptr) // Precondition: head_ptr is the head pointer of a linked list, with at // least one node. // Postcondition: The head node has been removed and returned to the heap; // head_ptr is now the head pointer of the new, shorter linked list. void list_head_remove(node*& head_ptr) { node *remove_ptr; remove_ptr = head_ptr; head_ptr = head_ptr->link( ); delete remove_ptr; } // Precondition: previous_ptr points to a node in a linked list, and this // is not the tail node of the list. // Postcondition: The node after previous_ptr has been removed from the // linked list. void list_remove(node* previous_ptr) { node *remove_ptr; remove_ptr = previous_ptr->link( ); previous_ptr->set_link( remove_ptr->link( ) ); delete remove_ptr; } // Precondition: head_ptr is the head pointer of a linked list. // Postcondition: All nodes of the list have been returned to the heap, // and the head_ptr is now NULL. void list_clear(node*& head_ptr) // Library facilities used: cstdlib { while (head_ptr != NULL) list_head_remove(head_ptr); } // void list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr) // Precondition: source_ptr is the head pointer of a linked list. // Postcondition: head_ptr and tail_ptr are the head and tail pointers for // a new list that contains the same items as the list pointed to by // source_ptr. The original list is unaltered. void list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr) // Library facilities used: cstdlib { head_ptr = NULL; tail_ptr = NULL; // Handle the case of the empty list. if (source_ptr == NULL) return; // create head node pointer for new list list_head_insert(head_ptr, source_ptr->data( )); tail_ptr = head_ptr; // Copy nodes at tail pointer source_ptr = source_ptr->link( ); while (source_ptr != NULL) { list_insert(tail_ptr, source_ptr->data( )); tail_ptr = tail_ptr->link( ); source_ptr = source_ptr->link( ); } } //the following have been implemented by James Grom // Precondition: start_ptr and end_ptr are pointers to nodes on the same // linked list, with the start_ptr node at or before the end_ptr node // Postcondition: head_ptr and tail_ptr are the head and tail pointers for a // new list that contains the items from start_ptr up to but not including // end_ptr. The end_ptr may also be NULL, in which case the new list // contains elements from start_ptr to the end of the list. void list_piece(node* start_ptr, node* end_ptr, node*& head_ptr, node*& tail_ptr) { //check if creating an empty list if(start_ptr==NULL||start_ptr==end_ptr) { head_ptr=NULL; tail_ptr=NULL; return; } //case where start==end has been handled //create a new_list andy copy the data from start pointer into the first node node *new_list=new node(start_ptr->data()); //have the old_list reference pont to the starting point node *old_list=start_ptr; //set head_ptr = to the new_list head_ptr=new_list; //traverse the old list from start_p to end_p stop traversal if old_list is or points to Null while(old_list!=NULL&&old_list!=end_ptr&&old_list->link()!= end_ptr) { //move old_list pointer to the next node old_list=old_list->link(); //to prevent double insertion insert after oldlist has been incremented list_insert(new_list,old_list->data()); //move new_list pointer new_list=new_list->link(); } //newlist is now pointing to the last node in the newly created list tail_ptr=new_list; return; } // Precondition: head_ptr is the head pointer of a linked list. // Postcondition: The return value is the count of the number of times // target appears as the data portion of a node on the linked list. // The linked list itself is unchanged. size_t list_occurrences(node* head_ptr, const node::value_type& target) { size_t count=0; const node *p=head_ptr; while(p!=NULL) { //count if u've found an occurence if(p->data()==target) { count++; } p=p->link(); } return count; } // Precondition: head_ptr is the head pointer of a linked list, and // position > 0 and position <= list_length(head_ptr)+1. // Postcondition: A new node has been added to the linked list with entry // as the data. The new node occurs at the specified position in the list. // (The head node is position 1, the next node is position 2, and so on.) // Any nodes that used to be after this specified position have been // shifted to make room for the one new node. void list_insert_at(node*& head_ptr, const node::value_type& entry, size_t position) { assert(position>0); assert(position <= list_length(head_ptr)+1); //position can refer to NULL (eg list_length(head_ptr)+1 //if position is at the head call head insert function if(position==1) { list_head_insert(head_ptr,entry); return; } //point previous to the node before to be inserted node *previous=head_ptr; int i=1; //move previous to i-1, stop traversing the list if at the end while(previous!=NULL) { if(i==position-1) { list_insert(previous,entry); return; } else{ previous=previous->link(); i++; } } //previous should now point to node at position -1 //now insert into list at appropriate location list_insert(previous,entry); return; } // Precondition: head_ptr is the head pointer of a linked list, and // position > 0 and position <= list_length(head_ptr). // Postcondition: The node at the specified position has been removed from // the linked list and the function has returned a copy of the data from // the removed node. // (The head node is position 1, the next node is position 2, and so on.) node::value_type list_remove_at(node*& head_ptr, size_t position) { //ensure valid preconditions assert(position>0); assert(position<=list_length(head_ptr)); //create a variable for return value node::value_type ret_val=head_ptr->data(); //if position refers to first node in the list, call remove head if(position==1) { list_head_remove(head_ptr); return ret_val; } //point previous to the node before to be inserted node *previous=head_ptr; //previous is at position 1 rn int i=1; //move previous position-1 times while(previous!=NULL) { if(i==(position-1)) { ret_val=previous->link()->data(); list_remove(previous); return ret_val; } previous=previous->link(); i++; } } // node* list_copy_segment(node* head_ptr, size_t start, size_t finish) // Precondition: head_ptr is the head pointer of a linked list, and // (1 <= start) and (start <= finish) and (finish <= list_length(head_ptr)). // Postcondition: The value returned is the head pointer for // a new list that contains copies of the items from the start position to // the finish position in the list that head_ptr points to. // (The head node is position 1, the next node is position 2, and so on.) // The list pointed to by head_ptr is unchanged. node* list_copy_segment(node* head_ptr, size_t start, size_t finish) { //assure valid preconditions assert((1<=start)&&(start <= finish)&&(finish <= list_length(head_ptr))); //translate into valid paramaters for list_piece node *start_ptr=list_locate(head_ptr,start); node *end_ptr=list_locate(head_ptr,finish)->link(); node *useless; //copy out the referenced piece of the list list_piece(start_ptr,end_ptr,head_ptr,useless); return head_ptr; } // Precondition: head_ptr is the head pointer of a linked list, and // the operator << has been defined for the value_type // Postcondition: The value_type of all the nodes in the linked list are printed void list_print (const node* head_ptr) { while(head_ptr!=NULL) { cout<<head_ptr->data(); head_ptr=head_ptr->link(); if(head_ptr!=NULL) cout<<", "; } cout<<endl; return; } // Precondition: head_ptr is the head pointer of a linked list // Postcondition: All the duplicates are removed from the linked list // Example: If the list contains 1,1,1,2, after running this function the list // contains 1,2 void list_remove_dups(node* head_ptr) { node::value_type temp; node *p; //ensure valid head_ptr to prevent segfault if(head_ptr==NULL) { return; } temp=head_ptr->data(); while(head_ptr!=NULL&&head_ptr->link()!=NULL) { while(list_search(head_ptr->link(),temp)!=NULL) { //a duplicate has been found //find the preceeding node to the one we want to delete p=head_ptr; while(p->link()!=list_search(head_ptr->link(),temp)) { p=p->link(); } //head pointer will never get deleted since only duplicates after the first are deleted //remove the node with duplicate value list_remove(p); } head_ptr=head_ptr->link(); } return; } // node* list_detect_loop (node* head_ptr); // Precondition: head_ptr is the head pointer of a linked list // Postcondition: If there is a loop in the linked list, the returned value // is a pointer to the start of the loop. The returned value is NULL if // there is no loop in the list node* list_detect_loop (node* head_ptr) { if(head_ptr==NULL) return NULL; //create a fast and a slow pointer node *fast=head_ptr; node *slow=head_ptr; bool loop_found=false; //use floyd's loop detection algorithm while(fast!=NULL&&fast->link()!=NULL) { fast=fast->link()->link(); slow=slow->link(); if(fast==slow) { loop_found=true; break; } } if(loop_found==false) return NULL; slow=head_ptr; while(slow!=fast) { slow=slow->link(); fast=fast->link(); } return slow; } }
[ "noreply@github.com" ]
noreply@github.com
ac4dde3f2ef0daedf97ddb1139e7cf69e15b2df2
cecc356b3ad5b4bf346c17ee611d1feaa306639f
/filters/__Sensors__.h
81a52d620e406377efb766615974619ba5bb4c35
[]
no_license
rafasaurus/robotello
20623aab3ee0a27fb3cc9fa78b248f0321b34d51
4867f98db081081fd911f1f024194c1dc96d5012
refs/heads/master
2020-08-23T02:10:38.015315
2019-11-19T11:46:57
2019-11-19T11:46:57
216,521,379
2
0
null
null
null
null
UTF-8
C++
false
false
2,044
h
#include "Queue.h" #define QUEUE_SIZE 7 #include "__Send__.h" // SensorIds #define R_id 0 #define L_id 1 #define RR_id 2 #define LL_id 3 #define COLORSENSE_RED_id 4 #define COLORSENSE_GREEN_id 5 #define COLORSENSE_BLUE_id 6 #define COLORSENSE1_MEAN_id 7 #define LANE_CNT_id 8 class __Sensors__ { class Sensor { public: // Init emptry queue and constructor Sensor():queue(QUEUE_SIZE) {} DataQueue<int> queue; int queueList[QUEUE_SIZE] = {0}; void push_(int data) { if (!queue.isFull()) { queue.enqueue(data); } else { queue.dequeue(); queue.enqueue(data); } queue.nextValue(queueList); } int getMean() { return queue.getMean(); } }; private: Sensor cR_; Sensor cG_; Sensor cB_; Sensor cS1_mean_; Sensor LL_; Sensor L_; Sensor R_; Sensor RR_; public: __Sensors__() {}; void push(int ll, int l, int r, int rr, int redColor, int greenColor, int blueColor, int colorSense1_mean) { LL_.push_(ll); L_.push_(l); R_.push_(r); RR_.push_(rr); cR_.push_(redColor); cB_.push_(blueColor); cG_.push_(greenColor); cS1_mean_.push_(colorSense1_mean); } void sendPayload(int laneCnt) { // lineTrackers payload send(L_.getMean(), L_id); send(LL_.getMean(), LL_id); send(R_.getMean(), R_id); send(RR_.getMean(), RR_id); // colorSensor payload send(cR_.getMean(), COLORSENSE_RED_id); send(cG_.getMean(), COLORSENSE_GREEN_id); send(cB_.getMean(), COLORSENSE_BLUE_id); send(cS1_mean_.getMean(), COLORSENSE1_MEAN_id); send(laneCnt, LANE_CNT_id); // Debug // Serial.println(); } };
[ "rafa.grigorian@gmail.com" ]
rafa.grigorian@gmail.com
8d3884d75fa068227fdb42976628cac2b00a1ee0
cd53c2e3e8a2cf94bb484c34e706ff40d8480a56
/core/F_LoadFromFile.h
2d3479929a7071aca9524dbcac7039695ad77ca9
[]
no_license
yxliang/structured_prediction_for_segmentation
901432ecd377ab846b4cf71e4169fa0c230c177b
d695e748ea69af33ecd844f86fddd06de2ad1f6f
refs/heads/master
2021-01-21T07:47:51.542361
2015-08-27T07:52:47
2015-08-27T07:52:47
47,535,481
1
0
null
2015-12-07T07:08:48
2015-12-07T07:08:46
null
UTF-8
C++
false
false
5,513
h
///////////////////////////////////////////////////////////////////////// // This program is free software; you can redistribute it and/or // // modify it under the terms of the GNU General Public License // // version 2 as published by the Free Software Foundation. // // // // This program is distributed in the hope that it will be useful, but // // WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // // General Public License for more details. // // // // Written and (C) by Aurelien Lucchi // // Contact <aurelien.lucchi@gmail.com> for comments & bug reports // ///////////////////////////////////////////////////////////////////////// #ifndef F_LoadFromFile_H #define F_LoadFromFile_H #include <vector> // SliceMe #include "Slice.h" #include "Slice3d.h" #include "Feature.h" //-------------------------------------------------------------------------TYPES // TODO : should really use char for 3d volumes !!! //typedef char fileFeatureType; typedef float fileFeatureType; #define USE_SPARSE_STRUCTURE 0 #if USE_SPARSE_STRUCTURE typedef map<ulong, fileFeatureType*> featureType; #else typedef fileFeatureType** featureType; #endif //-------------------------------------------------------------------------CLASS class F_LoadFromFile : public Feature { public: F_LoadFromFile(); ~F_LoadFromFile(); void clearFeatures(); string getAbsoluteFeaturePath(const string& featureFilename, const string& inputDir); int getSizeFeatureVectorForOneSupernode(); bool getFeatureVector(osvm_node *n, const int x, const int y); /** * Extract a feature vector for a given supernode in a 2d slice */ bool getFeatureVectorForOneSupernode(osvm_node *x, Slice* slice, const int supernodeId); /** * Extract a feature vector for a given supernode in a 3d volume */ bool getFeatureVectorForOneSupernode(osvm_node *x, Slice3d* slice3d, const int supernodeId); bool getFeatureVector(osvm_node *x, Slice3d* slice3d, const int gx, const int gy, const int gz); string getFeaturePath() { return featurePath; } eFeatureType getFeatureType() { return F_LOADFROMFILE; } /** * Load all the features in a given cube. */ void init(Slice& slice, const char* filename); void init(Slice3d& slice3d, const char* filename); void init(Slice_P& slice, const char* filename); void init(Slice3d& slice3d, const char* filename, map<sidType, sidType>& sid_mapping); /** * Load all the features in a given sub-cube. */ void init(Slice3d& slice3d, const char* filename, const node& start, const node& end); /** * Load features for given list of nodes. */ void init(Slice3d& slice3d, const char* filename, std::vector<sidType>& lNodes); void loadFeatureFilenames(const char* filename, vector<string>* lFeatureFilenames); /** * Load features from a text file that contain features * for each supervoxel. */ void loadTextFeatures(Slice_P& slice, const vector<string>& lFeatureFilenames); /** * Load features from a cube, e.g a TIF file contain features for * each voxel. */ void loadVoxelBasedFeaturesFromTIF(Slice3d& slice, const vector<string>& lFeatureFilenames); void loadSupervoxelBasedFeaturesFromTIF(Slice3d& slice3d, const vector<string>& lFeatureFilenames, vector<sidType>& lNodes); void loadSupervoxelBasedFeaturesFromBinary(Slice3d& slice3d, const vector<string>& lFeatureFilenames, vector<sidType>& lNodes); void loadSupervoxelBasedFeaturesFromBinary(Slice3d& slice3d, const vector<string>& lFeatureFilenames, vector<sidType>& lNodes, map<sidType, sidType>& sid_mapping); void loadSupervoxelBasedFeaturesFromSetOfBinaries(Slice3d& slice3d, const vector<string>& lFeatureFilenames, vector<sidType>& lNodes); featureType* getMutableFeatures() { return &features; } void rescale(); void rescale(Slice_P* slice); void setFeatures(featureType _features, int _nFeatures, int _featureSize) { features = _features; nFeatures = _nFeatures; featureSize = _featureSize; } void setFeatureSize(const int _featureSize) { featureSize = _featureSize; } private: featureType features; int nFeatures; // number of feature vectors int featureSize; // size of each feature vector string featurePath; bool initialized; }; #endif // F_LoadFromFile_H
[ "aurelien.lucchi@gmail.com" ]
aurelien.lucchi@gmail.com
c7184954020b6538f2ad8fdd488404b7eab104aa
995bcab0f4b26402475fee2564ed51723414a2a6
/sem_04/cg/lab_07/figures.h
8dbf44f479f8238921ad7115b4e27de668a428d2
[]
no_license
maxerMU/bmstu
e1400abdc5ca7c4b58f51ec5e46e072cd50297de
d91cb82ce8f43e1caea7c5d91c878b2329ec8427
refs/heads/main
2023-06-10T23:54:29.144731
2021-07-01T08:25:41
2021-07-01T08:25:41
308,846,327
4
0
null
2021-07-01T08:25:42
2020-10-31T09:23:57
C++
UTF-8
C++
false
false
2,081
h
#ifndef FIGURES_H #define FIGURES_H #include <QColor> #include <QPainter> class Figure { public: Figure(const QColor &fg = QColor(0, 0, 0), const QColor &bg = QColor(255, 255, 255)) :fg(fg), bg(bg) { } virtual void paint(QPainter &painter) const = 0; virtual ~Figure() {} void set_fg(const QColor &color) {fg = color;} void set_bg(const QColor &color) {bg = color;} protected: QColor fg; QColor bg; }; class point : public Figure { public: explicit point(const QColor &fg) :Figure(fg) { } point(double x, double y, const QColor &fg = QColor(0, 0, 0)) :Figure(fg), x(x), y(y) { } virtual void paint(QPainter &painter) const override; double get_x() const; double get_y() const; void set_x(long x); void set_y(long y); point operator-(const point& p); point operator+(const point& p); point operator/(double num); bool operator<(double eps); private: double x = 0; double y = 0; }; class line : public Figure { public: explicit line(const QColor &fg) :Figure(fg), p1(fg), p2(fg) { } line(const QColor &fg, long x, long y) :Figure(fg), p1(point(x, y, fg)), p2(point(x, y, fg)) { } virtual void paint(QPainter &painter) const override; point get_p1() const; point get_p2() const; void set_p1(const point &p); void set_p2(const point &p); private: point p1; point p2; }; class rectangle : public Figure { public: explicit rectangle(const QColor &fg) :Figure(fg), p1(fg), p2(fg) { } rectangle(const QColor &fg, long x, long y) :Figure(fg), p1(point(x, y, fg)), p2(point(x, y, fg)) { } virtual void paint(QPainter &painter) const override; point get_p1() const; point get_p2() const; void set_p1(const point &p); void set_p2(const point &p); long get_top() const; long get_bottom() const; long get_right() const; long get_left() const; private: point p1; point p2; }; #endif // FIGURES_H
[ "max_mitsevich@mail.ru" ]
max_mitsevich@mail.ru
bb5ea3be61b6f935261c7c586b1734842d10b6f2
55dd7a348adb87a80f26d58745b79719a220c1f5
/rtc.ino
4f58e1acd58d394402029c4978bd2cc128f911b5
[]
no_license
edbaez/riego
57e2290aa98d6a8fe1bc41f5b2fb269c043f89a6
6a31f0fff2e0a2be31ee91b02eb7cbbda32d1454
refs/heads/master
2021-05-04T13:02:07.711758
2018-02-05T14:03:27
2018-02-05T14:03:27
120,305,896
0
0
null
null
null
null
UTF-8
C++
false
false
3,357
ino
/* Ejemplo para arduino de lectura de fecha y hora al DS1307 en el modulo TinyRTC. Este ejemplo envial monitor serial la fecha y la hora almacenada en el RTC cada segundo. */ #include <Wire.h> // Declaracion de las variables para almacenar informacion de tiempo leida desde RTC uint8_t second, minute, hour, wday, day, month, year, ctrl; /** Inicio del sketch: Este codigo se ejecuta al conectar el arduino */ void setup_rtc() { // NOTA: Estas sentencias se requieren para alimentar directamente el // chip RTC desde los pines A3 Y A2 (colocar directamente el modulo sobre // la tarjeta arduino, sin la necesidad de cablear en Arduino UNO). // Si no se quiere hacer esto, se pueden eliminar o comentar sin problemas pinMode(A3, OUTPUT); digitalWrite(A3, HIGH); pinMode(A2, OUTPUT); digitalWrite(A2, LOW); // Configurar la comunicacion a 9600 baudios Serial.begin(9600); // Preparar la librería Wire (I2C) Wire.begin(); // Imprimir encabezado a la terminal Serial.println("----------------------------------------------------"); Serial.println("EJEMPLO LECTURA DE RTC DS1307 EN TINYRTC CON ARDUINO"); Serial.println(" https://www.geekfactory.mx "); Serial.println("----------------------------------------------------"); } /** Ciclo principàl del sketch: Leer y mostrar la hora y fecha cada segundo */ /** Esta funcion establece la cominicación con el DS1307 y lee los registros de fecha y hora. Entrega la informacion horaria en las variables globales declaradas al principio del sketch. */ bool read_ds1307() { // Iniciar el intercambio de información con el DS1307 (0xD0) Wire.beginTransmission(0x68); // Escribir la dirección del segundero Wire.write(0x00); // Terminamos la escritura y verificamos si el DS1307 respondio // Si la escritura se llevo a cabo el metodo endTransmission retorna 0 if (Wire.endTransmission() != 0) return false; // Si el DS1307 esta presente, comenzar la lectura de 8 bytes Wire.requestFrom(0x68, 8); // Recibimos el byte del registro 0x00 y lo convertimos a binario second = bcd2bin(Wire.read()); minute = bcd2bin(Wire.read()); // Continuamos recibiendo cada uno de los registros hour = bcd2bin(Wire.read()); wday = bcd2bin(Wire.read()); day = bcd2bin(Wire.read()); month = bcd2bin(Wire.read()); year = bcd2bin(Wire.read()); // Recibir los datos del registro de control en la dirección 0x07 ctrl = Wire.read(); // Operacion satisfactoria, retornamos verdadero return true; } /** Esta función convierte un número BCD a binario. Al dividir el número guardado en el parametro BCD entre 16 y multiplicar por 10 se convierten las decenas y al obtener el módulo 16 obtenemos las unidades. Ambas cantidades se suman para obtener el valor binario. */ uint8_t bcd2bin(uint8_t bcd) { // Convertir decenas y luego unidades a un numero binario return (bcd / 16 * 10) + (bcd % 16); } /** Imprime la fecha y hora al monitor serial de arduino */ void print_time() { Serial.print("Fecha: "); Serial.print(day); Serial.print('/'); Serial.print(month); Serial.print('/'); Serial.print(year); Serial.print(" Hora: "); Serial.print(hour); Serial.print(':'); Serial.print(minute); Serial.print(':'); Serial.print(second); Serial.println(); }
[ "edbaez@gmail.com" ]
edbaez@gmail.com
a7dade56fc95e365bcfa6c51c6610280c4915a49
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0075/CC6H12OOH-D
5da86fc4968798c0a1aee39837a2cc42b59be531
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
834
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0075"; object CC6H12OOH-D; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 0; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
8ee4d739e2e90a8f1fc171588204c2fecdb6a529
483b0afcb99602d30407ab30ed844e452339c70e
/cuttingSticks.cpp
dd96c9868a28facaa5f416dcbc65440f3a349f4d
[]
no_license
antonaldinho/Algorithms
073209054419ecb97cb7da87ccd4d6f402c7d598
889db74ae9e1e09fa500d89988c049e827e67a78
refs/heads/master
2021-06-25T22:56:49.072487
2017-09-10T16:20:04
2017-09-10T16:20:04
103,043,308
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,175
cpp
//José Antonio Alemán Salazar //A01196565 //Creado el lunes 6 de marzo de 2017 //Análisis y diseño de algoritmos //Tarea 10: Cutting Sticks //El programa calcula la manera menos costosa de cortar los palos de acuerdo a los cortes indicados #include <iostream> using namespace std; int main() { int iLength; cin >> iLength; while(iLength != 0) { int iMatrix[50][50]; int iCuts[50]; int iC; int iMin; cin >> iC; iCuts[0] = 0; iCuts[iC+1] = iLength; for(int i = 1; i <= iC; i++) cin >> iCuts[i]; for(int i = 0; i <= iC+1; i++) iMatrix[i][i+1] = 0; for(int j = 2; j<=iC+1; j++) { for(int i = j-2; i >= 0; i--) { iMin = INT_MAX; for(int k=i+1; k<j; k++) iMin = min(iMin, iMatrix[i][k] +iMatrix[k][j] + iCuts[j] -iCuts[i]); iMatrix[i][j]=iMin; } } cout << "The minimum cutting is " << iMatrix[0][iC+1] << endl; cin >> iLength; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
5f249579e6e85c5ffd1c95e8881c10f7b1abf844
5eace6c1fc699d5eb85c49269d17d963d430dda6
/sport_prog/felicityc_codecraft2014/nballs.cpp
964edbf39f369927831d20f7605f14647e2ac281
[]
no_license
shashwat001/my-codes
87fd8f508f039e621cc971072ac39d9f2d1d1851
f9db0a7c13c2689fde1b770bc0edfa092dc62ee9
refs/heads/master
2021-09-20T06:22:23.993687
2018-08-05T19:00:48
2018-08-05T19:00:48
5,686,297
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
//shashwat001 #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <iostream> #include <string> #include <vector> #include <set> #include <queue> #include <stack> #include <map> #include <list> #include <utility> #include <algorithm> #include <cassert> using namespace std; #define INF 2147483647 #define LINF 9223372036854775807 #define mp make_pair #define pb push_back typedef long long int lli; typedef pair<int,int> pi; int main () { int n,a,b,i; pi dp[100001]; cin>>n; for(i = 0;i <= 100000;i++) { dp[i].first = 0; dp[i].second = 0; } for(i = 0;i < n;i++) { cin>>a>>b; dp[a].first++; dp[b].second++; } int half = (n+1)/2; int minm = INF; for(i = 0;i <= 100000;i++) { if(dp[i].first<half) { if(half-dp[i].first <= dp[i].second) { minm = min(minm,half-dp[i].first); } } else { minm = 0; } } if(minm == INF) cout<<"Impossible"; else cout<<minm; return 0; }
[ "shashwat001@mdvlshashwatk.(none)" ]
shashwat001@mdvlshashwatk.(none)
54c41200f9bcba798b031fabce5489e23b07b569
6398c5babd7b8d3ad24fa743820bccd5f70fa1ed
/include/common/camera.hpp
09af1529c15dcf7d9e8fd8f978dca2a52bbfa741
[ "MIT" ]
permissive
Basez/Agnostik-Engine
f8d6173e17c4438b34853d1d51db64d808574e8f
10171bbeb73c590e75e9db5adf0135e0235f2884
refs/heads/master
2021-01-21T04:30:51.989357
2016-07-10T09:58:13
2016-07-10T09:58:13
38,234,601
7
0
null
null
null
null
UTF-8
C++
false
false
1,131
hpp
#pragma once namespace AGN { class Camera { public: Camera(glm::vec3 a_initialPosition = glm::vec3(), glm::quat a_initialRotation = glm::quat()); ~Camera(); void reset(glm::vec3 a_position, glm::quat a_rotation); void applyViewMatrix(); void translate(glm::vec3& a_addedPosition); void rotate(glm::quat& a_addedRotation); void setPosition(glm::vec3& a_postion); void setRotation(glm::quat& a_rotation); void setEulerAngles(glm::vec3& a_eulerAngles); void setProjectionRH(float a_fov, float a_zNear, float a_zFar); const glm::vec3 getPosition() const { return m_position; } const glm::quat getRotation() const { return m_rotation; } const glm::mat4 getProjectionMatrix() const { return m_projectionMatrix; } const glm::vec3 getForward() const; const glm::vec3 getEulerAngles() const; const glm::mat4 getViewMatrix(); const glm::vec3 getWorldPositionFromScreenPosition(const glm::vec2 a_screenPos) const; private: void updateViewMatrix(); glm::vec3 m_position; glm::quat m_rotation; glm::mat4 m_viewMatrix; glm::mat4 m_projectionMatrix; bool m_hasChangedFlag; }; }
[ "basvanzutphen@gmail.com" ]
basvanzutphen@gmail.com
a96a9c890f945d033daac4821002f9b8fea95802
d4950232267cb94adc954a05c6f8e78436e93b6d
/1121_二分图一•二分图判定.cpp
18b9896b901958e177bbc32432601a722d44cc2d
[]
no_license
xiaoxiamii/hihocode
f3bfec66ba7052b0c529769dac208dc1690ab0ff
395512eabcce1f8a230685f07d635e3340a95a2b
refs/heads/master
2021-01-10T01:19:32.709931
2015-12-03T14:23:34
2015-12-03T14:23:34
44,085,651
3
0
null
null
null
null
UTF-8
C++
false
false
1,484
cpp
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<math.h> #include<vector> #include<string> #include<sstream> #include<algorithm> #include<stack> #include<queue> #include<limits.h> #include<numeric> #include<cstring> #include<map> using namespace std; const int MAX_N = 1e4 + 10; const int MAX_M = 4e4 + 10; const int MAX_T = 1e5+10; static int N, M, S, T; struct edge{ int to; int next; int val; }edge[MAX_M*2]; int head[MAX_N]; int color[MAX_N]; int cnt; void addEdge(int u, int v) { edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++; } bool BFS(int start){ color[start] = 1; queue<int> q; q.push(start); while( !q.empty()) { int cur = q.front(); q.pop(); for(int k = head[cur]; k!= 0; k = edge[k].next){ if(color[edge[k].to] == -1){ color[edge[k].to] = 1 - color[cur]; q.push(edge[k].to); } else { if(color[edge[k].to] + color[cur] != 1){ return false; } } } } return true; } bool check(){ for(int i=1;i<=N;++i){ if(color[i] == -1){ if(!BFS(i)){ return false; } } } return true; } int main (){ cin>> T; while(T--){ cin>> N >> M; memset(color , -1 , sizeof(color)); memset(head, 0, sizeof(head)); memset(edge, 0, sizeof(edge)); cnt = 0; int u, v; for(int i =1; i<=M;++i){ cin >> u >> v; addEdge(u, v); addEdge(v, u); } if(check()){ cout << "Correct" << endl; } else { cout << "Wrong" << endl; } } system("pause"); return 0; }
[ "cj766@qq.com" ]
cj766@qq.com
6d5c765f55654b86711e5500116dbc5bc6d216e9
8dc84558f0058d90dfc4955e905dab1b22d12c08
/content/renderer/media/webrtc/rtc_video_decoder.cc
238e3a9dc63fddbd84f25dc6b646051871743166
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
33,930
cc
// Copyright 2013 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 "content/renderer/media/webrtc/rtc_video_decoder.h" #include <utility> #include "base/bind.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/task_runner_util.h" #include "content/renderer/media/webrtc/webrtc_video_frame_adapter.h" #include "gpu/command_buffer/common/mailbox_holder.h" #include "media/base/bind_to_current_loop.h" #include "media/video/gpu_video_accelerator_factories.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/webrtc/api/video/video_frame.h" #include "third_party/webrtc/modules/video_coding/codecs/h264/include/h264.h" #include "third_party/webrtc/rtc_base/bind.h" #include "third_party/webrtc/rtc_base/refcount.h" #include "third_party/webrtc/rtc_base/refcountedobject.h" #if defined(OS_WIN) #include "base/command_line.h" #include "base/win/windows_version.h" #include "content/public/common/content_switches.h" #endif // defined(OS_WIN) namespace content { const int32_t RTCVideoDecoder::ID_LAST = 0x3FFFFFFF; const int32_t RTCVideoDecoder::ID_HALF = 0x20000000; const int32_t RTCVideoDecoder::ID_INVALID = -1; // Number of consecutive frames that can be lost due to a VDA error before // falling back to SW implementation. const uint32_t kNumVDAErrorsBeforeSWFallback = 5; // Maximum number of concurrent VDA::Decode() operations RVD will maintain. // Higher values allow better pipelining in the GPU, but also require more // resources. static const size_t kMaxInFlightDecodes = 8; // Maximum number of pending WebRTC buffers that are waiting for shared memory. static const size_t kMaxNumOfPendingBuffers = 8; // Number of allocated shared memory segments. static const size_t kNumSharedMemorySegments = 16; RTCVideoDecoder::BufferData::BufferData(int32_t bitstream_buffer_id, uint32_t timestamp, size_t size, const gfx::Rect& visible_rect) : bitstream_buffer_id(bitstream_buffer_id), timestamp(timestamp), size(size), visible_rect(visible_rect) {} RTCVideoDecoder::BufferData::BufferData() {} RTCVideoDecoder::BufferData::~BufferData() {} RTCVideoDecoder::RTCVideoDecoder(webrtc::VideoCodecType type, media::GpuVideoAcceleratorFactories* factories) : vda_error_counter_(0), video_codec_type_(type), factories_(factories), next_picture_buffer_id_(0), state_(UNINITIALIZED), decode_complete_callback_(nullptr), num_shm_buffers_(0), next_bitstream_buffer_id_(0), reset_bitstream_buffer_id_(ID_INVALID), weak_factory_(this) { DCHECK(!factories_->GetTaskRunner()->BelongsToCurrentThread()); } RTCVideoDecoder::~RTCVideoDecoder() { DVLOG(2) << "~RTCVideoDecoder"; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); DestroyVDA(); // Delete all shared memories. ClearPendingBuffers(); } // static std::unique_ptr<RTCVideoDecoder> RTCVideoDecoder::Create( webrtc::VideoCodecType type, media::GpuVideoAcceleratorFactories* factories) { std::unique_ptr<RTCVideoDecoder> decoder; // See https://bugs.chromium.org/p/webrtc/issues/detail?id=5717. #if defined(OS_WIN) if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWin7WebRtcHWH264Decoding) && type == webrtc::kVideoCodecH264 && base::win::GetVersion() == base::win::VERSION_WIN7) { DLOG(ERROR) << "H264 HW decoding on Win7 is not supported."; return decoder; } #endif // defined(OS_WIN) // Convert WebRTC codec type to media codec profile. media::VideoCodecProfile profile; switch (type) { case webrtc::kVideoCodecVP8: profile = media::VP8PROFILE_ANY; break; case webrtc::kVideoCodecVP9: profile = media::VP9PROFILE_MIN; break; case webrtc::kVideoCodecH264: profile = media::H264PROFILE_MAIN; break; default: DVLOG(2) << "Video codec not supported:" << type; return decoder; } base::WaitableEvent waiter(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); decoder.reset(new RTCVideoDecoder(type, factories)); decoder->factories_->GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&RTCVideoDecoder::CreateVDA, base::Unretained(decoder.get()), profile, &waiter)); waiter.Wait(); // |decoder->vda_| is nullptr if the codec is not supported. if (decoder->vda_) decoder->state_ = INITIALIZED; else factories->GetTaskRunner()->DeleteSoon(FROM_HERE, decoder.release()); return decoder; } // static void RTCVideoDecoder::Destroy(webrtc::VideoDecoder* decoder, media::GpuVideoAcceleratorFactories* factories) { factories->GetTaskRunner()->DeleteSoon(FROM_HERE, decoder); } int32_t RTCVideoDecoder::InitDecode(const webrtc::VideoCodec* codecSettings, int32_t /*numberOfCores*/) { DVLOG(2) << "InitDecode"; DCHECK_EQ(video_codec_type_, codecSettings->codecType); base::AutoLock auto_lock(lock_); if (state_ == UNINITIALIZED || state_ == DECODE_ERROR) { LOG(ERROR) << "VDA is not initialized. state=" << state_; return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_UNINITIALIZED); } return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_OK); } int32_t RTCVideoDecoder::Decode( const webrtc::EncodedImage& inputImage, bool missingFrames, const webrtc::CodecSpecificInfo* /*codecSpecificInfo*/, int64_t /*renderTimeMs*/) { DVLOG(3) << "Decode"; base::AutoLock auto_lock(lock_); if (state_ == UNINITIALIZED || !decode_complete_callback_) { LOG(ERROR) << "The decoder has not initialized."; return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (state_ == DECODE_ERROR) { LOG(ERROR) << "Decoding error occurred."; // Try reseting the session up to |kNumVDAErrorsHandled| times. if (ShouldFallbackToSoftwareDecode()) return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE; base::AutoUnlock auto_unlock(lock_); Release(); return WEBRTC_VIDEO_CODEC_ERROR; } if (missingFrames || !inputImage._completeFrame) { DLOG(ERROR) << "Missing or incomplete frames."; // Unlike the SW decoder in libvpx, hw decoder cannot handle broken frames. // Return an error to request a key frame. return WEBRTC_VIDEO_CODEC_ERROR; } // Most platforms' VDA implementations support mid-stream resolution change // internally. Platforms whose VDAs fail to support mid-stream resolution // change gracefully need to have their clients cover for them, and we do that // here. #ifdef ANDROID const bool kVDACanHandleMidstreamResize = false; #else const bool kVDACanHandleMidstreamResize = true; #endif bool need_to_reset_for_midstream_resize = false; const gfx::Size new_frame_size(inputImage._encodedWidth, inputImage._encodedHeight); if (!new_frame_size.IsEmpty() && new_frame_size != frame_size_) { DVLOG(2) << "Got new size=" << new_frame_size.ToString(); if (new_frame_size.width() > max_resolution_.width() || new_frame_size.width() < min_resolution_.width() || new_frame_size.height() > max_resolution_.height() || new_frame_size.height() < min_resolution_.height()) { DVLOG(1) << "Resolution unsupported, falling back to software decode"; return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE; } gfx::Size prev_frame_size = frame_size_; frame_size_ = new_frame_size; if (!kVDACanHandleMidstreamResize && !prev_frame_size.IsEmpty() && prev_frame_size != frame_size_) { need_to_reset_for_midstream_resize = true; } } else if (IsFirstBufferAfterReset(next_bitstream_buffer_id_, reset_bitstream_buffer_id_)) { // TODO(wuchengli): VDA should handle it. Remove this when // http://crosbug.com/p/21913 is fixed. // If we're are in an error condition, increase the counter. vda_error_counter_ += vda_error_counter_ ? 1 : 0; DVLOG(1) << "The first frame should have resolution. Drop this."; return WEBRTC_VIDEO_CODEC_ERROR; } // Create buffer metadata. BufferData buffer_data(next_bitstream_buffer_id_, inputImage._timeStamp, inputImage._length, gfx::Rect(frame_size_)); // Mask against 30 bits, to avoid (undefined) wraparound on signed integer. next_bitstream_buffer_id_ = (next_bitstream_buffer_id_ + 1) & ID_LAST; // If a shared memory segment is available, there are no pending buffers, and // this isn't a mid-stream resolution change, then send the buffer for decode // immediately. Otherwise, save the buffer in the queue for later decode. std::unique_ptr<base::SharedMemory> shm_buffer; if (!need_to_reset_for_midstream_resize && pending_buffers_.empty()) shm_buffer = GetSHM_Locked(inputImage._length); if (!shm_buffer) { if (!SaveToPendingBuffers_Locked(inputImage, buffer_data)) { // We have exceeded the pending buffers count, we are severely behind. // Since we are returning ERROR, WebRTC will not be interested in the // remaining buffers, and will provide us with a new keyframe instead. // Better to drop any pending buffers and start afresh to catch up faster. DVLOG(1) << "Exceeded maximum pending buffer count, dropping"; ++vda_error_counter_; if (ShouldFallbackToSoftwareDecode()) return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE; ClearPendingBuffers(); return WEBRTC_VIDEO_CODEC_ERROR; } if (need_to_reset_for_midstream_resize) { Reset_Locked(); } return WEBRTC_VIDEO_CODEC_OK; } SaveToDecodeBuffers_Locked(inputImage, std::move(shm_buffer), buffer_data); factories_->GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&RTCVideoDecoder::RequestBufferDecode, weak_factory_.GetWeakPtr())); return WEBRTC_VIDEO_CODEC_OK; } int32_t RTCVideoDecoder::RegisterDecodeCompleteCallback( webrtc::DecodedImageCallback* callback) { DVLOG(2) << "RegisterDecodeCompleteCallback"; DCHECK(callback); base::AutoLock auto_lock(lock_); decode_complete_callback_ = callback; return WEBRTC_VIDEO_CODEC_OK; } int32_t RTCVideoDecoder::Release() { DVLOG(2) << "Release"; // Do not destroy VDA because WebRTC can call InitDecode and start decoding // again. base::AutoLock auto_lock(lock_); if (state_ == UNINITIALIZED) { LOG(ERROR) << "Decoder not initialized."; return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } if (next_bitstream_buffer_id_ != 0) reset_bitstream_buffer_id_ = next_bitstream_buffer_id_ - 1; else reset_bitstream_buffer_id_ = ID_LAST; frame_size_.SetSize(0, 0); Reset_Locked(); return WEBRTC_VIDEO_CODEC_OK; } void RTCVideoDecoder::ProvidePictureBuffers(uint32_t buffer_count, media::VideoPixelFormat format, uint32_t textures_per_buffer, const gfx::Size& size, uint32_t texture_target) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); DVLOG(3) << "ProvidePictureBuffers. texture_target=" << texture_target; if (!vda_) return; std::vector<uint32_t> texture_ids; std::vector<gpu::Mailbox> texture_mailboxes; if (format == media::PIXEL_FORMAT_UNKNOWN) format = media::PIXEL_FORMAT_ARGB; const uint32_t texture_count = buffer_count * textures_per_buffer; if (!factories_->CreateTextures(texture_count, size, &texture_ids, &texture_mailboxes, texture_target)) { NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } DCHECK_EQ(texture_count, texture_ids.size()); DCHECK_EQ(texture_count, texture_mailboxes.size()); std::vector<media::PictureBuffer> picture_buffers; for (size_t buffer_index = 0; buffer_index < buffer_count; ++buffer_index) { media::PictureBuffer::TextureIds ids; std::vector<gpu::Mailbox> mailboxes; for (size_t texture_index = 0; texture_index < textures_per_buffer; ++texture_index) { const size_t texture_id = texture_index + textures_per_buffer * buffer_index; ids.push_back(texture_ids[texture_id]); mailboxes.push_back(texture_mailboxes[texture_id]); } picture_buffers.push_back(media::PictureBuffer(next_picture_buffer_id_++, size, ids, mailboxes, texture_target, format)); const bool inserted = assigned_picture_buffers_ .insert(std::make_pair(picture_buffers.back().id(), picture_buffers.back())) .second; DCHECK(inserted); } vda_->AssignPictureBuffers(picture_buffers); } void RTCVideoDecoder::DismissPictureBuffer(int32_t id) { DVLOG(3) << "DismissPictureBuffer. id=" << id; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); std::map<int32_t, media::PictureBuffer>::iterator it = assigned_picture_buffers_.find(id); if (it == assigned_picture_buffers_.end()) { NOTREACHED() << "Missing picture buffer: " << id; return; } media::PictureBuffer buffer_to_dismiss = it->second; assigned_picture_buffers_.erase(it); if (!picture_buffers_at_display_.count(id)) { // We can delete the texture immediately as it's not being displayed. for (const auto& texture_id : buffer_to_dismiss.client_texture_ids()) factories_->DeleteTexture(texture_id); return; } // Not destroying a texture in display in |picture_buffers_at_display_|. // Postpone deletion until after it's returned to us. } void RTCVideoDecoder::PictureReady(const media::Picture& picture) { DVLOG(3) << "PictureReady"; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); std::map<int32_t, media::PictureBuffer>::iterator it = assigned_picture_buffers_.find(picture.picture_buffer_id()); if (it == assigned_picture_buffers_.end()) { NOTREACHED() << "Missing picture buffer: " << picture.picture_buffer_id(); NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } media::PictureBuffer& pb = it->second; if (picture.size_changed()) { DCHECK(pb.size() != picture.visible_rect().size()); DVLOG(3) << __func__ << " Updating size of PictureBuffer[" << pb.id() << "] from:" << pb.size().ToString() << " to:" << picture.visible_rect().size().ToString(); pb.set_size(picture.visible_rect().size()); } uint32_t timestamp = 0; gfx::Rect visible_rect; GetBufferData(picture.bitstream_buffer_id(), &timestamp, &visible_rect); if (!picture.visible_rect().IsEmpty()) visible_rect = picture.visible_rect(); if (visible_rect.IsEmpty() || !gfx::Rect(pb.size()).Contains(visible_rect)) { LOG(ERROR) << "Invalid picture size: " << visible_rect.ToString() << " should fit in " << pb.size().ToString(); NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } scoped_refptr<media::VideoFrame> frame = CreateVideoFrame(picture, pb, timestamp, visible_rect, pb.pixel_format()); if (!frame) { NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } bool inserted = picture_buffers_at_display_ .insert(std::make_pair(picture.picture_buffer_id(), pb.client_texture_ids())) .second; DCHECK(inserted); // Create a WebRTC video frame. webrtc::VideoFrame decoded_image( new rtc::RefCountedObject<WebRtcVideoFrameAdapter>(frame), timestamp, 0, webrtc::kVideoRotation_0); // Invoke decode callback. WebRTC expects no callback after Release. { base::AutoLock auto_lock(lock_); DCHECK(decode_complete_callback_); if (IsBufferAfterReset(picture.bitstream_buffer_id(), reset_bitstream_buffer_id_)) { decode_complete_callback_->Decoded(decoded_image); } // Reset error counter as we successfully decoded a frame. vda_error_counter_ = 0; } } scoped_refptr<media::VideoFrame> RTCVideoDecoder::CreateVideoFrame( const media::Picture& picture, const media::PictureBuffer& pb, uint32_t timestamp, const gfx::Rect& visible_rect, media::VideoPixelFormat pixel_format) { DCHECK(pb.texture_target()); // Convert timestamp from 90KHz to ms. base::TimeDelta timestamp_ms = base::TimeDelta::FromInternalValue( base::checked_cast<uint64_t>(timestamp) * 1000 / 90); // TODO(mcasas): The incoming data may actually be in a YUV format, but may be // labelled as ARGB. This may or may not be reported by VDA, depending on // whether it provides an implementation of VDA::GetOutputFormat(). // This prevents the compositor from messing with it, since the underlying // platform can handle the former format natively. Make sure the // correct format is used and everyone down the line understands it. gpu::MailboxHolder holders[media::VideoFrame::kMaxPlanes]; for (size_t i = 0; i < pb.client_texture_ids().size(); ++i) { holders[i].mailbox = pb.texture_mailbox(i); holders[i].texture_target = pb.texture_target(); } scoped_refptr<media::VideoFrame> frame = media::VideoFrame::WrapNativeTextures( pixel_format, holders, media::BindToCurrentLoop( base::Bind(&RTCVideoDecoder::ReleaseMailbox, weak_factory_.GetWeakPtr(), factories_, picture.picture_buffer_id(), pb.client_texture_ids())), pb.size(), visible_rect, visible_rect.size(), timestamp_ms); if (frame) { frame->metadata()->SetBoolean(media::VideoFrameMetadata::ALLOW_OVERLAY, picture.allow_overlay()); #if defined(OS_ANDROID) frame->metadata()->SetBoolean(media::VideoFrameMetadata::TEXTURE_OWNER, picture.texture_owner()); frame->metadata()->SetBoolean( media::VideoFrameMetadata::WANTS_PROMOTION_HINT, picture.wants_promotion_hint()); #endif } return frame; } void RTCVideoDecoder::NotifyEndOfBitstreamBuffer(int32_t id) { DVLOG(3) << "NotifyEndOfBitstreamBuffer. id=" << id; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); auto it = bitstream_buffers_in_decoder_.find(id); if (it == bitstream_buffers_in_decoder_.end()) { NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); NOTREACHED() << "Missing bitstream buffer: " << id; return; } { base::AutoLock auto_lock(lock_); PutSHM_Locked(std::move(it->second)); } bitstream_buffers_in_decoder_.erase(it); RequestBufferDecode(); } void RTCVideoDecoder::NotifyFlushDone() { DVLOG(3) << "NotifyFlushDone"; NOTREACHED() << "Unexpected flush done notification."; } void RTCVideoDecoder::NotifyResetDone() { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); DVLOG(3) << "NotifyResetDone"; if (!vda_) return; input_buffer_data_.clear(); { base::AutoLock auto_lock(lock_); state_ = INITIALIZED; } // Send the pending buffers for decoding. RequestBufferDecode(); } void RTCVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); if (!vda_) return; LOG(ERROR) << "VDA Error:" << error; UMA_HISTOGRAM_ENUMERATION("Media.RTCVideoDecoderError", error, media::VideoDecodeAccelerator::ERROR_MAX + 1); DestroyVDA(); base::AutoLock auto_lock(lock_); state_ = DECODE_ERROR; ++vda_error_counter_; } const char* RTCVideoDecoder::ImplementationName() const { return "ExternalDecoder"; } void RTCVideoDecoder::RequestBufferDecode() { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); if (!vda_) return; MovePendingBuffersToDecodeBuffers(); while (CanMoreDecodeWorkBeDone()) { // Get a buffer and data from the queue. std::unique_ptr<base::SharedMemory> shm_buffer; BufferData buffer_data; { base::AutoLock auto_lock(lock_); // Do not request decode if VDA is resetting. if (decode_buffers_.empty() || state_ == RESETTING) return; shm_buffer = std::move(decode_buffers_.front().first); buffer_data = decode_buffers_.front().second; decode_buffers_.pop_front(); // Drop the buffers before Release is called. if (!IsBufferAfterReset(buffer_data.bitstream_buffer_id, reset_bitstream_buffer_id_)) { PutSHM_Locked(std::move(shm_buffer)); continue; } } // Create a BitstreamBuffer and send to VDA to decode. media::BitstreamBuffer bitstream_buffer( buffer_data.bitstream_buffer_id, shm_buffer->handle(), buffer_data.size, 0, base::TimeDelta::FromInternalValue(buffer_data.timestamp)); const bool inserted = bitstream_buffers_in_decoder_ .insert(std::make_pair(bitstream_buffer.id(), std::move(shm_buffer))) .second; DCHECK(inserted) << "bitstream_buffer_id " << bitstream_buffer.id() << " existed already in bitstream_buffers_in_decoder_"; RecordBufferData(buffer_data); vda_->Decode(bitstream_buffer); } } bool RTCVideoDecoder::CanMoreDecodeWorkBeDone() { return bitstream_buffers_in_decoder_.size() < kMaxInFlightDecodes; } bool RTCVideoDecoder::IsBufferAfterReset(int32_t id_buffer, int32_t id_reset) { if (id_reset == ID_INVALID) return true; int32_t diff = id_buffer - id_reset; if (diff <= 0) diff += ID_LAST + 1; return diff < ID_HALF; } bool RTCVideoDecoder::IsFirstBufferAfterReset(int32_t id_buffer, int32_t id_reset) { if (id_reset == ID_INVALID) return id_buffer == 0; return id_buffer == ((id_reset + 1) & ID_LAST); } void RTCVideoDecoder::SaveToDecodeBuffers_Locked( const webrtc::EncodedImage& input_image, std::unique_ptr<base::SharedMemory> shm_buffer, const BufferData& buffer_data) { memcpy(shm_buffer->memory(), input_image._buffer, input_image._length); // Store the buffer and the metadata to the queue. decode_buffers_.emplace_back(std::move(shm_buffer), buffer_data); } bool RTCVideoDecoder::SaveToPendingBuffers_Locked( const webrtc::EncodedImage& input_image, const BufferData& buffer_data) { DVLOG(2) << "SaveToPendingBuffers_Locked" << ". pending_buffers size=" << pending_buffers_.size() << ". decode_buffers_ size=" << decode_buffers_.size() << ". available_shm size=" << available_shm_segments_.size(); // Queued too many buffers. Something goes wrong. if (pending_buffers_.size() >= kMaxNumOfPendingBuffers) { LOG(WARNING) << "Too many pending buffers!"; return false; } // Clone the input image and save it to the queue. uint8_t* buffer = new uint8_t[input_image._length]; // TODO(wuchengli): avoid memcpy. Extend webrtc::VideoDecoder::Decode() // interface to take a non-const ptr to the frame and add a method to the // frame that will swap buffers with another. memcpy(buffer, input_image._buffer, input_image._length); webrtc::EncodedImage encoded_image( buffer, input_image._length, input_image._length); std::pair<webrtc::EncodedImage, BufferData> buffer_pair = std::make_pair(encoded_image, buffer_data); pending_buffers_.push_back(buffer_pair); return true; } void RTCVideoDecoder::MovePendingBuffersToDecodeBuffers() { base::AutoLock auto_lock(lock_); while (pending_buffers_.size() > 0) { // Get a pending buffer from the queue. const webrtc::EncodedImage& input_image = pending_buffers_.front().first; const BufferData& buffer_data = pending_buffers_.front().second; // Drop the frame if it comes before Release. if (!IsBufferAfterReset(buffer_data.bitstream_buffer_id, reset_bitstream_buffer_id_)) { delete[] input_image._buffer; pending_buffers_.pop_front(); continue; } // Get shared memory and save it to decode buffers. std::unique_ptr<base::SharedMemory> shm_buffer = GetSHM_Locked(input_image._length); if (!shm_buffer) return; SaveToDecodeBuffers_Locked(input_image, std::move(shm_buffer), buffer_data); delete[] input_image._buffer; pending_buffers_.pop_front(); } } void RTCVideoDecoder::Reset_Locked() { DVLOG(2) << __func__; lock_.AssertAcquired(); // If VDA is already resetting, no need to request the reset again. if (state_ != RESETTING) { state_ = RESETTING; factories_->GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&RTCVideoDecoder::ResetInternal, weak_factory_.GetWeakPtr())); } } void RTCVideoDecoder::ResetInternal() { DVLOG(2) << __func__; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); if (vda_) { vda_->Reset(); } else { CreateVDA(vda_codec_profile_, nullptr); if (vda_) { base::AutoLock auto_lock(lock_); state_ = INITIALIZED; } } } // static void RTCVideoDecoder::ReleaseMailbox( base::WeakPtr<RTCVideoDecoder> decoder, media::GpuVideoAcceleratorFactories* factories, int64_t picture_buffer_id, const media::PictureBuffer::TextureIds& texture_ids, const gpu::SyncToken& release_sync_token) { DCHECK(factories->GetTaskRunner()->BelongsToCurrentThread()); factories->WaitSyncToken(release_sync_token); if (decoder) { decoder->ReusePictureBuffer(picture_buffer_id); return; } // It's the last chance to delete the texture after display, // because RTCVideoDecoder was destructed. for (const auto& id : texture_ids) factories->DeleteTexture(id); } void RTCVideoDecoder::ReusePictureBuffer(int64_t picture_buffer_id) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); DVLOG(3) << "ReusePictureBuffer. id=" << picture_buffer_id; DCHECK(!picture_buffers_at_display_.empty()); PictureBufferTextureMap::iterator display_iterator = picture_buffers_at_display_.find(picture_buffer_id); const auto texture_ids = display_iterator->second; DCHECK(display_iterator != picture_buffers_at_display_.end()); picture_buffers_at_display_.erase(display_iterator); if (!assigned_picture_buffers_.count(picture_buffer_id)) { // This picture was dismissed while in display, so we postponed deletion. for (const auto& id : texture_ids) factories_->DeleteTexture(id); return; } // DestroyVDA() might already have been called. if (vda_) vda_->ReusePictureBuffer(picture_buffer_id); } bool RTCVideoDecoder::IsProfileSupported(media::VideoCodecProfile profile) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); media::VideoDecodeAccelerator::Capabilities capabilities = factories_->GetVideoDecodeAcceleratorCapabilities(); for (const auto& supported_profile : capabilities.supported_profiles) { if (profile == supported_profile.profile) { min_resolution_ = supported_profile.min_resolution; max_resolution_ = supported_profile.max_resolution; return true; } } return false; } void RTCVideoDecoder::CreateVDA(media::VideoCodecProfile profile, base::WaitableEvent* waiter) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); if (!IsProfileSupported(profile)) { DVLOG(1) << "Unsupported profile " << GetProfileName(profile); } else { vda_ = factories_->CreateVideoDecodeAccelerator(); media::VideoDecodeAccelerator::Config config(profile); if (vda_ && !vda_->Initialize(config, this)) vda_.release()->Destroy(); vda_codec_profile_ = profile; } if (waiter) waiter->Signal(); } void RTCVideoDecoder::DestroyTextures() { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since // their textures may still be in use by the user of this RTCVideoDecoder. for (const auto& picture_buffer_at_display : picture_buffers_at_display_) assigned_picture_buffers_.erase(picture_buffer_at_display.first); for (const auto& assigned_picture_buffer : assigned_picture_buffers_) { for (const auto& id : assigned_picture_buffer.second.client_texture_ids()) factories_->DeleteTexture(id); } assigned_picture_buffers_.clear(); } void RTCVideoDecoder::DestroyVDA() { DVLOG(2) << "DestroyVDA"; DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); if (vda_) vda_.release()->Destroy(); DestroyTextures(); base::AutoLock auto_lock(lock_); // Put the buffers back in case we restart the decoder. for (auto& buffer : bitstream_buffers_in_decoder_) PutSHM_Locked(std::move(buffer.second)); bitstream_buffers_in_decoder_.clear(); state_ = UNINITIALIZED; } std::unique_ptr<base::SharedMemory> RTCVideoDecoder::GetSHM_Locked( size_t min_size) { // Reuse a SHM if possible. if (!available_shm_segments_.empty() && available_shm_segments_.back()->mapped_size() >= min_size) { std::unique_ptr<base::SharedMemory> buffer = std::move(available_shm_segments_.back()); available_shm_segments_.pop_back(); return buffer; } if (available_shm_segments_.size() != num_shm_buffers_) { // Either available_shm_segments_ is empty (and we already have some SHM // buffers allocated), or the size of available segments is not large // enough. In the former case we need to wait for buffers to be returned, // in the latter we need to wait for all buffers to be returned to drop // them and reallocate with a new size. return nullptr; } if (num_shm_buffers_ != 0) { available_shm_segments_.clear(); num_shm_buffers_ = 0; } // Create twice as large buffers as required, to avoid frequent reallocation. factories_->GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&RTCVideoDecoder::CreateSHM, weak_factory_.GetWeakPtr(), kNumSharedMemorySegments, min_size * 2)); // We'll be called again after the shared memory is created. return nullptr; } void RTCVideoDecoder::PutSHM_Locked( std::unique_ptr<base::SharedMemory> shm_buffer) { lock_.AssertAcquired(); available_shm_segments_.push_back(std::move(shm_buffer)); } void RTCVideoDecoder::CreateSHM(size_t count, size_t size) { DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent(); DVLOG(2) << "CreateSHM. count=" << count << ", size=" << size; for (size_t i = 0; i < count; i++) { std::unique_ptr<base::SharedMemory> shm = factories_->CreateSharedMemory(size); if (!shm) { LOG(ERROR) << "Failed allocating shared memory of size=" << size; NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } base::AutoLock auto_lock(lock_); PutSHM_Locked(std::move(shm)); ++num_shm_buffers_; } // Kick off the decoding. RequestBufferDecode(); } void RTCVideoDecoder::RecordBufferData(const BufferData& buffer_data) { input_buffer_data_.push_front(buffer_data); // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but // that's too small for some pathological B-frame test videos. The cost of // using too-high a value is low (192 bits per extra slot). static const size_t kMaxInputBufferDataSize = 128; // Pop from the back of the list, because that's the oldest and least likely // to be useful in the future data. if (input_buffer_data_.size() > kMaxInputBufferDataSize) input_buffer_data_.pop_back(); } void RTCVideoDecoder::GetBufferData(int32_t bitstream_buffer_id, uint32_t* timestamp, gfx::Rect* visible_rect) { for (const auto& buffer_data : input_buffer_data_) { if (buffer_data.bitstream_buffer_id != bitstream_buffer_id) continue; *timestamp = buffer_data.timestamp; *visible_rect = buffer_data.visible_rect; return; } NOTREACHED() << "Missing bitstream buffer id: " << bitstream_buffer_id; } int32_t RTCVideoDecoder::RecordInitDecodeUMA(int32_t status) { // Logging boolean is enough to know if HW decoding has been used. Also, // InitDecode is less likely to return an error so enum is not used here. bool sample = (status == WEBRTC_VIDEO_CODEC_OK) ? true : false; UMA_HISTOGRAM_BOOLEAN("Media.RTCVideoDecoderInitDecodeSuccess", sample); return status; } void RTCVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent() const { DCHECK(factories_->GetTaskRunner()->BelongsToCurrentThread()); } void RTCVideoDecoder::ClearPendingBuffers() { // Delete WebRTC input buffers. for (const auto& pending_buffer : pending_buffers_) delete[] pending_buffer.first._buffer; pending_buffers_.clear(); } bool RTCVideoDecoder::ShouldFallbackToSoftwareDecode() { // Check if SW H264 implementation is available before falling back, because // it might not available on the platform due to licensing issues. if (vda_error_counter_ > kNumVDAErrorsBeforeSWFallback && (video_codec_type_ != webrtc::kVideoCodecH264 || webrtc::H264Decoder::IsSupported())) { DLOG(ERROR) << vda_error_counter_ << " errors reported by VDA, falling back to software decode"; return true; } return false; } } // namespace content
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
65dd1b37bb905d2de4ed20669edd54c1d88c65d9
100e41a4fbe0c11756f81e1996881339fd3131d8
/BST.h
23131acfc91d8ad100c823477bcf209b722d5f1b
[ "LicenseRef-scancode-public-domain" ]
permissive
Killavus/BST
3644ba985bc0a1e2c1774191aeb3cefad1eadb9f
97220f6ddb24e60e4893cba9a801537e11e9260e
refs/heads/master
2021-01-02T22:57:08.276568
2013-03-16T04:55:26
2013-03-16T04:55:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,301
h
/** * Simple Binary Search Tree Implementation - Header Files. * * Author: Marcin Grzywaczewski [killavus@gmail.com] * Institute of Computer Science, Wrocław, Poland * * 2013 **/ #ifndef __BST_H__ #define __BST_H__ #include <cstdlib> class Node { public: Node(int __key, double __value) : _key(__key), _value(__value), parent(NULL), left(NULL), right(NULL) {} ~Node() { delete left; delete right; if(parent) { if(parent->left == this) parent->left = NULL; if(parent->right == this) parent->right = NULL; } } Node *parent, *left, *right; int key() const { return _key; } double value() const { return _value; } protected: int _key; double _value; }; class BST { public: BST() : root(NULL) {} bool empty() const; void insert(int key, double value); void drop(int key); const Node* find(int key) const; void sort(int result[], int *len) const; protected: Node* findParent(int key) const; Node* findSuccessor(Node *node) const; Node *root; void inOrderPut(Node *cursor, int result[], int *ptr, int *len) const; void replaceWithSuccessor(Node *node, Node *nodeSuccessor); }; #endif //__BST_H__
[ "killavus@gmail.com" ]
killavus@gmail.com
230c6180492e5b1f91bf7b37a652e8104a13650c
0057005bb64e68fe58c5ca0e40e7112bd23badef
/ebimu_driver/include/ebimu_driver/ebimu.h
2c2e0b41651907b4705348603775d588a9813c7c
[]
no_license
jiohLee/selfcar_2020_ws
e4b3c68d16c978499dc2ec55800384ddb94d0663
0cb2044edb20d65b72f7560a2c6d22d51b95640d
refs/heads/master
2023-03-06T16:02:19.431646
2021-02-23T04:45:27
2021-02-23T04:45:27
341,431,101
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
h
#include <ros/ros.h> #include <serial/serial.h> #include <sensor_msgs/Imu.h> #include <nav_msgs/Odometry.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2/LinearMath/Quaternion.h> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/LU> #include <eigen3/Eigen/Dense> class ebimu { public: ebimu(); void publishData(); private: enum IDX { QUAT_W = 0, QUAT_X = 1, QUAT_Y = 2, QUAT_Z = 3, GYRO_X = 4, GYRO_Y = 5, GYRO_Z = 6, ACCEL_X = 7, ACCEL_Y = 8, ACCEL_Z = 9 }; // ros ros::NodeHandle nh_; ros::NodeHandle pnh_; ros::Publisher pubImu; sensor_msgs::Imu msg; // data bool initSample; int sampleNum; Eigen::MatrixXd imuSample; // quat(w x y z), gyro(x,y,z), accelo(x,y,z) Eigen::MatrixXd R; // Covariance Matrix of all data; // serial serial::Serial serialPort; // constant static const float_t DegreetoRadian; static const float_t gtometerpersec; };
[ "jiosiro@gmail.com" ]
jiosiro@gmail.com
f73cf6d2524625540d87cda919e86d4df411152c
4847bb1bafdce8a79d7ee34c36f55459f4f76ffb
/Demo/D-ChangeContrast/image/changeContrast.cpp
0d61b94de54f214b23ee5477fd665451bdeb91f6
[]
no_license
huang123aini/OpenCVDemo
d784a23b0ca3cb0441f54197ca4acf383cc85ed2
d15e6a1e714334924b6c2364207768921e3acea5
refs/heads/main
2023-08-03T09:29:35.436449
2021-09-01T08:27:48
2021-09-01T08:27:48
401,984,305
3
0
null
null
null
null
UTF-8
C++
false
false
1,719
cpp
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat image = imread("lena.jpg"); if (image.empty()) { cout << "Could not open or find the image" << endl; cin.get(); //wait for any key press return -1; } Mat imageContrastHigh2; image.convertTo(imageContrastHigh2, -1, 2, 0); //increase the contrast by 2 Mat imageContrastHigh4; image.convertTo(imageContrastHigh4, -1, 4, 0); //increase the contrast by 4 Mat imageContrastLow0_5; image.convertTo(imageContrastLow0_5, -1, 0.5, 0); //decrease the contrast by 0.5 Mat imageContrastLow0_25; image.convertTo(imageContrastLow0_25, -1, 0.25, 0); //decrease the contrast by 0.25 String windowNameOriginalImage = "Original Image"; String windowNameContrastHigh2 = "Contrast Increased by 2"; String windowNameContrastHigh4 = "Contrast Increased by 4"; String windowNameContrastLow0_5 = "Contrast Decreased by 0.5"; String windowNameContrastLow0_25 = "Contrast Decreased by 0.25"; namedWindow(windowNameOriginalImage, WINDOW_NORMAL); namedWindow(windowNameContrastHigh2, WINDOW_NORMAL); namedWindow(windowNameContrastHigh4, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_5, WINDOW_NORMAL); namedWindow(windowNameContrastLow0_25, WINDOW_NORMAL); imshow(windowNameOriginalImage, image); imshow(windowNameContrastHigh2, imageContrastHigh2); imshow(windowNameContrastHigh4, imageContrastHigh4); imshow(windowNameContrastLow0_5, imageContrastLow0_5); imshow(windowNameContrastLow0_25, imageContrastLow0_25); waitKey(0); destroyAllWindows(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
539e3892c94fd1fdda1388dced0cd547b31113f8
996b485d92eacde738cfe2a275dd1f8232a76d93
/src/d3d_visualizer/stdafx.cpp
0b55adb89bb3504c13eddefb89255625d9af30d3
[]
no_license
wangshaohua/Shortest-paths-on-road-graphs
966f2acb68b97f372c42288358beb88b17f5ed3e
51c1abb882976e3cbfe3185c8ed5d9d42a23410b
refs/heads/master
2021-01-09T06:01:35.299841
2012-05-28T12:03:37
2012-05-28T12:03:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
// stdafx.cpp : source file that includes just the standard includes // d3d_visualizer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "vasily.knk@gmail.com" ]
vasily.knk@gmail.com
e132a1daf0deec29b9e3605955c9b75730fe4f26
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2653_httpd-2.4.25.cpp
2be960067e23d688e646ba9dac2182e3b214c645
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
static apr_bucket *h2_beam_bucket_create(h2_bucket_beam *beam, apr_bucket *bred, apr_bucket_alloc_t *list, apr_size_t n) { apr_bucket *b = apr_bucket_alloc(sizeof(*b), list); APR_BUCKET_INIT(b); b->free = apr_bucket_free; b->list = list; return h2_beam_bucket_make(b, beam, bred, n); }
[ "993273596@qq.com" ]
993273596@qq.com
c8467fc5c2e110b9a1bdf8b3625f7c3db7a4cb88
cfa955080fae0b3b8674ae339fbec99a9cd0fc6d
/week-2/day-1/DataStructures/ListIntroduction1.cpp
00830841aef1a6f1c048899d04491afa6c95a033
[]
no_license
green-fox-academy/Csano97
bfd77f3adb85a584537a54ad0242bee658c7b381
09abc43750c4029b1492a9727f186fb51863f815
refs/heads/master
2020-06-09T23:31:01.583756
2019-09-19T12:29:56
2019-09-19T12:29:56
193,527,586
0
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
#include <iostream> #include <vector> int main() { std::vector<std::string> names; for (int i = 0; i < names.size(); i++) { std::cout << names[i] << std::endl; } names.emplace_back("William"); std::cout << names.empty() << std::endl; names.emplace_back("John"); names.emplace_back("Amanda"); std::cout << names.size() << std::endl; std::cout << names[2] << std::endl; std::cout << "" << std::endl; for (int i = 0; i < names.size(); i++) { std::cout << names[i] << std::endl; } std::cout << "" << std::endl; for (int i = 0; i < names.size(); i++) { std::cout << i + 1 << ". " << names[i] << std::endl; } names.erase(names.begin() + 1); std::cout << "" << std::endl; for (int i = 1; i < names.size() + 1; --i) { std::cout << names[i] << std::endl; } names.clear(); return 0; }
[ "csano.kornel@gmail.com" ]
csano.kornel@gmail.com
984a271849d5bcfa19e6f168c334d241f877cdbd
ec8e370551e1549e04ba76870f5a9cbf80e25f97
/src/instruments/eadi3D/Eadi3DFont.cpp
edf8478067118cb858edc9c1a0436d759656d3bd
[]
no_license
jmc734/OpenEaagles
7c3ea87417ac6b4b29bd1130ddb849d8cec12aa3
e28efd40555651261f4dbccc7fd618e524f999aa
refs/heads/master
2020-12-25T11:41:31.620244
2015-08-31T17:25:37
2015-08-31T17:25:37
41,508,946
0
0
null
2015-08-27T20:10:29
2015-08-27T20:10:29
null
UTF-8
C++
false
false
23,674
cpp
#include "openeaagles/instruments/eadi3D/Eadi3DFont.h" namespace Eaagles { namespace Instruments { IMPLEMENT_SUBCLASS(Eadi3DFont,"Eadi3DFont") EMPTY_SLOTTABLE(Eadi3DFont) EMPTY_SERIALIZER(Eadi3DFont) // font scaled so six stroke font points (units used below) is 1 screen unit #define XSCALE (1.0/6.0) #define YSCALE (1.0/6.0) // Default font sizes const LCreal defaultFontWidth = static_cast<LCreal>(6.0f * XSCALE); const LCreal defaultFontHeight = static_cast<LCreal>(7.0f * YSCALE); //------------------------------------------------------------------------------ // Constructor(s) //------------------------------------------------------------------------------ Eadi3DFont::Eadi3DFont() { STANDARD_CONSTRUCTOR() setFontWidth( defaultFontWidth ); setFontHeight( defaultFontHeight ); setCharacterSpacing( defaultFontWidth ); setLineSpacing( defaultFontHeight ); } //------------------------------------------------------------------------------ // copyData() -- copy this object's data //------------------------------------------------------------------------------ EMPTY_COPYDATA(Eadi3DFont) //------------------------------------------------------------------------------ // deleteData() -- delete this object's data //------------------------------------------------------------------------------ EMPTY_DELETEDATA(Eadi3DFont) //------------------------------------------------------------------------------ // outputText() -- Text output routines //------------------------------------------------------------------------------ void Eadi3DFont::outputText(const double x, const double y, const char* txt, const int n, const bool vf, const bool) { // Make sure we have characters to print if (n <= 0) return; // Make sure we have a loaded font if (isNotLoaded()) { loadFont(); if (isNotLoaded()) throw new ExpInvalidFont(); } // Prepare the output text char cbuf[MSG_BUF_LEN]; int nn = xferChars(cbuf,MSG_BUF_LEN,txt,n); if (nn <= 0) return; // Set the base glListBase(getBase()); // output the text glPushMatrix(); glTranslated(x,y,0.0); glScalef(static_cast<GLfloat>(getFontWidth()), static_cast<GLfloat>(getFontHeight()), 1.0f); if (vf) { // Vertical text char cc[2]; cc[1] = '\0'; GLdouble dy = getLineSpacing(); if (getFontHeight() != 0.0) dy = getLineSpacing() / getFontHeight(); for (int i = 0; i < nn; i++) { cc[0] = cbuf[i]; glPushMatrix(); glTranslated(0.0, -(dy * i), 0.0); glCallLists(1, GL_UNSIGNED_BYTE, cc); glPopMatrix(); } } else { // Normal text glCallLists(nn, GL_UNSIGNED_BYTE, cbuf); } glPopMatrix(); } //------------------------------------------------------------------------------ // outputText() - text output, different parameters //------------------------------------------------------------------------------ void Eadi3DFont::outputText(const char* txt, const int n, const bool vf, const bool) { // Make sure we have characters to print if (n <= 0) return; // Make sure we have a loaded font if (isNotLoaded()) { loadFont(); if (isNotLoaded()) throw new ExpInvalidFont(); } // Prepare the output text char cbuf[MSG_BUF_LEN]; int nn = xferChars(cbuf,MSG_BUF_LEN,txt,n); if (nn <= 0) return; // Set the base glListBase(getBase()); // output and scale the text glPushMatrix(); glScalef(static_cast<GLfloat>(getFontWidth()), static_cast<GLfloat>(getFontHeight()), 1.0f); if (vf) { // Vertical text char cc[2]; cc[1] = '\0'; GLdouble dy = getLineSpacing(); if (getFontHeight() != 0.0) dy = getLineSpacing() / getFontHeight(); for (int i = 0; i < nn; i++) { cc[0] = cbuf[i]; glPushMatrix(); glTranslated(0.0, -(dy * i), 0.0); glCallLists(1, GL_UNSIGNED_BYTE, cc); glPopMatrix(); } } else { // Normal text glCallLists(nn, GL_UNSIGNED_BYTE, cbuf); } glPopMatrix(); } //------------------------------------------------------------------------------ // loadFont() -- //------------------------------------------------------------------------------ void Eadi3DFont::loadFont() { if (isLoaded()) return; // create the stroke font setBase( glGenLists(256) ); createEadi3DFont( getBase() ); setFontLoaded(); } //------------------------------------------------------------------------------ // Default stroke font --- //------------------------------------------------------------------------------ enum { FONT_BEGIN = 1, FONT_NEXT, FONT_END, FONT_ADVANCE }; #define MAX_STROKES 256 #define END_OF_LIST 256 // Displays so two (2) points on Y is our origin #define XOFFSET 0 #define YOFFSET 0 static float strokeFont[][1+MAX_STROKES*3] = { { 45, FONT_BEGIN, 0.000000f, 3.500000f, FONT_END, 4.000005f, 3.500000f, FONT_ADVANCE, 6.0f, 0.0f }, { 46, FONT_BEGIN, 1.500016f, 1.000011f, FONT_NEXT, 1.999984f, 1.999984f, FONT_NEXT, 2.499989f, 1.000011f, FONT_END, 1.500016f, 1.000011f, FONT_ADVANCE, 6.0f, 0.0f }, { 47, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 4.000005f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 48, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 0.000000f, 1.500016f, FONT_NEXT, 0.000000f, 5.499984f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 1.500016f, 0.000000f, FONT_END, 0.500005f, 0.500005f, FONT_ADVANCE, 6.0f, 0.0f }, { 49, FONT_BEGIN, 1.000011f, 0.000000f, FONT_END, 2.999995f, 0.000000f, FONT_BEGIN, 1.999984f, 0.000000f, FONT_NEXT, 1.999984f, 7.000000f, FONT_END, 1.000011f, 5.000016f, FONT_ADVANCE, 6.0f, 0.0f }, { 50, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 4.000005f, 0.000000f, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 3.500000f, 4.000005f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 0.500005f, 6.499995f, FONT_END, 0.000000f, 5.499984f, FONT_ADVANCE, 6.0f, 0.0f }, { 51, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 2.499989f, FONT_NEXT, 3.500000f, 3.500000f, FONT_NEXT, 2.499989f, 4.000005f, FONT_NEXT, 1.999984f, 4.000005f, FONT_NEXT, 4.000005f, 7.000000f, FONT_END, 0.000000f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 52, FONT_BEGIN, 3.500000f, 0.000000f, FONT_NEXT, 3.500000f, 7.000000f, FONT_NEXT, 2.499989f, 6.499995f, FONT_NEXT, 0.000000f, 2.499989f, FONT_END, 4.000005f, 2.499989f, FONT_ADVANCE, 6.0f, 0.0f }, { 53, FONT_BEGIN, 0.000000f, 1.000011f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 2.999995f, FONT_NEXT, 2.999995f, 4.000005f, FONT_NEXT, 1.000011f, 4.000005f, FONT_NEXT, 0.000000f, 2.999995f, FONT_NEXT, 0.000000f, 7.000000f, FONT_END, 4.000005f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 54, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 1.999984f, FONT_NEXT, 3.500000f, 2.999995f, FONT_NEXT, 2.499989f, 3.500000f, FONT_NEXT, 1.500016f, 3.500000f, FONT_NEXT, 0.500005f, 2.999995f, FONT_END, 0.000000f, 1.999984f, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.000000f, 3.500000f, FONT_NEXT, 1.000011f, 5.999989f, FONT_END, 2.499989f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 55, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 4.000005f, 7.000000f, FONT_END, 0.000000f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 56, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 1.999984f, FONT_NEXT, 3.500000f, 2.999995f, FONT_NEXT, 2.499989f, 3.500000f, FONT_NEXT, 1.500016f, 3.500000f, FONT_NEXT, 0.500005f, 4.000005f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.000000f, 5.499984f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 3.500000f, 4.000005f, FONT_END, 2.499989f, 3.500000f, FONT_BEGIN, 1.500016f, 3.500000f, FONT_NEXT, 0.500005f, 2.999995f, FONT_NEXT, 0.000000f, 1.999984f, FONT_NEXT, 0.000000f, 1.500016f, FONT_END, 0.500005f, 0.500005f, FONT_ADVANCE, 6.0f, 0.0f }, { 57, FONT_BEGIN, 1.500016f, 0.000000f, FONT_NEXT, 2.999995f, 1.000011f, FONT_NEXT, 4.000005f, 3.500000f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 0.000000f, 5.499984f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.500005f, 4.000005f, FONT_NEXT, 1.500016f, 3.500000f, FONT_NEXT, 2.499989f, 3.500000f, FONT_NEXT, 3.500000f, 4.000005f, FONT_END, 4.000005f, 5.000016f, FONT_ADVANCE, 6.0f, 0.0f }, { 65, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 4.500011f, FONT_NEXT, 1.000011f, 6.499995f, FONT_NEXT, 1.999984f, 7.000000f, FONT_NEXT, 2.999995f, 6.499995f, FONT_NEXT, 4.000005f, 4.500011f, FONT_END, 4.000005f, 0.000000f, FONT_BEGIN, 4.000005f, 3.500000f, FONT_END, 0.000000f, 3.500000f, FONT_ADVANCE, 6.0f, 0.0f }, { 66, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 2.999995f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 1.999984f, FONT_NEXT, 3.500000f, 2.999995f, FONT_NEXT, 2.999995f, 3.500000f, FONT_NEXT, 3.500000f, 4.000005f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.999995f, 7.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 0.500005f, 7.000000f, FONT_END, 0.500005f, 0.000000f, FONT_BEGIN, 0.500005f, 3.500000f, FONT_END, 2.999995f, 3.500000f, FONT_ADVANCE, 6.0f, 0.0f }, { 67, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_END, 4.000005f, 1.500016f, FONT_BEGIN, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.000000f, 1.999984f, FONT_END, 0.500005f, 0.500005f, FONT_ADVANCE, 6.0f, 0.0f }, { 68, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.499989f, 7.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 0.500005f, 7.000000f, FONT_END, 0.500005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 69, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_END, 4.000005f, 7.000000f, FONT_BEGIN, 2.999995f, 3.500000f, FONT_END, 0.000000f, 3.500000f, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 70, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_END, 4.000005f, 7.000000f, FONT_BEGIN, 2.499989f, 4.000005f, FONT_END, 0.000000f, 4.000005f, FONT_ADVANCE, 6.0f, 0.0f }, { 71, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 2.999995f, FONT_END, 1.999984f, 2.999995f, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 0.000000f, 1.999984f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_END, 4.000005f, 5.499984f, FONT_ADVANCE, 6.0f, 0.0f }, { 72, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 0.000000f, 3.500000f, FONT_END, 4.000005f, 3.500000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 73, FONT_BEGIN, 1.000011f, 0.000000f, FONT_END, 2.999995f, 0.000000f, FONT_BEGIN, 1.999984f, 0.000000f, FONT_END, 1.999984f, 7.000000f, FONT_BEGIN, 1.000011f, 7.000000f, FONT_END, 2.999995f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 74, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.500005f, FONT_NEXT, 2.999995f, 1.500016f, FONT_END, 2.999995f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 75, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_NEXT, 0.500005f, 3.500000f, FONT_END, 0.000000f, 3.500000f, FONT_BEGIN, 0.500005f, 3.500000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 76, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 4.000005f, 0.000000f, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 0.000000f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 77, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_NEXT, 1.999984f, 4.000005f, FONT_NEXT, 4.000005f, 7.000000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 78, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_NEXT, 4.000005f, 0.000000f, FONT_END, 4.000005f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 79, FONT_BEGIN, 1.000011f, 0.000000f, FONT_NEXT, 2.999995f, 0.000000f, FONT_NEXT, 4.000005f, 1.999984f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 2.999995f, 7.000000f, FONT_NEXT, 1.000011f, 7.000000f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.000000f, 1.999984f, FONT_END, 1.000011f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 80, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 3.500000f, 4.000005f, FONT_NEXT, 2.499989f, 3.500000f, FONT_END, 0.000000f, 3.500000f, FONT_ADVANCE, 6.0f, 0.0f }, { 81, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 0.000000f, 5.499984f, FONT_END, 0.000000f, 1.500016f, FONT_BEGIN, 1.999984f, 1.999984f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 82, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 0.000000f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_NEXT, 4.000005f, 5.499984f, FONT_NEXT, 4.000005f, 5.000016f, FONT_NEXT, 3.500000f, 4.000005f, FONT_NEXT, 2.499989f, 3.500000f, FONT_END, 0.000000f, 3.500000f, FONT_BEGIN, 1.999984f, 3.500000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 83, FONT_BEGIN, 0.000000f, 1.500016f, FONT_NEXT, 0.500005f, 0.500005f, FONT_NEXT, 1.500016f, 0.000000f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 4.000005f, 1.999984f, FONT_NEXT, 3.500000f, 2.999995f, FONT_NEXT, 2.499989f, 3.500000f, FONT_NEXT, 1.500016f, 3.500000f, FONT_NEXT, 0.500005f, 4.000005f, FONT_NEXT, 0.000000f, 5.000016f, FONT_NEXT, 0.000000f, 5.499984f, FONT_NEXT, 0.500005f, 6.499995f, FONT_NEXT, 1.500016f, 7.000000f, FONT_NEXT, 2.499989f, 7.000000f, FONT_NEXT, 3.500000f, 6.499995f, FONT_END, 4.000005f, 5.499984f, FONT_ADVANCE, 6.0f, 0.0f }, { 84, FONT_BEGIN, 1.999984f, 0.000000f, FONT_END, 1.999984f, 7.000000f, FONT_BEGIN, 0.000000f, 7.000000f, FONT_END, 4.000005f, 7.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 85, FONT_BEGIN, 0.500005f, 0.500005f, FONT_NEXT, 0.000000f, 1.500016f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_NEXT, 4.000005f, 1.500016f, FONT_NEXT, 3.500000f, 0.500005f, FONT_NEXT, 2.499989f, 0.000000f, FONT_NEXT, 1.500016f, 0.000000f, FONT_END, 0.500005f, 0.500005f, FONT_ADVANCE, 6.0f, 0.0f }, { 86, FONT_BEGIN, 1.999984f, 0.000000f, FONT_NEXT, 0.000000f, 4.500011f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_NEXT, 4.000005f, 4.500011f, FONT_END, 1.999984f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 87, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_NEXT, 4.000005f, 0.000000f, FONT_NEXT, 1.999984f, 3.500000f, FONT_END, 0.000000f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 88, FONT_BEGIN, 0.000000f, 0.000000f, FONT_END, 4.000005f, 7.000000f, FONT_BEGIN, 0.000000f, 7.000000f, FONT_END, 4.000005f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { 89, FONT_BEGIN, 1.999984f, 0.000000f, FONT_NEXT, 1.999984f, 3.500000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 4.000005f, 7.000000f, FONT_END, 1.999984f, 3.500000f, FONT_ADVANCE, 6.0f, 0.0f }, { 90, FONT_BEGIN, 0.000000f, 0.000000f, FONT_NEXT, 4.000005f, 7.000000f, FONT_END, 0.000000f, 7.000000f, FONT_BEGIN, 0.500005f, 3.500000f, FONT_END, 3.500000f, 3.500000f, FONT_BEGIN, 4.000005f, 0.000000f, FONT_END, 0.000000f, 0.000000f, FONT_ADVANCE, 6.0f, 0.0f }, { END_OF_LIST } }; //------------------------------------------------------------------------------ // createEadi3DFont() - create our font //------------------------------------------------------------------------------ GLenum Eadi3DFont::createEadi3DFont(GLuint fontBase) { for (GLint i = 0; strokeFont[i][0] != END_OF_LIST; i++) { glNewList(fontBase+static_cast<unsigned int>(strokeFont[i][0]), GL_COMPILE); for (GLint j = 1; strokeFont[i][j]; j += 3) { GLint mode = (GLint) strokeFont[i][j]; if (mode == FONT_BEGIN) { glBegin(GL_LINE_STRIP); glVertex2d(static_cast<double>(strokeFont[i][j+1]-XOFFSET)*XSCALE, static_cast<double>(strokeFont[i][j+2]-YOFFSET)*YSCALE); } else if (mode == FONT_NEXT) { glVertex2d(static_cast<double>(strokeFont[i][j+1]-XOFFSET)*XSCALE, static_cast<double>(strokeFont[i][j+2]-YOFFSET)*YSCALE); } else if (mode == FONT_END) { glVertex2d(static_cast<double>(strokeFont[i][j+1]-XOFFSET)*XSCALE, static_cast<double>(strokeFont[i][j+2]-YOFFSET)*YSCALE); glEnd(); } else if (mode == FONT_ADVANCE) { glTranslated(static_cast<double>(strokeFont[i][j+1])*XSCALE, static_cast<double>(strokeFont[i][j+2])*YSCALE, 0.0); break; } } glEndList(); } return GL_TRUE; } } // End Instruments namespace } // End Eaagles namespace
[ "doug@openeaagles.org" ]
doug@openeaagles.org
f92daf9ed43ccb452f0c5addce2c114dafbaf973
a772c6fcd17f431607a58df7a6cd34873a7e5815
/code - 20210906/AddRtuMasterDlg.h
81855aea32737dfccaf0ced0abaf502d02176eda
[]
no_license
wanglvhh/VisionProject
43624c8728b6ab3812a536d2a3927be5cd62393f
ce9a3d4b5342fa9b578073e69b28881d88a6da2f
refs/heads/master
2023-07-19T08:09:42.545448
2021-09-10T01:30:05
2021-09-10T01:30:05
404,651,996
3
1
null
null
null
null
GB18030
C++
false
false
885
h
#pragma once #include "afxcmn.h" // CAddRtuMasterDlg 对话框 class CAddRtuMasterDlg : public CDialogEx { DECLARE_DYNAMIC(CAddRtuMasterDlg) public: CWinXPButtonST m_btnOk; CWinXPButtonST m_btnCancel; CSkinComboBox m_comboPort; CSkinComboBox m_comboBaudRate; CSkinComboBox m_comboParity; CSkinComboBox m_comboBitsize; CSkinComboBox m_comboStopBits; UINT m_uSlaveID; RTUMASTERNODE m_rtuMasterNode ; private: void InitAllControl() ; void InitBtnControl() ; void InitComboControl() ; void UpdateAllControl() ; public: CAddRtuMasterDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CAddRtuMasterDlg(); // 对话框数据 enum { IDD = IDD_ADD_MODBUS_RTUMASTER_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); afx_msg void OnBnClickedOk(); };
[ "wanglvhh@outlook.com" ]
wanglvhh@outlook.com
8e682f54652b9d162a6d143a5dd6bd5b4b499aff
6414fe55142d7962fb604ea8fe0efa237cbc7bad
/acwing/算法竞赛进阶指南/110 防晒.cpp
16e0b44f8fcfa361d78f4f0a7dbebce1960569d5
[]
no_license
JinRLuo/solution-of-algorithm
18e15d142e914cd86c6996298cd8118a82ba6bae
604e4549d923a85de7fd47ee6bf491b0a8657062
refs/heads/master
2020-06-20T13:47:42.211881
2019-10-31T17:08:08
2019-10-31T17:08:08
197,141,148
1
0
null
null
null
null
UTF-8
C++
false
false
867
cpp
#include <bits/stdc++.h> using namespace std; //priority_queue<int,vector<int>,greater<int> > q; int c,l; struct cow{ int mins,maxs; }cw[2505]; struct spf{ int s,cover; }sf[2505]; int cmp1(cow c1,cow c2){ if(c1.mins==c2.mins) return c1.maxs>c2.maxs; return c1.mins>c2.mins; } int cmp2(spf s1,spf s2){ return s1.s>s2.s; } int main(){ int res=0; int a,b; cin >>c>>l; for(int i=0;i<c;i++){ cin >> cw[i].mins >> cw[i].maxs; } for(int i=0;i<l;i++){ cin >> sf[i].s >> sf[i].cover; } sort(cw,cw+c,cmp1); sort(sf,sf+l,cmp2); for(int i=0;i<c;i++){ for(int j=0;j<l;j++){ if(sf[j].s>=cw[i].mins&&sf[j].s<=cw[i].maxs&&sf[j].cover!=0){ res++; sf[j].cover--; break; } } } cout << res << endl; }
[ "997331539@qq.com" ]
997331539@qq.com
7ddaa77ed3416b499cbfb0bef38f23810d044ffb
0a5f9a707ea8f5e8fe0cc5d0d631dfb9dadcdb90
/MyList.h
71177eb2ee3a4a7db4ba42ec6de06d4b386d485e
[]
no_license
q4a/dakar2011
8adda624d997fb2d22066bcbd6d799a0604045c7
7f0049d132eac5bb147e860ca33d27bf03dd80c7
refs/heads/master
2021-04-03T20:12:54.458317
2010-12-22T13:01:14
2010-12-22T13:01:14
248,392,928
0
0
null
null
null
null
UTF-8
C++
false
false
4,468
h
/**************************************************************** * * * Name: MyList.h * * * * Creator: Balazs Tuska * * * * Description: * * This file descibe my chainlist. This class is very * * similar to the built in vector class, but it is mine. * * * ****************************************************************/ //--------------------------------------------------------------------------- #ifndef MyListH #define MyListH //--------------------------------------------------------------------------- template<class T> class CMyList { public: struct element { T data; element *next; element *prev; }; private: element *last; element *first; int len; public: CMyList() { last=0; first=0; len=0; } void delList() { if( !last || !first ) { last=0; first=0; len=0; return; } element *delthis=first; element *delnext=delthis->next; while( delthis ) { delnext=delthis->next; delete delthis; delthis=delnext; } last=0; first=0; len=0; } void addFirst(T newdata) { element *addthis=new element; addthis->next=first; addthis->prev=0; addthis->data=newdata; if( first ) first->prev=addthis; first=addthis; if( !last ) last=addthis; len++; } void addLast(T newdata) { element *addthis=new element; addthis->next=0; addthis->prev=last; addthis->data=newdata; if( last ) last->next=addthis; last=addthis; if( !first ) first=addthis; len++; } void push_back(T newdata) { element *addthis=new element; addthis->next=0; addthis->prev=last; addthis->data=newdata; if( last ) last->next=addthis; last=addthis; if( !first ) first=addthis; len++; } T getFirst() { if( !first ) return T(); return first->data; } T getLast() { if( !last ) return T(); return last->data; } void delFirst() { if( !first ) return; element *delthis=first; first=first->next; if( first ) first->prev=0; else last=0; delete delthis; len--; } void delLast() { if( !last ) return; element *delthis=last; last=last->prev; if( last ) last->next=0; else first=0; delete delthis; len--; } T removeFirst() { T ret = getFirst(); delFirst(); return ret; } T removeLast() { T ret = getLast(); delLast(); return ret; } T get(int index=0) { if( !first ) return T(); element *searchthis=first; int i=0; while( i<index && searchthis!=last ) { searchthis=searchthis->next; i++; } return searchthis->data; } void del(int index=0) { if( !first ) return; element *searchthis=first; int i=0; while( i<index && searchthis!=last ) { searchthis=searchthis->next; i++; } if( !searchthis ) return; if( searchthis->next ) searchthis->next->prev=searchthis->prev; else last=searchthis->prev; if( searchthis->prev ) searchthis->prev->next=searchthis->next; else first=searchthis->next; delete searchthis; len--; } void del(element* searchthis) { if( !first ) return; if( !searchthis ) return; if( searchthis->next ) searchthis->next->prev=searchthis->prev; else last=searchthis->prev; if( searchthis->prev ) searchthis->prev->next=searchthis->next; else first=searchthis->next; delete searchthis; len--; } bool isNull() { return first==0 && last==0; } int length() { return len; } int size() { return len; } T operator[](int index) const { return get(index); } T& operator[](int index) { if( !first ) throw true; element *searchthis=first; int i=0; while( i<index && searchthis!=last ) { searchthis=searchthis->next; i++; } return searchthis->data; } element* getIterator() { return first; } element* getEnd() { return last; } }; #endif
[ "btuska@0b255d0d-b62e-4858-a3ea-23bff437c660" ]
btuska@0b255d0d-b62e-4858-a3ea-23bff437c660
99302e54a2d383fd20372d494e05731686ad2ef1
1968705c7fd4e748faee2ba41b3e26f5755b8351
/iSlapping/iSlapping/Classes/GameScene.h
45f2fabd9347362a325ada6b415776a2ec1eed6d
[]
no_license
citydeer/iSlapping
63930ad7ea8350fefef1172170f98c0efd98b79a
98c24c76012fe46d0a7e7ca11562602736a6b240
refs/heads/master
2016-09-03T07:26:58.453399
2013-09-29T07:45:01
2013-09-29T07:45:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
910
h
// // GameScene.h // iSlapping // // Created by Pang Zhenyu on 13-7-18. // // #ifndef __iSlapping__GameScene__ #define __iSlapping__GameScene__ #include "cocos2d.h" class GameScene : public cocos2d::CCLayer { public: static cocos2d::CCScene* scene(); virtual ~GameScene(); virtual bool init(); CREATE_FUNC(GameScene); void startGame(); void gameOver(); protected: void shakerMoveEnded(CCNode* pNode); void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent); private: cocos2d::CCSprite* m_pShaker; cocos2d::CCSprite* m_pShadow; int m_iScore; int m_iStatus; int m_iHits; bool m_bHitInPreviousCircle; float m_fOffset; }; class GameOverScene : public cocos2d::CCLayer { public: virtual bool init(); CREATE_FUNC(GameOverScene); void onRestart(CCObject* pSender); void onBack(CCObject* pSender); }; #endif /* defined(__iSlapping__GameScene__) */
[ "citydeer@gmail.com" ]
citydeer@gmail.com
42548b254a0ead42faeb02331c7e04b03f76feb1
9faabf9d7a6302e57b9ba9429a59b8750fc04118
/FreeSixIMU/FIMU_ADXL345.h
c7c6adc64877f8cea19df7edf238df8cd755fa5f
[]
no_license
duncanjmr/Balancing-Robot
d659212962d1231f88ba7937f0ddbd7a934f79e6
54a8ee8619e9841f260afd36e90ffb6d21b36699
refs/heads/master
2020-05-16T22:33:41.478716
2015-07-24T19:05:01
2015-07-24T19:05:01
39,651,083
0
0
null
null
null
null
UTF-8
C++
false
false
6,790
h
/************************************************************************** * * * ADXL345 Driver for Arduino * * * *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU License. * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU License V2 for more details. * * * ***************************************************************************/ #include "Arduino.h" #ifndef FIMU_ADXL345_h #define FIMU_ADXL345_h /* -- ADXL345 addresses --*/ #define ADXL345_ADDR_ALT_HIGH 0x1D // ADXL345 address when ALT is connected to HIGH #define ADXL345_ADDR_ALT_LOW 0x53 // ADXL345 address when ALT is connected to LOW /* ------- Register names ------- */ #define ADXL345_DEVID 0x00 #define ADXL345_RESERVED1 0x01 #define ADXL345_THRESH_TAP 0x1d #define ADXL345_OFSX 0x1e #define ADXL345_OFSY 0x1f #define ADXL345_OFSZ 0x20 #define ADXL345_DUR 0x21 #define ADXL345_LATENT 0x22 #define ADXL345_WINDOW 0x23 #define ADXL345_THRESH_ACT 0x24 #define ADXL345_THRESH_INACT 0x25 #define ADXL345_TIME_INACT 0x26 #define ADXL345_ACT_INACT_CTL 0x27 #define ADXL345_THRESH_FF 0x28 #define ADXL345_TIME_FF 0x29 #define ADXL345_TAP_AXES 0x2a #define ADXL345_ACT_TAP_STATUS 0x2b #define ADXL345_BW_RATE 0x2c #define ADXL345_POWER_CTL 0x2d #define ADXL345_INT_ENABLE 0x2e #define ADXL345_INT_MAP 0x2f #define ADXL345_INT_SOURCE 0x30 #define ADXL345_DATA_FORMAT 0x31 #define ADXL345_DATAX0 0x32 #define ADXL345_DATAX1 0x33 #define ADXL345_DATAY0 0x34 #define ADXL345_DATAY1 0x35 #define ADXL345_DATAZ0 0x36 #define ADXL345_DATAZ1 0x37 #define ADXL345_FIFO_CTL 0x38 #define ADXL345_FIFO_STATUS 0x39 #define ADXL345_BW_1600 0xF // 1111 #define ADXL345_BW_800 0xE // 1110 #define ADXL345_BW_400 0xD // 1101 #define ADXL345_BW_200 0xC // 1100 #define ADXL345_BW_100 0xB // 1011 #define ADXL345_BW_50 0xA // 1010 #define ADXL345_BW_25 0x9 // 1001 #define ADXL345_BW_12 0x8 // 1000 #define ADXL345_BW_6 0x7 // 0111 #define ADXL345_BW_3 0x6 // 0110 /* Interrupt PINs INT1: 0 INT2: 1 */ #define ADXL345_INT1_PIN 0x00 #define ADXL345_INT2_PIN 0x01 /* Interrupt bit position */ #define ADXL345_INT_DATA_READY_BIT 0x07 #define ADXL345_INT_SINGLE_TAP_BIT 0x06 #define ADXL345_INT_DOUBLE_TAP_BIT 0x05 #define ADXL345_INT_ACTIVITY_BIT 0x04 #define ADXL345_INT_INACTIVITY_BIT 0x03 #define ADXL345_INT_FREE_FALL_BIT 0x02 #define ADXL345_INT_WATERMARK_BIT 0x01 #define ADXL345_INT_OVERRUNY_BIT 0x00 #define ADXL345_OK 1 // no error #define ADXL345_ERROR 0 // indicates error is predent #define ADXL345_NO_ERROR 0 // initial state #define ADXL345_READ_ERROR 1 // problem reading accel #define ADXL345_BAD_ARG 2 // bad method argument class ADXL345 { public: bool status; // set when error occurs // see error code for details byte error_code; // Initial state float gains[3]; // counts to Gs ADXL345(); void init(int address); void powerOn(); void readAccel(int16_t* xyz); void readAccel(int16_t* x, int16_t* y, int16_t* z); void get_Gxyz(float *xyz); void setTapThreshold(int tapThreshold); int getTapThreshold(); void setAxisGains(float *_gains); void getAxisGains(float *_gains); void setAxisOffset(int x, int y, int z); void getAxisOffset(int* x, int* y, int*z); void setTapDuration(int tapDuration); int getTapDuration(); void setDoubleTapLatency(int floatTapLatency); int getDoubleTapLatency(); void setDoubleTapWindow(int floatTapWindow); int getDoubleTapWindow(); void setActivityThreshold(int activityThreshold); int getActivityThreshold(); void setInactivityThreshold(int inactivityThreshold); int getInactivityThreshold(); void setTimeInactivity(int timeInactivity); int getTimeInactivity(); void setFreeFallThreshold(int freeFallthreshold); int getFreeFallThreshold(); void setFreeFallDuration(int freeFallDuration); int getFreeFallDuration(); bool isActivityXEnabled(); bool isActivityYEnabled(); bool isActivityZEnabled(); bool isInactivityXEnabled(); bool isInactivityYEnabled(); bool isInactivityZEnabled(); bool isActivityAc(); bool isInactivityAc(); void setActivityAc(bool state); void setInactivityAc(bool state); bool getSuppressBit(); void setSuppressBit(bool state); bool isTapDetectionOnX(); void setTapDetectionOnX(bool state); bool isTapDetectionOnY(); void setTapDetectionOnY(bool state); bool isTapDetectionOnZ(); void setTapDetectionOnZ(bool state); void setActivityX(bool state); void setActivityY(bool state); void setActivityZ(bool state); void setInactivityX(bool state); void setInactivityY(bool state); void setInactivityZ(bool state); bool isActivitySourceOnX(); bool isActivitySourceOnY(); bool isActivitySourceOnZ(); bool isTapSourceOnX(); bool isTapSourceOnY(); bool isTapSourceOnZ(); bool isAsleep(); bool isLowPower(); void setLowPower(bool state); float getRate(); void setRate(float rate); void set_bw(byte bw_code); byte get_bw_code(); byte getInterruptSource(); bool getInterruptSource(byte interruptBit); bool getInterruptMapping(byte interruptBit); void setInterruptMapping(byte interruptBit, bool interruptPin); bool isInterruptEnabled(byte interruptBit); void setInterrupt(byte interruptBit, bool state); void getRangeSetting(byte* rangeSetting); void setRangeSetting(int val); bool getSelfTestBit(); void setSelfTestBit(bool selfTestBit); bool getSpiBit(); void setSpiBit(bool spiBit); bool getInterruptLevelBit(); void setInterruptLevelBit(bool interruptLevelBit); bool getFullResBit(); void setFullResBit(bool fullResBit); bool getJustifyBit(); void setJustifyBit(bool justifyBit); void printAllRegister(); void writeTo(byte address, byte val); private: void readFrom(byte address, int num, byte buff[]); void setRegisterBit(byte regAdress, int bitPos, bool state); bool getRegisterBit(byte regAdress, int bitPos); uint8_t _buff[6] ; //6 bytes buffer for saving data read from the device int _dev_address; }; void print_byte(byte val); #endif
[ "duncanjmr@gmail.com" ]
duncanjmr@gmail.com
ef0c20fb6ed54c1c32e21b42aee52b2d90072075
9b7a6a7ceed99f121623d75b46514e060ce84096
/include/yama/assert.hpp
721022dbc781abacc483174beed58ca9656e3cb1
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iboB/yama
16831001e68487ae3a898af423334fd20a158f73
cc47134777187048ad850505f1327e1ee578232a
refs/heads/master
2022-10-09T00:38:18.178326
2022-09-26T17:20:28
2022-09-26T17:20:28
79,384,127
12
2
NOASSERTION
2019-08-04T15:31:13
2017-01-18T21:04:10
C++
UTF-8
C++
false
false
1,347
hpp
// Copyright (c) Borislav Stanimirov // SPDX-License-Identifier: MIT // #pragma once #include <cassert> #define YAMA_ASSERT_LEVEL_NONE 0 #define YAMA_ASSERT_LEVEL_CRITICAL 1 #define YAMA_ASSERT_LEVEL_BAD 2 #define YAMA_ASSERT_LEVEL_ALL 3 #if !defined(YAMA_ASSERT_LEVEL) # define YAMA_ASSERT_LEVEL YAMA_ASSERT_LEVEL_ALL #endif #define _YAMA_NOOP(cond, msg) #if YAMA_ASSERT_LEVEL == YAMA_ASSERT_LEVEL_NONE # define YAMA_ASSERT_CRIT _YAMA_NOOP # define YAMA_ASSERT_BAD _YAMA_NOOP # define YAMA_ASSERT_WARN _YAMA_NOOP #elif YAMA_ASSERT_LEVEL == YAMA_ASSERT_LEVEL_CRITICAL # define YAMA_ASSERT_CRIT(condition, text) YAMA_ASSERT(condition, text) # define YAMA_ASSERT_BAD _YAMA_NOOP # define YAMA_ASSERT_WARN _YAMA_NOOP #elif YAMA_ASSERT_LEVEL == YAMA_ASSERT_LEVEL_BAD # define YAMA_ASSERT_CRIT(condition, text) YAMA_ASSERT(condition, text) # define YAMA_ASSERT_BAD(condition, text) YAMA_ASSERT(condition, text) # define YAMA_ASSERT_WARN _YAMA_NOOP #elif YAMA_ASSERT_LEVEL == YAMA_ASSERT_LEVEL_ALL # define YAMA_ASSERT_CRIT(condition, text) YAMA_ASSERT(condition, text) # define YAMA_ASSERT_BAD(condition, text) YAMA_ASSERT(condition, text) # define YAMA_ASSERT_WARN(condition, text) YAMA_ASSERT(condition, text) #else # error "Yama: Invalid assertion level." #endif #define YAMA_ASSERT(cond, msg) assert((cond) && msg)
[ "b.stanimirov@abv.bg" ]
b.stanimirov@abv.bg
35757a62af70d511159bebf8d3f44e0ca222acd4
cff2067d5f45dc660a95e11051bbebfee87c41b5
/04-Collision/Dagger.cpp
85ef22228e0b33be1d1061d9a63a75bdbef1d50c
[]
no_license
linhmiyano99/AirportCheckin
361e63a28cf7ffa475175678084e09f618df7b13
79545207b716cd9cdafefd68035557da5559c446
refs/heads/master
2022-12-14T21:55:52.817533
2020-09-21T06:09:24
2020-09-21T06:09:24
296,395,723
0
0
null
null
null
null
UTF-8
C++
false
false
3,090
cpp
#include "Game.h" #include "Dagger.h" #include "Torch.h" #include "Boss.h" CDagger* CDagger::__instance = NULL; CDagger::CDagger() :CWeapon() { vx = 0.5f; AddAnimation(701); state = DAGGER_STATE_HIDE; start_attack = 0; isRender = false; } CDagger* CDagger::GetInstance() { if (__instance == NULL) __instance = new CDagger(); return __instance; } void CDagger::SetPosition(float simon_x, float simon_y) { if (nx < 0) { x = simon_x + 5; } else { x = simon_x - 20; } y = simon_y; } void CDagger::Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects) { if (start_attack > 0) { CollisionWithObject(dt, *coObjects); if (GetTickCount() - start_attack > DAGGER_TIME_ATTACK) { state = DAGGER_STATE_HIDE; start_attack = 0; isRender = false; } } if (state == DAGGER_STATE_ATTACK) { if (start_attack == 0) { start_attack = GetTickCount(); isRender = true; } if (nx > 0) x += dt * vx; else x -= dt * vx; } } void CDagger::Render() { if (isRender) { animations[0]->Render(x, y, nx, 255); //RenderBoundingBox(); } } void CDagger::GetBoundingBox(float& left, float& top, float& right, float& bottom) { if (state == DAGGER_STATE_ATTACK && isRender) { left = x; right = x + 40; top = y; bottom = y + 20; } } void CDagger::CollisionWithObject(DWORD dt, vector<LPGAMEOBJECT>& listObj) { if (state == DAGGER_STATE_ATTACK) { RECT rect, rect1; float l, t, r, b; float l1, t1, r1, b1; GetBoundingBox(l, t, r, b); rect.left = (int)l; rect.top = (int)t; rect.right = (int)r; rect.bottom = (int)b; for (int i = 0; i < listObj.size(); i++) { if (dynamic_cast<CTorch*>(listObj.at(i))) { CTorch* torch = dynamic_cast<CTorch*>(listObj.at(i)); if (torch->GetState() == TORCH_STATE_EXSIST || ((torch->GetState() == BOSS_STATE_ATTACK || torch->GetState() == BOSS_STATE_FLY) && torch->GetType() == eType::BOSS)) { if (torch->GetType() == eType::BRICK_1 || torch->GetType() == eType::BRICK_2) continue; torch->GetBoundingBox(l1, t1, r1, b1); rect1.left = (int)l1; rect1.top = (int)t1; rect1.right = (int)r1; rect1.bottom = (int)b1; if (CGame::GetInstance()->isCollision(rect, rect1)) // đụng độ { torch->Hurt(); if (torch->GetEnergy() <= 0) { CSimon* simon = CSimon::GetInstance(); if (torch->GetType() == eType::GHOST) simon->SetScore(100); else if (torch->GetType() == eType::PANTHER) simon->SetScore(300); else if (torch->GetType() == eType::BAT) simon->SetScore(200); else if (torch->GetType() == eType::FISHMEN) simon->SetScore(300); if (torch->GetEnergy() <= 0) { if (torch->GetType() == eType::BOSS) { torch->SetState(BOSS_STATE_NOT_EXSIST); simon->SetScore(1000); } else { torch->SetState(TORCH_STATE_NOT_EXSIST); } } } isRender = false; Sound::GetInstance()->Play(eSound::soundHurting); break; } } } } } }
[ "17520688@gm.uit.edu.vn" ]
17520688@gm.uit.edu.vn
4ba6d2419188ea8bce1e909575db6db39ca514f1
04ad71d31c5af9d348f3b87f11331233bcf37ed8
/source/Robot.cpp
1be7dda3b306516391673b58e3e33f09484bc0a7
[]
no_license
creatorlxd/HabiRobot
2a4c48aecf7309e5d3b2c53c2778e306e9626653
56aa72445573d8b9bf487687d9eafbadc90cbe49
refs/heads/master
2020-08-11T12:00:51.443848
2019-10-12T03:40:40
2019-10-12T03:40:40
214,561,438
1
0
null
null
null
null
UTF-8
C++
false
false
3,292
cpp
#include "Robot.h" RobotApplication::RobotApplication(const Wt::WEnvironment& env) : Wt::WApplication(env) { setTitle("Robot"); useStyleSheet("main.css"); setLocale(Wt::WLocale::currentLocale()); m_pTopWrapper = root()->addWidget(std::make_unique<Wt::WPanel>()); auto ptop = std::make_unique<TopInteractiveInterface>([this]() {this->RobotProcess(); }); m_pTop = ptop.get(); m_pTopWrapper->setCentralWidget(std::move(ptop)); m_pTopWrapper->addStyleClass("top_wrapper"); root()->addWidget(std::make_unique< Wt::WBreak>()); m_pWrapper = root()->addWidget(std::make_unique<Wt::WPanel>()); auto pmessage_shower = std::make_unique<MessageShower>(g_MaxMessage); m_pMessageShower = pmessage_shower.get(); m_pWrapper->setCentralWidget(std::move(pmessage_shower)); m_pWrapper->addStyleClass("wrapper"); m_pWrapper->resize(Wt::WLength::Auto, Wt::WLength(28.0*g_MaxMessage)); //28 mean wrapper's font-size m_RobotTexts = { L"您真是太强了", L"您真是太巨了", L"您的巨,从爱尔兰到契丹,无人不知,无人不晓", L"强!!!", L"强的已经超出我的理解范围了!", L"萤火岂敢与皓月争辉" }; } void RobotApplication::RobotProcess() { this->m_pMessageShower->PushMessage(L"你:" + m_pTop->GetInputText(), "text_user", "text_wrapper_user"); this->m_pMessageShower->PushMessage(L"ai:" + m_RobotTexts[m_RandomDevice() % m_RobotTexts.size()], "text_ai", "text_wrapper_ai"); this->m_pMessageShower->Roll(); this->m_pTop->ClearInput(); } MessageShower::MessageShower(unsigned int max_size) { setContentAlignment(Wt::AlignmentFlag::Center); m_MaxMessageSize = max_size; m_TopIndex = 0; } void MessageShower::PushMessage(const Wt::WString & message, const Wt::WString& text_class, const Wt::WString& panel_class) { auto ptr = std::make_unique<Wt::WText>(message); Wt::WPanel* pw = addWidget(std::make_unique<Wt::WPanel>()); ptr->addStyleClass("text"); ptr->addStyleClass(text_class); pw->addStyleClass("text_wrapper"); pw->addStyleClass(panel_class); pw->setCentralWidget(std::move(ptr)); m_Content.push_back(pw); if ((m_Content.size() - m_TopIndex) <= m_MaxMessageSize) pw->show(); else pw->hide(); } void MessageShower::Roll() { if ((m_Content.size() - m_TopIndex) <= m_MaxMessageSize) return; else { m_Content[m_TopIndex]->hide(); m_Content[m_TopIndex + m_MaxMessageSize]->show(); m_TopIndex += 1; } } TopInteractiveInterface::TopInteractiveInterface(const std::function<void()>& func) { auto peditlabel = std::make_unique<Wt::WLineEdit>(); auto pbutton = std::make_unique<Wt::WPushButton>(); m_pLayout = setLayout(std::make_unique<Wt::WHBoxLayout>()); m_Function = func; m_pEditLabel = peditlabel.get(); m_pButton = pbutton.get(); m_pEditLabel->setFocus(); m_pButton->setText("Submit"); m_pEditLabel->addStyleClass("top_input"); m_pButton->addStyleClass("top_button"); m_pEditLabel->enterPressed().connect(func); m_pButton->clicked().connect(func); m_pLayout->addWidget(std::move(peditlabel), 1); m_pLayout->addWidget(std::move(pbutton)); } const Wt::WString & TopInteractiveInterface::GetInputText() { return m_pEditLabel->text(); } void TopInteractiveInterface::ClearInput() { m_pEditLabel->setText(""); }
[ "creatorlxd@outlook.com" ]
creatorlxd@outlook.com
01b7f846c9ec1a948e445184b44cf6cba9751113
49908c0178e86a5c03d67f634c4f3654372724e8
/Assignment1/Assignment1/main.cpp
b48120a57836466e0a83307c6dd87228d81392b9
[]
no_license
SDKng/Assignment-1
bd0c4ba73e7d8ea9b1e0613199b4e5ef926c7e69
70f25b889df97fccbf48841f76eaeeebf922d737
refs/heads/master
2021-01-25T10:01:00.618442
2018-03-05T21:05:33
2018-03-05T21:05:33
123,334,889
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
<<<<<<< HEAD //Random Change #include <iostream> #include <Engine.h> using namespace std; struct sendHelp { void sendIt() { cout << "Nope\n"; } }; int main() { Engine e; e.print(); getchar(); ======= int main() { >>>>>>> 604206e8315857628e8aa06b97a2d15a4ae191f4 return 0; }
[ "Jacobalexandersaur@gmail.com" ]
Jacobalexandersaur@gmail.com
3502db2b5f51917598e4592277ea30056f334363
6f9f54ca1e1b223a993485fb5a7524e26cb9bcce
/c/main.cpp
d31b1b03277cfc79788d0a6426a3d0fb0c05b018
[ "MIT" ]
permissive
yasuharu/dlearning
51015e29eef4172040726eea6e3c0f526d4f3b37
856f4b8aad5396c138e365e326600986f8674dfe
refs/heads/master
2021-04-12T02:55:02.002208
2018-05-03T21:40:57
2018-05-03T21:40:57
125,681,619
0
0
null
null
null
null
UTF-8
C++
false
false
6,577
cpp
#include "mnist_loader.h" #include "node.h" #include <iostream> #include <memory> #include <Eigen/Core> #define EIGEN_MPL2_ONLY #define INPUT_SIZE 784 #define HIDDEN_SIZE 50 #define OUTPUT_SIZE 10 const double VAR_DIFF = 1.0e-4; const double MOD_RATIO = 1.0e-2; namespace { Eigen::VectorXf ReLu(Eigen::VectorXf &val) { Eigen::VectorXf ret(val.rows()); for(int i = 0 ; i < val.rows() ; i++) { ret[i] = fmax(0, val[i]); } return ret; } Eigen::VectorXf Softmax(Eigen::VectorXf &val) { Eigen::VectorXf ret(val.rows()); double sum = 0; double *exp_array = new double[val.rows()]; for(int i = 0 ; i < val.rows() ; i++) { exp_array[i] = exp(val[i]); sum += exp_array[i]; } // printf("softmax sum = %f\n", sum); for(int i = 0 ; i < val.rows() ; i++) { ret[i] = exp_array[i] / sum; } delete[] exp_array; return ret; } Eigen::VectorXf MakeOnehotVector(int size, int index) { Eigen::VectorXf ret = Eigen::VectorXf::Zero(size); ret[index] = 1; return ret; } float SquareError(Eigen::VectorXf vec1, Eigen::VectorXf vec2) { assert(vec1.rows() == vec2.rows()); assert(vec1.cols() == vec2.cols()); assert(vec1.cols() == 1); float error = 0; for(int i = 0 ; i < vec1.rows() ; i++) { float v = vec1[i] - vec2[i]; error += v * v; } return error; } int MaxIndex(Eigen::VectorXf vec) { int max_index = 0; for(int i = 0 ; i < vec.rows() ; i++) { if(vec[max_index] < vec[i]) { max_index = i; } } return max_index; } }; Eigen::VectorXf Array2VectorXf(uint8_t *array, int size) { Eigen::VectorXf ret(size); // this conversion needs due to different data format for(int i = 0 ; i < size ; i++) { ret[i] = array[i]; } return ret; } Eigen::VectorXf Predict(Node &node1, Node &node2, Eigen::VectorXf input) { Eigen::VectorXf temp; temp = node1.Calc(input); temp = ReLu(temp); temp = node2.Calc(temp); temp = Softmax(temp); return temp; } double CalcError(Node &node1, Node &node2, Eigen::VectorXf input, Eigen::VectorXf ans) { Eigen::VectorXf output = Predict(node1, node2, input); double error_rate = SquareError(output, ans); return error_rate; } int main() { std::vector<std::shared_ptr<Image> > train_image_list; std::vector<uint8_t> train_label_list; std::vector<std::shared_ptr<Image> > test_image_list; std::vector<uint8_t> test_label_list; Eigen::initParallel(); Eigen::setNbThreads(4); printf("[INFO] load image...\n"); std::shared_ptr<MnistLoader> loader = std::make_shared<MnistLoader>(); if(loader->LoadImage("../train-images-idx3-ubyte", train_image_list) == false) { printf("[ERROR] load data error.\n"); } if(loader->LoadLabel("../train-labels-idx1-ubyte", train_label_list) == false) { printf("[ERROR] load data error.\n"); } if(loader->LoadImage("../t10k-images-idx3-ubyte", test_image_list) == false) { printf("[ERROR] load data error.\n"); } if(loader->LoadLabel("../t10k-labels-idx1-ubyte", test_label_list) == false) { printf("[ERROR] load data error.\n"); } Node node1(INPUT_SIZE, HIDDEN_SIZE); if(node1.Load("weight_node1") == false) { printf("[INFO] node1 weight value initialize with random value.\n"); } Node node2(HIDDEN_SIZE, OUTPUT_SIZE); if(node2.Load("weight_node2") == false) { printf("[INFO] node2 weight value initialize with random value.\n"); } printf("[INFO] training...\n"); sranddev(); // for(int image_index = 0 ; image_index < train_image_list.size() ; image_index++) // for(int image_index = 0 ; image_index < 100 ; image_index++) for(int train_count = 0 ; train_count < 100 ; train_count++) { int image_index = rand() % train_image_list.size(); // if(image_index % 100 == 0) // { // printf("[INFO] exec %d/%d\n", image_index, (int)train_label_list.size()); // } std::shared_ptr<Image> image = train_image_list[image_index]; Eigen::VectorXf input = Array2VectorXf(image->image, image->image_size); int ans = train_label_list[image_index]; Eigen::VectorXf ans_vec = MakeOnehotVector(OUTPUT_SIZE, ans); // printf("image_index = %d, ans = %d\n", image_index, ans); input.normalize(); double *node1_mod = new double[node1.GetMaxWeightIndex()]; double *node2_mod = new double[node2.GetMaxWeightIndex()]; for(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++) { double dyp = 0; double dyn = 0; node1.PushWeightDiff(i, VAR_DIFF); dyp = CalcError(node1, node2, input, ans_vec); node1.PopWeightDiff(); node1.PushWeightDiff(i, -VAR_DIFF); dyn = CalcError(node1, node2, input, ans_vec); node1.PopWeightDiff(); node1_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF); // printf("dyp=%f, dyn=%f, mod=%f\n", dyp, dyn, node1_mod[i]); } for(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++) { double dyp = 0; double dyn = 0; node2.PushWeightDiff(i, VAR_DIFF); dyp = CalcError(node1, node2, input, ans_vec); node2.PopWeightDiff(); node2.PushWeightDiff(i, -VAR_DIFF); dyn = CalcError(node1, node2, input, ans_vec); node2.PopWeightDiff(); node2_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF); // printf("dyp=%lf, dyn=%lf, mod=%lf\n", dyp, dyn, node2_mod[i]); } for(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++) { node1.AddWeight(i, node1_mod[i] * -MOD_RATIO); } for(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++) { node2.AddWeight(i, node2_mod[i] * -MOD_RATIO); } delete[] node1_mod; delete[] node2_mod; //return 1; // if(image_index == 10) // { // // optimization test // return 1; // } } node1.Save("weight_node1"); node2.Save("weight_node2"); printf("[INFO] test...\n"); std::vector<uint8_t> result_list; for(int image_index = 0 ; image_index < test_image_list.size() ; image_index++) { std::shared_ptr<Image> image = test_image_list[image_index]; Eigen::VectorXf input = Array2VectorXf(image->image, image->image_size); input.normalize(); Eigen::VectorXf output = Predict(node1, node2, input); int result = MaxIndex(output); result_list.push_back(result); } assert(result_list.size() == test_label_list.size()); int success_count = 0; int fail_count = 0; for(int i = 0 ; i < result_list.size() ; i++) { // printf("result = %d, test = %d,", result_list[i], test_label_list[i]); if(result_list[i] == test_label_list[i]) { success_count++; }else { fail_count++; } } float accuracy = success_count / (float)(success_count + fail_count); std::cout << "accuracy = " << accuracy << std::endl; return 0; }
[ "admin@mail.yasuharu.net" ]
admin@mail.yasuharu.net
c46dacf12bda4fb69f8df78cfd1b18c9be799d53
386b7dae839c2288dfd8643d79e64466caad03d0
/src/snp_overlap/Overlap_snps.h
ad73e3168d5f5a83f92e98862c9b018c44dd72e8
[ "MIT" ]
permissive
apaul7/SURVIVOR
09a92beb67b6ed9e1fb5c61f4ca5f6ac2968bee9
382eecc63362cda7b63aacf6b16b4fc967680bb9
refs/heads/master
2020-04-25T06:24:05.653303
2019-10-17T12:39:54
2019-10-17T12:39:54
172,579,689
0
0
MIT
2019-02-25T20:29:28
2019-02-25T20:29:27
null
UTF-8
C++
false
false
974
h
/* * Overlap_snps.h * * Created on: Jul 18, 2017 * Author: sedlazec */ #ifndef SNP_OVERLAP_OVERLAP_SNPS_H_ #define SNP_OVERLAP_OVERLAP_SNPS_H_ #include <string.h> #include <string> #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <vector> #include <iosfwd> #include <algorithm> #include <sstream> #include <algorithm> #include "../simulator/Eval_vcf.h" #include "../merge_vcf/Paramer.h" using namespace std; void overlap_snpsGWASDB(std::string svs_file, std::string snp_file, int max_dist, int min_svs, int allele, std::string output); void overlap_snps(std::string svs_file, std::string snp_file, int max_dist, int min_svs, int allele, std::string output); void overlap_snps_gwas(std::string svs_file, std::string random_SV,int max_dist, int min_svs, std::string output); void generate_random_regions(std::string genome_file, std::string svs_vcf, int min_svs, std::string output); #endif /* SNP_OVERLAP_OVERLAP_SNPS_H_ */
[ "fritz.sedlazeck@gmail.com" ]
fritz.sedlazeck@gmail.com
5d2b7605cb02768f9b123638f77452132921b82f
f0396db85e1302c62fb86189beaca4a4e8a0ed0e
/src/ConfigManager.cpp
ba2c1df80db1631af284290e81a71fa451083b1e
[]
no_license
humdingerb/Helios
1f0d5a2d6ac86662b8107e0ce2a223a766dc04c2
f5d1c025f3b2836a42108f481d70b04b705f58d2
refs/heads/master
2021-01-10T23:37:30.564384
2016-10-09T17:01:02
2016-10-09T17:01:02
70,417,602
0
0
null
null
null
null
UTF-8
C++
false
false
6,161
cpp
#include "ConfigManager.h" #include <stdio.h> #include <TypeConstants.h> #include <Application.h> #include <AppFileInfo.h> #include <app/Roster.h> #include <Bitmap.h> ConfigManager::ConfigManager(const char *filename, bool reg) { initcheck=B_OK; configMsg=new BMessage(); configfile=new BFile(filename, B_READ_WRITE | B_CREATE_FILE); ReadConfiguration(); registermime=reg; } ConfigManager::~ConfigManager() { delete configMsg; delete configfile; } status_t ConfigManager::InitCheck() { return initcheck; } bool ConfigManager::HasData(const char *name) { return configMsg->GetInfo(name, &codeFound)==B_OK; } // BOOL void ConfigManager::SetBool(const char *name, bool value) { configMsg->RemoveName(name); configMsg->AddBool(name, value); } bool ConfigManager::GetBool(const char *name) { bool value; if (configMsg->FindBool(name, &value)!=B_OK) value=false; return value; } // INT64 void ConfigManager::SetInt64(const char *name, int64 value, int32 index) { if (configMsg->ReplaceInt64(name, index, value)!=B_OK) configMsg->AddInt64(name, value); } int64 *ConfigManager::GetInt64(const char *name, int32 index) { int64 value; if (configMsg->FindInt64(name, index, &value)!=B_OK) return NULL; return new int64(value); } // INT32 void ConfigManager::SetInt32(const char *name, int32 value) { configMsg->RemoveName(name); configMsg->AddInt32(name, value); } int32 ConfigManager::GetInt32(const char *name) { int32 value; configMsg->FindInt32(name, &value); return value; } // INT16 void ConfigManager::SetInt16(const char *name, int16 value) { configMsg->RemoveName(name); configMsg->AddInt16(name, value); } int16 ConfigManager::GetInt16(const char *name) { int16 value; configMsg->FindInt16(name, &value); return value; } // INT8 void ConfigManager::SetInt8(const char *name, int8 value) { configMsg->RemoveName(name); configMsg->AddInt8(name, value); } int8 ConfigManager::GetInt8(const char *name) { int8 value; configMsg->FindInt8(name, &value); return value; } // FLOAT void ConfigManager::SetFloat(const char *name, float value, int32 index) { if (configMsg->ReplaceFloat(name, index, value)!=B_OK) configMsg->AddFloat(name, value); } float *ConfigManager::GetFloat(const char *name, int32 index) { float value; if (configMsg->FindFloat(name, index, &value)!=B_OK) return NULL; return new float(value); } // RECT void ConfigManager::SetRect(const char *name, BRect value) { configMsg->RemoveName(name); configMsg->AddRect(name, value); } BRect *ConfigManager::GetRect(const char *name) { static BRect *value=new BRect(); configMsg->FindRect(name, value); return value; } // rgb_color void ConfigManager::SetColor(const char *name, rgb_color value) { configMsg->RemoveName(name); configMsg->AddData(name, B_RGB_COLOR_TYPE, &value, sizeof(value)); } rgb_color ConfigManager::GetColor(const char *name) { rgb_color *color; ssize_t length; configMsg->FindData(name, B_RGB_COLOR_TYPE, (const void **)(&color), &length); return *color; } // BMessage void ConfigManager::SetMessage(const char *name, BMessage *msg) { configMsg->RemoveName(name); configMsg->AddMessage(name, msg); } BMessage *ConfigManager::GetMessage(const char *name) { static BMessage *msg=new BMessage(); configMsg->FindMessage(name, msg); return msg; } // STRING void ConfigManager::SetString(const char *name, BString *value) { configMsg->RemoveName(name); configMsg->AddString(name, *value); } void ConfigManager::SetString(const char *name, const char *value) { configMsg->RemoveName(name); configMsg->AddString(name, value); } BString *ConfigManager::GetString(const char *name) { static BString *value=new BString(""); configMsg->FindString(name, value); return value; } // STRING WITH INDICES void ConfigManager::SetStringI(const char *name, BString *value, int32 index) { if (index+1>CountStrings(name)) configMsg->AddString(name, *value); else configMsg->ReplaceString(name, index, *value); } void ConfigManager::SetStringI(const char *name, const char *value, int32 index) { if (index+1>CountStrings(name)) configMsg->AddString(name, value); else configMsg->ReplaceString(name, index, value); } BString *ConfigManager::GetStringI(const char *name, int32 index) { static BString *value=new BString(""); configMsg->FindString(name, index, value); return value; } int32 ConfigManager::CountStrings(const char *name) { int32 count=0; type_code code; configMsg->GetInfo(name, &code, &count); return count; } void ConfigManager::RemoveString(const char *name, int32 index) { configMsg->RemoveData(name, index); } // set file type database entry for Helios project files void RegisterMIMEType() { app_info appinfo; BBitmap *licon, *micon; be_app->GetAppInfo(&appinfo); BAppFileInfo *appfileinfo=new BAppFileInfo(new BFile(&appinfo.ref, B_READ_WRITE)); BMimeType *projectmime=new BMimeType("application/x-vnd.Helios-project"); licon=new BBitmap(BRect(0,0,31,31), B_CMAP8); appfileinfo->GetIcon(licon, B_LARGE_ICON); projectmime->SetIconForType("application/x-vnd.Helios-project",licon, B_LARGE_ICON); projectmime->SetIcon(licon, B_LARGE_ICON); micon=new BBitmap(BRect(0,0,15,15), B_CMAP8); appfileinfo->GetIcon(micon, B_MINI_ICON); projectmime->SetIconForType("application/x-vnd.Helios-project",micon, B_MINI_ICON); projectmime->SetIcon(micon, B_MINI_ICON); projectmime->SetPreferredApp(appinfo.signature); projectmime->SetLongDescription("Helios CDRECORDer Project File"); projectmime->SetShortDescription("Helios Project"); projectmime->Install(); delete projectmime; delete appfileinfo; delete licon; delete micon; } void ConfigManager::ReadConfiguration() { if ((initcheck=configfile->InitCheck())==B_OK) { off_t filesize=0; configfile->GetSize(&filesize); if (filesize>0) { configfile->Seek(0, SEEK_SET); if (configMsg->Unflatten(configfile)==B_BAD_VALUE) { configfile->SetSize(0); } } else { if (registermime) RegisterMIMEType(); } } } void ConfigManager::WriteConfiguration() { if ((initcheck=configfile->InitCheck())==B_OK) { configfile->Seek(0, SEEK_SET); configMsg->Flatten(configfile); } }
[ "ajcsweb@gmail.com" ]
ajcsweb@gmail.com
d6b64bafc457b1c6a848b72862b068debf03c9cf
c3696e7b799f18aeff825345059ef1aa10d7515c
/LuaProject/Block.cpp
ae1c56aedb73c9238bf0102876d46f5cada8fa21
[]
no_license
Maakuz/LuaProject
27ba21698afd113ac330ad82524cb5ec6ce42943
42dfdaf8e0080b7d49bb854408334b21f1e952eb
refs/heads/master
2020-07-21T09:55:07.507001
2019-09-06T15:29:56
2019-09-06T15:29:56
206,823,359
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
#include "Block.h" Block::Block(sf::Texture* tex, int x, int y, int width, int height, int u, int v) : Entity(tex, width, height) { this->setPosition(float(x), float(y)); this->getBox()->updatePosition(x, y); this->setTextureRect(sf::IntRect(u, v, width, height)); } Block::~Block() { }
[ "markuswerdien@hotmail.com" ]
markuswerdien@hotmail.com
cea1b4480de9ae527399b8b449ffdc34e897439f
3531dd9f52b11ae26d0c5f624a815538bf4c1964
/templates/060_Standard_Template_Library_(STL)​/Section-20-The-Standard-Template-Library-(STL)​/Algorithms/main.cpp
e4813604bf5930ad4cac1bf3358e80f70ee3e437
[]
no_license
syurskyi/CPP_Topics
b9a481fa828fb763fe4e21388cd04b4e90c2cd96
c9851ab9e254e2fc01ab1bb819ca1d642f623fae
refs/heads/master
2022-12-11T16:12:49.219989
2020-09-01T22:36:08
2020-09-01T22:36:08
277,678,709
0
0
null
null
null
null
UTF-8
C++
false
false
3,510
cpp
// Section 20 // Algorithms ? ios.. ? ve.. ? <list> ? <algorithm> ? cct.. c_ Person { st. st.. name; in. age; pu.. Person() = de..; Person(st. st.. name, in. age) : name{name}, age{age} {} b.. op..<(co.. Person &rhs) co.. { r_ this->age < rhs.age; } b.. operator__(co.. Person &rhs) co.. { r_ (this->name __ rhs.name && this->age __ rhs.age); } }; // Find an element in a container v.. find_test st. c.. __ "\n========================" __ st. e.. st. ve..<in.> vec {1,2,3,4,5}; a.. loc = st. find(st. begin(vec), st. end(vec), 1); __ (loc != st. end(vec)) st. c.. __ "Found the number: " __ *loc __ st. e.. ____ st. c.. __ "Couldn't find the number" __ st. e.. st. list<Person> players { {"Larry", 18}, {"Moe", 20}, {"Curly", 21} }; a.. loc1 = st. find(players.begin(), players.end(), Person{"Moe", 20}); __ (loc1 != players.end()) st. c.. __ "Found Moe" __ st. e.. ____ st. c.. __ "Moe not found" __ st. e.. } // Count the number of elements in a container v.. count_test st. c.. __ "\n========================" __ st. e.. st. ve..<in.> vec {1,2,3,4,5,1,2,1}; in. num = st. count(vec.begin(), vec.end(), 1); st. c.. __ num __ " occurrences found" __ st. e.. } // Count the number of occurences of an element in a container // based on a predicate using a lambda expression v.. count_if_test st. c.. __ "\n========================" __ st. e.. // count only if the element is even st. ve..<in.> vec {1,2,3,4,5,1,2,1,100}; in. num = st. count_if(vec.begin(), vec.end(), [](in. x) { r_ x %2 __ 0; }); st. c.. __ num __ " even numbers found" __ st. e.. num = st. count_if(vec.begin(), vec.end(), [](in. x) { r_ x %2 != 0; }); st. c.. __ num __ " odd numbers found" __ st. e.. // how can we determine how many elements in vec are >= 5? num = st. count_if(vec.begin(), vec.end(), [](in. x) { r_ x>=5; }); st. c.. __ num __ " numbers are >= 5" __ st. e.. } // Replace occurrences of elements in a container v.. replace_test st. c.. __ "\n========================" __ st. e.. st. ve..<in.> vec {1,2,3,4,5,1,2,1}; ___ (a.. i: vec) { st. c.. __ i __ " "; } st. c.. __ st. e.. st. replace(vec.begin(), vec.end(), 1, 100); ___ (a.. i: vec) { st. c.. __ i __ " "; } st. c.. __ st. e.. } v.. all_of_test st. ve..<in.> vec1 {1,3,5,7,9,1,3,13,19,5}; __ (st. all_of(vec1.begin(), vec1.end(), [](in. x) { r_ x > 10; })) st. c.. __ "All the elements are > 10" __ st. e.. ____ st. c.. __ "Not all the elements are > 10" __ st. e.. __ (st. all_of(vec1.begin(), vec1.end(), [](in. x) { r_ x < 20; })) st. c.. __ "All the elements are < 20" __ st. e.. ____ st. c.. __ "Not all the elements are < 20" __ st. e.. } // Transform elements in a container - string in this example v.. string_transform_test st. c.. __ "\n========================" __ st. e.. st. st.. str1 {"007_This is a test"}; st. c.. __ "Before transform: " __ str1 __ st. e.. st. transform(str1.begin(), str1.end(), str1.begin(), ::toupper); st. c.. __ "After transform: " __ str1 __ st. e.. } in. main find_test(); // count_test(); // count_if_test(); // replace_test(); // all_of_test(); // string_transform_test(); r_ 0; }
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
b71b06c76b9e52e735af9041e3dd6656cf8a2530
44d05587f8578ee645ee572dff25a2496b865aac
/stm32cubeide/AuCAR_lib/ROS/py_trees_msgs/OpenBlackboardWatcher.h
e4fb7633ed794a72f4cb29d07ac472c363254f4f
[ "Apache-2.0" ]
permissive
YeongJunKim/AuCAR
3b1eb4c06b3c5533a45272f69f323019ea920f34
c2abb1ecbab2a25b1dd896ddbea50ac76fa4478d
refs/heads/master
2021-07-16T11:09:50.274652
2020-08-13T04:32:35
2020-08-13T04:32:35
188,990,518
2
1
Apache-2.0
2020-06-17T18:24:59
2019-05-28T08:48:04
C
UTF-8
C++
false
false
3,947
h
#ifndef _ROS_SERVICE_OpenBlackboardWatcher_h #define _ROS_SERVICE_OpenBlackboardWatcher_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace py_trees_msgs { static const char OPENBLACKBOARDWATCHER[] = "py_trees_msgs/OpenBlackboardWatcher"; class OpenBlackboardWatcherRequest : public ros::Msg { public: uint32_t variables_length; typedef char* _variables_type; _variables_type st_variables; _variables_type * variables; OpenBlackboardWatcherRequest(): variables_length(0), variables(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->variables_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->variables_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->variables_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->variables_length >> (8 * 3)) & 0xFF; offset += sizeof(this->variables_length); for( uint32_t i = 0; i < variables_length; i++){ uint32_t length_variablesi = strlen(this->variables[i]); varToArr(outbuffer + offset, length_variablesi); offset += 4; memcpy(outbuffer + offset, this->variables[i], length_variablesi); offset += length_variablesi; } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t variables_lengthT = ((uint32_t) (*(inbuffer + offset))); variables_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); variables_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); variables_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->variables_length); if(variables_lengthT > variables_length) this->variables = (char**)realloc(this->variables, variables_lengthT * sizeof(char*)); variables_length = variables_lengthT; for( uint32_t i = 0; i < variables_length; i++){ uint32_t length_st_variables; arrToVar(length_st_variables, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_st_variables; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_st_variables-1]=0; this->st_variables = (char *)(inbuffer + offset-1); offset += length_st_variables; memcpy( &(this->variables[i]), &(this->st_variables), sizeof(char*)); } return offset; } const char * getType(){ return OPENBLACKBOARDWATCHER; }; const char * getMD5(){ return "8f184382c36d538fab610317191b119e"; }; }; class OpenBlackboardWatcherResponse : public ros::Msg { public: typedef const char* _topic_type; _topic_type topic; OpenBlackboardWatcherResponse(): topic("") { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_topic = strlen(this->topic); varToArr(outbuffer + offset, length_topic); offset += 4; memcpy(outbuffer + offset, this->topic, length_topic); offset += length_topic; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_topic; arrToVar(length_topic, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_topic; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_topic-1]=0; this->topic = (char *)(inbuffer + offset-1); offset += length_topic; return offset; } const char * getType(){ return OPENBLACKBOARDWATCHER; }; const char * getMD5(){ return "d8f94bae31b356b24d0427f80426d0c3"; }; }; class OpenBlackboardWatcher { public: typedef OpenBlackboardWatcherRequest Request; typedef OpenBlackboardWatcherResponse Response; }; } #endif
[ "dud3722000@naver.com" ]
dud3722000@naver.com
73597282635e555e9eeba1e9f14ef0aebaf1e5ce
332297e5b7277ad48ec867933bd2c88bf49e8ff4
/components/sync/driver/sync_service.cc
44f439f721082777ae75374827d97da6dc5457ed
[ "BSD-3-Clause" ]
permissive
chorman0773/chromium
3b4147a24e41dab4abe82cde84b9a6f52dd7ee67
ba837a33fd29823d60e8119daf0d5b8113384ca6
refs/heads/master
2022-11-29T21:39:15.228897
2018-11-13T15:42:24
2018-11-13T15:42:24
157,396,636
1
0
NOASSERTION
2018-11-13T15:42:25
2018-11-13T14:52:16
null
UTF-8
C++
false
false
2,253
cc
// Copyright 2015 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 "components/sync/driver/sync_service.h" namespace syncer { SyncSetupInProgressHandle::SyncSetupInProgressHandle(base::Closure on_destroy) : on_destroy_(on_destroy) {} SyncSetupInProgressHandle::~SyncSetupInProgressHandle() { on_destroy_.Run(); } SyncUserSettings* SyncService::GetUserSettings() { return nullptr; } const SyncUserSettings* SyncService::GetUserSettings() const { return nullptr; } bool SyncService::IsSyncFeatureEnabled() const { // Note: IsFirstSetupComplete() shouldn't usually be true if we don't have a // primary account, but it could happen if the account changes from primary to // secondary. return GetDisableReasons() == DISABLE_REASON_NONE && IsFirstSetupComplete() && IsAuthenticatedAccountPrimary(); } bool SyncService::CanSyncFeatureStart() const { return GetDisableReasons() == DISABLE_REASON_NONE; } bool SyncService::IsEngineInitialized() const { switch (GetTransportState()) { case TransportState::DISABLED: case TransportState::WAITING_FOR_START_REQUEST: case TransportState::START_DEFERRED: case TransportState::INITIALIZING: return false; case TransportState::PENDING_DESIRED_CONFIGURATION: case TransportState::CONFIGURING: case TransportState::ACTIVE: return true; } NOTREACHED(); return false; } bool SyncService::IsSyncFeatureActive() const { if (!IsSyncFeatureEnabled()) { return false; } switch (GetTransportState()) { case TransportState::DISABLED: case TransportState::WAITING_FOR_START_REQUEST: case TransportState::START_DEFERRED: case TransportState::INITIALIZING: case TransportState::PENDING_DESIRED_CONFIGURATION: return false; case TransportState::CONFIGURING: case TransportState::ACTIVE: return true; } NOTREACHED(); return false; } bool SyncService::IsFirstSetupInProgress() const { return !IsFirstSetupComplete() && IsSetupInProgress(); } bool SyncService::HasUnrecoverableError() const { return HasDisableReason(DISABLE_REASON_UNRECOVERABLE_ERROR); } } // namespace syncer
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
56ada7ddf33d1100a8f24311e4ef121b264f3b9f
edcde36aec5ab5166510e9e2fb6afd369deaf13c
/src/compiler/tempest/intrinsic/defns.hpp
6cacc695df67f48fa9c1a23b1146f00bd4a44c18
[]
no_license
viridia/tempest
585f6f44b7047f60a9799fd082e168e815bd8264
a0ecf8269dc68edf182dce62bbef6b9602a0adc6
refs/heads/master
2020-03-23T11:53:47.431485
2018-11-16T01:59:28
2018-11-16T01:59:28
141,525,372
0
0
null
null
null
null
UTF-8
C++
false
false
2,769
hpp
#ifndef TEMPEST_INTRINSIC_DEFNS_HPP #define TEMPEST_INTRINSIC_DEFNS_HPP 1 #ifndef TEMPEST_SEMA_GRAPH_TYPE_HPP #include "tempest/sema/graph/type.hpp" #endif #ifndef TEMPEST_SEMA_GRAPH_DEFN_HPP #include "tempest/sema/graph/defn.hpp" #endif #ifndef TEMPEST_SEMA_GRAPH_TYPESTORE_HPP #include "tempest/sema/graph/typestore.hpp" #endif #ifndef TEMPEST_SUPPORT_ALLOCATOR_HPP #include "tempest/support/allocator.hpp" #endif namespace tempest::intrinsic { using tempest::sema::graph::Defn; using tempest::sema::graph::FunctionDefn; using tempest::sema::graph::Member; using tempest::sema::graph::SymbolTable; using tempest::sema::graph::Type; using tempest::sema::graph::TypeDefn; using tempest::sema::graph::TypeStore; using tempest::sema::graph::ValueDefn; struct PrimitiveOperators { std::unique_ptr<FunctionDefn> add; std::unique_ptr<FunctionDefn> subtract; std::unique_ptr<FunctionDefn> multiply; std::unique_ptr<FunctionDefn> divide; std::unique_ptr<FunctionDefn> remainder; std::unique_ptr<FunctionDefn> lsh; std::unique_ptr<FunctionDefn> rsh; std::unique_ptr<FunctionDefn> bitOr; std::unique_ptr<FunctionDefn> bitAnd; std::unique_ptr<FunctionDefn> bitXor; std::unique_ptr<FunctionDefn> lt; std::unique_ptr<FunctionDefn> le; std::unique_ptr<FunctionDefn> uminus; std::unique_ptr<FunctionDefn> comp; }; /** Class to contain all of the various intrinsic definitions. */ class IntrinsicDefns { public: IntrinsicDefns(); std::unique_ptr<SymbolTable> builtinScope; std::unique_ptr<TypeDefn> objectClass; std::unique_ptr<TypeDefn> throwableClass; std::unique_ptr<TypeDefn> flexAllocClass; TypeDefn* iterableType = nullptr; TypeDefn* iteratorType = nullptr; TypeDefn* addressType = nullptr; PrimitiveOperators intOps; PrimitiveOperators uintOps; PrimitiveOperators floatOps; // Equality intrinsic std::unique_ptr<FunctionDefn> eq; // Register an externally-declared intrinsic bool registerExternal(Defn* d); // Singleton getter. static IntrinsicDefns* get(); private: TypeStore _types; std::unique_ptr<TypeDefn> makeTypeDefn(Type::Kind kind, llvm::StringRef name); std::unique_ptr<FunctionDefn> makeInfixOp( llvm::StringRef name, Type* argType, IntrinsicFn intrinsic); std::unique_ptr<FunctionDefn> makeUnaryOp( llvm::StringRef name, Type* argType, IntrinsicFn intrinsic); std::unique_ptr<FunctionDefn> makeRelationalOp( llvm::StringRef name, Type* argType, IntrinsicFn intrinsic); ValueDefn* addValueDefn( std::unique_ptr<TypeDefn>& td, Member::Kind kind, llvm::StringRef name); static IntrinsicDefns* instance; }; } #endif
[ "viridia@gmail.com" ]
viridia@gmail.com
14c836ab43bd9c46758e41e7105cd6d3c418f64f
4cdae2fb4fffad141aa04865653edb454be753ba
/microanalyzer.h
5dc6f85e56a2b44ab04bd8f0355a9f6de66909c7
[]
no_license
juancarrascom/qt_maui_demo
e208195eeb1566fdd3f0193e999e67453b9b3f26
9d243ecb8156f714eb48c0773a034627fc5cff0d
refs/heads/main
2023-08-22T07:49:06.364757
2021-10-27T09:58:05
2021-10-27T09:58:05
419,383,080
0
0
null
null
null
null
UTF-8
C++
false
false
727
h
#ifndef MICROANALYZER_H #define MICROANALYZER_H #include <QObject> #include "modbus.h" #include "maparametters.h" class modbus; class maParametters; class microAnalyzer; class microAnalyzer : public QObject { Q_OBJECT public: explicit microAnalyzer(QObject *parent = nullptr); Q_INVOKABLE void readData(); Q_INVOKABLE void connectSensor(); signals: public slots: void getData(int address, int value); private: modbus *m_master=new modbus(); maParametters map; GroupSerialNumber gsm; QByteArray SensorBoardName; GroupDateSoftware gds; QDate SensorSoftDate; GroupSensorCommParametters gscp; GroupSensorValues gsv; // QModbusClient* m_master; }; #endif // MICROANALYZER_H
[ "juan.raul.carrasco@cefem-group.com" ]
juan.raul.carrasco@cefem-group.com
7d66d6da26791b733b339c1fcae63458601c264d
350366e4bf035dc718e7a3d2ec990ebfb81142b1
/homework_week2_3-3.cpp
e2d0cf73a46fc75b858aab64a98815c1a89e8051
[]
no_license
jsjs4013/Algorithm_class
c44913a44742032d960ebb038b448bb8507b0f97
c3369073dac2ff9a239e7c7b76754b96912850e5
refs/heads/master
2022-11-25T02:42:33.999657
2020-07-18T05:35:24
2020-07-18T05:35:24
271,691,609
1
0
null
null
null
null
UHC
C++
false
false
3,581
cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; void swap(int*, int*); void bubble(int[], int); void quick(int[], int); int main(void) { int N[10]; // 랜덤한 값 10개를 받는 배열 int K[1000]; // 랜덤한 값 1000개를 받는 배열 clock_t start, end; double result_bubble, result_quick; // 매번 rand()의 값을 다르게 하기위해 srand()와 time()을 사용하여 seed를 다르게 해줌 srand((unsigned int)time(NULL)); for (int i = 0; i < 10; i++) { // 랜덤한 1~10000까지의 값 중 10개를 배열 N[]에 저장하는 반복문 int num = rand(); N[i] = (int)num % 10000 + 1; } for (int i = 0; i < 1000; i++) { // 랜덤한 1~10000까지의 값 중 1000개를 배열 K[]에 저장하는 반복문 int num = rand(); K[i] = (int)num % 10000 + 1; } // time함수를 쓰면 함수가 너무빨리끝나 측정을 못하여 clock()함수를 사용 start = clock(); bubble(K, 1000); end = clock(); result_bubble = (double)(end - start); start = clock(); quick(K, 1000); end = clock(); result_quick = (double)(end - start); cout << "버블정렬이 실행되는데 걸린시간 : " << result_bubble / CLOCKS_PER_SEC << endl; cout << "퀵정렬이 실행되는데 걸린시간 : " << result_quick / CLOCKS_PER_SEC << endl; return 0; } void swap(int* a, int* b) { // 들어온 값인 a, b를 변환해주는 함수 int temp = *a; *a = *b; *b = temp; } void bubble(int N[], int size) { if (size == 1) // size의 크기가 1이되면 비교할 것이 없으므로 끝냄 return; for (int i = 0; i < size - 1; i++) { // 버블소트의 한 사이클을 진행하는 반복문 if (N[i] < N[i + 1]) { // 내림차순 정렬이므로 현재와 다음의 값을 비교하여 // 현재 값이 더 작으면 현재 값과 다음 값을 변환하여야 함 swap(&N[i], &N[i + 1]); } } bubble(N, size - 1); // 재귀호출 } void quick(int N[], int size) { int start, end, l, r; int pivot; int* stack = new int[size * 2 + 2]; // stack을 사용하는데 최대 크기가 2n + 2 임 int push = -1; // 배열을 stack의 LIFO처럼 사용하기 위한 변수 // LIFO 구조의 배열을 임의로 만들어줌 stack[++push] = size - 1; stack[++push] = 0; while (push >= 0) { // stack이 -1이 되면 즉 push값이 -1이 되면 빠져나옴 // 그전까지 분할하면서 퀵소트를 수행 start = stack[push--]; end = stack[push--]; if (end - start + 1 > 1) { // 각 분할된 곳의 값이 2이상이면 실행 pivot = N[end]; // pivot을 맨 뒤의 숫자로 만들어줌 l = start; // 비교할 배열의 왼쪽 부분 r = end - 1; // 비교할 배열의 오른쪽 부분 while (1) { // 비교대상이(l과 r) 교차될 때 까지 비교하기위한 반복문 while (N[l] > pivot) // pivot보다 큰 왼쪽 수를 위한 반복문 l++; while (r > start&& N[r] < pivot) // pivot보다 작은 오른쪽 수를 위한 반복문 r--; if (l >= r) // l과 r이 교차되면 반복문을 빠져나감 break; swap(&N[l], &N[r]); // 서로의 값을 바꿔줌 l++; r--; } // pivot의 자리와 l의 자리를 교환 N[end] = N[l]; N[l] = pivot; // 재귀대신 반복문을 사용하면 이렇게 해야함 stack[++push] = end; stack[++push] = l + 1; // 여기까지 나누는 부분의 오른쪽 배열 부분 stack[++push] = l - 1; stack[++push] = start; // 여기까지 나누는 부분의 왼쪽 배열 부분 } } delete[] stack; }
[ "jsjs4013@gmail.com" ]
jsjs4013@gmail.com
2d6ff517bcac512d78e5516829e7a30d43711dc1
50798948b698142f35a7f7db10034a1c7b6d088d
/complex/main.cpp
1f40a791adcac288e8a0fdd34fc4041711cce4fa
[]
no_license
vhmvd/Cpp
8a26442f0c813ba118f9d0f971f3a8d2834140b6
3727c96f7b0b506076bdba67d30fc01f06bdbe34
refs/heads/master
2023-06-09T07:24:26.373123
2021-06-30T12:05:04
2021-06-30T12:05:04
355,919,398
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include "complex.h" #include <iostream> using namespace std; int main() { complex obj1; cin >> obj1; }
[ "ahmn21@hotmail.com" ]
ahmn21@hotmail.com
7fda4769a600de316a98e4f0c1314fd5e38d3ea2
a2e04e4eac1cf93bb4c1d429e266197152536a87
/Cpp/SDK/EmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey_classes.h
82b5ab1d01c5cd6e51d3414f3d0c9e0d76c13010
[]
no_license
zH4x-SDK/zSoT-SDK
83a4b9fcdf628637613197cf644b7f4d101bb0cb
61af221bee23701a5df5f60091f96f2cf929846e
refs/heads/main
2023-07-16T18:23:41.914014
2021-08-27T15:44:23
2021-08-27T15:44:23
400,555,804
1
0
null
null
null
null
UTF-8
C++
false
false
904
h
#pragma once // Name: SoT, Version: 2.2.1.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass EmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey.EmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey_C // 0x0000 (FullSize[0x0038] - InheritedSize[0x0038]) class UEmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey_C : public UPromptCounterAccessKey { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass EmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey.EmissaryDiscoveredCargoRunCrate_RB_PromptAccessKey_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
7f9cb5577dcc8bfb4da57bdf9743babfec33a294
c7fb3080028a93c7d121ce2473dc919c983775e9
/RStation/GameLoop.cpp
f2cfd898355aee791c5b0c3ceab9500c25bc4b1e
[]
no_license
taiyal/Rhythm-Station
a52f33cb72574c1cae1afe5d1504f265ceda4109
b66111048fff4c6eef978b706307843871d01329
refs/heads/master
2020-06-26T07:23:39.893040
2010-09-14T17:49:28
2010-09-14T17:49:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,703
cpp
#include "RStation.h" #include <GL/glfw.h> #include "GameLoop.h" #include "AudioManager.h" #include "InputManager.h" #include "SceneManager.h" #include "RSUtil.h" #include "Screen.h" #include "Sprite.h" #include "Sound.h" bool bRunning = true; const int freq = 2; // update x times per second namespace Game { void Terminate() { bRunning = false; } void Run() { Timer timer; Scene::PushScreen(); // push overlay { Sprite *spr = new Sprite(); spr->Load("Themes/rstation-logo.png"); spr->Glow(rgba(0.25f, 0.25f, 0.25f, 0.0f)); spr->Register(); Sprite *spr_mouse = new Sprite(); spr_mouse->Load("Themes/_arrow.png"); spr_mouse->Hook(RS_ATTACH_CURSOR); int w = spr_mouse->getWidth(); int h = spr_mouse->getHeight(); spr_mouse->Offset(vec3(w/13.f,h/7.f,0)); // not perfect. spr_mouse->Rotate(vec3(0.f,0.f,-27.f)); spr_mouse->Scale(vec3(0.35f,0.5f,1.f)); spr_mouse->Register(); Sound *sound = new Sound(); sound->Load("Themes/shield-9.ogg"); sound->Loop(true); sound->Register(); } Log::Print("Loading took: " + timer.strAgo() + " seconds."); // Init is done, flush the log. Log::Write(); double then = glfwGetTime(); while(bRunning && glfwGetWindowParam(GLFW_OPENED)) { // calculate delta time double now = glfwGetTime(); float delta = float(now - then); // calculate FPS and set window title. if( int(then * freq) != int(now * freq) ) Util::UpdateWindowTitle(delta); then = now; // update this first so we're on the right frame Input::Update(); Scene::Update(delta); Scene::Draw(); } Scene::Clear(); } }
[ "shakesoda@gmail.com" ]
shakesoda@gmail.com
231e3312b471f601ee5b0644e8f047984acffeac
70c32209f201df97b5fac7d1c0736e98db6409bd
/paddle/fluid/inference/anakin/convert/op_converter.h
b9a221079dcec78fc86ebed7dfac0c59ec0f8540
[ "Apache-2.0" ]
permissive
shippingwang/Paddle
a4c6eb2346025206e7886bf146d88f708d9c3e0a
55a785bb10c9b494e6256855cbb1f73a63bb36e7
refs/heads/develop
2021-06-20T06:47:21.071760
2019-03-10T15:12:35
2019-03-10T15:12:35
150,683,895
0
1
Apache-2.0
2019-04-02T09:46:02
2018-09-28T04:02:10
C++
UTF-8
C++
false
false
4,394
h
// Copyright (c) 2018 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. #pragma once #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include "framework/core/types.h" #include "paddle/fluid/framework/block_desc.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/scope.h" #include "paddle/fluid/inference/anakin/convert/registrar.h" #include "paddle/fluid/inference/anakin/engine.h" #include "paddle/fluid/inference/utils/singleton.h" #include "saber/saber_types.h" namespace paddle { namespace inference { namespace anakin { using AnakinNvEngine = AnakinEngine<::anakin::saber::NV, ::anakin::Precision::FP32>; class AnakinOpConverter { public: AnakinOpConverter() = default; virtual void operator()(const framework::proto::OpDesc &op, const framework::Scope &scope, bool test_mode) {} void ConvertOp(const framework::proto::OpDesc &op, const std::unordered_set<std::string> &parameters, const framework::Scope &scope, AnakinNvEngine *engine, bool test_mode = false) { framework::OpDesc op_desc(op, nullptr); std::string op_type = op_desc.Type(); std::shared_ptr<AnakinOpConverter> it{nullptr}; if (op_type == "mul") { PADDLE_ENFORCE_EQ(op_desc.Input("Y").size(), 1UL); std::string Y = op_desc.Input("Y")[0]; std::cout << Y << parameters.count(Y) << std::endl; if (parameters.count(Y)) { it = OpRegister::instance()->Get("fc"); } } if (!it) { it = OpRegister::instance()->Get(op_type); } PADDLE_ENFORCE_NOT_NULL(it, "no OpConverter for optype [%s]", op_type); it->SetEngine(engine); (*it)(op, scope, test_mode); } void ConvertBlock(const framework::proto::BlockDesc &block, const std::unordered_set<std::string> &parameters, const framework::Scope &scope, AnakinNvEngine *engine) { std::unique_lock<std::mutex> lock(mutex_); for (auto i = 0; i < block.ops_size(); i++) { auto &op = block.ops(i); ConvertOp(op, parameters, scope, engine); } } void SetEngine(AnakinNvEngine *engine) { engine_ = engine; } virtual ~AnakinOpConverter() {} protected: bool test_mode_; AnakinNvEngine *engine_{nullptr}; private: std::unordered_map<std::string, AnakinOpConverter *> converters_; framework::Scope *scope_{nullptr}; std::mutex mutex_; }; } // namespace anakin } // namespace inference } // namespace paddle #define REGISTER_ANAKIN_OP_CONVERTER(op_type__, Converter__) \ struct anakin_##op_type__##_converter \ : public ::paddle::framework::Registrar { \ anakin_##op_type__##_converter() { \ ::paddle::inference:: \ Registry<paddle::inference::anakin::AnakinOpConverter>::Register< \ ::paddle::inference::anakin::Converter__>(#op_type__); \ } \ }; \ anakin_##op_type__##_converter anakin_##op_type__##_converter__; \ int TouchConverterRegister_anakin_##op_type__() { \ anakin_##op_type__##_converter__.Touch(); \ return 0; \ } #define USE_ANAKIN_CONVERTER(op_type__) \ extern int TouchConverterRegister_anakin_##op_type__(); \ static int use_op_converter_anakin_##op_type__ __attribute__((unused)) = \ TouchConverterRegister_anakin_##op_type__();
[ "noreply@github.com" ]
noreply@github.com
ed347499f47a6dd549972a46bc62e3b8caa9cf24
c42c15610f6db6998a285638ae5758b1777c3beb
/AI/ElementaryUnitAI.cpp
27f5a4175b3b9466fd920d4cb850632ab8ef79b3
[]
no_license
KorenevichAnton/IceAndFire
4715bf53b5a8cec4cab8eb68b6934327d3f6ab81
4594a4a3dedee732c6055a9c5da85a4f0ddb11df
refs/heads/master
2020-06-04T06:45:58.216502
2015-06-20T18:43:50
2015-06-20T18:43:50
37,781,336
0
0
null
null
null
null
UTF-8
C++
false
false
33,154
cpp
#include "ElementaryUnitAI.h" #include "Settings.h" #include "BattleModel.h" #include "cmdSetState.h" #include "cmdAttack.h" #include "cmdRemoveUnit.h" #include "BulletUnitAI.h" #include "HUDScreen.h" #include "Buf.h" #include "Card.h" #include "HeroAI.h" #include "MobFactory.h" #include "Utils.h" #include "Buf.h" using namespace cocos2d; //--------------------------------------------------------------------------------------------------------------------------------- ElementaryUnitAI::ElementaryUnitAI():UnitAI(), countPush(0), remainingCountPush(0) { //get settings _settings = Settings::sharedInstance(); CC_ASSERT(_settings); } //--------------------------------------------------------------------------------------------------------------------------------- ElementaryUnitAI::~ElementaryUnitAI() { } //--------------------------------------------------------------------------------------------------------------------------------- ElementaryUnitAI* ElementaryUnitAI::createTS(BattleModel *commandsQueue) { ElementaryUnitAI* pRet = new ElementaryUnitAI(); if (pRet) { pRet->_commands = commandsQueue; CC_SAFE_RETAIN(commandsQueue); } return pRet; } //--------------------------------------------------------------------------------------------------------------------------------- void ElementaryUnitAI::update(AnimatedUnitModel* unitAI, const cocos2d::CCArray *allUnits, float dt) { //update unit AI actions for(int i = 0; i < unitAI->_attacks->count(); i++) { UnitAttack* attModel = (UnitAttack*)unitAI->_attacks->objectAtIndex(i); if(attModel->remainedColdDown > 0) { attModel->remainedColdDown -= dt; if(attModel->remainedColdDown < dt) attModel->remainedColdDown = 0; } if(attModel->remainedActionColdDown > 0) { attModel->remainedActionColdDown -= dt; if(attModel->remainedActionColdDown < dt) attModel->remainedActionColdDown = 0; } } //mob's behavior if(unitAI->isAlive()) { if(unitAI->getState() != "deafened") { int priority = 0; //priority of possible action float useful = canAction(unitAI, allUnits, priority); //check the possibility of the action if (unitAI->getActionWaitTime() > 0 && unitAI->getAttack(priority) && unitAI->getAttack(priority)->type != AT_CALL) { unitAI->setState("wait1"); unitAI->setActionWaitTime(unitAI->getActionWaitTime() - dt); } else { UnitAttack* attM = unitAI->getAttack(priority); //for escape from its landing zone (for team 1) if(unitAI->getTeam() == 1 && unitAI->getPosition().x < (_settings->getBattleFieldRect().size.width - BATTLE_ZONE_WIDTH) / 2 && canMove(unitAI, allUnits)) { useful = -1; } // //for escape from its landing zone (for team 2) if(unitAI->getTeam() == 2 && unitAI->getPosition().x > _settings->getBattleFieldRect().size.width - (_settings->getBattleFieldRect().size.width - BATTLE_ZONE_WIDTH) / 2 && canMove(unitAI, allUnits)) { useful = -1; } if(useful >= 0) { if(useful == 0) { unitAI->setState(attM->animName); // if(attM->type == AT_CALL && attM->remainedActionColdDown == 0 && attM->remainedColdDown == 0) { for (std::vector<CSummoned>::iterator iter = attM->vSummoned.begin(); iter < attM->vSummoned.end(); iter++) { int randomSumm = rand()%((*iter).type.size()); if ((*iter).type[randomSumm] == "mob") { unitAI->setState(attM->animName); cmdSetState* setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); AnimatedUnitModel* pUnit = MobFactory::createTS(atoi((*iter).value[randomSumm].c_str()), unitAI->pBattleModel); pUnit->setInvoker(unitAI); pUnit->setSpecialID(atoi((*iter).value[randomSumm].c_str())); pUnit->setTeam(unitAI->getTeam()); pUnit->setLookMode(unitAI->getLookMode()); pUnit->setLine(unitAI->getLine()); //set position on line pUnit->setPosition(unitAI->getPosition()); //set move direction pUnit->setMoveTarget(unitAI->getMoveTarget()); //move to user landing zone //add unit AI pUnit->addBehavior(ElementaryUnitAI::createTS(pUnit->pBattleModel)); //add to battle model cmdAddUnit* add = cmdAddUnit::createTS(pUnit->pBattleModel, pUnit, 0); pUnit->pBattleModel->addCommand(add); attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; add->release(); pUnit->release(); } if ((*iter).type[randomSumm] == "spell") { unitAI->setState(attM->animName); cmdSetState* setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); Character* hero = unitAI->getTeam() == 1 ? unitAI->pBattleModel->getUserHero() : unitAI->pBattleModel->getOpponentHero(); int ads = atoi((*iter).value[randomSumm].c_str()); spellAttack* sa = unitAI->getSpellAttack(ads); AnimatedUnitModel* _spellModel = new AnimatedUnitModel(); BulletUnitAI* bAI = BulletUnitAI::createTS(unitAI->pBattleModel); bAI->addUntouchableUnit(3); _spellModel->addBehavior(bAI); bAI->release(); _spellModel->setMaxHp(100); _spellModel->setPosition(unitAI->getPosition()); _spellModel->setType(AUM_TYPE_SPELL); _spellModel->pBattleModel = unitAI->pBattleModel; _spellModel->setMoveDirection(unitAI->getMoveDirection()); _spellModel->setSkin(sa->skin); _spellModel->setOriginSkinPoint(CCPointZero); CC_ASSERT(sa); UnitAttack* att = new UnitAttack(); att->damage = sa->damage; att->damageDelta = sa->damageDelta; att->manaCost = sa->manaCost; att->range = sa->range; att->animName = sa->animName; att->damageTime = sa->damageTime; att->_bufs = sa->_bufs; att->animName = sa->animName; att->schoolName = sa->schoolName; _spellModel->addAttack(att); _spellModel->setSpecialID(atoi((*iter).value[randomSumm].c_str())); _spellModel->lifeTimeStarted = time(NULL) + 8; //Fire wall duration _spellModel->setMovingSpeed(0); _spellModel->setTeam(unitAI->getTeam()); cmdAddUnit* add = cmdAddUnit::createTS(unitAI->pBattleModel, _spellModel, 0); unitAI->pBattleModel->addCommand(add); hero->setCastCmdID(add->getID()); attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; add->release(); } } } cmdSetState* setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); if(unitAI->getSkin() == "Orc_Dubolom" && unitAI->getCurAttackTarget()->getSkin() != "Orc_Dubolom" && unitAI->getCurAttackTarget()->getSkin() != "Frostling_Warrior" && unitAI->getCurAttackTarget()->getSpecialID() == 45 && unitAI->getType() == AUM_TYPE_MOB) { unitAI->getCurAttackTarget()->remainingCountPush = 30; } //if action is that attack if(unitAI->getAttack(priority)->type == AT_ENEMY) { //init cooldown decrements attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; //calculate critical attack if(attM->criticalChance && attM->criticalChance > 0) { if(attM->critical) { attM->critical = false; attM->damage /= attM->criticalPower; } if((rand()%100 + 1) <= attM->criticalChance) { attM->damage *= attM->criticalPower; attM->critical = true; } } if(attM->generatedUnit.length() == 0) //melee unit action { if(unitAI->getSkin() == "Mehanic_Guard" || unitAI->getSkin() == "Demon_Rig") { attM->remainingCountPush = unitAI->getAttack(priority)->countPush; } cmdAttack* cmdatt = cmdAttack::createTS(unitAI, unitAI->getCurAttackTarget(), attM); _commands->addCommand(cmdatt); } else //range unit action { BulletUnitAI* bAI = BulletUnitAI::createTS(_commands); //create BULLET unit AnimatedUnitModel* unit = AnimatedUnitModel::createTSWithXML(attM->generatedUnit.c_str(), this->_commands); unit->setInvoker(unitAI); unit->setSpecialID(priority); /*CCArray *arr = unitAI->getAttack(priority)->_bufs; CCObject* obj; CCARRAY_FOREACH(arr, obj) { Buf *buf = Buf(obj); if(buf) { unit->getAttack()->_bufs->addObject(buf); } }*/ unit->getAttack()->_bufs = unitAI->getAttack(priority)->_bufs; unit->setTeam(unitAI->getTeam()); unit->setLine(unitAI->getLine()); unit->setPosition(unitAI->getPosition()); CCPoint dir = ccpNormalize(ccpSub(unitAI->getCurAttackTarget()->getPosition(), unitAI->getPosition())); unit->setMoveDirection(dir); if(unitAI->getTeam() == 1) unit->setLookMode(AUM_LOOK_LEFT_MODE); else unit->setLookMode(AUM_LOOK_RIGHT_MODE); //set config from MOB unit unit->getAttack()->critical = unitAI->getAttack(priority)->critical; unit->getAttack()->criticalChance = unitAI->getAttack(priority)->criticalChance; unit->getAttack()->criticalPower = unitAI->getAttack(priority)->criticalPower; unit->getAttack()->damage = unitAI->getAttack(priority)->damage; unit->getAttack()->damageDelta = unitAI->getAttack(priority)->damageDelta; unit->getAttack()->damageTime = unitAI->getAttack(priority)->damageTime; unit->getAttack()->coldDown = unitAI->getAttack(priority)->coldDown; unit->getAttack()->actionColdDown = unitAI->getAttack(priority)->actionColdDown; unit->getAttack()->schoolName = unitAI->getAttack(priority)->schoolName; if(unitAI->getSkin() == "Troll_Hunter" && rand()%100 + 1 > 50) { unit->getAttack()->timeStun = unitAI->getAttack(priority)->timeStun; } if(unitAI->getSkin() == "Frostling_Hunter" && rand()%100 + 1 > 50) { unit->getAttack()->remainingCountPush = unitAI->getAttack(priority)->countPush; } unit->addBehavior(bAI); bAI->release(); cmdAddUnit* add = cmdAddUnit::createTS((BattleModel*)_commands, unit, attM->damageTime); _commands->addCommand(add); add->release(); unit->release(); } } //if action is that friendly skill if(unitAI->getAttack(priority)->type == AT_FRIENDLY) { //for healer assert(unitAI->getAttack(priority)->subtype == "heal" || unitAI->getAttack(priority)->subtype == "regeneration" || unitAI->getAttack(priority)->subtype == "raiseSkeletons"|| unitAI->getAttack(priority)->subtype == "resurrection"); if(unitAI->getAttack(priority)->subtype == "heal" || unitAI->getAttack(priority)->subtype == "regeneration") { //init cooldown decrements attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; cmdAttack* cmdatt = cmdAttack::createTS(unitAI, unitAI->getCurAttackTarget(), attM); _commands->addCommand(cmdatt); }else if(unitAI->getAttack(priority)->subtype == "resurrection") { attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; unitAI->setActionWaitTime(attM->actionColdDown); unitAI->getCurAttackTarget()->setHp(unitAI->getMaxHp()); unitAI->getCurAttackTarget()->setState("move1"); setsta = cmdSetState::createTS(unitAI->getCurAttackTarget(), "move1"); unitAI->pBattleModel->addCommand(setsta); setsta->release(); unitAI->setState(attM->animName); setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); /* unitAI->setState(attM->animName); cmdSetState* setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); AnimatedUnitModel* pUnit = MobFactory::createTS(unitAI->getCurAttackTarget()->getSpecialID(), unitAI->pBattleModel); pUnit->setInvoker(unitAI); pUnit->setSpecialID(unitAI->getCurAttackTarget()->getSpecialID()); pUnit->setType(AUM_TYPE_MOB); pUnit->setTeam(unitAI->getTeam()); pUnit->setLookMode(unitAI->getLookMode()); pUnit->setLine(unitAI->getLine()); //set position on line pUnit->setPosition(unitAI->getCurAttackTarget()->getPosition()); //set move direction pUnit->setMoveTarget(unitAI->getMoveTarget()); //move to user landing zone //add unit AI pUnit->addBehavior(ElementaryUnitAI::createTS(pUnit->pBattleModel)); //add to battle model cmdAddUnit* add = cmdAddUnit::createTS(pUnit->pBattleModel, pUnit, 0); pUnit->pBattleModel->addCommand(add); attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; add->release(); pUnit->release(); unitAI->pBattleModel->removeUnit(unitAI->getCurAttackTarget(), true);*/ } else if(unitAI->getAttack(priority)->subtype == "raiseSkeletons") { unitAI->setState(attM->animName); cmdSetState* setsta = cmdSetState::createTS(unitAI, attM->animName); _commands->addCommand(setsta); setsta->release(); int idNewMob = 1; switch (unitAI->getCurAttackTarget()->getTypeMob()) { case 1: idNewMob = 11; break; case 2: idNewMob = 10; break; case 3: idNewMob = 12; break; case 4: idNewMob = 9; break; default: break; } AnimatedUnitModel* pUnit = MobFactory::createTS(idNewMob, unitAI->pBattleModel); pUnit->setInvoker(unitAI); pUnit->setSpecialID(idNewMob); pUnit->setType(AUM_TYPE_MOB); pUnit->setTeam(unitAI->getTeam()); pUnit->setLookMode(unitAI->getLookMode()); pUnit->setLine(unitAI->getLine()); //set position on line pUnit->setPosition(unitAI->getCurAttackTarget()->getPosition()); //set move direction pUnit->setMoveTarget(unitAI->getMoveTarget()); //move to user landing zone //add unit AI pUnit->addBehavior(ElementaryUnitAI::createTS(pUnit->pBattleModel)); //add to battle model cmdAddUnit* add = cmdAddUnit::createTS(pUnit->pBattleModel, pUnit, 0); pUnit->pBattleModel->addCommand(add); attM->remainedColdDown = attM->coldDown; attM->remainedActionColdDown = attM->actionColdDown; add->release(); pUnit->release(); unitAI->pBattleModel->removeUnit(unitAI->getCurAttackTarget(), true); } } } else { if(attM->type == AT_CALL && attM->remainedActionColdDown == 0) { if(canMove(unitAI, allUnits) && unitAI->getMovingSpeed() != 0) { unitAI->setState("move1"); float part = unitAI->getMovingSpeed() * dt / ccpDistance(unitAI->getMoveTarget(), unitAI->getPosition()); CCPoint resV = ccpMult(ccpSub(unitAI->getMoveTarget(), unitAI->getPosition()), part); unitAI->setPosition(ccpAdd(unitAI->getPosition(), resV)); //set access to landing zone landingZoneAccess(unitAI, allUnits); // wait on center battle zone for singleplayer if(_settings->getGameMode() == GM_SINGLEPLAYER && unitAI->getTeam() == 1 && unitAI->getPosition().x > _settings->getBattleFieldRect().size.width / 2) { unitAI->setMovingSpeed(0); unitAI->setState("wait1"); } } else unitAI->setState("wait1"); }else unitAI->setActionWaitTime(useful); } } else { int* nAttack = new int(); sscanf(unitAI->getState().c_str(), "damage%d", nAttack); if(*nAttack == 0) { if(canMove(unitAI, allUnits) && unitAI->getMovingSpeed() != 0) { unitAI->setState("move1"); float part = unitAI->getMovingSpeed() * dt / ccpDistance(unitAI->getMoveTarget(), unitAI->getPosition()); CCPoint resV = ccpMult(ccpSub(unitAI->getMoveTarget(), unitAI->getPosition()), part); unitAI->setPosition(ccpAdd(unitAI->getPosition(), resV)); //set access to landing zone landingZoneAccess(unitAI, allUnits); // wait on center battle zone for singleplayer if(_settings->getGameMode() == GM_SINGLEPLAYER && unitAI->getTeam() == 1 && unitAI->getPosition().x > _settings->getBattleFieldRect().size.width / 2) { unitAI->setMovingSpeed(0); unitAI->setState("wait1"); } } else { unitAI->setState("wait1"); } } else { unitAI->setActionWaitTime(1); } } } } } else { countPush = 0; unitAI->setState("death1"); } } //--------------------------------------------------------------------------------------------------------------------------------- void ElementaryUnitAI::landingZoneAccess(AnimatedUnitModel* unitAI, const cocos2d::CCArray *allUnits) { float landingColsWidth = (_settings->getBattleFieldRect().size.width - BATTLE_ZONE_WIDTH) / 2; //allow access for every line for(int i = 0; i < 3; i++) HUDScreen::getInstance()->landingZoneAccess[i] = true; //deny access for appointed line CCObject* obj; CCARRAY_FOREACH(allUnits, obj) { AnimatedUnitModel* unit = (AnimatedUnitModel*) obj; //deny access to user landing zone if (unit->isAlive() && unit->getType() == AUM_TYPE_MOB && unit->getTeam() == 2 && unit->getPosition().x < landingColsWidth + 20) { HUDScreen::getInstance()->landingZoneAccess[unit->getLine() - 1] = false; } //deny access to opponent hero AI landing zone if(_settings->getGameMode() == GM_SINGLE_AI) { if (unit->isAlive() && unit->getType() == AUM_TYPE_MOB && unit->getTeam() == 1 && unit->getPosition().x > _settings->getBattleFieldRect().size.width - landingColsWidth - 20) { _commands->getOpponentHero()->pAI->landingZoneAccess[unit->getLine() - 1] = false; } } } if(unitAI->getTeam() == 2) { if(unitAI->getPosition().x < landingColsWidth / 2) { //cause damage to the user hero _commands->getUserHero()->causeDamage(unitAI->getAttack(), unitAI->getAttack()->damage); //hide and remove unit unitAI->setPosition(ccp(512, -1000)); cmdRemoveUnit* cmdrm = cmdRemoveUnit::createTS(_commands, unitAI, 0); _commands->addCommand(cmdrm); //allow access for this unit line HUDScreen::getInstance()->landingZoneAccess[unitAI->getLine() - 1] = true; } } if(_commands->getOpponentHero() && unitAI->getTeam() == 1) { if(unitAI->getPosition().x > _settings->getBattleFieldRect().size.width - landingColsWidth / 2) { //cause damage to the opponent hero _commands->getOpponentHero()->causeDamage(unitAI->getAttack(), unitAI->getAttack()->damage); //hide and remove unit unitAI->setPosition(ccp(512, -1000)); cmdRemoveUnit* cmdrm = cmdRemoveUnit::createTS(_commands, unitAI, 0); _commands->addCommand(cmdrm); //allow access for this unit line if(_settings->getGameMode() == GM_SINGLE_AI) _commands->getOpponentHero()->pAI->landingZoneAccess[unitAI->getLine() - 1] = true; } } } //--------------------------------------------------------------------------------------------------------------------------------- CCPoint ElementaryUnitAI::pathFind(const AnimatedUnitModel* unitAI,const AnimatedUnitModel* unit) { CCPoint resV = ccpSub(unit->getPosition(),unitAI->getPosition()); Settings* set = Settings::sharedInstance(); int step = set->getBattleFieldRect().size.width / set->getMobAIMaxDirectDistance(); float delta = set->getBattleFieldRect().size.height / set->getMobAIFakeTargetVariance(); if (ccpLength(resV)<step) return ccpAdd(unitAI->getPosition(), resV); else { float k = (float) step / ccpLength(resV); CCPoint fakevector = ccpAdd(ccpMult(resV, k),ccp(0,CCRANDOM_MINUS1_1()*delta)); CCPoint faketarget = ccpAdd(unitAI->getPosition(), fakevector); // fake target could be out of the BattleField faketarget.y = MAX(faketarget.y,0); faketarget.y = MIN(faketarget.y,set->getBattleFieldRect().size.height); return faketarget; } }
[ "korenevichanton@gmail.com" ]
korenevichanton@gmail.com
990afb46e48cf88653382a0bb506e18a65e61e4b
e878e09bea2849ba192605a57959a0ac6904a3c6
/2.C++/5.Datos.Estructurados/2.Trabajo Clase Teórica - Vectores.Paralelos(Ordenamiento-Búsqueda)/Problema_1.cpp
19a8011cde64d17454da87f0122f99aa38bbc528
[]
no_license
Lunahri17/1k4-lunahri
f61f829b92d435fb21ab5d33a5451644532dd34f
03f5fd35370d3970d994cc9530a658fc8d4d1f6d
refs/heads/master
2023-03-26T13:58:34.210050
2021-04-04T22:22:25
2021-04-04T22:22:25
271,795,247
3
1
null
2020-07-31T22:08:25
2020-06-12T12:39:46
C++
UTF-8
C++
false
false
2,220
cpp
#include<stdio.h> #include<stdlib.h> #include<math.h> void leer(int n1,float pro1[50],int leg1[50]); void ordenar(int n1,float pro1[50],int leg1[50]); void mostrar(int n1,float pro1[50],int leg1[50]); int buscar(int n1,int leg[50],int lega1); main(void) { int n,i,leg[50],lega,esta; float pro[50]; printf("Ingrese la cantidad de alumnos: "); scanf("%d",&n); leer(n,pro,leg); ordenar(n,pro,leg); printf("\n\tVectores ordenados: \n"); mostrar(n,pro,leg); printf("\n\n\tLos 3 mejores promedios:\n"); printf("\n pro[0]= %.2f - leg[0]= %d",pro[0],leg[0]); printf("\n pro[1]= %.2f - leg[1]= %d",pro[1],leg[1]); printf("\n pro[2]= %.2f - leg[2]= %d",pro[2],leg[2]); printf("\nIngrese legajo a buscar: "); scanf("%d",&lega); esta=buscar(n,leg,lega); //0 si no esta, 1 si esta if(esta==0) { printf("\nEl legajo %d No esta",lega); } else { printf("\nEl legajo %d Si esta",lega); } } void leer(int n1,float pro1[50],int leg1[50]) { int i; for(i=0;i<n1;i++) { printf("\n pro[%d]= ",i); scanf("%f",&pro1[i]); printf("\n leg[%d]= ",i); scanf("%d",&leg1[i]); } } void ordenar(int n1,float pro1[50],int leg1[50]) { int i,aux,aux1,b; do { b=0; //vector ordenado for(i=0;i<n1-1;i++) { if(pro1[i]<pro1[i+1]) { aux=pro1[i]; pro1[i]=pro1[i+1]; pro1[i+1]=aux; aux1=leg1[i]; leg1[i]=leg1[i+1]; leg1[i+1]=aux1; b=1; //Vector ordenado } } } while(b==1); } void mostrar(int n1,float pro1[50],int leg1[50]) { int i; for(i=0;i<n1;i++) { printf("\n pro[%d]= %.2f",i,pro1[i]); printf("\n leg[%d]= %d",i,leg1[i]); } } int buscar(int n1,int leg1[50],int lega1) { //Busqueda secuencial int i,esta1=0; for(i=0;i<n1 and esta1==0;i++) { if(lega1==leg1[i]) { esta1=1; } } return esta1; }
[ "jeremy17games@hotmail.com" ]
jeremy17games@hotmail.com
ea9100b6804138fc77ed7d209be96dd1d578213a
e3b05dbf2fa9499db644378e8de95f2e8395571a
/src/mrb_joystick.cxx
acca43438ddc02eab9b0fa61a540900dc4960e3b
[]
no_license
IceDragon200/mruby-sfml-window
c44bf9d09b792e85b1d672cdb797df074fdc2c39
3285860d9e877da44e1b56d023e3c37ab2d28896
refs/heads/master
2020-12-24T08:22:27.613840
2020-01-14T15:07:54
2020-01-14T15:07:54
34,407,383
0
0
null
null
null
null
UTF-8
C++
false
false
4,328
cxx
#include <mruby.h> #include <mruby/array.h> #include <mruby/class.h> #include <SFML/Window/Joystick.hpp> #include "mrb/cxx/helpers.hxx" #include "mrb_joystick.hxx" static sf::Joystick::Axis joystick_index_to_axis(mrb_state* mrb, mrb_int index) { switch (index) { case 0: return sf::Joystick::X; case 1: return sf::Joystick::Y; case 2: return sf::Joystick::Z; case 3: return sf::Joystick::R; case 4: return sf::Joystick::U; case 5: return sf::Joystick::V; case 6: return sf::Joystick::PovX; case 7: return sf::Joystick::PovY; } mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid axis id!"); return sf::Joystick::Axis::X; } static mrb_value joystick_is_connected(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_get_args(mrb, "i", &index); return mrb_bool_value(sf::Joystick::isConnected(index)); } static mrb_value joystick_get_button_count(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_get_args(mrb, "i", &index); return mrb_fixnum_value(sf::Joystick::getButtonCount(index)); } static mrb_value joystick_has_axis(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_int axis; mrb_get_args(mrb, "ii", &index, &axis); return mrb_bool_value(sf::Joystick::hasAxis(index, joystick_index_to_axis(mrb, axis))); } static mrb_value joystick_is_button_pressed(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_int button; mrb_get_args(mrb, "ii", &index, &button); return mrb_bool_value(sf::Joystick::isButtonPressed(index, button)); } static mrb_value joystick_get_axis_position(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_int axis; mrb_get_args(mrb, "ii", &index, &axis); return mrb_float_value(mrb, sf::Joystick::getAxisPosition(index, joystick_index_to_axis(mrb, axis))); } static mrb_value joystick_identification_data(mrb_state* mrb, mrb_value self) { mrb_int index; mrb_value result; sf::Joystick::Identification ident; mrb_get_args(mrb, "i", &index); result = mrb_ary_new_capa(mrb, 3); ident = sf::Joystick::getIdentification(index); mrb_ary_set(mrb, result, 0, mrb_str_new_cstr(mrb, ident.name.toAnsiString().c_str())); mrb_ary_set(mrb, result, 1, mrb_fixnum_value(ident.vendorId)); mrb_ary_set(mrb, result, 2, mrb_fixnum_value(ident.productId)); return result; } static mrb_value joystick_update(mrb_state* mrb, mrb_value self) { sf::Joystick::update(); return self; } MRB_SFML_EXTERN void mrb_sfml_joystick_init_bind(mrb_state* mrb, struct RClass* mod) { struct RClass* joystick_module = mrb_define_module_under(mrb, mod, "Joystick"); struct RClass* axis_module = mrb_define_module_under(mrb, joystick_module, "Axis"); mrb_define_const(mrb, joystick_module, "Count", mrb_fixnum_value(sf::Joystick::Count)); mrb_define_const(mrb, joystick_module, "ButtonCount", mrb_fixnum_value(sf::Joystick::ButtonCount)); mrb_define_const(mrb, joystick_module, "AxisCount", mrb_fixnum_value(sf::Joystick::AxisCount)); mrb_define_const(mrb, axis_module, "X", mrb_fixnum_value(sf::Joystick::X)); mrb_define_const(mrb, axis_module, "Y", mrb_fixnum_value(sf::Joystick::Y)); mrb_define_const(mrb, axis_module, "Z", mrb_fixnum_value(sf::Joystick::Z)); mrb_define_const(mrb, axis_module, "R", mrb_fixnum_value(sf::Joystick::R)); mrb_define_const(mrb, axis_module, "U", mrb_fixnum_value(sf::Joystick::U)); mrb_define_const(mrb, axis_module, "V", mrb_fixnum_value(sf::Joystick::V)); mrb_define_const(mrb, axis_module, "PovX", mrb_fixnum_value(sf::Joystick::PovX)); mrb_define_const(mrb, axis_module, "PovY", mrb_fixnum_value(sf::Joystick::PovY)); mrb_define_class_method(mrb, joystick_module, "is_connected?", joystick_is_connected, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, joystick_module, "button_count", joystick_get_button_count, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, joystick_module, "has_axis?", joystick_has_axis, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, joystick_module, "is_button_pressed?", joystick_is_button_pressed, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, joystick_module, "axis_position", joystick_get_axis_position, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, joystick_module, "identification_data", joystick_identification_data, MRB_ARGS_REQ(1)); mrb_define_class_method(mrb, joystick_module, "update", joystick_update, MRB_ARGS_NONE()); }
[ "mistdragon100@gmail.com" ]
mistdragon100@gmail.com
b5a2f7ac61053bae4de271c44140c4730dc543e4
30bafee133a8c2b5e4a8f3fc8cef58db57971a19
/17B_Project_1/mainwindow.cpp
f461406367ad21b2e9aa08a19ac1f4df11d94920
[]
no_license
akimzet/2DGameCollision
48ae6e0cd25368e2f4f5cae2495c26ec59655710
3cab9e2fe7e83b4fb84d45717f34c468a8d384b7
refs/heads/master
2020-07-03T09:30:14.363943
2016-11-19T02:25:24
2016-11-19T02:25:24
74,181,791
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //qApp->setStyleSheet("#groupBox { background-color: yellow }"); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_newButton_clicked() { settingMenu *k=new settingMenu; k->show(); this->close(); } void MainWindow::on_highscoreButton_clicked() { highscore *k=new highscore; k->show(); this->close(); }
[ "akim18@horizon.csueastbay.edu" ]
akim18@horizon.csueastbay.edu
6b2532a687e8be746d6ceaf2eed578c18f2dc724
b92ce30fa7ec457db50d1c060a0b5522c72a12ca
/ex2/Project1/ValuesToNames.h
459feb4de5513b497117794c6aaac359c62ee3c0
[]
no_license
batyapollack/CPP-OOP
53d10979584fa02600dab7d2b67659c73c3baccf
af930aaa6460ec7ab3f91b8a7603db9e59c0586f
refs/heads/master
2022-12-22T08:46:03.739154
2020-10-06T12:23:35
2020-10-06T12:23:35
301,716,724
0
0
null
null
null
null
UTF-8
C++
false
false
2,572
h
#pragma once //----------------IncludeSection-------------------------------------------------------- #include <iostream> #include "AbstractName.h" //--------------------------------------------------------------------------------------- //----------------------template class ValuesToNames------------------------------------- template<typename T> class ValuesToNames { public: int getData() const { return m_data; }; //getData void setData(const int & a) { // setData m_data = a; m_type.setName(m_data); }; const std::string& getName() const;//getName operator int() const { return m_data; }; // case operator to int(must work on const object!) private: int m_data; // Data T m_type;//m_type }; //---------------------------------------------------------------------------------------- //-------------template getName----------------------------------------------------------- //get the name from each vector of ClassName , CurrencyName, DestinationName template<typename T> const std::string& ValuesToNames<T>::getName() const { return m_type.getName(); } //---------------------------------------------------------------------------------------- //-----------------template operator<---------------------------------------------------- template<typename T> bool operator<(const ValuesToNames<T> & fv, const int& a) { return int(fv) < a; } //--------------------------------------------------------------------------------------- //----------template operator>----------------------------------------------------------- template<typename T> bool operator>(const ValuesToNames<T> & fv, const int& a) { return int(fv) > a; } //--------------------------------------------------------------------------------------- //------------------template operator<<-------------------------------------------------- // --------------------print the name---------------------------------------------------- template<typename T> inline std::ostream & operator<<(std::ostream & os, const ValuesToNames<T> & fv) { os << fv.getName(); return os; } //--------------------------------------------------------------------------------------- //--------------operator>>--------------------------------------------------------------- //--------cin to setData----------------------------------------------------------------- template<typename T> inline std::istream & operator>>(std::istream & is, ValuesToNames<T> & fv) { int x; is >> x; fv.setData(x); return is; } //----------------------------------------------------------------------------------------
[ "=" ]
=
8a5811e9025d8c6448c7d07e01a2ed2375cbbb56
3fcb238b0dfe3239cce0be12c78b79718ad0f0eb
/Source/Map.h
d35df7e3ff6b3f9eebb903ea696170fb62204256
[]
no_license
craig95/flyingAnt
dbf1977e2f2cfe5b59923913d1c7a88b299bf9d1
408ff42415aa1fd74806fb03dc3b5aa2210e5ff0
refs/heads/master
2016-08-11T15:19:13.671388
2015-11-01T14:33:03
2015-11-01T14:33:03
45,339,830
0
0
null
null
null
null
UTF-8
C++
false
false
3,138
h
/** * @file Map.h * @class Map * @author Craig van Heerden U15029779, Dedre Olwage U15015239 * * @brief This is the map object. It will keep an array of the map and be able to print it out. */ #ifndef MAP_H #define MAP_H #include "subject.h" class Map : public Subject { private: //complete char** MapContents; char* FileLocation; void SetMap(); int mapSizeX; int mapSizeY; //Observer and Mediator /** * @brief The integers holding the x- and y-coordinates of where the trap can be located at. */ int trapX, trapY; public: //complete Map (); ~Map(); /** * This constructor sets the attribute "File Location"'s value. * @param A char which the attribute "File location" should be set to. */ Map(char*); /** * This function prints the contents of the 2D dynamic array onto the screen. * @return Nothing, the function is void. */ void printMap(); /** * This function determines whether a player/mob can move or not. * @param Four integers, initial x- and y-coordinate, and the x- and y-coordinate the player/mob wants to move to. * @return A bool indication whether the player/mob can move or not. */ bool Move(int,int,int,int); /** * This function that sets the contents of given text file into the 2D dynamic array. * @return Nothing, the function is void. */ void setMap(); /** * This function returns the lenght of the map (total rows of the 2D dynamic array). * @return Nothing, the function is void. */ int getXLength(); /** * This function returns the width of the map (total columns of the 2D dynamic array). * @return Nothing, the function is void. */ int getYLength(); /** * This function sets a specific cell in the map * @param Four integers, initial x- and y-coordinate, and the x- and y-coordinate the player/mob wants to move to, and a char to indicate what that cell should be set to. * @return Nothing, the function is void. */ void setCell(int x, int y,int x2, int y2, char c); /** * This function returns a certian cell's contents. * @param Two integers, the x- and y-coordinate of the cell which the contents of has to be returned. * @return A char conteaining the contents of a specific cell. */ char getCell(int,int); /** * This function creates calls another function in it to determine whether if there is a character above,below,left or right from the player/mob. * @param Two integers, initial x- and y-coordinate used to calculate cells around it. * @return A character indicating if there is something 'a'bove, 'b'elow, 'l'eft or 'r'ight from the player/mob. */ char testCell(int,int); /** * This function informs the Subject about a change it underwent, so the Subject can react accordingly. * @return Nothing is returned (function is void). */ void notify(Subject *map);//O /** * This function 'clears' the cell at the coordinates by making it a space. * @param Two integers, the x and y coordinates of the cell to be cleared. * @return Nothing is returned (function is void). */ void clear(int, int);//O }; #endif
[ "u15029779@tuks.co.za" ]
u15029779@tuks.co.za