hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
acaf28fb533f2ed3c43c2fb1af5098f5f85cd0c6
166
cpp
C++
src/Resolution.cpp
chao-mu/vidrevolt
d7be4ed7a30ef9cec794c54ca1a06e4117420604
[ "MIT" ]
null
null
null
src/Resolution.cpp
chao-mu/vidrevolt
d7be4ed7a30ef9cec794c54ca1a06e4117420604
[ "MIT" ]
null
null
null
src/Resolution.cpp
chao-mu/vidrevolt
d7be4ed7a30ef9cec794c54ca1a06e4117420604
[ "MIT" ]
null
null
null
#include "Resolution.h" namespace vidrevolt { std::string Resolution::str() const { return std::to_string(width) + "x" + std::to_string(height); } }
20.75
68
0.63253
chao-mu
acb2d4cb122f8bbecac7a2d5e67676d9ad5f5286
687
cpp
C++
tests/main.cpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
9
2017-04-24T08:55:48.000Z
2021-12-21T13:15:02.000Z
tests/main.cpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
null
null
null
tests/main.cpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
2
2019-02-19T20:16:16.000Z
2019-08-22T08:51:26.000Z
#include <hougeo/json.h> #include <iostream> #include <fstream> // prints the file content of given houdini file void printLog( const std::string &path, std::ostream *out ) { std::ifstream in( path.c_str(), std::ios_base::in | std::ios_base::binary ); hougeo::json::JSONLogger logger(*out); hougeo::json::Parser p; p.parse( &in, &logger ); } int main(void) { printLog( std::string(TESTS_FILE_PATH)+"/test_box.bgeo", &std::cout ); printLog( std::string(TESTS_FILE_PATH)+"/test_volume.bgeo", &std::cout ); printLog( std::string(TESTS_FILE_PATH)+"/test_box.geo", &std::cout ); printLog( std::string(TESTS_FILE_PATH)+"/test_volume.geo", &std::cout ); return 0; }
21.46875
77
0.678311
all-in-one-of
acb3de12b891c8be8153746689eb3fa6c051b985
1,514
hpp
C++
cpp/map_key_iterator.hpp
frobware/cmd-key-happy
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
[ "MIT" ]
35
2015-09-24T23:04:03.000Z
2022-03-09T16:31:16.000Z
cpp/map_key_iterator.hpp
frobware/cmd-key-happy
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
[ "MIT" ]
4
2016-05-17T20:25:14.000Z
2019-06-05T16:14:34.000Z
cpp/map_key_iterator.hpp
frobware/cmd-key-happy
cd64bba07dc729f2701b0fc1e603d04d2dbc64e9
[ "MIT" ]
8
2015-12-08T01:18:58.000Z
2020-07-24T21:53:34.000Z
#pragma once // This class/idea/idiom taken from a reply on stackoverflow (but I // cannot find the original author). XXX Add missing attribution for // this code. #include <map> #include <iterator> namespace frobware { template<typename map_type> class key_iterator : public map_type::iterator { public: typedef typename map_type::iterator map_iterator; typedef typename map_iterator::value_type::first_type key_type; key_iterator(map_iterator& other) :map_type::iterator(other) {}; key_type& operator*() { return map_type::iterator::operator*().first; } }; template<typename map_type> key_iterator<map_type> key_begin(map_type& m) { return key_iterator<map_type>(m.begin()); } template<typename map_type> key_iterator<map_type> key_end(map_type& m) { return key_iterator<map_type>(m.end()); } template<typename map_type> class const_key_iterator : public map_type::const_iterator { public: typedef typename map_type::const_iterator map_iterator; typedef typename map_iterator::value_type::first_type key_type; const_key_iterator(const map_iterator& other) :map_type::const_iterator(other) {}; const key_type& operator*() const { return map_type::const_iterator::operator*().first; } }; template<typename map_type> const_key_iterator<map_type> key_begin(const map_type& m) { return const_key_iterator<map_type>(m.begin()); } template<typename map_type> const_key_iterator<map_type> key_end(const map_type& m) { return const_key_iterator<map_type>(m.end()); } }
23.65625
84
0.76288
frobware
acb4c8db6da1d9f72b7e06ce2b56fffda243b6f0
2,314
cc
C++
caffe2/operators/tensor_protos_db_input.cc
KevinKecc/caffe2
a2b6c6e2f0686358a84277df65e9489fb7d9ddb2
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/operators/tensor_protos_db_input.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
27
2018-04-14T06:44:22.000Z
2018-08-01T18:02:39.000Z
caffe2/operators/tensor_protos_db_input.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "caffe2/operators/tensor_protos_db_input.h" namespace caffe2 { REGISTER_CPU_OPERATOR(TensorProtosDBInput, TensorProtosDBInput<CPUContext>); OPERATOR_SCHEMA(TensorProtosDBInput) .NumInputs(1) .NumOutputs(1, INT_MAX) .SetDoc(R"DOC( TensorProtosDBInput is a simple input operator that basically reads things from a db where each key-value pair stores an index as key, and a TensorProtos object as value. These TensorProtos objects should have the same size, and they will be grouped into batches of the given size. The DB Reader is provided as input to the operator and it returns as many output tensors as the size of the TensorProtos object. Each output will simply be a tensor containing a batch of data with size specified by the 'batch_size' argument containing data from the corresponding index in the TensorProtos objects in the DB. )DOC") .Arg("batch_size", "(int, default 0) the number of samples in a batch. The " "default value of 0 means that the operator will attempt to insert the " "entire data in a single output blob.") .Input(0, "data", "A pre-initialized DB reader. Typically, this is obtained " "by calling CreateDB operator with a db_name and a db_type. The " "resulting output blob is a DB Reader tensor") .Output(0, "output", "The output tensor in which the batches of data are " "returned. The number of output tensors is equal to the size of " "(number of TensorProto's in) the TensorProtos objects stored in the " "DB as values. Each output tensor will be of size specified by the " "'batch_size' argument of the operator"); NO_GRADIENT(TensorProtosDBInput); } // namespace caffe2
47.22449
80
0.741573
KevinKecc
acb4ebe8bad9a08dff2f049b774946e1aef8b3cd
9,960
hpp
C++
libvast/vast/plugin.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/plugin.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/plugin.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include "vast/fwd.hpp" #include "vast/command.hpp" #include "vast/config.hpp" #include "vast/system/actors.hpp" #include <caf/actor_system_config.hpp> #include <caf/error.hpp> #include <caf/stream.hpp> #include <caf/typed_actor.hpp> #include <cstdint> #include <memory> #include <vector> namespace vast { // -- plugin singleton --------------------------------------------------------- namespace plugins { /// Retrieves the system-wide plugin singleton. std::vector<plugin_ptr>& get() noexcept; } // namespace plugins // -- plugin version ----------------------------------------------------------- /// The version of a plugin in format major.minor.patch.tweak. extern "C" struct plugin_version { uint16_t major; uint16_t minor; uint16_t patch; uint16_t tweak; }; /// @relates plugin_version std::string to_string(plugin_version x); /// Checks if a version meets the plugin version requirements. /// @param version The version to compare against the requirements. bool has_required_version(const plugin_version& version) noexcept; /// Support CAF type-inspection. /// @relates plugin_version template <class Inspector> auto inspect(Inspector& f, plugin_version& x) -> typename Inspector::result_type { return f(x.major, x.minor, x.patch, x.tweak); } // -- plugin type ID blocks ---------------------------------------------------- /// The type ID block used by a plugin as [begin, end). extern "C" struct plugin_type_id_block { uint16_t begin; uint16_t end; }; /// Support CAF type-inspection. /// @relates plugin_type_id_block template <class Inspector> auto inspect(Inspector& f, plugin_type_id_block& x) -> typename Inspector::result_type { return f(x.begin, x.end); } // -- plugin ------------------------------------------------------------------- /// The plugin base class. class plugin { public: /// The current version of the plugin API. When registering a plugin, set the /// corresponding plugin version in the `VAST_REGISTER_PLUGIN` macro. constexpr static auto version = plugin_version{0, 1, 0, 0}; /// Destroys any runtime state that the plugin created. For example, /// de-register from existing components, deallocate memory. virtual ~plugin() noexcept = default; /// Initializes a plugin with its respective entries from the YAML config /// file, i.e., `plugin.<NAME>`. /// @param config The relevant subsection of the configuration. virtual caf::error initialize(data config) = 0; /// Returns the unique name of the plugin. virtual const char* name() const = 0; }; // -- analyzer plugin ---------------------------------------------------------- /// A base class for plugins that hook into the input stream. /// @relates plugin class analyzer_plugin : public virtual plugin { public: /// Creates an actor that hooks into the input table slice stream. /// @param node A pointer to the NODE actor handle. /// @returns The actor handle to the analyzer. virtual system::analyzer_plugin_actor make_analyzer(system::node_actor::pointer node) const = 0; }; // -- command plugin ----------------------------------------------------------- /// A base class for plugins that add commands. /// @relates plugin class command_plugin : public virtual plugin { public: /// Creates additional commands. /// @note VAST calls this function before initializing the plugin, which means /// that this function cannot depend on any plugin state. The logger is /// unavailable when this function is called. virtual std::pair<std::unique_ptr<command>, command::factory> make_command() const = 0; }; // -- plugin_ptr --------------------------------------------------------------- /// An owned plugin and dynamically loaded plugin. /// @relates plugin class plugin_ptr final { public: /// Load a plugin from the specified library filename. /// @param filename The filename that's passed to 'dlopen'. /// @param cfg The actor system config to register type IDs with. static caf::expected<plugin_ptr> make(const char* filename, caf::actor_system_config& cfg) noexcept; /// Unload a plugin and its required resources. ~plugin_ptr() noexcept; /// Forbid copying of plugins. plugin_ptr(const plugin_ptr&) = delete; plugin_ptr& operator=(const plugin_ptr&) = delete; /// Move-construction and move-assignment. plugin_ptr(plugin_ptr&& other) noexcept; plugin_ptr& operator=(plugin_ptr&& rhs) noexcept; /// Pointer facade. explicit operator bool() noexcept; const plugin* operator->() const noexcept; plugin* operator->() noexcept; const plugin& operator*() const noexcept; plugin& operator&() noexcept; /// Upcast a plugin to a more specific plugin type. /// @tparam Plugin The specific plugin type to try to upcast to. /// @returns A pointer to the upcasted plugin, or 'nullptr' on failure. template <class Plugin> const Plugin* as() const { static_assert(std::is_base_of_v<plugin, Plugin>, "'Plugin' must be derived " "from 'vast::plugin'"); return dynamic_cast<const Plugin*>(instance_); } /// Upcast a plugin to a more specific plugin type. /// @tparam Plugin The specific plugin type to try to upcast to. /// @returns A pointer to the upcasted plugin, or 'nullptr' on failure. template <class Plugin> Plugin* as() { static_assert(std::is_base_of_v<plugin, Plugin>, "'Plugin' must be derived " "from 'vast::plugin'"); return dynamic_cast<Plugin*>(instance_); } /// Returns the plugin version. plugin_version version() const; private: /// Create a plugin_ptr. plugin_ptr(void* library, plugin* instance, void (*deleter)(plugin*)) noexcept; /// Implementation details. void* library_ = {}; plugin* instance_ = {}; void (*deleter_)(plugin*) = {}; }; } // namespace vast // -- helper macros ------------------------------------------------------------ #define VAST_REGISTER_PLUGIN(name, major, minor, tweak, patch) \ extern "C" ::vast::plugin* vast_plugin_create() { \ return new name; \ } \ extern "C" void vast_plugin_destroy(class ::vast::plugin* plugin) { \ delete plugin; \ } \ extern "C" struct ::vast::plugin_version vast_plugin_version() { \ return {major, minor, tweak, patch}; \ } \ extern "C" const char* vast_libvast_version() { \ return VAST_VERSION; \ } \ extern "C" const char* vast_libvast_build_tree_hash() { \ return VAST_BUILD_TREE_HASH; \ } #define VAST_REGISTER_PLUGIN_TYPE_ID_BLOCK(...) \ VAST_PP_OVERLOAD(VAST_REGISTER_PLUGIN_TYPE_ID_BLOCK_, __VA_ARGS__) \ (__VA_ARGS__) #define VAST_REGISTER_PLUGIN_TYPE_ID_BLOCK_1(name) \ extern "C" void vast_plugin_register_type_id_block( \ ::caf::actor_system_config& cfg) { \ cfg.add_message_types<::caf::id_block::name>(); \ } \ extern "C" ::vast::plugin_type_id_block vast_plugin_type_id_block() { \ return {::caf::id_block::name::begin, ::caf::id_block::name::end}; \ } #define VAST_REGISTER_PLUGIN_TYPE_ID_BLOCK_2(name1, name2) \ extern "C" void vast_plugin_register_type_id_block( \ ::caf::actor_system_config& cfg) { \ cfg.add_message_types<::caf::id_block::name1>(); \ cfg.add_message_types<::caf::id_block::name2>(); \ } \ extern "C" ::vast::plugin_type_id_block vast_plugin_type_id_block() { \ return {::caf::id_block::name1::begin < ::caf::id_block::name2::begin \ ? ::caf::id_block::name1::begin \ : ::caf::id_block::name2::begin, \ ::caf::id_block::name1::end > ::caf::id_block::name2::end \ ? ::caf::id_block::name1::end \ : ::caf::id_block::name2::end}; \ }
40.819672
80
0.531627
ngrodzitski
acb5f05ec38b0370a836cbace0a6fdd707038f11
2,989
cpp
C++
compiler/src/Ast/AstStringLiteral.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
16
2015-03-30T02:46:49.000Z
2020-07-28T13:36:54.000Z
compiler/src/Ast/AstStringLiteral.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
1
2020-09-01T09:38:30.000Z
2020-09-01T09:38:30.000Z
compiler/src/Ast/AstStringLiteral.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
2
2020-02-07T02:09:48.000Z
2020-02-19T13:31:35.000Z
#include "stdafx.h" #include "AstStringLiteral.h" #include "AstModule.h" #include "../CodeGenerate/StringLiteGen.h" AstStringLiteral::AstStringLiteral(const char * v) { if (v[0] == '"') { name.assign(v + 1); // 去除首尾双引号 name.erase(name.end() - 1); } else { name.assign(v); } escape(); } CodeGen * AstStringLiteral::makeGen(AstContext * parent) { return new StringLiteGen(parent, name); } void AstStringLiteral::escape() { size_t pos = 0; while (true) { pos = name.find('\\', pos); if (pos == std::string::npos) break; if (pos == name.size() - 1) throw std::runtime_error("非法字符串"); char c = name[pos + 1]; switch (c) { case 'a': // \a 响铃(BEL) 007 name.replace(pos++, 2, "\a"); break; case 'b': // \b 退格(BS) 008 name.replace(pos++, 2, "\b"); break; case 'f': // \f 换页(FF) 012 name.replace(pos++, 2, "\f"); break; case 'n': // \n 换行(LF) 010 name.replace(pos++, 2, "\n"); break; case 'r': // \r 回车(CR) 013 name.replace(pos++, 2, "\r"); break; case 't': // \t 水平制表(HT) 009 name.replace(pos++, 2, "\t"); break; case 'v': // \v 垂直制表(VT) 011 name.replace(pos++, 2, "\v"); break; case '\\': // \\ 反斜杠 092 name.replace(pos++, 2, "\\"); break; case '\'': // \' 单引号字符 039 name.replace(pos++, 2, "\'"); break; case '\"': // \" 双引号字符 034 name.replace(pos++, 2, "\""); break; case '\0': // \0 空字符(NULL) 000 name.replace(pos++, 2, "\0"); break; case 'x': // \xhh 任意字符 二位十六进制 if (name.size() - 1 < pos + 3) // 如果字符不足 throw std::runtime_error("非法的转义字符"); { unsigned char v = hex(name[pos + 2]); v = v << 4 | hex(name[pos + 3]); name.erase(pos, 3); name[pos++] = (char)v; } default: if (c >= '0' && c <= '7') { // 0 ~ 7 if (name.size() - 1 == pos + 1) { // 如果是最后一个字符 name.erase(pos); name[pos] = 0; return; } unsigned char v = c - '0'; c = name[pos + 2]; if (c >= '0' && c <= '7') { // 下一个字符仍然是 0~7, 那么认为是 3字节8进制 v = v << 3 | (c - '0'); if (name.size() < pos + 4) throw std::runtime_error("非法的转义字符"); c = name[pos + 3]; if (c >= '0' && c <= '7') { v = v << 3 | (c - '0'); name.erase(pos, 3); name[pos] = (char)v; } else { throw std::runtime_error("非法的转义字符"); } } else { name.erase(pos); name[pos++] = 0; } } break; } } } unsigned char AstStringLiteral::hex(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'a' && c <= 'f') { return c - 'a'; } else if (c >= 'A' && c <= 'F') { return c - 'A'; } else { throw std::runtime_error("非法的转义字符"); } } void AstStringLiteral::replaceAll(std::string & orignStr, const std::string & findStr, const std::string & newStr) { size_t pos = 0; auto l = findStr.size(); auto newStrLen = newStr.size(); while (true) { pos = orignStr.find(findStr, pos); if (pos == std::string::npos) break; orignStr.replace(pos, l, newStr); pos += newStrLen; } }
22.473684
116
0.512881
jadedrip
acb5f1640a390b5b862aedd997d7590dc3a5ebe3
502
cpp
C++
src/commands/info.cpp
JorelAli/Metro
61341e5d288aaa13b57de47e1c2ff68465e209da
[ "MIT" ]
null
null
null
src/commands/info.cpp
JorelAli/Metro
61341e5d288aaa13b57de47e1c2ff68465e209da
[ "MIT" ]
null
null
null
src/commands/info.cpp
JorelAli/Metro
61341e5d288aaa13b57de47e1c2ff68465e209da
[ "MIT" ]
null
null
null
#include "pch.h" Command info { "info", "Show the state of the repo", // execute [](const Arguments &args) { Repository repo = git::Repository::open("."); cout << "Current branch: " << metro::current_branch_name(repo) << endl; cout << "Merging: " << (metro::merge_ongoing(repo)? "yes" : "no") << endl; }, // printHelp [](const Arguments &args) { std::cout << "Usage: metro info\n"; } };
26.421053
86
0.484064
JorelAli
acbf5b8b127b28a658a27d069894f4bac517577e
673
cpp
C++
code/main.cpp
stoman/HashCode2018
de3a540d7a8ac07e2bbdbe7422801fefb33a00ec
[ "MIT" ]
1
2018-03-06T13:36:45.000Z
2018-03-06T13:36:45.000Z
code/main.cpp
stoman/HashCode2018
de3a540d7a8ac07e2bbdbe7422801fefb33a00ec
[ "MIT" ]
1
2018-03-05T17:00:46.000Z
2018-03-10T12:28:51.000Z
code/main.cpp
stoman/HashCode2018
de3a540d7a8ac07e2bbdbe7422801fefb33a00ec
[ "MIT" ]
null
null
null
#include "util.cpp" #include "part1.cpp" #include "part2.cpp" //input/output code int main(int argc, char* argv[]) { ios::sync_with_stdio(false); srand(time(NULL)); //read input Input input; readInput(input, cin); //read command line args string algorithm = ""; if(argc > 1) { algorithm = argv[1]; } //solve problem cerr << "using algorithm " << algorithm << endl; if(algorithm == "naive") { assignrides(input); log(); } else { cerr << "unknown algorithm" << endl; return 1; } //print output for(int i = 0; i < input.f; i++) { cout << input.paths[i].size(); for(int j: input.paths[i]) { cout << ' ' << j; } cout << endl; } };
16.825
49
0.591382
stoman
acbfc79e49fbdd1961ba931877c2bee2fe444077
1,333
cpp
C++
aws-cpp-sdk-backup/source/model/ListBackupVaultsResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-backup/source/model/ListBackupVaultsResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-backup/source/model/ListBackupVaultsResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/backup/model/ListBackupVaultsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Backup::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListBackupVaultsResult::ListBackupVaultsResult() { } ListBackupVaultsResult::ListBackupVaultsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListBackupVaultsResult& ListBackupVaultsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("BackupVaultList")) { Array<JsonView> backupVaultListJsonList = jsonValue.GetArray("BackupVaultList"); for(unsigned backupVaultListIndex = 0; backupVaultListIndex < backupVaultListJsonList.GetLength(); ++backupVaultListIndex) { m_backupVaultList.push_back(backupVaultListJsonList[backupVaultListIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
26.66
126
0.763691
lintonv
acbff0d2bc6fd0d2b2a9c66d92ffb8ec3b355c0a
1,226
cpp
C++
OGDF/_examples/layout/orthogonal/main.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
13
2017-12-21T03:35:41.000Z
2022-01-31T13:45:25.000Z
OGDF/_examples/layout/orthogonal/main.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
7
2017-09-13T01:31:24.000Z
2021-12-14T00:31:50.000Z
OGDF/_examples/layout/orthogonal/main.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
15
2017-09-07T18:28:55.000Z
2022-01-18T14:17:43.000Z
#include <ogdf/planarity/PlanarizationLayout.h> #include <ogdf/planarity/SubgraphPlanarizer.h> #include <ogdf/planarity/VariableEmbeddingInserter.h> #include <ogdf/planarity/FastPlanarSubgraph.h> #include <ogdf/orthogonal/OrthoLayout.h> #include <ogdf/planarity/EmbedderMinDepthMaxFaceLayers.h> #include <ogdf/fileformats/GraphIO.h> using namespace ogdf; int main() { Graph G; GraphAttributes GA(G, GraphAttributes::nodeGraphics | GraphAttributes::edgeGraphics | GraphAttributes::nodeLabel | GraphAttributes::edgeStyle | GraphAttributes::nodeStyle | GraphAttributes::nodeTemplate); GraphIO::readGML(GA, G, "ERDiagram.gml"); PlanarizationLayout pl; SubgraphPlanarizer *crossMin = new SubgraphPlanarizer; FastPlanarSubgraph *ps = new FastPlanarSubgraph; ps->runs(100); VariableEmbeddingInserter *ves = new VariableEmbeddingInserter; ves->removeReinsert(rrAll); crossMin->setSubgraph(ps); crossMin->setInserter(ves); EmbedderMinDepthMaxFaceLayers *emb = new EmbedderMinDepthMaxFaceLayers; pl.setEmbedder(emb); OrthoLayout *ol = new OrthoLayout; ol->separation(20.0); ol->cOverhang(0.4); pl.setPlanarLayouter(ol); pl.call(GA); GraphIO::writeGML(GA, "ERDiagram-layout.gml"); return 0; }
24.52
72
0.777325
shahnidhi
acc1aeab0c888abdc127e061373d13a39f347805
10,148
cpp
C++
sdk/chustd/ImageFormat.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
90
2016-08-23T00:13:04.000Z
2022-02-22T09:40:46.000Z
sdk/chustd/ImageFormat.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
25
2016-09-01T07:09:03.000Z
2022-01-31T16:18:57.000Z
sdk/chustd/ImageFormat.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
17
2017-05-03T17:49:25.000Z
2021-12-28T06:47:56.000Z
/////////////////////////////////////////////////////////////////////////////// // This file is part of the chustd library // Copyright (C) ChuTeam // For conditions of distribution and use, see copyright notice in chustd.h /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ImageFormat.h" #include "File.h" ////////////////////////////////////////////////////////////////////// using namespace chustd; ////////////////////////////////////////////////////////////////////// Color Color::Black(0, 0, 0); Color Color::White(255, 255, 255); Color Color::Red(255, 0, 0); Color Color::Green(0, 255, 0); Color Color::Blue(0, 0, 255); Color Color::Yellow(255, 255, 0); Color Color::Cyan(0, 255, 255); Color Color::Magenta(255, 0, 255); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// PixelFormat AnimFrame::GetPixelFormat() const { if( m_pOwner ) { return m_pOwner->GetPixelFormat(); } return PF_Unknown; } bool AnimFrame::HasSimpleTransparency() const { if( m_pOwner ) { return m_pOwner->HasSimpleTransparency(); } return false; } uint16 AnimFrame::GetGreyTransIndex() const { if( m_pOwner ) { return m_pOwner->GetGreyTransIndex(); } return 0; } void AnimFrame::GetTransIndexes(uint16& red, uint16& green, uint16& blue) const { if( m_pOwner ) { return m_pOwner->GetTransIndexes(red, green, blue); } red = green = blue = 0; } const Palette& AnimFrame::GetPalette() const { if( m_pOwner ) { return m_pOwner->GetPalette(); } return Palette::Null; } ////////////////////////////////////////////////////////////////////// const Palette Palette::Null; ////////////////////////////////////////////////////////////////////// // Returns true if one of the color has a alpha not equal to 255 bool Palette::HasNonOpaqueColor() const { for(int i = 0; i < m_count; ++i) { if( m_colors[i].GetAlpha() != 255 ) { return true; } } return false; } bool Palette::AllAlphasAreOpaque() const { for(int i = 0; i < m_count; ++i) { if( m_colors[i].GetAlpha() != 0 ) return false; } return true; } void Palette::SetAlphaFullOpaque() { for(int i = 0; i < m_count; ++i) { m_colors[i].SetAlpha(255); } } // Returns -1 if not found int Palette::FindColor(Color col) const { for(int i = 0; i < m_count; ++i) { if( m_colors[i] == col ) { return i; } } return -1; } // Returns -1 if not found int Palette::GetFirstFullyTransparentColor() const { for(int i = 0; i < m_count; ++i) { if( m_colors[i].a == 0 ) { return i; } } return -1; } ////////////////////////////////////////////////////////////////////// ImageFormat::ImageFormat() { m_width = 0; m_height = 0; m_lastError = 0; } ImageFormat::~ImageFormat() { } //////////////////////////////////////////////////// bool ImageFormat::IsGray(PixelFormat pf) { switch(pf) { case PF_1bppGrayScale: case PF_2bppGrayScale: case PF_4bppGrayScale: case PF_8bppGrayScale: case PF_16bppGrayScale: return true; default: break; } return false; } bool ImageFormat::IsIndexed(PixelFormat pf) { return pf == PF_1bppIndexed || pf == PF_2bppIndexed || pf == PF_4bppIndexed || pf == PF_8bppIndexed; } int32 ImageFormat::SizeofPixelInBits(PixelFormat ePixelFormat) { switch(ePixelFormat) { case PF_Unknown: return 0; case PF_1bppGrayScale: return 1; case PF_2bppGrayScale: return 2; case PF_4bppGrayScale: return 4; case PF_8bppGrayScale: return 8; case PF_16bppGrayScale: return 16; case PF_16bppGrayScaleAlpha: return 16; case PF_32bppGrayScaleAlpha: return 32; case PF_1bppIndexed: return 1; case PF_2bppIndexed: return 2; case PF_4bppIndexed: return 4; case PF_8bppIndexed: return 8; case PF_16bppArgb1555: case PF_16bppArgb4444: case PF_16bppRgb555: case PF_16bppRgb565: return 16; case PF_24bppRgb: case PF_24bppBgr: return 24; case PF_32bppRgba: case PF_32bppBgra: return 32; case PF_48bppRgb: return 48; case PF_64bppRgba: return 64; } ASSERT(0); return 0; } int32 ImageFormat::ComputeByteWidth(PixelFormat epf, int32 width) { const int32 sizeofPixelInBits = ImageFormat::SizeofPixelInBits(epf); // Size of a row in bits const int32 bitWidth = width * sizeofPixelInBits; // Round up for size of a row in bytes const int32 addWidth = ((bitWidth & 7) != 0) ? 1 : 0; const int32 byteWidth = bitWidth / 8 + addWidth; return byteWidth; } ////////////////////////////////////////////////////////////////////////////// String ImageFormat::GetLastErrorString() const { switch(m_lastError) { case ioErr: return "Error accessing to the file"; case badFileFormat: return "Bad File Format"; case notEnoughMemory: return "Not enough memory"; case uncompleteFile: return "Uncomplete file"; } return "Unknown error"; } bool ImageFormat::Load(const String& filePath) { File file; if( !file.Open(filePath) ) { m_lastError = ioErr; return false; } return LoadFromFile(file); } int32 ImageFormat::GetWidth() const { return m_width; } int32 ImageFormat::GetHeight() const { return m_height; } const Buffer& ImageFormat::GetPixels() const { return m_pixels; } void ImageFormat::FreeBuffer() { m_pixels.Clear(); } void ImageFormat::FlipVertical() { PixelFormat epf = GetPixelFormat(); if( epf == PF_Unknown ) { return; } const int32 bytesPerRow = ImageFormat::ComputeByteWidth(epf, m_width); uint8* pComponents = m_pixels.GetWritePtr(); const int32 heightDiv2 = m_height / 2; for(int iY = 0; iY < heightDiv2; ++iY) { uint8* pSrc = pComponents + (iY * bytesPerRow); uint8* pDst = pComponents + ((m_height - 1 - iY) * bytesPerRow); for(int iByte = 0; iByte < bytesPerRow; ++iByte) { uint8 swap = pDst[iByte]; pDst[iByte] = pSrc[iByte]; pSrc[iByte] = swap; } } } void ImageFormat::SetAlphaFullOpaque() { PixelFormat epf = GetPixelFormat(); if( epf == PF_Unknown ) { return; } const int32 pixelCount = m_width * m_height; if( epf == PF_32bppRgba || epf == PF_32bppBgra ) { uint8* pDst = m_pixels.GetWritePtr(); const uint8 alpha = 255; for(int i = 0; i < pixelCount; ++i) { pDst[3] = alpha; pDst += 4; } } } int32 ImageFormat::GetLastError() const { return m_lastError; } bool ImageFormat::IsIndexed() const { return IsIndexed(GetPixelFormat()); } bool ImageFormat::IsAnimated() const { return false; } bool ImageFormat::HasDefaultImage() const { return false; } int32 ImageFormat::GetFrameCount() const { return 0; } const AnimFrame* ImageFormat::GetAnimFrame(int /*index*/) const { return nullptr; } /////////////////////////////////////////////////////////////////////////////////////////////////// // If animated, gets the number of times the animation loops. int32 ImageFormat::GetLoopCount() const { return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Packs single-pixel bytes into multiple-pixels bytes. // // [in,out] pixels Pixels in: one pixel per byte, out: multiple pixels per byte // [in] width Width in pixels // [in] height Height in pixels // [in] pixelFormat Target pixel format // // Returns true upon success /////////////////////////////////////////////////////////////////////////////////////////////////// bool ImageFormat::PackPixels(Buffer& pixels, int width, int height, PixelFormat pixelFormat) { if( width < 0 || height < 0 ) { return false; // Bad arg } int bitsPerPix = ImageFormat::SizeofPixelInBits(pixelFormat); if( bitsPerPix > 8 ) { return false; // Bad arg } if( bitsPerPix == 8 ) { // Nothing to do return true; } if( pixels.GetSize() < (width * height) ) { ASSERT(0); return false; } const int32 bytesPerRow = ImageFormat::ComputeByteWidth(pixelFormat, width); uint8* pIn = pixels.GetWritePtr(); uint8* pOut = pIn; // Note: there is padding at the end of each row uint8 currentByte = 0; // Current byte value int usedBitCount = 0; // Number of bits used inside the byte for(int iRow = 0; iRow < height; iRow++) { currentByte = 0; usedBitCount = 0; for(int iCol = 0; iCol < width; iCol++) { uint8 nVal = pIn[iRow * width + iCol]; usedBitCount += bitsPerPix; currentByte |= (nVal << (8 - usedBitCount)); if( usedBitCount == 8 ) { pOut[0] = currentByte; ++pOut; currentByte = 0; usedBitCount = 0; } } if( usedBitCount != 0 ) { pOut[0] = currentByte; ++pOut; } } int newSize = bytesPerRow * height; pixels.SetSize(newSize); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Unpacks multiple pixels per byte to get one pixel per byte. // // [in,out] pixels Pixels in: one pixel per bytes, out: multiple pixels per byte // [in] width Width in pixels // [in] height Height in pixels // [in] pixelFormat Source pixel format // // Returns true upon success. /////////////////////////////////////////////////////////////////////////////////////////////////// bool ImageFormat::UnpackPixels(Buffer& pixels, int width, int height, PixelFormat pixelFormat) { int bitsPerPix = ImageFormat::SizeofPixelInBits(pixelFormat); if( bitsPerPix >= 8 ) { // Nothing to do return true; } Buffer newBuffer; if( !newBuffer.SetSize(width * height) ) { return false; } const uint8* pSrc = pixels.GetReadPtr(); uint8* pDst = newBuffer.GetWritePtr(); int32 mask = ~((~0UL) << bitsPerPix); int32 shift = 8 - bitsPerPix; int srcIndex = 0; int dstIndex = 0; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { uint8 currentByte = pSrc[srcIndex]; uint8 colorIndex = uint8( (currentByte >> shift) & mask); shift -= bitsPerPix; if( shift < 0 ) { shift = 8 - bitsPerPix; srcIndex++; } pDst[dstIndex] = colorIndex; dstIndex++; } // Some padding bits may remain if( shift != 8 - bitsPerPix ) { shift = 8 - bitsPerPix; srcIndex++; } } pixels = newBuffer; return true; }
20.134921
101
0.582184
hadrien-psydk
acc251772bb370a154ff6840dedcb61bdce121e9
2,801
cpp
C++
tools/light-directions/main.cpp
bradparks/Restore__3d_model_from_pics_2d_multiple_images
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
[ "MIT" ]
21
2018-07-17T02:35:43.000Z
2022-02-25T00:45:09.000Z
tools/light-directions/main.cpp
bradparks/Restore__3d_model_from_pics_2d_multiple_images
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
[ "MIT" ]
null
null
null
tools/light-directions/main.cpp
bradparks/Restore__3d_model_from_pics_2d_multiple_images
58f935130693e6eba2db133ce8dec3fd6a3d3dd0
[ "MIT" ]
11
2018-09-06T17:29:36.000Z
2022-01-29T12:20:59.000Z
// Copyright (c) 2015-2016, Kai Wolf // // 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 <string> #include <memory> #include <opencv2/highgui/highgui.hpp> #include "common/dataset.hpp" #include "common/utils.hpp" #include "io/dataset_reader.hpp" #include "io/assets_path.hpp" #include "filtering/segmentation.hpp" #include "rendering/bounding_box.hpp" #include "rendering/voxel_carving.hpp" #include "rendering/light_dir_estimation.hpp" using namespace ret; using namespace ret::io; using namespace ret::calib; using namespace ret::filtering; using namespace ret::rendering; std::shared_ptr<DataSet> loadDataSet(const std::string &path, const std::size_t num_imgs) { DataSetReader dsr(path); auto ds = dsr.load(num_imgs); for (std::size_t i = 0; i < num_imgs; ++i) { ds->getCamera(i).setMask(Binarize( ds->getCamera(i).getImage(), cv::Scalar(0, 0, 30))); } return ds; } int main() { const std::size_t VOXEL_DIM = 128; const std::size_t NUM_IMGS = 36; auto ds = loadDataSet(std::string(ASSETS_PATH) + "/squirrel", NUM_IMGS); BoundingBox bbox(ds->getCamera(0), ds->getCamera((NUM_IMGS / 4) - 1)); auto bb_bounds = bbox.getBounds(); auto vc = ret::make_unique<VoxelCarving>(bb_bounds, VOXEL_DIM); for (const auto &cam : ds->getCameras()) { vc->carve(cam); } auto mesh = vc->createVisualHull(); LightDirEstimation light; for (auto idx = 0; idx < NUM_IMGS; ++idx) { auto light_dir = light.execute(ds->getCamera(idx), mesh); cv::Mat light_dirs = light.displayLightDirections( ds->getCamera(idx), light_dir); cv::imwrite("light_dir" + std::to_string(idx) + ".png", light_dirs); } return 0; }
36.376623
80
0.697251
bradparks
acc3b189afe63eedffa6fa7e2d92c221cb77349a
48,337
cc
C++
supersonic/cursor/core/aggregate_groups.cc
IssamElbaytam/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
201
2015-03-18T21:55:00.000Z
2022-03-03T01:48:26.000Z
supersonic/cursor/core/aggregate_groups.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
6
2015-03-19T16:47:19.000Z
2020-10-05T09:38:26.000Z
supersonic/cursor/core/aggregate_groups.cc
edisona/supersonic
062a48ddcb501844b25a8ae51bd777fcf7ac1721
[ "Apache-2.0" ]
54
2015-03-19T16:31:57.000Z
2021-12-31T10:14:57.000Z
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <stddef.h> #include <algorithm> #include "supersonic/utils/std_namespace.h" #include <list> #include "supersonic/utils/std_namespace.h" #include <memory> #include <set> #include "supersonic/utils/std_namespace.h" #include <vector> using std::vector; #include <glog/logging.h> #include "supersonic/utils/logging-inl.h" #include "supersonic/utils/macros.h" #include "supersonic/utils/port.h" #include "supersonic/utils/scoped_ptr.h" #include "supersonic/utils/stringprintf.h" #include "supersonic/utils/exception/failureor.h" #include "supersonic/base/exception/exception.h" #include "supersonic/base/exception/exception_macros.h" #include "supersonic/base/exception/result.h" #include "supersonic/base/infrastructure/bit_pointers.h" #include "supersonic/base/infrastructure/block.h" #include "supersonic/base/infrastructure/projector.h" #include "supersonic/base/infrastructure/types.h" #include "supersonic/base/memory/memory.h" #include "supersonic/cursor/base/cursor.h" #include "supersonic/cursor/base/operation.h" #include "supersonic/cursor/proto/cursors.pb.h" #include "supersonic/cursor/core/aggregate.h" #include "supersonic/cursor/core/aggregator.h" #include "supersonic/cursor/core/hybrid_group_utils.h" #include "supersonic/cursor/core/sort.h" #include "supersonic/cursor/infrastructure/basic_cursor.h" #include "supersonic/cursor/infrastructure/basic_operation.h" #include "supersonic/cursor/infrastructure/iterators.h" #include "supersonic/cursor/infrastructure/ordering.h" #include "supersonic/cursor/infrastructure/row_hash_set.h" #include "supersonic/cursor/infrastructure/table.h" #include "supersonic/proto/supersonic.pb.h" #include "supersonic/utils/strings/join.h" #include "supersonic/utils/container_literal.h" #include "supersonic/utils/map_util.h" #include "supersonic/utils/pointer_vector.h" #include "supersonic/utils/stl_util.h" namespace supersonic { class TupleSchema; namespace { // Creates and updates a block of unique keys that are the result of grouping. class GroupKeySet { public: typedef row_hash_set::FindResult FindResult; // Re-exporting. // Creates a GroupKeySet. group_by_columns describes which columns constitute // a key and should be grouped together, it can be empty, in which case all // rows are considered equal and are grouped together. Set is pre-allocated // to store initial_row_capacity unique keys, and it can grow as needed. static FailureOrOwned<GroupKeySet> Create( const BoundSingleSourceProjector* group_by, BufferAllocator* allocator, rowcount_t initial_row_capacity, const int64 max_unique_keys_in_result) { std::unique_ptr<GroupKeySet> group_key_set( new GroupKeySet(group_by, allocator, max_unique_keys_in_result)); PROPAGATE_ON_FAILURE(group_key_set->Init(initial_row_capacity)); return Success(group_key_set.release()); } const TupleSchema& key_schema() const { return key_projector_->result_schema(); } // View on a block that keeps unique keys. Can be called only when key is not // empty. const View& key_view() const { return key_row_set_.indexed_view(); } // How many rows can a view passed in the next call to Insert() have. // TODO(user): Remove this limitation (the row hash set could use a loop // to insert more items that it can process in a single shot). rowcount_t max_view_row_count_to_insert() const { // Does not accept views larger then cursor::kDefaultRowCount because this // is the size of preallocated table that holds result of Insert(). return Cursor::kDefaultRowCount; } // Count of unique keys in the set. rowcount_t size() const { return key_row_set_.size(); } // Inserts all unique keys from the view to the key block. For each row // from input view finds an index of its key in the key block and puts // these indexes in the result table. // Input view can not have more rows then max_view_row_count_to_insert(). const rowid_t Insert(const View& view, FindResult* result) { CHECK_LE(view.row_count(), max_view_row_count_to_insert()); key_projector_->Project(view, &child_key_view_); child_key_view_.set_row_count(view.row_count()); return key_row_set_.Insert(child_key_view_, result); } void Reset() { key_row_set_.Clear(); } void Compact() { key_row_set_.Compact(); } private: GroupKeySet(const BoundSingleSourceProjector* group_by, BufferAllocator* allocator, const int64 max_unique_keys_in_result) : key_projector_(group_by), child_key_view_(key_projector_->result_schema()), key_row_set_(key_projector_->result_schema(), allocator, max_unique_keys_in_result) {} FailureOrVoid Init(rowcount_t reserved_capacity) { if (!key_row_set_.ReserveRowCapacity(reserved_capacity)) { THROW(new Exception( ERROR_MEMORY_EXCEEDED, StrCat("Block allocation failed. Key block with capacity ", reserved_capacity, " not allocated."))); } return Success(); } std::unique_ptr<const BoundSingleSourceProjector> key_projector_; // View over an input view from child but with only key columns. View child_key_view_; row_hash_set::RowHashSet key_row_set_; DISALLOW_COPY_AND_ASSIGN(GroupKeySet); }; // Cursor that is used for handling the standard GroupAggregate mode and // BestEffortGroupAggregate mode. The difference between these two modes is that // GroupAggregate needs to process the whole input during creation (returns out // of memory error if aggregation result is too large) and // BestEffortGroupAggregate does not process anything during creation and // processes as large chunks as possible during iteration phase, but does not // guarantee that the final result will be fully aggregated (i.e. there can be // more than one output for a given key). To make BestEffortGroupAggregate // deterministic (always producing the same output), pass GuaranteeMemory as its // allocator. class GroupAggregateCursor : public BasicCursor { public: // Creates the cursor. Returns immediately (w/o processing any input). static FailureOrOwned<GroupAggregateCursor> Create( const BoundSingleSourceProjector* group_by, Aggregator* aggregator, BufferAllocator* allocator, // Takes ownership BufferAllocator* original_allocator, // Doesn't take ownership. bool best_effort, const int64 max_unique_keys_in_result, Cursor* child) { std::unique_ptr<BufferAllocator> allocator_owned(CHECK_NOTNULL(allocator)); std::unique_ptr<Cursor> child_owner(child); std::unique_ptr<Aggregator> aggregator_owner(aggregator); FailureOrOwned<GroupKeySet> key = GroupKeySet::Create( group_by, allocator_owned.get(), aggregator_owner->capacity(), max_unique_keys_in_result); PROPAGATE_ON_FAILURE(key); vector<const TupleSchema*> input_schemas(2); input_schemas[0] = &key->key_schema(); input_schemas[1] = &aggregator->schema(); std::unique_ptr<MultiSourceProjector> result_projector( (new CompoundMultiSourceProjector()) ->add(0, ProjectAllAttributes()) ->add(1, ProjectAllAttributes())); FailureOrOwned<const BoundMultiSourceProjector> bound_result_projector( result_projector->Bind(input_schemas)); PROPAGATE_ON_FAILURE(bound_result_projector); TupleSchema result_schema = bound_result_projector->result_schema(); return Success( new GroupAggregateCursor(result_schema, allocator_owned.release(), // Takes ownership. original_allocator, key.release(), aggregator_owner.release(), bound_result_projector.release(), best_effort, max_unique_keys_in_result, child_owner.release())); } virtual ResultView Next(rowcount_t max_row_count) { while (true) { if (result_.next(max_row_count)) { return ResultView::Success(&result_.view()); } if (input_exhausted_) return ResultView::EOS(); // No rows from this call, yet input not exhausted. Retry. PROPAGATE_ON_FAILURE(ProcessInput()); if (child_.is_waiting_on_barrier()) return ResultView::WaitingOnBarrier(); } } // If false, the Cursor will not return more data above what was already // returned from Next() calls (unless TruncateResultView is called). This // method can be used to determine if best-effort group managed to do full // grouping: // - Call .Next(numeric_limits<rowcount_t>::max()) // - Now if CanReturnMoreData() == false, we know that all the results of // best-effort group are in a single view, which means that the data was fully // aggregated. // - TruncateResultView can be used to rewind the cursor to the beginning. bool CanReturnMoreData() const { return !input_exhausted_ || (result_.rows_remaining() > result_.row_count()); } // Truncates the current result ViewIterator. If we only called Next() once, // this rewinds the Cursor to the beginning. bool TruncateResultView() { return result_.truncate(0); } virtual bool IsWaitingOnBarrierSupported() const { return child_.is_waiting_on_barrier_supported(); } virtual void Interrupt() { child_.Interrupt(); } virtual void ApplyToChildren(CursorTransformer* transformer) { child_.ApplyToCursor(transformer); } virtual CursorId GetCursorId() const { return best_effort_ ? BEST_EFFORT_GROUP_AGGREGATE : GROUP_AGGREGATE; } private: // Takes ownership of the allocator, key, aggregator, and child. GroupAggregateCursor(const TupleSchema& result_schema, BufferAllocator* allocator, BufferAllocator* original_allocator, GroupKeySet* key, Aggregator* aggregator, const BoundMultiSourceProjector* result_projector, bool best_effort, const int64 max_unique_keys_in_result, Cursor* child) : BasicCursor(result_schema), allocator_(allocator), original_allocator_(CHECK_NOTNULL(original_allocator)), child_(child), key_(key), aggregator_(aggregator), result_(result_schema), result_projector_(result_projector), inserted_keys_(Cursor::kDefaultRowCount), best_effort_(best_effort), input_exhausted_(false), reset_aggregator_in_processinput_(false), max_unique_keys_in_result_(max_unique_keys_in_result) {} // Process as many rows from input as can fit into result block. If after the // first call to ProcessInput() input_exhausted_ is true, the result is fully // aggregated (there are no rows with equal group by columns). // Initializes the result_ to iterate over the aggregation result. FailureOrVoid ProcessInput(); // Owned allocator used to allocate the memory. // NOTE: it is used by other member objects created by GroupAggregateCursor so // it has to be destroyed last. Keep it as the first class member. std::unique_ptr<const BufferAllocator> allocator_; // Non-owned allocator used to check whether we can allocate more memory or // not. const BufferAllocator* original_allocator_; // The input. CursorIterator child_; // Holds key columns of the result. Wrapper around RowHashSet. std::unique_ptr<GroupKeySet> key_; // Holds 'aggregated' columns of the result. std::unique_ptr<Aggregator> aggregator_; // Iterates over a result of last call to ProcessInput. If // cursor_over_result_->Next() returns EOS and input_exhausted() is false, // ProcessInput needs to be called again to prepare next part of a result and // set cursor_over_result_ to iterate over it. ViewIterator result_; // Projector to combine key & aggregated columns into the result. std::unique_ptr<const BoundMultiSourceProjector> result_projector_; GroupKeySet::FindResult inserted_keys_; // If true, OOM is not fatal; the data aggregated up-to OOM are emitted, // and the aggregation starts anew. bool best_effort_; // Set when EOS reached in the input stream. bool input_exhausted_; // To track when ProcessInput() should reset key_ and aggregator_. It // shouldn't be done after exiting with WAITING_ON_BARRIER - some data might // lost. Reset is also not needed in first ProcessInput() call. bool reset_aggregator_in_processinput_; // Maximum number of unique key combination(as per input order) to aggregate // the results upon. If limit is hit, all remaining rows are aggregated // together in the last row at index = max_unique_keys_in_result_ const int64 max_unique_keys_in_result_; DISALLOW_COPY_AND_ASSIGN(GroupAggregateCursor); }; FailureOrVoid GroupAggregateCursor::ProcessInput() { if (reset_aggregator_in_processinput_) { reset_aggregator_in_processinput_ = false; key_->Reset(); // Compacting GroupKeySet to release more memory. This is a workaround for // having (allocator_->Available() == 0) constantly, which would allow to // only process one block of input data per call to ProcessInput(). However, // freeing the underlying datastructures and building them from scratch many // times can be inefficient. // TODO(user): Implement a less aggressive solution to this problem. key_->Compact(); aggregator_->Reset(); } rowcount_t row_count = key_->size(); // Process the input while not exhausted and memory quota not exceeded. // (But, test the condition at the end of the loop, to guarantee that we // process at least one chunk of the input data). do { // Fetch next block from the input. if (!PREDICT_TRUE(child_.Next(Cursor::kDefaultRowCount, false))) { PROPAGATE_ON_FAILURE(child_); if (!child_.has_data()) { if (child_.is_eos()) { input_exhausted_ = true; } else { DCHECK(child_.is_waiting_on_barrier()); DCHECK(!reset_aggregator_in_processinput_); return Success(); } } break; } // Add new rows to the key set. child_.truncate(key_->Insert(child_.view(), &inserted_keys_)); if (child_.view().row_count() == 0) { // Failed to add any new keys. break; } row_count = key_->size(); if (aggregator_->capacity() < row_count) { // Not enough space to hold the aggregate columns; need to reallocate. // But, if already over quota, give up. if (allocator_->Available() == 0) { // Rewind the input and ignore trailing rows. row_count = aggregator_->capacity(); for (rowid_t i = 0; i < child_.view().row_count(); ++i) { if (inserted_keys_.row_ids()[i] >= row_count) { child_.truncate(i); break; } } } else { if (original_allocator_->Available() < allocator_->Available()) { THROW(new Exception(ERROR_MEMORY_EXCEEDED, "Underlying allocator ran out of memory.")); } // Still have spare memory; reallocate. rowcount_t requested_capacity = std::max(2 * aggregator_->capacity(), row_count); if (!aggregator_->Reallocate(requested_capacity)) { // OOM when trying to make more room for aggregate columns. Rewind the // last input block, so that it is re-fetched by the next // ProcessInput, and break out of the loop, returning what we have up // to now. row_count = aggregator_->capacity(); child_.truncate(0); break; } } } // Update the aggregate columns w/ new rows. PROPAGATE_ON_FAILURE( aggregator_->UpdateAggregations(child_.view(), inserted_keys_.row_ids())); } while (allocator_->Available() > 0); if (!input_exhausted_) { if (best_effort_) { if (row_count == 0) { THROW(new Exception( ERROR_MEMORY_EXCEEDED, StringPrintf( "In best-effort mode, failed to process even a single row. " "Memory free: %zd", allocator_->Available()))); } } else { // Non-best-effort. THROW(new Exception( ERROR_MEMORY_EXCEEDED, StringPrintf( "Failed to process the entire input. " "Memory free: %zd", allocator_->Available()))); } } const View* views[] = { &key_->key_view(), &aggregator_->data() }; result_projector_->Project(&views[0], &views[2], my_view()); my_view()->set_row_count(row_count); result_.reset(*my_view()); reset_aggregator_in_processinput_ = true; return Success(); } class GroupAggregateOperation : public BasicOperation { public: // Takes ownership of SingleSourceProjector, AggregationSpecification and // child_operation. GroupAggregateOperation(const SingleSourceProjector* group_by, const AggregationSpecification* aggregation, GroupAggregateOptions* options, bool best_effort, Operation* child) : BasicOperation(child), group_by_(group_by), aggregation_specification_(aggregation), best_effort_(best_effort), options_(options != NULL ? options : new GroupAggregateOptions()) {} virtual ~GroupAggregateOperation() {} virtual FailureOrOwned<Cursor> CreateCursor() const { FailureOrOwned<Cursor> child_cursor = child()->CreateCursor(); PROPAGATE_ON_FAILURE(child_cursor); BufferAllocator* original_allocator = buffer_allocator(); std::unique_ptr<BufferAllocator> allocator; if (options_->enforce_quota()) { allocator.reset(new GuaranteeMemory(options_->memory_quota(), original_allocator)); } else { allocator.reset(new MemoryLimit( options_->memory_quota(), false, original_allocator)); } FailureOrOwned<Aggregator> aggregator = Aggregator::Create( *aggregation_specification_, child_cursor->schema(), allocator.get(), options_->estimated_result_row_count()); PROPAGATE_ON_FAILURE(aggregator); FailureOrOwned<const BoundSingleSourceProjector> bound_group_by = group_by_->Bind(child_cursor->schema()); PROPAGATE_ON_FAILURE(bound_group_by); return BoundGroupAggregateWithLimit( bound_group_by.release(), aggregator.release(), allocator.release(), original_allocator, best_effort_, options_->max_unique_keys_in_result(), child_cursor.release()); } private: std::unique_ptr<const SingleSourceProjector> group_by_; std::unique_ptr<const AggregationSpecification> aggregation_specification_; const bool best_effort_; std::unique_ptr<GroupAggregateOptions> options_; DISALLOW_COPY_AND_ASSIGN(GroupAggregateOperation); }; // Hybrid group implementation classes and functions. // Hybrid group aggregate uses disk-based sorting to allow processing more data // than would fit in memory. // // The key steps of the algorithm are: // - DISTINCT aggregation elimination // - preaggregation with best-effort GroupAggregate // - sorting the preaggregated data // - combining preaggregated rows on duplicate keys // - final aggregation using AggregateClusters. // // The motivation for eliminating DISINCT aggregations is threefold: // - partial results of DISTINCT aggregations can't be easily combined, // - building a whole set of unique values of an attribute for a single key can // take arbitrary amount of memory, // - existing code for computing DISTINCT aggregations doesn't track the memory // needed for tracking sets of unique values, // Here DISTINCT aggregations are eliminated by removing duplicate values in // DISTINCT aggregated columns, so these aggregations can then be computed with // ordinary, non-DISTINCT aggregating functions. This is done by adding DISTINCT // aggregated columns to the preaggregation key. To get unique values for each // DISTINCT aggregated column, each column needs to be processed separately. It // is achieved by transforming the input in such a way that each DISTINCT // aggregated column gets its copy of rows, where all other distinct aggregated // columns are set to NULL. This is the job of BoundHybridGroupTransform. The // approach used here relies heavily on the way NULLs are handled in // aggregation, most notably: // - NULLs in grouping key is treated as a distinct value, // - except for COUNT(*) aggregating functions ignore NULL input values. // // The next step is to preaggregate the (possibly transformed) input data using // best-effort GroupAggregate on a key extended with any DISTINCT aggregated // columns. This is done to reduce the amount of data that will need to be // sorted before final aggregation. Also, when there are no DISTINCT // aggregations best-effort preaggregation may manage to fully aggregate the // input - in this case sorting and final aggregation is not needed (which // improves performance). // // The preaggregated data is then sorted on the extended key and // AggregateClusters is performed to combine rows with equal keys. In the last // step final aggregation is performed with AggregateClusters on the original // key. // Analyzes grouping specification and sets up parameters for various stages of // hybrid group implementation. class HybridGroupSetup { public: // Takes ownership of input. static FailureOrOwned<const HybridGroupSetup> Create( const SingleSourceProjector& group_by_columns, const AggregationSpecification& aggregation_specification, const TupleSchema& input_schema) { std::unique_ptr<HybridGroupSetup> setup(new HybridGroupSetup); PROPAGATE_ON_FAILURE(setup->Init(group_by_columns, aggregation_specification, input_schema)); return Success(setup.release()); } // For restoring non-nullability of COUNT columns in hybrid group by. We // combine partial COUNT results using SUM and SUM's result is nullable. // TODO(user): This would be unneccesary if we could specify that SUM's result // should be not nullable. FailureOrOwned<Cursor> MakeCountColumnsNotNullable( Cursor* cursor, BufferAllocator* allocator) const { CHECK(initialized_); vector<string> column_names(columns_to_make_not_nullable_.begin(), columns_to_make_not_nullable_.end()); return column_names.empty() ? Success(cursor) : MakeSelectedColumnsNotNullable(ProjectNamedAttributes(column_names), allocator, cursor); } // Computes the result schema for HybridGroupFinalAggregationCursor. FailureOr<TupleSchema> ComputeResultSchema( const TupleSchema& group_by_columns_schema, const TupleSchema& aggregator_schema) const { CHECK(initialized_); FailureOr<TupleSchema> result_schema_bad_nullability = TupleSchema::TryMerge(group_by_columns_schema, aggregator_schema); PROPAGATE_ON_FAILURE(result_schema_bad_nullability); // Fixing nullability of COUNT columns. They may be wrong in // final_aggregator->schema() because final_aggregation uses SUM to compute // final results of COUNT(column) and SUMS's result is nullable. TupleSchema result_schema; for (int i = 0; i < result_schema_bad_nullability.get().attribute_count(); ++i) { const Attribute& attribute = result_schema_bad_nullability.get().attribute(i); result_schema.add_attribute( Attribute(attribute.name(), attribute.type(), ContainsKey(columns_to_make_not_nullable_, attribute.name()) ? NOT_NULLABLE : attribute.nullability())); } return Success(result_schema); } // Returns a cursor with input transformed for hybrid group. FailureOrOwned<Cursor> TransformInput(BufferAllocator* allocator, Cursor* input) const { CHECK(initialized_); std::unique_ptr<Cursor> input_owned(input); if (count_star_present_) { // Add a column with non-null values for implementing COUNT(*). FailureOrOwned<Cursor> input_with_count_star( ExtendByConstantColumn(count_star_column_name_, allocator, input_owned.release())); PROPAGATE_ON_FAILURE(input_with_count_star); input_owned.reset(input_with_count_star.release()); } return BoundHybridGroupTransform( group_by_columns_->Clone(), column_group_projectors_, allocator, input_owned.release()); } const AggregationSpecification& pregroup_aggregation() const { CHECK(initialized_); return pregroup_aggregation_; } const AggregationSpecification& pregroup_combine_aggregation() const { CHECK(initialized_); return pregroup_combine_aggregation_; } const AggregationSpecification& final_aggregation() const { CHECK(initialized_); return final_aggregation_; } const SingleSourceProjector& pregroup_group_by_columns() const { CHECK(initialized_); return pregroup_group_by_columns_; } bool has_distinct_aggregations() const { CHECK(initialized_); return has_distinct_aggregations_; } const SingleSourceProjector& group_by_columns_by_name() const { CHECK(initialized_); return *group_by_columns_by_name_; } private: HybridGroupSetup() : initialized_(false), count_star_column_name_("$hybrid_group_count_star$") {} FailureOrVoid Init( const SingleSourceProjector& group_by_columns, const AggregationSpecification& aggregation_specification, const TupleSchema& input_schema) { CHECK(!initialized_); group_by_columns_.reset(group_by_columns.Clone()); has_distinct_aggregations_ = false; count_star_present_ = false; // Hybrid group-by may need to project group-by columns multiple times // over transformed inputs, and it wouldn't work if the projector was // renaming columns, selecting columns by position or taking all input // columns. Because of this, in later stages of processing we use a // projector based on result column names of the original projector. FailureOrOwned<const SingleSourceProjector> group_by_columns_by_name( ProjectUsingProjectorResultNames(group_by_columns, input_schema)); PROPAGATE_ON_FAILURE(group_by_columns_by_name); group_by_columns_by_name_.reset(group_by_columns_by_name.release()); // pregroup_group_by_columns_ will contain all the original group-by columns // plus all the distinct aggregated columns. pregroup_group_by_columns_.add(group_by_columns_by_name_->Clone()); set<string> distinct_columns_set; set<string> nondistinct_columns_set; CompoundSingleSourceProjector nondistinct_columns; for (int i = 0; i < aggregation_specification.size(); ++i) { const AggregationSpecification::Element& elem = aggregation_specification.aggregation(i); const string pregroup_column_prefix = elem.is_distinct() ? "$hybrid_group_pregroup_column_d$" : "$hybrid_group_pregroup_column_nd$"; const string pregroup_column_name = StrCat(pregroup_column_prefix, elem.input()); AggregationSpecification::Element final_elem(elem); if (elem.is_distinct()) { has_distinct_aggregations_ = true; // <aggregate-function>(DISTINCT col). if (elem.input() == "") { THROW(new Exception( ERROR_ATTRIBUTE_MISSING, StringPrintf("Incorrect aggregation specification. Distinct " "aggregation needs input column."))); } if (InsertIfNotPresent(&distinct_columns_set, elem.input())) { column_group_projectors_.push_back( ProjectNamedAttributeAs(elem.input(), pregroup_column_name)); pregroup_group_by_columns_.add( ProjectNamedAttributeAs(pregroup_column_name, pregroup_column_name)); } // No need to add anything to pregroup_aggregation_. final_elem.set_input(pregroup_column_name); } else { AggregationSpecification::Element pregroup_elem(elem); // <aggregate-function>(col) or COUNT(*). if (elem.input() != "") { if (InsertIfNotPresent(&nondistinct_columns_set, elem.input())) { nondistinct_columns.add( ProjectNamedAttributeAs(elem.input(), pregroup_column_name)); } pregroup_elem.set_input(pregroup_column_name); } else { count_star_present_ = true; pregroup_elem.set_input(count_star_column_name_); } final_elem.set_input(pregroup_elem.output()); if (elem.aggregation_operator() == COUNT) { columns_to_make_not_nullable_.insert(final_elem.output()); final_elem.set_aggregation_operator(SUM); } AggregationSpecification::Element pregroup_combine_elem(final_elem); pregroup_combine_elem.set_output(pregroup_combine_elem.input()); pregroup_aggregation_.add(pregroup_elem); pregroup_combine_aggregation_.add(pregroup_combine_elem); } final_aggregation_.add(final_elem); } if (count_star_present_) { // Add a column with non-null values for implementing COUNT(*). nondistinct_columns.add( ProjectNamedAttributeAs(count_star_column_name_, count_star_column_name_)); } if (!nondistinct_columns_set.empty() || count_star_present_ || column_group_projectors_.empty()) { column_group_projectors_.push_back(nondistinct_columns.Clone()); } initialized_ = true; return Success(); } static FailureOrOwned<const SingleSourceProjector> ProjectUsingProjectorResultNames(const SingleSourceProjector& projector, const TupleSchema& schema) { FailureOrOwned<const BoundSingleSourceProjector> bound_projector( projector.Bind(schema)); PROPAGATE_ON_FAILURE(bound_projector); const TupleSchema& result_schema = bound_projector->result_schema(); vector<string> result_names; for (int i = 0; i < result_schema.attribute_count(); ++i) { result_names.push_back(result_schema.attribute(i).name()); } return Success(ProjectNamedAttributes(result_names)); } private: // Was the object initialized successfully with Init(...). bool initialized_; // Does the AggregationSpecification contain DISTINCT aggregations? bool has_distinct_aggregations_; // Does the AggregationSpecification contain COUNT(*)? bool count_star_present_; // The name of the column added for COUNT(*) implementation. const string count_star_column_name_; // The original group by columns projector. std::unique_ptr<const SingleSourceProjector> group_by_columns_; // A safe projector for use in later processing, based on the result // names of the original group_by_columns_ projector. std::unique_ptr<const SingleSourceProjector> group_by_columns_by_name_; // A set of COUNT columns (names) that will need nullability fixing because // the implementation uses SUM on later (post pregroup) stages. set<string> columns_to_make_not_nullable_; // A set of projectors that define column groups for the // HybridGroupTransformCursor. There's a separate projector for each column // that has DISTINCT aggregations on it, and a shared projector for all // columns that have non-DISTINCT aggregations on them. util::gtl::PointerVector<const SingleSourceProjector> column_group_projectors_; // Group-by columns for the pregroup aggregation (will additionally contain // distinct aggregated columns). CompoundSingleSourceProjector pregroup_group_by_columns_; // The initial (pregroup) aggregation. AggregationSpecification pregroup_aggregation_; // Aggregation for combining results of pregroup for duplicated keys. AggregationSpecification pregroup_combine_aggregation_; // Final aggregation combining results of pregroup aggregation for // non-DISTINCT aggregations and using ordinary, non-DISTINCT aggregations in // place of original DISTINCT aggregations. AggregationSpecification final_aggregation_; DISALLOW_COPY_AND_ASSIGN(HybridGroupSetup); }; // Combines preaggregated results on repeated (extended) keys and the final // aggregation to compute the results for DISTINCT aggregations. class HybridGroupFinalAggregationCursor : public BasicCursor { public: // Takes ownership of hybrid_group_setup, final_aggregator, // final_group_by_columns and pregroup_cursor. HybridGroupFinalAggregationCursor( const TupleSchema& result_schema, const HybridGroupSetup* hybrid_group_setup, Aggregator* final_aggregator, const BoundSingleSourceProjector* final_group_by_columns, StringPiece temporary_directory_prefix, BufferAllocator* allocator, GroupAggregateCursor* pregroup_cursor) : BasicCursor(result_schema), is_waiting_on_barrier_supported_( pregroup_cursor->IsWaitingOnBarrierSupported()), hybrid_group_setup_(hybrid_group_setup), final_aggregator_(final_aggregator), final_group_by_columns_(final_group_by_columns), temporary_directory_prefix_(temporary_directory_prefix.ToString()), allocator_(allocator), pregroup_cursor_(pregroup_cursor) { } virtual ResultView Next(rowcount_t max_row_count) { if (result_cursor_ == NULL && sorter_ == NULL) { ResultView first_result = pregroup_cursor_->Next( numeric_limits<rowcount_t>::max()); if (first_result.is_eos() || !first_result.has_data()) { return first_result; } if (!pregroup_cursor_->CanReturnMoreData() && !hybrid_group_setup_->has_distinct_aggregations()) { pregroup_cursor_->TruncateResultView(); // There are no distinct aggregations, so if pregroup fully aggregated // all the data (a single output block), its result can be returned as // final result. LOG(INFO) << "HybridGroupAggregate not using disk."; PROPAGATE_ON_FAILURE(SetResultCursor(pregroup_cursor_.release())); } else { // Pregroup best-effort didn't fully aggregate the data. Sorting data to // combine duplicate pregroup keys. The final aggregation will be // performed using AggregateClusters, as the data will also be sorted on // the original key. if (first_result.has_data()) { pregroup_cursor_->TruncateResultView(); } LOG(INFO) << "HybridGroupAggregate using disk (" << (hybrid_group_setup_->has_distinct_aggregations() ? "distinct aggregations" : "best-effort failed") << ")."; FailureOrOwned<const BoundSingleSourceProjector> bound_group_by_columns( hybrid_group_setup_->pregroup_group_by_columns().Bind( pregroup_cursor_->schema())); PROPAGATE_ON_FAILURE(bound_group_by_columns); sorter_.reset(CreateUnbufferedSorter( pregroup_cursor_->schema(), new BoundSortOrder(bound_group_by_columns.release()), temporary_directory_prefix_, allocator_)); } } if (result_cursor_ == NULL && sorter_ != NULL) { while (true) { ResultView result = pregroup_cursor_->Next( numeric_limits<rowcount_t>::max()); PROPAGATE_ON_FAILURE(result); if (result.is_waiting_on_barrier()) { return ResultView::WaitingOnBarrier(); } if (result.is_eos()) { break; } VLOG(1) << "Writing " << result.view().row_count() << " rows to UnbufferedSorter."; FailureOr<rowcount_t> written = sorter_->Write(result.view()); PROPAGATE_ON_FAILURE(written); CHECK_EQ(written.get(), result.view().row_count()); } // Aggregate to combine duplicated pregroup keys. FailureOrOwned<Cursor> sorted = sorter_->GetResultCursor(); PROPAGATE_ON_FAILURE(sorted); sorter_.reset(); FailureOrOwned<Aggregator> aggregator = Aggregator::Create( hybrid_group_setup_->pregroup_combine_aggregation(), sorted.get()->schema(), allocator_, 1024); PROPAGATE_ON_FAILURE(aggregator); FailureOrOwned<const BoundSingleSourceProjector> sorted_group_by_columns = hybrid_group_setup_->pregroup_group_by_columns().Bind( sorted.get()->schema()); PROPAGATE_ON_FAILURE(sorted_group_by_columns); FailureOrOwned<Cursor> combine_cursor = BoundAggregateClusters( sorted_group_by_columns.release(), aggregator.release(), allocator_, sorted.release()); PROPAGATE_ON_FAILURE(combine_cursor); // Restoring COUNT column nullability, so we have exactly the same schema // that final_aggregator was built for. FailureOrOwned<Cursor> combine_cursor_count_nonnullable = hybrid_group_setup_->MakeCountColumnsNotNullable( combine_cursor.release(), allocator_); PROPAGATE_ON_FAILURE(combine_cursor_count_nonnullable); // Final aggregation on the original key using AggregateClusters. FailureOrOwned<Cursor> aggregated = BoundAggregateClusters( final_group_by_columns_.release(), final_aggregator_.release(), allocator_, combine_cursor_count_nonnullable.release()); PROPAGATE_ON_FAILURE(aggregated); PROPAGATE_ON_FAILURE(SetResultCursor(aggregated.release())); } CHECK(sorter_ == NULL); CHECK(result_cursor_ != NULL); ResultView result = result_cursor_->Next(max_row_count); PROPAGATE_ON_FAILURE(result); return result; } virtual bool IsWaitingOnBarrierSupported() const { return is_waiting_on_barrier_supported_; } virtual void Interrupt() { Cursor* pregroup_cursor = pregroup_cursor_.get(); if (pregroup_cursor != NULL) { pregroup_cursor->Interrupt(); } Cursor* result_cursor = result_cursor_.get(); if (result_cursor != NULL) { result_cursor->Interrupt(); } } virtual CursorId GetCursorId() const { return HYBRID_GROUP_FINAL_AGGREGATION; } // Runs the transformer recursively on the pregrouping aggregate cursor. // // This solution effectively omits the transformation of the pregrouping // cursor, as it conflicts with the return type of Transform(). // The hybrid aggregate and pregroup aggregate cursor are treated as one // by cursor transformers. virtual void ApplyToChildren(CursorTransformer* transformer) { pregroup_cursor_->ApplyToChildren(transformer); } private: FailureOrVoid SetResultCursor(Cursor* result_cursor) { FailureOrOwned<Cursor> result_cursor_fixed_nullability = hybrid_group_setup_->MakeCountColumnsNotNullable( result_cursor, allocator_); PROPAGATE_ON_FAILURE(result_cursor_fixed_nullability); result_cursor_.reset(result_cursor_fixed_nullability.release()); CHECK(TupleSchema::AreEqual(schema(), result_cursor_->schema(), true)) << "schema(): " << schema().GetHumanReadableSpecification() << "\naggregated_owned->schema(): " << result_cursor_->schema().GetHumanReadableSpecification(); return Success(); } bool is_waiting_on_barrier_supported_; std::unique_ptr<const HybridGroupSetup> hybrid_group_setup_; std::unique_ptr<Aggregator> final_aggregator_; std::unique_ptr<const BoundSingleSourceProjector> final_group_by_columns_; size_t memory_quota_; string temporary_directory_prefix_; BufferAllocator* allocator_; std::unique_ptr<GroupAggregateCursor> pregroup_cursor_; std::unique_ptr<Sorter> sorter_; std::unique_ptr<Cursor> result_cursor_; DISALLOW_COPY_AND_ASSIGN(HybridGroupFinalAggregationCursor); }; } // namespace Operation* GroupAggregate( const SingleSourceProjector* group_by, const AggregationSpecification* aggregation, GroupAggregateOptions* options, Operation* child) { return new GroupAggregateOperation(group_by, aggregation, options, false, child); } Operation* BestEffortGroupAggregate( const SingleSourceProjector* group_by, const AggregationSpecification* aggregation, GroupAggregateOptions* options, Operation* child) { return new GroupAggregateOperation(group_by, aggregation, options, true, child); } // TODO(user): Remove this variant in favor of BoundGroupAggregateWithLimit FailureOrOwned<Cursor> BoundGroupAggregate( const BoundSingleSourceProjector* group_by, Aggregator* aggregator, BufferAllocator* allocator, BufferAllocator* original_allocator, bool best_effort, Cursor* child) { return BoundGroupAggregateWithLimit(group_by, aggregator, allocator, original_allocator, best_effort, kint64max, child); } FailureOrOwned<Cursor> BoundGroupAggregateWithLimit( const BoundSingleSourceProjector* group_by, Aggregator* aggregator, BufferAllocator* allocator, BufferAllocator* original_allocator, bool best_effort, const int64 max_unique_keys_in_result, Cursor* child) { FailureOrOwned<GroupAggregateCursor> result = GroupAggregateCursor::Create( group_by, aggregator, allocator, original_allocator == NULL ? allocator : original_allocator, best_effort, max_unique_keys_in_result, child); PROPAGATE_ON_FAILURE(result); return Success(result.release()); } FailureOrOwned<Cursor> BoundHybridGroupAggregate( const SingleSourceProjector* group_by_columns, const AggregationSpecification& aggregation_specification, StringPiece temporary_directory_prefix, BufferAllocator* allocator, size_t memory_quota, const HybridGroupDebugOptions* debug_options, Cursor* child) { std::unique_ptr<Cursor> child_owner(child); std::unique_ptr<const SingleSourceProjector> group_by_columns_owner( group_by_columns); std::unique_ptr<const HybridGroupDebugOptions> debug_options_owned( debug_options); FailureOrOwned<const HybridGroupSetup> hybrid_group_setup( HybridGroupSetup::Create(*group_by_columns_owner, aggregation_specification, child_owner->schema())); PROPAGATE_ON_FAILURE(hybrid_group_setup); FailureOrOwned<Cursor> transformed_input( hybrid_group_setup->TransformInput(allocator, child_owner.release())); PROPAGATE_ON_FAILURE(transformed_input); if (debug_options_owned != NULL && debug_options_owned->return_transformed_input()) { return transformed_input; } // Use best-effort group aggregate to pregroup the data. FailureOrOwned<const BoundSingleSourceProjector> bound_pregroup_columns( hybrid_group_setup->pregroup_group_by_columns().Bind( transformed_input->schema())); PROPAGATE_ON_FAILURE(bound_pregroup_columns); // limit_allocator will be owned by 'pregroup_cursor'. std::unique_ptr<BufferAllocator> limit_allocator( new MemoryLimit(memory_quota, false, allocator)); FailureOrOwned<Aggregator> pregroup_aggregator = Aggregator::Create( hybrid_group_setup->pregroup_aggregation(), transformed_input->schema(), limit_allocator.get(), 1024); PROPAGATE_ON_FAILURE(pregroup_aggregator); FailureOrOwned<GroupAggregateCursor> pregroup_cursor = GroupAggregateCursor::Create( bound_pregroup_columns.release(), pregroup_aggregator.release(), limit_allocator.release(), allocator, true, // best effort. kint64max, transformed_input.release()); PROPAGATE_ON_FAILURE(pregroup_cursor); // Building final_aggregator and final_group_by_columns to compute the // result_schema for HybridGroupFinalAggregationCursor. FailureOrOwned<Aggregator> final_aggregator = Aggregator::Create( hybrid_group_setup->final_aggregation(), pregroup_cursor->schema(), allocator, 1024); PROPAGATE_ON_FAILURE(final_aggregator); FailureOrOwned<const BoundSingleSourceProjector> final_group_by_columns( hybrid_group_setup->group_by_columns_by_name().Bind( pregroup_cursor->schema())); PROPAGATE_ON_FAILURE(final_group_by_columns); // Calculate the schema of the final cursor. FailureOr<TupleSchema> result_schema = hybrid_group_setup->ComputeResultSchema( final_group_by_columns->result_schema(), final_aggregator->schema()); PROPAGATE_ON_FAILURE(result_schema); return Success(new HybridGroupFinalAggregationCursor( result_schema.get(), hybrid_group_setup.release(), final_aggregator.release(), final_group_by_columns.release(), temporary_directory_prefix, allocator, pregroup_cursor.release())); } class HybridGroupAggregateOperation : public BasicOperation { public: HybridGroupAggregateOperation( const SingleSourceProjector* group_by_columns, const AggregationSpecification* aggregation_specification, size_t memory_quota, StringPiece temporary_directory_prefix, Operation* child) : BasicOperation(child), group_by_columns_(group_by_columns), aggregation_specification_(aggregation_specification), memory_quota_(memory_quota), temporary_directory_prefix_(temporary_directory_prefix.ToString()) {} virtual ~HybridGroupAggregateOperation() {} virtual FailureOrOwned<Cursor> CreateCursor() const { FailureOrOwned<Cursor> child_cursor = child()->CreateCursor(); PROPAGATE_ON_FAILURE(child_cursor); return BoundHybridGroupAggregate( group_by_columns_->Clone(), *aggregation_specification_, temporary_directory_prefix_, buffer_allocator(), memory_quota_, NULL, child_cursor.release()); } private: std::unique_ptr<const SingleSourceProjector> group_by_columns_; std::unique_ptr<const AggregationSpecification> aggregation_specification_; size_t memory_quota_; string temporary_directory_prefix_; DISALLOW_COPY_AND_ASSIGN(HybridGroupAggregateOperation); }; Operation* HybridGroupAggregate( const SingleSourceProjector* group_by_columns, const AggregationSpecification* aggregation_specification, size_t memory_quota, StringPiece temporary_directory_prefix, Operation* child) { return new HybridGroupAggregateOperation(group_by_columns, aggregation_specification, memory_quota, temporary_directory_prefix, child); } } // namespace supersonic
41.669828
80
0.701781
IssamElbaytam
acc5d6b6567be09ad8389cda0ec835b7f7bc50ab
23,914
cpp
C++
src/states/main-state.cpp
xterminal86/nrogue
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
[ "MIT" ]
7
2019-03-05T05:32:13.000Z
2022-01-10T10:06:47.000Z
src/states/main-state.cpp
xterminal86/nrogue
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
[ "MIT" ]
2
2020-01-19T16:43:51.000Z
2021-12-16T14:54:56.000Z
src/states/main-state.cpp
xterminal86/nrogue
1d4e578b3d854b8e4d41f5ba1477de9b2c9e864f
[ "MIT" ]
null
null
null
#include "main-state.h" #include "application.h" #include "map.h" #include "printer.h" #include "stairs-component.h" #include "target-state.h" #include "spells-processor.h" void MainState::Init() { _playerRef = &Application::Instance().PlayerInstance; } void MainState::HandleInput() { // // Otherwise we could still time-in some action // even after we received fatal damage. // // E.g. we wait a turn, spider approaches and deals fatal damage, // this results in Player.IsAlive = false, but if we check IsAlive() // at the end of HandleInput(), we could still issue some other command // if we are quick enough before condition is checked // and current state changes to ENDGAME_STATE. // if (!_playerRef->IsAlive()) { Application::Instance().ChangeState(GameStates::ENDGAME_STATE); return; } _keyPressed = GetKeyDown(); switch (_keyPressed) { case ALT_K7: case NUMPAD_7: ProcessMovement({ -1, -1 }); break; case ALT_K8: case NUMPAD_8: ProcessMovement({ 0, -1 }); break; case ALT_K9: case NUMPAD_9: ProcessMovement({ 1, -1 }); break; case ALT_K4: case NUMPAD_4: ProcessMovement({ -1, 0 }); break; case ALT_K2: case NUMPAD_2: ProcessMovement({ 0, 1 }); break; case ALT_K6: case NUMPAD_6: ProcessMovement({ 1, 0 }); break; case ALT_K1: case NUMPAD_1: ProcessMovement({ -1, 1 }); break; case ALT_K3: case NUMPAD_3: ProcessMovement({ 1, 1 }); break; case ALT_K5: case NUMPAD_5: Printer::Instance().AddMessage(Strings::MsgWait); _playerRef->FinishTurn(); break; case 'a': { if (Map::Instance().CurrentLevel->Peaceful) { PrintNoAttackInTown(); } else if (_playerRef->IsSwimming()) { Printer::Instance().AddMessage(Strings::MsgNotInWater); } else { Application::Instance().ChangeState(GameStates::ATTACK_STATE); } } break; case '$': { auto str = Util::StringFormat("You have %i %s", _playerRef->Money, Strings::MoneyName.data()); Printer::Instance().AddMessage(str); } break; case 'e': Application::Instance().ChangeState(GameStates::INVENTORY_STATE); break; case 'm': Application::Instance().ChangeState(GameStates::SHOW_MESSAGES_STATE); break; case 'l': Application::Instance().ChangeState(GameStates::LOOK_INPUT_STATE); break; case 'i': Application::Instance().ChangeState(GameStates::INTERACT_INPUT_STATE); break; case 'I': DisplayScenarioInformation(); break; case 'g': TryToPickupItem(); break; case '@': Application::Instance().ChangeState(GameStates::INFO_STATE); break; case 'H': case 'h': case '?': Application::Instance().ChangeState(GameStates::HELP_STATE); break; case 'Q': Application::Instance().ChangeState(GameStates::EXITING_STATE); break; case 'f': ProcessRangedWeapon(); break; case '>': { auto res = CheckStairs('>'); if (res.first != nullptr) { ClimbStairs(res); } } break; case '<': { auto res = CheckStairs('<'); if (res.first != nullptr) { ClimbStairs(res); } } break; #ifdef DEBUG_BUILD case '`': Application::Instance().ChangeState(GameStates::DEV_CONSOLE); break; case 'T': { int exitX = Map::Instance().CurrentLevel->LevelExit.X; int exitY = Map::Instance().CurrentLevel->LevelExit.Y; if (_playerRef->MoveTo(exitX, exitY)) { Map::Instance().CurrentLevel->AdjustCamera(); Update(true); _playerRef->FinishTurn(); } else { auto str = Util::StringFormat("[%i;%i] is occupied!", exitX, exitY); Printer::Instance().AddMessage(str); DebugLog("%s\n", str.data()); } } break; case 's': GetActorsAround(); break; #endif default: break; } } void MainState::Update(bool forceUpdate) { if (_keyPressed != -1 || forceUpdate) { Printer::Instance().Clear(); _playerRef->CheckVisibility(); Map::Instance().Draw(); _playerRef->Draw(); DisplayStartHint(); DisplayExitHint(); DisplayStatusIcons(); DrawHPMP(); if (Printer::Instance().ShowLastMessage) { DisplayGameLog(); } else { Printer::Instance().ResetMessagesToDisplay(); } Printer::Instance().PrintFB(Printer::TerminalWidth - 1, 0, Map::Instance().CurrentLevel->LevelName, Printer::kAlignRight, Colors::WhiteColor); #ifdef DEBUG_BUILD PrintDebugInfo(); #endif Printer::Instance().Render(); } } void MainState::ProcessMovement(const Position& dirOffsets) { // TODO: levitation if (_playerRef->TryToAttack(dirOffsets.X, dirOffsets.Y)) { _playerRef->FinishTurn(); } else if (_playerRef->Move(dirOffsets.X, dirOffsets.Y)) { // This line must be the first in order to // allow potential messages to show in FinishTurn() // (e.g. starvation damage message) after player moved. Printer::Instance().ShowLastMessage = false; Map::Instance().CurrentLevel->MapOffsetX -= dirOffsets.X; Map::Instance().CurrentLevel->MapOffsetY -= dirOffsets.Y; _playerRef->FinishTurn(); auto& px = _playerRef->PosX; auto& py = _playerRef->PosY; // Sometimes loot can drop on top of stairs // which can make them hard to find on map. if(Map::Instance().CurrentLevel->MapArray[px][py]->Image == '>') { Printer::Instance().AddMessage(Strings::MsgStairsDown); } else if(Map::Instance().CurrentLevel->MapArray[px][py]->Image == '<') { Printer::Instance().AddMessage(Strings::MsgStairsUp); } } } void MainState::DisplayGameLog() { int x = Printer::TerminalWidth - 1; int y = Printer::TerminalHeight - 1; int count = 0; auto msgs = Printer::Instance().GetLastMessages(); for (auto& m : msgs) { Printer::Instance().PrintFB(x, y - count, m.Message, Printer::kAlignRight, m.FgColor, m.BgColor); count++; } } void MainState::TryToPickupItem() { auto res = Map::Instance().GetGameObjectToPickup(_playerRef->PosX, _playerRef->PosY); if (res.first != -1) { if (ProcessMoneyPickup(res)) { CheckIfSomethingElseIsLyingHere({ _playerRef->PosX, _playerRef->PosY }); return; } if (_playerRef->Inventory.IsFull()) { Application::Instance().ShowMessageBox(MessageBoxType::ANY_KEY, Strings::MessageBoxEpicFailHeaderText, { Strings::MsgInventoryFull }, Colors::MessageBoxRedBorderColor); return; } ProcessItemPickup(res); CheckIfSomethingElseIsLyingHere({ _playerRef->PosX, _playerRef->PosY }); } else { Printer::Instance().AddMessage(Strings::MsgNothingHere); } } void MainState::CheckIfSomethingElseIsLyingHere(const Position& pos) { auto res = Map::Instance().GetGameObjectToPickup(pos.X, pos.Y); if (res.first != -1) { Printer::Instance().AddMessage(Strings::MsgSomethingLying); } } void MainState::DrawHPMP() { int curHp = _playerRef->Attrs.HP.Min().Get(); int maxHp = _playerRef->Attrs.HP.Max().Get(); int curMp = _playerRef->Attrs.MP.Min().Get(); int maxMp = _playerRef->Attrs.MP.Max().Get(); int th = Printer::TerminalHeight; UpdateBar(1, th - 2, _playerRef->Attrs.HP); auto str = Util::StringFormat("%i/%i", curHp, maxHp); Printer::Instance().PrintFB(GlobalConstants::HPMPBarLength / 2, th - 2, str, Printer::kAlignCenter, Colors::WhiteColor, "#880000"); UpdateBar(1, th - 1, _playerRef->Attrs.MP); str = Util::StringFormat("%i/%i", curMp, maxMp); Printer::Instance().PrintFB(GlobalConstants::HPMPBarLength / 2, th - 1, str, Printer::kAlignCenter, Colors::WhiteColor, "#000088"); } void MainState::UpdateBar(int x, int y, RangedAttribute& attr) { float ratio = ((float)attr.Min().Get() / (float)attr.Max().Get()); int len = ratio * GlobalConstants::HPMPBarLength; std::string bar = "["; for (int i = 0; i < GlobalConstants::HPMPBarLength; i++) { bar += (i < len) ? "=" : " "; } bar += "]"; Printer::Instance().PrintFB(x, y, bar, Printer::kAlignLeft, Colors::WhiteColor); } std::pair<GameObject*, bool> MainState::CheckStairs(int stairsSymbol) { GameObject* stairsTile = Map::Instance().CurrentLevel->MapArray[_playerRef->PosX][_playerRef->PosY].get(); if (stairsSymbol == '>') { if (stairsTile->Image != stairsSymbol) { Printer::Instance().AddMessage(Strings::MsgNoStairsDown); _stairsTileInfo.first = nullptr; } else { _stairsTileInfo.first = stairsTile; _stairsTileInfo.second = true; } } else if (stairsSymbol == '<') { if (stairsTile->Image != stairsSymbol) { Printer::Instance().AddMessage(Strings::MsgNoStairsUp); _stairsTileInfo.first = nullptr; } else { _stairsTileInfo.first = stairsTile; _stairsTileInfo.second = false; } } return _stairsTileInfo; } void MainState::ClimbStairs(const std::pair<GameObject*, bool>& stairsTileInfo) { bool upOrDown = stairsTileInfo.second; Component* c = stairsTileInfo.first->GetComponent<StairsComponent>(); StairsComponent* stairs = static_cast<StairsComponent*>(c); Map::Instance().ChangeLevel(stairs->LeadsTo, upOrDown); } void MainState::PrintDebugInfo() { _debugInfo = Util::StringFormat("Act: %i Ofst: %i %i: Plr: [%i;%i] Hunger: %i", _playerRef->Attrs.ActionMeter, Map::Instance().CurrentLevel->MapOffsetX, Map::Instance().CurrentLevel->MapOffsetY, _playerRef->PosX, _playerRef->PosY, _playerRef->Attrs.Hunger); Printer::Instance().PrintFB(1, 1, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); _debugInfo = Util::StringFormat("Key: %i Actors: %i Respawn: %i", _keyPressed, Map::Instance().CurrentLevel->ActorGameObjects.size(), Map::Instance().CurrentLevel->RespawnCounter()); Printer::Instance().PrintFB(1, 2, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); _debugInfo = Util::StringFormat("Level Start: [%i;%i]", Map::Instance().CurrentLevel->LevelStart.X, Map::Instance().CurrentLevel->LevelStart.Y); Printer::Instance().PrintFB(1, 3, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); _debugInfo = Util::StringFormat("Level Exit: [%i;%i]", Map::Instance().CurrentLevel->LevelExit.X, Map::Instance().CurrentLevel->LevelExit.Y); Printer::Instance().PrintFB(1, 4, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); _debugInfo = Util::StringFormat("Colors Used: %i", Printer::Instance().ColorsUsed()); Printer::Instance().PrintFB(1, 5, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); _debugInfo = Util::StringFormat("Turns passed: %i", Application::Instance().TurnsPassed); Printer::Instance().PrintFB(1, 6, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); Printer::Instance().PrintFB(1, 7, "Actors watched:", Printer::kAlignLeft, Colors::WhiteColor); int yOffset = 0; bool found = false; for (auto& id : _actorsForDebugDisplay) { for (auto& a : Map::Instance().CurrentLevel->ActorGameObjects) { if (a->ObjectId() == id) { _debugInfo = Util::StringFormat("%s_%lu (%i)", a->ObjectName.data(), id, a->Attrs.ActionMeter); Printer::Instance().PrintFB(1, 8 + yOffset, _debugInfo, Printer::kAlignLeft, Colors::WhiteColor); yOffset++; found = true; } } } if (!found) { Printer::Instance().PrintFB(1, 8, "<Press 's' to scan 1x1 around player>", Printer::kAlignLeft, Colors::WhiteColor); } } void MainState::ProcessRangedWeapon() { if (Map::Instance().CurrentLevel->Peaceful) { // NOTE: comment out all lines for debug if needed PrintNoAttackInTown(); return; } if (_playerRef->IsSwimming()) { Printer::Instance().AddMessage(Strings::MsgNotInWater); return; } // TODO: wands in both hands? ItemComponent* weapon = _playerRef->EquipmentByCategory[EquipmentCategory::WEAPON][0]; if (weapon != nullptr) { if (weapon->Data.ItemType_ == ItemType::WAND) { ProcessWand(weapon); } else if (weapon->Data.ItemType_ == ItemType::RANGED_WEAPON) { ProcessWeapon(weapon); } else { Printer::Instance().AddMessage(Strings::MsgNotRangedWeapon); } } else { Printer::Instance().AddMessage(Strings::MsgEquipWeapon); } } void MainState::ProcessWeapon(ItemComponent* weapon) { ItemComponent* arrows = _playerRef->EquipmentByCategory[EquipmentCategory::SHIELD][0]; if (arrows != nullptr) { bool isBow = (weapon->Data.RangedWeaponType_ == RangedWeaponType::SHORT_BOW || weapon->Data.RangedWeaponType_ == RangedWeaponType::LONGBOW || weapon->Data.RangedWeaponType_ == RangedWeaponType::WAR_BOW); bool isXBow = (weapon->Data.RangedWeaponType_ == RangedWeaponType::LIGHT_XBOW || weapon->Data.RangedWeaponType_ == RangedWeaponType::XBOW || weapon->Data.RangedWeaponType_ == RangedWeaponType::HEAVY_XBOW); if (arrows->Data.ItemType_ != ItemType::ARROWS) { Printer::Instance().AddMessage(Strings::MsgWhatToShoot); } else { if ( (isBow && arrows->Data.AmmoType == ArrowType::BOLTS) || (isXBow && arrows->Data.AmmoType == ArrowType::ARROWS) ) { Printer::Instance().AddMessage(Strings::MsgWrongAmmo); return; } if (arrows->Data.Amount == 0) { Printer::Instance().AddMessage(Strings::MsgNoAmmo); } else { auto s = Application::Instance().GetGameStateRefByName(GameStates::TARGET_STATE); TargetState* ts = static_cast<TargetState*>(s); ts->Setup(weapon); Application::Instance().ChangeState(GameStates::TARGET_STATE); } } } else { Printer::Instance().AddMessage(Strings::MsgWhatToShoot); } } void MainState::ProcessWand(ItemComponent* wand) { // NOTE: amount of charges should be subtracted // separately in corresponding methods // (i.e. EffectsProcessor or inside TargetState), // because combat wands require targeting, // which is checked against out of bounds, // and only after it's OK and player hits "fire", // the actual firing takes place. if (wand->Data.Amount == 0) { Printer::Instance().AddMessage(Strings::MsgNoCharges); } else { switch (wand->Data.SpellHeld.SpellType_) { // TODO: finish wands effects and attack // (e.g. wand of heal others etc.) case SpellType::LIGHT: SpellsProcessor::Instance().ProcessWand(wand); break; case SpellType::STRIKE: case SpellType::FROST: case SpellType::TELEPORT: case SpellType::FIREBALL: case SpellType::LASER: case SpellType::LIGHTNING: case SpellType::MAGIC_MISSILE: case SpellType::NONE: { auto s = Application::Instance().GetGameStateRefByName(GameStates::TARGET_STATE); TargetState* ts = static_cast<TargetState*>(s); ts->Setup(wand); Application::Instance().ChangeState(GameStates::TARGET_STATE); } break; default: break; } } } bool MainState::ProcessMoneyPickup(std::pair<int, GameObject*>& pair) { ItemComponent* ic = pair.second->GetComponent<ItemComponent>(); if (ic->Data.ItemType_ == ItemType::COINS) { auto message = Util::StringFormat(Strings::FmtPickedUpIS, ic->Data.Amount, ic->OwnerGameObject->ObjectName.data()); Printer::Instance().AddMessage(message); _playerRef->Money += ic->Data.Amount; auto it = Map::Instance().CurrentLevel->GameObjects.begin(); Map::Instance().CurrentLevel->GameObjects.erase(it + pair.first); return true; } return false; } void MainState::ProcessItemPickup(std::pair<int, GameObject*>& pair) { ItemComponent* ic = pair.second->GetComponent<ItemComponent>(); auto go = Map::Instance().CurrentLevel->GameObjects[pair.first].release(); _playerRef->Inventory.Add(go); std::string objName = ic->Data.IsIdentified ? go->ObjectName : ic->Data.UnidentifiedName; std::string message; if (ic->Data.IsStackable) { message = Util::StringFormat(Strings::FmtPickedUpIS, ic->Data.Amount, objName.data()); } else { message = Util::StringFormat(Strings::FmtPickedUpS, objName.data()); } Printer::Instance().AddMessage(message); auto it = Map::Instance().CurrentLevel->GameObjects.begin(); Map::Instance().CurrentLevel->GameObjects.erase(it + pair.first); } void MainState::DisplayStartHint() { int th = Printer::TerminalHeight; Printer::Instance().PrintFB(1, th - 4, '<', Colors::WhiteColor, Colors::DoorHighlightColor); auto curLvl = Map::Instance().CurrentLevel; int dx = curLvl->LevelStart.X - _playerRef->PosX; int dy = curLvl->LevelStart.Y - _playerRef->PosY; std::string dir; if (dy > 0) { dir += "S"; } else if (dy < 0) { dir += "N"; } if (dx > 0) { dir += "E"; } else if (dx < 0) { dir += "W"; } Printer::Instance().PrintFB(2, th - 4, dir, Printer::kAlignLeft, Colors::WhiteColor); } void MainState::DisplayExitHint() { int th = Printer::TerminalHeight; Printer::Instance().PrintFB(1, th - 3, '>', Colors::WhiteColor, Colors::DoorHighlightColor); std::string dir; auto curLvl = Map::Instance().CurrentLevel; if (curLvl->ExitFound) { int dx = curLvl->LevelExit.X - _playerRef->PosX; int dy = curLvl->LevelExit.Y - _playerRef->PosY; if (dy > 0) { dir += "S"; } else if (dy < 0) { dir += "N"; } if (dx > 0) { dir += "E"; } else if (dx < 0) { dir += "W"; } } Printer::Instance().PrintFB(2, th - 3, curLvl->ExitFound ? dir : "??", Printer::kAlignLeft, Colors::WhiteColor); } void MainState::DisplayStatusIcons() { int startPos = 4; DisplayHungerStatus(startPos); DisplayWeaponCondition(startPos); DisplayArmorCondition(startPos); DisplayAmmoCondition(startPos); DisplayActiveEffects(startPos); } void MainState::DisplayHungerStatus(const int& startPos) { if (_playerRef->IsStarving) { Printer::Instance().PrintFB(startPos, _th - 3, '%', Colors::WhiteColor, Colors::RedColor); } else { int hungerMax = _playerRef->Attrs.HungerRate.Get(); int part = hungerMax - hungerMax * 0.25; if (_playerRef->Attrs.Hunger >= part) { Printer::Instance().PrintFB(startPos, _th - 3, '%', Colors::WhiteColor, "#999900"); } } } void MainState::DisplayWeaponCondition(const int& startPos) { ItemComponent* weapon = _playerRef->EquipmentByCategory[EquipmentCategory::WEAPON][0]; if (weapon != nullptr && (weapon->Data.ItemType_ == ItemType::WEAPON || weapon->Data.ItemType_ == ItemType::RANGED_WEAPON)) { int maxDur = weapon->Data.Durability.Max().Get(); int warning = maxDur * 0.3f; if (weapon->Data.Durability.Min().Get() <= warning) { Printer::Instance().PrintFB(startPos + 2, _th - 3, ')', Colors::YellowColor); } } } void MainState::DisplayArmorCondition(const int& startPos) { ItemComponent* armor = _playerRef->EquipmentByCategory[EquipmentCategory::TORSO][0]; if (armor != nullptr && armor->Data.ItemType_ == ItemType::ARMOR) { int maxDur = armor->Data.Durability.Max().Get(); int warning = maxDur * 0.3f; if (armor->Data.Durability.Min().Get() <= warning) { Printer::Instance().PrintFB(startPos + 4, _th - 3, '[', Colors::YellowColor); } } } void MainState::DisplayAmmoCondition(const int& startPos) { ItemComponent* arrows = _playerRef->EquipmentByCategory[EquipmentCategory::SHIELD][0]; if (arrows != nullptr && arrows->Data.ItemType_ == ItemType::ARROWS) { int amount = arrows->Data.Amount; if (amount <= 3) { Printer::Instance().PrintFB(startPos + 6, _th - 3, '^', Colors::YellowColor); } } } void MainState::DisplayActiveEffects(const int& startPos) { int offsetX = startPos; std::map<std::string, int> effectDurationByName; for (auto& kvp : _playerRef->Effects()) { for (const ItemBonusStruct& item : kvp.second) { std::string shortName = GlobalConstants::BonusDisplayNameByType.at(item.Type); int duration = item.Duration; if (duration != -1) { effectDurationByName[shortName] += duration; } else { effectDurationByName[shortName] = duration; } } } for (auto& kvp : effectDurationByName) { bool isFading = (kvp.second <= GlobalConstants::TurnReadyValue && kvp.second != -1); std::string color = isFading ? Colors::ShadesOfGrey::Four : Colors::WhiteColor; Printer::Instance().PrintFB(offsetX, _th - 4, kvp.first, Printer::kAlignLeft, color); offsetX += 4; } } void MainState::PrintNoAttackInTown() { int index = RNG::Instance().RandomRange(0, 2); Printer::Instance().AddMessage(Strings::MsgNotInTown[index]); } void MainState::GetActorsAround() { _actorsForDebugDisplay.clear(); int lx = _playerRef->PosX - 1; int ly = _playerRef->PosY - 1; int hx = _playerRef->PosX + 1; int hy = _playerRef->PosY + 1; if (lx >= 0 && ly >= 0 && hx < Map::Instance().CurrentLevel->MapSize.X - 1 && hy < Map::Instance().CurrentLevel->MapSize.Y - 1) { for (int x = lx; x <= hx; x++) { for (int y = ly; y <= hy; y++) { for (auto& a : Map::Instance().CurrentLevel->ActorGameObjects) { if (a->PosX == x && a->PosY == y) { _actorsForDebugDisplay.push_back(a->ObjectId()); } } } } } } void MainState::DisplayScenarioInformation() { std::vector<std::string> messages; auto seedString = RNG::Instance().GetSeedString(); std::stringstream ss; ss << "Seed string: \"" << seedString.first << "\""; messages.push_back(ss.str()); ss.str(""); ss << "Seed value: " << seedString.second; messages.push_back(ss.str()); Application::Instance().ShowMessageBox(MessageBoxType::ANY_KEY, "Scenario Information", messages); }
26.308031
146
0.59116
xterminal86
acc80e24d55eaff214a28394fc1b5439f3009647
2,417
hpp
C++
src/game/level/tiled.hpp
lowkey42/MagnumOpus
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
5
2020-03-13T23:16:33.000Z
2022-03-20T19:16:46.000Z
src/game/level/tiled.hpp
lowkey42/MagnumOpus
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
24
2015-04-20T20:26:23.000Z
2015-11-20T22:39:38.000Z
src/game/level/tiled.hpp
lowkey42/medienprojekt
87897b16192323b40064119402c74e014a48caf3
[ "MIT" ]
1
2022-03-08T03:11:21.000Z
2022-03-08T03:11:21.000Z
/**************************************************************************\ * load & save JSON files from Tiled editor * * ___ * * /\/\ __ _ __ _ _ __ _ _ _ __ ___ /___\_ __ _ _ ___ * * / \ / _` |/ _` | '_ \| | | | '_ ` _ \ // // '_ \| | | / __| * * / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \ * * \/ \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/ * * |___/ |_| * * * * Copyright (c) 2014 Florian Oetke * * * * This file is part of MagnumOpus and distributed under the MIT License * * See LICENSE file for details. * \**************************************************************************/ #pragma once #include <vector> #include <string> #include <unordered_map> #include "../../core/utils/template_utils.hpp" #include "../../core/utils/string_utils.hpp" namespace mo { namespace level { struct TiledObject { int height; int width; int x; int y; int rotation; std::string name; std::string type; bool visible; std::unordered_map<std::string, std::string> properties; }; struct TiledLayer { std::vector<int> data; int height; int width; std::string name; int opacity; std::string type; bool visible; int x; int y; std::string draworder = "topdown"; std::vector<TiledObject> objects; }; struct TiledLevel { int height; int width; std::vector<TiledLayer> layers; std::unordered_map<std::string, std::string> properties; std::string orientation = "orthogonal"; std::string renderorder = "right-down"; int tileheight; int tilewidth; int version; TiledLayer& add_layer(std::string name, std::string type) { layers.emplace_back(); auto& l = layers.back(); l.height = height; l.width = width; l.x = 0; l.y = 0; l.visible = true; l.name = std::move(name); l.opacity = 1; l.type = std::move(type); return l; } }; extern TiledLevel parse_level(std::istream& s); extern void write_level(std::ostream& s, const TiledLevel& level); } }
26.855556
76
0.456765
lowkey42
acc80f97c25dec5002e4fe818cfc940e628f317e
10,729
cpp
C++
src/storage-client.cpp
corehacker/ch-storage-client
d5621b0d5e6f16b9c517d4d048a209dde8169b61
[ "MIT" ]
null
null
null
src/storage-client.cpp
corehacker/ch-storage-client
d5621b0d5e6f16b9c517d4d048a209dde8169b61
[ "MIT" ]
null
null
null
src/storage-client.cpp
corehacker/ch-storage-client
d5621b0d5e6f16b9c517d4d048a209dde8169b61
[ "MIT" ]
null
null
null
/******************************************************************************* * * BSD 2-Clause License * * Copyright (c) 2017, Sandeep Prakash * 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. ******************************************************************************/ /******************************************************************************* * Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com> * * \file storage-client.cpp * * \author Sandeep Prakash * * \date Nov 02, 2017 * * \brief * ******************************************************************************/ #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <string> #include <sys/types.h> #include <chrono> #include <cstdio> #include <dirent.h> #include <ch-cpp-utils/utils.hpp> #include <ch-cpp-utils/http/client/http.hpp> #include <glog/logging.h> #include "storage-client.hpp" using std::ifstream; using std::chrono::system_clock; using ChCppUtils::mkPath; using ChCppUtils::directoryListing; using ChCppUtils::fileExpired; using ChCppUtils::fileExists; using ChCppUtils::getEpochNano; using ChCppUtils::getDateTime; using ChCppUtils::replace; using ChCppUtils::Http::Client::HttpClientImpl; namespace SC { static int get_num_fds(void); static int get_num_fds() { int fd_count; char buf[64]; struct dirent *dp; DIR *dir = NULL; snprintf(buf, 64, "/proc/%i/fd/", getpid()); fd_count = 0; dir = opendir(buf); while ((dp = readdir(dir)) != NULL) { fd_count++; } closedir(dir); return fd_count; } UploadContext::UploadContext(StorageClient *client, HttpRequest *request) { this->client = client; this->request = request; } UploadContext::~UploadContext() { } StorageClient *UploadContext::getClient() { return client; } HttpRequest *UploadContext::getRequest() { return request; } StorageClient::StorageClient(Config *config) { mConfig = config; procStat = new ProcStat(); purge(true); for(auto watch : mConfig->getWatchDirs()) { FtsOptions options = {false}; options.bIgnoreRegularFiles = false; options.bIgnoreHiddenFiles = true; options.bIgnoreHiddenDirs = true; options.bIgnoreRegularDirs = true; options.filters = mConfig->getFilters(); Fts *fts = new Fts(watch.dir, &options); mFts.emplace_back(fts); FsWatch *fsWatch = new FsWatch(watch.dir); LOG(INFO) << "Adding watch: " << watch.dir << ": " << (watch.upload ? "true" : "false"); mFsWatch.emplace_back(fsWatch); mWatchDirMap.emplace(make_pair(watch.dir, watch.upload)); } uploadPrefix = "http://" + mConfig->getHostname() + ":" + std::to_string(mConfig->getPort()) + mConfig->getPrefix() + "/" + mConfig->getName(); mTimer = new Timer(); struct timeval tv = {0}; tv.tv_sec = mConfig->getPurgeIntervalSec(); mTimerEvent = mTimer->create(&tv, StorageClient::_onTimerEvent, this); } StorageClient::~StorageClient() { for(auto fts : mFts) { delete fts; } for(auto watch : mFsWatch) { delete watch; } mTimer->destroy(mTimerEvent); delete mTimer; } void StorageClient::_onFile(OnFileData &data, void *this_) { StorageClient *client = (StorageClient *) this_; client->onFile(data); } bool StorageClient::shouldUpload(OnFileData &data) { unordered_map<string, bool>::iterator it; bool upload = false; for ( it = mWatchDirMap.begin(); it != mWatchDirMap.end(); it++ ) { string dir = it->first; upload = it->second; if(strncmp(data.path.c_str(), dir.c_str(), dir.size()) == 0) { break; } } return upload; } void StorageClient::onFile(OnFileData &data) { LOG(INFO) << "onFile: " << data.name << ", " << data.path << ", " << data.ext; if(!shouldUpload(data)) { LOG(INFO) << "No upload needed based on config"; return; } LOG(INFO) << "Needs upload based on config"; if(data.ext == "ts") { std::ifstream segmentFile(data.path); if(!segmentFile.is_open()) { LOG(WARNING) << "Segment file open failed. File may not exist. " "Might be deleted on startup which got detected by " "fs watch: " << data.path; return; } LOG(INFO) << "Segment file exists. Will add it to the queue: " << data.path; uploadQueue.emplace_back(data); } else if(data.ext == "m3u8") { if(uploadQueue.size() == 0) { return; } std::vector<std::string> playlist; std::ifstream playlistFile(data.path); std::string line; while(std::getline(playlistFile, line)) { string filename = line.substr(line.find_last_of('/') + 1); LOG(INFO) << " + " << filename; playlist.push_back(filename); } OnFileData tsData = uploadQueue.at(0); LOG(INFO) << "Queue head: " << tsData.name; bool found = false; string inf; string targetDuration; for(uint32_t i = 0; i < playlist.size(); i++) { string filename = playlist[i]; if(filename.find("#EXT-X-TARGETDURATION") != string::npos) { targetDuration = filename.substr(filename.find_first_of(":") + 1); } if(filename == tsData.name) { found = true; inf = playlist[i - 1]; break; } } if(found) { uploadQueue.erase(uploadQueue.begin()); string infValue = inf.substr(inf.find_last_of(":") + 1); if(infValue.find_last_of(",") != string::npos) { infValue.erase(infValue.find_last_of(","), 1); } LOG(INFO) << "File found: " << tsData.name << ":" << infValue; upload(tsData, infValue, targetDuration); } } else { } } void StorageClient::_onLoad(HttpRequestLoadEvent *event, void *this_) { UploadContext *context = (UploadContext *) this_; StorageClient *client = context->getClient(); client->onLoad(event); HttpRequest *request = context->getRequest(); delete request; delete context; } void StorageClient::onLoad(HttpRequestLoadEvent *event) { LOG(INFO) << "Request Complete"; } void StorageClient::_onFilePurge (OnFileData &data, void *this_) { StorageClient *client = (StorageClient *) this_; client->onFilePurge(data); } void StorageClient::onFilePurge (OnFileData &data) { bool markForDelete = fileExpired(data.path, mConfig->getPurgeTtlSec()); if(markForDelete) { if(0 != std::remove(data.path.data())) { LOG(ERROR) << "File: " << data.path << ", marked for Delete! failed to delete"; perror("remove"); } else { LOG(INFO) << "File: " << data.path << ", marked for Delete! Deleted successfully"; } } } void StorageClient::_onFilePurgeForced (OnFileData &data, void *this_) { StorageClient *client = (StorageClient *) this_; client->onFilePurgeForced(data); } void StorageClient::onFilePurgeForced (OnFileData &data) { if(0 != std::remove(data.path.data())) { LOG(ERROR) << "File: " << data.path << ", marked for Delete! failed to delete"; perror("remove"); } else { LOG(INFO) << "File: " << data.path << ", marked for Delete! Deleted successfully"; } } void StorageClient::purge(bool force) { for(auto watchDir : mConfig->getWatchDirs()) { FtsOptions options; // LOG(INFO) << "Purging files in: " << watchDir; memset(&options, 0x00, sizeof(FtsOptions)); options.bIgnoreRegularFiles = false; options.bIgnoreHiddenFiles = true; options.bIgnoreHiddenDirs = true; options.bIgnoreRegularDirs = true; Fts fts(watchDir.dir, &options); if(!force) { fts.walk(StorageClient::_onFilePurge, this); } else { fts.walk(StorageClient::_onFilePurgeForced, this); } } } void StorageClient::_onTimerEvent(TimerEvent *event, void *this_) { StorageClient *server = (StorageClient *) this_; server->onTimerEvent(event); } void StorageClient::onTimerEvent(TimerEvent *event) { uint32_t rss = procStat->getRSS(); LOG(INFO) << "Number of open fd(s): " << get_num_fds(); LOG(INFO) << "RSS: " << rss / 1024 << " KB, Max RSS Configured: " << (mConfig->getMaxRss() / 1024) << " KB"; if(rss > mConfig->getMaxRss()) { LOG(ERROR) << "*********FATAL**********"; LOG(ERROR) << "Too much memory in use. Exiting process."; LOG(FATAL) << "*********FATAL**********"; exit(1); } purge(false); mTimer->restart(event); } void StorageClient::upload(OnFileData &data, string &infValue, string &targetDuration) { LOG(INFO) << "File to be uploaded: name: " << data.name << ", path: " << data.path; string targetName = getDateTime() + "-" + std::to_string(getEpochNano()) + "." + data.ext; std::replace(targetName.begin(), targetName.end(), ' ', '-'); std::replace(targetName.begin(), targetName.end(), ':', '-'); LOG(INFO) << "Will rename to: " << targetName; std::ifstream file(data.path, std::ios::binary | std::ios::ate); if(!file.is_open()) { LOG(WARNING) << "File open failed: " << data.path; return; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector<char> buffer(size); if (file.read(buffer.data(), size)) { LOG(INFO) << "File content read " << size << " bytes"; string url = uploadPrefix + "/" + targetName + "?extinf=" + infValue + "&targetduration=" + targetDuration; LOG(INFO) << "Target URL: " << url; HttpRequest *request = new HttpRequest(); UploadContext *context = new UploadContext(this, request); request->onLoad(StorageClient::_onLoad).bind(context); request->open(EVHTTP_REQ_POST, url).send(buffer.data(), buffer.size()); } } void StorageClient::start() { for(auto watch : mFsWatch) { watch->init(); watch->OnNewFileCbk(StorageClient::_onFile, this); watch->start(mConfig->getFilters()); } for(auto fts : mFts) { fts->walk(StorageClient::_onFile, this); } } } // End namespace SS.
28.919137
90
0.651412
corehacker
acc8a54f4767d35c69483b333b5d6c042883d19e
5,003
cpp
C++
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
2
2018-10-15T18:27:50.000Z
2019-04-16T18:34:59.000Z
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
null
null
null
test/CompilationTests/LambdaTests/MakePromise/RValue.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "gmock/gmock.h" #include "Promise.hpp" using namespace prm; /*** * * 1. make_promise function. * * We have types: * ExeT * ExeVoid * * ResolveT * ResolveVoid * ResolveUndefined * * RejectT * RejectVoid * RejectUndefined * * There are the following combinations availiable: * ExeT, ResolveT, RejectT * ExeT, ResolveT, RejectVoid * ExeT, ResolveT, RejectUndefined * * ExeT, ResolveVoid, RejectT * ExeT, ResolveVoid, RejectVoid * ExeT, ResolveVoid, RejectUndefined * * ExeT, ResolveUndefined, RejectT * ExeT, ResolveUndefined, RejectVoid * ExeT, ResolveUndefined, RejectUndefined <- Not supported * * ExeVoid, ResolveT, RejectT * ExeVoid, ResolveT, RejectVoid * ExeVoid, ResolveT, RejectUndefined * * ExeVoid, ResolveVoid, RejectT * ExeVoid, ResolveVoid, RejectVoid * ExeVoid, ResolveVoid, RejectUndefined * * ExeVoid, ResolveUndefined, RejectT * ExeVoid, ResolveUndefined, RejectVoid * ExeVoid, ResolveUndefined, RejectUndefined <- Not supported * ***/ class MakePromiseLambdaRValue: public ::testing::TestWithParam<bool> { }; INSTANTIATE_TEST_CASE_P( TestWithParameters, MakePromiseLambdaRValue, testing::Values( false, true )); // ExeT, ResolveT, RejectT TEST_P(MakePromiseLambdaRValue, ExeResolveReject) { make_promise([this](int e, Resolver<char> resolve, Rejector<double> reject) { ASSERT_TRUE(10 == e); return GetParam() ? resolve('w') : reject(5.3); }) .startExecution(10); } // ExeT, ResolveT, RejectVoid TEST_P(MakePromiseLambdaRValue, ExeResolveRejectVoid) { make_promise([this](int e, Resolver<char> resolve, Rejector<void> reject) { ASSERT_TRUE(10 == e); return GetParam() ? resolve('w') : reject(); }) .startExecution(10); } // ExeT, ResolveT, RejectUndefined TEST(MakePromiseLambdaRValue, ExeResolve) { make_promise([](int e, Resolver<char> resolve) { ASSERT_TRUE(10 == e); return resolve('w'); }) .startExecution(10); } // ExeT, ResolveVoid, RejectT TEST_P(MakePromiseLambdaRValue, ExeResolveVoidReject) { make_promise([this](int e, Resolver<void> resolve, Rejector<double> reject) { ASSERT_TRUE(10 == e); return GetParam() ? resolve() : reject(5.3); }) .startExecution(10); } // ExeT, ResolveVoid, RejectVoid TEST_P(MakePromiseLambdaRValue, ExeResolveVoidRejectVoid) { make_promise([this](int e, Resolver<void> resolve, Rejector<void> reject) { ASSERT_TRUE(10 == e); return GetParam() ? resolve() : reject(); }) .startExecution(10); } // ExeT, ResolveVoid, RejectUndefined TEST(MakePromiseLambdaRValue, ExeResolveVoid) { make_promise([](int e, Resolver<void> resolve) { ASSERT_TRUE(10 == e); return resolve(); }) .startExecution(10); } // ExeT, ResolveUndefined, RejectT TEST(MakePromiseLambdaRValue, ExeReject) { make_promise([](int e, Rejector<double> reject) { ASSERT_TRUE(10 == e); return reject(5.3); }) .startExecution(10); } // ExeT, ResolveUndefined, RejectVoid TEST(MakePromiseLambdaRValue, ExeRejectVoid) { make_promise([](int e, Rejector<void> reject) { ASSERT_TRUE(10 == e); return reject(); }) .startExecution(10); } // ExeVoid, ResolveT, RejectT TEST_P(MakePromiseLambdaRValue, ResolveReject) { make_promise([this](Resolver<char> resolve, Rejector<double> reject) { return GetParam() ? resolve('w') : reject(5.3); }) .startExecution(); } // ExeVoid, ResolveT, RejectVoid TEST_P(MakePromiseLambdaRValue, ResolveRejectVoid) { make_promise([this](Resolver<char> resolve, Rejector<void> reject) { return GetParam() ? resolve('w') : reject(); }) .startExecution(); } // ExeVoid, ResolveT, RejectUndefined TEST(MakePromiseLambdaRValue, Resolve) { make_promise([](Resolver<char> resolve) { return resolve('w'); }) .startExecution(); } // ExeVoid, ResolveVoid, RejectT TEST_P(MakePromiseLambdaRValue, ResolvVoideReject) { make_promise([this](Resolver<void> resolve, Rejector<double> reject) { return GetParam() ? resolve() : reject(5.3); }) .startExecution(); } // ExeVoid, ResolveVoid, RejectVoid TEST_P(MakePromiseLambdaRValue, ResolvVoideRejectVoid) { make_promise([this](Resolver<void> resolve, Rejector<void> reject) { return GetParam() ? resolve() : reject(); }) .startExecution(); } // ExeVoid, ResolveVoid, RejectUndefined TEST(MakePromiseLambdaRValue, ResolvVoide) { make_promise([](Resolver<void> resolve) { return resolve(); }) .startExecution(); } // ExeVoid, ResolveUndefined, RejectT TEST(MakePromiseLambdaRValue, Reject) { make_promise([](Rejector<double> reject) { return reject(5.3); }) .startExecution(); } // ExeVoid, ResolveUndefined, RejectVoid TEST(MakePromiseLambdaRValue, RejectVoid) { make_promise([](Rejector<void> reject) { return reject(); }) .startExecution(); }
23.82381
81
0.678193
rocky01
accadd5dba17414263f9529f7f8f55df3cdbe57a
1,445
cc
C++
src/envoy/http/grpc_metadata_scrubber/filter.cc
CorrelatedLabs/esp-v2
9fa93040d70f98087b3586a88a0764b9f5ec544c
[ "Apache-2.0" ]
163
2019-12-18T18:40:50.000Z
2022-03-17T03:34:22.000Z
src/envoy/http/grpc_metadata_scrubber/filter.cc
CorrelatedLabs/esp-v2
9fa93040d70f98087b3586a88a0764b9f5ec544c
[ "Apache-2.0" ]
669
2019-12-19T00:36:12.000Z
2022-03-30T20:27:52.000Z
src/envoy/http/grpc_metadata_scrubber/filter.cc
CorrelatedLabs/esp-v2
9fa93040d70f98087b3586a88a0764b9f5ec544c
[ "Apache-2.0" ]
177
2019-12-19T00:35:51.000Z
2022-03-24T10:22:23.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/envoy/http/grpc_metadata_scrubber/filter.h" #include <string> #include "source/common/grpc/common.h" #include "source/common/http/headers.h" namespace espv2 { namespace envoy { namespace http_filters { namespace grpc_metadata_scrubber { Envoy::Http::FilterHeadersStatus Filter::encodeHeaders( Envoy::Http::ResponseHeaderMap& headers, bool) { ENVOY_LOG(debug, "Filter::encodeHeaders is called."); config_->stats().all_.inc(); if (Envoy::Grpc::Common::hasGrpcContentType(headers) && headers.ContentLength() != nullptr) { ENVOY_LOG(debug, "Content-length header is removed"); headers.removeContentLength(); config_->stats().removed_.inc(); } return Envoy::Http::FilterHeadersStatus::Continue; } } // namespace grpc_metadata_scrubber } // namespace http_filters } // namespace envoy } // namespace espv2
31.413043
75
0.737716
CorrelatedLabs
accec0a52732000b9e66a70a4aa93cc464cdfbe8
463
cpp
C++
server/src/notifier/detail/system.cpp
chyla/slas
c0c222e55571a7f8b2cb0b68b3e4900dbff9a986
[ "MIT" ]
1
2016-03-03T13:04:57.000Z
2016-03-03T13:04:57.000Z
server/src/notifier/detail/system.cpp
chyla/slas
c0c222e55571a7f8b2cb0b68b3e4900dbff9a986
[ "MIT" ]
null
null
null
server/src/notifier/detail/system.cpp
chyla/slas
c0c222e55571a7f8b2cb0b68b3e4900dbff9a986
[ "MIT" ]
null
null
null
/* * Copyright 2016 Adam Chyła, adam@chyla.org * All rights reserved. Distributed under the terms of the MIT License. */ #include "system.h" #include <unistd.h> namespace notifier { namespace detail { SystemPtr System::Create() { return std::make_shared<System>(); } void System::Sleep(unsigned seconds) { sleep(seconds); } time_t System::Time() { return time(nullptr); } tm* System::GMTime(const time_t *timep) { return gmtime(timep); } } }
13.228571
71
0.688985
chyla
acd61f4db9e2ad2931692a24e7686ac496b734a9
969
hpp
C++
include/mcnla/isvd/integrator.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
include/mcnla/isvd/integrator.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
include/mcnla/isvd/integrator.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @file include/mcnla/isvd/integrator.hpp /// @brief The iSVD integrator header. /// /// @author Mu Yang <<emfomy@gmail.com>> /// #ifndef MCNLA_ISVD_INTEGRATOR_HPP_ #define MCNLA_ISVD_INTEGRATOR_HPP_ // Kolmogorov-Nagumo-type #include <mcnla/isvd/integrator/kolmogorov_nagumo_integrator.hpp> #include <mcnla/isvd/integrator/row_block_kolmogorov_nagumo_integrator.hpp> #include <mcnla/isvd/integrator/row_block_gramian_kolmogorov_nagumo_integrator.hpp> // Wen-Yin line search #include <mcnla/isvd/integrator/row_block_wen_yin_integrator.hpp> #include <mcnla/isvd/integrator/row_block_gramian_wen_yin_integrator.hpp> // Reduce-sum #include <mcnla/isvd/integrator/row_block_reduction_integrator.hpp> // Extrinsic mean #include <mcnla/isvd/integrator/row_block_extrinsic_mean_integrator.hpp> #endif // MCNLA_ISVD_INTEGRATOR_HPP_
35.888889
128
0.705882
emfomy
acd7fdd67d541eb39a0a53e46e832dbc059fe020
3,109
hpp
C++
include/landscapes/svo_tree.sanity.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
32
2015-12-29T04:33:08.000Z
2021-04-08T01:46:44.000Z
include/landscapes/svo_tree.sanity.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
null
null
null
include/landscapes/svo_tree.sanity.hpp
realazthat/landscapes
0d56d67beb5641b913100d86601fce8a5a63fb1c
[ "MIT", "WTFPL", "Unlicense", "0BSD" ]
2
2019-04-05T02:28:02.000Z
2019-06-11T07:59:53.000Z
#ifndef SVO_TREE_SANITY_HPP #define SVO_TREE_SANITY_HPP 1 #include "svo_tree.fwd.hpp" #include <iosfwd> #include <string> namespace svo{ // See https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values ::std::ostream& operator<<(::std::ostream& out, const svo::svo_block_sanity_error_t& error); // See https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values ::std::ostream& operator<<(::std::ostream& out, const svo::svo_slice_sanity_error_t& error); struct svo_slice_sanity_error_t { svo_slice_sanity_error_t() : has_error(false) , slice0(0), slice1(0), slice2(0) {} svo_slice_sanity_error_t(const std::string& error, const svo_slice_t* slice0=0, const svo_slice_t* slice1=0, const svo_slice_t* slice2=0) : has_error(true) , error(error) , slice0(slice0) , slice1(slice1) , slice2(slice2) {} operator bool() const { return has_error; } bool has_error; std::string error; const svo_slice_t* slice0; const svo_slice_t* slice1; const svo_slice_t* slice2; }; struct svo_block_sanity_error_t { svo_block_sanity_error_t() : has_error(false) , block0(0), block1(0), block2(0) {} svo_block_sanity_error_t(const std::string& error, const svo_block_t* block0=0, const svo_block_t* block1=0, const svo_block_t* block2=0) : has_error(true) , error(error) , block0(block0) , block1(block1) , block2(block2) {} operator bool() const { return has_error; } bool has_error; std::string error; const svo_block_t* block0; const svo_block_t* block1; const svo_block_t* block2; }; enum svo_sanity_type_t{ none = 0 , minimal = 1 << 1 , levels = 1 << 2 , pos_data = 1 << 3 , channel_data = 1 << 4 , children = 1 << 5 , parent = 1 << 6 , all_data = pos_data | channel_data , all = minimal | levels | pos_data | channel_data | children | parent , default_sanity = all }; svo_slice_sanity_error_t svo_slice_sanity( const svo_slice_t* slice , svo_sanity_type_t sanity_type = svo_sanity_type_t::default_sanity , int recurse = 1 , bool parent_recurse = true); //svo_slice_sanity_error_t svo_slice_sanity_check_error(const svo_slice_t* slice, int recurse=0); //svo_slice_sanity_error_t svo_slice_sanity_check_parent_error(const svo_slice_t* slice, int recurse=0); //svo_slice_sanity_error_t svo_slice_sanity_check_children_error(const svo_slice_t* slice, int recurse=0); //svo_slice_sanity_error_t svo_slice_pos_data_sanity_check(const svo_slice_t* slice); //svo_slice_sanity_error_t svo_slice_channels_sanity_check(const svo_slice_t* slice); //svo_slice_sanity_error_t svo_slice_all_sanity_check(const svo_slice_t* slice); svo_block_sanity_error_t svo_block_sanity_check(const svo_block_t* block, int recurse=0); } //namespace svo #endif
29.609524
141
0.693149
realazthat
acdb388131cb6a63f8247b8982f33554a75e71df
449
hpp
C++
library/ATF/CCheckSumGuildConverter.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CCheckSumGuildConverter.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CCheckSumGuildConverter.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CCheckSumBaseConverter.hpp> #include <CCheckSumGuildData.hpp> START_ATF_NAMESPACE struct CCheckSumGuildConverter : CCheckSumBaseConverter { public: void Convert(long double dDalant, long double dGold, struct CCheckSumGuildData* pkCheckSum); }; END_ATF_NAMESPACE
28.0625
108
0.768374
lemkova
acdf191c7bcfb35a6ab7f1fd2e1f2abea29d6b4d
2,147
cpp
C++
src/operators/opLess.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
4
2018-08-31T09:44:52.000Z
2021-03-01T19:10:00.000Z
src/operators/opLess.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
21
2019-12-29T08:33:34.000Z
2020-11-22T16:38:37.000Z
src/operators/opLess.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
null
null
null
#include "operators/opLess.h" #include "operators/simpleOperator.hpp" using namespace std; void OpLess::reevaluateImpl(IntView& leftView, IntView& rightView, bool, bool) { Int diff = (rightView.value - 1) - leftView.value; violation = abs(min<Int>(diff, 0)); } void OpLess::updateVarViolationsImpl(const ViolationContext&, ViolationContainer& vioContainer) { if (violation == 0) { return; } else if (allOperandsAreDefined()) { left->updateVarViolations( IntViolationContext(violation, IntViolationContext::Reason::TOO_LARGE), vioContainer); right->updateVarViolations( IntViolationContext(violation, IntViolationContext::Reason::TOO_SMALL), vioContainer); } else { left->updateVarViolations(violation, vioContainer); right->updateVarViolations(violation, vioContainer); } } void OpLess::copy(OpLess&) const {} ostream& OpLess::dumpState(ostream& os) const { os << "OpLess: violation=" << violation << "\nleft: "; left->dumpState(os); os << "\nright: "; right->dumpState(os); return os; } string OpLess::getOpName() const { return "OpLess"; } void OpLess::debugSanityCheckImpl() const { left->debugSanityCheck(); right->debugSanityCheck(); auto leftOption = left->getViewIfDefined(); auto rightOption = right->getViewIfDefined(); if (!leftOption || !rightOption) { sanityLargeViolationCheck(violation); return; } auto& leftView = *leftOption; auto& rightView = *rightOption; Int diff = (rightView.value - 1) - leftView.value; UInt checkViolation = abs(min<Int>(diff, 0)); sanityEqualsCheck(checkViolation, violation); } template <typename Op> struct OpMaker; template <> struct OpMaker<OpLess> { static ExprRef<BoolView> make(ExprRef<IntView> l, ExprRef<IntView> r); }; ExprRef<BoolView> OpMaker<OpLess>::make(ExprRef<IntView> l, ExprRef<IntView> r) { return make_shared<OpLess>(move(l), move(r)); }
32.044776
80
0.63251
athanor
ace3f5b4bcba607dd8c0c08bbfa5d5dbc03dd891
2,711
hpp
C++
filelib/include/ini/INI_Tokenizer.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
1
2021-12-09T20:01:21.000Z
2021-12-09T20:01:21.000Z
filelib/include/ini/INI_Tokenizer.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
null
null
null
filelib/include/ini/INI_Tokenizer.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
null
null
null
#pragma once #include <TokenReduxDefaultDefs.hpp> namespace file::ini::tokenizer { using namespace token::DefaultDefs; /** * @struct INITokenizer * @brief Tokenizes the contents of an INI config file. */ struct INITokenizer : token::base::TokenizerBase<LEXEME, LexemeDict, ::token::DefaultDefs::TokenType, Token> { INITokenizer(std::stringstream&& buffer) : TokenizerBase(std::move(buffer), LEXEME::WHITESPACE, LEXEME::_EOF) {} protected: TokenT getNext() override { const auto ch{ getch() }; switch (get_lexeme(ch)) { case LEXEME::POUND: [[fallthrough]]; case LEXEME::SEMICOLON:// Comment return Token{ std::string(1ull, ch) += getline('\n', false), TokenType::COMMENT }; case LEXEME::EQUALS: // Setter Start return Token{ ch, TokenType::SETTER }; case LEXEME::QUOTE_SINGLE: // String (single) start return Token{ getline('\''), TokenType::STRING }; case LEXEME::QUOTE_DOUBLE: // String (double) start return Token{ getline('\"'), TokenType::STRING }; case LEXEME::SQUAREBRACKET_OPEN: return Token{ getline(']'), TokenType::HEADER }; case LEXEME::LETTER_LOWERCASE: [[fallthrough]]; // if text appears without an enclosing quote, parse it as a key case LEXEME::LETTER_UPPERCASE: { // the case of unenclosed string variables is handled by the parser, not the tokenizer const auto pos{ rollback() }; std::string str; if (const auto lc{ str::tolower(ch) }; lc == 't' && getline_and_match(4u, "true", str)) return{ str, TokenType::BOOLEAN }; else if (lc == 'f' && getline_and_match(5u, "false", str)) return{ str, TokenType::BOOLEAN }; else ss.seekg(pos - 1ll); // getnotsimilar to newlines, equals, pound/semicolon '#'/';' (comments), and EOF return Token{ str::strip_line(getnotsimilar(LEXEME::NEWLINE, LEXEME::EQUALS, LEXEME::POUND, LEXEME::SEMICOLON, LEXEME::_EOF), "#;"), TokenType::KEY }; } case LEXEME::SUBTRACT: [[fallthrough]]; // number start case LEXEME::DIGIT: { rollback(); const auto str{ getsimilar(LEXEME::SUBTRACT, LEXEME::DIGIT, LEXEME::PERIOD) }; return (str::pos_valid(str.find('.') || !str.empty() && (str.back() == 'f' || str.back() == 'F')) ? Token{ str, TokenType::NUMBER } : Token{ str, TokenType::NUMBER_INT }); } case LEXEME::NEWLINE: return Token{ ch, TokenType::NEWLINE }; case LEXEME::WHITESPACE: throw make_exception("TokenizerINI::getNext()\tReceived unexpected whitespace character as input!"); case LEXEME::ESCAPE: return Token{ std::string(1u, ch) += getch(true), TokenType::ESCAPED }; case LEXEME::_EOF: return Token{ TokenType::END }; default: return Token{ ch, TokenType::NULL_TYPE }; } } }; }
41.707692
175
0.665806
radj307
ace4859641d2c085e8fd73a2fa2df95442aa6b3c
1,496
cpp
C++
asps/modbus/pdu/message/message_service.cpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/message/message_service.cpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/message/message_service.cpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The asps Authors. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Modbus PDU Message Service. #include <asps/modbus/pdu/message/message_service.hpp> #include <asps/modbus/pdu/message/client_message.hpp> namespace asps { namespace modbus { namespace pdu { message_serialization_service::pointer_type make_client_read_coils_request(uint16_t starting_address, uint16_t quantity_of_coils) { return std::make_shared<client_read_coils_request>(starting_address, quantity_of_coils); } message_unserialization_service::pointer_type make_client_read_coils_response() { return std::make_shared<client_exception>( std::make_shared<client_read_coils_response>()); } message_serialization_service::pointer_type make_client_read_discrete_inputs_request(uint16_t starting_address, uint16_t quantity_of_inputs) { return std::make_shared<client_read_discrete_inputs_request>(starting_address, quantity_of_inputs); } message_unserialization_service::pointer_type make_client_read_discrete_inputs_response() { return std::make_shared<client_exception>( std::make_shared<client_read_discrete_inputs_response>()); } } // pdu } // modbus } // asps
31.829787
83
0.707888
activesys
ace55a95143f50865e1aed308f8888bebc014257
1,577
hpp
C++
include/helpFunctions.hpp
ekildishev/lab-01-parser
03b9bf4480ceb2285f2650249f4edeb30ae469ef
[ "MIT" ]
2
2019-12-07T11:53:40.000Z
2020-09-28T17:47:20.000Z
include/helpFunctions.hpp
ekildishev/lab-01-parser
03b9bf4480ceb2285f2650249f4edeb30ae469ef
[ "MIT" ]
null
null
null
include/helpFunctions.hpp
ekildishev/lab-01-parser
03b9bf4480ceb2285f2650249f4edeb30ae469ef
[ "MIT" ]
null
null
null
// Copyright 2018 Your Name <your_email> #pragma once #include <iostream> #include <sstream> bool isSpace(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } int findEnd(const std::string &s, int start, char openSym, char closeSym) { unsigned int i = 0; unsigned int openC = 1; unsigned int closeC = 0; for (unsigned int j = start + 1; j < s.length(); ++j) { char symbol = s[j]; if (symbol == openSym) { openC++; } else if (symbol == closeSym) { closeC++; } if (openC == closeC) { i = j; break; } } return i + 1; } unsigned int missSpaces(const std::string &s, unsigned int current) { while (current < s.length() && isSpace(s[current])) { ++current; } return current; } std::string getString(const std::string &s, unsigned int start) { unsigned int end = start + 1; while (end < s.length() && s[end] != '\"') { ++end; } if (end >= s.length()) { throw std::exception(); } return s.substr(start + 1, end - start - 1); } bool isNum(char c) { return ((c > '0') && (c < '9')) || (c == '.'); } std::pair<double, unsigned int> getNumAndLen(const std::string &s, unsigned int start) { double result; unsigned int cur = start; while (cur < s.length() && isNum(s[cur])) { ++cur; } if (cur == s.length()) { throw std::exception(); } std::stringstream ss; std::string str = s.substr(start, cur - start); ss << str; ss >> result; return std::pair<double, unsigned int>(result, cur - start); }
23.191176
75
0.54851
ekildishev
ace7200352adb1e3e4c032c952d31007c6ad6491
4,610
hpp
C++
tests/widgets/ExampleColorWidget.hpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
372
2015-02-09T15:05:16.000Z
2022-03-30T15:35:17.000Z
tests/widgets/ExampleColorWidget.hpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
324
2015-10-05T14:30:41.000Z
2022-03-30T07:06:04.000Z
tests/widgets/ExampleColorWidget.hpp
noisecode3/DPF
86a621bfd86922a49ce593fec2a618a1e0cc6ef3
[ "0BSD" ]
89
2015-02-20T11:26:50.000Z
2022-02-11T00:07:27.000Z
/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef EXAMPLE_COLOR_WIDGET_HPP_INCLUDED #define EXAMPLE_COLOR_WIDGET_HPP_INCLUDED // ------------------------------------------------------ // DGL Stuff #include "../../dgl/Color.hpp" #include "../../dgl/StandaloneWindow.hpp" #include "../../dgl/SubWidget.hpp" START_NAMESPACE_DGL // ------------------------------------------------------ // our widget template <class BaseWidget> class ExampleColorWidget : public BaseWidget, public IdleCallback { char cur; bool reverse; int r, g, b; Rectangle<uint> bgFull, bgSmall; public: static constexpr const char* kExampleWidgetName = "Color"; // SubWidget explicit ExampleColorWidget(Widget* const parent); // TopLevelWidget explicit ExampleColorWidget(Window& windowToMapTo); // StandaloneWindow explicit ExampleColorWidget(Application& app); protected: void idleCallback() noexcept override { switch (cur) { case 'r': if (reverse) { if (--r == 0) cur = 'g'; } else { if (++r == 100) cur = 'g'; } break; case 'g': if (reverse) { if (--g == 0) cur = 'b'; } else { if (++g == 100) cur = 'b'; } break; case 'b': if (reverse) { if (--b == 0) { cur = 'r'; reverse = false; } } else { if (++b == 100) { cur = 'r'; reverse = true; } } break; } BaseWidget::repaint(); } void onDisplay() override { const GraphicsContext& context(BaseWidget::getGraphicsContext()); // paint bg color (in full size) Color(r, g, b).setFor(context); bgFull.draw(context); // paint inverted color (in 2/3 size) Color(100-r, 100-g, 100-b).setFor(context); bgSmall.draw(context); } void onResize(const Widget::ResizeEvent& ev) override { const uint width = ev.size.getWidth(); const uint height = ev.size.getHeight(); // full bg bgFull = Rectangle<uint>(0, 0, width, height); // small bg, centered 2/3 size bgSmall = Rectangle<uint>(width/6, height/6, width*2/3, height*2/3); } }; // SubWidget template<> inline ExampleColorWidget<SubWidget>::ExampleColorWidget(Widget* const parent) : SubWidget(parent), cur('r'), reverse(false), r(0), g(0), b(0) { setSize(300, 300); parent->getApp().addIdleCallback(this); } // TopLevelWidget template<> inline ExampleColorWidget<TopLevelWidget>::ExampleColorWidget(Window& windowToMapTo) : TopLevelWidget(windowToMapTo), cur('r'), reverse(false), r(0), g(0), b(0) { setSize(300, 300); addIdleCallback(this); } // StandaloneWindow template<> inline ExampleColorWidget<StandaloneWindow>::ExampleColorWidget(Application& app) : StandaloneWindow(app), cur('r'), reverse(false), r(0), g(0), b(0) { setSize(300, 300); addIdleCallback(this); done(); } typedef ExampleColorWidget<SubWidget> ExampleColorSubWidget; typedef ExampleColorWidget<TopLevelWidget> ExampleColorTopLevelWidget; typedef ExampleColorWidget<StandaloneWindow> ExampleColorStandaloneWindow; // ------------------------------------------------------ END_NAMESPACE_DGL #endif // EXAMPLE_COLOR_WIDGET_HPP_INCLUDED
25.611111
90
0.556182
noisecode3
ace8a8b566adb1abdc0bdcfa117a4830d77098a6
4,096
cc
C++
src/developer/feedback/bugreport/bug_reporter.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
src/developer/feedback/bugreport/bug_reporter.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
src/developer/feedback/bugreport/bug_reporter.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "src/developer/feedback/bugreport/bug_reporter.h" #include <fuchsia/feedback/cpp/fidl.h> #include <lib/fsl/vmo/strings.h> #include <stdio.h> #include <zircon/errors.h> #include <zircon/status.h> #include <vector> #include "src/developer/feedback/bugreport/bug_report_schema.h" #include "third_party/rapidjson/include/rapidjson/document.h" #include "third_party/rapidjson/include/rapidjson/filewritestream.h" #include "third_party/rapidjson/include/rapidjson/prettywriter.h" namespace fuchsia { namespace bugreport { namespace { void AddAnnotations(const std::vector<fuchsia::feedback::Annotation>& annotations, rapidjson::Document* document) { rapidjson::Value json_annotations(rapidjson::kObjectType); for (const auto& annotation : annotations) { json_annotations.AddMember(rapidjson::StringRef(annotation.key), annotation.value, document->GetAllocator()); } document->AddMember("annotations", json_annotations, document->GetAllocator()); } void AddAttachments(const std::vector<fuchsia::feedback::Attachment>& attachments, const std::set<std::string>& attachment_allowlist, rapidjson::Document* document) { rapidjson::Value json_attachments(rapidjson::kObjectType); for (const auto& attachment : attachments) { if (!attachment_allowlist.empty() && attachment_allowlist.find(attachment.key) == attachment_allowlist.end()) { continue; } std::string value; if (!fsl::StringFromVmo(attachment.value, &value)) { fprintf(stderr, "Failed to parse attachment VMO as string for key %s\n", attachment.key.c_str()); continue; } json_attachments.AddMember(rapidjson::StringRef(attachment.key), value, document->GetAllocator()); } document->AddMember("attachments", json_attachments, document->GetAllocator()); } bool MakeAndWriteJson(const fuchsia::feedback::Data& feedback_data, const std::set<std::string>& attachment_allowlist, FILE* out_file) { rapidjson::Document document; document.SetObject(); AddAnnotations(feedback_data.annotations(), &document); AddAttachments(feedback_data.attachments(), attachment_allowlist, &document); char buffer[65536]; rapidjson::FileWriteStream output_stream(out_file, buffer, sizeof(buffer)); rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(output_stream); document.Accept(writer); if (!writer.IsComplete()) { fprintf(stderr, "Failed to write JSON\n"); return false; } return true; } } // namespace bool MakeBugReport(std::shared_ptr<::sys::ServiceDirectory> services, const std::set<std::string>& attachment_allowlist, const char* out_filename) { fuchsia::feedback::DataProviderSyncPtr feedback_data_provider; services->Connect(feedback_data_provider.NewRequest()); fuchsia::feedback::DataProvider_GetData_Result result; const zx_status_t get_data_status = feedback_data_provider->GetData(&result); if (get_data_status != ZX_OK) { fprintf(stderr, "Failed to get data from fuchsia.feedback.DataProvider: %d (%s)\n", get_data_status, zx_status_get_string(get_data_status)); return false; } if (result.is_err()) { fprintf(stderr, "fuchsia.feedback.DataProvider failed to get data: %d (%s) ", result.err(), zx_status_get_string(result.err())); return false; } if (out_filename) { FILE* out_file = fopen(out_filename, "w"); if (!out_file) { fprintf(stderr, "Failed to open output file %s\n", out_filename); return false; } const bool success = MakeAndWriteJson(result.response().data, attachment_allowlist, out_file); fclose(out_file); return success; } else { return MakeAndWriteJson(result.response().data, attachment_allowlist, stdout); } } } // namespace bugreport } // namespace fuchsia
36.900901
100
0.708984
OpenTrustGroup
aceddcdbb1d88f3707b4016d24a72046131048aa
2,754
cpp
C++
src/camino_minimo/camino_minimo.cpp
mmaximiliano/algo3-project2
bad8f7704f8d004c1e21ba684e98890578bf8ccc
[ "MIT" ]
null
null
null
src/camino_minimo/camino_minimo.cpp
mmaximiliano/algo3-project2
bad8f7704f8d004c1e21ba684e98890578bf8ccc
[ "MIT" ]
null
null
null
src/camino_minimo/camino_minimo.cpp
mmaximiliano/algo3-project2
bad8f7704f8d004c1e21ba684e98890578bf8ccc
[ "MIT" ]
null
null
null
#include "bellman_ford.h" #include "dijkstra.h" #include "dijkstra_cp.h" #include "floyd_warshall.h" #include "estructuras.h" #include "funciones_auxiliares.h" #include <chrono> int infinito = 10000000; int main(){ grafo_ad G = crear_grafo_modificado(); vector<vector<int> > distancias; string metodo; auto start = std::chrono::steady_clock::now(); auto end = std::chrono::steady_clock::now(); long long total = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); cout << "Recordar poner método de resoulción al final del archivo: d: dijkstra, dp: dijkstra cola prioridad, bf: ford, fw: floyd" << endl; cin >> metodo; if(metodo == "d"){ start = std::chrono::steady_clock::now(); //llamar dijkstra n veces for(int i = 0; i < G.cant_nodos; i+=61){ vector<int> aux = dijkstra(G, i); vector<int> aux2; for(int j = 0; j < aux.size(); j+=61){ aux2.push_back(aux[j]); } distancias.push_back(aux2); } end = std::chrono::steady_clock::now(); total = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); cout<<total<<'\n'; imprimir_resultado(distancias); }else if (metodo == "dp"){ start = std::chrono::steady_clock::now(); //llamar dijkstra_cp n veces for(int i = 0; i < G.cant_nodos; i+=61){ vector<int> aux = dijkstra_cp(G, i); vector<int> aux2; for(int j = 0; j < aux.size(); j+=61){ aux2.push_back(aux[j]); } distancias.push_back(aux2); } end = std::chrono::steady_clock::now(); total = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); cout<<total<<'\n'; imprimir_resultado(distancias); }else if(metodo == "bf"){ start = std::chrono::steady_clock::now(); //llamar bf n veces for(int i = 0; i < G.cant_nodos; i+=61){ vector<int> aux = bellman_ford(G, i); vector<int> aux2; for(int j = 0; j < aux.size(); j+=61){ aux2.push_back(aux[j]); } distancias.push_back(aux2); } end = std::chrono::steady_clock::now(); total = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); cout<<total<<'\n'; imprimir_resultado(distancias); }else if(metodo == "fw"){ start = std::chrono::steady_clock::now(); //llamar a floyd warshall distancias = floyd_warshall(G); end = std::chrono::steady_clock::now(); total = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); cout<<total<<'\n'; imprimir_resultado_floyd(distancias); }else{ cout << "no se ingresó un método válido" << endl; return 1; } return 0; }
34
141
0.60167
mmaximiliano
acef454a33829800d8af20ea3d9e6a04a72644ae
94
cc
C++
cc/Neat/Bit/Sequence.cc
ma16/rpio
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
[ "BSD-2-Clause" ]
1
2020-06-07T14:50:44.000Z
2020-06-07T14:50:44.000Z
cc/Neat/Bit/Sequence.cc
ma16/rpio
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
[ "BSD-2-Clause" ]
null
null
null
cc/Neat/Bit/Sequence.cc
ma16/rpio
2e9e5f6794ebe8d60d62e0c65a14edd80f0194ec
[ "BSD-2-Clause" ]
null
null
null
// BSD 2-Clause License, see github.com/ma16/rpio #include "Sequence.h" // empty on purpose
15.666667
49
0.712766
ma16
acf00657c2eb69b30ad27537a0df822180e114ed
1,516
hpp
C++
Phoenix3D/PX2Simulation/SkillCompl/PX2SkillActorLink.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/PX2Simulation/SkillCompl/PX2SkillActorLink.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/PX2Simulation/SkillCompl/PX2SkillActorLink.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2SkillActorLink.hpp #ifndef PX2SKILLACTORLINK_HPP #define PX2SKILLACTORLINK_HPP #include "PX2Actor.hpp" #include "PX2BeamEmitter.hpp" namespace PX2 { class SkillActorLink : public Actor { PX2_DECLARE_RTTI; PX2_DECLARE_NAMES; PX2_DECLARE_STREAM(SkillActorLink); public: SkillActorLink(); virtual ~SkillActorLink(); virtual void Update(double appSeconds); enum TargetType { TT_ACTOR, TT_POSITION, TT_MAX_TYPE }; void SetTargetType(TargetType type); TargetType GetTargetType() const; void SetFromActorID(int ID); int GetFromActorID() const; void SetFromActorAnchorID(int anchorID); int GetFromActorAnchorID() const; void SetToActorID(int ID); int GetToActorID() const; void SetToActorAnchorID(int anchorID); int GetToActorAnchorID() const; void SetToPosition(const APoint &pos); const APoint &GetToPosition() const; void SetLinkSpeed(float speed); float GetLinkSpeed() const; void Start(); virtual void OnStart(); bool IsLinked() const; void SetOver(bool over); bool IsOver() const; protected: TargetType mTargetType; int mFromActorID; int mFormAnchorID; int mToActorID; int mToAnchorID; APoint mToPos; float mLinkSpeed; BeamEmitterPtr mLinkBeam; float mLinkToNeedTime; APoint mLastPos; float mCurRunTime; InterpCurveFloat3 mCurve; bool mIsLinked; bool mIsOver; }; PX2_REGISTER_STREAM(SkillActorLink); typedef Pointer0<SkillActorLink> SkillActorLinkPtr; #include "PX2SkillActorLink.inl" } #endif
18.716049
52
0.751979
PheonixFoundation
acf2ccbda43fc2317dd3b4cb2642161227aafc8f
1,955
hpp
C++
src/lib/lossy_cast.hpp
dey4ss/hyrise
c304b9ced36044e303eb8a4d68a05fc7edc04819
[ "MIT" ]
1
2019-12-30T13:23:30.000Z
2019-12-30T13:23:30.000Z
src/lib/lossy_cast.hpp
dey4ss/hyrise
c304b9ced36044e303eb8a4d68a05fc7edc04819
[ "MIT" ]
11
2019-12-02T20:47:52.000Z
2020-02-04T23:19:31.000Z
src/lib/lossy_cast.hpp
dey4ss/hyrise
c304b9ced36044e303eb8a4d68a05fc7edc04819
[ "MIT" ]
1
2020-11-17T19:18:58.000Z
2020-11-17T19:18:58.000Z
#pragma once #include <optional> #include <string> #include <type_traits> #include <boost/lexical_cast.hpp> #include <boost/variant.hpp> #include "resolve_type.hpp" namespace opossum { /** * Contrary to the functions in lossless_cast.hpp, converts from an AllTypeVariant to any target, even if accuracy/data * is lost by the conversion. * * Use this function only in contexts where (query-)result accuracy is not affected (e.g., statistics/estimations) * * If @param source is NULL, return std::nullopt * If @param source is a string, perform a boost::lexical_cast<> * If @param source is arithmetic, perform a static_cast<>, clamping the returned value at * `std::numeric_limits<Target>::min()/max()` to avoid undefined behaviour. */ template <typename Target> std::optional<Target> lossy_variant_cast(const AllTypeVariant& source) { if (variant_is_null(source)) return std::nullopt; std::optional<Target> result; resolve_data_type(data_type_from_all_type_variant(source), [&](const auto source_data_type_t) { using SourceDataType = typename decltype(source_data_type_t)::type; if constexpr (std::is_same_v<Target, SourceDataType>) { result = boost::get<SourceDataType>(source); } else { if constexpr (std::is_same_v<pmr_string, SourceDataType> == std::is_same_v<pmr_string, Target>) { const auto source_value = boost::get<SourceDataType>(source); if (source_value > std::numeric_limits<Target>::max()) { result = std::numeric_limits<Target>::max(); } else if (source_value < std::numeric_limits<Target>::lowest()) { result = std::numeric_limits<Target>::lowest(); } else { result = static_cast<Target>(boost::get<SourceDataType>(source)); } } else { result = boost::lexical_cast<Target>(boost::get<SourceDataType>(source)); } } }); return result; } } // namespace opossum
34.910714
119
0.685934
dey4ss
acf4a9e896b18a13187658d478d2ea8356b620bf
22,442
cpp
C++
src/sed/libs/seiscomp3/datamodel/strongmotion/strongmotionparameters.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
94
2015-02-04T13:57:34.000Z
2021-11-01T15:10:06.000Z
src/sed/libs/seiscomp3/datamodel/strongmotion/strongmotionparameters.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
233
2015-01-28T15:16:46.000Z
2021-08-23T11:31:37.000Z
src/sed/libs/seiscomp3/datamodel/strongmotion/strongmotionparameters.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
95
2015-02-13T15:53:30.000Z
2021-11-02T14:54:54.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public 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 * * SeisComP Public License for more details. * ***************************************************************************/ // This file was created by a source code generator. // Do not modify the contents. Change the definition and run the generator // again! #define SEISCOMP_COMPONENT DataModel #include <seiscomp3/datamodel/strongmotion/strongmotionparameters.h> #include <seiscomp3/datamodel/strongmotion/simplefilter.h> #include <seiscomp3/datamodel/strongmotion/record.h> #include <seiscomp3/datamodel/strongmotion/strongorigindescription.h> #include <algorithm> #include <seiscomp3/datamodel/metadata.h> #include <seiscomp3/logging/log.h> namespace Seiscomp { namespace DataModel { namespace StrongMotion { IMPLEMENT_SC_CLASS_DERIVED(StrongMotionParameters, PublicObject, "StrongMotionParameters"); StrongMotionParameters::MetaObject::MetaObject(const Core::RTTI* rtti) : Seiscomp::Core::MetaObject(rtti) { addProperty(arrayObjectProperty("simpleFilter", "SimpleFilter", &StrongMotionParameters::simpleFilterCount, &StrongMotionParameters::simpleFilter, static_cast<bool (StrongMotionParameters::*)(SimpleFilter*)>(&StrongMotionParameters::add), &StrongMotionParameters::removeSimpleFilter, static_cast<bool (StrongMotionParameters::*)(SimpleFilter*)>(&StrongMotionParameters::remove))); addProperty(arrayObjectProperty("record", "Record", &StrongMotionParameters::recordCount, &StrongMotionParameters::record, static_cast<bool (StrongMotionParameters::*)(Record*)>(&StrongMotionParameters::add), &StrongMotionParameters::removeRecord, static_cast<bool (StrongMotionParameters::*)(Record*)>(&StrongMotionParameters::remove))); addProperty(arrayObjectProperty("strongOriginDescription", "StrongOriginDescription", &StrongMotionParameters::strongOriginDescriptionCount, &StrongMotionParameters::strongOriginDescription, static_cast<bool (StrongMotionParameters::*)(StrongOriginDescription*)>(&StrongMotionParameters::add), &StrongMotionParameters::removeStrongOriginDescription, static_cast<bool (StrongMotionParameters::*)(StrongOriginDescription*)>(&StrongMotionParameters::remove))); } IMPLEMENT_METAOBJECT(StrongMotionParameters) StrongMotionParameters::StrongMotionParameters() : PublicObject("StrongMotionParameters") { } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StrongMotionParameters::StrongMotionParameters(const StrongMotionParameters& other) : PublicObject() { *this = other; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StrongMotionParameters::~StrongMotionParameters() { std::for_each(_simpleFilters.begin(), _simpleFilters.end(), std::compose1(std::bind2nd(std::mem_fun(&SimpleFilter::setParent), (PublicObject*)NULL), std::mem_fun_ref(&SimpleFilterPtr::get))); std::for_each(_records.begin(), _records.end(), std::compose1(std::bind2nd(std::mem_fun(&Record::setParent), (PublicObject*)NULL), std::mem_fun_ref(&RecordPtr::get))); std::for_each(_strongOriginDescriptions.begin(), _strongOriginDescriptions.end(), std::compose1(std::bind2nd(std::mem_fun(&StrongOriginDescription::setParent), (PublicObject*)NULL), std::mem_fun_ref(&StrongOriginDescriptionPtr::get))); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::operator==(const StrongMotionParameters& rhs) const { return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::operator!=(const StrongMotionParameters& rhs) const { return !operator==(rhs); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::equal(const StrongMotionParameters& other) const { return *this == other; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StrongMotionParameters& StrongMotionParameters::operator=(const StrongMotionParameters& other) { PublicObject::operator=(other); return *this; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::assign(Object* other) { StrongMotionParameters* otherStrongMotionParameters = StrongMotionParameters::Cast(other); if ( other == NULL ) return false; *this = *otherStrongMotionParameters; return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::attachTo(PublicObject* parent) { return false; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::detachFrom(PublicObject* object) { return false; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::detach() { return false; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Object* StrongMotionParameters::clone() const { StrongMotionParameters* clonee = new StrongMotionParameters(); *clonee = *this; return clonee; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::updateChild(Object* child) { SimpleFilter* simpleFilterChild = SimpleFilter::Cast(child); if ( simpleFilterChild != NULL ) { SimpleFilter* simpleFilterElement = SimpleFilter::Cast(PublicObject::Find(simpleFilterChild->publicID())); if ( simpleFilterElement && simpleFilterElement->parent() == this ) { *simpleFilterElement = *simpleFilterChild; return true; } return false; } Record* recordChild = Record::Cast(child); if ( recordChild != NULL ) { Record* recordElement = Record::Cast(PublicObject::Find(recordChild->publicID())); if ( recordElement && recordElement->parent() == this ) { *recordElement = *recordChild; return true; } return false; } StrongOriginDescription* strongOriginDescriptionChild = StrongOriginDescription::Cast(child); if ( strongOriginDescriptionChild != NULL ) { StrongOriginDescription* strongOriginDescriptionElement = StrongOriginDescription::Cast(PublicObject::Find(strongOriginDescriptionChild->publicID())); if ( strongOriginDescriptionElement && strongOriginDescriptionElement->parent() == this ) { *strongOriginDescriptionElement = *strongOriginDescriptionChild; return true; } return false; } return false; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void StrongMotionParameters::accept(Visitor* visitor) { for ( std::vector<SimpleFilterPtr>::iterator it = _simpleFilters.begin(); it != _simpleFilters.end(); ++it ) (*it)->accept(visitor); for ( std::vector<RecordPtr>::iterator it = _records.begin(); it != _records.end(); ++it ) (*it)->accept(visitor); for ( std::vector<StrongOriginDescriptionPtr>::iterator it = _strongOriginDescriptions.begin(); it != _strongOriginDescriptions.end(); ++it ) (*it)->accept(visitor); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size_t StrongMotionParameters::simpleFilterCount() const { return _simpleFilters.size(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SimpleFilter* StrongMotionParameters::simpleFilter(size_t i) const { return _simpleFilters[i].get(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SimpleFilter* StrongMotionParameters::findSimpleFilter(const std::string& publicID) const { SimpleFilter* object = SimpleFilter::Cast(PublicObject::Find(publicID)); if ( object != NULL && object->parent() == this ) return object; return NULL; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::add(SimpleFilter* simpleFilter) { if ( simpleFilter == NULL ) return false; // Element has already a parent if ( simpleFilter->parent() != NULL ) { SEISCOMP_ERROR("StrongMotionParameters::add(SimpleFilter*) -> element has already a parent"); return false; } if ( PublicObject::IsRegistrationEnabled() ) { SimpleFilter* simpleFilterCached = SimpleFilter::Find(simpleFilter->publicID()); if ( simpleFilterCached ) { if ( simpleFilterCached->parent() ) { if ( simpleFilterCached->parent() == this ) SEISCOMP_ERROR("StrongMotionParameters::add(SimpleFilter*) -> element with same publicID has been added already"); else SEISCOMP_ERROR("StrongMotionParameters::add(SimpleFilter*) -> element with same publicID has been added already to another object"); return false; } else simpleFilter = simpleFilterCached; } } // Add the element _simpleFilters.push_back(simpleFilter); simpleFilter->setParent(this); // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_ADD); simpleFilter->accept(&nc); } // Notify registered observers childAdded(simpleFilter); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::remove(SimpleFilter* simpleFilter) { if ( simpleFilter == NULL ) return false; if ( simpleFilter->parent() != this ) { SEISCOMP_ERROR("StrongMotionParameters::remove(SimpleFilter*) -> element has another parent"); return false; } std::vector<SimpleFilterPtr>::iterator it; it = std::find(_simpleFilters.begin(), _simpleFilters.end(), simpleFilter); // Element has not been found if ( it == _simpleFilters.end() ) { SEISCOMP_ERROR("StrongMotionParameters::remove(SimpleFilter*) -> child object has not been found although the parent pointer matches???"); return false; } // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); (*it)->accept(&nc); } (*it)->setParent(NULL); childRemoved((*it).get()); _simpleFilters.erase(it); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::removeSimpleFilter(size_t i) { // index out of bounds if ( i >= _simpleFilters.size() ) return false; // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); _simpleFilters[i]->accept(&nc); } _simpleFilters[i]->setParent(NULL); childRemoved(_simpleFilters[i].get()); _simpleFilters.erase(_simpleFilters.begin() + i); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size_t StrongMotionParameters::recordCount() const { return _records.size(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Record* StrongMotionParameters::record(size_t i) const { return _records[i].get(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Record* StrongMotionParameters::findRecord(const std::string& publicID) const { Record* object = Record::Cast(PublicObject::Find(publicID)); if ( object != NULL && object->parent() == this ) return object; return NULL; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::add(Record* record) { if ( record == NULL ) return false; // Element has already a parent if ( record->parent() != NULL ) { SEISCOMP_ERROR("StrongMotionParameters::add(Record*) -> element has already a parent"); return false; } if ( PublicObject::IsRegistrationEnabled() ) { Record* recordCached = Record::Find(record->publicID()); if ( recordCached ) { if ( recordCached->parent() ) { if ( recordCached->parent() == this ) SEISCOMP_ERROR("StrongMotionParameters::add(Record*) -> element with same publicID has been added already"); else SEISCOMP_ERROR("StrongMotionParameters::add(Record*) -> element with same publicID has been added already to another object"); return false; } else record = recordCached; } } // Add the element _records.push_back(record); record->setParent(this); // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_ADD); record->accept(&nc); } // Notify registered observers childAdded(record); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::remove(Record* record) { if ( record == NULL ) return false; if ( record->parent() != this ) { SEISCOMP_ERROR("StrongMotionParameters::remove(Record*) -> element has another parent"); return false; } std::vector<RecordPtr>::iterator it; it = std::find(_records.begin(), _records.end(), record); // Element has not been found if ( it == _records.end() ) { SEISCOMP_ERROR("StrongMotionParameters::remove(Record*) -> child object has not been found although the parent pointer matches???"); return false; } // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); (*it)->accept(&nc); } (*it)->setParent(NULL); childRemoved((*it).get()); _records.erase(it); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::removeRecord(size_t i) { // index out of bounds if ( i >= _records.size() ) return false; // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); _records[i]->accept(&nc); } _records[i]->setParent(NULL); childRemoved(_records[i].get()); _records.erase(_records.begin() + i); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size_t StrongMotionParameters::strongOriginDescriptionCount() const { return _strongOriginDescriptions.size(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StrongOriginDescription* StrongMotionParameters::strongOriginDescription(size_t i) const { return _strongOriginDescriptions[i].get(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StrongOriginDescription* StrongMotionParameters::findStrongOriginDescription(const std::string& publicID) const { StrongOriginDescription* object = StrongOriginDescription::Cast(PublicObject::Find(publicID)); if ( object != NULL && object->parent() == this ) return object; return NULL; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::add(StrongOriginDescription* strongOriginDescription) { if ( strongOriginDescription == NULL ) return false; // Element has already a parent if ( strongOriginDescription->parent() != NULL ) { SEISCOMP_ERROR("StrongMotionParameters::add(StrongOriginDescription*) -> element has already a parent"); return false; } if ( PublicObject::IsRegistrationEnabled() ) { StrongOriginDescription* strongOriginDescriptionCached = StrongOriginDescription::Find(strongOriginDescription->publicID()); if ( strongOriginDescriptionCached ) { if ( strongOriginDescriptionCached->parent() ) { if ( strongOriginDescriptionCached->parent() == this ) SEISCOMP_ERROR("StrongMotionParameters::add(StrongOriginDescription*) -> element with same publicID has been added already"); else SEISCOMP_ERROR("StrongMotionParameters::add(StrongOriginDescription*) -> element with same publicID has been added already to another object"); return false; } else strongOriginDescription = strongOriginDescriptionCached; } } // Add the element _strongOriginDescriptions.push_back(strongOriginDescription); strongOriginDescription->setParent(this); // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_ADD); strongOriginDescription->accept(&nc); } // Notify registered observers childAdded(strongOriginDescription); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::remove(StrongOriginDescription* strongOriginDescription) { if ( strongOriginDescription == NULL ) return false; if ( strongOriginDescription->parent() != this ) { SEISCOMP_ERROR("StrongMotionParameters::remove(StrongOriginDescription*) -> element has another parent"); return false; } std::vector<StrongOriginDescriptionPtr>::iterator it; it = std::find(_strongOriginDescriptions.begin(), _strongOriginDescriptions.end(), strongOriginDescription); // Element has not been found if ( it == _strongOriginDescriptions.end() ) { SEISCOMP_ERROR("StrongMotionParameters::remove(StrongOriginDescription*) -> child object has not been found although the parent pointer matches???"); return false; } // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); (*it)->accept(&nc); } (*it)->setParent(NULL); childRemoved((*it).get()); _strongOriginDescriptions.erase(it); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool StrongMotionParameters::removeStrongOriginDescription(size_t i) { // index out of bounds if ( i >= _strongOriginDescriptions.size() ) return false; // Create the notifiers if ( Notifier::IsEnabled() ) { NotifierCreator nc(OP_REMOVE); _strongOriginDescriptions[i]->accept(&nc); } _strongOriginDescriptions[i]->setParent(NULL); childRemoved(_strongOriginDescriptions[i].get()); _strongOriginDescriptions.erase(_strongOriginDescriptions.begin() + i); return true; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void StrongMotionParameters::serialize(Archive& ar) { // Do not read/write if the archive's version is higher than // currently supported if ( ar.isHigherVersion<0,11>() ) { SEISCOMP_ERROR("Archive version %d.%d too high: StrongMotionParameters skipped", ar.versionMajor(), ar.versionMinor()); ar.setValidity(false); return; } if ( ar.hint() & Archive::IGNORE_CHILDS ) return; ar & NAMED_OBJECT_HINT("simpleFilter", Seiscomp::Core::Generic::containerMember(_simpleFilters, Seiscomp::Core::Generic::bindMemberFunction<SimpleFilter>(static_cast<bool (StrongMotionParameters::*)(SimpleFilter*)>(&StrongMotionParameters::add), this)), Archive::STATIC_TYPE); ar & NAMED_OBJECT_HINT("record", Seiscomp::Core::Generic::containerMember(_records, Seiscomp::Core::Generic::bindMemberFunction<Record>(static_cast<bool (StrongMotionParameters::*)(Record*)>(&StrongMotionParameters::add), this)), Archive::STATIC_TYPE); ar & NAMED_OBJECT_HINT("strongOriginDescription", Seiscomp::Core::Generic::containerMember(_strongOriginDescriptions, Seiscomp::Core::Generic::bindMemberFunction<StrongOriginDescription>(static_cast<bool (StrongMotionParameters::*)(StrongOriginDescription*)>(&StrongMotionParameters::add), this)), Archive::STATIC_TYPE); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } } }
33.296736
458
0.543356
damb
acf4ec5b0c59feb0947e332da9ef1ea843127c50
2,253
cpp
C++
server.cpp
no-go/ServerPush
eeb75fa7e6a0a10f1edcc6dd7dc0821e29e5503c
[ "Unlicense" ]
null
null
null
server.cpp
no-go/ServerPush
eeb75fa7e6a0a10f1edcc6dd7dc0821e29e5503c
[ "Unlicense" ]
null
null
null
server.cpp
no-go/ServerPush
eeb75fa7e6a0a10f1edcc6dd7dc0821e29e5503c
[ "Unlicense" ]
null
null
null
#include <iostream> #include <sstream> #include <chrono> #include <thread> #include <cstdlib> #include <list> #include <algorithm> // find() #include "lib/UniSocket.hpp" using namespace std; #define POLLINGMYSEC 500000 list<UniSocket> clientConnections; void threadHandle(UniSocket usock) { string msg; bool newMessage; try { cout << "hello " << usock.getIp() << ":" << usock.getPeerPort() << endl; } catch(UniSocketException & e) { cout << e._msg << endl; } while(true) { stringstream ss; try { msg = usock.recv(true); ss << "client " << usock.getIp() << ":" << usock.getPeerPort() << " says: " << msg; newMessage = true; if (msg == (string) ":q") break; } catch(UniSocketException & e) { this_thread::sleep_for(chrono::microseconds(POLLINGMYSEC)); newMessage = false; } if (newMessage == false) continue; // need iterator to erase !! //for (auto &so : clientConnections) { so.send(ss.str()); .... for (auto i = clientConnections.begin(); i != clientConnections.end(); ) { try { cout << " try to send '" << msg << "' to " << i->getIp() << ":" << i->getPeerPort() << endl; i->send(ss.str()); ++i; } catch (UniSocketException & e) { cout << "ups! " << i->getIp() << ":" << i->getPeerPort() << " " << e._msg << endl; i = clientConnections.erase(i); } } } try { cout << "bye " << usock.getIp() << ":" << usock.getPeerPort() << endl; auto iter = find_if( clientConnections.begin(), clientConnections.end(), [&]( UniSocket us ) { if ( ( usock.getIp() == us.getIp() ) && ( usock.getPeerPort() == us.getPeerPort() ) ) { return true; } else { return false; } } ); usock.close(); clientConnections.erase(iter); } catch(UniSocketException & e) { cout << e._msg << endl; } } int main(int argc, char * argv[]) { if (argc < 2) { cout<<"usage: "<<argv[0]<<" <port>"<<endl; return 1; } try { UniServerSocket svr(atoi(argv[1]), 5); while (true) { UniSocket us = svr.accept(); clientConnections.push_back(us); thread t(threadHandle, us); t.detach(); } } catch(UniSocketException e) { cout << e._msg << endl; } return 0; }
21.457143
76
0.562805
no-go
acf5634c551b27ebcde2921a53ffe5723db612bd
5,042
cpp
C++
openbr/plugins/cluster/onlinerod.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
61
2016-01-27T04:23:04.000Z
2020-06-19T20:45:16.000Z
openbr/plugins/cluster/onlinerod.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
2
2016-04-09T13:55:15.000Z
2017-11-21T03:08:08.000Z
openbr/plugins/cluster/onlinerod.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
18
2016-01-27T13:07:47.000Z
2022-01-22T17:19:18.000Z
#include <openbr/plugins/openbr_internal.h> #include <openbr/core/cluster.h> #include <openbr/core/opencvutils.h> using namespace cv; namespace br { /*! * \brief Constructors clusters based on the Rank-Order distance in an online, incremental manner * \author Charles Otto \cite caotto * \author Jordan Cheney \cite JordanCheney * \br_property br::Distance* distance Distance to compute the similarity score between templates. Default is L2. * \br_property int kNN Maximum number of nearest neighbors to keep for each template. Default is 20. * \br_property float aggression Clustering aggresiveness. A higher value will result in larger clusters. Default is 10. * \br_property bool incremental If true, compute the clusters as each template is processed otherwise compute the templates at the end. Default is false. * \br_property QString evalOutput Path to store cluster informtation. Optional. Default is an empty string. * \br_paper Zhu et al. * "A Rank-Order Distance based Clustering Algorithm for Face Tagging" * CVPR 2011 */ class OnlineRODTransform : public TimeVaryingTransform { Q_OBJECT Q_PROPERTY(br::Distance *distance READ get_distance WRITE set_distance RESET reset_distance STORED true) Q_PROPERTY(int kNN READ get_kNN WRITE set_kNN RESET reset_kNN STORED false) Q_PROPERTY(float aggression READ get_aggression WRITE set_aggression RESET reset_aggression STORED false) Q_PROPERTY(bool incremental READ get_incremental WRITE set_incremental RESET reset_incremental STORED false) Q_PROPERTY(QString evalOutput READ get_evalOutput WRITE set_evalOutput RESET reset_evalOutput STORED false) BR_PROPERTY(br::Distance*, distance, Distance::make(".Dist(L2)",this)) BR_PROPERTY(int, kNN, 20) BR_PROPERTY(float, aggression, 10) BR_PROPERTY(bool, incremental, false) BR_PROPERTY(QString, evalOutput, "") TemplateList templates; Neighborhood neighborhood; public: OnlineRODTransform() : TimeVaryingTransform(false, false) {} private: void projectUpdate(const TemplateList &src, TemplateList &dst) { // update current graph foreach(const Template &t, src) { QList<float> scores = distance->compare(templates, t); // attempt to udpate each existing point's (sorted) k-NN list with these results. Neighbors currentN; for (int i=0; i < scores.size(); i++) { currentN.append(Neighbor(i, scores[i])); Neighbors target = neighborhood[i]; // should we insert the new neighbor into the current target's list? if (target.size() < kNN || scores[i] > target.last().second) { // insert into the sorted nearest neighbor list Neighbor temp(scores.size(), scores[i]); br::Neighbors::iterator res = qLowerBound(target.begin(), target.end(), temp, compareNeighbors); target.insert(res, temp); if (target.size() > kNN) target.removeLast(); neighborhood[i] = target; } } // add a new row, consisting of the top neighbors of the newest point int actuallyKeep = std::min(kNN, currentN.size()); std::partial_sort(currentN.begin(), currentN.begin()+actuallyKeep, currentN.end(), compareNeighbors); Neighbors selected = currentN.mid(0, actuallyKeep); neighborhood.append(selected); templates.append(t); } if (incremental) identifyClusters(dst); } void finalize(TemplateList &output) { if (!templates.empty()) { identifyClusters(output); templates.clear(); neighborhood.clear(); } } void identifyClusters(TemplateList &dst) { Clusters clusters = ClusterGraph(neighborhood, aggression, evalOutput); if (Globals->verbose) qDebug("Built %d clusters from %d templates", clusters.size(), templates.size()); for (int i = 0; i < clusters.size(); i++) { // Calculate the centroid of each cluster Mat center = Mat::zeros(templates[0].m().rows, templates[0].m().cols, CV_32F); foreach (int t, clusters[i]) { Mat converted; templates[t].m().convertTo(converted, CV_32F); center += converted; } center /= clusters[i].size(); // Calculate the Euclidean distance from the center to use as the cluster confidence foreach (int t, clusters[i]) { templates[t].file.set("Cluster", i); Mat c; templates[t].m().convertTo(c, CV_32F); Mat p; pow(c - center, 2, p); templates[t].file.set("ClusterConfidence", sqrt(sum(p)[0])); } } dst.append(templates); } }; BR_REGISTER(Transform, OnlineRODTransform) } // namespace br #include "onlinerod.moc"
40.015873
154
0.63923
kassemitani
acf5d0d8f5329aaae342414fd903983e792ee2c4
254
cpp
C++
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#476_NumberComplement_sol5_bit_manipulation_O(1)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int findComplement(int num) { int msb = 31 - __builtin_clz((unsigned int)num); int fullMask = ((1U << (msb + 1)) - 1); int numComplement = fullMask ^ num; return numComplement; } };
28.222222
57
0.555118
Tudor67
acf81a09adee92346a866c739f451b3cc7006bf2
5,884
cc
C++
tree/TrieTree.cc
raining888/leetcode
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
[ "MIT" ]
null
null
null
tree/TrieTree.cc
raining888/leetcode
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
[ "MIT" ]
null
null
null
tree/TrieTree.cc
raining888/leetcode
e9e8ac51d49e0c5f1450a6b76ba9777b89f7e25b
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include <string> #include <unordered_map> #include <string.h> using namespace std; class TrieTree { public: class Node { public: int pass; // 标记该节点有多少个相同前缀的节点 int end; //标记该节点加入过多少次,或者说有多少个以该节点结尾的单词 unordered_map<int, Node*> nexts; Node() { pass = 0; end = 0; } }; class Trie { public: Node* root; Trie() { root = new Node(); } void insert(string word) { if (word == "") { return; } const char* chs = word.c_str(); Node* node = root; node->pass++; int index = 0; int len = strlen(chs); for (int i = 0; i < len; i++) { // 从左往右遍历字符 index = (int)chs[i]; // 由字符,对应成走向哪条路 if (node->nexts.find(index) == node->nexts.end()) { node->nexts.emplace(index, new Node()); } node = node->nexts.at(index); node->pass++; } node->end++; } void del(string word) { if (search(word) != 0) { const char* chs = word.c_str(); Node* node = root; node->pass--; int index = 0; int len = strlen(chs); for (int i = 0; i < len; i++) { index = (int) chs[i]; if (--node->nexts.at(index)->pass == 0) { node->nexts.erase(index); return; } node = node->nexts.at(index); } node->end--; } } // word这个单词之前加入过几次 int search(string word) { if (word == "") { return 0; } const char* chs = word.c_str(); Node* node = root; int index = 0; int len = strlen(chs); for (int i = 0; i < len; i++) { index = (int) chs[i]; if (node->nexts.find(index) == node->nexts.end()) { return 0; } node = node->nexts.at(index); } return node->end; } // 所有加入的字符串中,有几个是以pre这个字符串作为前缀的 int prefixNumber(string pre) { if (pre == "") { return 0; } const char* chs = pre.c_str(); Node* node = root; int index = 0; int len = strlen(chs); for (int i = 0; i < len; i++) { index = (int) chs[i]; if (node->nexts.find(index) == node->nexts.end()) { return 0; } node = node->nexts.at(index); } return node->pass; } }; class Right { public: unordered_map<string, int> box; void insert(string word) { if(box.find(word) == box.end()) { box.emplace(word, 1); } else { box[word]++; } } void del (string word) { if(box.find(word) != box.end()) { if(box.at(word) == 1) { box.erase(word); } else { box[word]--; } } } int search(string word) { if(box.find(word) == box.end()) { return 0; } else { return box.at(word); } } int prefixNumber(string pre) { int count = 0; for(auto cur : box) { if(cur.first.find(pre) == 0) // pre是开始字符 { count += box.at(cur.first); } } return count; } }; static int getRandom(int min, int max) { random_device seed; // 硬件生成随机数种子 ranlux48 engine(seed()); // 利用种子生成随机数引 uniform_int_distribution<> distrib(min, max); // 设置随机数范围,并为均匀分布 int res = distrib(engine); // 随机数 return res; } static string generateRandomString(int strLen) { int len = getRandom(1, strLen); char* ans = new char[len]; for (int i = 0; i < len; i++) { int value = (int) getRandom(0, 5); ans[i] = (char) (97 + value); } return string(ans); } static string* generateRandomStringArray(int arrLen, int strLen, int* len) { *len = getRandom(1, arrLen); string* ans = new string[*len]; for (int i = 0; i < *len; i++) { ans[i] = generateRandomString(strLen); } return ans; } }; int main() { int arrLen = 100; int strLen = 20; int testTimes = 1000; int len = 0; for (int i = 0; i < testTimes; i++) { string* arr = TrieTree::generateRandomStringArray(arrLen, strLen, &len); TrieTree::Trie trie; TrieTree::Right right; for (int j = 0; j < len; j++) { double decide = double (TrieTree::getRandom(0, 1023) / 1024.0); if (decide < 0.25) { trie.insert(arr[j]); right.insert(arr[j]); } else if (decide < 0.5) { trie.del(arr[j]); right.del(arr[j]); } else if (decide < 0.75) { int ans1 = trie.search(arr[j]); int ans2 = right.search(arr[j]); if (ans1 != ans2) { cout << "Oops!" << endl; } } else { int ans1 = trie.prefixNumber(arr[j]); int ans2 = right.prefixNumber(arr[j]); if (ans1 != ans2) { cout << "Oops!" << endl; } } } } cout << "finish!" << endl; return 0; }
21.873606
78
0.406526
raining888
acf8e33715d26fbff11bf57300d429ec1ec3965c
2,786
cpp
C++
src/components/improviser.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
17
2021-03-22T14:17:16.000Z
2022-02-22T20:58:27.000Z
src/components/improviser.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
null
null
null
src/components/improviser.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
1
2021-11-17T18:00:55.000Z
2021-11-17T18:00:55.000Z
#include "improviser.h" #include "synth/synth.h" void ImproviserComponent::update(Synth const & synth) { constexpr auto transfer = util::generate_lookup_table<float, 7 * 7>([](int index) -> float { constexpr float matrix[7 * 7] = { 1.0f, 2.0f, 2.0f, 3.0f, 5.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 1.0f, 5.0f, 3.0f, 2.0f, 2.0f, 1.0f, 1.0f, 2.0f, 3.0f, 2.0f, 3.0f, 2.0f, 1.0f, 2.0f, 1.0f, 2.0f, 2.0f, 1.0f, 7.0f, 1.0f, 2.0f, 2.0f, 1.0f, 2.0f, 3.0f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f, 1.0f, 2.0f, 5.0f, 2.0f, 2.0f, 1.0f, 1.0f, 2.0f, 1.0f }; auto row = index / 7; auto offset = index % 7; auto cumulative = 0.0f; auto row_sum = 0.0f; for (int i = 0; i < 7; i++) { auto val = matrix[row * 7 + i]; if (i <= offset) cumulative += val; row_sum += val; } return cumulative / row_sum; }); constexpr int MAJOR_SCALE[7] = { 0, 2, 4, 5, 7, 9, 11 }; constexpr int MINOR_SCALE[7] = { 0, 2, 3, 5, 7, 8, 10 }; constexpr auto BASE_NOTE = util::note<util::NoteName::C, 3>(); constexpr auto VELOCITY = 0.5f; auto const scale = mode == Mode::MAJOR ? MAJOR_SCALE : MINOR_SCALE; auto steps_per_second = 4.0f / 60.0f * float(synth.settings.tempo); auto samples = 16.0f * SAMPLE_RATE / steps_per_second; for (int i = 0; i < BLOCK_SIZE; i++) { if (current_time >= samples) { for (auto note : chord) { outputs[0].add_event(NoteEvent::make_release(synth.time + i, note)); } chord.clear(); auto u = util::randf(seed); auto next_chord = 0; while (next_chord < 7 && transfer[current_chord * 7 + next_chord] < u) next_chord++; current_chord = next_chord; current_time = 0; for (int n = 0; n < num_notes; n++) { auto note = BASE_NOTE + tonality + scale[util::wrap(current_chord + 2*n, 7)]; chord.emplace_back(note); outputs[0].add_event(NoteEvent::make_press(synth.time + i, note, VELOCITY)); } } current_time++; } } void ImproviserComponent::render(Synth const & synth) { auto fmt_tonality = [](int tonality, char * fmt, int len) { static constexpr char const * names[12] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; strcpy_s(fmt, len, names[tonality]); }; tonality .render(fmt_tonality); ImGui::SameLine(); num_notes.render(); auto mode_index = int(mode); if (ImGui::BeginCombo("Mode", mode_names[mode_index])) { for (int i = 0; i < util::array_count(mode_names); i++) { if (ImGui::Selectable(mode_names[i], mode_index == i)) { mode_index = i; } } ImGui::EndCombo(); } mode = Mode(mode_index); } void ImproviserComponent::serialize_custom(json::Writer & writer) const { writer.write("mode", int(mode)); } void ImproviserComponent::deserialize_custom(json::Object const & object) { mode = Mode(object.find_int("mode")); }
27.048544
112
0.609835
jan-van-bergen
acfa788c86bc91b8b073a6d5b3d5515772723cce
2,887
cpp
C++
Source/WebCore/Modules/webgpu/WebGPUComputePassEncoder.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/Modules/webgpu/WebGPUComputePassEncoder.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/Modules/webgpu/WebGPUComputePassEncoder.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2019 Apple 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. 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 INC. 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. */ #include "config.h" #include "WebGPUComputePassEncoder.h" #if ENABLE(WEBGPU) #include "GPUComputePassEncoder.h" #include "GPUProgrammablePassEncoder.h" #include "Logging.h" #include "WebGPUComputePipeline.h" namespace WebCore { Ref<WebGPUComputePassEncoder> WebGPUComputePassEncoder::create(RefPtr<GPUComputePassEncoder>&& encoder) { return adoptRef(*new WebGPUComputePassEncoder(WTFMove(encoder))); } WebGPUComputePassEncoder::WebGPUComputePassEncoder(RefPtr<GPUComputePassEncoder>&& encoder) : m_passEncoder { WTFMove(encoder) } { } void WebGPUComputePassEncoder::setPipeline(const WebGPUComputePipeline& pipeline) { if (!m_passEncoder) { LOG(WebGPU, "GPUComputePassEncoder::setPipeline(): Invalid operation!"); return; } if (!pipeline.computePipeline()) { LOG(WebGPU, "GPUComputePassEncoder::setPipeline(): Invalid pipeline!"); return; } m_passEncoder->setPipeline(makeRef(*pipeline.computePipeline())); } void WebGPUComputePassEncoder::dispatch(unsigned x, unsigned y, unsigned z) { if (!m_passEncoder) { LOG(WebGPU, "GPUComputePassEncoder::dispatch(): Invalid operation!"); return; } // FIXME: Add Web GPU validation. m_passEncoder->dispatch(x, y, z); } GPUProgrammablePassEncoder* WebGPUComputePassEncoder::passEncoder() { return m_passEncoder.get(); } const GPUProgrammablePassEncoder* WebGPUComputePassEncoder::passEncoder() const { return m_passEncoder.get(); } } // namespace WebCore #endif // ENABLE(WEBGPU)
33.964706
103
0.748528
jacadcaps
acff9a03c40bfd96d0dc41ce22181ba72f6ae208
348
cpp
C++
2017-08-03/I.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
3
2018-04-02T06:00:51.000Z
2018-05-29T04:46:29.000Z
2017-08-03/I.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-03-31T17:54:30.000Z
2018-05-02T11:31:06.000Z
2017-08-03/I.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-10-07T00:08:06.000Z
2021-06-28T11:02:59.000Z
#include <cstdlib> #include <cstdio> #include <cstring> using namespace std; int T; int N, cnt[2]; int main() { int t, i, x; scanf("%d", &T); for(t = 0;t < T;t += 1) { cnt[0] = cnt[1] = 0; scanf("%d", &N); for(i = 0;i < N;i += 1) { scanf("%d", &x); cnt[x & 1] += 1; } printf("2 %d\n", cnt[0] >= cnt[1]?0:1); } exit(0); }
12.888889
41
0.462644
tangjz
4a038e9aad87dbd1b13a4488a297ed810a225bf5
230
cpp
C++
lang/C++/averages-arithmetic-mean-3.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
5
2021-01-29T20:08:05.000Z
2022-03-22T06:16:05.000Z
lang/C++/averages-arithmetic-mean-3.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/averages-arithmetic-mean-3.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2021-04-13T04:19:31.000Z
2021-04-13T04:19:31.000Z
#include <iterator> #include <algorithm> template <typename Iterator> double mean(Iterator begin, Iterator end) { if (begin == end) return 0; return std::accumulate(begin, end, 0.0) / std::distance(begin, end); }
20.909091
72
0.669565
ethansaxenian
4a07244eeeb593544fc963b05a5583d3de6dbb77
1,758
cpp
C++
tests/Geometry/XSRay2Test.cpp
Sibras/ShiftLib
83e1ab9605aca6535af836ad1e68bf3c3049d976
[ "Apache-2.0" ]
null
null
null
tests/Geometry/XSRay2Test.cpp
Sibras/ShiftLib
83e1ab9605aca6535af836ad1e68bf3c3049d976
[ "Apache-2.0" ]
null
null
null
tests/Geometry/XSRay2Test.cpp
Sibras/ShiftLib
83e1ab9605aca6535af836ad1e68bf3c3049d976
[ "Apache-2.0" ]
null
null
null
/** * Copyright Matthew Oliver * * 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 XSTESTMAIN # include "XSCompilerOptions.h" # define XS_OVERRIDE_SHIFT_NS TESTISA(Ray2Test) # define XS_TESTING_RAY2 # include "Geometry/XSGTestGeometry.hpp" using namespace XS_OVERRIDE_SHIFT_NS; using namespace XS_OVERRIDE_SHIFT_NS::Shift; template<typename T> class TESTISA(Ray2) : public ::testing::Test { public: using Type = T; using TypeInt = typename T::Type; // requested type static constexpr SIMDWidth width = T::width; // requested width static constexpr SIMDWidth widthImpl = T::widthImpl; // actual width in use static constexpr bool packed = T::packed; }; using Ray2TestTypes = ::testing::Types<Ray2<float, true, SIMDWidth::Scalar>, Ray2<float, false, SIMDWidth::Scalar>, Ray2<float, true, SIMDWidth::B16>, Ray2<float, false, SIMDWidth::B16>, Ray2<float, true, SIMDWidth::B32>, Ray2<float, false, SIMDWidth::B32> /*, Ray2<float, true, SIMDWidth::B64>, Ray2<float, false, SIMDWidth::B64>*/>; TYPED_TEST_SUITE(TESTISA(Ray2), Ray2TestTypes); TYPED_TEST_NS2(Ray2, TESTISA(Ray2), Ray2) { using TestType = typename TestFixture::Type; // TODO:************ } #endif
35.16
116
0.710466
Sibras
4a0e8d4bb60b0ec8f6211aaa2ff7184f24e140bd
561
cpp
C++
src/tema cu WHILE/Aplicatii 4/ex4.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
2
2021-11-27T18:29:32.000Z
2021-11-28T14:35:47.000Z
src/tema cu WHILE/Aplicatii 4/ex4.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
src/tema cu WHILE/Aplicatii 4/ex4.cpp
andrew-miroiu/Cpp-projects
d0917a7f78aef929c25dc9b019e910951c2050ac
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { /* 4. Se citeşte de la tastatură un număr natural x de cel mult 9 cifre. Se cere să se calculeze produsul cifrelor impare. Exemplu: dacă x =6543 atunci produsul cifrelor impare este 3*5=15*/ int x,p=1; cout<<"Scrie un nr. de macimum 9 cifre= "; cin>>x; while(x>0) { if(x%2!=0) { p=p*(x%10); x=x/10; } else { x=x/10; } } cout<<"Produsul cifrelor impare este "<<p; return 0; }
17
100
0.516934
andrew-miroiu
4a0ede123971155c879137ed989de53d24a7e985
1,803
cpp
C++
Lance2D/Tools/GraphView.cpp
lance-tech/Lance-2D
45d733df5a080cb1102f2014cd2dea9d9b928b0d
[ "MIT" ]
1
2022-02-27T15:35:57.000Z
2022-02-27T15:35:57.000Z
Lance2D/Tools/GraphView.cpp
lance-tech/Lance-2D
45d733df5a080cb1102f2014cd2dea9d9b928b0d
[ "MIT" ]
null
null
null
Lance2D/Tools/GraphView.cpp
lance-tech/Lance-2D
45d733df5a080cb1102f2014cd2dea9d9b928b0d
[ "MIT" ]
null
null
null
#include "GraphView.h" #include "NodeModel.h" GraphView::GraphView(QWidget *parent) : QTreeView(parent), engineEventModel(nullptr) { } GraphView::~GraphView() { } void GraphView::Initialize(EngineEventModel &model) { SetEngineModel(model); connect(this, SIGNAL(clicked(QModelIndex)), this, SLOT(SelectObject(QModelIndex))); connect(engineEventModel, SIGNAL(ObjectNameChanged(const QString &)), this, SLOT(ObjectNameChanged(const QString &))); } void GraphView::SetEngineModel(EngineEventModel &model) { engineEventModel = &model; } void GraphView::mousePressEvent(QMouseEvent *event) { QTreeView::mousePressEvent(event); if (!indexAt(event->pos()).isValid()) { selectionModel()->clear(); } } void GraphView::ObjectNameChanged(const QString &objectName) { NodeModel *model = (NodeModel*)this->model(); QModelIndex selectedIndex = model->FindIndexByName(objectName.toUtf8().constData()); update(selectedIndex); } void GraphView::SelectObject(QModelIndex index) { Object& prevObject = engineEventModel->GetSelectObject(); if (&prevObject) { prevObject.SetSelected(false); } NodeModel *model = (NodeModel*)this->model(); Node& selectedNode = model->getItem(index); Object& object = selectedNode.GetNodeObject(); engineEventModel->SetObject(&object); engineEventModel->SetNode(&selectedNode); object.SetSelected(true); emit ObjectSelected(); } void GraphView::SelectObject() { Object& selectedObject = engineEventModel->GetSelectObject(); NodeModel *model = (NodeModel*)this->model(); QModelIndex selectedIndex = model->FindIndexByName(selectedObject.Name); this->selectionModel()->setCurrentIndex(selectedIndex, QItemSelectionModel::ClearAndSelect); Node& node = model->getItem(selectedIndex); engineEventModel->SetNode(&node); emit ObjectSelected(); }
22.822785
119
0.755408
lance-tech
4a115e8ec19668860f858a4965ca76d1679f0649
615
hpp
C++
model/player.hpp
travnick/SlipperTanks
33334cf0994402e7ba0e8de54f75a86835e0bae0
[ "Apache-2.0" ]
1
2015-01-11T11:03:18.000Z
2015-01-11T11:03:18.000Z
model/player.hpp
travnick/SlipperTanks
33334cf0994402e7ba0e8de54f75a86835e0bae0
[ "Apache-2.0" ]
null
null
null
model/player.hpp
travnick/SlipperTanks
33334cf0994402e7ba0e8de54f75a86835e0bae0
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> class QVector3D; struct InputEvents; class Node; class Player { public: Player(); ~Player(); const std::string &getRequiredModelName() const; void setAttachedNode(Node *attachedModel); const Node &getAttachedNode() const; Node &getAttachedNode(); void move(const QVector3D &moveDirection, float seconds); void rotate(float angle, const QVector3D &axis); void setSpeed(float speed); private: void handleInputEvents(const InputEvents & inputEvents, float secondsElapsed); std::string _requiredModelName; Node *_attachedNode; };
18.636364
82
0.715447
travnick
4a1179ee7ae693a959bcea83b3a3d08e4fb0fc89
251
cpp
C++
lzham_assert.cpp
pg9182/tf2lzham
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
[ "MIT" ]
null
null
null
lzham_assert.cpp
pg9182/tf2lzham
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
[ "MIT" ]
null
null
null
lzham_assert.cpp
pg9182/tf2lzham
c11a1f50ebc85f9290ede436a1f8e2f34b646be0
[ "MIT" ]
null
null
null
// File: lzham_assert.cpp // See Copyright Notice and license at the end of lzham.h #include "lzham_core.h" void lzham_assert(const char* pExp, const char* pFile, unsigned line) { printf("%s(%u): Assertion failed: \"%s\"\n", pFile, line, pExp); }
27.888889
69
0.693227
pg9182
4a11b18559df526fb7ed452752e4b5ef3820c186
8,879
cpp
C++
src/client/input/InputPicker.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
6
2018-05-11T23:16:02.000Z
2019-06-13T01:35:07.000Z
src/client/input/InputPicker.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
33
2018-05-11T14:12:22.000Z
2022-03-12T00:55:25.000Z
src/client/input/InputPicker.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
1
2018-12-06T23:39:55.000Z
2018-12-06T23:39:55.000Z
#include <algorithm> #include <client/input/InputPicker.hpp> #include <common/logic/logic_service.hpp> #include <glm/gtc/matrix_transform.hpp> using namespace familyline::input; using namespace familyline::graphics; using namespace familyline::logic; InputPicker::InputPicker( Terrain* terrain, Window* win, SceneManager* sm, Camera* cam, ObjectManager* om) { this->_terrain = terrain; this->_win = win; this->_sm = sm; this->_cam = cam; this->_om = om; // ObjectEventEmitter::addListener(&oel); } /* Get cursor ray in screen space */ glm::vec4 InputPicker::GetCursorScreenRay() { int w = 0, h = 0, x = 0, y = 0; _win->getSize(w, h); Cursor::GetInstance()->GetPositions(x, y); // Create ray data. glm::vec4 ray = glm::vec4((2.0f * x) / w - 1.0f, 1.0f - (2.0f - y) / h, -1.0f, 1.0f); return ray; } /* Get cursor ray in eye space */ glm::vec4 InputPicker::GetCursorEyeRay() { glm::vec4 cur_eye = glm::inverse(_cam->GetProjectionMatrix()) * this->GetCursorScreenRay(); return glm::vec4(cur_eye.x, cur_eye.y, -1.0f, 0.0f); } /* Get cursor ray in world space */ glm::vec3 InputPicker::GetCursorWorldRay() { /* glm::vec4 cur_world = glm::inverse(_cam->GetViewMatrix()) * this->GetCursorEyeRay(); glm::vec3 cur_world3 = glm::vec3(cur_world.x, cur_world.y, cur_world.z); return glm::normalize(cur_world3); */ int x = 0, y = 0, w = 0, h = 0; _win->getSize(w, h); Cursor::GetInstance()->GetPositions(x, y); glm::vec3 cStart = glm::unProject( glm::vec3(x, h - y, 0), _cam->GetViewMatrix(), _cam->GetProjectionMatrix(), glm::vec4(0, 0, w, h)); glm::vec3 cEnd = glm::unProject( glm::vec3(x, h - y, 1), _cam->GetViewMatrix(), _cam->GetProjectionMatrix(), glm::vec4(0, 0, w, h)); glm::vec3 cur_world = glm::normalize(cEnd - cStart); return cur_world; } /* Check if we intersect with the terrain between between start and end */ bool InputPicker::CheckIfTerrainIntersect(glm::vec3 ray, float start, float end) { glm::vec3 pStart = _cam->GetPosition() + (ray * start); glm::vec3 pEnd = _cam->GetPosition() + (ray * end); if (pStart.y >= 0 && pEnd.y < 0) { return true; } return false; } void InputPicker::UpdateTerrainProjectedPosition() { glm::vec3 cur_world = this->GetCursorWorldRay(); /*printf("\ncamera_pos: %.4f %.4f %.4f, ray_pos: %.4f %.4f %.4f\n", _cam->GetPosition().x, _cam->GetPosition().y, _cam->GetPosition().z, cur_world.x, cur_world.y, cur_world.z); */ float prolong_near = 0.1f, prolong_far = 128.0f; float prolong_now = prolong_near + ((prolong_far - prolong_near) / 2.0f); glm::vec3 pHalf = glm::vec3(64, 0, 64); auto [width, height] = _terrain->getSize(); // printf("near: %.3f %.3f %.3f, far: %.3f %.3f %.3f, prolongs: { ", // pNear.x, pNear.y, pNear.z, pFar.x, pFar.y, pFar.z); for (int i = 0; i < MAX_PICK_ITERATIONS; i++) { /* Here, we'll check if the ray projection is above or below the terrain If we're above, we'll adjust pNear to that point If we're below, we'll adjust pFar to that point To check that, we simply check if pFar is under and pNear and pHalf are above */ if (this->CheckIfTerrainIntersect(cur_world, prolong_near, prolong_now)) prolong_far = prolong_now; else prolong_near = prolong_now; prolong_now = prolong_near + ((prolong_far - prolong_near) / 2.0f); pHalf = _cam->GetPosition() + (cur_world * prolong_now); // printf("%.2f (%.2f %.2f %.2f), ", prolong_now, pHalf.x, pHalf.y, pHalf.z); } glm::vec3 collide = _terrain->graphicalToGame(pHalf); /* Clamp collide to the terrain area */ if (collide.x >= width) collide.x = width - 1; if (collide.z >= height) collide.z = height - 1; if (collide.x < 0) collide.x = 0; if (collide.z < 0) collide.z = 0; auto pointHeight = _terrain->getHeightFromCoords(glm::vec2(collide.x, collide.z)); if (collide.x > 0 && collide.z > 0) collide.y = pointHeight; // printf(" }\nprol: %.2f, pos: %.3f %.3f %.3f, gamespace: %.3f %.3f %.3f\n\n", // 1.0f, pHalf.x, pHalf.y, pHalf.z, collide.x, collide.y, collide.z); _intersectedPosition = collide; } void InputPicker::UpdateIntersectedObject() { glm::vec3 direction = this->GetCursorWorldRay(); glm::vec3 origin = _cam->GetPosition(); const auto& olist = familyline::logic::LogicService::getObjectListener(); std::set<object_id_t> toAdd; std::set<object_id_t> toRemove; std::map<object_id_t, bool> aliveMap; auto aliveObjects = olist->getAliveObjects(); for (auto obj : this->poi_list) { // Stored object is still alive if (aliveObjects.find(obj.ID) != aliveObjects.end()) { aliveMap[obj.ID] = true; } // Stored object is not alive anymore if (aliveObjects.find(obj.ID) == aliveObjects.end()) { aliveMap[obj.ID] = false; toRemove.insert(obj.ID); } } for (auto objid : aliveObjects) { // We have a new stored object if (aliveMap.find(objid) == aliveMap.end()) { toAdd.insert(objid); } } for (auto objid : toRemove) { poi_list.erase(std::remove_if( poi_list.begin(), poi_list.end(), [&](const PickerObjectInfo& poi) { return poi.ID == objid; })); } for (auto objid : toAdd) { auto object = _om->get(objid).value(); if (!object->getLocationComponent()) { continue; } auto mesh = object->getLocationComponent()->mesh; poi_list.emplace_back(object->getPosition(), std::dynamic_pointer_cast<Mesh>(mesh), objid); } // Check the existing objects for (const PickerObjectInfo& poi : poi_list) { auto obj = _om->get(poi.ID); if (!obj) continue; auto osize = (*obj)->getSize(); auto gsize = _terrain->gameToGraphical( glm::vec3(osize.x, 0, osize.y)); if (!poi.mesh) continue; auto gpos = poi.mesh->getPosition(); glm::vec4 vmin = glm::vec4(-gsize.x/2, gpos.y, -gsize.z/2, 1); glm::vec4 vmax = glm::vec4(gsize.x/2, glm::max(gsize.x, gsize.z), gsize.z/2, 1); vmin = poi.mesh->getWorldMatrix() * vmin; vmax = poi.mesh->getWorldMatrix() * vmax; glm::min(vmin.y, 0.0f); glm::max(vmax.y, 0.0f); // glm::vec3 planePosX, planePosY, planePosZ; float tmin = -100000; float tmax = 100000; float dxmin, dxMax; if (direction.x != 0) { dxmin = (vmin.x - origin.x) / direction.x; dxMax = (vmax.x - origin.x) / direction.x; tmin = fmaxf(tmin, fminf(dxmin, dxMax)); tmax = fminf(tmax, fmaxf(dxmin, dxMax)); // printf("x: %.4f %.4f \t", dxmin, dxMax); if (tmax < tmin) continue; } if (direction.y != 0) { dxmin = (vmin.y - origin.y) / direction.y; dxMax = (vmax.y - origin.y) / direction.y; tmin = fmaxf(tmin, fminf(dxmin, dxMax)); tmax = fminf(tmax, fmaxf(dxmin, dxMax)); // printf("y: %.4f %.4f \t", dxmin, dxMax); if (tmax < tmin) continue; } if (direction.z != 0) { dxmin = (vmin.z - origin.z) / direction.z; dxMax = (vmax.z - origin.z) / direction.z; tmin = fmaxf(tmin, fminf(dxmin, dxMax)); tmax = fminf(tmax, fmaxf(dxmin, dxMax)); // printf("z: %.4f %.4f \t", dxmin, dxMax); if (tmax < tmin) continue; } // printf("total: %.4f %.4f\n", tmin, tmax); /* Ray misses */ if (tmin < 0) { continue; } /* Collided with both 3 axis! */ if (tmax >= tmin) { auto lobj = _om->get(poi.ID); if (!lobj.has_value()) return; _locatableObject = lobj.value(); if (!_locatableObject.expired()) return; } } _locatableObject = std::weak_ptr<GameObject>(); } /* Get position where the cursor collides with the terrain, in render coordinates */ glm::vec3 InputPicker::GetTerrainProjectedPosition() { return _terrain->gameToGraphical(_intersectedPosition); } /* Get position where the cursor collides with the terrain, in game coordinates */ glm::vec2 InputPicker::GetGameProjectedPosition() { glm::vec3 intGame = _intersectedPosition; return glm::vec2(intGame.x, intGame.z); } /* Get the object that were intersected by the cursor ray */ std::weak_ptr<GameObject> InputPicker::GetIntersectedObject() { return this->_locatableObject; }
31.485816
99
0.580696
arthurmco
4a1656a12f6b3fd4c0f8350d60bdddfc1e01306b
26,822
cpp
C++
packages/multiCam/src/obstacleDetection.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
2
2021-01-15T13:27:19.000Z
2021-08-04T08:40:52.000Z
packages/multiCam/src/obstacleDetection.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
null
null
null
packages/multiCam/src/obstacleDetection.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
5
2018-05-01T10:39:31.000Z
2022-03-25T03:02:35.000Z
// Copyright 2018-2020 Andre Pool (Falcons) // SPDX-License-Identifier: Apache-2.0 // Jan Feitsma, december 2019 #include "obstacleDetection.hpp" #include <math.h> #include "tracing.hpp" using namespace std; using namespace cv; obstacleDetection::obstacleDetection(cameraReceive *camRecv, configurator *conf, Dewarper *dewarp, preprocessor *prep, size_t type, size_t camIndex) { this->camRecv = camRecv; this->conf = conf; this->dewarp = dewarp; this->prep = prep; this->type = type; this->camIndex = camIndex; height = conf->getCameraHeight(); width = conf->getCameraWidth(); exportMutex.lock(); // initialize frames so even without running the update method the frames can be used by the viewer erodeFrame = Mat::zeros(height, width, CV_8UC1); dilateFrame = Mat::zeros(height, width, CV_8UC1); inRangeFrame = Mat::zeros(height, width, CV_8UC1); // make the result list empty so the first request does not get bogus data positions.clear(); positionsRemoteViewerExportMutex.unlock(); obstaclePointListExportMutex.unlock(); exportMutex.unlock(); busy = false; printCount = 0; exportMutex.lock(); for (size_t ii = 0; ii < height; ii++) { // create vector for the closest obstacle pixels closestPixels.push_back(-1); closestGroups.push_back(-1); } exportMutex.unlock(); } void obstacleDetection::keepGoing() { while (1) { update(); } } typedef enum closestState { CLOSEST_INIT = 0, CLOSEST_NOTHING, CLOSEST_FOUND, CLOSEST_PENDING, CLOSEST_STORE, } closestStateT; // try to find the closest line for obstacles // first get all closest obstacle points // then group them together // use these groups to split the dilated obstacle image, so the borders are separated // and even robot close to each other (but at a different distance) // NOTE: the camera is rotated, so the nearby axis the y axis (x = 0) void obstacleDetection::findClosestLineGroups() { // run through all lines for (size_t yy = 0; yy < height; yy++) { // get the closest pixel of this particular line // Note: the lock mutex is already set by the caller of this function closestPixels[yy] = -1; // default closest obstacle pixel not found for (size_t xx = 0; xx < width; xx++) { uchar pixelVal = inRangeFrame.at<uchar>(yy, xx); if (pixelVal != 0) { // found the obstacle pixel, store and goto next line closestPixels[yy] = xx; xx = width; // found it, go to next line } } } // now group the pixels, each group represents one obstacle // initialize the closestGroup vector, meaning the closest pixels are not related to any group for (size_t yy = 0; yy < height; yy++) { closestGroups[yy] = -1; // not assigned to any group } ssize_t groupIndex = 0; for (ssize_t yy0 = 0; yy0 < height - 1; yy0++) { ssize_t xx0 = closestPixels[yy0]; if (xx0 >= 0) { if (closestGroups[yy0] < 0) { // this pixel was not yet related to a group, assign to new group closestGroups[yy0] = groupIndex; groupIndex++; // prepare for next group } // determine distance to all of the remaining pixels for (ssize_t yy1 = yy0 + 1; yy1 < height; yy1++) { ssize_t xx1 = closestPixels[yy1]; if (xx1 >= 0) { double delta = sqrt(pow(xx0 - xx1, 2) + pow(yy0 - yy1, 2)); double threshold = (xx1 - 470.0) / -16.0; if (threshold > 15.0) { threshold = 15.0; } if (threshold < 3.0) { threshold = 3.0; } if (delta < threshold) { // this obstacle pixels is close to the yy0 obstacle pixels, assign to same group closestGroups[yy1] = closestGroups[yy0]; } } } } } // now we know for each closest pixel if it belongs to a group and if so to which group } // Search for obstacles in the related camera // Pixels are filtered by the Erode, Dilate and the minimum size // The dewarp function is used to convert the obstacle (bottom) camera pixels to x,y offset in mm // The x,y position is relative to the robot (and camera on that robot) // The camera is 90 degrees rotated, so the x mainly represents the distance between the // robot and the obstacle, while the y mainly represents the angle // An y of 0 means the obstacle is straight for the camera, and negative y means the obstacle // is at the left side of the camera and a positive y, the obstacle is at the right // side of the robot // The x,y Cartesian coordinate converted to Polar coordinates, to make them // easier to use as relative to the Robot // Note: The radius is measured from the closest yellow pixel, but because of the camera position, this // is roughly the same as the center of the obstacle. void obstacleDetection::update() { TRACE_FUNCTION(""); // get the pixels of the camera vector<linePointSt> cartesian; // wait for points, delivered by the receiver // Note: one point is actually a line (xBegin,y) and (xEnd,y) if (type == ballType) { printf("ERROR : obstacleDetection is not intended for ball detection\n"); exit(EXIT_FAILURE); } else if (type == ballFarType) { printf("ERROR : obstacleDetection is not intended for FAR ball detection\n"); exit(EXIT_FAILURE); } else if (type == obstacleType) { cartesian = camRecv->getObstaclePointsWait(camIndex); } else { printf("ERROR : type %zu unknown\n", type); exit( EXIT_FAILURE); } obstaclePointListExportMutex.lock(); obstaclePointList = cartesian; obstaclePointListExportMutex.unlock(); // construct "image" from received points { TRACE_SCOPE("CONSTRUCT_AND_EXPORT_OBSTACLE", ""); exportMutex.lock(); inRangeFrame = Mat::zeros(height, width, CV_8UC1); for (size_t ii = 0; ii < cartesian.size(); ii++) { int xBegin = cartesian[ii].xBegin; if (xBegin < conf->getBall(type).distanceOffset) { xBegin = conf->getBall(type).distanceOffset; } int xEnd = cartesian[ii].xEnd; int y = cartesian[ii].yBegin; // TODO: use yEnd to create a rectangle instead of line // TODO: set line width back to 1 if all lines are scanned in grabber (now only half the lines used) if (xEnd >= xBegin) { // xEnd can be lower the xBegin because of using the distance offset (mainly required for obstacles because of the camera cover) line(inRangeFrame, Point(xBegin, y), Point(xEnd, y), 255, 2, 0); } } // mask camera cover to prevent false obstacles (and fake balls) // create two triangles that block the fake obstacles // left triangle int blockColor = 0; Point blockTriangle[1][3]; blockTriangle[0][0] = Point(0, 0); blockTriangle[0][1] = Point(0, conf->getMask().leftCloseby); blockTriangle[0][2] = Point(conf->getMask().leftFarAway, 0); const Point* pptLeft[1] = { blockTriangle[0] }; int npt[] = { 3 }; fillPoly(inRangeFrame, pptLeft, npt, 1, blockColor, 0); // right triangle blockTriangle[0][0] = Point(0, ROI_HEIGHT - 1); blockTriangle[0][1] = Point(0, conf->getMask().rightCloseby); blockTriangle[0][2] = Point(conf->getMask().rightFarAway, ROI_HEIGHT - 1); const Point* pptRight[1] = { blockTriangle[0] }; fillPoly(inRangeFrame, pptRight, npt, 1, blockColor, 0); // determine obstacle groups from the closest by obstacle pixels if (type == obstacleType) { findClosestLineGroups(); } // typically there are points of 1 pixel wide, likely caused by the demosaicing in the FPGA erode(inRangeFrame, erodeFrame, conf->getBall(type).erode); // reduce // now cluster together what is left dilate(erodeFrame, dilateFrame, conf->getBall(type).dilate); // expand // use the closest by obstacle groups to separate the dilated frame, so the contours will not stretch // over multiple obstacles (e.g. black border) ssize_t groupIndexPrev = closestGroups[0]; for (ssize_t yy = 1; yy < height; yy++) { ssize_t groupIndex = closestGroups[yy]; // add a blocking line when the group is changing or no obstacle pixel found on line if ((groupIndexPrev != groupIndex) || (groupIndex == -1)) { groupIndexPrev = groupIndex; // make the blocking line wider if the dilate is wider to remove dilated pixels on the other side of the blocking line int lineWidth = conf->getBall(type).dilateSlider; line(dilateFrame, Point(0, yy), Point(width - 1, yy), 0, lineWidth); } } vector<vector<Point> > contours; vector<Vec4i> hierarchy; // determine contours that will encapsulate the clusters Mat tmp; dilateFrame.copyTo(tmp); // copy dilateFrame otherwise it will be modified by findContours findContours(tmp, contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, Point(0, 0)); positions.clear(); // start with empty list for (size_t ii = 0; ii < contours.size(); ii++) { // make a bounding rectangle around each contour to calculate the distance, center and amount of obstacle pixels Rect rect = boundingRect(contours.at(ii)); // determine the pixel closest by to the obstacle (radius) int xClosestBy = rect.x; // determine the center of the obstacle (azimuth) int yCenter = rect.y + rect.height / 2; // determine the amount of obstacle pixels inside the bounding rectangle int pixels = countNonZero(inRangeFrame(rect)); // convert from Cartesian to Polar int16_t xField = 0; int16_t yField = 0; obstacleSt polar; // diagnostics bool attemptedDewarp = false; bool usedDewarp = false; bool enoughPixels = pixels > conf->getBall(type).pixels; // the height of an obstacle (robot) is larger then the width // however there are cases when 2 robots are next to each other // so only reject when obstacle is really low // this reject the black border lines if (rect.height > (2 * rect.width)) { // note: camera is rotated enoughPixels = 0; } // close by obstacles should have a significant size // TODO: make use of (configurable) curve instead of fixed values if (xClosestBy < 25) { if (pixels < 6000) { // verify with falcons/data/internal/vision/multiCam/r2/cam0_20190705_084029.jpg enoughPixels = 0; } else { // printf("INFO : cam %zu obstacle x closest %d pixels %d\n", camIndex, xClosestBy, pixels); } } else if (xClosestBy < 50) { if (pixels < 4000) { enoughPixels = 0; } else { // printf("INFO : cam %zu obstacle x closest %d pixels %d\n", camIndex, xClosestBy, pixels); } } else if (xClosestBy < 100) { if (pixels < 3000) { enoughPixels = 0; } } else if (xClosestBy < 150) { if (pixels < 2000) { enoughPixels = 0; } } else if (xClosestBy < 200) { if (pixels < 1000) { enoughPixels = 0; } } // for farther away the configuration slider is used // check if there are enough pixels to qualify for a obstacle if (enoughPixels) { bool valid = false; polar.size = pixels; polar.xClosestBy = xClosestBy; polar.yCenter = yCenter; polar.rect = rect; // convert from camera dimensions (pixels) to field dimensions (meters) // obstacles are by definition ALWAYS on the floor (z == 0) // so we use dewarp (also used for line points) to determine the relative location of the ball float azimuthDewarp = 0.0; float elevationDewarp = 0.0; float radiusDewarpMm = FLT_MAX; if ((xClosestBy >= 0) && (xClosestBy < (ROI_WIDTH / 2)) && (yCenter < ROI_HEIGHT)) { // TODO: move the dewarp to he camRecv // the correct dewarp already selected on the multiCam level bool ok = dewarp->transformFloor(xClosestBy, yCenter, yField, xField); // xField and yField result in mm if (ok) { // dewarp is calibrated for the pixel input at center of the line, while the ball and obstacle detection // provide the first dilate pixel, compensate to provide the center of the ball or obstacle double xFieldRadiusCorrected = xField + conf->getBall(type).xCenter; // in mm radiusDewarpMm = sqrt(xFieldRadiusCorrected * xFieldRadiusCorrected + yField * yField); // in mm // the dewarp is calibrated for the lines, the xField is closest by // TODO: checkout why angle needs to be set negative over here // would expect the x and y would have the correct polarity and atan2 should then also be correct azimuthDewarp = -atan2(yField, xFieldRadiusCorrected); // polar.azimuth = -polar.azimuth - CV_PI/2.0; // new calibration uses inverted angles - 90 degrees // Note: the obstacleDetection is relative to it's own camera, so adding the 90 degrees per camera's will be performed // on the higher level elevationDewarp = atan2(-CAMERA_HEIGHT, 1e-3 * radiusDewarpMm); // yikes, careful with MM scaling ... valid = true; } // if xField attemptedDewarp = true; } // if xClosestBy // obstacle on the floor polar.azimuth = azimuthDewarp; polar.elevation = elevationDewarp; polar.radius = radiusDewarpMm; usedDewarp = true; if (valid) { char typeStr[32]; sprintf(typeStr, "obstacle"); // azimuth range: horizontal view angle is around -60 to 60 = 120 degrees (of which 90 is used) // however the camera cover of robot 4 generates obstacles with a azimuth of 77 degrees #define AZIMUTH 90.0 // elevation range: down -80 degrees to 80 degrees = 160 degree, robot 3 is -81 degrees, add some more headroor #define ELEVATION 85.0 if ((polar.azimuth < -(M_PI * AZIMUTH / 180.0)) || (polar.azimuth > (M_PI * AZIMUTH / 180.0))) { printf( "ERROR : cam %zu %s azimuth %5.1f out of range, elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.elevation < (-M_PI * ELEVATION / 180.0)) || (polar.elevation > ( M_PI * ELEVATION / 180.0))) { printf( "ERROR : cam %zu %s elevation %5.1f out of range, azimuth %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.elevation / M_PI, 180.0 * polar.azimuth / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.xClosestBy < 0) || (polar.xClosestBy >= ROI_WIDTH)) { printf( "ERROR : cam %zu %s x out of range azimuth %5.1f elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.yCenter < 0) || (polar.yCenter >= ROI_HEIGHT)) { printf( "ERROR : cam %zu %s y out of range azimuth %5.1f elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.rect.height < 0) || (polar.rect.height > ROI_HEIGHT)) { printf( "ERROR : cam %zu %s rect out of range azimuth %5.1f elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.size < 0) || (polar.size > (ROI_WIDTH * ROI_HEIGHT))) { printf( "ERROR : cam %zu %s size out of range azimuth %5.1f elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else if ((polar.radius < 0) || (polar.radius > 20000)) { printf( "ERROR : cam %zu %s radius out of range azimuth %5.1f elevation %5.1f radius %6.0f size %6d x closest by %4d y center %4d y width %4d\n", camIndex, typeStr, 180.0 * polar.azimuth / M_PI, 180.0 * polar.elevation / M_PI, polar.radius, polar.size, polar.xClosestBy, polar.yCenter, polar.rect.height); } else { // each camera should be able to detect 90 degrees (=> -45 degrees to 45 degrees) // because of tolerances a ball on the 45 degree line might be missed // with a range of 46 degrees a ball might be reported by 2 camera's // TODO: add function that removes double balls (or let world model deal with it) float azimuth = conf->getBall(type).azimuth; if ((polar.azimuth >= -azimuth) && (polar.azimuth <= azimuth)) { positions.push_back(polar); #ifdef NONO } else { printf("WARNING : cam %zu obstacle angle of %.0f degrees should be covered by other camera\n", camIndex, 180.0 * polar.azimuth / M_PI); #endif } // if polar. } // valid } // if enoughPixels } // for contours.size() // containment for compile warnings about not used diagnostics variables (void) attemptedDewarp; (void) usedDewarp; } // sort on size sort(positions.begin(), positions.end()); positionsRemoteViewerExportMutex.lock(); positionsRemoteViewer = positions; positionsRemoteViewerExportMutex.unlock(); exportMutex.unlock(); } if (positions.size() > 0) { // Notify new ball position notifyNewPos(); } busy = false; } vector<obstacleSt> obstacleDetection::getPositions() { exportMutex.lock(); std::vector<obstacleSt> retVal = positions; exportMutex.unlock(); return retVal; } vector<ssize_t> obstacleDetection::getClosestPixels() { exportMutex.lock(); std::vector<ssize_t> retVal = closestPixels; exportMutex.unlock(); return retVal; } vector<ssize_t> obstacleDetection::getClosestGroups() { exportMutex.lock(); std::vector<ssize_t> retVal = closestGroups; exportMutex.unlock(); return retVal; } vector<obstacleSt> obstacleDetection::getAndClearPositionsRemoteViewer() { positionsRemoteViewerExportMutex.lock(); std::vector<obstacleSt> retVal = positionsRemoteViewer; positionsRemoteViewer.clear(); positionsRemoteViewerExportMutex.unlock(); return retVal; } vector<obstacleSt> obstacleDetection::getPositionsExport() { vector<obstacleSt> retVal = getPositions(); for (size_t ii = 0; ii < retVal.size(); ii++) { double tmpAzimuth = retVal[ii].azimuth; // TODO: checkout if this is still needed, and if, convert to radians + conf->getExportOffset().rzBall; // normalize to prevent issues when running of range for remote viewer export retVal[ii].azimuth = fmod(2 * CV_PI + tmpAzimuth, 2 * CV_PI); retVal[ii].elevation = retVal[ii].elevation; // no fmod, kthxbye } return retVal; } cv::Mat obstacleDetection::getDilateFrame() { exportMutex.lock(); cv::Mat retVal = dilateFrame.clone(); exportMutex.unlock(); return retVal; } cv::Mat obstacleDetection::getErodeFrame() { exportMutex.lock(); cv::Mat retVal = erodeFrame.clone(); exportMutex.unlock(); return retVal; } cv::Mat obstacleDetection::getInRangeFrame() { exportMutex.lock(); cv::Mat retVal = inRangeFrame.clone(); exportMutex.unlock(); return retVal; } size_t obstacleDetection::getAmount() { size_t amount = 0; exportMutex.lock(); for (size_t ii = 0; ii < positions.size(); ii++) { if (positions[ii].size >= conf->getBall(type).pixels) { amount++; } } exportMutex.unlock(); return amount; } void obstacleDetection::notifyNewPos() { vector<obstacleSt> exportPos = getPositionsExport(); #ifndef NOROS if (type != obstacleType) { std::vector<ballPositionType> balls; for (uint ii = 0; ii < exportPos.size(); ii++) { double size = exportPos[ii].size; if (size > conf->getBall(type).pixels) { // Note: the world model needs to discard balls that are outside the field e.g. yellow something around the field // this is depending on the final position, which is determined by the world model instead of the localization on this robot double angleRad = exportPos[ii].azimuth;// counter clockwise angle between this robot shooter and the obstacle // cam 1 is left of cam 0 = counterclockwise angleRad += camIndex * CV_PI / 2.0; // camIndex * 90 degrees, every camera is 90 degrees rotated // from center of this robot to closest edge of ball, there is no need to add a ballRadius to radius\ (ball edge) because in field view the radius is very close to the center // exportPos[ii].radius is in mm, while Ros expects meters double radius = 0.001f * exportPos[ii].radius; double score = size / 100.0f; if (score > 1.0) { score = 1.0; } // cout << "ball index " << ii << " size " << size << " score " << score << " << " angle radians " << angleRad << " radius " << radius << endl; ballPositionType ball; ball.setAngle(angleRad); ball.setRadius(radius); ball.setConfidence(score); ball.setElevation(exportPos[ii].elevation); ball.setBallType(type); balls.push_back(ball); } } for (vector<observer*>::const_iterator iter = vecObservers.begin(); iter != vecObservers.end(); ++iter) { if (*iter != NULL) { (*iter)->update_own_ball_position(balls, conf->getBallLatencyOffset()); } } } else { std::vector<obstaclePositionType> obstacles; for (uint ii = 0; ii < exportPos.size(); ii++) { double size = exportPos[ii].size; if (size > conf->getBall(type).pixels) { // type is in this case obstacle // Note: the world model needs to discard balls that are outside the field e.g. yellow something around the field // this is depending on the final position, which is determined by the world model instead of the localization on this robot double angleRad = exportPos[ii].azimuth;// counter clockwise angle between this robot shooter and the obstacle // cam 1 is left of cam 0 = counterclockwise angleRad += camIndex * CV_PI / 2.0; // camIndex * 90 degrees, every camera is 90 degrees rotated // from center of this robot to closest edge of ball, there is no need to add a ballRadius to radius (ball edge) because in field view the radius is very close to the center // exportPos[ii].radius is in mm, while Ros expects meters double radius = 0.001f * exportPos[ii].radius; double score = size / 1000.0f; if (score > 1.0) { score = 1.0; } // cout << "ball index " << ii << " size " << size << " score " << score << " << " angle radians " << angleRad << " radius " << radius << endl; obstaclePositionType obstacle; obstacle.setAngle(angleRad); obstacle.setRadius(radius); obstacle.setConfidence(score); int color = 0; // 0 is black obstacle.setColor(color); obstacles.push_back(obstacle); } } for (vector<observer*>::const_iterator iter = vecObservers.begin(); iter != vecObservers.end(); ++iter) { if (*iter != NULL) { (*iter)->update_own_obstacle_position(obstacles, conf->getObstacleLatencyOffset()); } } } #endif } void obstacleDetection::attach(observer *observer) { vecObservers.push_back(observer); } void obstacleDetection::detach(observer *observer) { vecObservers.erase(std::remove(vecObservers.begin(), vecObservers.end(), observer), vecObservers.end()); } std::vector<linePointSt> obstacleDetection::getObstaclePoints() { obstaclePointListExportMutex.lock(); std::vector<linePointSt> retVal = obstaclePointList; obstaclePointListExportMutex.unlock(); return retVal; }
44.927973
190
0.594736
Falcons-Robocup
4a17238b90fd000f50b87eb59d7902c34bb96e19
965
cpp
C++
source/data_model/python/src/identity/object_id.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/data_model/python/src/identity/object_id.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/data_model/python/src/identity/object_id.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "../python_extension.hpp" #include "lue/info/identity/object_id.hpp" #include <pybind11/pybind11.h> namespace py = pybind11; using namespace pybind11::literals; namespace lue { namespace data_model { void init_object_id( py::module& module) { py::class_<ObjectID, same_shape::Value>( module, "ObjectID", R"( A class for storing the IDs of objects whose state does not change through time Use this class when object state is stored that does not change through time. The order of the IDs stored must match the order of the state stored. For example, when storing tree stem locations, the order of space points stored in the space domain must match the order of object IDs in the :class:`ObjectID` instance. You never have to create an :class:`ObjectID` instance yourself. :class:`Phenomenon` instances provide one. )") ; } } // namespace data_model } // namespace lue
24.125
74
0.700518
OliverSchmitz
4a1b0ba12f4518aaea6263a719ea6417392d33ea
1,902
cpp
C++
code/qttoolkit/importer/code/clip.cpp
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/qttoolkit/importer/code/clip.cpp
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/qttoolkit/importer/code/clip.cpp
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
#include "clip.h" namespace Importer { //------------------------------------------------------------------------------ /** */ Clip::Clip() { // empty } //------------------------------------------------------------------------------ /** */ Clip::~Clip() { // empty } //------------------------------------------------------------------------------ /** */ void Clip::SetName( const QString& name ) { this->name = name; } //------------------------------------------------------------------------------ /** */ const QString& Clip::GetName() const { return this->name; } //------------------------------------------------------------------------------ /** */ void Clip::SetStart( uint start ) { this->start = start; } //------------------------------------------------------------------------------ /** */ const uint Clip::GetStart() const { return this->start; } //------------------------------------------------------------------------------ /** */ void Clip::SetEnd( uint end ) { this->end = end; } //------------------------------------------------------------------------------ /** */ const uint Clip::GetEnd() const { return this->end; } //------------------------------------------------------------------------------ /** */ void Clip::SetPreInfinity( Clip::InfinityType infinityType ) { this->preInfinity = infinityType; } //------------------------------------------------------------------------------ /** */ const Clip::InfinityType Clip::GetPreInfinity() const { return this->preInfinity; } //------------------------------------------------------------------------------ /** */ void Clip::SetPostInfinity( Clip::InfinityType infinityType ) { this->postInfinity = infinityType; } //------------------------------------------------------------------------------ /** */ const Clip::InfinityType Clip::GetPostInfinity() const { return this->postInfinity; } }
17.135135
80
0.302839
gscept
4a1e2ead9d37ec79e2588268a92d9b2197f121fc
9,289
cpp
C++
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
DragonJoker/DatabaseConnector
502b136588b46119c2a0f4ed6b6623c0cc6715c2
[ "MIT" ]
2
2018-03-01T01:14:38.000Z
2019-10-27T13:29:18.000Z
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
DragonJoker/DatabaseConnector
502b136588b46119c2a0f4ed6b6623c0cc6715c2
[ "MIT" ]
null
null
null
Source/Plugin/MySql/Src/DatabaseStatementMySql.cpp
DragonJoker/DatabaseConnector
502b136588b46119c2a0f4ed6b6623c0cc6715c2
[ "MIT" ]
null
null
null
/************************************************************************//** * @file DatabaseStatementMySql.cpp * @author Sylvain Doremus * @version 1.0 * @date 3/20/2014 2:47:39 PM * * * @brief CDatabaseStatementMySql class definition. * * @details Describes a statement for MYSQL database. * ***************************************************************************/ #include "DatabaseMySqlPch.h" #include "DatabaseStatementMySql.h" #include "DatabaseConnectionMySql.h" #include "DatabaseMySql.h" #include "DatabaseParameterMySql.h" #include "ExceptionDatabaseMySql.h" #include <DatabaseStringUtils.h> #include <DatabaseRow.h> #include <mysql/mysql.h> BEGIN_NAMESPACE_DATABASE_MYSQL { static const String ERROR_MYSQL_MISSING_INITIALIZATION = STR( "Method Initialise must be called before calling method CreateParameter" ); static const String ERROR_MYSQL_CANT_CREATE_STATEMENT = STR( "Couldn't create the statement" ); static const String ERROR_MYSQL_LOST_CONNECTION = STR( "The statement has lost his connection" ); static const String ERROR_FIELD_RETRIEVAL = STR( "Field retrieval error" ); static const String INFO_MYSQL_BIND_PARAMETER_NAME = STR( "BindParameter : " ); static const String INFO_MYSQL_BIND_PARAMETER_VALUE = STR( ", Value : " ); static const String DEBUG_MYSQL_PREPARING_STATEMENT = STR( "Preparing statement 0x%08X" ); static const TChar * INFO_MYSQL_STATEMENT_PREPARATION = STR( "Statement preparation" ); static const TChar * INFO_MYSQL_STATEMENT_PARAMS_BINDING = STR( "Statement parameters binding" ); static const TChar * INFO_MYSQL_STATEMENT_RESET = STR( "Statement reset" ); static const String MYSQL_SQL_DELIM = STR( "?" ); static const String MYSQL_SQL_PARAM = STR( "@" ); static const String MYSQL_SQL_SET = STR( "SET @" ); static const String MYSQL_SQL_NULL = STR( " = NULL;" ); static const String MYSQL_SQL_SELECT = STR( "SELECT " ); static const String MYSQL_SQL_AS = STR( " AS " ); static const String MYSQL_SQL_COMMA = STR( "," ); CDatabaseStatementMySql::CDatabaseStatementMySql( DatabaseConnectionMySqlSPtr connection, const String & query ) : CDatabaseStatement( connection, query ) , _statement( NULL ) , _connectionMySql( connection ) , _paramsCount( 0 ) { } CDatabaseStatementMySql::~CDatabaseStatementMySql() { Cleanup(); } DatabaseParameterSPtr CDatabaseStatementMySql::DoCreateParameter( DatabaseValuedObjectInfosSPtr infos, EParameterType parameterType ) { DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection(); if ( !connection ) { DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION ); } DatabaseParameterMySqlSPtr parameter = std::make_shared< CDatabaseParameterMySql >( connection, infos, uint16_t( _arrayInParams.size() + 1 ), parameterType, std::make_unique< SValueUpdater >( this ) ); DatabaseParameterSPtr ret = DoAddParameter( parameter ); if ( ret && parameterType == EParameterType_IN ) { _arrayInParams.push_back( parameter ); } return ret; } EErrorType CDatabaseStatementMySql::DoInitialise() { DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection(); if ( !connection ) { DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION ); } EErrorType eReturn = EErrorType_ERROR; if ( !_query.empty() ) { _paramsCount = uint32_t( std::count( _query.begin(), _query.end(), STR( '?' ) ) ); _arrayQueries = StringUtils::Split( _query, STR( "?" ), _paramsCount + 1 ); } CLogger::LogDebug( ( Format( DEBUG_MYSQL_PREPARING_STATEMENT ) % this ).str() ); assert( _paramsCount == GetParametersCount() ); StringStream query; unsigned short i = 0; auto && itQueries = _arrayQueries.begin(); auto && itParams = DoGetParameters().begin(); auto && itParamsEnd = DoGetParameters().end(); _outInitialisers.clear(); _arrayOutParams.clear(); _outInitialisers.reserve( GetParametersCount() ); _arrayOutParams.reserve( GetParametersCount() ); _bindings.reserve( GetParametersCount() ); while ( itQueries != _arrayQueries.end() && itParams != itParamsEnd ) { query << ( *itQueries ); DatabaseParameterMySqlSPtr parameter = std::static_pointer_cast< CDatabaseParameterMySql >( *itParams ); if ( parameter->GetParamType() == EParameterType_OUT ) { query << MYSQL_SQL_PARAM + parameter->GetName(); DatabaseStatementSPtr stmt = connection->CreateStatement( MYSQL_SQL_SET + parameter->GetName() + MYSQL_SQL_NULL ); stmt->Initialise(); _outInitialisers.push_back( stmt ); _arrayOutParams.push_back( parameter ); } else if ( parameter->GetParamType() == EParameterType_IN ) { MYSQL_BIND bind = { 0 }; _bindings.push_back( bind ); query << MYSQL_SQL_DELIM; } else { query << MYSQL_SQL_PARAM + parameter->GetName(); DatabaseStatementSPtr stmt = connection->CreateStatement( MYSQL_SQL_SET + parameter->GetName() + STR( " = " ) + MYSQL_SQL_DELIM ); stmt->CreateParameter( parameter->GetName(), parameter->GetType(), parameter->GetLimits(), EParameterType_IN ); stmt->Initialise(); _inOutInitialisers.push_back( std::make_pair( stmt, parameter ) ); _arrayOutParams.push_back( parameter ); } ++i; ++itQueries; ++itParams; } while ( itQueries != _arrayQueries.end() ) { query << ( *itQueries ); ++itQueries; } _query = query.str(); if ( !_arrayOutParams.empty() ) { String sep; StringStream queryInOutParam; queryInOutParam << MYSQL_SQL_SELECT; for ( auto && parameter : _arrayOutParams ) { queryInOutParam << sep << MYSQL_SQL_PARAM << parameter.lock()->GetName() << MYSQL_SQL_AS << parameter.lock()->GetName(); sep = MYSQL_SQL_COMMA; } _stmtOutParams = connection->CreateStatement( queryInOutParam.str() ); _stmtOutParams->Initialise(); } _statement = mysql_stmt_init( connection->GetConnection() ); if ( _statement ) { eReturn = EErrorType_NONE; } else { DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_CANT_CREATE_STATEMENT ); } MySQLCheck( mysql_stmt_prepare( _statement, _query.c_str(), uint32_t( _query.size() ) ), INFO_MYSQL_STATEMENT_PREPARATION, EDatabaseExceptionCodes_StatementError, connection->GetConnection() ); MYSQL_RES * meta = mysql_stmt_param_metadata( _statement ); size_t index = 0; for ( auto && it : _arrayInParams ) { DatabaseParameterMySqlSPtr parameter = it.lock(); parameter->SetStatement( _statement ); parameter->SetBinding( &_bindings[index++] ); } MySQLCheck( mysql_stmt_bind_param( _statement, _bindings.data() ), INFO_MYSQL_STATEMENT_PARAMS_BINDING, EDatabaseExceptionCodes_StatementError, connection->GetConnection() ); return eReturn; } bool CDatabaseStatementMySql::DoExecuteUpdate() { DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection(); if ( !connection ) { DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION ); } DoPreExecute(); bool bReturn = connection->ExecuteUpdate( _statement ); if ( bReturn ) { DoPostExecute(); } return bReturn; } DatabaseResultSPtr CDatabaseStatementMySql::DoExecuteSelect() { DatabaseConnectionMySqlSPtr connection = DoGetMySqlConnection(); if ( !connection ) { DB_EXCEPT( EDatabaseExceptionCodes_StatementError, ERROR_MYSQL_LOST_CONNECTION ); } DoPreExecute(); DatabaseResultSPtr pReturn = connection->ExecuteSelect( _statement, _infos ); if ( pReturn ) { DoPostExecute(); } return pReturn; } void CDatabaseStatementMySql::DoCleanup() { _bindings.clear(); _arrayInParams.clear(); _arrayOutParams.clear(); _outInitialisers.clear(); _arrayQueries.clear(); _paramsCount = 0; _stmtOutParams.reset(); if ( _statement ) { mysql_stmt_close( _statement ); _statement = NULL; } } void CDatabaseStatementMySql::DoPreExecute() { for ( auto && it : _inOutInitialisers ) { DatabaseParameterSPtr parameter = it.second.lock(); if ( parameter->GetObjectValue().IsNull() ) { it.first->SetParameterNull( 0 ); } else { it.first->SetParameterValue( 0, static_cast< const CDatabaseValuedObject & >( *parameter ) ); } it.first->ExecuteUpdate(); } for ( auto && it : _outInitialisers ) { it->ExecuteUpdate(); } } void CDatabaseStatementMySql::DoPostExecute() { if ( !_arrayOutParams.empty() ) { DatabaseResultSPtr pReturn = _stmtOutParams->ExecuteSelect(); if ( pReturn && pReturn->GetRowCount() ) { DatabaseRowSPtr row = pReturn->GetFirstRow(); for ( auto && wparameter : _arrayOutParams ) { DatabaseParameterSPtr parameter = wparameter.lock(); if ( parameter->GetParamType() == EParameterType_INOUT || parameter->GetParamType() == EParameterType_OUT ) { DatabaseFieldSPtr field; try { field = row->GetField( parameter->GetName() ); } COMMON_CATCH( ERROR_FIELD_RETRIEVAL ) if ( field ) { parameter->SetValue( static_cast< const CDatabaseValuedObject & >( *field ) ); } } } } } MySQLCheck( mysql_stmt_reset( _statement ), INFO_MYSQL_STATEMENT_RESET, EDatabaseExceptionCodes_StatementError, DoGetMySqlConnection()->GetConnection() ); } } END_NAMESPACE_DATABASE_MYSQL
28.937695
203
0.704597
DragonJoker
4a221ff7b3f586bea67e1e0012279042d81bc237
2,053
cpp
C++
dev/Code/Framework/AzToolsFramework/Tests/PropertyIntSliderCtrlTests.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzToolsFramework/Tests/PropertyIntSliderCtrlTests.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzToolsFramework/Tests/PropertyIntSliderCtrlTests.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "PropertyIntCtrlCommonTests.h" #include <AzToolsFramework/UI/PropertyEditor/PropertyIntSliderCtrl.hxx> namespace UnitTest { using namespace AzToolsFramework; template <typename ValueType> using PropertySliderCtrlFixture = PropertyCtrlFixture<ValueType, PropertyIntSliderCtrl, IntSliderHandler>; TYPED_TEST_CASE(PropertySliderCtrlFixture, IntegerPrimtitiveTestConfigs); TYPED_TEST(PropertySliderCtrlFixture, PropertySliderCtrlHandlersCreated) { this->PropertyCtrlHandlersCreated(); } TYPED_TEST(PropertySliderCtrlFixture, PropertySliderCtrlWidgetsCreated) { this->PropertyCtrlWidgetsCreated(); } TYPED_TEST(PropertySliderCtrlFixture, SliderWidget_Minimum_ExpectQtWidgetLimits_Min) { this->Widget_Minimum_ExpectQtWidgetLimits_Min(); } TYPED_TEST(PropertySliderCtrlFixture, SliderWidget_Maximum_ExpectQtWidgetLimits_Max) { EXPECT_EQ(this->m_widget->maximum(), AzToolsFramework::QtWidgetLimits<TypeParam>::Max()); } TYPED_TEST(PropertySliderCtrlFixture, SliderHandlerMinMaxLimit_ModifyHandler_ExpectSuccessAndValidRangeLimitToolTipString) { this->HandlerMinMaxLimit_ModifyHandler_ExpectSuccessAndValidRangeLimitToolTipString(); } TYPED_TEST(PropertySliderCtrlFixture, SliderHandlerMinMaxLessLimit_ModifyHandler_ExpectSuccessAndValidLessLimitToolTipString) { this->HandlerMinMaxLessLimit_ModifyHandler_ExpectSuccessAndValidLessLimitToolTipString(); } } // namespace UnitTest
37.327273
129
0.789089
brianherrera
4a233bd65d10e1ffce66653b3d1f088b61feafc9
1,864
cpp
C++
Room.cpp
guyou/T-watch-2020
e68fb1c3171157bb943c1ebf8351f1d66411980a
[ "BSD-3-Clause" ]
74
2020-09-29T17:27:03.000Z
2022-03-31T08:04:13.000Z
Room.cpp
guyou/T-watch-2020
e68fb1c3171157bb943c1ebf8351f1d66411980a
[ "BSD-3-Clause" ]
36
2020-09-30T19:33:16.000Z
2021-04-18T03:31:32.000Z
Room.cpp
guyou/T-watch-2020
e68fb1c3171157bb943c1ebf8351f1d66411980a
[ "BSD-3-Clause" ]
23
2020-10-09T07:41:09.000Z
2021-12-06T10:13:35.000Z
/* # Maze Generator ### Date: 28 March 2018 ### Author: Pisica Alin */ #include "config.h" #include "DudleyWatch.h" #include "Room.h" using namespace std; Room::Room(int i, int j, int rw) { this->x = i; this->y = j; this->roomWidth = rw; walls[0] = true; walls[1] = true; walls[2] = true; walls[3] = true; visited = false; } void Room::removeWalls(Room &r) { if (this->x - r.x == -1) { this->removeWall(1); r.removeWall(3); } if (this->x - r.x == 1) { this->removeWall(3); r.removeWall(1); } if (this->y - r.y == -1) { this->removeWall(2); r.removeWall(0); } if (this->y - r.y == 1) { this->removeWall(0); r.removeWall(2); } } void Room::show(void) { int xCoord = this->x * roomWidth; int yCoord = this->y * roomWidth; if (this->walls[0]) { tft->drawLine(xCoord, yCoord, // top xCoord + this->roomWidth, yCoord, TFT_RED); } if (this->walls[1]) { // right tft->drawLine(xCoord + this->roomWidth, yCoord, xCoord + this->roomWidth, yCoord + this->roomWidth, TFT_RED); } if (this->walls[2]) { // bottom tft->drawLine(xCoord, yCoord + this->roomWidth, xCoord + this->roomWidth, yCoord + this->roomWidth, TFT_RED); } if (this->walls[3]) { // left tft->drawLine(xCoord, yCoord, xCoord, yCoord + this->roomWidth, TFT_RED); } } void Room::printWalls() { for (int i = 0; i < 4; i++) { std::cout << walls[i] << " "; } std::cout << "\n"; } void Room::removeWall(int w) { this->walls[w] = false; } bool Room::hasWall(int w) { return this->walls[w]; } void Room::visit(bool setact) { this->visited = setact; } int Room::getPositionInVector(int size) { return this->x * size + this->y; } int Room::getX() { return this->x; } int Room::getY() { return this->y; } bool Room::isVisited() { return this->visited; }
18.828283
65
0.574571
guyou
4a23773eea7ab8ed96529a1582dd03f3538b76a7
11,484
hpp
C++
iRODS/server/core/include/irods_resource_plugin.hpp
iychoi/cyverse-irods
0070b8677a82e763f1d940ae6537b1c8839a628a
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/core/include/irods_resource_plugin.hpp
iychoi/cyverse-irods
0070b8677a82e763f1d940ae6537b1c8839a628a
[ "BSD-3-Clause" ]
7
2019-12-02T17:55:49.000Z
2019-12-02T17:55:59.000Z
iRODS/server/core/include/irods_resource_plugin.hpp
benlazarine/cyverse-irods
2bf9cfae4c3a1062ffe2af92b1f086ddc5fce025
[ "BSD-3-Clause" ]
1
2015-02-19T18:30:33.000Z
2015-02-19T18:30:33.000Z
#ifndef ___IRODS_RESC_PLUGIN_HPP__ #define ___IRODS_RESC_PLUGIN_HPP__ // =-=-=-=-=-=-=- #include "irods_resource_constants.hpp" #include "irods_operation_wrapper.hpp" #include "irods_resource_plugin_context.hpp" #include <iostream> namespace irods { /// =-=-=-=-=-=-=- /// @brief typedef for resource maintenance operation for start / stop operations typedef error( *resource_maintenance_operation )( plugin_property_map&, resource_child_map& ); // =-=-=-=-=-=-=- /** * \author Jason M. Coposky * \brief * **/ class resource : public plugin_base { public: // =-=-=-=-=-=-=- /// @brief Constructors resource( const std::string&, // instance name const std::string& ); // context // =-=-=-=-=-=-=- /// @brief Destructor virtual ~resource(); // =-=-=-=-=-=-=- /// @brief copy ctor resource( const resource& _rhs ); // =-=-=-=-=-=-=- /// @brief Assignment Operator - necessary for stl containers resource& operator=( const resource& _rhs ); // =-=-=-=-=-=-=- /// @brief override from parent plugin_base virtual error delay_load( void* _h ); // =-=-=-=-=-=-=- /// @brief get a property from the map if it exists. catch the exception in the case where // the template types may not match and return success/fail template< typename T > error get_property( const std::string& _key, T& _val ) { error ret = properties_.get< T >( _key, _val ); return PASSMSG( "resource::get_property", ret ); } // get_property // =-=-=-=-=-=-=- /// @brief set a property in the map template< typename T > error set_property( const std::string& _key, const T& _val ) { error ret = properties_.set< T >( _key, _val ); return PASSMSG( "resource::set_property", ret ); } // set_property // =-=-=-=-=-=-=- /// @brief interface to add and remove children using the zone_name::resource_name virtual error add_child( const std::string&, const std::string&, resource_ptr ); virtual error remove_child( const std::string& ); virtual int num_children() { return children_.size(); } virtual bool has_child( const std::string& _name ) { return children_.has_entry( _name ); } // =-=-=-=-=-=-=- /// @brief interface to get and set a resource's parent pointer virtual error set_parent( const resource_ptr& ); virtual error get_parent( resource_ptr& ); // =-=-=-=-=-=-=- /// @brief interface to set start / stop functions void set_start_operation( const std::string& ); void set_stop_operation( const std::string& ); // =-=-=-=-=-=-=- /// @brief interface to call start / stop functions error start_operation( void ) { return ( *start_operation_ )( properties_, children_ ); } error stop_operation( void ) { return ( *stop_operation_ )( properties_, children_ ); } // =-=-=-=-=-=-=- /// @brief default start operation static error default_start_operation( plugin_property_map&, resource_child_map& ) { return SUCCESS(); }; // =-=-=-=-=-=-=- /// @brief default stop operation static error default_stop_operation( plugin_property_map&, resource_child_map& ) { return SUCCESS(); }; // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 0 param error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call( ctx ); } // call - // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 1 param template< typename T1 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1 >( ctx, _t1 ); } // call - T1 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 2 params template< typename T1, typename T2 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2 >( ctx, _t1, _t2 ); } // call - T1, T2 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 3 params template< typename T1, typename T2, typename T3 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3 >( ctx, _t1, _t2, _t3 ); } // call - T1, T2, T3 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 4 params template< typename T1, typename T2, typename T3, typename T4 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3, T4 _t4 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3, T4 >( ctx, _t1, _t2, _t3, _t4 ); } // call - T1, T2, T3, T4 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 5 params template< typename T1, typename T2, typename T3, typename T4, typename T5 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3, T4 _t4, T5 _t5 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3, T4, T5 >( ctx, _t1, _t2, _t3, _t4, _t5 ); } // call - T1, T2, T3, T4, T5 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 6 params template< typename T1, typename T2, typename T3, typename T4, typename T5, typename T6 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3, T4 _t4, T5 _t5, T6 _t6 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3, T4, T5, T6 >( ctx, _t1, _t2, _t3, _t4, _t5, _t6 ); } // call - T1, T2, T3, T4, T5, T6 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 7 params template< typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3, T4 _t4, T5 _t5, T6 _t6, T7 _t7 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3, T4, T5, T6, T7 >( ctx, _t1, _t2, _t3, _t4, _t5, _t6, _t7 ); } // call - T1, T2, T3, T4, T5, T6, T7 // =-=-=-=-=-=-=- /// @brief delegate the call to the operation in question to the operation wrapper, with 8 params template< typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8 > error call( rsComm_t* _comm, const std::string& _op, irods::first_class_object_ptr _obj, T1 _t1, T2 _t2, T3 _t3, T4 _t4, T5 _t5, T6 _t6, T7 _t7, T8 _t8 ) { resource_plugin_context ctx( properties_, _obj, "", _comm, children_ ); return operations_[ _op ].call< T1, T2, T3, T4, T5, T6, T7, T8 >( ctx, _t1, _t2, _t3, _t4, _t5, _t6, _t7, _t8 ); } // call - T1, T2, T3, T4, T5, T6, T7, T8 protected: // =-=-=-=-=-=-=- /// @brief Start / Stop functions - can be overwritten by plugin devs // called when a plugin is loaded or unloaded for init / cleanup std::string start_opr_name_; resource_maintenance_operation start_operation_; std::string stop_opr_name_; resource_maintenance_operation stop_operation_; // =-=-=-=-=-=-=- /// @brief Pointers to Child and Parent Resources resource_child_map children_; resource_ptr parent_; // =-=-=-=-=-=-=- /// @brief operations to be loaded from the plugin lookup_table< operation_wrapper > operations_; }; // class resource // =-=-=-=-=-=-=- // given the name of a resource, try to load the shared object error load_resource_plugin( resource_ptr&, // plugin const std::string, // plugin name const std::string, // instance name const std::string ); // context string }; // namespace irods #endif // ___IRODS_RESC_PLUGIN_HPP__
38.797297
126
0.485023
iychoi
4a245dc052d196b548942a4e87f9c62f67ef5f5b
2,566
hpp
C++
app/src/main/cpp/core/CCSmartPtr.hpp
imengyu/VR720
256a5da596ed19736d3c0a44c401f2ea21c2c30b
[ "MIT" ]
4
2021-06-29T12:27:17.000Z
2022-03-29T00:59:47.000Z
app/src/main/cpp/core/CCSmartPtr.hpp
imengyu/VR720
256a5da596ed19736d3c0a44c401f2ea21c2c30b
[ "MIT" ]
null
null
null
app/src/main/cpp/core/CCSmartPtr.hpp
imengyu/VR720
256a5da596ed19736d3c0a44c401f2ea21c2c30b
[ "MIT" ]
2
2021-06-29T12:36:44.000Z
2022-03-29T00:59:49.000Z
// // Created by roger on 2020/10/30. // #ifndef VR720_CCSMARTPTR_HPP #define VR720_CCSMARTPTR_HPP #include <unordered_map> //模板类作为友元时要先有声明 template <typename T> class CCSmartPtr; //辅助类 class CCUPtr { public: //构造函数的参数为基础对象的指针 CCUPtr(void* ptr); //析构函数 ~CCUPtr(); //引用计数 int count; //基础对象指针 void *p; }; //指针池 class CCPtrPool { public: std::unordered_map<void*, CCUPtr*> pool; static bool IsStaticPoolCanUse(); static CCPtrPool* GetStaticPool(); static void InitPool(); static void ReleasePool(); CCUPtr* GetPtr(void* ptr); CCUPtr* AddPtr(void* ptr); CCUPtr* AddRefPtr(void* ptr); CCUPtr* RemoveRefPtr(void* ptr); void ReleasePtr(void* ptr); void ClearUnUsedPtr(); void ReleaseAllPtr(); }; #define CCPtrPoolStatic CCPtrPool::GetStaticPool() #define CCPtrPoolStaticCanUse CCPtrPool::IsStaticPoolCanUse() //智能指针类 template <typename T> class CCSmartPtr { private: T* ptr = nullptr; CCUPtr* rp = nullptr; //辅助类对象指针 public: CCSmartPtr() { ptr = nullptr; if(CCPtrPoolStaticCanUse) rp = CCPtrPoolStatic->AddPtr(nullptr); } //构造函数 CCSmartPtr(T *srcPtr) { ptr = srcPtr; if(CCPtrPoolStaticCanUse) rp = CCPtrPoolStatic->AddPtr(srcPtr); } //复制构造函数 CCSmartPtr(const CCSmartPtr<T> &sp) { ptr = sp.ptr; if(CCPtrPoolStaticCanUse) rp = CCPtrPoolStatic->AddRefPtr(sp.ptr); } //重载赋值操作符 CCSmartPtr& operator = (const CCSmartPtr<T>& rhs) { if(CCPtrPoolStaticCanUse) CCPtrPoolStatic->RemoveRefPtr(ptr); ptr = rhs.ptr; if(CCPtrPoolStaticCanUse) rp = CCPtrPoolStatic->AddRefPtr(ptr); return *this; } T & operator *() const { //重载*操作符 return *ptr; } T* operator ->() const { //重载->操作符 return ptr; } bool IsNullptr() const { return ptr == nullptr; } T* GetPtr() const { return ptr; } int CheckRef() { if (rp) return rp->count; return 0; } int AddRef() { if (rp) return ++rp->count; return 0; } void ForceRelease() { if(CCPtrPoolStaticCanUse) CCPtrPool::GetStaticPool()->ReleasePtr(ptr); ptr = nullptr; *rp = nullptr; } ~CCSmartPtr() { //析构函数 if(CCPtrPoolStaticCanUse) CCPtrPoolStatic->RemoveRefPtr(ptr); ptr = nullptr; rp = nullptr; } }; #endif //VR720_CCSMARTPTR_HPP
19.891473
61
0.581839
imengyu
4a2542f273d1a78e7a1b2055cf15342bb19ca5ec
6,574
cpp
C++
Unix/tests/micxx/test_array.cpp
Beguiled/omi
1c824681ee86f32314f430db972e5d3938f10fd4
[ "MIT" ]
165
2016-08-18T22:06:39.000Z
2019-05-05T11:09:37.000Z
Unix/tests/micxx/test_array.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
409
2016-08-18T20:52:56.000Z
2019-05-06T10:03:11.000Z
Unix/tests/micxx/test_array.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
72
2016-08-23T02:30:08.000Z
2019-04-30T22:57:03.000Z
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ #include <ut/ut.h> #include <micxx/array.h> #include <micxx/types.h> #include <pal/atomic.h> using namespace mi; NitsSetup(TestArraySetup) NitsEndSetup NitsCleanup(TestArraySetup) NitsEndCleanup //union AlignmentStruct { // void* p; // Uint64 i; //}; NitsTestWithSetup(TestArrayCtor, TestArraySetup) { const char s[] = "string1"; Array<char> v1(s, sizeof(s)); UT_ASSERT( strcmp(s, v1.GetData()) == 0); UT_ASSERT( v1.GetSize() == sizeof(s)); // default ctor Array<char> v2; UT_ASSERT( v2.GetData() == 0); UT_ASSERT( v2.GetSize() == 0); // array ctor with 0 elements Array<char> v3(s, 0); UT_ASSERT( v3.GetData() == 0); UT_ASSERT( v3.GetSize() == 0); } NitsEndTest NitsTestWithSetup(TestAccessOperator, TestArraySetup) { unsigned int sample[] = {1,2,3}; Array<unsigned int> v(sample,3); UT_ASSERT( v.GetSize() == 3); UT_ASSERT( v[0] == 1 ); UT_ASSERT( v[1] == 2 ); UT_ASSERT( v[2] == 3 ); } NitsEndTest template< typename TYPE, size_t AligmentSize> static void TestDataAlignmentT() { Array<TYPE> v; v.PushBack( TYPE() ); UT_ASSERT(v.GetSize() == 1); UT_ASSERT(((long)v.GetData()) % AligmentSize == 0); } struct AlignmentTestStruct { char c[21]; void*p; }; NitsTestWithSetup(TestDataAlignment, TestArraySetup) { TestDataAlignmentT<char,sizeof(char)>(); TestDataAlignmentT<long,sizeof(long)>(); TestDataAlignmentT<Uint64,sizeof(void*)>(); TestDataAlignmentT<void*,sizeof(void*)>(); TestDataAlignmentT<int,sizeof(int)>(); TestDataAlignmentT<short int,sizeof(short int)>(); TestDataAlignmentT<AlignmentTestStruct,sizeof(void*)>(); } NitsEndTest struct TestCreateDestroyClass{ bool m_created; bool m_destroyed; static volatile ptrdiff_t m_ctorCalls; static volatile ptrdiff_t m_dtorCalls; String s; TestCreateDestroyClass() { s = MI_T("1"); m_created = true; m_destroyed = false; Atomic_Inc(&m_ctorCalls); } TestCreateDestroyClass(const TestCreateDestroyClass& x) { Atomic_Inc(&m_ctorCalls); *this = x; } ~TestCreateDestroyClass() { UT_ASSERT(isValid()); m_created = false; m_destroyed = true; Atomic_Inc(&m_dtorCalls); } bool isValid()const {return m_created && !m_destroyed && s == MI_T("1");} }; volatile ptrdiff_t TestCreateDestroyClass::m_ctorCalls = 0; volatile ptrdiff_t TestCreateDestroyClass::m_dtorCalls = 0; static void TestAllItemsAreValid( const Array<TestCreateDestroyClass>& v ) { for( Uint32 i = 0; i < v.GetSize(); i++ ) { UT_ASSERT(v[i].isValid()); } } NitsTestWithSetup(TestCreatingDestroyingObjects, TestArraySetup) { Array<TestCreateDestroyClass> v, v2; v.Resize(10); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v.PushBack( TestCreateDestroyClass() ); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v2 = v; TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v.PushBack( TestCreateDestroyClass() ); UT_ASSERT(v.GetSize() == 12); UT_ASSERT(v2.GetSize() == 11); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v.Delete(0); v2.Delete(10); UT_ASSERT(v.GetSize() == 11); UT_ASSERT(v2.GetSize() == 10); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v[1] = v2[4]; TestAllItemsAreValid(v); TestAllItemsAreValid(v2); } NitsEndTest NitsTestWithSetup(TestClear, TestArraySetup) { Array<TestCreateDestroyClass> v, v2; v.PushBack(TestCreateDestroyClass()); v2 = v; v2.Resize(2); UT_ASSERT(v.GetSize() == 1); UT_ASSERT(v2.GetSize() == 2); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); v2.Clear(); UT_ASSERT(v.GetSize() == 1); UT_ASSERT(v2.GetSize() == 0); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); } NitsEndTest NitsTestWithSetup(TestResize, TestArraySetup) { Array<TestCreateDestroyClass> v, v2; v.Resize(3); v2 = v; v2.Resize(3); UT_ASSERT(v.GetSize() == 3); UT_ASSERT(v2.GetSize() == 3); TestAllItemsAreValid(v); TestAllItemsAreValid(v2); } NitsEndTest NitsTestWithSetup(TestResizeWithRealloc, TestArraySetup) { Array<TestCreateDestroyClass> v, v2; v.Resize(3); UT_ASSERT(v.GetSize() == 3); TestAllItemsAreValid(v); // resize to big number to trigger re-alloc v.Resize(3000); UT_ASSERT(v.GetSize() == 3000); TestAllItemsAreValid(v); } NitsEndTest NitsTestWithSetup(TestAssignEmpty, TestArraySetup) { Array<TestCreateDestroyClass> v, v2; v.Resize(3); v = v2; UT_ASSERT(v.GetSize() == 0); UT_ASSERT(v2.GetSize() == 0); } NitsEndTest NitsTestWithSetup(TestDeleteTheOnlyOne, TestArraySetup) { Array<TestCreateDestroyClass> v; v.Resize(1); v.Delete(0); UT_ASSERT(v.GetSize() == 0); } NitsEndTest NitsTestWithSetup(TestResizeToShrink, TestArraySetup) { Array<TestCreateDestroyClass> v; v.Resize(100); v.Resize(10); UT_ASSERT(v.GetSize() == 10); TestAllItemsAreValid(v); } NitsEndTest NitsTestWithSetup(TestCtorDtorBalance, TestArraySetup) { ptrdiff_t ctor, dtor; ctor = Atomic_Read(&TestCreateDestroyClass::m_ctorCalls); dtor = Atomic_Read(&TestCreateDestroyClass::m_dtorCalls); UT_ASSERT_EQUAL(ctor, dtor); } NitsEndTest NitsTestWithSetup(TestGetWritableData, TestArraySetup) { Array< int > v; v.Resize(3); v.GetWritableData() [0] = 0; v.GetWritableData() [1] = 1; v.GetWritableData() [2] = 2; UT_ASSERT(0 == v[0]); UT_ASSERT(1 == v[1]); UT_ASSERT(2 == v[2]); } NitsEndTest NitsTestWithSetup(TestInlineCOW, TestArraySetup) { Array< int > v; v.PushBack(0); Array< int > v2 = v; v2[0] = 1; v.PushBack(1); UT_ASSERT(0 == v[0]); UT_ASSERT(1 == v[1]); UT_ASSERT(1 == v2[0]); UT_ASSERT(v.GetSize() == 2); UT_ASSERT(v2.GetSize() == 1); } NitsEndTest NitsTestWithSetup(TestInlineCOWFromEmptyVector, TestArraySetup) { Array< int > v; int* p = v.GetWritableData(); UT_ASSERT(0 == p); UT_ASSERT(v.GetSize() == 0); } NitsEndTest // simple type // alignment // should be the last test - verifies balance of ctor/dtor
19.278592
80
0.635686
Beguiled
4a266040bbee1fab1478724187f55db0d23f53f4
4,382
cpp
C++
cpp/cpp_typecheck_enum_type.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
cpp/cpp_typecheck_enum_type.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
cpp/cpp_typecheck_enum_type.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
/*******************************************************************\ Module: C++ Language Type Checking Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include <i2string.h> #include <arith_tools.h> #include <ansi-c/c_qualifiers.h> #include "cpp_typecheck.h" #include "cpp_enum_type.h" /*******************************************************************\ Function: cpp_typecheckt::typecheck_enum_body Inputs: Outputs: Purpose: \*******************************************************************/ void cpp_typecheckt::typecheck_enum_body(symbolt &enum_symbol) { typet &type=enum_symbol.type; exprt &body=static_cast<exprt &>(type.add("body")); irept::subt &components=body.get_sub(); typet enum_type("symbol"); enum_type.identifier(enum_symbol.name); mp_integer i=0; Forall_irep(it, components) { const irep_idt &name=it->name(); if(it->find("value").is_not_nil()) { exprt &value=static_cast<exprt &>(it->add("value")); typecheck_expr(value); make_constant_index(value); if(to_integer(value, i)) throw "failed to produce integer for enum"; } exprt final_value("constant", enum_type); final_value.value(integer2string(i)); symbolt symbol; symbol.name=id2string(enum_symbol.name)+"::"+id2string(name); symbol.base_name=name; symbol.value.swap(final_value); symbol.location=static_cast<const locationt &>(it->find("#location")); symbol.mode="C++"; // All types are c++ types symbol.module=module; symbol.type=enum_type; symbol.is_type=false; symbol.is_macro=true; symbolt *new_symbol; if(context.move(symbol, new_symbol)) throw "cpp_typecheckt::typecheck_enum_body: context.move() failed"; cpp_idt &scope_identifier= cpp_scopes.put_into_scope(*new_symbol); scope_identifier.id_class=cpp_idt::SYMBOL; ++i; } } /*******************************************************************\ Function: cpp_typecheckt::typecheck_enum_type Inputs: Outputs: Purpose: \*******************************************************************/ void cpp_typecheckt::typecheck_enum_type(typet &type) { // first save qualifiers c_qualifierst qualifiers; qualifiers.read(type); // these behave like special struct types // replace by type symbol cpp_enum_typet &enum_type=to_cpp_enum_type(type); bool has_body=enum_type.has_body(); std::string base_name=id2string(enum_type.get_name()); bool anonymous=base_name.empty(); bool tag_only_declaration=enum_type.get_tag_only_declaration(); if(anonymous) base_name="#anon"+i2string(anon_counter++); cpp_scopet &dest_scope= tag_scope(base_name, has_body, tag_only_declaration); const irep_idt symbol_name= dest_scope.prefix+"tag."+base_name; // check if we have it symbolt* previous_symbol = context.find_symbol(symbol_name); if(previous_symbol != nullptr) { // we do! symbolt &symbol = *previous_symbol; if(has_body) { err_location(type); str << "error: enum symbol `" << base_name << "' declared previously" << std::endl; str << "location of previous definition: " << symbol.location << std::endl; throw 0; } } else if(has_body) { std::string pretty_name= cpp_scopes.current_scope().prefix+base_name; symbolt symbol; symbol.name=symbol_name; symbol.base_name=base_name; symbol.value.make_nil(); symbol.location=type.location(); symbol.mode="C++"; // All types are c++ types. symbol.module=module; symbol.type.swap(type); symbol.is_type=true; symbol.is_macro=false; symbol.pretty_name=pretty_name; // move early, must be visible before doing body symbolt *new_symbol; if(context.move(symbol, new_symbol)) throw "cpp_typecheckt::typecheck_enum_type: context.move() failed"; // put into scope cpp_idt &scope_identifier= cpp_scopes.put_into_scope(*new_symbol); scope_identifier.id_class=cpp_idt::CLASS; typecheck_enum_body(*new_symbol); } else { err_location(type); str << "use of enum `" << base_name << "' without previous declaration"; throw 0; } // create type symbol type=typet("symbol"); type.identifier(symbol_name); qualifiers.write(type); }
23.945355
74
0.620949
holao09
4a27d81860c96ee4d46eaac5afc22be73258a520
3,692
cpp
C++
src/gameobject/script.cpp
LePtitDev/gamengin
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
[ "BSD-3-Clause" ]
null
null
null
src/gameobject/script.cpp
LePtitDev/gamengin
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
[ "BSD-3-Clause" ]
null
null
null
src/gameobject/script.cpp
LePtitDev/gamengin
f0b2c966a96df5b56eb50fd0fb79eb14a68b859a
[ "BSD-3-Clause" ]
null
null
null
#include "script.h" #include "gameobject.h" #include "../assets/assets.h" ScriptComponent::ScriptComponent(GameObject *parent) : Component(parent), started(false) { script.loadLibScript(); } const char * ScriptComponent::getScriptName() const { return scriptName.c_str(); } bool ScriptComponent::assign(const char * name) { Asset * asset = Asset::Find(name); if (asset == 0 || asset->getData<std::string>() == 0) return false; scriptName = name; script.load(asset->getData<std::string>()->c_str()); LuaScript::Variable vr; vr.type = LuaScript::VariableType::POINTER; vr.v_pointer = (void *)&gameObject(); script.createVariable("this", vr); script.execute(); return true; } void ScriptComponent::update() { if (!started && script.getVariable("start").type == LuaScript::VariableType::FUNCTION) script.callFunction("start", 0, 0); started = true; if (script.getVariable("update").type == LuaScript::VariableType::FUNCTION) script.callFunction("update", 0, 0); } void ScriptComponent::keyPressEvent(QKeyEvent * event) { if (script.getVariable("keyPress").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable key; key.type = LuaScript::INTEGER; key.v_integer = event->key(); script.callFunction("keyPress", &key, 1); } } void ScriptComponent::keyReleaseEvent(QKeyEvent * event) { if (script.getVariable("keyRelease").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable key; key.type = LuaScript::INTEGER; key.v_integer = event->key(); script.callFunction("keyRelease", &key, 1); } } void ScriptComponent::mousePressEvent(QMouseEvent * event) { if (script.getVariable("mousePress").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable args[3]; args[0].type = LuaScript::INTEGER; args[0].v_integer = (int)event->button(); args[1].type = LuaScript::INTEGER; args[1].v_integer = (int)event->x(); args[2].type = LuaScript::INTEGER; args[2].v_integer = (int)event->y(); script.callFunction("mousePress", args, 3); } } void ScriptComponent::mouseReleaseEvent(QMouseEvent * event) { if (script.getVariable("mouseRelease").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable args[3]; args[0].type = LuaScript::INTEGER; args[0].v_integer = (int)event->button(); args[1].type = LuaScript::INTEGER; args[1].v_integer = (int)event->x(); args[2].type = LuaScript::INTEGER; args[2].v_integer = (int)event->y(); script.callFunction("mouseRelease", args, 3); } } void ScriptComponent::mouseMoveEvent(QMouseEvent * event) { if (script.getVariable("mouseMove").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable args[2]; args[0].type = LuaScript::INTEGER; args[0].v_integer = (int)event->x(); args[1].type = LuaScript::INTEGER; args[1].v_integer = (int)event->y(); script.callFunction("mouseMove", args, 2); } } void ScriptComponent::wheelEvent(QWheelEvent * event) { if (script.getVariable("wheel").type == LuaScript::VariableType::FUNCTION) { LuaScript::Variable arg; arg.type = LuaScript::INTEGER; arg.v_integer = event->delta(); script.callFunction("wheel", &arg, 1); } } void ScriptComponent::destroy() { removeComponent(); delete this; } void ScriptComponent::clone(GameObject * c) { ScriptComponent * s = c->addComponent<ScriptComponent>(); if (scriptName != "") s->assign(scriptName.c_str()); }
32.964286
90
0.637866
LePtitDev
4a289bd2736decc8b8c7543b4098a3ffbf5db92e
1,389
hpp
C++
header/FemaleCharacter.hpp
digladieux/TP5_SMA
450153930410982c79dc79c5694885268fd4a04d
[ "Apache-2.0" ]
null
null
null
header/FemaleCharacter.hpp
digladieux/TP5_SMA
450153930410982c79dc79c5694885268fd4a04d
[ "Apache-2.0" ]
null
null
null
header/FemaleCharacter.hpp
digladieux/TP5_SMA
450153930410982c79dc79c5694885268fd4a04d
[ "Apache-2.0" ]
null
null
null
/** * \file FemaleCharacter.hpp * \author Gladieux Cunha Dimitri & Gonzales Florian * \brief Fichier d'en-tete du fichier source FemaleCharacter.cpp * \date 2018-12-03 */ #ifndef FEMALE_CHARACTER_HPP #define FEMALE_CHARACTER_HPP #include "Character.hpp" #include "Date.hpp" /** * \class FemaleCharacter * \brief Un personnage feminin herite des attributs et methodes d'un personnage. Le but d'un personnage feminin est de donner naissance a des enfants */ class FemaleCharacter : public Character { private: unsigned int baby_per_pregnancy; /*! Nombre de bebe par couche */ Date pregnancy_time; /*! Nombre de mois avant la couche */ unsigned int menopause; /*! Age ou le personnage feminin ne pourra plus faire d'enfant */ public: FemaleCharacter(const Date &, unsigned int team = 0); FemaleCharacter(const Date &, unsigned int, unsigned int, unsigned int team = 0, unsigned int life = 200); FemaleCharacter(const FemaleCharacter &); ~FemaleCharacter(); FemaleCharacter &operator=(const FemaleCharacter &) ; unsigned int getBabyPerPregnancy() const noexcept; Date getPregnancyTime() const noexcept; void randomBabyPerPregnancy() noexcept; void setTimePregnancy(const Date &date) noexcept; unsigned int getMonthPregnancy(const Date &) const; unsigned int getMenopause() const noexcept; }; #endif
33.071429
151
0.726422
digladieux
4a2a8af9ca1cafbeee0869be2642203fd4e19cea
11,404
cpp
C++
src/js/jit/JitOptions.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
149
2018-12-23T09:08:00.000Z
2022-02-02T09:18:38.000Z
src/js/jit/JitOptions.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
null
null
null
src/js/jit/JitOptions.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
56
2018-12-23T18:11:40.000Z
2021-11-30T13:18:17.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "jit/JitOptions.h" #include "mozilla/TypeTraits.h" #include <cstdlib> #include "vm/JSFunction.h" using namespace js; using namespace js::jit; using mozilla::Maybe; namespace js { namespace jit { DefaultJitOptions JitOptions; static void Warn(const char* env, const char* value) { fprintf(stderr, "Warning: I didn't understand %s=\"%s\"\n", env, value); } template<typename T> struct IsBool : mozilla::FalseType {}; template<> struct IsBool<bool> : mozilla::TrueType {}; static Maybe<int> ParseInt(const char* str) { char* endp; int retval = strtol(str, &endp, 0); if (*endp == '\0') { return mozilla::Some(retval); } return mozilla::Nothing(); } template<typename T> T overrideDefault(const char* param, T dflt) { char* str = getenv(param); if (!str) { return dflt; } if (IsBool<T>::value) { if (strcmp(str, "true") == 0 || strcmp(str, "yes") == 0) { return true; } if (strcmp(str, "false") == 0 || strcmp(str, "no") == 0) { return false; } Warn(param, str); } else { Maybe<int> value = ParseInt(str); if (value.isSome()) { return value.ref(); } Warn(param, str); } return dflt; } #define SET_DEFAULT(var, dflt) var = overrideDefault("JIT_OPTION_" #var, dflt) DefaultJitOptions::DefaultJitOptions() { // Whether to perform expensive graph-consistency DEBUG-only assertions. // It can be useful to disable this to reduce DEBUG-compile time of large // wasm programs. SET_DEFAULT(checkGraphConsistency, true); #ifdef CHECK_OSIPOINT_REGISTERS // Emit extra code to verify live regs at the start of a VM call // are not modified before its OsiPoint. SET_DEFAULT(checkOsiPointRegisters, false); #endif // Whether to enable extra code to perform dynamic validation of // RangeAnalysis results. SET_DEFAULT(checkRangeAnalysis, false); // Toggles whether IonBuilder fallbacks to a call if we fail to inline. SET_DEFAULT(disableInlineBacktracking, false); // Toggles whether Alignment Mask Analysis is globally disabled. SET_DEFAULT(disableAma, false); // Toggles whether Effective Address Analysis is globally disabled. SET_DEFAULT(disableEaa, false); // Toggles whether Edge Case Analysis is gobally disabled. SET_DEFAULT(disableEdgeCaseAnalysis, false); // Toggle whether global value numbering is globally disabled. SET_DEFAULT(disableGvn, false); // Toggles whether inlining is globally disabled. SET_DEFAULT(disableInlining, false); // Toggles whether loop invariant code motion is globally disabled. SET_DEFAULT(disableLicm, false); // Toggles whether Loop Unrolling is globally disabled. SET_DEFAULT(disableLoopUnrolling, true); // Toggles wheter optimization tracking is globally disabled. SET_DEFAULT(disableOptimizationTracking, true); // Toggle whether Profile Guided Optimization is globally disabled. SET_DEFAULT(disablePgo, false); // Toggles whether instruction reordering is globally disabled. SET_DEFAULT(disableInstructionReordering, false); // Toggles whether Range Analysis is globally disabled. SET_DEFAULT(disableRangeAnalysis, false); // Toggles wheter Recover instructions is globally disabled. SET_DEFAULT(disableRecoverIns, false); // Toggle whether eager scalar replacement is globally disabled. SET_DEFAULT(disableScalarReplacement, false); // Toggles whether CacheIR stubs are used. SET_DEFAULT(disableCacheIR, false); // Toggles whether CacheIR stubs for binary arith operations are used SET_DEFAULT(disableCacheIRBinaryArith, false); // Toggles whether sincos optimization is globally disabled. // See bug984018: The MacOS is the only one that has the sincos fast. #if defined(XP_MACOSX) SET_DEFAULT(disableSincos, false); #else SET_DEFAULT(disableSincos, true); #endif // Toggles whether sink code motion is globally disabled. SET_DEFAULT(disableSink, true); // Whether functions are compiled immediately. SET_DEFAULT(eagerCompilation, false); // Whether IonBuilder should prefer IC generation above specialized MIR. SET_DEFAULT(forceInlineCaches, false); // Toggles whether large scripts are rejected. SET_DEFAULT(limitScriptSize, true); // Toggles whether functions may be entered at loop headers. SET_DEFAULT(osr, true); // Whether to enable extra code to perform dynamic validations. SET_DEFAULT(runExtraChecks, false); // How many invocations or loop iterations are needed before functions // are compiled with the baseline compiler. // Duplicated in all.js - ensure both match. SET_DEFAULT(baselineWarmUpThreshold, 10); // Number of exception bailouts (resuming into catch/finally block) before // we invalidate and forbid Ion compilation. SET_DEFAULT(exceptionBailoutThreshold, 10); // Number of bailouts without invalidation before we set // JSScript::hadFrequentBailouts and invalidate. // Duplicated in all.js - ensure both match. SET_DEFAULT(frequentBailoutThreshold, 10); // Whether to run all debug checks in debug builds. // Disabling might make it more enjoyable to run JS in debug builds. SET_DEFAULT(fullDebugChecks, true); // How many actual arguments are accepted on the C stack. SET_DEFAULT(maxStackArgs, 4096); // How many times we will try to enter a script via OSR before // invalidating the script. SET_DEFAULT(osrPcMismatchesBeforeRecompile, 6000); // The bytecode length limit for small function. SET_DEFAULT(smallFunctionMaxBytecodeLength_, 130); // An artificial testing limit for the maximum supported offset of // pc-relative jump and call instructions. SET_DEFAULT(jumpThreshold, UINT32_MAX); // Branch pruning heuristic is based on a scoring system, which is look at // different metrics and provide a score. The score is computed as a // projection where each factor defines the weight of each metric. Then this // score is compared against a threshold to prevent a branch from being // removed. SET_DEFAULT(branchPruningHitCountFactor, 1); SET_DEFAULT(branchPruningInstFactor, 10); SET_DEFAULT(branchPruningBlockSpanFactor, 100); SET_DEFAULT(branchPruningEffectfulInstFactor, 3500); SET_DEFAULT(branchPruningThreshold, 4000); // Force how many invocation or loop iterations are needed before compiling // a function with the highest ionmonkey optimization level. // (i.e. OptimizationLevel_Normal) const char* forcedDefaultIonWarmUpThresholdEnv = "JIT_OPTION_forcedDefaultIonWarmUpThreshold"; if (const char* env = getenv(forcedDefaultIonWarmUpThresholdEnv)) { Maybe<int> value = ParseInt(env); if (value.isSome()) { forcedDefaultIonWarmUpThreshold.emplace(value.ref()); } else { Warn(forcedDefaultIonWarmUpThresholdEnv, env); } } // Same but for compiling small functions. const char* forcedDefaultIonSmallFunctionWarmUpThresholdEnv = "JIT_OPTION_forcedDefaultIonSmallFunctionWarmUpThreshold"; if (const char* env = getenv(forcedDefaultIonSmallFunctionWarmUpThresholdEnv)) { Maybe<int> value = ParseInt(env); if (value.isSome()) { forcedDefaultIonSmallFunctionWarmUpThreshold.emplace(value.ref()); } else { Warn(forcedDefaultIonSmallFunctionWarmUpThresholdEnv, env); } } // Force the used register allocator instead of letting the optimization // pass decide. const char* forcedRegisterAllocatorEnv = "JIT_OPTION_forcedRegisterAllocator"; if (const char* env = getenv(forcedRegisterAllocatorEnv)) { forcedRegisterAllocator = LookupRegisterAllocator(env); if (!forcedRegisterAllocator.isSome()) { Warn(forcedRegisterAllocatorEnv, env); } } SET_DEFAULT(spectreIndexMasking, true); SET_DEFAULT(spectreObjectMitigationsBarriers, true); SET_DEFAULT(spectreObjectMitigationsMisc, true); SET_DEFAULT(spectreStringMitigations, true); SET_DEFAULT(spectreValueMasking, true); SET_DEFAULT(spectreJitToCxxCalls, true); // Toggles whether unboxed plain objects can be created by the VM. SET_DEFAULT(disableUnboxedObjects, false); // Toggles the optimization whereby offsets are folded into loads and not // included in the bounds check. SET_DEFAULT(wasmFoldOffsets, true); // Controls whether two-tiered compilation should be requested when // compiling a new wasm module, independently of other heuristics, and // should be delayed to test both baseline and ion paths in compiled code, // as well as the transition from one tier to the other. SET_DEFAULT(wasmDelayTier2, false); // Until which wasm bytecode size should we accumulate functions, in order // to compile efficiently on helper threads. Baseline code compiles much // faster than Ion code so use scaled thresholds (see also bug 1320374). SET_DEFAULT(wasmBatchBaselineThreshold, 10000); SET_DEFAULT(wasmBatchIonThreshold, 1100); #ifdef JS_TRACE_LOGGING // Toggles whether the traceLogger should be on or off. In either case, // some data structures will always be created and initialized such as // the traceLoggerState. However, unless this option is set to true // the traceLogger will not be recording any events. SET_DEFAULT(enableTraceLogger, false); #endif } bool DefaultJitOptions::isSmallFunction(JSScript* script) const { return script->length() <= smallFunctionMaxBytecodeLength_; } void DefaultJitOptions::enableGvn(bool enable) { disableGvn = !enable; } void DefaultJitOptions::setEagerCompilation() { eagerCompilation = true; baselineWarmUpThreshold = 0; forcedDefaultIonWarmUpThreshold.reset(); forcedDefaultIonWarmUpThreshold.emplace(0); forcedDefaultIonSmallFunctionWarmUpThreshold.reset(); forcedDefaultIonSmallFunctionWarmUpThreshold.emplace(0); } void DefaultJitOptions::setCompilerWarmUpThreshold(uint32_t warmUpThreshold) { forcedDefaultIonWarmUpThreshold.reset(); forcedDefaultIonWarmUpThreshold.emplace(warmUpThreshold); forcedDefaultIonSmallFunctionWarmUpThreshold.reset(); forcedDefaultIonSmallFunctionWarmUpThreshold.emplace(warmUpThreshold); // Undo eager compilation if (eagerCompilation && warmUpThreshold != 0) { jit::DefaultJitOptions defaultValues; eagerCompilation = false; baselineWarmUpThreshold = defaultValues.baselineWarmUpThreshold; } } void DefaultJitOptions::resetCompilerWarmUpThreshold() { forcedDefaultIonWarmUpThreshold.reset(); // Undo eager compilation if (eagerCompilation) { jit::DefaultJitOptions defaultValues; eagerCompilation = false; baselineWarmUpThreshold = defaultValues.baselineWarmUpThreshold; } } } // namespace jit } // namespace js
34.981595
98
0.720537
fengjixuchui
4a2aabe87801f4187ff368b6ef7a296ed3619fb9
2,424
cpp
C++
multimedia/danim/src/daxctl/controls/ihbase/dmpguid/dmpguids.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/danim/src/daxctl/controls/ihbase/dmpguid/dmpguids.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/danim/src/daxctl/controls/ihbase/dmpguid/dmpguids.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Lists the Data1 member of a variety of GUIDS #include <windows.h> #include <initguid.h> // once per build #include "..\precomp.h" #include "..\..\mmctl\inc\ochelp.h" #include "objsafe.h" #include "docobj.h" #include <stdio.h> #define DUMPGUID(I,IID) \ WriteItem(pfHeader, pfCase, I, IID);\ rgdwIID[i] = IID.Data1; \ i++; void WriteToHeader(FILE *pFile, LPSTR pszInterface, GUID riid) { fprintf(pFile, "#define %s_DATA1 0x%lx\r\n", pszInterface, riid.Data1); } void WriteToSwitch(FILE *pFile, LPSTR pszInterface) { TCHAR rgchFormat[] = TEXT("case %s_DATA1:\r\n{\r\nif (IsShortEqualIID(riid,%s))\r\n"); fprintf(pFile, rgchFormat, pszInterface, pszInterface); } void WriteItem(FILE *pHfile, FILE *pSwitchFile, LPSTR pszInterface, GUID riid) { WriteToHeader(pHfile, pszInterface, riid); WriteToSwitch(pSwitchFile, pszInterface); } void main() { TCHAR rgchHeader[] = TEXT("header.h"); TCHAR rgchSwitch[] = TEXT("switch.cpp"); DWORD rgdwIID[14]; int i = 0; int j; FILE *pfHeader, *pfCase; pfHeader = fopen(rgchHeader, "wb+"); pfCase = fopen(rgchSwitch, "wb+"); if ( (pfHeader) && (pfCase) ) { ZeroMemory(rgdwIID, sizeof(rgdwIID)); DUMPGUID("IID_IViewObject", IID_IViewObject); DUMPGUID("IID_IViewObject2", IID_IViewObject2); DUMPGUID("IID_IViewObjectEx", IID_IViewObjectEx); DUMPGUID("IID_IOleCommandTarget", IID_IOleCommandTarget); DUMPGUID("IID_IOleObject", IID_IOleObject); DUMPGUID("IID_IOleInPlaceObjectWindowless", IID_IOleInPlaceObjectWindowless); DUMPGUID("IID_IOleControl", IID_IOleControl); DUMPGUID("IID_IConnectionPointContainer", IID_IConnectionPointContainer); DUMPGUID("IID_IOleInPlaceObject", IID_IOleInPlaceObject); DUMPGUID("IID_IPersistVariantIO", IID_IPersistVariantIO); DUMPGUID("IID_IProvideClassInfo", IID_IProvideClassInfo); DUMPGUID("IID_IObjectSafety", IID_IObjectSafety); DUMPGUID("IID_ISpecifyPropertyPages", IID_ISpecifyPropertyPages); DUMPGUID("IID_IUnknown", IID_IUnknown); for (i=0; i < (sizeof(rgdwIID)/sizeof(rgdwIID[0])) - 1; i++) { for (j = i+1; j < (sizeof(rgdwIID)/sizeof(rgdwIID[0])); j++) { if (rgdwIID[i] == rgdwIID[j]) printf("%lu and %lu match !\n", i, j); } } } if (pfHeader) { fprintf(pfHeader, "\r\n"); fclose(pfHeader); } if (pfCase) { fprintf(pfHeader, "\r\n"); fclose(pfCase); } return; }
27.545455
88
0.683168
npocmaka
4a2bb6a43126d867175c93d1ee451c82a38743a7
17,490
cpp
C++
src/pola/scene/mesh/MD2MeshLoader.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
src/pola/scene/mesh/MD2MeshLoader.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
src/pola/scene/mesh/MD2MeshLoader.cpp
lij0511/pandora
5988618f29d2f1ba418ef54a02e227903c1e7108
[ "Apache-2.0" ]
null
null
null
/* * MD2MeshLoader.cpp * * Created on: 2016年5月21日 * Author: lijing */ #include <stdint.h> //#define USE_MD2_MESH #include "pola/log/Log.h" #include "pola/scene/mesh/MD2MeshLoader.h" #include "pola/scene/mesh/Mesh.h" #ifdef USE_MD2_MESH #include "pola/scene/mesh/MD2AnimatedMesh.h" #endif #include <string.h> namespace pola { namespace scene { const int32_t MD2_MAGIC_NUMBER = 844121161; const int32_t MD2_VERSION = 8; const int32_t MD2_MAX_VERTS = 2048; const int32_t Q2_VERTEX_NORMAL_TABLE_SIZE = 162; static const float Q2_VERTEX_NORMAL_TABLE[Q2_VERTEX_NORMAL_TABLE_SIZE][3] = { {-0.525731f, 0.000000f, 0.850651f}, {-0.442863f, 0.238856f, 0.864188f}, {-0.295242f, 0.000000f, 0.955423f}, {-0.309017f, 0.500000f, 0.809017f}, {-0.162460f, 0.262866f, 0.951056f}, {0.000000f, 0.000000f, 1.000000f}, {0.000000f, 0.850651f, 0.525731f}, {-0.147621f, 0.716567f, 0.681718f}, {0.147621f, 0.716567f, 0.681718f}, {0.000000f, 0.525731f, 0.850651f}, {0.309017f, 0.500000f, 0.809017f}, {0.525731f, 0.000000f, 0.850651f}, {0.295242f, 0.000000f, 0.955423f}, {0.442863f, 0.238856f, 0.864188f}, {0.162460f, 0.262866f, 0.951056f}, {-0.681718f, 0.147621f, 0.716567f}, {-0.809017f, 0.309017f, 0.500000f}, {-0.587785f, 0.425325f, 0.688191f}, {-0.850651f, 0.525731f, 0.000000f}, {-0.864188f, 0.442863f, 0.238856f}, {-0.716567f, 0.681718f, 0.147621f}, {-0.688191f, 0.587785f, 0.425325f}, {-0.500000f, 0.809017f, 0.309017f}, {-0.238856f, 0.864188f, 0.442863f}, {-0.425325f, 0.688191f, 0.587785f}, {-0.716567f, 0.681718f, -0.147621f}, {-0.500000f, 0.809017f, -0.309017f}, {-0.525731f, 0.850651f, 0.000000f}, {0.000000f, 0.850651f, -0.525731f}, {-0.238856f, 0.864188f, -0.442863f}, {0.000000f, 0.955423f, -0.295242f}, {-0.262866f, 0.951056f, -0.162460f}, {0.000000f, 1.000000f, 0.000000f}, {0.000000f, 0.955423f, 0.295242f}, {-0.262866f, 0.951056f, 0.162460f}, {0.238856f, 0.864188f, 0.442863f}, {0.262866f, 0.951056f, 0.162460f}, {0.500000f, 0.809017f, 0.309017f}, {0.238856f, 0.864188f, -0.442863f}, {0.262866f, 0.951056f, -0.162460f}, {0.500000f, 0.809017f, -0.309017f}, {0.850651f, 0.525731f, 0.000000f}, {0.716567f, 0.681718f, 0.147621f}, {0.716567f, 0.681718f, -0.147621f}, {0.525731f, 0.850651f, 0.000000f}, {0.425325f, 0.688191f, 0.587785f}, {0.864188f, 0.442863f, 0.238856f}, {0.688191f, 0.587785f, 0.425325f}, {0.809017f, 0.309017f, 0.500000f}, {0.681718f, 0.147621f, 0.716567f}, {0.587785f, 0.425325f, 0.688191f}, {0.955423f, 0.295242f, 0.000000f}, {1.000000f, 0.000000f, 0.000000f}, {0.951056f, 0.162460f, 0.262866f}, {0.850651f, -0.525731f, 0.000000f}, {0.955423f, -0.295242f, 0.000000f}, {0.864188f, -0.442863f, 0.238856f}, {0.951056f, -0.162460f, 0.262866f}, {0.809017f, -0.309017f, 0.500000f}, {0.681718f, -0.147621f, 0.716567f}, {0.850651f, 0.000000f, 0.525731f}, {0.864188f, 0.442863f, -0.238856f}, {0.809017f, 0.309017f, -0.500000f}, {0.951056f, 0.162460f, -0.262866f}, {0.525731f, 0.000000f, -0.850651f}, {0.681718f, 0.147621f, -0.716567f}, {0.681718f, -0.147621f, -0.716567f}, {0.850651f, 0.000000f, -0.525731f}, {0.809017f, -0.309017f, -0.500000f}, {0.864188f, -0.442863f, -0.238856f}, {0.951056f, -0.162460f, -0.262866f}, {0.147621f, 0.716567f, -0.681718f}, {0.309017f, 0.500000f, -0.809017f}, {0.425325f, 0.688191f, -0.587785f}, {0.442863f, 0.238856f, -0.864188f}, {0.587785f, 0.425325f, -0.688191f}, {0.688191f, 0.587785f, -0.425325f}, {-0.147621f, 0.716567f, -0.681718f}, {-0.309017f, 0.500000f, -0.809017f}, {0.000000f, 0.525731f, -0.850651f}, {-0.525731f, 0.000000f, -0.850651f}, {-0.442863f, 0.238856f, -0.864188f}, {-0.295242f, 0.000000f, -0.955423f}, {-0.162460f, 0.262866f, -0.951056f}, {0.000000f, 0.000000f, -1.000000f}, {0.295242f, 0.000000f, -0.955423f}, {0.162460f, 0.262866f, -0.951056f}, {-0.442863f, -0.238856f, -0.864188f}, {-0.309017f, -0.500000f, -0.809017f}, {-0.162460f, -0.262866f, -0.951056f}, {0.000000f, -0.850651f, -0.525731f}, {-0.147621f, -0.716567f, -0.681718f}, {0.147621f, -0.716567f, -0.681718f}, {0.000000f, -0.525731f, -0.850651f}, {0.309017f, -0.500000f, -0.809017f}, {0.442863f, -0.238856f, -0.864188f}, {0.162460f, -0.262866f, -0.951056f}, {0.238856f, -0.864188f, -0.442863f}, {0.500000f, -0.809017f, -0.309017f}, {0.425325f, -0.688191f, -0.587785f}, {0.716567f, -0.681718f, -0.147621f}, {0.688191f, -0.587785f, -0.425325f}, {0.587785f, -0.425325f, -0.688191f}, {0.000000f, -0.955423f, -0.295242f}, {0.000000f, -1.000000f, 0.000000f}, {0.262866f, -0.951056f, -0.162460f}, {0.000000f, -0.850651f, 0.525731f}, {0.000000f, -0.955423f, 0.295242f}, {0.238856f, -0.864188f, 0.442863f}, {0.262866f, -0.951056f, 0.162460f}, {0.500000f, -0.809017f, 0.309017f}, {0.716567f, -0.681718f, 0.147621f}, {0.525731f, -0.850651f, 0.000000f}, {-0.238856f, -0.864188f, -0.442863f}, {-0.500000f, -0.809017f, -0.309017f}, {-0.262866f, -0.951056f, -0.162460f}, {-0.850651f, -0.525731f, 0.000000f}, {-0.716567f, -0.681718f, -0.147621f}, {-0.716567f, -0.681718f, 0.147621f}, {-0.525731f, -0.850651f, 0.000000f}, {-0.500000f, -0.809017f, 0.309017f}, {-0.238856f, -0.864188f, 0.442863f}, {-0.262866f, -0.951056f, 0.162460f}, {-0.864188f, -0.442863f, 0.238856f}, {-0.809017f, -0.309017f, 0.500000f}, {-0.688191f, -0.587785f, 0.425325f}, {-0.681718f, -0.147621f, 0.716567f}, {-0.442863f, -0.238856f, 0.864188f}, {-0.587785f, -0.425325f, 0.688191f}, {-0.309017f, -0.500000f, 0.809017f}, {-0.147621f, -0.716567f, 0.681718f}, {-0.425325f, -0.688191f, 0.587785f}, {-0.162460f, -0.262866f, 0.951056f}, {0.442863f, -0.238856f, 0.864188f}, {0.162460f, -0.262866f, 0.951056f}, {0.309017f, -0.500000f, 0.809017f}, {0.147621f, -0.716567f, 0.681718f}, {0.000000f, -0.525731f, 0.850651f}, {0.425325f, -0.688191f, 0.587785f}, {0.587785f, -0.425325f, 0.688191f}, {0.688191f, -0.587785f, 0.425325f}, {-0.955423f, 0.295242f, 0.000000f}, {-0.951056f, 0.162460f, 0.262866f}, {-1.000000f, 0.000000f, 0.000000f}, {-0.850651f, 0.000000f, 0.525731f}, {-0.955423f, -0.295242f, 0.000000f}, {-0.951056f, -0.162460f, 0.262866f}, {-0.864188f, 0.442863f, -0.238856f}, {-0.951056f, 0.162460f, -0.262866f}, {-0.809017f, 0.309017f, -0.500000f}, {-0.864188f, -0.442863f, -0.238856f}, {-0.951056f, -0.162460f, -0.262866f}, {-0.809017f, -0.309017f, -0.500000f}, {-0.681718f, 0.147621f, -0.716567f}, {-0.681718f, -0.147621f, -0.716567f}, {-0.850651f, 0.000000f, -0.525731f}, {-0.688191f, 0.587785f, -0.425325f}, {-0.587785f, 0.425325f, -0.688191f}, {-0.425325f, 0.688191f, -0.587785f}, {-0.425325f, -0.688191f, -0.587785f}, {-0.587785f, -0.425325f, -0.688191f}, {-0.688191f, -0.587785f, -0.425325f}, }; struct MD2AnimationType { int32_t begin; int32_t end; int32_t fps; std::string name; }; const int32_t MD2_ANIMATION_TYPE_LIST_SIZE = 21; static const MD2AnimationType MD2AnimationTypeList[MD2_ANIMATION_TYPE_LIST_SIZE] = { { 0, 39, 9, "STAND"}, // STAND { 40, 45, 10, "RUN"}, // RUN { 46, 53, 10, "ATTACK"}, // ATTACK { 54, 57, 7, "PAIN_A"}, // PAIN_A { 58, 61, 7, "PAIN_B"}, // PAIN_B { 62, 65, 7, "PAIN_C"}, // PAIN_C { 66, 71, 7, "JUMP"}, // JUMP { 72, 83, 7, "FLIP"}, // FLIP { 84, 94, 7, "SALUTE"}, // SALUTE { 95, 111, 10, "FALLBACK"}, // FALLBACK {112, 122, 7, "WAVE"}, // WAVE {123, 134, 6, "POINT"}, // POINT {135, 153, 10, "CROUCH_STAND"}, // CROUCH_STAND {154, 159, 7, "CROUCH_WALK"}, // CROUCH_WALK {160, 168, 10, "CROUCH_ATTACK"}, // CROUCH_ATTACK {169, 172, 7, "CROUCH_PAIN"}, // CROUCH_PAIN {173, 177, 5, "CROUCH_DEATH"}, // CROUCH_DEATH {178, 183, 7, "DEATH_FALLBACK"}, // DEATH_FALLBACK {184, 189, 7, "DEATH_FALLFORWARD"}, // DEATH_FALLFORWARD {190, 197, 7, "DEATH_FALLBACKSLOW"}, // DEATH_FALLBACKSLOW {198, 198, 5, "BOOM"}, // BOOM }; #include "pola/utils/spack.h" struct MD2Header { int32_t magic; // four character code "IDP2" int32_t version; // must be 8 int32_t skinWidth; // width of the texture int32_t skinHeight; // height of the texture int32_t frameSize; // size in bytes of an animation frame int32_t numSkins; // number of textures int32_t numVertices; // total number of vertices int32_t numTexcoords; // number of vertices with texture coords int32_t numTriangles; // number of triangles int32_t numGlCommands; // number of opengl commands (triangle strip or triangle fan) int32_t numFrames; // animation keyframe count int32_t offsetSkins; // offset in bytes to 64 character skin names int32_t offsetTexcoords; // offset in bytes to texture coordinate list int32_t offsetTriangles; // offset in bytes to triangle list int32_t offsetFrames; // offset in bytes to frame list int32_t offsetGlCommands;// offset in bytes to opengl commands int32_t offsetEnd; // offset in bytes to end of file } PACK_STRUCT; struct MD2Vertex { uint8_t vertex[3]; // [0] = X, [1] = Z, [2] = Y uint8_t lightNormalIndex; // index in the normal table } PACK_STRUCT; struct MD2Frame { float scale[3]; // first scale the vertex position float translate[3]; // then translate the position char name[16]; // the name of the animation that this key belongs to MD2Vertex vertices[1]; // vertex 1 of SMD2Header.numVertices } PACK_STRUCT; struct MD2Triangle { uint16_t vertexIndices[3]; uint16_t textureIndices[3]; } PACK_STRUCT; struct MD2TextureCoordinate { int16_t s; int16_t t; } PACK_STRUCT; #include "pola/utils/sunpack.h" MD2MeshLoader::MD2MeshLoader() { } MD2MeshLoader::~MD2MeshLoader() { } bool MD2MeshLoader::available(io::InputStream* is) { MD2Header header; is->read(&header, sizeof(MD2Header)); bool accept = true; if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) { LOGE("MD2 Loader: Wrong file header\n"); accept = false; } return accept; } pola::utils::sp<MeshLoader::MeshInfo> MD2MeshLoader::doLoadMesh(io::InputStream* is) { #if !defined(USE_MD2_MESH) MD2Header header; is->read(&header, sizeof(MD2Header)); if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) { LOGE("MD2 Loader: Wrong file header\n"); return nullptr; } // read Triangles is->seek(header.offsetTriangles); MD2Triangle *triangles = new MD2Triangle[header.numTriangles]; if (!is->read(triangles, header.numTriangles *sizeof(MD2Triangle))) { delete[] triangles; LOGE("MD2 Loader: Error reading triangles."); return nullptr; } // read Vertices uint8_t buffer[MD2_MAX_VERTS*4+128]; MD2Frame* frame = (MD2Frame*)buffer; is->seek(header.offsetFrames); Mesh* mesh = new Mesh; graphic::Geometry3D* geometry = (graphic::Geometry3D*) mesh->geometry(); geometry->alloc(header.numTriangles * 3, FLAG_GEOMETRY_DEFAULT | FLAG_GEOMETRY_NORMAL | FLAG_GEOMETRY_UV); const int16_t count = header.numTriangles * 3; for (int16_t i = 0; i < count; i += 3) { geometry->addIndex((uint16_t) i); geometry->addIndex((uint16_t) i + 1); geometry->addIndex((uint16_t) i + 2); } Animations* animations = new Animations; mesh->setAnimations(animations); is->seek(header.offsetFrames); graphic::Box3 boundingBox; int32_t frameIndex = 0; for (int32_t animationIndex = 0; animationIndex < MD2_ANIMATION_TYPE_LIST_SIZE; animationIndex ++) { if (frameIndex >= header.numFrames) { break; } MD2AnimationType animationType = MD2AnimationTypeList[animationIndex]; FrameAnimation* animation = new FrameAnimation(animationType.name); animations->addAnimation(animation); float frameTime = 1.f / animationType.fps; for (frameIndex = animationType.begin; frameIndex <= animationType.end; frameIndex ++) { if (frameIndex >= header.numFrames) { break; } is->read(frame, header.frameSize); LOGD("FrameName=%s", frame->name); // add vertices FrameAnimation::KeyFrameData& frameData = animation->addKeyFrame(frameTime); frameData.positions.resize(header.numTriangles * 3); frameData.normals.resize(header.numTriangles * 3); graphic::vec3* positions = frameData.positions.data(); graphic::vec3* normals = frameData.normals.data(); for (int32_t j = 0; j < header.numTriangles; ++j) { for (int32_t ti = 0; ti < 3; ++ti) { uint32_t num = triangles[j].vertexIndices[ti]; float x = frame->vertices[num].vertex[0]; x = x * frame->scale[0] + frame->translate[0]; float y = frame->vertices[num].vertex[1]; y = y * frame->scale[1] + frame->translate[1]; float z = frame->vertices[num].vertex[2]; z = z * frame->scale[2] + frame->translate[2]; positions[0] = {x, z, y}; boundingBox.expandByPoint(positions[0]); positions ++; float nx = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][0]; float ny = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][1]; float nz = Q2_VERTEX_NORMAL_TABLE[frame->vertices[num].lightNormalIndex][2]; normals[0] = {nx, nz, ny}; normals ++; } } if (frameIndex == 0) { memcpy(geometry->positions(), frameData.positions.data(), sizeof(graphic::vec3) * header.numTriangles * 3); memcpy(geometry->normals(), frameData.normals.data(), sizeof(graphic::vec3) * header.numTriangles * 3); } } } geometry->setBoundingBox(boundingBox); is->seek(header.offsetTexcoords); MD2TextureCoordinate* textureCoords = new MD2TextureCoordinate[header.numTexcoords]; is->read(textureCoords, sizeof(MD2TextureCoordinate)*header.numTexcoords); if (header.numFrames > 0) { float dmaxs = 1.0f / (header.skinWidth); float dmaxt = 1.0f / (header.skinHeight); graphic::vec2* uvs = geometry->uvs();; for (int32_t t = 0; t < header.numTriangles; ++t) { for (int32_t n = 0; n < 3; ++n) { int32_t index = t * 3 + n; uvs[index] = {(textureCoords[triangles[t].textureIndices[n]].s + 0.5f) * dmaxs, (textureCoords[triangles[t].textureIndices[n]].t + 0.5f) * dmaxt}; } } } delete[] triangles; delete[] textureCoords; pola::utils::sp<MeshLoader::MeshInfo> result = new MeshInfo; result->mesh = mesh; return result; #else MD2Header header; is->read(&header, sizeof(MD2Header)); if (header.magic != MD2_MAGIC_NUMBER || header.version != MD2_VERSION) { LOGE("MD2 Loader: Wrong file header\n"); return nullptr; } // read Triangles is->seek(header.offsetTriangles); MD2Triangle *triangles = new MD2Triangle[header.numTriangles]; if (!is->read(triangles, header.numTriangles *sizeof(MD2Triangle))) { delete[] triangles; LOGE("MD2 Loader: Error reading triangles."); return nullptr; } // read Vertices uint8_t buffer[MD2_MAX_VERTS*4+128]; MD2Frame* frame = (MD2Frame*)buffer; is->seek(header.offsetFrames); MD2AnimatedMesh* mesh = new MD2AnimatedMesh; graphic::Geometry3D* geometry = (graphic::Geometry3D*) mesh->geometry(); geometry->alloc(header.numTriangles * 3, FLAG_GEOMETRY_DEFAULT | FLAG_GEOMETRY_NORMAL | FLAG_GEOMETRY_UV); const int16_t count = header.numTriangles * 3; for (int16_t i = 0; i < count; i += 3) { geometry->addIndex((uint16_t) i); geometry->addIndex((uint16_t) i + 1); geometry->addIndex((uint16_t) i + 2); } mesh->frameTransforms.resize(header.numFrames); mesh->frameList.resize(header.numFrames); mesh->setFrameCount(header.numFrames); is->seek(header.offsetFrames); for (int32_t i = 0; i < header.numFrames; ++i) { is->read(frame, header.frameSize); LOGD("FrameName=%s", frame->name); // save keyframe scale and translation FrameTransform* frameTransforms = mesh->frameTransforms.data(); frameTransforms[i].scale[0] = frame->scale[0]; frameTransforms[i].scale[2] = frame->scale[1]; frameTransforms[i].scale[1] = frame->scale[2]; frameTransforms[i].translate[0] = frame->translate[0]; frameTransforms[i].translate[2] = frame->translate[1]; frameTransforms[i].translate[1] = frame->translate[2]; graphic::Box3 boundingBox; mesh->frameList[i].resize(header.numTriangles * 3); FrameItem* frameItems = mesh->frameList[i].data(); // add vertices for (int32_t j = 0; j < header.numTriangles; ++j) { for (int32_t ti = 0; ti < 3; ++ti) { FrameItem v; uint32_t num = triangles[j].vertexIndices[ti]; v.pos[0] = frame->vertices[num].vertex[0]; v.pos[2] = frame->vertices[num].vertex[1]; v.pos[1] = frame->vertices[num].vertex[2]; v.normal_index = frame->vertices[num].lightNormalIndex; *(frameItems++) = v; boundingBox.expandByPoint({v.pos[0] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0], v.pos[1] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0], v.pos[2] * frameTransforms[i].scale[0] + frameTransforms[i].translate[0]}); } } geometry->setBoundingBox(boundingBox); } is->seek(header.offsetTexcoords); MD2TextureCoordinate* textureCoords = new MD2TextureCoordinate[header.numTexcoords]; is->read(textureCoords, sizeof(MD2TextureCoordinate)*header.numTexcoords); if (header.numFrames > 0) { float dmaxs = 1.0f / (header.skinWidth); float dmaxt = 1.0f / (header.skinHeight); graphic::vec2* uvs = geometry->uvs();; for (int32_t t = 0; t < header.numTriangles; ++t) { for (int32_t n = 0; n < 3; ++n) { int32_t index = t * 3 + n; uvs[index] = {(textureCoords[triangles[t].textureIndices[n]].s + 0.5f) * dmaxs, (textureCoords[triangles[t].textureIndices[n]].t + 0.5f) * dmaxt}; } } } delete[] triangles; delete[] textureCoords; pola::utils::sp<MeshLoader::MeshInfo> result = new MeshInfo; result->mesh = mesh; return result; #endif } } /* namespace scene */ } /* namespace pola */
34.702381
150
0.671755
lij0511
4a2f142e7fedc3ecb35677a84f21e77c4584a8bf
6,418
cpp
C++
main.cpp
SebMenozzi/NN
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
[ "MIT" ]
null
null
null
main.cpp
SebMenozzi/NN
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
[ "MIT" ]
null
null
null
main.cpp
SebMenozzi/NN
d9a5bd1a13cc4112711ad0483a6b9b94de80de46
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include "matrix.h" #include "NN.h" // nombre de neurones en hidden layer #define nb_neurons_hidden_layer 3 // nombre d'itération #define epoch 2000 // capacité d'apprentissage #define learning_rate 0.7 // GLOBAL // donnée entrante d'input pour XOR const int training_data[4][2] = { { 1, 0 }, // 1 XOR 1 = 1 { 1, 1 }, // 0 { 0, 1 }, // 1 { 0, 0 } // 0 }; // résultat attendu const int answer_data[4] = { 1, 0, 1, 0 }; // objectif int target; Matrix input_to_hidden_weights(nb_neurons_hidden_layer, 2); Matrix input_to_hidden_bias(nb_neurons_hidden_layer, 1); Matrix input_layer(2, 1); Matrix hidden_to_output_weights(1, nb_neurons_hidden_layer); Matrix hidden_to_output_bias(1, 1); Matrix hidden_layer(nb_neurons_hidden_layer, 1); Matrix output_layer(1, 1); float error_rate; // for debug // UTILS // donne un float entre -1 et 1 double random_between_neg_1_pos_1() { int randNumber = rand() % 2; // 0 or 1 double result = rand() / (RAND_MAX + 1.0); // between 0 and 1 return (randNumber == 1) ? result : -1 * result; } // met des poids aléatoires de input vers hidden layer void generate_random_input_to_hidden_weights() { for (size_t row = 0; row < nb_neurons_hidden_layer; row++) { for (size_t column = 0; column < 2; column++) { input_to_hidden_weights.setValue(row, column, random_between_neg_1_pos_1()); } } } // met des poids aléatoires de hidden vers output layer void generate_random_hidden_to_output_weights() { for (size_t row = 0; row < nb_neurons_hidden_layer; row++) { hidden_to_output_weights.setValue(0, row, random_between_neg_1_pos_1()); } } // activation function float sigmoid(float x) { return 1.0 / (1.0 + exp(-x)); } // derivative of activation function float sigmoid_prime(float x) { return x * (1.0 - x); } // applique la fonction sigmoide pour chaque case d'une matrice Matrix applySigmoid(Matrix a) { for (size_t column = 0; column < a.getHeight(); column++) { for (size_t row = 0; row < a.getWidth(); row++) { a.setValue(column, row, sigmoid(a.getValue(column, row))); } } return a; } // FORWARD PROPAGATION void forward_propagate() { hidden_layer = applySigmoid(input_to_hidden_weights * input_layer + input_to_hidden_bias); output_layer = applySigmoid(hidden_to_output_weights * hidden_layer + hidden_to_output_bias); } // BACKWARD PROPAGATION void back_propagate() { float error = output_layer.getValue(0, 0) - target; error_rate = pow(error, 2); for (int row = 0; row < nb_neurons_hidden_layer; row++) { for (int column = 0; column < 2; column++) { float deltaw1 = error * sigmoid_prime(output_layer.getValue(0, 0)) * hidden_to_output_weights.getValue(0, row) * sigmoid_prime(hidden_layer.getValue(row, 0)) * input_layer.getValue(column, 0); // new input weights float new_input_to_hidden_weights = input_to_hidden_weights.getValue(row, column) - deltaw1 * learning_rate; input_to_hidden_weights.setValue(row, column, new_input_to_hidden_weights); } float deltaw2 = error * sigmoid_prime(output_layer.getValue(0, 0)) * hidden_layer.getValue(row, 0); // new hidden weights float new_hidden_to_output_weights = hidden_to_output_weights.getValue(0, row) - deltaw2 * learning_rate; hidden_to_output_weights.setValue(0, row, new_hidden_to_output_weights); float deltab1 = error * sigmoid_prime(output_layer.getValue(0, 0)) * hidden_to_output_weights.getValue(0, row) * sigmoid_prime(hidden_layer.getValue(row, 0)); // new input bias float new_input_to_hidden_bias = input_to_hidden_bias.getValue(row, 0) - deltab1 * learning_rate; input_to_hidden_bias.setValue(row, 0, new_input_to_hidden_bias); float deltab2 = error * sigmoid_prime(output_layer.getValue(0, 0)); // new hidden bias float new_hidden_to_output_bias = hidden_to_output_bias.getValue(0, 0) - deltab2 * learning_rate; hidden_to_output_bias.setValue(0, 0, new_hidden_to_output_bias); } } void display_result() { std::cout << "(" << input_layer.getValue(0, 0) << ", " << input_layer.getValue(1, 0) << ") : expected: " << target << " (error:" << output_layer.getValue(0, 0) << ")" << std::endl; } int main() { /* generate_random_input_to_hidden_weights(); generate_random_hidden_to_output_weights(); // pour chaque itération (2000) for (int i = 0; i < epoch; i++) { // pour chaque données à apprendre ( (0, 0) , (1, 0) , (0, 1) , (1, 1) pour XOR) for (int inputs = 0; inputs < 4; inputs++) { // on initialize le premier neurone de input layer input_layer.setValue(0, 0, training_data[inputs][0]); // on initialize le second neurone de input layer input_layer.setValue(1, 0, training_data[inputs][1]); // on initialize la valeur target correspond au résulat attendu par rapport aux neurones de input layer (0 ou 1 pour XOR) target = answer_data[inputs]; forward_propagate(); back_propagate(); display_result(); } }*/ (void) training_data; (void) answer_data; // TEST input_layer.setValue(0, 0, 0.01); // Entree 1 input_layer.setValue(1, 0, 0.99); // Entree 2 // Calcule forward_propagate(); // Affichage std::cout << "Sortie : " << output_layer.getValue(0, 0) << std::endl; // Calcule forward_propagate(); // Affichage std::cout << "Sortie : " << output_layer.getValue(0, 0) << std::endl; // Voici comment j'aimerais l'utiliser après apprentissage std::vector<size_t> nbNeurones; nbNeurones.push_back(2); // Inputs nbNeurones.push_back(3); // First hidden layer nbNeurones.push_back(1); // Output NN nn(nbNeurones); std::vector<float> inputs; inputs.push_back(0.01); // Input 0 inputs.push_back(0.99); // Input 1 nn.setInputs(inputs); std::vector<float> outputs = nn.getOutputs(); std::cout << "output : " << outputs[0] << std::endl; return 0; }
33.778947
184
0.636179
SebMenozzi
4a303890d6bfe4bcb7ea0879e59e2fff4af81c00
673
cpp
C++
Array6/Array6/Source.cpp
DipeshKazi/C-Repository
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
[ "MIT" ]
null
null
null
Array6/Array6/Source.cpp
DipeshKazi/C-Repository
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
[ "MIT" ]
null
null
null
Array6/Array6/Source.cpp
DipeshKazi/C-Repository
b58f26a1bdb2a159b3a1d025fea2f0d4b2d70823
[ "MIT" ]
null
null
null
#include <iostream> int addition[] = { 23, 6, 47, 35, 2, 14 }; int n, result = 0; int high = 0; int odd = 0; int even = 0; int main() { //Avarage int average = 0.0; for (n = 0; n < 6; ++n) { result = addition[n] + result; average = result / 6; } std::cout << "Average of Number "<< average << std::endl; //Highest Number for (n = 0; n < 6; ++n) { if (addition[n] >high) high = addition[n]; } std::cout << " Highest Number " << high << std::endl; //Odd Number for (n = 0; n < 6; ++n) { if (even != addition[n] % 2) odd = addition[n]; std::cout << " odd Number " << odd << std::endl; } system("pause"); return 0; }
12.942308
58
0.511144
DipeshKazi
4a32a6945aab8ddf08bdf5f18d1124c3015f6d01
544
cc
C++
CommonTools/CandAlgos/plugins/GenJetParticleRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CommonTools/CandAlgos/plugins/GenJetParticleRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CommonTools/CandAlgos/plugins/GenJetParticleRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CommonTools/CandAlgos/interface/GenJetParticleSelector.h" #include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "FWCore/Framework/interface/MakerMacros.h" namespace reco { namespace modules { typedef SingleObjectSelector< reco::GenParticleCollection, ::GenJetParticleSelector, reco::GenParticleRefVector > GenJetParticleRefSelector; DEFINE_FWK_MODULE(GenJetParticleRefSelector); } }
30.222222
67
0.746324
nistefan
4a333d1023d1ad880c887a985d7a962128604a34
2,102
hpp
C++
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/Executors/StereoReconstruction/StereoReconstructionExecutor.hpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @addtogroup DFNs * @{ */ #ifndef STEREORECONSTRUCTION_EXECUTOR_HPP #define STEREORECONSTRUCTION_EXECUTOR_HPP #include "DFNCommonInterface.hpp" #include <StereoReconstruction/StereoReconstructionInterface.hpp> #include <Types/CPP/PointCloud.hpp> #include <Types/CPP/Frame.hpp> namespace CDFF { namespace DFN { namespace Executors { /** * All the methods in this class execute the DFN for the computation of a point cloud for a pair of stereo images. * A DFN instance has to be passed in the constructor of these class. Each method takes the following parameters: * @param leftInputFrame: left camera image; * @param rightInputFrame: right camera image; * @param outputCloud: output point cloud. * * The main difference between the four methods are input and output types: * Methods (i) and (ii) have the constant pointer as input, Methods (iii) and (iv) have a constant reference as input; * Methods (i) and (iii) are non-creation methods, they give constant pointers as output, the output is just the output reference in the DFN; * When using creation methods, the output has to be initialized to NULL. * Methods (ii) and (iv) are creation methods, they copy the output of the DFN in the referenced output variable. Method (ii) takes a pointer, method (iv) takes a reference. */ void Execute(StereoReconstructionInterface* dfn, FrameWrapper::FrameConstPtr leftInputFrame, FrameWrapper::FrameConstPtr rightInputFrame, PointCloudWrapper::PointCloudConstPtr& outputCloud); void Execute(StereoReconstructionInterface* dfn, FrameWrapper::FrameConstPtr inputFrame, FrameWrapper::FrameConstPtr rightInputFrame, PointCloudWrapper::PointCloudPtr outputCloud); void Execute(StereoReconstructionInterface* dfn, const FrameWrapper::Frame& leftInputFrame, const FrameWrapper::Frame& rightInputFrame, PointCloudWrapper::PointCloudConstPtr& outputCloud); void Execute(StereoReconstructionInterface* dfn, const FrameWrapper::Frame& leftInputFrame, const FrameWrapper::Frame& rightInputFrame, PointCloudWrapper::PointCloud& outputCloud); } } } #endif // STEREORECONSTRUCTION_EXECUTOR_HPP /** @} */
42.04
172
0.797336
H2020-InFuse
4a3420319bbb2383e61ff1c277b92243071423dc
9,890
cpp
C++
src/ukf.cpp
grygoryant/CarND-Unscented-Kalman-Filter-Project
c0519637544de1d31ff02712be632e622d66ef34
[ "MIT" ]
null
null
null
src/ukf.cpp
grygoryant/CarND-Unscented-Kalman-Filter-Project
c0519637544de1d31ff02712be632e622d66ef34
[ "MIT" ]
null
null
null
src/ukf.cpp
grygoryant/CarND-Unscented-Kalman-Filter-Project
c0519637544de1d31ff02712be632e622d66ef34
[ "MIT" ]
null
null
null
#include "ukf.h" #include "Eigen/Dense" #include <iostream> /** * Initializes Unscented Kalman filter * This is scaffolding, do not modify */ UKF::UKF() { // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; n_x_ = 5; n_aug_ = n_x_ + 2; lambda_ = 3 - n_aug_; n_z_radar_ = 3; n_z_laser_ = 2; // initial state vector x_ = eig_vec(n_x_); // initial covariance matrix P_ = eig_mat::Identity(n_x_, n_x_); // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 2; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 0.3; //DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer. // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer. Xsig_pred_ = eig_mat(n_x_, 2 * n_aug_ + 1); weights_ = eig_vec(2 * n_aug_ + 1); weights_(0) = lambda_/(lambda_ + n_aug_); for(int i = 1; i < 2 * n_aug_ + 1; ++i) { weights_(i) = 1/(2 * (lambda_ + n_aug_)); } R_laser_ = eig_mat(n_z_laser_, n_z_laser_); R_laser_ << std_laspx_*std_laspx_, 0, 0, std_laspy_*std_laspy_; R_radar_ = eig_mat(n_z_radar_, n_z_radar_); R_radar_ << std_radr_*std_radr_, 0, 0, 0, std_radphi_*std_radphi_, 0, 0, 0,std_radrd_*std_radrd_; } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { if (!is_initialized_) { // first measurement if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { double rho = meas_package.raw_measurements_[0]; double phi = meas_package.raw_measurements_[1]; double rho_dot = meas_package.raw_measurements_[2]; double vx = rho_dot * cos(phi); double vy = rho_dot * sin(phi); x_ << rho * cos(phi), rho * sin(phi), sqrt(vx * vx + vy * vy), 0, 0; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER) { x_ << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1], 0, 0, 0; } time_us_ = meas_package.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; return; } double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds time_us_ = meas_package.timestamp_; Prediction(dt); if (use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR) { UpdateRadar(meas_package); } else if(use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER) { UpdateLidar(meas_package); } } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { auto Xsig_aug = eig_mat(n_aug_, 2 * n_aug_ + 1); GenAugmentedSigmaPoints(Xsig_aug); PredictSigmaPoints(Xsig_aug, delta_t); PredictStateMean(); PredictStateCovariance(); } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { auto z_pred = eig_vec(n_z_laser_); auto S = eig_mat(n_z_laser_ , n_z_laser_); auto Zsig = eig_mat(n_z_laser_, 2 * n_aug_ + 1); GenLaserMeasSigPoints(Zsig); PredictLaserMeasurement(Zsig, z_pred, S); auto Tc = eig_mat(n_x_, n_z_laser_); eig_vec z_diff = eig_vec::Zero(n_z_laser_); UpdateCommon(meas_package, z_pred, S, Zsig, Tc, z_diff); NIS_laser_ = z_diff.transpose() * S.inverse() * z_diff; std::cout << "NIS_L = " << NIS_laser_ << std::endl; } void UKF::UpdateCommon(const MeasurementPackage& meas_package, const eig_mat& z_pred, const eig_mat& S, const eig_mat& Zsig, eig_mat& Tc, eig_vec& z_diff) { Tc.fill(0.0); for(int i = 0; i < 2 * n_aug_ + 1; i++) { z_diff = Zsig.col(i) - z_pred; //angle normalization while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; // state difference eig_vec x_diff = Xsig_pred_.col(i) - x_; //angle normalization while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI; while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI; Tc = Tc + weights_(i) * x_diff * z_diff.transpose(); } //Kalman gain K; eig_mat K = Tc * S.inverse(); //residual z_diff = meas_package.raw_measurements_ - z_pred; //angle normalization while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; //update state mean and covariance matrix x_ = x_ + K * z_diff; P_ = P_ - K*S*K.transpose(); } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { auto z_pred = eig_vec(n_z_radar_); auto S = eig_mat(n_z_radar_ , n_z_radar_); auto Zsig = eig_mat(n_z_radar_, 2 * n_aug_ + 1); GenRadarMeasSigPoints(Zsig); PredictRadarMeasurement(Zsig, z_pred, S); auto Tc = eig_mat(n_x_, n_z_radar_); eig_vec z_diff = eig_vec::Zero(n_z_radar_); UpdateCommon(meas_package, z_pred, S, Zsig, Tc, z_diff); NIS_radar_ = z_diff.transpose() * S.inverse() * z_diff; std::cout << "NIS_R = " << NIS_radar_ << std::endl; } void UKF::GenAugmentedSigmaPoints(eig_mat& aug_sigma_points) { auto x_aug = eig_vec(n_aug_); x_aug.setZero(); auto P_aug = eig_mat(n_aug_, n_aug_); x_aug.head(n_x_) = x_; P_aug.fill(0); P_aug.topLeftCorner(n_x_, n_x_) = P_; P_aug(5,5) = std_a_ * std_a_; P_aug(6,6) = std_yawdd_ * std_yawdd_; //create square root matrix eig_mat A = P_aug.llt().matrixL(); //create augmented sigma points aug_sigma_points.col(0) = x_aug; for (int i = 0; i < n_aug_; i++) { aug_sigma_points.col(i + 1) = x_aug + sqrt(lambda_ + n_aug_) * A.col(i); aug_sigma_points.col(i + 1 + n_aug_) = x_aug - sqrt(lambda_ + n_aug_) * A.col(i); } } void UKF::PredictSigmaPoints(const eig_mat& aug_sigma_points, double delta_t) { for(int i = 0; i < 2 * n_aug_ + 1; ++i) { double p_x = aug_sigma_points(0,i); double p_y = aug_sigma_points(1,i); double v = aug_sigma_points(2,i); double yaw = aug_sigma_points(3,i); double yawd = aug_sigma_points(4,i); double nu_a = aug_sigma_points(5,i); double nu_yawdd = aug_sigma_points(6,i); double px_p, py_p; if (fabs(yawd) > 0.001) { px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw)); py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) ); } else { px_p = p_x + v*delta_t*cos(yaw); py_p = p_y + v*delta_t*sin(yaw); } double v_p = v; double yaw_p = yaw + yawd*delta_t; double yawd_p = yawd; px_p = px_p + 0.5*nu_a*delta_t*delta_t * cos(yaw); py_p = py_p + 0.5*nu_a*delta_t*delta_t * sin(yaw); v_p = v_p + nu_a*delta_t; yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t; yawd_p = yawd_p + nu_yawdd*delta_t; Xsig_pred_(0,i) = px_p; Xsig_pred_(1,i) = py_p; Xsig_pred_(2,i) = v_p; Xsig_pred_(3,i) = yaw_p; Xsig_pred_(4,i) = yawd_p; } } void UKF::PredictStateMean() { x_.setZero(); for (int i = 0; i < 2 * n_aug_ + 1; i++) { x_ = x_ + weights_(i) * Xsig_pred_.col(i); } } void UKF::PredictStateCovariance() { P_.setZero(); for (int i = 0; i < 2 * n_aug_ + 1; i++) { eig_vec x_diff = Xsig_pred_.col(i) - x_; while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI; while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI; P_ = P_ + weights_(i) * x_diff * x_diff.transpose() ; } } void UKF::GenRadarMeasSigPoints(eig_mat& z_sig) { for(int i = 0; i < 2 * n_aug_ + 1; ++i) { double px = Xsig_pred_(0, i); double py = Xsig_pred_(1, i); double v = Xsig_pred_(2, i); double psy = Xsig_pred_(3, i); double psy_dot = Xsig_pred_(4, i); double rho = sqrt(px * px + py * py) + 0.000001; // edding small value to avoid division by zero double phi = atan2(py, px); double rho_dot = (px*cos(psy)*v + py*sin(psy)*v)/rho; z_sig(0, i) = rho; z_sig(1, i) = phi; z_sig(2, i) = rho_dot; } } void UKF::GenLaserMeasSigPoints(eig_mat& z_sig) { for(int i = 0; i < 2 * n_aug_ + 1; ++i) { double px = Xsig_pred_(0, i); double py = Xsig_pred_(1, i); z_sig(0, i) = px; z_sig(1, i) = py; } } void UKF::PredictRadarMeasurement(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) { CalcInnovCovMat(z_sig, z_pred, S); S = S + R_radar_; } void UKF::PredictLaserMeasurement(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) { CalcInnovCovMat(z_sig, z_pred, S); S = S + R_laser_; } void UKF::CalcInnovCovMat(const eig_mat& z_sig, eig_vec& z_pred, eig_mat& S) { //calculate mean predicted measurement z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { z_pred = z_pred + weights_(i) * z_sig.col(i); } //calculate innovation covariance matrix S S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { //residual eig_vec z_diff = z_sig.col(i) - z_pred; //angle normalization while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI; S = S + weights_(i) * z_diff * z_diff.transpose(); } }
28.257143
100
0.649646
grygoryant
4a3422dd5e1a7764a8d02b0d968a73607a3a7a25
417
cpp
C++
engine/mysqlparser/listener/CheckSqlStatementListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
1
2020-10-23T09:38:22.000Z
2020-10-23T09:38:22.000Z
engine/mysqlparser/listener/CheckSqlStatementListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
engine/mysqlparser/listener/CheckSqlStatementListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
// // Created by zhukovasky on 2020/10/13. // #include "CheckSqlStatementListener.h" void CheckSqlStatementListener::exitSql_statement(parser::MySQLParser::Sql_statementContext *context) { MySQLParserBaseListener::exitSql_statement(context); } void CheckSqlStatementListener::enterSql_statement(parser::MySQLParser::Sql_statementContext *context) { MySQLParserBaseListener::enterSql_statement(context); }
27.8
104
0.810552
zhukovaskychina
6653f1069ceef9716aa05f73235434f7710e31da
19,579
hpp
C++
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
everitoken/evt
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
[ "Apache-2.0" ]
1,411
2018-04-23T03:57:30.000Z
2022-02-13T10:34:22.000Z
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
baby636/evt
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
[ "Apache-2.0" ]
27
2018-06-11T10:34:42.000Z
2019-07-27T08:50:02.000Z
libraries/chain/include/evt/chain/contracts/evt_contract_utils.hpp
baby636/evt
3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea
[ "Apache-2.0" ]
364
2018-06-09T12:11:53.000Z
2020-12-15T03:26:48.000Z
/** * @file * @copyright defined in evt/LICENSE.txt */ #pragma once namespace evt { namespace chain { namespace contracts { /** * Implements addmeta, paycharge, paybonus, prodvote, updsched, addscript and updscript actions */ namespace internal { bool check_involved_node(const group_def& group, const group::node& node, const public_key_type& key) { auto result = false; group.visit_node(node, [&](const auto& n) { if(n.is_leaf()) { if(group.get_leaf_key(n) == key) { result = true; // find one, return false to stop iterate group return false; } return true; } if(check_involved_node(group, n, key)) { result = true; // find one, return false to stop iterate group return false; } return true; }); return result; } auto check_involved_permission = [](auto& tokendb_cache, const auto& permission, const auto& creator) { for(auto& a : permission.authorizers) { auto& ref = a.ref; switch(ref.type()) { case authorizer_ref::account_t: { if(creator.is_account_ref() && ref.get_account() == creator.get_account()) { return true; } break; } case authorizer_ref::group_t: { const auto& name = ref.get_group(); if(creator.is_account_ref()) { auto gp = make_empty_cache_ptr<group_def>(); READ_DB_TOKEN(token_type::group, std::nullopt, name, gp, unknown_group_exception, "Cannot find group: {}", name); if(check_involved_node(*gp, gp->root(), creator.get_account())) { return true; } } else { if(name == creator.get_group()) { return true; } } } } // switch } return false; }; auto check_involved_domain = [](auto& tokendb_cache, const auto& domain, auto pname, const auto& creator) { switch(pname) { case N(issue): { return check_involved_permission(tokendb_cache, domain.issue, creator); } case N(transfer): { return check_involved_permission(tokendb_cache, domain.transfer, creator); } case N(manage): { return check_involved_permission(tokendb_cache, domain.manage, creator); } } // switch return false; }; auto check_involved_fungible = [](auto& tokendb_cache, const auto& fungible, auto pname, const auto& creator) { switch(pname) { case N(manage): { return check_involved_permission(tokendb_cache, fungible.manage, creator); } } // switch return false; }; auto check_involved_group = [](const auto& group, const auto& key) { if(group.key().is_public_key() && group.key().get_public_key() == key) { return true; } return false; }; auto check_involved_owner = [](const auto& token, const auto& key) { for(auto& addr : token.owner) { if(addr.is_public_key() && addr.get_public_key() == key) { return true; } } return false; }; auto check_involved_creator = [](const auto& target, const auto& key) { return target.creator == key; }; template<typename T> bool check_duplicate_meta(const T& v, const meta_key& key) { if(std::find_if(v.metas.cbegin(), v.metas.cend(), [&](const auto& meta) { return meta.key == key; }) != v.metas.cend()) { return true; } return false; } template<> bool check_duplicate_meta<group_def>(const group_def& v, const meta_key& key) { if(std::find_if(v.metas_.cbegin(), v.metas_.cend(), [&](const auto& meta) { return meta.key == key; }) != v.metas_.cend()) { return true; } return false; } auto check_meta_key_reserved = [](const auto& key) { EVT_ASSERT(!key.reserved(), meta_key_exception, "Meta-key is reserved and cannot be used"); }; } // namespace internal EVT_ACTION_IMPL_BEGIN(addmeta) { using namespace internal; const auto& act = context.act; auto& amact = context.act.data_as<add_clr_t<ACT>>(); try { DECLARE_TOKEN_DB() if(act.domain == N128(.group)) { // group check_meta_key_reserved(amact.key); auto gp = make_empty_cache_ptr<group_def>(); READ_DB_TOKEN(token_type::group, std::nullopt, act.key, gp, unknown_group_exception, "Cannot find group: {}", act.key); EVT_ASSERT2(!check_duplicate_meta(*gp, amact.key), meta_key_exception,"Metadata with key: {} already exists.", amact.key); if(amact.creator.is_group_ref()) { EVT_ASSERT(amact.creator.get_group() == gp->name_, meta_involve_exception, "Only group itself can add its own metadata"); } else { // check involved, only group manager(aka. group key) can add meta EVT_ASSERT(check_involved_group(*gp, amact.creator.get_account()), meta_involve_exception, "Creator is not involved in group: ${name}.", ("name",act.key)); } gp->metas_.emplace_back(meta(amact.key, amact.value, amact.creator)); UPD_DB_TOKEN(token_type::group, *gp); } else if(act.domain == N128(.fungible)) { // fungible if(amact.key.reserved()) { EVT_ASSERT(check_reserved_meta(amact, fungible_metas), meta_key_exception, "Meta-key is reserved and cannot be used"); } auto fungible = make_empty_cache_ptr<fungible_def>(); READ_DB_TOKEN(token_type::fungible, std::nullopt, (symbol_id_type)std::stoul((std::string)act.key), fungible, unknown_fungible_exception, "Cannot find fungible with symbol id: {}", act.key); EVT_ASSERT(!check_duplicate_meta(*fungible, amact.key), meta_key_exception, "Metadata with key ${key} already exists.", ("key",amact.key)); if(amact.creator.is_account_ref()) { // check involved, only creator or person in `manage` permission can add meta auto involved = check_involved_creator(*fungible, amact.creator.get_account()) || check_involved_fungible(tokendb_cache, *fungible, N(manage), amact.creator); EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in fungible: ${name}.", ("name",act.key)); } else { // check involved, only group in `manage` permission can add meta EVT_ASSERT(check_involved_fungible(tokendb_cache, *fungible, N(manage), amact.creator), meta_involve_exception, "Creator is not involved in fungible: ${name}.", ("name",act.key)); } fungible->metas.emplace_back(meta(amact.key, amact.value, amact.creator)); UPD_DB_TOKEN(token_type::fungible, *fungible); } else if(act.key == N128(.meta)) { // domain if(amact.key.reserved()) { EVT_ASSERT(check_reserved_meta(amact, domain_metas), meta_key_exception, "Meta-key is reserved and cannot be used"); } auto domain = make_empty_cache_ptr<domain_def>(); READ_DB_TOKEN(token_type::domain, std::nullopt, act.domain, domain, unknown_domain_exception, "Cannot find domain: {}", act.domain); EVT_ASSERT(!check_duplicate_meta(*domain, amact.key), meta_key_exception, "Metadata with key ${key} already exists.", ("key",amact.key)); // check involved, only person involved in `manage` permission can add meta EVT_ASSERT(check_involved_domain(tokendb_cache, *domain, N(manage), amact.creator), meta_involve_exception, "Creator is not involved in domain: ${name}.", ("name",act.key)); domain->metas.emplace_back(meta(amact.key, amact.value, amact.creator)); UPD_DB_TOKEN(token_type::domain, *domain); } else { // token check_meta_key_reserved(amact.key); auto token = make_empty_cache_ptr<token_def>(); READ_DB_TOKEN(token_type::token, act.domain, act.key, token, unknown_token_exception, "Cannot find token: {} in {}", act.key, act.domain); EVT_ASSERT(!check_token_destroy(*token), token_destroyed_exception, "Metadata cannot be added on destroyed token."); EVT_ASSERT(!check_token_locked(*token), token_locked_exception, "Metadata cannot be added on locked token."); EVT_ASSERT(!check_duplicate_meta(*token, amact.key), meta_key_exception, "Metadata with key ${key} already exists.", ("key",amact.key)); auto domain = make_empty_cache_ptr<domain_def>(); READ_DB_TOKEN(token_type::domain, std::nullopt, act.domain, domain, unknown_domain_exception, "Cannot find domain: {}", amact.key); if(amact.creator.is_account_ref()) { // check involved, only person involved in `issue` and `transfer` permissions or `owners` can add meta auto involved = check_involved_owner(*token, amact.creator.get_account()) || check_involved_domain(tokendb_cache, *domain, N(issue), amact.creator) || check_involved_domain(tokendb_cache, *domain, N(transfer), amact.creator); EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in token ${domain}-${name}.", ("domain",act.domain)("name",act.key)); } else { // check involved, only group involved in `issue` and `transfer` permissions can add meta auto involved = check_involved_domain(tokendb_cache, *domain, N(issue), amact.creator) || check_involved_domain(tokendb_cache, *domain, N(transfer), amact.creator); EVT_ASSERT(involved, meta_involve_exception, "Creator is not involved in token ${domain}-${name}.", ("domain",act.domain)("name",act.key)); } token->metas.emplace_back(meta(amact.key, amact.value, amact.creator)); UPD_DB_TOKEN(token_type::token, *token); } } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() EVT_ACTION_IMPL_BEGIN(paycharge) { using namespace internal; auto& pcact = context.act.data_as<add_clr_t<ACT>>(); try { DECLARE_TOKEN_DB() property_stakes evt, pevt; READ_DB_ASSET_NO_THROW_NO_NEW(pcact.payer, pevt_sym(), pevt); auto paid = std::min((int64_t)pcact.charge, pevt.amount); if(paid > 0) { pevt.amount -= paid; PUT_DB_ASSET(pcact.payer, pevt); } if(paid < pcact.charge) { READ_DB_ASSET_NO_THROW_NO_NEW(pcact.payer, evt_sym(), evt); auto remain = pcact.charge - paid; if(evt.amount < (int64_t)remain) { EVT_THROW2(charge_exceeded_exception,"There are only {} and {} left, but charge is {}", asset(evt.amount, evt_sym()), asset(pevt.amount, pevt_sym()), asset(pcact.charge, evt_sym())); } evt.amount -= remain; PUT_DB_ASSET(pcact.payer, evt); } auto pbs = context.control.pending_block_state(); auto& prod = pbs->get_scheduled_producer(pbs->header.timestamp).block_signing_key; property_stakes bp; READ_DB_ASSET_NO_THROW(address(prod), evt_sym(), bp); // give charge to producer bp.amount += pcact.charge; PUT_DB_ASSET(prod, bp); } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() EVT_ACTION_IMPL_BEGIN(paybonus) { // empty body // will not execute here assert(false); return; } EVT_ACTION_IMPL_END() namespace internal { auto update_chain_config = [](auto& conf, auto key, auto v) { switch(key.value) { case N128(network-charge-factor): { conf.base_network_charge_factor = v; break; } case N128(storage-charge-factor): { conf.base_storage_charge_factor = v; break; } case N128(cpu-charge-factor): { conf.base_cpu_charge_factor = v; break; } case N128(global-charge-factor): { conf.global_charge_factor = v; break; } default: { EVT_THROW2(prodvote_key_exception, "Configuration key: {} is not valid", key); } } // switch }; } // namespace internal EVT_ACTION_IMPL_BEGIN(prodvote) { using namespace internal; auto& pvact = context.act.data_as<add_clr_t<ACT>>(); try { EVT_ASSERT(context.has_authorized(N128(.prodvote), pvact.key), action_authorize_exception, "Invalid authorization fields in action(domain and key)."); EVT_ASSERT(pvact.value > 0 && pvact.value < 1'000'000, prodvote_value_exception, "Invalid prodvote value: ${v}", ("v",pvact.value)); auto conf = context.control.get_global_properties().configuration; auto& sche = context.control.active_producers(); auto& exec_ctx = context.control.get_execution_context(); DECLARE_TOKEN_DB() auto updact = false; auto act = name(); // test if it's action-upgrade vote and wheather action is valid { auto key = pvact.key.to_string(); if(boost::starts_with(key, "action-")) { try { act = name(key.substr(7)); } catch(name_type_exception&) { EVT_THROW2(prodvote_key_exception, "Invalid action name provided: {}", key.substr(7)); } auto cver = exec_ctx.get_current_version(act); auto mver = exec_ctx.get_max_version(act); EVT_ASSERT2(pvact.value >= cver && pvact.value <= exec_ctx.get_max_version(act), prodvote_value_exception, "Provided version: {} for action: {} is not valid, should be in range ({},{}]", pvact.value, act, cver, mver); updact = true; } } auto pkey = sche.get_producer_key(pvact.producer); EVT_ASSERT(pkey.has_value(), prodvote_producer_exception, "${p} is not a valid producer", ("p",pvact.producer)); auto map = make_empty_cache_ptr<flat_map<public_key_type, int64_t>>(); READ_DB_TOKEN_NO_THROW(token_type::prodvote, std::nullopt, pvact.key, map); if(map == nullptr) { auto newmap = flat_map<public_key_type, int64_t>(); newmap.emplace(*pkey, pvact.value); map = tokendb_cache.put_token<std::add_rvalue_reference_t<decltype(newmap)>, true>( token_type::prodvote, action_op::put, std::nullopt, pvact.key, std::move(newmap)); } else { auto it = map->emplace(*pkey, pvact.value); if(it.second == false) { // existed EVT_ASSERT2(it.first->second != pvact.value, prodvote_value_exception, "Value voted for {} is the same as previous voted", pvact.key); it.first->second = pvact.value; } tokendb_cache.put_token(token_type::prodvote, action_op::put, std::nullopt, pvact.key, *map); } auto is_prod = [&](auto& pk) { for(auto& p : sche.producers) { if(p.block_signing_key == pk) { return true; } } return false; }; auto values = std::vector<int64_t>(); for(auto& it : *map) { if(is_prod(it.first)) { values.emplace_back(it.second); } } auto limit = (int64_t)values.size(); if(values.size() != sche.producers.size()) { limit = ::ceil(2.0 * sche.producers.size() / 3.0); if((int64_t)values.size() <= limit) { // if the number of votes is equal or less than 2/3 producers // don't update return; } } if(!updact) { // general global config updates, find the median and update int64_t nv = 0; // find median if(values.size() % 2 == 0) { auto it1 = values.begin() + values.size() / 2 - 1; auto it2 = values.begin() + values.size() / 2; std::nth_element(values.begin(), it1 , values.end()); std::nth_element(values.begin(), it2 , values.end()); nv = ::floor((*it1 + *it2) / 2); } else { auto it = values.begin() + values.size() / 2; std::nth_element(values.begin(), it , values.end()); nv = *it; } update_chain_config(conf, pvact.key, nv); context.control.set_chain_config(conf); } else { // update action version // find the all the votes which vote-version is large than current version // and update version with the version which has more than 2/3 votes of producers auto cver = exec_ctx.get_current_version(act); auto map = flat_map<int, int>(); // maps version to votes for(auto& v : values) { if(v > cver) { map[v] += 1; } } for(auto& it : map) { if(it.second >= limit) { exec_ctx.set_version(act, it.first); break; } } } } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() EVT_ACTION_IMPL_BEGIN(updsched) { auto usact = context.act.data_as<ACT>(); try { EVT_ASSERT(context.has_authorized(N128(.prodsched), N128(.update)), action_authorize_exception, "Invalid authorization fields in action(domain and key)."); context.control.set_proposed_producers(std::move(usact.producers)); } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() EVT_ACTION_IMPL_BEGIN(newscript) { using namespace internal; auto asact = context.act.data_as<ACT>(); try { EVT_ASSERT(context.has_authorized(N128(.script), asact.name), action_authorize_exception, "Invalid authorization fields in action(domain and key)."); DECLARE_TOKEN_DB() EVT_ASSERT2(!tokendb.exists_token(token_type::script, std::nullopt, asact.name), script_duplicate_exception, "Script: {} already exists.", asact.name); auto script = script_def(); script.name = asact.name; script.content = asact.content; script.creator = asact.creator; ADD_DB_TOKEN(token_type::script, script); } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() EVT_ACTION_IMPL_BEGIN(updscript) { using namespace internal; auto usact = context.act.data_as<ACT>(); try { EVT_ASSERT(context.has_authorized(N128(.script), usact.name), action_authorize_exception, "Invalid authorization fields in action(domain and key)."); DECLARE_TOKEN_DB() auto script = make_empty_cache_ptr<script_def>(); READ_DB_TOKEN(token_type::script, std::nullopt, usact.name, script, unknown_script_exception,"Cannot find script: {}", usact.name); script->content = usact.content; UPD_DB_TOKEN(token_type::script, *script); } EVT_CAPTURE_AND_RETHROW(tx_apply_exception); } EVT_ACTION_IMPL_END() }}} // namespace evt::chain::contracts
38.847222
155
0.597579
everitoken
66563bb8e35abe71e4e45296d5d345ddc6abf425
2,255
cpp
C++
implementations/ugene/src/plugins/pcr/src/PrimerLibraryTableController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/pcr/src/PrimerLibraryTableController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/pcr/src/PrimerLibraryTableController.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "PrimerLibraryTableController.h" #include <U2Core/U2OpStatusUtils.h> #include <U2Core/U2SafePoints.h> #include "PrimerLibrary.h" #include "PrimerLibraryTable.h" namespace U2 { PrimerLibraryTableController::PrimerLibraryTableController(QObject *parent, PrimerLibraryTable *table) : QObject(parent), table(table) { SAFE_POINT(NULL != table, "Primer library table is NULL", ); U2OpStatus2Log os; library = PrimerLibrary::getInstance(os); SAFE_POINT_OP(os, ); connect(library, SIGNAL(si_primerAdded(const U2DataId &)), SLOT(sl_primerAdded(const U2DataId &))); connect(library, SIGNAL(si_primerChanged(const U2DataId &)), SLOT(sl_primerChanged(const U2DataId &))); connect(library, SIGNAL(si_primerRemoved(const U2DataId &)), SLOT(sl_primerRemoved(const U2DataId &))); } void PrimerLibraryTableController::sl_primerAdded(const U2DataId &primerId) { U2OpStatus2Log os; Primer primer = library->getPrimer(primerId, os); CHECK_OP(os, ); table->addPrimer(primer); } void PrimerLibraryTableController::sl_primerChanged(const U2DataId &primerId) { U2OpStatus2Log os; Primer primer = library->getPrimer(primerId, os); CHECK_OP(os, ); table->updatePrimer(primer); } void PrimerLibraryTableController::sl_primerRemoved(const U2DataId &primerId) { U2OpStatus2Log os; table->removePrimer(primerId, os); } } // namespace U2
34.166667
107
0.740133
r-barnes
6657f123be8a1b44c7f57c2e4f7376537a99460b
894
hpp
C++
stapl_release/stapl/views/proxy/accessor_traits.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/proxy/accessor_traits.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/proxy/accessor_traits.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_VIEWS_PROXY_ACCESSOR_TRAITS_HPP #define STAPL_VIEWS_PROXY_ACCESSOR_TRAITS_HPP namespace stapl { ////////////////////////////////////////////////////////////////////// /// @brief Metafunction that defines traits for accessors. /// /// @tparam Accessor Accessor in question ////////////////////////////////////////////////////////////////////// template<typename Accessor> struct accessor_traits { typedef std::false_type is_localized; }; } // namespace stapl #endif // STAPL_VIEWS_PROXY_ACCESSOR_TRAITS_HPP
28.83871
74
0.658837
parasol-ppl
6658fc7765e5b55eb33e464cfc1a36f7ca747ecb
6,006
cc
C++
tests/core/test_reencode_string_table.cc
JCSDA/odc-1
8a120ebc744778248dda0267094cbf9aaa9d7246
[ "Apache-2.0" ]
2
2020-03-17T15:44:50.000Z
2020-11-18T09:28:18.000Z
tests/core/test_reencode_string_table.cc
JCSDA/odc-1
8a120ebc744778248dda0267094cbf9aaa9d7246
[ "Apache-2.0" ]
4
2020-03-25T20:50:46.000Z
2021-10-20T00:03:19.000Z
tests/core/test_reencode_string_table.cc
JCSDA/odc-1
8a120ebc744778248dda0267094cbf9aaa9d7246
[ "Apache-2.0" ]
6
2020-03-30T16:43:22.000Z
2021-11-14T09:22:07.000Z
/* * (C) Copyright 1996-2012 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <ctime> #include <cstdlib> #include <algorithm> #include <cmath> #include "eckit/testing/Test.h" #include "eckit/system/SystemInfo.h" #include "eckit/eckit_ecbuild_config.h" #include "odc/api/ColumnType.h" #include "odc/core/Codec.h" #include "odc/codec/String.h" using namespace eckit::testing; using namespace odc::core; using namespace odc::codec; // ------------------------------------------------------------------------------------------------------ // TODO with codecs: // // i) Make them templated on the stream/datahandle directly // ii) Construct them with a specific data handle/stream // iii) Why are we casting data handles via a void* ??? // Given the codec-initialising data, add the header on that is used to construct the // codec. size_t prepend_codec_selection_header(std::vector<unsigned char>& data, const std::string& codec_name, bool bigEndian=false) { data.insert(data.begin(), 4, 0); data[bigEndian ? 3 : 0] = static_cast<unsigned char>(codec_name.size()); data.insert(data.begin() + 4, codec_name.begin(), codec_name.end()); return 4 + codec_name.length(); } CASE("Character strings can be stored in a flat list, and indexed") { // n.b. no missing values const char* source_data[] = { // Codec header "\x00\x00\x00\x00", // 0 = hasMissing "\x00\x00\x00\x00\x00\x00\x00\x00", // min unspecified "\x00\x00\x00\x00\x00\x00\x00\x00", // max unspecified "\x00\x00\x00\x00\x00\x00\x00\x00", // missingValue unspecified // How many strings are there in the table? "\x06\x00\x00\x00", // String data (prepended with lengths) // length, data, "cnt (discarded)", index "\x08\x00\x00\x00", "ghijklmn", "\x00\x00\x00\x00", "\x00\x00\x00\x00", "\x0c\x00\x00\x00", "uvwxyzabcdef", "\x00\x00\x00\x00", "\x01\x00\x00\x00", // too long "\x08\x00\x00\x00", "opqrstuv", "\x00\x00\x00\x00", "\x02\x00\x00\x00", "\x02\x00\x00\x00", "ab", "\x00\x00\x00\x00", "\x03\x00\x00\x00", // This string is too short "\x06\x00\x00\x00", "ghijkl", "\x00\x00\x00\x00", "\x04\x00\x00\x00", "\x08\x00\x00\x00", "mnopqrst", "\x00\x00\x00\x00", "\x05\x00\x00\x00", // 8-byte length }; // Loop throumgh endiannesses for the source data for (int i = 0; i < 4; i++) { bool bigEndianSource = (i % 2 == 0); bool bits16 = (i > 1); std::vector<unsigned char> data; for (size_t j = 0; j < sizeof(source_data) / sizeof(const char*); j++) { size_t len = (j < 5) ? ((j == 0 || j == 4) ? 4 : 8) : ((j+2) % 4 == 0 ? ::strlen(source_data[j]) : 4); data.insert(data.end(), source_data[j], source_data[j] + len); // n.b. Don't reverse the endianness of the string data. if (bigEndianSource && !((j > 5) && ((j+2) % 4 == 0))) std::reverse(data.end()-len, data.end()); } // Which strings do we wish to decode (look at them in reverse. nb refers to index column) for (int n = 5; n >= 0; n--) { if (bits16 && bigEndianSource) data.push_back(0); data.push_back(static_cast<unsigned char>(n)); if (bits16 && !bigEndianSource) data.push_back(0); } // Construct codec directly, and decode the header // Skip name of codec GeneralDataStream ds(bigEndianSource != eckit::system::SystemInfo::isBigEndian(), &data[0], data.size()); std::unique_ptr<Codec> c; if (bigEndianSource == eckit::system::SystemInfo::isBigEndian()) { if (bits16) { c.reset(new CodecInt16String<SameByteOrder>(odc::api::STRING)); } else { c.reset(new CodecInt8String<SameByteOrder>(odc::api::STRING)); } } else { if (bits16) { c.reset(new CodecInt16String<OtherByteOrder>(odc::api::STRING)); } else { c.reset(new CodecInt8String<OtherByteOrder>(odc::api::STRING)); } } c->load(ds); EXPECT(ds.position() == eckit::Offset(148)); // Now re-encode the codec header, and check that we get what we started with! eckit::Buffer writeBuffer(4096); ::memset(writeBuffer, 0, writeBuffer.size()); GeneralDataStream ds2(bigEndianSource != eckit::system::SystemInfo::isBigEndian(), writeBuffer); c->save(ds2); // Check that the data is the same both times! EXPECT(ds2.position() == eckit::Offset(148)); // eckit::Log::info() << "DATA: " << std::endl; // for (size_t n = 0; n < data.size(); n++) { // eckit::Log::info() << std::hex << int(data[n]) << " " << int(dh_write.getBuffer()[n]) << std::endl; // if (int(data[n]) != int(dh_write.getBuffer()[n])) // eckit::Log::info() << "******************************" << std::endl; // } // The header should be correctly re-encoded. EXPECT(::memcmp(writeBuffer, &data[0], 148) == 0); // We haven't encoded the data itself for (size_t i = 148; i < 154; i++) { EXPECT(writeBuffer[i] == 0); } } } // ------------------------------------------------------------------------------------------------------ int main(int argc, char* argv[]) { return run_tests(argc, argv); }
35.964072
113
0.542624
JCSDA
665a45b48936de7bd1759e91dd45c4da3c5c457e
7,061
cpp
C++
src/widgets/menu_style.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/widgets/menu_style.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/widgets/menu_style.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: menu_style.cpp 48480 2011-02-12 16:20:24Z ivanovic $ */ /* wesnoth menu styles Copyright (C) 2006 - 2011 by Patrick Parker <patrick_x99@hotmail.com> wesnoth menu Copyright (C) 2003-5 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ #define GETTEXT_DOMAIN "wesnoth-lib" #include "global.hpp" #include "widgets/menu.hpp" #include "font.hpp" #include "image.hpp" #include "video.hpp" namespace gui { //static initializations menu::imgsel_style menu::bluebg_style("misc/selection2", true, 0x000000, 0x000000, 0x333333, 0.35, 0.0, 0.3); menu::style menu::simple_style; menu::style &menu::default_style = menu::bluebg_style; menu *empty_menu = NULL; //constructors menu::style::style() : font_size_(font::SIZE_NORMAL), cell_padding_(font::SIZE_NORMAL * 3/5), thickness_(0), normal_rgb_(0x000000), selected_rgb_(0x000099), heading_rgb_(0x333333), normal_alpha_(0.2), selected_alpha_(0.6), heading_alpha_(0.3), max_img_w_(-1), max_img_h_(-1) {} menu::style::~style() {} menu::imgsel_style::imgsel_style(const std::string &img_base, bool has_bg, int normal_rgb, int selected_rgb, int heading_rgb, double normal_alpha, double selected_alpha, double heading_alpha) : img_base_(img_base), has_background_(has_bg), initialized_(false), load_failed_(false), normal_rgb2_(normal_rgb), selected_rgb2_(selected_rgb), heading_rgb2_(heading_rgb), normal_alpha2_(normal_alpha), selected_alpha2_(selected_alpha), heading_alpha2_(heading_alpha) {} menu::imgsel_style::~imgsel_style() {} size_t menu::style::get_font_size() const { return font_size_; } size_t menu::style::get_cell_padding() const { return cell_padding_; } size_t menu::style::get_thickness() const { return thickness_; } void menu::style::scale_images(int max_width, int max_height) { max_img_w_ = max_width; max_img_h_ = max_height; } surface menu::style::get_item_image(const image::locator& img_loc) const { surface surf = image::get_image(img_loc); if(!surf.null()) { int scale = 100; if(max_img_w_ > 0 && surf->w > max_img_w_) { scale = (max_img_w_ * 100) / surf->w; } if(max_img_h_ > 0 && surf->h > max_img_h_) { scale = std::min<int>(scale, ((max_img_h_ * 100) / surf->h)); } if(scale != 100) { return scale_surface(surf, (scale * surf->w)/100, (scale * surf->h)/100); } } return surf; } bool menu::imgsel_style::load_image(const std::string &img_sub) { std::string path = img_base_ + "-" + img_sub + ".png"; const surface image = image::get_image(path); img_map_[img_sub] = image; return(!image.null()); } bool menu::imgsel_style::load_images() { if(!initialized_) { if( load_image("border-botleft") && load_image("border-botright") && load_image("border-topleft") && load_image("border-topright") && load_image("border-left") && load_image("border-right") && load_image("border-top") && load_image("border-bottom") ) { thickness_ = std::min( img_map_["border-top"]->h, img_map_["border-left"]->w); if(has_background_ && !load_image("background")) { load_failed_ = true; } else { normal_rgb_ = normal_rgb2_; normal_alpha_ = normal_alpha2_; selected_rgb_ = selected_rgb2_; selected_alpha_ = selected_alpha2_; heading_rgb_ = heading_rgb2_; heading_alpha_ = heading_alpha2_; load_failed_ = false; } initialized_ = true; } else { thickness_ = 0; initialized_ = true; load_failed_ = true; } } return (!load_failed_); } void menu::imgsel_style::draw_row_bg(menu& menu_ref, const size_t row_index, const SDL_Rect& rect, ROW_TYPE type) { if(type == SELECTED_ROW && has_background_ && !load_failed_) { if(bg_cache_.width != rect.w || bg_cache_.height != rect.h) { //draw scaled background image //scale image each time (to prevent loss of quality) bg_cache_.surf = scale_surface(img_map_["background"], rect.w, rect.h); bg_cache_.width = rect.w; bg_cache_.height = rect.h; } SDL_Rect clip = rect; menu_ref.video().blit_surface(rect.x,rect.y,bg_cache_.surf,NULL,&clip); } else { style::draw_row_bg(menu_ref, row_index, rect, type); } } void menu::imgsel_style::draw_row(menu& menu_ref, const size_t row_index, const SDL_Rect& rect, ROW_TYPE type) { if(!load_failed_) { //draw item inside style::draw_row(menu_ref, row_index, rect, type); if(type == SELECTED_ROW) { // draw border surface image; SDL_Rect area; SDL_Rect clip = rect; area.x = rect.x; area.y = rect.y; image = img_map_["border-top"]; area.x = rect.x; area.y = rect.y; do { menu_ref.video().blit_surface(area.x,area.y,image,NULL,&clip); area.x += image->w; } while( area.x < rect.x + rect.w ); image = img_map_["border-left"]; area.x = rect.x; area.y = rect.y; do { menu_ref.video().blit_surface(area.x,area.y,image,NULL,&clip); area.y += image->h; } while( area.y < rect.y + rect.h ); image = img_map_["border-right"]; area.x = rect.x + rect.w - thickness_; area.y = rect.y; do { menu_ref.video().blit_surface(area.x,area.y,image,NULL,&clip); area.y += image->h; } while( area.y < rect.y + rect.h ); image = img_map_["border-bottom"]; area.x = rect.x; area.y = rect.y + rect.h - thickness_; do { menu_ref.video().blit_surface(area.x,area.y,image,NULL,&clip); area.x += image->w; } while( area.x < rect.x + rect.w ); image = img_map_["border-topleft"]; area.x = rect.x; area.y = rect.y; menu_ref.video().blit_surface(area.x,area.y,image); image = img_map_["border-topright"]; area.x = rect.x + rect.w - image->w; area.y = rect.y; menu_ref.video().blit_surface(area.x,area.y,image); image = img_map_["border-botleft"]; area.x = rect.x; area.y = rect.y + rect.h - image->h; menu_ref.video().blit_surface(area.x,area.y,image); image = img_map_["border-botright"]; area.x = rect.x + rect.w - image->w; area.y = rect.y + rect.h - image->h; menu_ref.video().blit_surface(area.x,area.y,image); } } else { //default drawing style::draw_row(menu_ref, row_index, rect, type); } } SDL_Rect menu::imgsel_style::item_size(const std::string& item) const { SDL_Rect bounds = style::item_size(item); bounds.w += 2 * thickness_; bounds.h += 2 * thickness_; return bounds; } } //namesapce gui
28.938525
114
0.648067
blackberry
665ad027326b931c3a3428d790cf347fcb9e40d6
12,051
cc
C++
mysql-server/sql/dd/impl/types/routine_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/routine_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/routine_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql/dd/impl/types/routine_impl.h" #include <new> #include <sstream> #include <string> #include "lex_string.h" #include "my_sys.h" #include "my_user.h" // parse_user #include "mysql_com.h" #include "mysqld_error.h" #include "sql/dd/dd_utility.h" // normalize_string() #include "sql/dd/impl/raw/raw_record.h" // Raw_record #include "sql/dd/impl/tables/parameters.h" // Parameters #include "sql/dd/impl/tables/routines.h" // Routines #include "sql/dd/impl/tables/schemata.h" // Schemata::name_collation #include "sql/dd/impl/transaction_impl.h" // Open_dictionary_tables_ctx #include "sql/dd/impl/types/parameter_impl.h" // Parameter_impl #include "sql/dd/impl/utils.h" // is_string_in_lowercase #include "sql/dd/string_type.h" // dd::String_type #include "sql/dd/types/parameter.h" #include "sql/dd/types/weak_object.h" using dd::tables::Parameters; using dd::tables::Routines; namespace dd { /////////////////////////////////////////////////////////////////////////// // Routine_impl implementation. /////////////////////////////////////////////////////////////////////////// Routine_impl::Routine_impl() : m_routine_type(RT_PROCEDURE), m_sql_data_access(SDA_CONTAINS_SQL), m_security_type(View::ST_INVOKER), m_is_deterministic(false), m_sql_mode(0), m_created(0), m_last_altered(0), m_parameters(), m_schema_id(INVALID_OBJECT_ID), m_client_collation_id(INVALID_OBJECT_ID), m_connection_collation_id(INVALID_OBJECT_ID), m_schema_collation_id(INVALID_OBJECT_ID) {} Routine_impl::~Routine_impl() {} /////////////////////////////////////////////////////////////////////////// bool Routine_impl::validate() const { if (schema_id() == INVALID_OBJECT_ID) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "Schema ID is not set"); return true; } return false; } /////////////////////////////////////////////////////////////////////////// bool Routine_impl::restore_children(Open_dictionary_tables_ctx *otx) { return m_parameters.restore_items( this, otx, otx->get_table<Parameter>(), Parameters::create_key_by_routine_id(this->id())); } /////////////////////////////////////////////////////////////////////////// bool Routine_impl::store_children(Open_dictionary_tables_ctx *otx) { return m_parameters.store_items(otx); } /////////////////////////////////////////////////////////////////////////// bool Routine_impl::drop_children(Open_dictionary_tables_ctx *otx) const { return m_parameters.drop_items( otx, otx->get_table<Parameter>(), Parameters::create_key_by_routine_id(this->id())); } ///////////////////////////////////////////////////////////////////////// bool Routine_impl::restore_attributes(const Raw_record &r) { // Read id and name. restore_id(r, Routines::FIELD_ID); restore_name(r, Routines::FIELD_NAME); // Read enums m_routine_type = (enum_routine_type)r.read_int(Routines::FIELD_TYPE); m_sql_data_access = (enum_sql_data_access)r.read_int(Routines::FIELD_SQL_DATA_ACCESS); m_security_type = (View::enum_security_type)r.read_int(Routines::FIELD_SECURITY_TYPE); // Read booleans m_is_deterministic = r.read_bool(Routines::FIELD_IS_DETERMINISTIC); // Read ulonglong m_sql_mode = r.read_int(Routines::FIELD_SQL_MODE); m_created = r.read_int(Routines::FIELD_CREATED); m_last_altered = r.read_int(Routines::FIELD_LAST_ALTERED); // Read references m_schema_id = r.read_ref_id(Routines::FIELD_SCHEMA_ID); m_client_collation_id = r.read_ref_id(Routines::FIELD_CLIENT_COLLATION_ID); m_connection_collation_id = r.read_ref_id(Routines::FIELD_CONNECTION_COLLATION_ID); m_schema_collation_id = r.read_ref_id(Routines::FIELD_SCHEMA_COLLATION_ID); // Read strings m_definition = r.read_str(Routines::FIELD_DEFINITION); m_definition_utf8 = r.read_str(Routines::FIELD_DEFINITION_UTF8); m_parameter_str = r.read_str(Routines::FIELD_PARAMETER_STR); m_comment = r.read_str(Routines::FIELD_COMMENT); // Read definer user/host { String_type definer = r.read_str(Routines::FIELD_DEFINER); char user_name_holder[USERNAME_LENGTH + 1]; LEX_STRING user_name = {user_name_holder, USERNAME_LENGTH}; char host_name_holder[HOSTNAME_LENGTH + 1]; LEX_STRING host_name = {host_name_holder, HOSTNAME_LENGTH}; parse_user(definer.c_str(), definer.length(), user_name.str, &user_name.length, host_name.str, &host_name.length); m_definer_user.assign(user_name.str, user_name.length); m_definer_host.assign(host_name.str, host_name.length); } return false; } /////////////////////////////////////////////////////////////////////////// bool Routine_impl::store_attributes(Raw_record *r) { dd::Stringstream_type definer; definer << m_definer_user << '@' << m_definer_host; return store_id(r, Routines::FIELD_ID) || store_name(r, Routines::FIELD_NAME) || r->store(Routines::FIELD_SCHEMA_ID, m_schema_id) || r->store(Routines::FIELD_NAME, name()) || r->store(Routines::FIELD_TYPE, m_routine_type) || r->store(Routines::FIELD_DEFINITION, m_definition) || r->store(Routines::FIELD_DEFINITION_UTF8, m_definition_utf8) || r->store(Routines::FIELD_PARAMETER_STR, m_parameter_str) || r->store(Routines::FIELD_IS_DETERMINISTIC, m_is_deterministic) || r->store(Routines::FIELD_SQL_DATA_ACCESS, m_sql_data_access) || r->store(Routines::FIELD_SECURITY_TYPE, m_security_type) || r->store(Routines::FIELD_DEFINER, definer.str()) || r->store(Routines::FIELD_SQL_MODE, m_sql_mode) || r->store(Routines::FIELD_CLIENT_COLLATION_ID, m_client_collation_id) || r->store(Routines::FIELD_CONNECTION_COLLATION_ID, m_connection_collation_id) || r->store(Routines::FIELD_SCHEMA_COLLATION_ID, m_schema_collation_id) || r->store(Routines::FIELD_CREATED, m_created) || r->store(Routines::FIELD_LAST_ALTERED, m_last_altered) || r->store(Routines::FIELD_COMMENT, m_comment, m_comment.empty()); } /////////////////////////////////////////////////////////////////////////// bool Routine::update_id_key(Id_key *key, Object_id id) { key->update(id); return false; } /////////////////////////////////////////////////////////////////////////// void Routine_impl::debug_print(String_type &outb) const { dd::Stringstream_type ss; ss << "id: {OID: " << id() << "}; " << "m_name: " << name() << "; " << "m_routine_type: " << m_routine_type << "; " << "m_sql_data_access: " << m_sql_data_access << "; " << "m_security_type: " << m_security_type << "; " << "m_is_deterministic: " << m_is_deterministic << "; " << "m_sql_mode: " << m_sql_mode << "; " << "m_created: " << m_created << "; " << "m_last_altered: " << m_last_altered << "; " << "m_definition: " << m_definition << "; " << "m_definition_utf8: " << m_definition_utf8 << "; " << "m_parameter_str: " << m_parameter_str << "; " << "m_definer_user: " << m_definer_user << "; " << "m_definer_host: " << m_definer_host << "; " << "m_comment: " << m_comment << "; " << "m_schema_id: {OID: " << m_schema_id << "}; " << "m_client_collation_id: " << m_client_collation_id << "; " << "m_connection_collation_id: " << m_connection_collation_id << "; " << "m_schema_collation_id: " << m_schema_collation_id << "; " << "m_parameters: " << m_parameters.size() << " [ "; for (const Parameter *f : parameters()) { String_type ob; f->debug_print(ob); ss << ob; } ss << "] "; outb = ss.str(); } /////////////////////////////////////////////////////////////////////////// Parameter *Routine_impl::add_parameter() { Parameter_impl *p = new (std::nothrow) Parameter_impl(this); m_parameters.push_back(p); return p; } /////////////////////////////////////////////////////////////////////////// const Object_table &Routine_impl::object_table() const { return DD_table::instance(); } /////////////////////////////////////////////////////////////////////////// void Routine_impl::register_tables(Open_dictionary_tables_ctx *otx) { otx->add_table<Routines>(); otx->register_tables<Parameter>(); } /////////////////////////////////////////////////////////////////////////// Routine_impl::Routine_impl(const Routine_impl &src) : Weak_object(src), Entity_object_impl(src), m_routine_type(src.m_routine_type), m_sql_data_access(src.m_sql_data_access), m_security_type(src.m_security_type), m_is_deterministic(src.m_is_deterministic), m_sql_mode(src.m_sql_mode), m_created(src.m_created), m_last_altered(src.m_last_altered), m_definition(src.m_definition), m_definition_utf8(src.m_definition_utf8), m_parameter_str(src.m_parameter_str), m_definer_user(src.m_definer_user), m_definer_host(src.m_definer_host), m_comment(src.m_comment), m_parameters(), m_schema_id(src.m_schema_id), m_client_collation_id(src.m_client_collation_id), m_connection_collation_id(src.m_connection_collation_id), m_schema_collation_id(src.m_schema_collation_id) { m_parameters.deep_copy(src.m_parameters, this); } /////////////////////////////////////////////////////////////////////////// void Routine::create_mdl_key(enum_routine_type type, const String_type &schema_name, const String_type &name, MDL_key *mdl_key) { #ifndef DEBUG_OFF // Make sure schema name is lowercased when lower_case_table_names == 2. if (lower_case_table_names == 2) DBUG_ASSERT(is_string_in_lowercase(schema_name, tables::Schemata::name_collation())); DBUG_EXECUTE_IF("simulate_lctn_two_case_for_schema_case_compare", { DBUG_ASSERT( (lower_case_table_names == 2) || is_string_in_lowercase(schema_name, &my_charset_utf8_tolower_ci)); }); #endif /* Normalize the routine name so that key comparison for case and accent insensitive routine names yields the correct result. */ char normalized_name[NAME_CHAR_LEN * 2]; size_t len = normalize_string(DD_table::name_collation(), name, normalized_name, sizeof(normalized_name)); mdl_key->mdl_key_init( type == RT_FUNCTION ? MDL_key::FUNCTION : MDL_key::PROCEDURE, schema_name.c_str(), normalized_name, len, name.c_str()); } /////////////////////////////////////////////////////////////////////////// const CHARSET_INFO *Routine::name_collation() { return DD_table::name_collation(); } /////////////////////////////////////////////////////////////////////////// } // namespace dd
37.659375
80
0.623019
silenc3502
665aeed8c479167df9775fc3b7dffe99f6daf42b
3,986
cc
C++
src/devices/pwm/bin/pwmctl/pwmctl.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/devices/pwm/bin/pwmctl/pwmctl.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2022-03-01T01:12:04.000Z
2022-03-01T01:17:26.000Z
src/devices/pwm/bin/pwmctl/pwmctl.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia 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 "pwmctl.h" #include <stdlib.h> #include <string> #include <soc/aml-common/aml-pwm-regs.h> namespace pwmctl { constexpr long kBadParse = -1; long parse_positive_long(const char* number) { char* end; long result = strtol(number, &end, 10); if (end == number || *end != '\0' || result < 0) { return kBadParse; } return result; } float parse_positive_float(const char* number) { char* end; float result = strtof(number, &end); if (end == number || *end != '\0' || result < 0) { return kBadParse; } return result; } namespace cmd_str { constexpr char kEnable[] = "enable"; constexpr char kDisable[] = "disable"; constexpr char kSetConfig[] = "config"; } // namespace cmd_str zx_status_t enable(fidl::WireSyncClient<fuchsia_hardware_pwm::Pwm>& client) { auto result = client->Enable(); if (!result.ok()) { fprintf(stderr, "Failed to enable device\n"); return ZX_ERR_INTERNAL; } return ZX_OK; } zx_status_t disable(fidl::WireSyncClient<fuchsia_hardware_pwm::Pwm>& client) { auto result = client->Disable(); if (!result.ok()) { fprintf(stderr, "Failed to disable device\n"); return ZX_ERR_INTERNAL; } return ZX_OK; } zx_status_t set_config(fidl::WireSyncClient<fuchsia_hardware_pwm::Pwm>& client, bool polarity, uint32_t period_ns, float duty_cycle) { if (duty_cycle < 0.0 || duty_cycle > 100.0) { fprintf(stderr, "Duty cycle must be between 0.0 and 100.0\n"); return ZX_ERR_INVALID_ARGS; } // TODO(fxbug.dev/41256): This is AML specific, factor this into a plugin or something. aml_pwm::mode_config cfg; cfg.mode = aml_pwm::ON; fuchsia_hardware_pwm::wire::PwmConfig config; config.polarity = polarity; config.period_ns = period_ns; config.duty_cycle = duty_cycle; config.mode_config = fidl::VectorView<uint8_t>::FromExternal(reinterpret_cast<uint8_t*>(&cfg), sizeof(cfg)); zx_status_t result = client->SetConfig(config).status(); if (result != ZX_OK) { fprintf(stderr, "Failed to set config, rc = %d\n", result); } return result; } zx_status_t run(int argc, char const* argv[], fidl::ClientEnd<fuchsia_hardware_pwm::Pwm> device) { // Pick the command out of the arguments. if (argc < 3) { fprintf(stderr, "Expected a subcommand\n"); return ZX_ERR_INVALID_ARGS; } fidl::WireSyncClient<fuchsia_hardware_pwm::Pwm> client(std::move(device)); const std::string cmd(argv[2]); if (!strncmp(cmd_str::kEnable, argv[2], std::size(cmd_str::kEnable))) { return enable(client); } else if (!strncmp(cmd_str::kDisable, argv[2], std::size(cmd_str::kDisable))) { return disable(client); } else if (!strncmp(cmd_str::kSetConfig, argv[2], std::size(cmd_str::kSetConfig))) { if (argc < 6) { fprintf(stderr, "%s expects 3 arguments %s %s <polarity> <period> <duty_cycle>\n", argv[1], argv[0], argv[1]); return ZX_ERR_INVALID_ARGS; } long polarity = parse_positive_long(argv[3]); long period_ns_arg = parse_positive_long(argv[4]); float duty_cycle = parse_positive_float(argv[5]); if (polarity != 1 && polarity != 0) { fprintf(stderr, "Polarity must be 0 or 1.\n"); return ZX_ERR_INVALID_ARGS; } if (period_ns_arg < 0 || period_ns_arg > std::numeric_limits<uint32_t>::max()) { fprintf(stderr, "Invalid argument for period.\n"); return ZX_ERR_INVALID_ARGS; } uint32_t period_ns = static_cast<uint32_t>(period_ns_arg); if (duty_cycle < 0.0 || duty_cycle > 100.0) { fprintf(stderr, "Duty cycle must be between 0.0 and 100.0\n"); return ZX_ERR_INVALID_ARGS; } return set_config(client, polarity == 1, period_ns, duty_cycle); } fprintf(stderr, "Invalid command: %s\n", cmd.c_str()); return ZX_ERR_INVALID_ARGS; } } // namespace pwmctl
29.094891
98
0.673106
allansrc
665bc659bfc05a54b24049a7e0b3053034cc1c57
16,846
cxx
C++
main/sc/source/ui/view/dbfunc.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/ui/view/dbfunc.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/ui/view/dbfunc.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <sfx2/app.hxx> #include <sfx2/bindings.hxx> #include <vcl/msgbox.hxx> #include <com/sun/star/sdbc/XResultSet.hpp> #include "dbfunc.hxx" #include "docsh.hxx" #include "attrib.hxx" #include "sc.hrc" #include "undodat.hxx" #include "dbcolect.hxx" #include "globstr.hrc" #include "global.hxx" #include "dbdocfun.hxx" #include "editable.hxx" //================================================================== ScDBFunc::ScDBFunc( Window* pParent, ScDocShell& rDocSh, ScTabViewShell* pViewShell ) : ScViewFunc( pParent, rDocSh, pViewShell ) { } //UNUSED2008-05 ScDBFunc::ScDBFunc( Window* pParent, const ScDBFunc& rDBFunc, ScTabViewShell* pViewShell ) : //UNUSED2008-05 ScViewFunc( pParent, rDBFunc, pViewShell ) //UNUSED2008-05 { //UNUSED2008-05 } ScDBFunc::~ScDBFunc() { } // // Hilfsfunktionen // void ScDBFunc::GotoDBArea( const String& rDBName ) { ScDocument* pDoc = GetViewData()->GetDocument(); ScDBCollection* pDBCol = pDoc->GetDBCollection(); sal_uInt16 nFoundAt = 0; if ( pDBCol->SearchName( rDBName, nFoundAt ) ) { ScDBData* pData = (*pDBCol)[nFoundAt]; DBG_ASSERT( pData, "GotoDBArea: Datenbankbereich nicht gefunden!" ); if ( pData ) { SCTAB nTab = 0; SCCOL nStartCol = 0; SCROW nStartRow = 0; SCCOL nEndCol = 0; SCROW nEndRow = 0; pData->GetArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow ); SetTabNo( nTab ); MoveCursorAbs( nStartCol, nStartRow, ScFollowMode( SC_FOLLOW_JUMP ), sal_False, sal_False ); // bShift,bControl DoneBlockMode(); InitBlockMode( nStartCol, nStartRow, nTab ); MarkCursor( nEndCol, nEndRow, nTab ); SelectionChanged(); } } } // aktuellen Datenbereich fuer Sortieren / Filtern suchen ScDBData* ScDBFunc::GetDBData( sal_Bool bMark, ScGetDBMode eMode, ScGetDBSelection eSel ) { ScDocShell* pDocSh = GetViewData()->GetDocShell(); ScDBData* pData = NULL; ScRange aRange; ScMarkType eMarkType = GetViewData()->GetSimpleArea(aRange); if ( eMarkType == SC_MARK_SIMPLE || eMarkType == SC_MARK_SIMPLE_FILTERED ) { bool bShrinkColumnsOnly = false; if (eSel == SC_DBSEL_ROW_DOWN) { // Don't alter row range, additional rows may have been selected on // purpose to append data, or to have a fake header row. bShrinkColumnsOnly = true; // Select further rows only if only one row or a portion thereof is // selected. if (aRange.aStart.Row() != aRange.aEnd.Row()) { // If an area is selected shrink that to the actual used // columns, don't draw filter buttons for empty columns. eSel = SC_DBSEL_SHRINK_TO_USED_DATA; } else if (aRange.aStart.Col() == aRange.aEnd.Col()) { // One cell only, if it is not marked obtain entire used data // area. const ScMarkData& rMarkData = GetViewData()->GetMarkData(); if (!(rMarkData.IsMarked() || rMarkData.IsMultiMarked())) eSel = SC_DBSEL_KEEP; } } switch (eSel) { case SC_DBSEL_SHRINK_TO_SHEET_DATA: { // Shrink the selection to sheet data area. ScDocument* pDoc = pDocSh->GetDocument(); SCCOL nCol1 = aRange.aStart.Col(), nCol2 = aRange.aEnd.Col(); SCROW nRow1 = aRange.aStart.Row(), nRow2 = aRange.aEnd.Row(); if (pDoc->ShrinkToDataArea( aRange.aStart.Tab(), nCol1, nRow1, nCol2, nRow2)) { aRange.aStart.SetCol(nCol1); aRange.aEnd.SetCol(nCol2); aRange.aStart.SetRow(nRow1); aRange.aEnd.SetRow(nRow2); } } break; case SC_DBSEL_SHRINK_TO_USED_DATA: case SC_DBSEL_ROW_DOWN: { // Shrink the selection to actual used area. ScDocument* pDoc = pDocSh->GetDocument(); SCCOL nCol1 = aRange.aStart.Col(), nCol2 = aRange.aEnd.Col(); SCROW nRow1 = aRange.aStart.Row(), nRow2 = aRange.aEnd.Row(); bool bShrunk; pDoc->ShrinkToUsedDataArea( bShrunk, aRange.aStart.Tab(), nCol1, nRow1, nCol2, nRow2, bShrinkColumnsOnly); if (bShrunk) { aRange.aStart.SetCol(nCol1); aRange.aEnd.SetCol(nCol2); aRange.aStart.SetRow(nRow1); aRange.aEnd.SetRow(nRow2); } } break; default: ; // nothing } pData = pDocSh->GetDBData( aRange, eMode, eSel ); } else if ( eMode != SC_DB_OLD ) pData = pDocSh->GetDBData( ScRange( GetViewData()->GetCurX(), GetViewData()->GetCurY(), GetViewData()->GetTabNo() ), eMode, SC_DBSEL_KEEP ); if ( pData && bMark ) { ScRange aFound; pData->GetArea(aFound); MarkRange( aFound, sal_False ); } return pData; } // Datenbankbereiche aendern (Dialog) void ScDBFunc::NotifyCloseDbNameDlg( const ScDBCollection& rNewColl, const List& rDelAreaList ) { ScDocShell* pDocShell = GetViewData()->GetDocShell(); ScDocShellModificator aModificator( *pDocShell ); ScDocument* pDoc = pDocShell->GetDocument(); ScDBCollection* pOldColl = pDoc->GetDBCollection(); ScDBCollection* pUndoColl = NULL; ScDBCollection* pRedoColl = NULL; const sal_Bool bRecord (pDoc->IsUndoEnabled()); long nDelCount = rDelAreaList.Count(); for (long nDelPos=0; nDelPos<nDelCount; nDelPos++) { ScRange* pEntry = (ScRange*) rDelAreaList.GetObject(nDelPos); if ( pEntry ) { ScAddress& rStart = pEntry->aStart; ScAddress& rEnd = pEntry->aEnd; pDocShell->DBAreaDeleted( rStart.Tab(), rStart.Col(), rStart.Row(), rEnd.Col(), rEnd.Row() ); // Targets am SBA abmelden nicht mehr noetig } } if (bRecord) pUndoColl = new ScDBCollection( *pOldColl ); // neue Targets am SBA anmelden nicht mehr noetig pDoc->CompileDBFormula( sal_True ); // CreateFormulaString pDoc->SetDBCollection( new ScDBCollection( rNewColl ) ); pDoc->CompileDBFormula( sal_False ); // CompileFormulaString pOldColl = NULL; pDocShell->PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID ); aModificator.SetDocumentModified(); SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_DBAREAS_CHANGED ) ); if (bRecord) { pRedoColl = new ScDBCollection( rNewColl ); pDocShell->GetUndoManager()->AddUndoAction( new ScUndoDBData( pDocShell, pUndoColl, pRedoColl ) ); } } // // wirkliche Funktionen // // Sortieren void ScDBFunc::UISort( const ScSortParam& rSortParam, sal_Bool bRecord ) { ScDocShell* pDocSh = GetViewData()->GetDocShell(); ScDocument* pDoc = pDocSh->GetDocument(); SCTAB nTab = GetViewData()->GetTabNo(); ScDBData* pDBData = pDoc->GetDBAtArea( nTab, rSortParam.nCol1, rSortParam.nRow1, rSortParam.nCol2, rSortParam.nRow2 ); if (!pDBData) { DBG_ERROR( "Sort: keine DBData" ); return; } ScSubTotalParam aSubTotalParam; pDBData->GetSubTotalParam( aSubTotalParam ); if (aSubTotalParam.bGroupActive[0] && !aSubTotalParam.bRemoveOnly) { // Subtotals wiederholen, mit neuer Sortierung DoSubTotals( aSubTotalParam, bRecord, &rSortParam ); } else { Sort( rSortParam, bRecord ); // nur sortieren } } void ScDBFunc::Sort( const ScSortParam& rSortParam, sal_Bool bRecord, sal_Bool bPaint ) { ScDocShell* pDocSh = GetViewData()->GetDocShell(); SCTAB nTab = GetViewData()->GetTabNo(); ScDBDocFunc aDBDocFunc( *pDocSh ); sal_Bool bSuccess = aDBDocFunc.Sort( nTab, rSortParam, bRecord, bPaint, sal_False ); if ( bSuccess && !rSortParam.bInplace ) { // Ziel markieren ScRange aDestRange( rSortParam.nDestCol, rSortParam.nDestRow, rSortParam.nDestTab, rSortParam.nDestCol + rSortParam.nCol2 - rSortParam.nCol1, rSortParam.nDestRow + rSortParam.nRow2 - rSortParam.nRow1, rSortParam.nDestTab ); MarkRange( aDestRange ); } } // Filtern void ScDBFunc::Query( const ScQueryParam& rQueryParam, const ScRange* pAdvSource, sal_Bool bRecord ) { ScDocShell* pDocSh = GetViewData()->GetDocShell(); SCTAB nTab = GetViewData()->GetTabNo(); ScDBDocFunc aDBDocFunc( *pDocSh ); sal_Bool bSuccess = aDBDocFunc.Query( nTab, rQueryParam, pAdvSource, bRecord, sal_False ); if (bSuccess) { sal_Bool bCopy = !rQueryParam.bInplace; if (bCopy) { // Zielbereich markieren (DB-Bereich wurde ggf. angelegt) ScDocument* pDoc = pDocSh->GetDocument(); ScDBData* pDestData = pDoc->GetDBAtCursor( rQueryParam.nDestCol, rQueryParam.nDestRow, rQueryParam.nDestTab, sal_True ); if (pDestData) { ScRange aDestRange; pDestData->GetArea(aDestRange); MarkRange( aDestRange ); } } if (!bCopy) { UpdateScrollBars(); SelectionChanged(); // for attribute states (filtered rows are ignored) } GetViewData()->GetBindings().Invalidate( SID_UNFILTER ); } } // Autofilter-Knoepfe ein-/ausblenden void ScDBFunc::ToggleAutoFilter() { ScDocShell* pDocSh = GetViewData()->GetDocShell(); ScDocShellModificator aModificator( *pDocSh ); ScDBData* pDBData = GetDBData( sal_False, SC_DB_MAKE_AUTOFILTER, SC_DBSEL_ROW_DOWN ); if ( pDBData == NULL ) { return; } // use a list action for the AutoFilter buttons (ScUndoAutoFilter) and the filter operation const String aUndo = ScGlobal::GetRscString( STR_UNDO_QUERY ); pDocSh->GetUndoManager()->EnterListAction( aUndo, aUndo ); pDBData->SetByRow( sal_True ); ScQueryParam aParam; pDBData->GetQueryParam( aParam ); ScDocument* pDoc = GetViewData()->GetDocument(); bool bHasAutoFilter = true; const SCROW nRow = aParam.nRow1; const SCTAB nTab = GetViewData()->GetTabNo(); for ( SCCOL nCol=aParam.nCol1; nCol<=aParam.nCol2 && bHasAutoFilter; ++nCol ) { const sal_Int16 nFlag = ((ScMergeFlagAttr*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_MERGE_FLAG ))->GetValue(); if ( (nFlag & SC_MF_AUTO) == 0 ) bHasAutoFilter = false; } bool bPaint = false; if ( bHasAutoFilter ) { // switch filter buttons for ( SCCOL nCol=aParam.nCol1; nCol<=aParam.nCol2; ++nCol ) { const sal_Int16 nFlag = ((ScMergeFlagAttr*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_MERGE_FLAG ))->GetValue(); pDoc->ApplyAttr( nCol, nRow, nTab, ScMergeFlagAttr( nFlag & ~SC_MF_AUTO ) ); } ScRange aRange; pDBData->GetArea( aRange ); pDocSh->GetUndoManager()->AddUndoAction( new ScUndoAutoFilter( pDocSh, aRange, pDBData->GetName(), sal_False ) ); pDBData->SetAutoFilter(sal_False); // switch off filter const SCSIZE nEC = aParam.GetEntryCount(); for ( SCSIZE i=0; i<nEC; ++i ) { aParam.GetEntry(i).bDoQuery = sal_False; } aParam.bDuplicate = sal_True; Query( aParam, NULL, sal_True ); // delete internal database range for auto filter if ( pDBData->IsInternalForAutoFilter() ) { ScDBDocFunc aFunc(*pDocSh); aFunc.DeleteDBRange( pDBData->GetName(), sal_False ); } pDBData = NULL; bPaint = true; } else { if ( !pDoc->IsBlockEmpty( nTab, aParam.nCol1, aParam.nRow1, aParam.nCol2, aParam.nRow2 ) ) { if ( !pDBData->HasHeader() ) { if ( MessBox( GetViewData()->GetDialogParent(), WinBits(WB_YES_NO | WB_DEF_YES), ScGlobal::GetRscString( STR_MSSG_DOSUBTOTALS_0 ), ScGlobal::GetRscString( STR_MSSG_MAKEAUTOFILTER_0 ) ).Execute() == RET_YES ) { pDBData->SetHeader( sal_True ); } } ScRange aRange; pDBData->GetArea( aRange ); pDocSh->GetUndoManager()->AddUndoAction( new ScUndoAutoFilter( pDocSh, aRange, pDBData->GetName(), sal_True ) ); pDBData->SetAutoFilter(sal_True); for ( SCCOL nCol=aParam.nCol1; nCol<=aParam.nCol2; ++nCol ) { const sal_Int16 nFlag = ((ScMergeFlagAttr*) pDoc->GetAttr( nCol, nRow, nTab, ATTR_MERGE_FLAG ))->GetValue(); pDoc->ApplyAttr( nCol, nRow, nTab, ScMergeFlagAttr( nFlag | SC_MF_AUTO ) ); } pDocSh->PostPaint( aParam.nCol1, nRow, nTab, aParam.nCol2, nRow, nTab, PAINT_GRID ); bPaint = true; } else { ErrorBox aErrorBox( GetViewData()->GetDialogParent(), WinBits( WB_OK | WB_DEF_OK ), ScGlobal::GetRscString( STR_ERR_AUTOFILTER ) ); aErrorBox.Execute(); } } pDocSh->GetUndoManager()->LeaveListAction(); if ( bPaint ) { aModificator.SetDocumentModified(); SfxBindings& rBindings = GetViewData()->GetBindings(); rBindings.Invalidate( SID_AUTO_FILTER ); rBindings.Invalidate( SID_AUTOFILTER_HIDE ); } } // nur ausblenden, keine Daten veraendern void ScDBFunc::HideAutoFilter() { ScDocShell* pDocSh = GetViewData()->GetDocShell(); ScDocShellModificator aModificator( *pDocSh ); ScDBData* pDBData = GetDBData( sal_False ); SCTAB nTab; SCCOL nCol1, nCol2; SCROW nRow1, nRow2; pDBData->GetArea(nTab, nCol1, nRow1, nCol2, nRow2); { ScDocument* pDoc = pDocSh->GetDocument(); for (SCCOL nCol=nCol1; nCol<=nCol2; nCol++) { const sal_Int16 nFlag = ((ScMergeFlagAttr*) pDoc->GetAttr( nCol, nRow1, nTab, ATTR_MERGE_FLAG ))->GetValue(); pDoc->ApplyAttr( nCol, nRow1, nTab, ScMergeFlagAttr( nFlag & ~SC_MF_AUTO ) ); } } const String aUndo = ScGlobal::GetRscString( STR_UNDO_QUERY ); pDocSh->GetUndoManager()->EnterListAction( aUndo, aUndo ); { ScRange aRange; pDBData->GetArea( aRange ); pDocSh->GetUndoManager()->AddUndoAction( new ScUndoAutoFilter( pDocSh, aRange, pDBData->GetName(), sal_False ) ); pDBData->SetAutoFilter(sal_False); // delete internal database range for auto filter if ( pDBData->IsInternalForAutoFilter() ) { ScDBDocFunc aFunc(*pDocSh); aFunc.DeleteDBRange( pDBData->GetName(), sal_False ); } pDBData = NULL; } pDocSh->GetUndoManager()->LeaveListAction(); pDocSh->PostPaint( nCol1,nRow1,nTab, nCol2,nRow1,nTab, PAINT_GRID ); aModificator.SetDocumentModified(); SfxBindings& rBindings = GetViewData()->GetBindings(); rBindings.Invalidate( SID_AUTO_FILTER ); rBindings.Invalidate( SID_AUTOFILTER_HIDE ); } // Re-Import sal_Bool ScDBFunc::ImportData( const ScImportParam& rParam, sal_Bool bRecord ) { ScDocument* pDoc = GetViewData()->GetDocument(); ScEditableTester aTester( pDoc, GetViewData()->GetTabNo(), rParam.nCol1,rParam.nRow1, rParam.nCol2,rParam.nRow2 ); if ( !aTester.IsEditable() ) { ErrorMessage(aTester.GetMessageId()); return sal_False; } ScDBDocFunc aDBDocFunc( *GetViewData()->GetDocShell() ); return aDBDocFunc.DoImport( GetViewData()->GetTabNo(), rParam, NULL, bRecord ); }
31.905303
124
0.612846
Grosskopf
6664d56200c6f7ed14b7b4598c2b608bcad854dd
2,566
cpp
C++
graph-source-code/194-C/4785501.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/194-C/4785501.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/194-C/4785501.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include <stdio.h> #include <vector> #include <list> #include <iostream> #include <algorithm> #include <queue> using namespace std; int T = 0; typedef vector < vector < int > > table; int x[4] = { 0 , 0 , -1 , 1 }; int y[4] = { -1 , 1 , 0 , 0 }; table time ( 52 , vector < int > ( 52 , 0 ) );; table up ( 52 , vector < int > ( 52 , 0 ) );; bool dfs ( pair < int , int > v , pair < int , int > p , const table &graph , bool root ) { T++; int count_child = 0; up [ v.first ][ v.second ] = time [ v.first ][ v.second ] = T; bool res = false; for ( int j = 0; j < 4; ++j ) { if ( graph [ v.first + x[j] ][ v.second + y[j] ] == 1 ) { pair < int , int > u = make_pair ( v.first + x[j] , v.second + y[j] ); if (u == p) continue; if ( time[u.first][u.second] != 0 ) up[ v.first ][ v.second ] = min ( up [ v.first ][ v.second ] , time [ u.first ][ u.second ] ); else { bool f = dfs ( u , v , graph , false ); if (f) res = true; count_child++; up [ v.first ][ v.second ] = min ( up[ v.first ][ v.second ] , up [ u.first ][ u.second ] ); if (!root && up[u.first][u.second] >= time [v.first][v.second] ) return true; } } } if ( root && count_child > 1 ) return true; return res; } int main() { int n; int m; cin >> n; cin >> m; table v ( n+2 , vector < int > ( m+2 , 0 ) ); for ( int i = 1; i <= n; ++i ) { for ( int j = 1; j <= m; ++j ) { char ch; cin >> ch; if ( ch == '#' ) v[i][j] = 1; else v[i][j] = 0; } } int ans = -1; for ( int i = 1; i <= n; ++i ) for ( int j = 1; j <= m; ++j ) { if (v[i][j] == 0) continue; if (ans == -1 && time[i][j] == 0 ) { if (dfs ( make_pair( i , j ) , make_pair ( -1 , -1 ) , v , true )) { ans = 1; } else { ans = 2; } } } if (T <= 2) { ans = -1; } cout << ans << "\n"; return 0; }
27.891304
116
0.336321
AmrARaouf
6666e8cdec563ad86fc13f874239fbb7226dcbe7
939
cpp
C++
projects/cpp_project_andriidem_plant/src/Employee.cpp
andriidem308/cpp_practice
6f46b3fb9786ec8fb8bc05a29d8ff2caf0ac53c3
[ "MIT" ]
1
2020-09-23T20:05:56.000Z
2020-09-23T20:05:56.000Z
projects/cpp_project_andriidem_plant/src/Employee.cpp
andriidem308/cpp_practice
6f46b3fb9786ec8fb8bc05a29d8ff2caf0ac53c3
[ "MIT" ]
null
null
null
projects/cpp_project_andriidem_plant/src/Employee.cpp
andriidem308/cpp_practice
6f46b3fb9786ec8fb8bc05a29d8ff2caf0ac53c3
[ "MIT" ]
null
null
null
/*** * * Project name: Plant * File: Employee.cpp * Project was created by Andrii Demchenko on 21.11.19 * Year: 2-nd * Specialization: Computer mathematics * Taras Shevchenko National University of Kyiv * e-mail: andriidem308@gmail.com * phone number: +380660209961 * ***/ #include "../headers/Employee.h" Employee::Employee(string _employee_name, string _employee_surname, int _employee_age, int _experience, Product *_product, Profession *_profession, vector<Equipment*> _equipments) : Worker(std::move(_employee_name), std::move(_employee_surname), _employee_age, _experience) { product = _product; profession = _profession; equipments = _equipments; } void Employee::addEquipment(Equipment *_equipment) { equipments.push_back(_equipment);} double Employee::calcSalary() { double calculatedSalary = 0.1 * profession->getRate() * getExperience() + product->FullOfProduction() * 0.05; return calculatedSalary; }
28.454545
110
0.749734
andriidem308
66699804c18a6dec03b5b4b5bc371cbac184cac0
911
cpp
C++
Acmicpc/C++/BOJ3908.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-07-08T23:16:19.000Z
2020-07-08T23:16:19.000Z
Acmicpc/C++/BOJ3908.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-05-16T03:12:24.000Z
2020-05-16T03:14:42.000Z
Acmicpc/C++/BOJ3908.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
2
2020-05-16T03:25:16.000Z
2021-02-10T16:51:25.000Z
#include <bits/stdc++.h> using namespace std; int prime[1121]; int dp[15][1121]; int main() { // freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); memset(prime, 1, sizeof(prime)); map<int, int> m; for (int i = 2; i < 1121; i++) { if (prime[i]) { m[i] = 1; for (int j = i + i; j < 1121; j += i) { if (prime[j]) { prime[j] = 0; } } } } dp[0][0] = 1; int cnt = 0; for (auto it = m.begin(); it != m.end(); it++) { for (int i = 1120; i >= it->first; --i) { for (int j = 1 ; j <= 14; j++) { dp[j][i] += dp[j - 1][i - it->first]; } } } int t; cin >> t; while (t--) { int n, k; cin >> n >> k; cout << dp[k][n] << '\n'; } return 0; }
26.028571
74
0.385291
sungmen
666c020696e0bb652e4219c4cb68a855d62fce57
9,723
cpp
C++
src/gpu/blas/blas1/ExSUM.Launcher.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
src/gpu/blas/blas1/ExSUM.Launcher.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
src/gpu/blas/blas1/ExSUM.Launcher.cpp
nikolovjovan/exblas
7541d384242a84a8b8314648d939b846ca632321
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Inria and University Pierre and Marie Curie * All rights reserved. */ #include "common.hpp" #include "ExSUM.Launcher.hpp" //////////////////////////////////////////////////////////////////////////////// // OpenCL launcher for bitonic sort kernel //////////////////////////////////////////////////////////////////////////////// #define EXSUM_KERNEL "ExSUM" #define EXSUM_COMPLETE_KERNEL "ExSUMComplete" #define ROUND_KERNEL "ExSUMRound" static size_t szKernelLength; // Byte size of kernel code static char* cSources = NULL; // Buffer to hold source for compilation static cl_program cpProgram; //OpenCL Superaccumulator program static cl_kernel ckKernel; //OpenCL Superaccumulator kernels static cl_kernel ckComplete; static cl_kernel ckRound; static cl_command_queue cqDefaultCommandQue; //Default command queue for Superaccumulator static cl_mem d_Superacc; static cl_mem d_PartialSuperaccs; #ifdef AMD static const uint PARTIAL_SUPERACCS_COUNT = 1024; #else static const uint PARTIAL_SUPERACCS_COUNT = 512; #endif static const uint WORKGROUP_SIZE = 256; static const uint MERGE_WORKGROUP_SIZE = 64; static const uint MERGE_SUPERACCS_SIZE = 128; static uint NbElements; #ifdef AMD static char compileOptions[256] = "-DWARP_COUNT=16 -DWARP_SIZE=16 -DMERGE_WORKGROUP_SIZE=64 -DMERGE_SUPERACCS_SIZE=128 -DUSE_KNUTH"; #else static char compileOptions[256] = "-DWARP_COUNT=16 -DWARP_SIZE=16 -DMERGE_WORKGROUP_SIZE=64 -DMERGE_SUPERACCS_SIZE=128 -DUSE_KNUTH -DNVIDIA -cl-mad-enable -cl-fast-relaxed-math"; // -cl-nv-verbose"; #endif //////////////////////////////////////////////////////////////////////////////// // GPU reduction related functions //////////////////////////////////////////////////////////////////////////////// extern "C" cl_int initExSUM( cl_context cxGPUContext, cl_command_queue cqParamCommandQue, cl_device_id cdDevice, const char* program_file, const uint NbElems, const uint NbFPE ){ cl_int ciErrNum; NbElements = NbElems; // Read the OpenCL kernel in from source file FILE *program_handle; // Load the program sources program_handle = fopen(program_file, "r"); if (!program_handle) { fprintf(stderr, "Failed to load kernel.\n"); exit(1); } fseek(program_handle, 0, SEEK_END); szKernelLength = ftell(program_handle); rewind(program_handle); cSources = (char *) malloc(szKernelLength + 1); cSources[szKernelLength] = '\0'; ciErrNum = fread(cSources, sizeof(char), szKernelLength, program_handle); fclose(program_handle); //printf("clCreateProgramWithSource...\n"); cpProgram = clCreateProgramWithSource(cxGPUContext, 1, (const char **)&cSources, &szKernelLength, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateProgramWithSource, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } //printf("...building ExSUM program\n"); sprintf(compileOptions, "%s -DNBFPE=%d", compileOptions, NbFPE); ciErrNum = clBuildProgram(cpProgram, 0, NULL, compileOptions, NULL, NULL); if (ciErrNum != CL_SUCCESS) { printf("Error in clBuildProgram, Line %u in file %s !!!\n\n", __LINE__, __FILE__); // Determine the reason for the error char buildLog[16384]; clGetProgramBuildInfo(cpProgram, cdDevice, CL_PROGRAM_BUILD_LOG, sizeof(buildLog), &buildLog, NULL); printf("%s\n", buildLog); return EXIT_FAILURE; } //printf("...creating ExSUM kernels:\n"); ckKernel = clCreateKernel(cpProgram, EXSUM_KERNEL, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateKernel: ExSUM, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } ckComplete = clCreateKernel(cpProgram, EXSUM_COMPLETE_KERNEL, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateKernel: ExSUMComplete, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } ckRound = clCreateKernel(cpProgram, ROUND_KERNEL, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateKernel: Round, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } //printf("...allocating internal buffer\n"); uint size = PARTIAL_SUPERACCS_COUNT; size = size * bin_count * sizeof(cl_long); d_PartialSuperaccs = clCreateBuffer(cxGPUContext, CL_MEM_READ_WRITE, size, NULL, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateBuffer for d_PartialSuperaccs, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } d_Superacc = clCreateBuffer(cxGPUContext, CL_MEM_READ_WRITE, bin_count * sizeof(bintype), NULL, &ciErrNum); if (ciErrNum != CL_SUCCESS) { printf("Error in clCreateBuffer for d_Superacc, Line %u in file %s !!!\n\n", __LINE__, __FILE__); return EXIT_FAILURE; } //Save default command queue cqDefaultCommandQue = cqParamCommandQue; //Discard temp storage free(cSources); return EXIT_SUCCESS; } extern "C" void closeExSUM(void){ cl_int ciErrNum; ciErrNum = clReleaseMemObject(d_PartialSuperaccs); ciErrNum |= clReleaseMemObject(d_Superacc); ciErrNum |= clReleaseKernel(ckKernel); ciErrNum |= clReleaseKernel(ckComplete); ciErrNum |= clReleaseKernel(ckRound); ciErrNum |= clReleaseProgram(cpProgram); if (ciErrNum != CL_SUCCESS) { printf("Error in closeExSUM(), Line %u in file %s !!!\n\n", __LINE__, __FILE__); } } //////////////////////////////////////////////////////////////////////////////// // OpenCL launchers for Superaccumulator / mergeSuperaccumulators kernels //////////////////////////////////////////////////////////////////////////////// extern "C" size_t ExSUM( cl_command_queue cqCommandQueue, cl_mem d_Res, cl_mem d_a, const cl_uint inca, const cl_uint offset, cl_int *ciErrNumRes ){ cl_int ciErrNum; size_t NbThreadsPerWorkGroup, TotalNbThreads; if(!cqCommandQueue) cqCommandQueue = cqDefaultCommandQue; { NbThreadsPerWorkGroup = WORKGROUP_SIZE; TotalNbThreads = PARTIAL_SUPERACCS_COUNT * NbThreadsPerWorkGroup; cl_uint i = 0; ciErrNum = clSetKernelArg(ckKernel, i++, sizeof(cl_mem), (void *)&d_PartialSuperaccs); ciErrNum |= clSetKernelArg(ckKernel, i++, sizeof(cl_mem), (void *)&d_a); ciErrNum |= clSetKernelArg(ckKernel, i++, sizeof(cl_uint), (void *)&inca); ciErrNum |= clSetKernelArg(ckKernel, i++, sizeof(cl_uint), (void *)&offset); ciErrNum |= clSetKernelArg(ckKernel, i++, sizeof(cl_uint), (void *)&NbElements); if (ciErrNum != CL_SUCCESS) { printf("Error in clSetKernelArg, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } ciErrNum = clEnqueueNDRangeKernel(cqCommandQueue, ckKernel, 1, NULL, &TotalNbThreads, &NbThreadsPerWorkGroup, 0, NULL, NULL); if (ciErrNum != CL_SUCCESS) { printf("Error in clEnqueueNDRangeKernel, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } } { NbThreadsPerWorkGroup = MERGE_WORKGROUP_SIZE; TotalNbThreads = NbThreadsPerWorkGroup; //TotalNbThreads *= bin_count; TotalNbThreads *= PARTIAL_SUPERACCS_COUNT / MERGE_SUPERACCS_SIZE; cl_uint i = 0; //ciErrNum = clSetKernelArg(ckComplete, i++, sizeof(cl_mem), (void *)&d_Superacc); ciErrNum = clSetKernelArg(ckComplete, i++, sizeof(cl_mem), (void *)&d_Res); ciErrNum |= clSetKernelArg(ckComplete, i++, sizeof(cl_mem), (void *)&d_PartialSuperaccs); ciErrNum |= clSetKernelArg(ckComplete, i++, sizeof(cl_uint), (void *)&PARTIAL_SUPERACCS_COUNT); if (ciErrNum != CL_SUCCESS) { printf("Error in clSetKernelArg, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } ciErrNum = clEnqueueNDRangeKernel(cqCommandQueue, ckComplete, 1, NULL, &TotalNbThreads, &NbThreadsPerWorkGroup, 0, NULL, NULL); if (ciErrNum != CL_SUCCESS) { printf("ciErrNum = %d\n", ciErrNum); printf("Error in clEnqueueNDRangeKernel, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } } /*{ NbThreadsPerWorkGroup = MERGE_WORKGROUP_SIZE; TotalNbThreads = NbThreadsPerWorkGroup; cl_uint i = 0; ciErrNum = clSetKernelArg(ckRound, i++, sizeof(cl_mem), (void *)&d_Res); ciErrNum |= clSetKernelArg(ckRound, i++, sizeof(cl_mem), (void *)&d_Superacc); if (ciErrNum != CL_SUCCESS) { printf("Error in clSetKernelArg, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } ciErrNum = clEnqueueNDRangeKernel(cqCommandQueue, ckRound, 1, NULL, &TotalNbThreads, &NbThreadsPerWorkGroup, 0, NULL, NULL); if (ciErrNum != CL_SUCCESS) { printf("Error in clEnqueueNDRangeKernel, Line %u in file %s !!!\n\n", __LINE__, __FILE__); *ciErrNumRes = EXIT_FAILURE; return 0; } }*/ return WORKGROUP_SIZE; }
40.5125
199
0.616991
nikolovjovan
666c19f7b488c1482dab97d40106a1c4be5d3a15
5,846
cpp
C++
of2030/src/effect_manager.cpp
markkorput/of2030
b8e03ef341fc6e55e95fc9a770e48f84560a95a8
[ "MIT" ]
null
null
null
of2030/src/effect_manager.cpp
markkorput/of2030
b8e03ef341fc6e55e95fc9a770e48f84560a95a8
[ "MIT" ]
18
2016-05-09T14:05:18.000Z
2016-06-11T10:59:13.000Z
of2030/src/effect_manager.cpp
markkorput/of2030
b8e03ef341fc6e55e95fc9a770e48f84560a95a8
[ "MIT" ]
null
null
null
// // effect_manager.cpp // emptyExample // // Created by Mark van de Korput on 16-05-15. // // #include "effect_manager.hpp" #include <regex> using namespace of2030; EffectManager::~EffectManager(){ for(int i=effects.size()-1; i>=0; i--){ deleteEffect(effects[i]); } effects.clear(); } Effect* EffectManager::get(const string &trigger){ // create new instance Effect* pEffect = createEffect(trigger); // add to our internal list add(pEffect); // return it to caller return pEffect; } void EffectManager::add(Effect* effect){ bool added=false; if(bSortByLayerAscending){ int count=effects.size(); int layer = effect->getLayer(); for(int i=0; i<count; i++){ if(effects[i]->getLayer() > layer){ effects.insert(effects.begin()+i, effect); added=true; break; } } } // no effect found with a layer-value that's larger // than the new effect's layer-value; simply add the new effect // to the end of our list if(!added) effects.push_back(effect); ofNotifyEvent(effectAddedEvent, *effect, this); } Effect* EffectManager::createEffect(const string &trigger){ ofLogVerbose() << "EffectManager::createEffect with: " << trigger; Effect* pEffect; // default type, just set name to whatever was specified pEffect = new Effect(); // pEffect->name = triggerToName(trigger); pEffect->trigger = trigger; return pEffect; } void EffectManager::deleteEffect(Effect* effect){ ofLogVerbose() << "EffectManager::deleteEffect"; // default; simply Effect delete effect; } bool EffectManager::remove(Effect* effect){ // find effect in our list for(int i=effects.size()-1; i>=0; i--){ // this one? if(effects[i] == effect){ // remove from list effects.erase(effects.begin()+i); // notify ofNotifyEvent(effectRemovedEvent, *effect, this); // done return true; } } // not found ofLogWarning() << "[EffectManager::remove] could not find specified effect in list, ignoring"; return false; } void EffectManager::clear(){ // THIS CAUSES CRASHES // for(auto effect: effects){ // remove(effect); // } for(int i=effects.size()-1; i>=0; i--){ remove(effects[i]); } } //string EffectManager::triggerToName(const string &trigger){ // // matches on any digits at then end of the string // std::regex expression("(\\d+)$"); // // return the trigger name without any trailing digits // return std::regex_replace(trigger, expression, ""); //} void EffectManager::sort(){ vector<Effect*> sorted_effects; int lowest, tmp; // we'll move effect pointers from our effects vector // into the local sorted_effects vector and swap them at the end // kee looping until all pointer are moved while(!effects.empty()){ // we'll need an initial layer value; take the first effect's layer lowest = effects[0]->getLayer(); // loop over all other effects, to find the (next) lowest layer value for(int i=effects.size()-1; i>0; i--){ tmp = effects[i]->getLayer(); if(tmp < lowest) lowest = tmp; } // lowest now contains the lowest layer value for the remaining effects // loop over all remaining effects again and move the ones with this layer value tmp = effects.size(); for(int i=0; i<tmp; i++){ Effect* effect = effects[i]; // does this effect has the lowest layer value? if(effect->getLayer() == lowest){ // add this effect to the (back of) the sorted vector... sorted_effects.push_back(effect); // ... and remove it from our main vector effects.erase(effects.begin()+i); } } } // swap the content of the -currently empty- effects vector // with the temporary local sorted effects vector effects.swap(sorted_effects); } // // EfficientEffectManager // SINGLETON_INLINE_IMPLEMENTATION_CODE(EfficientEffectManager) const int idle_cache_limit = 10; Effect* EfficientEffectManager::get(string trigger){ // find already allocated effect in idle manager Effect* pEffect = idle_manager.getEffectByIndex(idle_manager.getCount() - 1); // no existing idle instance found, default to "normal behaviour" (allocate new instance) if(!pEffect){ // no idle effect found; create new one like usual return EffectManager::get(trigger); } // found one, remove it from idle manager idle_manager.remove(pEffect); // reset its time values (and some other attributes) pEffect->reset(); // update name if necessary //pEffect->name = triggerToName(trigger); pEffect->trigger = trigger; // add to our own list add(pEffect); // done return pEffect; } void EfficientEffectManager::finish(Effect* effect){ // ofLogVerbose() << "EfficientEffectManager::finish"; // remove from our "active list" if(!remove(effect)){ // remove failed, meaning this effect could not be found in our list, abort return; } // check if cache of idle instance has reached its limits yet if(idle_manager.getCount() >= idle_cache_limit){ // idle cache full, just delete this instance deleteEffect(effect); return; } // add it to our idle_manager, so we can recycle this instance later // ofLogVerbose() << "idle_manager count before: " << idle_manager.getCount(); idle_manager.add(effect); ofLogVerbose() << "[EfficientEffectManager] idle effects count: " << idle_manager.getCount(); }
28.241546
98
0.622306
markkorput
666eeb467cce11b8f562f7f89184a0bc279cd124
2,675
hpp
C++
include/svgpp/adapter/line.hpp
RichardCory/svgpp
801e0142c61c88cf2898da157fb96dc04af1b8b0
[ "BSL-1.0" ]
428
2015-01-05T17:13:54.000Z
2022-03-31T08:25:47.000Z
include/svgpp/adapter/line.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
61
2015-01-08T14:32:27.000Z
2021-12-06T16:55:11.000Z
include/svgpp/adapter/line.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
90
2015-05-19T04:56:46.000Z
2022-03-26T16:42:50.000Z
// Copyright Oleg Maximenko 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://github.com/svgpp/svgpp for library home page. #pragma once #include <svgpp/definitions.hpp> #include <svgpp/detail/adapt_context.hpp> #include <boost/optional.hpp> #include <boost/noncopyable.hpp> #include <boost/mpl/set.hpp> namespace svgpp { typedef boost::mpl::set4<tag::attribute::x1, tag::attribute::y1, tag::attribute::x2, tag::attribute::y2> line_shape_attributes; template<class Length> class collect_line_attributes_adapter: boost::noncopyable { public: template<class Context> bool on_exit_attributes(Context & context) const { typedef detail::unwrap_context<Context, tag::length_policy> length_policy_context; typedef typename length_policy_context::policy length_policy_t; typename length_policy_t::length_factory_type & converter = length_policy_t::length_factory(length_policy_context::get(context)); typename length_policy_t::length_factory_type::coordinate_type x1 = 0, y1 = 0, x2 = 0, y2 = 0; if (x1_) x1 = converter.length_to_user_coordinate(*x1_, tag::length_dimension::width()); if (x2_) x2 = converter.length_to_user_coordinate(*x2_, tag::length_dimension::width()); if (y1_) y1 = converter.length_to_user_coordinate(*y1_, tag::length_dimension::height()); if (y2_) y2 = converter.length_to_user_coordinate(*y2_, tag::length_dimension::height()); typedef detail::unwrap_context<Context, tag::basic_shapes_events_policy> basic_shapes_events; basic_shapes_events::policy::set_line(basic_shapes_events::get(context), x1, y1, x2, y2); return true; } void set(tag::attribute::x1, Length const & val) { x1_ = val; } void set(tag::attribute::y1, Length const & val) { y1_ = val; } void set(tag::attribute::x2, Length const & val) { x2_ = val; } void set(tag::attribute::y2, Length const & val) { y2_ = val; } private: boost::optional<Length> x1_, y1_, x2_, y2_; }; struct line_to_path_adapter { template<class Context, class Coordinate> static void set_line(Context & context, Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2) { typedef detail::unwrap_context<Context, tag::path_events_policy> path_events; typename path_events::type & path_context = path_events::get(context); path_events::policy::path_move_to(path_context, x1, y1, tag::coordinate::absolute()); path_events::policy::path_line_to(path_context, x2, y2, tag::coordinate::absolute()); path_events::policy::path_exit(path_context); } }; }
36.148649
104
0.730841
RichardCory
66702f70f6caa396a34b18d259408b9d54e39d50
269
cpp
C++
PointTEST.cpp
ismail-klc/point-cloud-processing
82d9c371a7c648ea4131e3d565f7274b806edf4d
[ "MIT" ]
null
null
null
PointTEST.cpp
ismail-klc/point-cloud-processing
82d9c371a7c648ea4131e3d565f7274b806edf4d
[ "MIT" ]
null
null
null
PointTEST.cpp
ismail-klc/point-cloud-processing
82d9c371a7c648ea4131e3d565f7274b806edf4d
[ "MIT" ]
null
null
null
#include "Point.h" #include <iostream> using namespace std; int main() { Point p1, p2; p1.setX(4); p1.setY(7); p1.setZ(8); p2.setX(2); p2.setY(6); p2.setZ(9); cout << (p1 == p2) << endl; cout << p1.distance(p2); system("pause"); }
11.695652
29
0.527881
ismail-klc
667204f549368ec413d937251deae01f07e52a66
329
cpp
C++
pico_json/example.cpp
minamaged113/training
29984f4d22967625b87281bb2247246b1b0033a7
[ "MIT" ]
46
2019-07-02T05:10:47.000Z
2022-03-19T16:29:19.000Z
pico_json/example.cpp
minamaged113/training
29984f4d22967625b87281bb2247246b1b0033a7
[ "MIT" ]
62
2019-09-24T17:57:07.000Z
2022-03-28T15:35:45.000Z
pico_json/example.cpp
minamaged113/training
29984f4d22967625b87281bb2247246b1b0033a7
[ "MIT" ]
33
2019-09-19T19:29:37.000Z
2022-03-17T05:28:06.000Z
#include "picojson/picojson.h" int main(void) { const char* json = "{\"a\":1}"; picojson::value v; std::string err; const char* json_end = picojson::parse(v, json, json + strlen(json), &err); if (! err.empty()) { std::cerr << err << std::endl; } std::cout << "Json parsed ok!" << std::endl; return 0; }
19.352941
77
0.571429
minamaged113
66796b366f9956ba5423660633cf6f0c22d39c4c
2,119
cxx
C++
main/shell/source/tools/regsvrex/regsvrex.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/shell/source/tools/regsvrex/regsvrex.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/shell/source/tools/regsvrex/regsvrex.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_shell.hxx" #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif typedef HRESULT (__stdcall *lpfnDllRegisterServer)(); typedef HRESULT (__stdcall *lpfnDllUnregisterServer)(); /** */ bool IsUnregisterParameter(const char* Param) { return ((0 == _stricmp(Param, "/u")) || (0 == _stricmp(Param, "-u"))); } /** */ int main(int argc, char* argv[]) { HMODULE hmod; HRESULT hr = E_FAIL; lpfnDllRegisterServer lpfn_register; lpfnDllUnregisterServer lpfn_unregister; if (2 == argc) { hmod = LoadLibraryA(argv[1]); if (hmod) { lpfn_register = (lpfnDllRegisterServer)GetProcAddress( hmod, "DllRegisterServer"); if (lpfn_register) hr = lpfn_register(); FreeLibrary(hmod); } } else if (3 == argc && IsUnregisterParameter(argv[1])) { hmod = LoadLibraryA(argv[2]); if (hmod) { lpfn_unregister = (lpfnDllUnregisterServer)GetProcAddress( hmod, "DllUnregisterServer"); if (lpfn_unregister) hr = lpfn_unregister(); FreeLibrary(hmod); } } return 0; }
24.079545
70
0.66588
Grosskopf
667abc375a3c2cc295712f1cfa31088369b2109e
953
cpp
C++
Prova III/Aula XXIV/mochilaBackTrack.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
Prova III/Aula XXIV/mochilaBackTrack.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
Prova III/Aula XXIV/mochilaBackTrack.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> using namespace std; const int n = 27; bool melhorSolucao[n] ; int pesos[n] = {3,2,2,6,4,5,20,3,1,2,4,2,1,4,1,1,1,2,1,2,2,4,2,4,3,4,2}; int custos[n] = {300,190,180,300,190,180,300,190,180,300,190,180,300,190,180,300,190,180,12,36,152,65,25,125,250,300,245}; int capacidade = 10; int melhorLucro = -1; void solve(bool combs[], int begin, int n,int lucroParcial, int pesoParcial) { if (pesoParcial > capacidade) { return; } if (begin >= n) { int lucro = lucroParcial; if (lucro > melhorLucro) { melhorLucro = lucro; for(int i=0;i<n;i++) melhorSolucao[i] = combs[i]; } } else { combs[begin] = 0; solve(combs, begin+1, n,lucroParcial,pesoParcial); combs[begin] = 1; solve(combs, begin+1, n,lucroParcial+custos[begin],pesoParcial+pesos[begin]); } } int main(int argc, char **argv) { bool combs[n]; solve(combs,0,n,0,0); cout << "Melhor lucro: " << melhorLucro << endl; return 0; }
25.756757
122
0.650577
EhODavi
667c0041468b36c82a086ff95801b3f7aa5ce408
8,207
cpp
C++
src/libsnw_util/slot_allocator.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
src/libsnw_util/slot_allocator.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
src/libsnw_util/slot_allocator.cpp
Sojourn/snw
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <iostream> #include "align.h" #include "slot_allocator.h" snw::slot_allocator::slot_allocator(size_t capacity) : capacity_(capacity) , size_(0) , height_(0) { size_t branch_count = 0; size_t leaf_count = 0; // compute the tree layout { size_t width = align_up(capacity_, node_capacity) / node_capacity; levels_[height_].width = width; leaf_count += width; ++height_; while (width > 1) { width = align_up(width, node_capacity) / node_capacity; levels_[height_].width = width; branch_count += width; ++height_; } // put levels in desending order std::reverse(levels_, levels_ + height_); } // setup the tree { size_t depth = 0; if (branch_count > 0) { branch_nodes_.resize(branch_count); size_t branch_offset = 0; for (; depth < (height_ - 1); ++depth) { levels_[depth].first = &branch_nodes_[branch_offset]; branch_offset += levels_[depth].width; } } leaf_nodes_.resize(leaf_count); levels_[depth].first = leaf_nodes_.data(); } check_integrity(); } bool snw::slot_allocator::allocate(uint64_t* slot) { if (size() == capacity()) { return false; } cursor c; for (size_t depth = 0; depth < height_; ++depth) { node& node = levels_[depth].first[c.tell()]; int chunk_offset = 0; int bit_offset = 0; if (is_leaf_level(depth)) { leaf_node& leaf = static_cast<leaf_node&>(node); for (; chunk_offset < node_chunk_count; ++chunk_offset) { uint64_t& live_chunk = leaf.live[chunk_offset]; uint64_t dead_chunk = ~live_chunk; if (dead_chunk) { bit_offset = count_trailing_zeros(dead_chunk); break; } } } else { branch_node& branch = static_cast<branch_node&>(node); for (; chunk_offset < node_chunk_count; ++chunk_offset) { uint64_t& dead_chunk = branch.any_dead[chunk_offset]; if (dead_chunk) { bit_offset = count_trailing_zeros(dead_chunk); break; } } } std::cout << "depth:" << depth << std::endl; std::cout << "index:" << c.tell() << std::endl; std::cout << "chunk_offset:" << chunk_offset << std::endl; std::cout << "bit_offset:" << bit_offset << std::endl; assert(chunk_offset < node_chunk_count); c.desend(chunk_offset, bit_offset); } *slot = c.tell(); std::cout << "slot:" << *slot << std::endl; assert(*slot < capacity_); std::cout << std::endl; bool any_live = false; bool any_dead = false; for (size_t i = 0; i < height_; ++i) { int chunk_offset = c.chunk_offset(); int bit_offset = c.bit_offset(); c.ascend(); size_t depth = height_ - i - 1; size_t node_index = c.tell(); node& node = levels_[depth].first[node_index]; if (is_leaf_level(depth)) { leaf_node& leaf = static_cast<leaf_node&>(node); assert(!test_bit(leaf.live[chunk_offset], bit_offset)); set_bit(leaf.live[chunk_offset], bit_offset); any_live = true; any_dead = !all(leaf.live); } else { branch_node& branch = static_cast<branch_node&>(node); if (any_live) { set_bit(branch.any_live[chunk_offset], bit_offset); any_live = true; } if (!any_dead) { clear_bit(branch.any_dead[chunk_offset], bit_offset); any_dead = none(branch.any_dead); } } } #if 1 check_integrity(); #endif return true; } void snw::slot_allocator::deallocate(uint64_t slot) { cursor c(slot); bool any_live = false; bool any_dead = false; // TODO: detect if we can stop iteration early for (size_t i = 0; i < height_; ++i) { int chunk_offset = c.chunk_offset(); int bit_offset = c.bit_offset(); c.ascend(); size_t depth = height_ - i - 1; size_t node_index = c.tell(); node& node = levels_[depth].first[node_index]; if (i == 0) { leaf_node& leaf = static_cast<leaf_node&>(node); assert(test_bit(leaf.live[chunk_offset], bit_offset)); clear_bit(leaf.live[chunk_offset], bit_offset); any_live = any(leaf.live); any_dead = true; } else { branch_node& branch = static_cast<branch_node&>(node); if (!any_live) { clear_bit(branch.any_live[chunk_offset], bit_offset); any_live = any(branch.any_live); } if (any_dead) { set_bit(branch.any_dead[chunk_offset], bit_offset); any_dead = true; } } } } bool snw::slot_allocator::is_leaf_level(size_t depth) const { return (depth == (height_ - 1)); } bool snw::slot_allocator::any(const uint64_t (&chunks)[node_chunk_count]) { for (uint64_t chunk: chunks) { if (chunk != 0) { return true; } } return false; } bool snw::slot_allocator::all(const uint64_t (&chunks)[node_chunk_count]) { for (uint64_t chunk: chunks) { if (chunk != std::numeric_limits<uint64_t>::max()) { return false; } } return true; } bool snw::slot_allocator::none(const uint64_t (&chunks)[node_chunk_count]) { return !any(chunks); } void snw::slot_allocator::check_integrity() const { for (size_t depth = 0; depth < (height_ - 1); ++depth) { for (size_t node_offset = 0; node_offset < levels_[depth].width; ++node_offset) { const branch_node& branch = static_cast<const branch_node&>(levels_[depth].first[node_offset]); for (int chunk_offset = 0; chunk_offset < node_chunk_count; ++chunk_offset) { // check integrity of any_live for_each_set_bit(branch.any_live[chunk_offset], [&](int bit_offset) { cursor cursor(node_offset); cursor.desend(chunk_offset, bit_offset); const node& child_node = levels_[depth + 1].first[cursor.tell()]; if (is_leaf_level(depth + 1)) { const leaf_node& child_leaf = static_cast<const leaf_node&>(child_node); assert(any(child_leaf.live)); } else { const branch_node& child_branch = static_cast<const branch_node&>(child_node); assert(any(child_branch.any_live)); } }); // check integrity of any_dead for_each_set_bit(branch.any_dead[chunk_offset], [&](int bit_offset) { cursor cursor(node_offset); cursor.desend(chunk_offset, bit_offset); const node& child_node = levels_[depth + 1].first[cursor.tell()]; if (is_leaf_level(depth + 1)) { const leaf_node& child_leaf = static_cast<const leaf_node&>(child_node); assert(!all(child_leaf.live)); } else { const branch_node& child_branch = static_cast<const branch_node&>(child_node); assert(any(child_branch.any_dead)); } }); } } } } snw::slot_allocator::branch_node::branch_node() { for (uint64_t& chunk: any_live) { chunk = std::numeric_limits<uint64_t>::min(); } for (uint64_t& chunk: any_dead) { chunk = std::numeric_limits<uint64_t>::max(); } } snw::slot_allocator::leaf_node::leaf_node() { for (uint64_t& chunk: live) { chunk = std::numeric_limits<uint64_t>::min(); } }
30.737828
107
0.540271
Sojourn
667c6c9b39a404741e3f5d8efeb2d55bdead5198
2,103
cpp
C++
15.cpp
TwoFX/aoc2021
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
[ "Apache-2.0" ]
1
2021-12-17T11:07:15.000Z
2021-12-17T11:07:15.000Z
15.cpp
TwoFX/aoc2021
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
[ "Apache-2.0" ]
null
null
null
15.cpp
TwoFX/aoc2021
0c6f4f1642c2efdc55d7cec5ef214803859b07cd
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define eb emplace_back #define all(a) begin(a), end(a) #define has(a, b) (a.find(b) != a.end()) #define fora(i, n) for(int i = 0; i < n; i++) #define forb(i, n) for(int i = 1; i <= n; i++) #define forc(a, b) for(const auto &a : b) #define ford(i, n) for(int i = n; i >= 0; i--) #define maxval(t) numeric_limits<t>::max() #define minval(t) numeric_limits<t>::min() #define imin(a, b) a = min(a, b) #define imax(a, b) a = max(a, b) #define sz(x) (int)(x).size() #define pvec(v) copy(all(v), ostream_iterator<decltype(v)::value_type>(cout, " ")) #define dbgs(x) #x << " = " << x #define dbgs2(x, y) dbgs(x) << ", " << dbgs(y) #define dbgs3(x, y, z) dbgs2(x, y) << ", " << dbgs(z) #define dbgs4(w, x, y, z) dbgs3(w, x, y) << ", " << dbgs(z) using ll = long long; using ld = long double; int n; constexpr ll inf = 100000000000; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); vector<vector<ll>> F; string s; while (cin >> s) { F.eb(); forc(c, s) { ll r = c - '0'; F.back().pb(r); } } int m = sz(F); n = 5 * sz(F); vector<vector<ll>> f(n, vector<ll>(n)); fora(i, n) fora(j, n) { int ir = i % m; int jr = j % m; int d = i / m + j / m; int q = F[ir][jr] + d; while (q > 9) q -= 9; f[i][j] = q; } vector<vector<ll>> best(n, vector<ll>(n, inf)); priority_queue<pair<ll, pair<int, int>>, vector<pair<ll, pair<int, int>>>, greater<pair<ll, pair<int, int>>>> pq; best[0][0] = 0; pq.emplace(mp(0, mp(0, 0))); while (!pq.empty()) { auto t = pq.top(); pq.pop(); int i = t.second.first; int j = t.second.second; ll d = t.first; if (d < best[i][j]) continue; for (int di = -1; di <= 1; ++di) { for (int dj = -1; dj <= 1; ++dj) { if ((di == 0) == (dj == 0)) continue; int ii = i + di; int jj = j + dj; if (ii < 0 || ii >= n || jj < 0 || jj >= n) continue; ll pd = d + f[ii][jj]; if (pd < best[ii][jj]) { best[ii][jj] = pd; pq.emplace(mp(pd, mp(ii, jj))); } } } } cout << best[n - 1][n - 1] << endl; }
23.629213
114
0.527342
TwoFX
667c6fc9cfd3df56e34d3d3b3241784f185732eb
693
cpp
C++
Support/Extensions/APIOutputFramework/DatabaseGraphNode.cpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Extensions/APIOutputFramework/DatabaseGraphNode.cpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Extensions/APIOutputFramework/DatabaseGraphNode.cpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
#include "APIFunctionsEnvironment.hpp" // Framework includes #include "DatabaseGraphNode.hpp" GSAPI::DatabaseGraphNode::DatabaseGraphNode (API_DatabaseInfo dbInfo) { node = dbInfo; } GSAPI::DatabaseGraphNode::~DatabaseGraphNode (void) { } bool GSAPI::DatabaseGraphNode::HasChild (DatabaseGraphNode* child) { return (children.FindFirst (child) != MaxUIndex); } void GSAPI::DatabaseGraphNode::AddChild (GSAPI::DatabaseGraphNode* child) { children.Push (child); } const GS::Array<GSAPI::DatabaseGraphNode*>& GSAPI::DatabaseGraphNode::GetChildren (void) const { return children; } API_DatabaseInfo GSAPI::DatabaseGraphNode::GetDatabaseInfo (void) const { return node; }
20.382353
94
0.756133
graphisoft-python
667ef198f1d97292a1674d2f8d27b80e0ae99630
2,100
cpp
C++
project/examples/baselib/src/baselib.cpp
qigao/cmake-template
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
[ "MIT" ]
null
null
null
project/examples/baselib/src/baselib.cpp
qigao/cmake-template
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
[ "MIT" ]
23
2022-03-08T11:24:35.000Z
2022-03-23T04:14:31.000Z
project/examples/baselib/src/baselib.cpp
qigao/project-cpp-template
cd1b7f8995bba7e672f3ca35463ecc129ea7bcbc
[ "MIT" ]
null
null
null
#include "version.h" #include <baselib.h> #include <fstream> #include <iostream> #include <zmq.hpp> #include <zmq_addon.hpp> namespace baselib { void printInfo() { zmq::context_t ctx; zmq::socket_t sock1(ctx, zmq::socket_type::push); zmq::socket_t sock2(ctx, zmq::socket_type::pull); sock1.bind("tcp://127.0.0.1:*"); const std::string last_endpoint = sock1.get(zmq::sockopt::last_endpoint); std::cout << "Connecting to " << last_endpoint << std::endl; sock2.connect(last_endpoint); std::array<zmq::const_buffer, 2> send_msgs = { zmq::str_buffer("foo"), zmq::str_buffer("bar!") }; if (!zmq::send_multipart(sock1, send_msgs)) return; std::vector<zmq::message_t> recv_msgs; const auto ret = zmq::recv_multipart(sock2, std::back_inserter(recv_msgs)); if (!ret) return; std::cout << "Got " << *ret << " messages" << std::endl; std::string dataPath = "data"; std::cout << "Version: " << PROJECT_VERSION << "\n" << "Author: " << GIT_AUTHOR_NAME << "\n" << "Branch: " << GIT_BRANCH << "\n" << "Date: " << GIT_COMMIT_DATE_ISO8601 << "\n\n" << std::endl; // Library name std::cout << "Library template::baselib" << std::endl; std::cout << "========================================" << std::endl; // Library type (static or dynamic) #ifdef BASELIB_STATIC_DEFINE std::cout << "Library type: STATIC" << std::endl; #else std::cout << "Library type: SHARED" << std::endl; #endif // Data directory std::cout << "Data path: " << dataPath << std::endl; std::cout << std::endl; // Read file std::cout << "Data directory access" << std::endl; std::cout << "========================================" << std::endl; std::string fileName = dataPath + "/DATA_FOLDER.txt"; std::cout << "Reading from '" << fileName << "': " << std::endl; std::cout << std::endl; std::ifstream f(fileName); if (f.is_open()) { std::string line; while (getline(f, line)) { std::cout << line << '\n'; } f.close(); } else { std::cout << "Unable to open file." << std::endl; } } }// namespace baselib
31.343284
77
0.579524
qigao
667f4c8c0389e26678257aa84c2aef335fecde5b
1,643
cpp
C++
src/behaviors/charge.cpp
Datorsmurf/liang
0fc2f142429894f349399189eb16737ae71c2460
[ "MIT" ]
1
2021-12-27T09:43:26.000Z
2021-12-27T09:43:26.000Z
src/behaviors/charge.cpp
Datorsmurf/liang
0fc2f142429894f349399189eb16737ae71c2460
[ "MIT" ]
null
null
null
src/behaviors/charge.cpp
Datorsmurf/liang
0fc2f142429894f349399189eb16737ae71c2460
[ "MIT" ]
null
null
null
#include "charge.h" #include "Controller.h" #include "Logger.h" #include "definitions.h" Charge::Charge(Controller *controller_, LOGGER *logger_, BATTERY *battery_, MowerModel* mowerModel_) { controller = controller_; logger = logger_; battery = battery_; mowerModel = mowerModel_; } void Charge::start() { controller->StopMovement(); controller->StopCutter(); lastCharge = millis(); wiggleStart = 0; } int Charge::loop() { if (mowerModel->CurrentOpModeId == OP_MODE_MOW && battery->isFullyCharged()) { return BEHAVIOR_LAUNCH; } if(battery->isBeingCharged()) { lastCharge = millis(); wiggleStart = 0; } //Give up wiggling after 2 minutes if (hasTimeout(lastCharge, 120000)) { //logger->log("Giving up wiggling."); wiggleStart = 0; } else if(hasTimeout(lastCharge, 2000) && wiggleStart == 0) { logger->log("Dock connection lost. Trying wiggling to reconnect."); wiggleStart = millis(); } //Async wiggling allow for the wiggling to stop immediately when connection is restored. if (wiggleStart > 0){ int i = ((wiggleStart - millis()) / 100) % 200; if ( i == 0 || i == 16) { controller->RunAsync(0, 190, SHORT_ACCELERATION_TIME); } else if (i == 1|| i == 15) { controller->RunAsync(190, 0, SHORT_ACCELERATION_TIME); } else { controller->StopMovement(); } return id(); } controller->StopMovement(); return id(); } int Charge::id() { return BEHAVIOR_CHARGE; } String Charge::desc() { return "Charging"; }
25.671875
102
0.606817
Datorsmurf
66879e66140e6f2f54fb19602ecf31a3192264d5
15,105
cc
C++
src/cc/common/Properties.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
358
2015-01-04T14:04:51.000Z
2022-03-25T09:36:01.000Z
src/cc/common/Properties.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
167
2015-02-09T23:09:42.000Z
2022-02-17T02:47:40.000Z
src/cc/common/Properties.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
124
2015-01-12T13:54:36.000Z
2022-03-04T16:34:24.000Z
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // \brief Properties implementation. // // Created 2004/05/05 // // Copyright 2008-2012,2016 Quantcast Corporation. All rights reserved. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //---------------------------------------------------------------------------- #include "Properties.h" #include "RequestParser.h" #include <iostream> #include <fstream> #include <cstdlib> #include <string.h> #include <errno.h> namespace KFS { using std::string; using std::istream; using std::ifstream; using std::pair; inline static int AsciiCharToLower(int c) { return ((c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c); } template<typename T> inline bool Properties::Parse(const Properties::String& str, const T& def, T& out) const { const char* ptr = str.GetPtr(); const size_t size = str.GetSize(); if (intbase == 10) { if (! DecIntParser::Parse(ptr, size, out)) { out = def; } return true; } if (intbase == 16) { if (! HexIntParser::Parse(ptr, size, out)) { out = def; } return true; } return false; } template<typename T> inline static void removeLTSpaces(const string& str, string::size_type start, string::size_type end, T& outStr, bool asciiToLower = false) { char const* const delims = " \t\r\n"; if (start >= str.length()) { outStr.clear(); return; } string::size_type const first = str.find_first_not_of(delims, start); if (end <= first || first == string::npos) { outStr.clear(); return; } string::size_type const last = str.find_last_not_of( delims, end == string::npos ? string::npos : end - 1); if (asciiToLower) { outStr.clear(); for (const char* p = str.data() + first, * e = str.data() + (last == string::npos ? str.size() : last + 1); p < e; ++p) { outStr.Append(AsciiCharToLower(*p & 0xFF)); } return; } outStr.Copy(str.c_str() + first, (last == string::npos ? str.size() : last + 1) - first); } /* static */ string Properties::AsciiToLower(const string& str) { string s(str); for (string::iterator i = s.begin(); i != s.end(); ++i) { const int c = AsciiCharToLower(*i & 0xFF); if (c != *i) { *i = c; } } return s; } Properties::Properties(int base) : intbase(base), propmap() { } Properties::Properties(const Properties &p) : intbase(p.intbase), propmap(p.propmap) { } Properties::~Properties() { } int Properties::loadProperties( const char* fileName, char delimiter, ostream* verbose /* = 0 */, bool multiline /* = false */, bool keysAsciiToLower /* = false */) { ifstream input(fileName); if(! input.is_open()) { const int err = errno; return (err < 0 ? err : (0 == err ? -EIO : -err)); } loadProperties(input, delimiter, verbose, multiline, keysAsciiToLower); input.close(); return 0; } int Properties::loadProperties( istream& ist, char delimiter, ostream* verbose, bool multiline /* = false */, bool keysAsciiToLower /* = false */) { string line; String key; String val; if (ist) { line.reserve(512); } while (ist) { getline(ist, line); //read one line at a time if (line.empty() || line[0] == '#') { continue; // ignore comments } // find the delimiter string::size_type const pos = line.find(delimiter); if (pos == string::npos) { continue; // ignore if no delimiter is found } removeLTSpaces(line, 0, pos, key, keysAsciiToLower); removeLTSpaces(line, pos + 1, string::npos, val); if (multiline) { // allow properties to span across multiple lines propmap[key].Append(val); } else { propmap[key] = val; } if (verbose) { (*verbose) << "loading key " << key << " with value " << propmap[key] << "\n"; } } return 0; } int Properties::loadProperties( const char* buf, size_t len, char delimiter, ostream* verbose /* = 0 */, bool multiline /* = false */, bool keysAsciiToLower /* = false */) { PropertiesTokenizer tokenizer(buf, len); if (keysAsciiToLower) { String lkey; while (tokenizer.Next(delimiter)) { const PropertiesTokenizer::Token& key = tokenizer.GetKey(); const PropertiesTokenizer::Token& val = tokenizer.GetValue(); lkey.clear(); for (const char* p = key.mPtr, * e = p + key.mLen; p < e; ++p) { lkey.Append(AsciiCharToLower(*p & 0xFF)); } if (multiline) { propmap[lkey].Append(val.mPtr, val.mLen); } else { propmap[lkey].Copy(val.mPtr, val.mLen); } if (verbose) { (*verbose) << "loading key "; verbose->write(key.mPtr, key.mLen); (*verbose) << " with value "; verbose->write(val.mPtr, val.mLen); (*verbose) << "\n"; } } } else { while (tokenizer.Next(delimiter)) { const PropertiesTokenizer::Token& key = tokenizer.GetKey(); const PropertiesTokenizer::Token& val = tokenizer.GetValue(); if (multiline) { propmap[String(key.mPtr, key.mLen)].Append(val.mPtr, val.mLen); } else { propmap[String(key.mPtr, key.mLen)].Copy(val.mPtr, val.mLen); } if (verbose) { (*verbose) << "loading key "; verbose->write(key.mPtr, key.mLen); (*verbose) << " with value "; verbose->write(val.mPtr, val.mLen); (*verbose) << "\n"; } } } return 0; } void Properties::setValue(const string& key, const string& value) { String kstr; if (key.length() > size_t(kStringBufSize)) { kstr = key; } else { kstr.Copy(key.data(), key.size()); } if (value.length() > size_t(kStringBufSize)) { propmap[kstr] = value; } else { propmap[kstr].Copy(value.data(), value.size()); } } void Properties::setValue(const Properties::String& key, const string& value) { if (value.length() > size_t(kStringBufSize)) { propmap[key] = value; } else { propmap[key].Copy(value.data(), value.size()); } } string Properties::getValueSelf(const Properties::String& key, const string& def) const { PropMap::const_iterator const i = find(key); if (i == propmap.end()) { return def; } if (i->second.size() > size_t(kStringBufSize)) { return i->second.GetStr(); } return string(i->second.data(), i->second.size()); } const char* Properties::getValueSelf(const Properties::String& key, const char* def) const { PropMap::const_iterator const i = find(key); return (i == propmap.end() ? def : i->second.c_str()); } int Properties::getValueSelf(const Properties::String& key, int def) const { PropMap::const_iterator const i = find(key); int ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : (int)strtol(i->second.c_str(), 0, intbase))); } unsigned int Properties::getValueSelf(const Properties::String& key, unsigned int def) const { PropMap::const_iterator const i = find(key); unsigned int ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : (unsigned int)strtoul(i->second.c_str(), 0, intbase))); } long Properties::getValueSelf(const Properties::String& key, long def) const { PropMap::const_iterator const i = find(key); long ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : strtol(i->second.c_str(), 0, intbase))); } unsigned long Properties::getValueSelf(const Properties::String& key, unsigned long def) const { PropMap::const_iterator const i = find(key); unsigned long ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : strtoul(i->second.c_str(), 0, intbase))); } long long Properties::getValueSelf(const Properties::String& key, long long def) const { PropMap::const_iterator const i = find(key); long long ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : strtoll(i->second.c_str(), 0, intbase))); } unsigned long long Properties::getValueSelf(const Properties::String& key, unsigned long long def) const { PropMap::const_iterator const i = find(key); unsigned long long ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : strtoull(i->second.c_str(), 0, intbase))); } double Properties::getValueSelf(const Properties::String& key, double def) const { PropMap::const_iterator const i = find(key); if (i == propmap.end()) { return def; } char* e = 0; const char* const p = i->second.c_str(); const double ret = strtod(p, &e); return ((p < e && *e <= ' ') ? ret : def); } signed char Properties::getValueSelf(const Properties::String& key, signed char def) const { PropMap::const_iterator const i = find(key); signed char ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : (signed char)strtol(i->second.c_str(), 0, intbase))); } unsigned char Properties::getValueSelf(const Properties::String& key, unsigned char def) const { PropMap::const_iterator const i = find(key); unsigned char ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : (unsigned char)strtoul(i->second.c_str(), 0, intbase))); } char Properties::getValueSelf(const Properties::String& key, char def) const { PropMap::const_iterator const i = find(key); char ret = def; return (i == propmap.end() ? def : (Parse(i->second, def, ret) ? ret : (char)strtol(i->second.c_str(), 0, intbase))); } bool Properties::remove(const Properties::String& key) { return (propmap.erase(key) > 0); } void Properties::getList(string& outBuf, const string& linePrefix, const string& lineSuffix) const { PropMap::const_iterator iter; for (iter = propmap.begin(); iter != propmap.end(); iter++) { if (iter->first.size() > 0) { outBuf += linePrefix; outBuf.append(iter->first.data(), iter->first.size()); outBuf += '='; outBuf.append(iter->second.data(), iter->second.size()); outBuf += lineSuffix; } } return; } size_t Properties::copyWithPrefix(const char* prefix, Properties& props) const { return copyWithPrefix(prefix, prefix ? strlen(prefix) : size_t(0), props); } inline static bool KeyStartsWith(const Properties::String& key, const char* prefix, size_t prefixLen) { return (key.size() >= prefixLen && memcmp(key.data(), prefix, prefixLen) == 0); } size_t Properties::copyWithPrefix(const char* prefix, size_t prefixLen, Properties& props) const { size_t ret = 0; if (prefix && 0 < prefixLen) { for (PropMap::const_iterator it = propmap.lower_bound( String(prefix, prefixLen)); it != propmap.end(); it++) { const String& key = it->first; if (! KeyStartsWith(key, prefix, prefixLen)) { break; } pair<PropMap::iterator, bool> res = props.propmap.insert( make_pair(key, it->second)); if (res.second) { ret++; } else if (res.first->second != it->second) { res.first->second = it->second; ret++; } } return ret; } for (PropMap::const_iterator it = propmap.begin(); it != propmap.end(); ++it) { const String& key = it->first; if (prefixLen <= key.size()) { pair<PropMap::iterator, bool> res = props.propmap.insert( make_pair(key, it->second)); if (res.second) { ret++; } else if (res.first->second != it->second) { res.first->second = it->second; ret++; } } } return ret; } bool Properties::equalsWithPrefix(const char* prefix, size_t prefixLen, const Properties& props) const { if (prefixLen <= 0) { return (propmap == props.propmap); } if (prefix) { const String pref(prefix, prefixLen); for (PropMap::const_iterator it = propmap.lower_bound(pref), oit = props.propmap.lower_bound(pref); ; ++it, ++oit) { if (it == propmap.end() || ! KeyStartsWith(it->first, prefix, prefixLen)) { return (oit == props.propmap.end() || ! KeyStartsWith(oit->first, prefix, prefixLen)); } if (oit == props.propmap.end() || *it != *oit) { break; } } return false; } for (PropMap::const_iterator it = propmap.begin(), oit = props.propmap.begin(); ;) { while (it != propmap.end() && it->first.size() < prefixLen) { ++it; } while (oit != props.propmap.end() && oit->first.size() < prefixLen) { ++oit; } if (it == propmap.end()) { return (oit == props.propmap.end()); } if (oit == props.propmap.end() || *it != *oit) { break; } ++it; ++oit; } return false; } bool Properties::hasPrefix(const char* prefix) const { return hasPrefix(prefix, strlen(prefix)); } bool Properties::hasPrefix(const char* prefix, size_t prefixLen) const { if (! prefix || prefixLen <= 0) { return (! propmap.empty()); } PropMap::const_iterator const it = propmap.lower_bound(String(prefix, prefixLen)); return (it != propmap.end() && KeyStartsWith(it->first, prefix, prefixLen)); } } // namespace KFS
28.71673
80
0.553525
kristi
6687e88611b8c88160b5ec7f98d2021ec8e03f16
283
cc
C++
source/nss_api/src/LogError.cc
1nfiniteloop/nss-http
84f4412e30527b9e56e6bc59b3009987f2352671
[ "MIT" ]
null
null
null
source/nss_api/src/LogError.cc
1nfiniteloop/nss-http
84f4412e30527b9e56e6bc59b3009987f2352671
[ "MIT" ]
null
null
null
source/nss_api/src/LogError.cc
1nfiniteloop/nss-http
84f4412e30527b9e56e6bc59b3009987f2352671
[ "MIT" ]
null
null
null
#include <iostream> #include <syslog.h> #include "LogError.h" namespace nss_api { void LogError(const std::string& message) { openlog("nss-http", LOG_CONS | LOG_NDELAY, LOG_LOCAL1); syslog(LOG_ERR, "nss-http error: %s", message.c_str()); closelog(); } } // namespace nss_api
20.214286
58
0.699647
1nfiniteloop
668b22422cdc87542273663c4cb0b4a7c53dc990
1,006
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/LAB MID/main(1).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include <iostream> #include "stack.cpp" #include "queue.cpp" using namespace std; QueueLL Reverse (int k) { QueueLL<char> qq ; for(int i = k ; i > 0 ; i-- ) { qq.insertAtEnd(q.getValue(i)) } for (int i = k ; q.hasNext () ; i++ ) { qq.enqueue(q.getValue(i)) ; } return qq ; } int getMax () { int m = 0 ; StackLL ss ; StackLL sss ; while (s.hasNext ()) { ss.push(s.Top()) ; sss.push (s.Top ()) ; s.pop () ; } while (sss.hasNext ()) { s.push (sss.pop()) ; } while (ss.hasNext()) { if (m<ss.top) { m= ss.pop() ; sss.pop(); } } return m ; } int main() { //2-QUEUE QueueLL <char> q ; q.enqueue('a') ; q.enqueue('b') ; q.enqueue('c') ; q.enqueue('d') ; cout << q.Reverse (2 ) ; //1-Stack StackLL <int > s ; s.push(1); s.push(2); s.push(4); s.push(3); s.push(5); cout << s.getMax () ; return 0; }
16.766667
43
0.445328
diptu
668b330b93d84dd01a682426fbe99ced2598a426
1,210
cpp
C++
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
vanilla/34-find_first_and_last_position_of_element_in_sorted_array.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
class Solution { public: //找到非降序数组中首个大于(等于)目标数的下标,以下两种均可 //注意r的初始赋值、迭代式和循环条件中的取等情况 int binarySearch(vector<int>& nums, int target, bool allow_eq){ int l = 0, r = nums.size() - 1, mid; while(l <= r){ mid = (l + r) >> 1; if((eq && nums[mid] < target) || (!eq && nums[mid] <= target)) l = mid + 1; else r = mid - 1; } return l; } int binarySearch(vector<int>& nums, int target, bool allow_eq){ int l = 0, r = nums.size(), mid; while(l < r){ mid = (l + r) >> 1; if((eq && nums[mid] < target) || (!eq && nums[mid] <= target)) l = mid + 1; else r = mid; } return l; } vector<int> searchRange(vector<int>& nums, int target) { int first = binarySearch(nums, target, true); if(first >= nums.size() || nums[first] != target) first = -1; int second = first == -1 ? -1 : binarySearch(nums, target, false)-1; vector<int> ans = {first, second}; return ans; } };
37.8125
89
0.428926
Junlin-Yin
668e17d5bb73cb07b1b2e61a556510751b8c0e8a
1,752
cpp
C++
codejam/qualification/latin/main.cpp
jschmidtnj/competitive
cb16f285f1022d9d16e654b755d89a1b0e53deeb
[ "MIT" ]
null
null
null
codejam/qualification/latin/main.cpp
jschmidtnj/competitive
cb16f285f1022d9d16e654b755d89a1b0e53deeb
[ "MIT" ]
null
null
null
codejam/qualification/latin/main.cpp
jschmidtnj/competitive
cb16f285f1022d9d16e654b755d89a1b0e53deeb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int num_tests; cin >> num_tests; for (int current_test = 0; current_test < num_tests; current_test++) { int n; cin >> n; int trace = 0; unordered_set<int> row_vals; row_vals.reserve(n); vector<unordered_set<int>> column_vals; column_vals.reserve(n); for (int i = 0; i < n; i++) { column_vals.push_back(unordered_set<int>()); } for (unordered_set<int>& column_set : column_vals) { column_set.reserve(n); } vector<bool> column_limit; column_limit.reserve(n); for (int i = 0; i < n; i++) { column_limit.push_back(false); } int num_repeat_rows = 0; int num_repeat_columns = 0; for (int row = 0; row < n; row++) { bool found_repeat_row = false; for (int column = 0; column < n; column++) { int current_val; cin >> current_val; if (!column_limit.at(column)) { if (column_vals.at(column).find(current_val) == column_vals.at(column).end()) { column_vals.at(column).insert(current_val); } else { num_repeat_columns++; column_limit.at(column) = true; } } if (!found_repeat_row) { if (row_vals.find(current_val) == row_vals.end()) { row_vals.insert(current_val); } else { found_repeat_row = true; } } if (row == column) { trace += current_val; } } if (found_repeat_row) { num_repeat_rows++; } row_vals.clear(); } cout << "Case #" << current_test + 1 << ": " << trace << ' ' << num_repeat_rows << ' ' << num_repeat_columns << '\n'; } }
27.809524
72
0.538813
jschmidtnj
668ebba06c41a39f8be59841f6699dce1368cd37
3,412
cpp
C++
app/qshare/FastDXT/main.cpp
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
null
null
null
app/qshare/FastDXT/main.cpp
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
null
null
null
app/qshare/FastDXT/main.cpp
benyaboy/sage-graphics
090640167329ace4b6ad266d47db5bb2b0394232
[ "Unlicense" ]
1
2021-07-02T10:31:03.000Z
2021-07-02T10:31:03.000Z
/****************************************************************************** * Fast DXT - a realtime DXT compression tool * * Author : Luc Renambot * * Copyright (C) 2007 Electronic Visualization Laboratory, * University of Illinois at Chicago * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the distribution. * * Neither the name of the University of Illinois at Chicago nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Direct questions, comments etc about SAGE to http://www.evl.uic.edu/cavern/forum/ * *****************************************************************************/ #include "dxt.h" #include "util.h" #if defined(__APPLE__) #define memalign(x,y) malloc((y)) #else #include <malloc.h> #endif int main(int argc, char** argv) { ALIGN16( byte *in ); ALIGN16( byte *out); double t1, t2; int nbbytes; // Initialize some timing functions and else aInitialize(); /* Read an image. */ unsigned long width = atoi(argv[1]); unsigned long height = atoi(argv[2]); in = (byte*)memalign(16, width*height*4); memset(in, 0, width*height*4); FILE *f=fopen(argv[3], "rb"); fread(in, 1, width*height*4, f); fclose(f); out = (byte*)memalign(16, width*height*4); memset(out, 0, width*height*4); fprintf(stderr, "Converting to raw: %ldx%ld\n", width, height); t1 = aTime(); for (int k=0;k<100;k++) { CompressImageDXT1( in, out, width, height, nbbytes); } t2 = aTime(); fprintf(stderr, "Converted to DXT: %d byte, compression %ld\n", nbbytes, (width*height*4) / (nbbytes)); fprintf(stderr, "Time %.2f sec, Single %.2f sec, Freq %.2f Hz\n", t2-t1, (t2-t1)/100.0, 100.0/(t2-t1) ); fprintf(stderr, "MP/sec %.2f\n", ((double)(width*height)) / ((t2-t1)*10000.0) ); #if 1 FILE *g=fopen("out.dxt", "wb+"); fwrite(&width, 4, 1, g); fwrite(&height, 4, 1, g); //nbbytes = width * height * 4 / 4; //DXT5 nbbytes = width * height * 3 / 6; // DXT1 fwrite(out, 1, nbbytes, g); fclose(g); #endif memfree(in); memfree(out); return 0; }
32.188679
84
0.658851
benyaboy
668f0e3d40e90a9d5d1b759b8223cc378ad9c16d
2,685
hpp
C++
third_party/gfootball_engine/src/framework/scheduler.hpp
Jonas1711/football
6a20dcb832da71d4e97e094e4afa060533aa7dcc
[ "Apache-2.0" ]
2
2021-03-16T06:46:38.000Z
2021-09-14T02:01:16.000Z
third_party/gfootball_engine/src/framework/scheduler.hpp
Jonas1711/football
6a20dcb832da71d4e97e094e4afa060533aa7dcc
[ "Apache-2.0" ]
null
null
null
third_party/gfootball_engine/src/framework/scheduler.hpp
Jonas1711/football
6a20dcb832da71d4e97e094e4afa060533aa7dcc
[ "Apache-2.0" ]
4
2020-07-30T17:02:42.000Z
2022-01-03T19:32:53.000Z
// Copyright 2019 Google LLC & Bastiaan Konings // 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. // written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_SCHEDULER #define _HPP_SCHEDULER #include "../defines.hpp" #include "../systems/isystemtask.hpp" #include "../types/iusertask.hpp" #include "tasksequence.hpp" namespace blunted { struct TaskSequenceProgram { boost::shared_ptr<TaskSequence> taskSequence; int programCounter = 0; int previousProgramCounter = 0; unsigned long sequenceStartTime = 0; unsigned long lastSequenceTime = 0; unsigned long startTime = 0; int timesRan = 0; // set to true if sequence is finished bool readyToQuit = false; }; // sort of 'light version' of the above, meant as informative to return to nosey enquirers struct TaskSequenceInfo { TaskSequenceInfo() { sequenceStartTime_ms = 0; lastSequenceTime_ms = 0; startTime_ms = 0; sequenceTime_ms = 0; timesRan = 0; } unsigned long sequenceStartTime_ms = 0; unsigned long lastSequenceTime_ms = 0; unsigned long startTime_ms = 0; int sequenceTime_ms = 0; int timesRan = 0; }; struct TaskSequenceQueueEntry { TaskSequenceQueueEntry() { timeUntilDueEntry_ms = 0; } boost::shared_ptr<TaskSequenceProgram> program; long timeUntilDueEntry_ms = 0; }; class Scheduler { public: Scheduler(); virtual ~Scheduler(); int GetSequenceCount(); void RegisterTaskSequence(boost::shared_ptr<TaskSequence> sequence); void ResetTaskSequenceTime(const std::string &name); TaskSequenceInfo GetTaskSequenceInfo(const std::string &name); /// send due system tasks a SystemTaskMessage_StartFrame message /// invoke due user tasks with an Execute() call bool Run(); protected: unsigned long previousTime_ms = 0; std::vector < boost::shared_ptr<TaskSequenceProgram> > sequences; }; } #endif
30.168539
132
0.707263
Jonas1711
66928415080d4149cdc1347d017a213eba83667d
2,257
cpp
C++
RobWork/src/rw/sensor/CameraModel.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/sensor/CameraModel.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/sensor/CameraModel.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "CameraModel.hpp" using namespace rw::sensor; using namespace rw::kinematics; CameraModel::CameraModel (const rw::math::ProjectionMatrix& projection, const std::string& name, rw::kinematics::Frame* frame, const std::string& modelInfo) : SensorModel (name, frame, modelInfo), _pmatrix (projection), _sdata (1, rw::core::ownedPtr (new CameraModelCache ()).cast< StateCache > ()) { add (_sdata); } CameraModel::~CameraModel () {} double CameraModel::getFarClippingPlane () const { return _pmatrix.getClipPlanes ().second; } double CameraModel::getNearClippingPlane () const { return _pmatrix.getClipPlanes ().first; } Image::Ptr CameraModel::getImage (const rw::kinematics::State& state) { return _sdata.getStateCache< CameraModelCache > (state)->_image; } void CameraModel::setImage (Image::Ptr img, rw::kinematics::State& state) { _sdata.getStateCache< CameraModelCache > (state)->_image = img; } rw::math::ProjectionMatrix CameraModel::getProjectionMatrix () const { return _pmatrix; } double CameraModel::getFieldOfViewX () const { double fovy, aspect, znear, zfar; _pmatrix.getPerspective (fovy, aspect, znear, zfar); return fovy * aspect; } double CameraModel::getFieldOfViewY () const { double fovy, aspect, znear, zfar; _pmatrix.getPerspective (fovy, aspect, znear, zfar); return fovy; }
30.917808
96
0.668587
ZLW07
66968babd49c7d9ec889fb929f4d1d532124cfce
1,151
cpp
C++
Dynamic Programming/goldmine.cpp
Ajax-07/Java-Questions-and-Solutions
816c0b7900340ddc438cb8091fbe64f7b56232cc
[ "MIT" ]
null
null
null
Dynamic Programming/goldmine.cpp
Ajax-07/Java-Questions-and-Solutions
816c0b7900340ddc438cb8091fbe64f7b56232cc
[ "MIT" ]
null
null
null
Dynamic Programming/goldmine.cpp
Ajax-07/Java-Questions-and-Solutions
816c0b7900340ddc438cb8091fbe64f7b56232cc
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int maxGold(int n, int m, vector<vector<int>> arr){ int ans = 0; if(n==1){ for(int j=0; j<m; j++) ans += arr[0][j]; return ans; } int dp[n][m]; for(int i=n-1; i>=0; i--) dp[i][m-1] = arr[i][m-1]; ans=INT_MIN; for(int j=m-2; j>=0; j--){ for(int i=0; i<n; i++){ if(i==0) dp[i][j] = arr[i][j]+max(dp[i][j+1],dp[i+1][j+1]) ; else if(i==n-1) dp[i][j] = arr[i][j]+max(dp[i-1][j+1], dp[i][j+1]); else dp[i][j] = arr[i][j]+max(dp[i][j+1],max(dp[i-1][j+1], dp[i+1][j+1])); } } for(int i=0; i<n; i++) ans = max(ans,dp[i][0]); return ans; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n,m; cin >> n >> m; vector<vector<int>> arr(n); for(int i=0; i<n; i++) arr[i].resize(m); for(int i=0; i<n; i++) for(int j=0; j<m; j++) cin >> arr[i][j]; cout << maxGold(n, m, arr); return 0; }
20.553571
81
0.414422
Ajax-07