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
5c404b0c46c1e1b426c706138fdb7e2f0f9345bb
1,964
cpp
C++
ftt_backend/hlsBackend.cpp
Hecmay/p4c-ftt
9180e9635d3df5bd5c2ce74a5c24af5df027b9df
[ "MIT" ]
null
null
null
ftt_backend/hlsBackend.cpp
Hecmay/p4c-ftt
9180e9635d3df5bd5c2ce74a5c24af5df027b9df
[ "MIT" ]
null
null
null
ftt_backend/hlsBackend.cpp
Hecmay/p4c-ftt
9180e9635d3df5bd5c2ce74a5c24af5df027b9df
[ "MIT" ]
null
null
null
#include "lib/error.h" #include "lib/nullstream.h" #include "frontends/p4/evaluator/evaluator.h" #include "hlsBackend.h" #include "target.h" #include "hlsType.h" #include "hlsProgram.h" namespace P4HLS { void run_ebpf_backend(const EbpfOptions& options, const IR::ToplevelBlock* toplevel, P4::ReferenceMap* refMap, P4::TypeMap* typeMap) { if (toplevel == nullptr) return; auto main = toplevel->getMain(); if (main == nullptr) { ::warning(ErrorType::WARN_MISSING, "Could not locate top-level block; is there a %1% module?", IR::P4Program::main); return; } Target* target; if (options.target.isNullOrEmpty() || options.target == "kernel") { target = new KernelSamplesTarget(); } else if (options.target == "bcc") { target = new BccTarget(); } else if (options.target == "test") { target = new TestTarget(); } else { ::error("Unknown target %s; legal choices are 'bcc', 'kernel', and test", options.target); return; } CodeBuilder c(target); CodeBuilder h(target); P4HLSTypeFactory::createFactory(typeMap); auto ebpfprog = new P4HLSProgram(options, toplevel->getProgram(), refMap, typeMap, toplevel); if (!ebpfprog->build()) return; if (options.outputFile.isNullOrEmpty()) return; cstring cfile = options.outputFile; auto cstream = openFile(cfile, false); if (cstream == nullptr) return; cstring hfile; const char* dot = cfile.findlast('.'); if (dot == nullptr) hfile = cfile + ".h"; else hfile = cfile.before(dot) + ".h"; auto hstream = openFile(hfile, false); if (hstream == nullptr) return; ebpfprog->emitH(&h, hfile); ebpfprog->emitC(&c, hfile); *cstream << c.toString(); *hstream << h.toString(); cstream->flush(); hstream->flush(); } } // namespace P4HLS
27.277778
98
0.600305
Hecmay
5c420197519741bd5d396af42b2a59c22254ac3b
3,228
cpp
C++
src/org/apache/poi/util/ShortField.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/ShortField.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/ShortField.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/util/ShortField.java #include <org/apache/poi/util/ShortField.hpp> #include <java/lang/ArrayIndexOutOfBoundsException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <org/apache/poi/util/LittleEndian.hpp> poi::util::ShortField::ShortField(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::util::ShortField::ShortField(int32_t offset) /* throws(ArrayIndexOutOfBoundsException) */ : ShortField(*static_cast< ::default_init_tag* >(0)) { ctor(offset); } poi::util::ShortField::ShortField(int32_t offset, int16_t value) /* throws(ArrayIndexOutOfBoundsException) */ : ShortField(*static_cast< ::default_init_tag* >(0)) { ctor(offset,value); } poi::util::ShortField::ShortField(int32_t offset, ::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ : ShortField(*static_cast< ::default_init_tag* >(0)) { ctor(offset,data); } poi::util::ShortField::ShortField(int32_t offset, int16_t value, ::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ : ShortField(*static_cast< ::default_init_tag* >(0)) { ctor(offset,value,data); } void poi::util::ShortField::ctor(int32_t offset) /* throws(ArrayIndexOutOfBoundsException) */ { super::ctor(); if(offset < 0) { throw new ::java::lang::ArrayIndexOutOfBoundsException(::java::lang::StringBuilder().append(u"Illegal offset: "_j)->append(offset)->toString()); } _offset = offset; } void poi::util::ShortField::ctor(int32_t offset, int16_t value) /* throws(ArrayIndexOutOfBoundsException) */ { ctor(offset); set(value); } void poi::util::ShortField::ctor(int32_t offset, ::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ { ctor(offset); readFromBytes(data); } void poi::util::ShortField::ctor(int32_t offset, int16_t value, ::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ { ctor(offset); set(value, data); } int16_t poi::util::ShortField::get() { return _value; } void poi::util::ShortField::set(int16_t value) { _value = value; } void poi::util::ShortField::set(int16_t value, ::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ { _value = value; writeToBytes(data); } void poi::util::ShortField::readFromBytes(::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ { _value = LittleEndian::getShort(data, _offset); } void poi::util::ShortField::readFromStream(::java::io::InputStream* stream) /* throws(IOException) */ { _value = LittleEndian::readShort(stream); } void poi::util::ShortField::writeToBytes(::int8_tArray* data) /* throws(ArrayIndexOutOfBoundsException) */ { LittleEndian::putShort(data, _offset, _value); } java::lang::String* poi::util::ShortField::toString() { return ::java::lang::String::valueOf(static_cast< int32_t >(_value)); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::util::ShortField::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.util.ShortField", 30); return c; } java::lang::Class* poi::util::ShortField::getClass0() { return class_(); }
28.069565
152
0.703841
pebble2015
5c42ca7bb0f4595b1a2817fda887cf080c6f291c
1,119
cpp
C++
beecrowd/C++/basico/1021.cpp
MateusdeNovaesSantos/Tecnologias
0a4d55f82942e33ed86202c58596f03d0dddbf6d
[ "MIT" ]
null
null
null
beecrowd/C++/basico/1021.cpp
MateusdeNovaesSantos/Tecnologias
0a4d55f82942e33ed86202c58596f03d0dddbf6d
[ "MIT" ]
null
null
null
beecrowd/C++/basico/1021.cpp
MateusdeNovaesSantos/Tecnologias
0a4d55f82942e33ed86202c58596f03d0dddbf6d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ double N; long int NINT; cin >> N; N = N * 100; NINT = N; cout << "NOTAS:" << endl; cout << NINT / 10000 << " nota(s) de R$ 100.00" << endl; NINT %= 10000; cout << NINT / 5000 << " nota(s) de R$ 50.00" << endl; NINT %= 5000; cout << NINT / 2000 << " nota(s) de R$ 20.00" << endl; NINT %= 2000; cout << NINT / 1000 << " nota(s) de R$ 10.00" << endl; NINT %= 1000; cout << NINT / 500 << " nota(s) de R$ 5.00" << endl; NINT %= 500; cout << NINT / 200 << " nota(s) de R$ 2.00" << endl; NINT %= 200; cout << "MOEDAS:" << endl; cout << NINT / 100 << " moeda(s) de R$ 1.00" << endl; NINT %= 100; cout << NINT / 50 << " moeda(s) de R$ 0.50" << endl; NINT %= 50; cout << NINT / 25 << " moeda(s) de R$ 0.25" << endl; NINT %= 25; cout << NINT / 10 << " moeda(s) de R$ 0.10" << endl; NINT %= 10; cout << NINT / 5 << " moeda(s) de R$ 0.05" << endl; NINT %= 5; cout << NINT / 1 << " moeda(s) de R$ 0.01" << endl; return 0; }
16.701493
60
0.449508
MateusdeNovaesSantos
5c45b1f6fa955a76c9ba95c608399dc707462bd6
2,874
hpp
C++
lib/headers/Optimisation/LevenbergMarquardt.hpp
JackHunt/GaussianProcess
64820259608229ebc324904ec2f6213f205af804
[ "BSD-3-Clause" ]
null
null
null
lib/headers/Optimisation/LevenbergMarquardt.hpp
JackHunt/GaussianProcess
64820259608229ebc324904ec2f6213f205af804
[ "BSD-3-Clause" ]
null
null
null
lib/headers/Optimisation/LevenbergMarquardt.hpp
JackHunt/GaussianProcess
64820259608229ebc324904ec2f6213f205af804
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2020, Jack Miles Hunt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPLIB_LEVENBERG_MARQUARDT_HEADER #define GPLIB_LEVENBERG_MARQUARDT_HEADER #include "Optimiser.hpp" namespace GPLib::Optimisation { template<typename T> class LMParameters : public OptimiserParameters<T> { protected: T lambda; public: LMParameters(std::shared_ptr<GaussianProcess<T>> gp, const MappedMatrix<T>& X, const MappedVector<T>& Y, T lambda = 0.1, unsigned int maxIterations = 100, T minConvergenceNorm = 1e-3, unsigned int convergenceWindow = 5) : OptimiserParameters<T>(X, Y, maxIterations, minConvergenceNorm, convergenceWindow) { // Verify lambda. assert(lambda > 0); } T getLambda() const { return lambda; } void setLambda(T lambda) { assert(lambda > 0); this->lambda = lambda; } }; template<typename T> class LevenbergMarquardt : public Optimiser<T> { protected: T lambda; Matrix<T> gradK; public: LevenbergMarquardt(const LMParameters<T>& parameters); virtual ~LevenbergMarquardt(); virtual void operator()() override; }; } #endif
34.214286
78
0.68302
JackHunt
5c4c739eba81376c7be499db87eeb6d6b2385962
3,449
cpp
C++
BINARYTREE/binarytree.cpp
michaelpeterswa/cpsc223
ae5371126ccf91e7c2179a04fd8057036be65e2d
[ "MIT" ]
1
2019-01-17T21:23:24.000Z
2019-01-17T21:23:24.000Z
BINARYTREE/binarytree.cpp
michaelpeterswa/cpsc223
ae5371126ccf91e7c2179a04fd8057036be65e2d
[ "MIT" ]
null
null
null
BINARYTREE/binarytree.cpp
michaelpeterswa/cpsc223
ae5371126ccf91e7c2179a04fd8057036be65e2d
[ "MIT" ]
null
null
null
//file binarytree.cpp //author Michael Peters //date October 7, 2018 //Specification of ADT Binary Tree // Data object: a binary tree which is either empty or // in the form of r // / // TL TR // where TL and TR are binary trees // Data Structure: // Operations: create, destroy, insert a new node, // traversals: preorder, inorder, postorder #include <iostream> #include "binarytree.h" using namespace std; //recursive helper (preorder) void preorderHelper(TreeNode tree[], int myroot) { Item copyItem; if(myroot != -1){ tree[myroot].getItem(copyItem); cout << "\t" << copyItem << endl; preorderHelper(tree, tree[myroot].getLeftChild()); preorderHelper(tree, tree[myroot].getRightChild()); } } //recursive helper (inorder) void inorderHelper(TreeNode tree[], int myroot) { Item copyItem; if(myroot != -1){ inorderHelper(tree, tree[myroot].getLeftChild()); tree[myroot].getItem(copyItem); cout << "\t" << copyItem << endl; inorderHelper(tree, tree[myroot].getRightChild()); } } //recursive helper (postorder) void postorderHelper(TreeNode tree[], int myroot) { Item copyItem; if(myroot != -1){ postorderHelper(tree, tree[myroot].getLeftChild()); postorderHelper(tree, tree[myroot].getRightChild()); tree[myroot].getItem(copyItem); cout << "\t" << copyItem << endl; } } //creates an empty binary tree //post an empty BinaryTree object exists BinaryTree::BinaryTree() { root = -1; numberOfItems = 0; } //releases a binary tree //pre a BinaryTree object exists //post the BinaryTree object no longer exists BinaryTree::~BinaryTree() { root = -1; numberOfItems = 0; } //inserts a new node into a binary tree //pre BinaryTree object exists. newItem, left, right are assigned //post a node containing newItem with children left and right // has been added to the BinaryTree object //usage tree.insert(myItem, 1, 2); void BinaryTree::insert(const Item& newItem, int left, int right) { if (numberOfItems < MAXITEMS) { binaryTree[numberOfItems].setNode(newItem, left, right); if(numberOfItems == 0) root = 0; numberOfItems++;//use setnode inn treenode class } } //performs a Pre-Order traversal of a binary tree //pre BinaryTree object exists //post the items of the BinaryTree object are printed in Pre-Order // with items separated by a semi-colon // There is a newline after the last one //usage tree.preorder(); void BinaryTree::preorder() { preorderHelper(binaryTree, root); cout << endl; } //performs a In-Order traversal of a binary tree //pre BinaryTree object exists //post the items of the BinaryTree object are printed in In-Order // with items separated by a semi-colon // There is a newline after the last one //usage tree.inorder(); void BinaryTree::inorder() { inorderHelper(binaryTree, root); cout << endl; } //performs a Post-Order traversal of a binary tree //pre BinaryTree object exists //post the items of the BinaryTree object are printed in Post-Order // with items separated by a semi-colon // There is a newline after the last one //usage tree.postorder(); void BinaryTree::postorder() { postorderHelper(binaryTree, root); cout << endl; }
27.814516
67
0.654103
michaelpeterswa
5c4da1d7449913d58645996c9cf4a44da29a100b
1,167
hpp
C++
src/macros.hpp
sandialabs/calibr8
a7be9213a49eb2b56f58041a2a88b0184382de4d
[ "MIT" ]
5
2021-08-31T00:33:36.000Z
2022-03-29T17:10:28.000Z
src/macros.hpp
sandialabs/calibr8
a7be9213a49eb2b56f58041a2a88b0184382de4d
[ "MIT" ]
null
null
null
src/macros.hpp
sandialabs/calibr8
a7be9213a49eb2b56f58041a2a88b0184382de4d
[ "MIT" ]
null
null
null
#pragma once #include "control.hpp" #define ALWAYS_ASSERT(cond) \ do { \ if (! (cond)) { \ char omsg[2048]; \ sprintf(omsg, "%s failed at %s + %d \n", \ #cond, __FILE__, __LINE__); \ calibr8::assert_fail(omsg); \ } \ } while (0) #define ALWAYS_ASSERT_VERBOSE(cond, msg) \ do { \ if (! (cond)) { \ char omsg[2048]; \ sprintf(omsg, "%s failed at %s + %d \n %s \n", \ #cond, __FILE__, __LINE__, msg); \ calibr8::assert_fail(omsg); \ } \ } while(0) #ifdef NDEBUG #define DEBUG_ASSERT(cond) #define DEBUG_ASSERT_VERBOSE(cond, msg) #else #define DEBUG_ASSERT(cond) \ ALWAYS_ASSERT(cond) #define DEBUG_ASSERT_VERBOSE(cond, msg) \ ALWAYS_ASSERT_VERBOSE(cond, msg) #endif
34.323529
55
0.382177
sandialabs
5c4e24a82ebe72dfde7af5dfcec8238079f3dc1c
964
cpp
C++
test/std/input.output/iostreams.base/ios/basic.ios.members/rdbuf_streambuf.pass.cpp
ontio/libcxx-mirror
4b4f32ea383deb28911f5618126c6ea6c110b5e4
[ "Apache-2.0" ]
null
null
null
test/std/input.output/iostreams.base/ios/basic.ios.members/rdbuf_streambuf.pass.cpp
ontio/libcxx-mirror
4b4f32ea383deb28911f5618126c6ea6c110b5e4
[ "Apache-2.0" ]
1
2019-04-21T16:53:33.000Z
2019-04-21T17:15:25.000Z
test/std/input.output/iostreams.base/ios/basic.ios.members/rdbuf_streambuf.pass.cpp
ontio/libcxx-mirror
4b4f32ea383deb28911f5618126c6ea6c110b5e4
[ "Apache-2.0" ]
1
2020-09-09T07:40:32.000Z
2020-09-09T07:40:32.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // basic_streambuf<charT,traits>* rdbuf(basic_streambuf<charT,traits>* sb); #include <ios> #include <streambuf> #include <cassert> int main(int, char**) { std::ios ios(0); assert(ios.rdbuf() == 0); assert(!ios.good()); std::streambuf* sb = (std::streambuf*)1; std::streambuf* sb2 = ios.rdbuf(sb); assert(sb2 == 0); assert(ios.rdbuf() == sb); assert(ios.good()); sb2 = ios.rdbuf(0); assert(sb2 == (std::streambuf*)1); assert(ios.rdbuf() == 0); assert(ios.bad()); return 0; }
26.777778
80
0.529046
ontio
5c52fdef8f92ca574f0357e0caa4b8a4e4624efb
363
hpp
C++
frontend/typing/normalisation.hpp
NicolaiLS/becarre
cf23e80041f856f50b9f96c087819780dfe1792c
[ "MIT" ]
null
null
null
frontend/typing/normalisation.hpp
NicolaiLS/becarre
cf23e80041f856f50b9f96c087819780dfe1792c
[ "MIT" ]
null
null
null
frontend/typing/normalisation.hpp
NicolaiLS/becarre
cf23e80041f856f50b9f96c087819780dfe1792c
[ "MIT" ]
null
null
null
#if !defined(BECARRE_FRONTEND_TYPING_NORMALISATION_HPP) #define BECARRE_FRONTEND_TYPING_NORMALISATION_HPP #include <optional> namespace becarre::frontend::typing { struct Type; namespace normalisation { void apply(Type &); } // namespace normalisation } // namespace becarre::frontend::typing #endif // !defined(BECARRE_FRONTEND_TYPING_NORMALISATION_HPP)
17.285714
61
0.804408
NicolaiLS
5c53076c74b580736f75fc95f36cf1da164c6427
8,160
cpp
C++
libadb/src/libadb/api/channel/channel-api.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/src/libadb/api/channel/channel-api.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/src/libadb/api/channel/channel-api.cpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#include <libadb/api/channel/channel-api.hpp> #include <libadb/api/context/context.hpp> #include <nlohmann/json.hpp> #include <libadb/api/auth/token-bot.hpp> #include <libadb/api/utils/fill-reason.hpp> #include <libadb/api/utils/message-session.hpp> #include <libadb/api/utils/read-response.hpp> #include <fmt/core.h> #include <cpr/cpr.h> #include <algorithm> using namespace adb::api; using namespace adb::types; ChannelApi::ChannelApi(std::shared_ptr<Context> context) : context_(context), baseUrl_(context->getBaseUrl() + "/channels") { } std::optional<Channel> ChannelApi::getChannel(const adb::types::SFID &channelId) { auto url = fmt::format("{}/{}", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}; session.SetHeader(header); auto response = session.Get(); return readRequestResponseOpt<Channel>(response); } bool ChannelApi::deleteChannel(const adb::types::SFID &channelId, std::optional<std::string> reason) { auto url = fmt::format("{}/{}", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}; session.SetHeader(header); fillReason(header, reason); auto response = session.Delete(); return readCommandResponse(response); } std::vector<Message> ChannelApi::getMessages(adb::types::SFID channelId, std::optional<GetMessagesOpt> opt, std::optional<uint8_t> limit) { auto url = fmt::format("{}/{}/messages", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto params = cpr::Parameters{}; if (opt.has_value()) { auto optVal = opt.value(); std::string key; switch (optVal.type) { case GetMessagesOptType::After: key = "after"; break; case GetMessagesOptType::Around: key = "around"; break; case GetMessagesOptType::Before: key = "before"; break; } if (!key.empty()) params.Add(cpr::Parameter(key, optVal.messageId.to_string())); } if (limit.has_value()) { params.Add(cpr::Parameter("limit", std::to_string(limit.value()))); } session.SetParameters(params); session.SetHeader(cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}); auto response = session.Get(); return readRequestResponse<std::vector<Message>>(response); } std::optional<Message> ChannelApi::getMessage(const adb::types::SFID &channelId, const adb::types::SFID &messageId) { auto url = fmt::format("{}/{}/messages/{}", baseUrl_, channelId.to_string(), messageId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}; session.SetHeader(header); auto response = session.Get(); return readRequestResponseOpt<Message>(response); } bool ChannelApi::createReaction(adb::types::SFID channelId, adb::types::SFID messageId, std::string emoji) { auto encodedEmoji = cpr::util::urlEncode(emoji); auto url = fmt::format("{}/{}/messages/{}/reactions/{}/@me", baseUrl_, channelId.to_string(), messageId.to_string(), encodedEmoji); auto response = cpr::Put( cpr::Url{url}, cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}, cpr::Payload{} ); return readCommandResponse(response); } std::optional<Message> ChannelApi::createMessage(adb::types::SFID channelId, const CreateMessageParams &params) { auto url = fmt::format("{}/{}/messages", baseUrl_, channelId.to_string()); nlohmann::json j = params; auto data = j.dump(); auto session = cpr::Session(); session.SetUrl(url); fillSessionWithMessage(params, data, session, {TokenBot::getBotAuthTokenHeader(context_)}); auto response = session.Post(); return readRequestResponseOpt<Message>(response); } std::optional<Message> ChannelApi::editMessage(adb::types::SFID channelId, adb::types::SFID messageId, const EditMessageParams &params) { auto url = fmt::format("{}/{}/messages/{}", baseUrl_, channelId.to_string(), messageId.to_string()); nlohmann::json j = params; auto data = j.dump(); auto session = cpr::Session(); session.SetUrl(url); fillSessionWithMessage(params, data, session, {TokenBot::getBotAuthTokenHeader(context_)}); auto response = session.Patch(); return readRequestResponseOpt<Message>(response); } bool ChannelApi::deleteMessage(const adb::types::SFID &channelId, const adb::types::SFID &messageId, std::optional<std::string> reason) { auto url = fmt::format("{}/{}/messages/{}", baseUrl_, channelId.to_string(), messageId.to_string()); auto session = cpr::Session(); session.SetUrl(url); cpr::Header header{TokenBot::getBotAuthTokenHeader(context_)}; fillReason(header, reason); session.SetHeader(header); auto response = session.Delete(); return readCommandResponse(response); } bool ChannelApi::bulkDeleteMessages(SFID channelId, std::vector<SFID> messageIds, std::optional<std::string> reason) { auto url = fmt::format("{}/{}/messages/bulk-delete", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto contentType = std::pair{"content-type", "application/json"}; cpr::Header header{TokenBot::getBotAuthTokenHeader(context_), contentType}; fillReason(header, reason); session.SetHeader(header); nlohmann::json j { {"messages", messageIds} }; auto data = j.dump(); session.SetBody(data); auto response = session.Post(); return readCommandResponse(response); } std::optional<FollowedChannel> ChannelApi::followNewsChannel(adb::types::SFID channelId, adb::types::SFID webhookChannelId) { auto url = fmt::format("{}/{}/followers", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto contentType = std::pair{"content-type", "application/json"}; session.SetHeader({TokenBot::getBotAuthTokenHeader(context_), contentType}); nlohmann::json j { {"webhook_channel_id", webhookChannelId} }; auto data = j.dump(); session.SetBody(data); auto response = session.Post(); return readRequestResponseOpt<FollowedChannel>(response); } std::vector<Message> ChannelApi::getPinnedMessages(const adb::types::SFID &channelId) { auto url = fmt::format("{}/{}/pins", baseUrl_, channelId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}; session.SetHeader(header); auto response = session.Get(); return readRequestResponse<std::vector<Message>>(response); } bool ChannelApi::pinMessage(const adb::types::SFID &channelId, const adb::types::SFID &messageId, std::optional<std::string> reason) { auto url = fmt::format("{}/{}/pins/{}", baseUrl_, channelId.to_string(), messageId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto contentType = std::pair{"content-type", "application/json"}; auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_), contentType}; fillReason(header, reason); session.SetHeader(header); // Empty body session.SetBody("{}"); auto response = session.Put(); return readCommandResponse(response); } bool ChannelApi::unpinMessage(const adb::types::SFID &channelId, const adb::types::SFID &messageId, std::optional<std::string> reason) { auto url = fmt::format("{}/{}/pins/{}", baseUrl_, channelId.to_string(), messageId.to_string()); auto session = cpr::Session(); session.SetUrl(url); auto header = cpr::Header{TokenBot::getBotAuthTokenHeader(context_)}; fillReason(header, reason); session.SetHeader(header); auto response = session.Delete(); return readCommandResponse(response); }
37.090909
137
0.673039
faserg1
5c5682b447ab378307987a121bfaabc74b405d8d
149
cpp
C++
source/lib/memory/unused_memory_fea0_feff.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
source/lib/memory/unused_memory_fea0_feff.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
source/lib/memory/unused_memory_fea0_feff.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
#include "lib/memory/unused_memory_fea0_feff.hpp" namespace gb_lib { uint8_t UnusedMemoryFEA0_FEFF::getByte(uint16_t address) { return 0; } }
13.545455
56
0.765101
olduf
5c58eaae8401922d30075897bb5bc28bde474f7a
867
cpp
C++
src/deco.cpp
mrnoda/first-demo
d89b6f4fbe02073aab16365d9f57eae4a695e554
[ "MIT" ]
null
null
null
src/deco.cpp
mrnoda/first-demo
d89b6f4fbe02073aab16365d9f57eae4a695e554
[ "MIT" ]
2
2015-04-18T19:58:14.000Z
2015-04-18T19:59:00.000Z
src/deco.cpp
mrnoda/first-demo
d89b6f4fbe02073aab16365d9f57eae4a695e554
[ "MIT" ]
null
null
null
#include <stdexcept> #include "deco.h" #include "utility.h" namespace effects { Deco::Deco(sf::RenderWindow &window) : Effect(window), border_colour_(sf::Color(100, 20, 100)) { auto window_size = window.getSize(); auto thickness = window_size.y / 60.0f; sf::RectangleShape border(sf::Vector2f(window_size.x, thickness)); border.setFillColor(border_colour_); // Top border borders_.push_back(border); // Bottom border border.setPosition(0, window_size.y - thickness); borders_.push_back(border); } Deco::~Deco() {} void Deco::update(sf::Time elapsed) {} void Deco::draw() { window_.pushGLStates(); for (const auto &border : borders_) { window_.draw(border); } window_.popGLStates(); } }
21.146341
75
0.580161
mrnoda
5c59b70c8d06b7c1b020f24832aa684e9c943679
2,132
cpp
C++
udsc2/src/api/phoneme.cpp
utkucandogan/udsc2
ced007c0760ce0c3a4b2fbdd14672e38bd58d6d6
[ "Apache-2.0" ]
null
null
null
udsc2/src/api/phoneme.cpp
utkucandogan/udsc2
ced007c0760ce0c3a4b2fbdd14672e38bd58d6d6
[ "Apache-2.0" ]
null
null
null
udsc2/src/api/phoneme.cpp
utkucandogan/udsc2
ced007c0760ce0c3a4b2fbdd14672e38bd58d6d6
[ "Apache-2.0" ]
null
null
null
#include <udsc2/phoneme/phoneme.h> #include "phoneme.hpp" #include "util/bit.h" #include <limits> namespace udsc2::api { int phoneme_difference(const api::PhonemeProperties pLeft, const api::PhonemeProperties pRight, const api::PhonemeProperties ignore) { // These are tecnical 'Phonemes' such as start, end or whitespace. Only comparison that // we need is whether their types are same. if (pLeft.type < 8 || pRight.type < 8) { return pLeft.type == pRight.type ? 0 : std::numeric_limits<int>::max(); } // Custom comparison methods that is defined by extension writers. for (auto f : udsc2::Phoneme::comparators) { int i = f(pLeft, pRight, ignore); if (i != -1) return i; } // If types are not same directly get out. Note that this is not before the custom // comparators because extensions may need cross-type differences (such as vowel-semivowel // comparison). if (pLeft.type != pRight.type) { return std::numeric_limits<int>::max(); } int ret = 0; switch (pLeft.type) { case api::TYP_VOWEL: if (ignore.roundness == api::ROU_NONE && pLeft.roundness != pRight.roundness) { return std::numeric_limits<int>::max(); } if (ignore.height == api::HEI_NONE) { ret += std::abs(pLeft.height - pRight.height); } if (ignore.backness == api::BAC_NONE) { ret += std::abs(pLeft.backness - pRight.backness); } case api::TYP_CONSONANT: if (ignore.release == api::REL_NORMAL && pLeft.release != pRight.release) { if (pLeft.release == api::REL_NORMAL) { ret += 1; } else { return std::numeric_limits<int>::max(); } } if (ignore.voicing == api::VOI_NONE && pLeft.voicing != pRight.voicing) { ++ret; } ret += util::popcount(( pLeft.poa ^ pRight.poa ) & ~ignore.poa); ret += util::popcount(( pLeft.moa ^ pRight.moa ) & ~ignore.moa); return ret; } return std::numeric_limits<int>::max(); } }
30.898551
95
0.583959
utkucandogan
5c5b199d7a305e11547eae8647633d9fb5de9575
463
cpp
C++
query/scorer/BM25.cpp
Da-Huang/Search-Engine
5f1faed6c49adb7f3cc2199c33dbe6bc7094c932
[ "Apache-2.0" ]
1
2015-02-07T13:11:43.000Z
2015-02-07T13:11:43.000Z
query/scorer/BM25.cpp
Da-Huang/Search-Engine
5f1faed6c49adb7f3cc2199c33dbe6bc7094c932
[ "Apache-2.0" ]
1
2015-04-14T05:04:19.000Z
2015-04-14T05:04:19.000Z
query/scorer/BM25.cpp
Da-Huang/Search-Engine
5f1faed6c49adb7f3cc2199c33dbe6bc7094c932
[ "Apache-2.0" ]
null
null
null
#include <cmath> #include <BM25.h> double BM25::R(size_t tf, size_t dl, double avgdl) { const double K = k1 * (1 - b + b * dl / avgdl); return tf * (k1 + 1) / (tf + K); } double BM25::idf(size_t df, size_t DOC_NUM) { return log(1 + (DOC_NUM - df + double(0.5)) / (df + double(0.5)) ); return 0; } double BM25::score(size_t df, size_t DOC_NUM, size_t tf, size_t dl, double avgdl) { // return tf; return idf(df, DOC_NUM) * R(tf, dl, avgdl); }
18.52
52
0.598272
Da-Huang
5c5badcb17dbd63a5d0181212eb0d66937270cf8
1,468
cpp
C++
src/xrGame/static_cast_checked_test.cpp
acidicMercury8/xray-1.6
52fba7348a93a52ff9694f2c9dd40c0d090e791e
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
src/xrGame/static_cast_checked_test.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/xrGame/static_cast_checked_test.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2020-05-17T10:01:14.000Z
2020-09-11T20:17:27.000Z
//////////////////////////////////////////////////////////////////////////// // Module : static_cast_checked.cpp // Created : 04.12.2007 // Modified : 04.12.2007 // Author : Dmitriy Iassenev // Description : checked static_cast implementation for debug purposes //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "static_cast_checked.hpp" // non-polymorphic test struct A {}; struct B : A {}; A a; B* b0 = static_cast_checked<B*> (&a); B& b1 = static_cast_checked<B&> (a); B const * b2 = static_cast_checked<B const *> (&a); B const & b3 = static_cast_checked<B const &> (a); B const * b4 = static_cast_checked<B const *> ((A const *)&a); B const & b5 = static_cast_checked<B const &> ((A const &)a); // the next 2 lines won't compile B* b6 = static_cast_checked<B*> ((A const *)&a); B& b7 = static_cast_checked<B&> ((A const &)a); // polymorphic test struct C {virtual ~C() {}}; struct D : C {}; C c; D* d0 = static_cast_checked<D*> (&c); D& d1 = static_cast_checked<D&> (c); D const * d2 = static_cast_checked<D const *> (&c); D const & d3 = static_cast_checked<D const &> (c); D const * d4 = static_cast_checked<D const *> ((C const *)&c); D const & d5 = static_cast_checked<D const &> ((C const &)c); // the next 2 lines won't compile D* d6 = static_cast_checked<D*> ((C const *)&c); D& d7 = static_cast_checked<D&> ((C const &)c);
36.7
77
0.55654
acidicMercury8
5c635061262edc0077c26515342ef1dc851a84a7
1,107
cc
C++
src/Basevector.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
48
2016-04-26T16:52:59.000Z
2022-01-15T09:18:17.000Z
src/Basevector.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
45
2016-04-27T08:20:56.000Z
2022-02-14T07:47:11.000Z
src/Basevector.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
15
2016-05-11T14:35:25.000Z
2022-01-15T09:18:45.000Z
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2010) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// /* * \file Basevector.cc * \author tsharpe * \date Sep 23, 2009 * * \brief */ #include "Basevector.h" void ReverseComplement( vecbasevector& vbv ) { vecbvec::iterator end(vbv.end()); for ( vecbvec::iterator itr(vbv.begin()); itr != end; ++itr ) itr->ReverseComplement(); } #include "feudal/OuterVecDefs.h" template class OuterVec<BaseVec>; template class OuterVec<BaseVec,BaseVec::allocator_type>; template class OuterVec< OuterVec<BaseVec,BaseVec::allocator_type>, MempoolOwner<unsigned char> >;
36.9
79
0.558266
Amjadhpc
5c6eb51173b7bcba9c2dc0f5e1c0eecb427b4e23
669
cpp
C++
linear-list/array/rotate_image.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
1
2015-07-15T07:31:42.000Z
2015-07-15T07:31:42.000Z
linear-list/array/rotate_image.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
linear-list/array/rotate_image.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; /** * You are given an n × n 2D matrix representing an image. * Rotate the image by 90 degrees (clockwise). * Follow up: Could you do this in-place? * */ class Solution { public: void rotate(vector<vector<int> >& matrix) { int n = matrix.size(); //副对角线翻转 for(int i = 0; i < n; i++) { for(int j = 0; j < n - i; j++) swap(matrix[i][j], matrix[n - j - 1][n - i - 1]); } //中线翻转 for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) swap(matrix[i][j], matrix[n - i - 1][j]); } } };
22.3
65
0.472347
zhangxin23
5c6f1120a7cf503ef4a941153cc48524469e94be
2,424
hpp
C++
src/application/app_alphapose/alpha_pose.hpp
hito0512/tensorRT_Pro
d577fbab615a3d84cb50824d2418655659fd61af
[ "MIT" ]
537
2021-10-03T10:51:49.000Z
2022-03-31T10:07:05.000Z
src/application/app_alphapose/alpha_pose.hpp
hito0512/tensorRT_Pro
d577fbab615a3d84cb50824d2418655659fd61af
[ "MIT" ]
52
2021-10-04T09:05:35.000Z
2022-03-31T07:35:22.000Z
src/application/app_alphapose/alpha_pose.hpp
hito0512/tensorRT_Pro
d577fbab615a3d84cb50824d2418655659fd61af
[ "MIT" ]
146
2021-10-11T00:46:19.000Z
2022-03-31T02:19:37.000Z
#ifndef ALPHA_POSE_HPP #define ALPHA_POSE_HPP #include <vector> #include <memory> #include <string> #include <future> #include <opencv2/opencv.hpp> /* # change AlphaPose-master/configs/halpe_136/resnet/256x192_res50_lr1e-3_2x-regression.yaml CONV_DIM : 256 -> CONV_DIM : 128 import torch import yaml from easydict import EasyDict as edict from alphapose.models import builder class Alphapose(torch.nn.Module): def __init__(self): super().__init__() config_file = "configs/halpe_136/resnet/256x192_res50_lr1e-3_2x-regression.yaml" check_point = "pretrained_models/multi_domain_fast50_regression_256x192.pth" with open(config_file, "r") as f: config = edict(yaml.load(f, Loader=yaml.FullLoader)) self.pose_model = builder.build_sppe(config.MODEL, preset_cfg=config.DATA_PRESET) self.pose_model.load_state_dict(torch.load(check_point, map_location="cpu")) def forward(self, x): hm = self.pose_model(x) # postprocess stride = int(x.size(2) / hm.size(2)) b, c, h, w = map(int, hm.size()) prob = hm.sigmoid() confidence, _ = prob.view(-1, c, h * w).max(dim=2, keepdim=True) prob = prob / prob.sum(dim=[2, 3], keepdim=True) coordx = torch.arange(w, device=prob.device, dtype=torch.float32) coordy = torch.arange(h, device=prob.device, dtype=torch.float32) hmx = (prob.sum(dim=2) * coordx).sum(dim=2, keepdim=True) * stride hmy = (prob.sum(dim=3) * coordy).sum(dim=2, keepdim=True) * stride return torch.cat([hmx, hmy, confidence], dim=2) model = Alphapose().eval() dummy = torch.zeros(1, 3, 256, 192) torch.onnx.export( model, (dummy,), "alpha-pose-136.onnx", input_names=["images"], output_names=["keypoints"], opset_version=11, dynamic_axes={ "images": {0: "batch"}, "keypoints": {0: "batch"} } ) */ // based on https://github.com/MVIG-SJTU/AlphaPose v0.5.0 version namespace AlphaPose{ using namespace std; using namespace cv; typedef tuple<Mat, Rect> Input; class Infer{ public: virtual shared_future<vector<Point3f>> commit(const Input& input) = 0; virtual vector<shared_future<vector<Point3f>>> commits(const vector<Input>& inputs) = 0; }; shared_ptr<Infer> create_infer(const string& engine_file, int gpuid); }; // namespace AlphaPose #endif // ALPHA_POSE_HPP
31.480519
96
0.665429
hito0512
5c7264079ac15c2c01c4c6c91a060c8fe48eae33
1,235
hpp
C++
includes/MIP_constants.hpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
5
2021-12-04T04:42:32.000Z
2022-01-21T13:23:47.000Z
includes/MIP_constants.hpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
null
null
null
includes/MIP_constants.hpp
xmuriqui/muriqui
ff1492c70e297077c9450ef9175e5a80c6627140
[ "MIT" ]
null
null
null
#ifndef MIP_CONSTANTS_HPP #define MIP_CONSTANTS_HPP #include "MIP_config.hpp" namespace minlpproblem { enum MIP_RETURN_CODE { MIP_SUCESS = 0, MIP_BAD_DEFINITIONS = -1, MIP_BAD_VALUE = -2, MIP_INDEX_FAULT = -3, MIP_MEMORY_ERROR = -4, MIP_REPETEAD_INDEXES = -5, MIP_UPPER_TRIANGLE_INDEX = -6, MIP_UNDEFINED_ERROR = -7, MIP_CALLBACK_FUNCTION_ERROR = -8, MIP_LIBRARY_NOT_AVAILABLE = -9, MIP_INFEASIBILITY = -10, MIP_NOT_APPLICABLE = -11, MIP_FAILURE = -12, MIP_RETURN_CODE_BEGIN = MIP_FAILURE, MIP_RETURN_CODE_END = MIP_SUCESS }; enum MIP_VARTYPE { MIP_VT_CONTINUOUS = 201, MIP_VT_INTEGER = 202, MIP_VT_CONTINGER = 203, //special kind of variable to internal use //MIP_VT_BINARY = 204 MIP_VARTYPE_BEGIN = 201, MIP_VARTYPE_END = 203 }; enum MIP_PROBLEMTYPE { MIP_PT_LP = 140, MIP_PT_MILP, MIP_PT_QP, MIP_PT_MIQP, MIP_PT_QCP, MIP_PT_MIQCP, MIP_PT_NLP, MIP_PT_MINLP }; } #endif
19.603175
74
0.556275
xmuriqui
5c733a75519d2dc0a81ecbc857e533c588476f43
1,775
hpp
C++
fastdecoder/src/decoder.hpp
tuxzz/lightvideo
3654d7a452ec42a7e2d40129ef571375e5f93ddb
[ "MIT" ]
2
2019-05-05T22:37:19.000Z
2021-05-17T03:32:44.000Z
fastdecoder/src/decoder.hpp
tuxzz/lightvideo
3654d7a452ec42a7e2d40129ef571375e5f93ddb
[ "MIT" ]
null
null
null
fastdecoder/src/decoder.hpp
tuxzz/lightvideo
3654d7a452ec42a7e2d40129ef571375e5f93ddb
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <cstdint> #include "struct.hpp" #include "imagechannel.hpp" #include "colorformat.hpp" namespace LightVideoDecoder { class DecoderPrivate; class Decoder final { public: typedef std::function<void(char*, int64_t)> ReadFunc; typedef std::function<void(int64_t)> SeekFunc; typedef std::function<void()> PosFunc; Decoder(ReadFunc readFunc, SeekFunc seekFunc, PosFunc posFunc); ~Decoder(); /* property getter */ uint32_t width() const; uint32_t height() const; uint32_t framerate() const; uint32_t frameCount() const; ColorFormat colorFormat() const; uint8_t formatVersion() const; double duration() const; uint32_t channelCount() const; /* method */ void seekFrame(uint32_t pos); void nextFrame(); void decodeCurrentFrame(); /* status getter */ uint32_t currentFrameNumber() const; bool isCurrentFrameDecoded() const; uint32_t getCurrentFrameFS() const; uint32_t getCurrentFrameHS() const; private: /* func */ void loadPacket(); void loadFrame(); ReadFunc m_read; SeekFunc m_seek; PosFunc m_pos; /* info */ MainStruct m_mainStruct; ColorFormatInfo m_colorFormatInfo; /* status */ VideoFramePacket m_currentPacket; VideoFrameStruct m_currentFrameStruct; uint32_t m_currentFrameNumber, m_prevFullFrameNumber; bool m_packetLoaded, m_frameLoaded, m_currentFrameDecoded; /* buffer */ char *m_compressedDataBuffer, *m_uncompressedDataBuffer, *m_frameDataBuffer; uint32_t m_uncompressedDataBufferPos; /* private */ DecoderPrivate *m_dptr; }; } // namespace LightVideoDecoder
25
81
0.673803
tuxzz
f075d689497d0edced6ad946289a5a859d3fb327
9,364
cpp
C++
modules/ide_old/src/NewFilePage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/NewFilePage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/NewFilePage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
#include "NewFilePage_1.h" NewFilePage_1::NewFilePage_1(QWidget* parent) : QWidget(parent) { titlePtr = new QLabel("<b>Select file type</b>"); langStrPtr = new QString("null"); fileTypeStrPtr = new QString("null"); langsStrLstPtr = new QVector<QListWidgetItem*>(); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile2.png"/*"cFile.png"*/), "C") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cppFile2.png"), "C++") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "pyFile.jpg"), "Python") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "javaFile.png"), "Java") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "lispFile.jpg"), "Lisp") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "shellFile.png"), "Shell Script") ); langsStrLstPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "file.png"), "Other") ); cFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); cFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Header file") ); cFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Source file") ); cppFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); cppFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Header file") ); cppFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Source file") ); pythonFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); pythonFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Header file") ); pythonFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Dynamic Reconfiguration") ); javaFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); javaFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Class file") ); javaFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Interface file") ); lispFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); lispFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Source file") ); shellFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); shellFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "BASH file") ); shellFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Bourne file") ); shellFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "C Shell file") ); shellFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Korn file") ); shellFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Z Shell file") ); otherFileOptLstWidPtrVecPtr = new QVector<QListWidgetItem*>(); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "msg file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "srv file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "css file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "xml file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "json file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "yaml file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "sql file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "CMakeLists file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "package file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "Markdown file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "text file") ); otherFileOptLstWidPtrVecPtr->push_back(new QListWidgetItem(QIcon(RosEnv::imagesInstallLoc + "cFile.png"), "empty file") ); langsLwPtr = new QListWidget(); //langsLwPtr->addItems(*langsStrLstPtr); for(size_t i = 0; i < langsStrLstPtr->size(); i++) { langsLwPtr->addItem(langsStrLstPtr->at(i) ); } //langsLwPtr->item(0)->setSelected(true); connect(langsLwPtr, SIGNAL(itemSelectionChanged()), this, SLOT(handleSwapOptionsSlot())); fileTypeStrLstPtrVec = new QVector<QVector<QListWidgetItem*>*>(); fileTypeStrLstPtrVec->push_back(cFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(cppFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(pythonFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(javaFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(lispFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(shellFileOptLstWidPtrVecPtr); fileTypeStrLstPtrVec->push_back(otherFileOptLstWidPtrVecPtr); fileTypeLwPtr = new QListWidget(); //fileTypeLwPtr->addItems(*(fileTypeStrLstPtrVec.at(0)) ); // default for(size_t i = 0; i < fileTypeStrLstPtrVec->at(0)->size(); i++) { fileTypeLwPtr->addItem(new QListWidgetItem(*fileTypeStrLstPtrVec->at(0)->at(i)) ); // default } outerLayoutPtr = new QGridLayout(); outerLayoutPtr->addWidget(titlePtr, 0, 0, 1, 2, Qt::AlignHCenter); outerLayoutPtr->addWidget(langsLwPtr, 1, 0); outerLayoutPtr->addWidget(fileTypeLwPtr, 1, 1); this->setLayout(outerLayoutPtr); } void NewFilePage_1::handleSwapOptionsSlot() { fileTypeLwPtr->clear(); // Remove old items (actually, it deletes them totally--not just form the UI) for(size_t i = 0; i < fileTypeStrLstPtrVec->at(langsLwPtr->currentRow())->size(); i++) { fileTypeLwPtr->addItem(new QListWidgetItem(*fileTypeStrLstPtrVec->at(langsLwPtr->currentRow())->at(i)) ); } } void NewFilePage_1::setLangStrPtr() { if(langsLwPtr->selectedItems().size() != 0) { langStrPtr = new QString(langsLwPtr->currentItem()->text() ); } else { cerr << "Invalid input at NewFilePage_1::setLangStrPtr()" << endl; } } QString* NewFilePage_1::getLangStrPtr() { return langStrPtr; } void NewFilePage_1::setFileTypeStrPtr() { if(fileTypeLwPtr->selectedItems().size() != 0) { fileTypeStrPtr = new QString(fileTypeLwPtr->currentItem()->text() ); } else { cerr << "Invalid input at NewFilePage_1::setFileTypeStrPtr()" << endl; } } QString* NewFilePage_1::getFileTypeStrPtr() { return fileTypeStrPtr; } void NewFilePage_1::triggerMutators() { setLangStrPtr(); setFileTypeStrPtr(); } QString* NewFilePage_1::toString() { QString* tmp = new QString("Language: "); tmp->append(getLangStrPtr() ); tmp->append("\nFile Type: "); tmp->append(getFileTypeStrPtr() ); return tmp; } NewFilePage_1::~NewFilePage_1() { ; }
48.020513
120
0.601773
DeepBlue14
f076c6fbd27720f0b643179527a8641a414e65d0
7,733
hpp
C++
src/truetouch.hpp
TrueTouch/truetouch-firmware
ae6f435613a557c111d4f4eed6d548280a7c5702
[ "MIT" ]
null
null
null
src/truetouch.hpp
TrueTouch/truetouch-firmware
ae6f435613a557c111d4f4eed6d548280a7c5702
[ "MIT" ]
null
null
null
src/truetouch.hpp
TrueTouch/truetouch-firmware
ae6f435613a557c111d4f4eed6d548280a7c5702
[ "MIT" ]
null
null
null
/** * truetouch.hpp - a simple protocol written on top of a BLE UART for controlling pins on * the TrueTouch device. * * Copyright (c) 2021 TrueTouch * Distributed under the MIT license (see LICENSE or https://opensource.org/licenses/MIT) */ #pragma once #include "nordic_ble.hpp" #include "boards_inc.h" #include <app_error.h> #include <app_timer.h> #include <cstdint> #include <climits> #include <cstddef> #include <cstring> #ifndef TRUETOUCH_PULSE_PARALLEL # warning "TRUETOUCH_PULSE_PARALLEL not defined - defaulting to false" #define TRUETOUCH_PULSE_PARALLEL false #endif class TrueTouch { public: //////////////////////////////////////////////////////////////////////////////////////////////////// // Public Types //////////////////////////////////////////////////////////////////////////////////////////////////// /** The type constituting a bitset. */ using Bitset = std::uint32_t; /** Types of commands. */ enum class Command : std::uint8_t { SOLENOID_WRITE = 0x01, /*!< Digital write to the given fingers' solenoids. */ SOLENOID_PULSE = 0x02, /*!< Pulse given fingers' solenoids for so many ms. */ ERM_SET = 0x03, /*!< Set PWM on given fingers' ERM motors. */ }; /** Fingers the TrueTouch device is connected to. */ enum class Finger : std::uint8_t { THUMB = 0, INDEX = 1, MIDDLE = 2, RING = 3, PINKY = 4, PALM = 5, }; /** Solenoid write options. */ enum class GpioOutput : std::uint8_t { OUT_LOW = 0, OUT_HIGH = 1 }; /** Solenoid write parameters. */ struct __attribute__((packed)) SolenoidWrite { Command command; Bitset finger_bitset; // n-th bit set configures n-th finger in the Finger enum GpioOutput output; }; /** Solenoid pulse parameters. */ struct __attribute__((packed)) SolenoidPulse { Command command; Bitset finger_bitset; // n-th bit set configures n-th finger in the Finger enum std::uint32_t duration_ms; // duration of pulse per gpio in ms }; /** ERM set parameters. */ struct __attribute__((packed)) ErmSet { Command command; Bitset finger_bitset; // n-th bit set configures n-th finger in the Finger enum std::uint8_t intensity; // 0-255 }; //////////////////////////////////////////////////////////////////////////////////////////////////// // Public Constants //////////////////////////////////////////////////////////////////////////////////////////////////// /** Size of the UART buffer. */ static constexpr std::size_t BUFFER_SIZE { 256 }; /** Max number of bits in a bitset. */ static constexpr std::size_t BITSET_BIT_COUNT { sizeof(Bitset) * CHAR_BIT }; /** Number of solenoids in the system. */ static constexpr std::size_t SOLENOID_COUNT { 5 }; /** Mask of possible solenoid bits in a bitset. */ static constexpr std::uint32_t SOLENOID_MASK { (1UL << SOLENOID_COUNT) - 1 }; /** Number of ERM motors in the system. */ static constexpr std::size_t ERM_COUNT { 6 }; /** Mask of possible ERM motor bits in a bitset. */ static constexpr std::uint32_t ERM_MASK { (1UL << ERM_COUNT) - 1 }; public: //////////////////////////////////////////////////////////////////////////////////////////////////// // Public Functions //////////////////////////////////////////////////////////////////////////////////////////////////// /** * Initializes hardware used for TrueTouch. BLE should be initialized before this is called. */ TrueTouch(); virtual ~TrueTouch(); /** Services any pending data read by this device. */ void service(); /** Util - returns the nRF pin corresponding to the given finger's solenoid. * Returns -1 for the palm. */ static int finger_to_solenoid_pin(Finger finger); static int finger_to_solenoid_pin(int finger) { APP_ERROR_CHECK_BOOL(finger < SOLENOID_COUNT); return finger_to_solenoid_pin(static_cast<Finger>(finger)); } /** Util - returns the nRF pin corresponding to the given finger's ERM motor. */ static int finger_to_erm_pin(Finger finger); static int finger_to_erm_pin(int finger) { APP_ERROR_CHECK_BOOL(finger < ERM_COUNT); return finger_to_erm_pin(static_cast<Finger>(finger)); } private: //////////////////////////////////////////////////////////////////////////////////////////////////// // Internal Constants //////////////////////////////////////////////////////////////////////////////////////////////////// /** The value used when there's no current pulse bit. */ static constexpr std::uint32_t NO_ACTIVE_BIT = static_cast<std::uint32_t>(-1); //////////////////////////////////////////////////////////////////////////////////////////////////// // Internal Data //////////////////////////////////////////////////////////////////////////////////////////////////// /** Buffer used to read data recieved from BLE UART. */ std::uint8_t _buffer[BUFFER_SIZE]; volatile std::size_t _buffer_cnt; /** An app timer control block and instance pointer. * NOTE: this is defined without the macro so that it can be per class instance. This could * introduce issues in later SDK versions, keep an eye on changes. */ app_timer_t _timer_cb = { .active = false, }; const app_timer_id_t _timer = &_timer_cb; /** Bitset of pins to be pulsed. */ Bitset _pulse_pin_bitset; /** Duration of each pulse in ms. */ std::uint32_t _pulse_dur_ms; /** Currently active bit being pulsed (used for sequential pulsing config). */ std::uint32_t _current_pulse_bit; //////////////////////////////////////////////////////////////////////////////////////////////////// // Internal Functions //////////////////////////////////////////////////////////////////////////////////////////////////// /** Functions to handle commands */ void handle_solenoid_write(); void handle_solenoid_pulse(); void handle_solenoid_pulse_sequential(); void handle_solenoid_pulse_parallel(); void handle_erm_set(); /* Sends an ACK for debugging/benchmarking purposes. Sends the given * message to the other side. */ #ifdef BENCHMARK_TIMING void ack(std::uint8_t *bytes, std::uint16_t len); #endif /** Copy bytes from the BLE UART byte buffer into the type T */ template <typename T> T parse_bytes() { if (_buffer_cnt < sizeof(T)) { /* Uh-oh... */ APP_ERROR_HANDLER(0); } else { /* Grab the structure from the byte buffer. */ T ret; std::memcpy(&ret, _buffer, sizeof(T)); /* Done with these bytes, "erase" them. */ std::size_t remaining = _buffer_cnt - sizeof(T); std::memmove(&_buffer[0], &_buffer[sizeof(T)], remaining); _buffer_cnt -= sizeof(T); return ret; } // subdue the return type warning (APP_ERROR_HANDLER will not return) return T{}; } /** Callback to handle incoming UART data. */ static void ble_uart_callback(void *context, const std::uint8_t *data, std::uint16_t length); /** Callback called when the timer expires. */ static void timer_timeout_callback(void *context); /** Delegate callbacks depending on configuration. */ void timer_timeout_callback_parallel(); void timer_timeout_callback_sequential(); };
36.305164
101
0.528126
TrueTouch
f0790e6b4e55e8359c355ec19eabd6c8196c18f0
641
hpp
C++
include/locic/Parser/TemplateParser.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
include/locic/Parser/TemplateParser.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
include/locic/Parser/TemplateParser.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#ifndef LOCIC_PARSER_TEMPLATEPARSER_HPP #define LOCIC_PARSER_TEMPLATEPARSER_HPP #include <locic/AST.hpp> #include <locic/Parser/TemplateBuilder.hpp> namespace locic { namespace Debug { class SourcePosition; } namespace Parser { class TemplateInfo; class TokenReader; class TemplateParser { public: TemplateParser(TokenReader& reader); ~TemplateParser(); TemplateInfo parseTemplate(); AST::Node<AST::TemplateVarList> parseTemplateVarList(); AST::Node<AST::TemplateVar> parseTemplateVar(); private: TokenReader& reader_; TemplateBuilder builder_; }; } } #endif
15.634146
58
0.706708
scross99
f07a3778e625992cd5ef4cf609abb57f28e9fbda
2,108
cc
C++
Trie/trie.cc
zhanMingming/DataStruct
7e0c665f02d49919e3df2f08f7a5945300ebd8f1
[ "MIT" ]
1
2019-11-23T15:41:58.000Z
2019-11-23T15:41:58.000Z
Trie/trie.cc
zhanMingming/DataStruct
7e0c665f02d49919e3df2f08f7a5945300ebd8f1
[ "MIT" ]
null
null
null
Trie/trie.cc
zhanMingming/DataStruct
7e0c665f02d49919e3df2f08f7a5945300ebd8f1
[ "MIT" ]
null
null
null
#include"trie.h" #include<cstring> #include<iostream> Trie::Trie() :root(NULL) {} Trie::Trie_node::Trie_node() { data=NULL; for(int index=0;index <Num_chars;++index) { num_char[index]=NULL; } } Trie::~Trie() { } int Trie::insert(const char *word,const char *number) { if(word==NULL||number==NULL) { std::cout << "insert error" << std::endl; return 0; } if(strlen(number) > 11) { std::cout << "the number is overlength" << std::endl; return 0; } if(root==NULL) { root=new Trie_node; } Trie_node *location=root; char char_code; while(location != NULL && *word !=0) { if(*word >='A'&& *word <='Z') { char_code=*word-'A'; }else if(*word>='a'&& *word<='z') { char_code=*word-'a'; }else { return 0; } if(location->num_char[char_code]==NULL) { location->num_char[char_code]=new Trie_node; } location=location->num_char[char_code]; ++word; } location->data=new char[strlen(number)]; strcpy(location->data,number); return 1; } int Trie::search(const char *word,char *number) { if(word == NULL) { return 0; } char char_code; Trie_node *location=root; while(location != NULL && *word !=0) { if(*word >='A' && *word <='Z') { char_code=*word-'A'; }else if(*word>='a'&& *word<='z') { char_code=*word-'a'; }else { return 0; } if(location->num_char[char_code]==NULL) { return 0; } location=location->num_char[char_code]; ++word; } if(location != NULL && location->data != NULL) { strcpy(number,location->data); return 1; }else { return 0; } }
15.275362
62
0.4426
zhanMingming
f07ab6bc91c3f089f5643326b052f12ad6bc2a34
1,109
cpp
C++
Training (Lopatin)/B.cpp
michaelarakel/local-trainings-and-upsolvings
7ec663fd80e6a9f7c9ffa37bd97b5197f1e4a73c
[ "Unlicense" ]
null
null
null
Training (Lopatin)/B.cpp
michaelarakel/local-trainings-and-upsolvings
7ec663fd80e6a9f7c9ffa37bd97b5197f1e4a73c
[ "Unlicense" ]
null
null
null
Training (Lopatin)/B.cpp
michaelarakel/local-trainings-and-upsolvings
7ec663fd80e6a9f7c9ffa37bd97b5197f1e4a73c
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <cstdio> using namespace std; vector <vector <int> > g; vector <char> used; vector <int> matching; bool augment_path(int v) { if (used[v]) return false; used[v] = true; for (int i = 0; i < g[v].size(); ++i) { int node = g[v][i]; if (matching[node] == -1 || augment_path(node)) { matching[node] = v; return true; } } return false; } int main() { //freopen("pairs.in", "r", stdin); //freopen("pairs.out", "w", stdout); int n, m; cin >> n >> m; g.resize(n); for (int i = 0; i < n; ++i) { int num; while (cin >> num) { if (num == 0) break; g[i].push_back(num - 1); } } used = vector <char>(n, false); matching = vector <int>(m, -1); int count = 0; for (int i = 0; i < n; ++i) { used.assign(n, false); augment_path(i); } for (int i = 0; i < m; ++i) if (matching[i] != -1) ++count; cout << count << endl; for (int i = 0; i < matching.size(); ++i) if (matching[i] != -1) cout << matching[i] + 1 << ' ' << i + 1 << endl; }
16.552239
52
0.493237
michaelarakel
f07d5fa8601a4812b6405afea95482e972db512c
8,092
cpp
C++
ee450/lab1/main.cpp
chenying-wang/usc-ee-coursework-public
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
[ "MIT" ]
1
2021-03-24T10:46:20.000Z
2021-03-24T10:46:20.000Z
ee450/lab1/main.cpp
chenying-wang/usc-ee-coursework-public
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
[ "MIT" ]
null
null
null
ee450/lab1/main.cpp
chenying-wang/usc-ee-coursework-public
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
[ "MIT" ]
1
2021-03-25T09:18:45.000Z
2021-03-25T09:18:45.000Z
#include <iostream> #include <fstream> #include <vector> #include <deque> #include <unordered_map> #include <unordered_set> #include <iterator> #include <sstream> #include <string> #include <limits> #ifdef __TIME_STAT #include <chrono> #endif #define SUCCESS 0 #define ERROR -1 #define MAX(T) std::numeric_limits<T>::max() #define OUTPUT_FILE "./result.txt" #ifndef __EE450_GRAPH #define __EE450_GRAPH template<typename T> class Graph { private: const uint64_t m_size; std::vector<std::string> m_vertices; std::unordered_map<std::string, uint64_t> m_vertexMapping; std::vector<std::vector<T>> m_matrix; uint64_t m_idx; const uint64_t getVertexIdx(const std::string v) const; const uint64_t getOrInsertVertexIdx(const std::string v); public: Graph(const uint64_t size); virtual ~Graph(); Graph<T> *addEdge(const std::string s, const std::string t, T distance); Graph<T> *addUndirectedEdge(const std::string v1, const std::string v2, T distance); std::unordered_map<uint64_t, uint64_t> calculateDistances(const std::string s, const std::string t) const; uint64_t getSize() const { return this->m_size; } }; #endif template<typename T> Graph<T>::Graph(const uint64_t size) : m_size(size), m_vertices(std::vector<std::string>(size)), m_vertexMapping(std::unordered_map<std::string, uint64_t>(size)), m_matrix(std::vector<std::vector<T>>(size)), m_idx(0UL) { for (auto i = 0UL; i < this->m_size; ++i) { this->m_matrix[i] = std::vector<uint8_t>(this->m_size, MAX(T)); this->m_matrix[i][i] = 0UL; } } template<typename T> Graph<T>::~Graph() { this->m_vertices.clear(); this->m_vertexMapping.clear(); for (auto v : this->m_matrix) { v.clear(); } this->m_matrix.clear(); } template<typename T> Graph<T> *Graph<T>::addEdge(const std::string s, const std::string t, T distance) { const auto sIdx = this->getOrInsertVertexIdx(s); const auto tIdx = this->getOrInsertVertexIdx(t); if (sIdx >= this->m_size || tIdx >= this->m_size) { std::cerr << "Failed to add edge from " << s << " to " << t << '\n'; return this; } this->m_matrix[sIdx][tIdx] = distance; return this; } template<typename T> Graph<T> *Graph<T>::addUndirectedEdge(const std::string v1, const std::string v2, T distance) { const auto v1Idx = this->getOrInsertVertexIdx(v1); const auto v2Idx = this->getOrInsertVertexIdx(v2); if (v1Idx >= this->m_size || v2Idx >= this->m_size) { std::cerr << "Failed to add edge between " << v1 << " and " << v2 << '\n'; return this; } this->m_matrix[v1Idx][v2Idx] = distance; this->m_matrix[v2Idx][v1Idx] = distance; return this; } template<typename T> std::unordered_map<uint64_t, uint64_t> Graph<T>::calculateDistances(const std::string s, const std::string t) const { const auto sIdx = this->getVertexIdx(s); const auto tIdx = this->getVertexIdx(t); if (sIdx >= this->m_size || tIdx >= this->m_size) { return std::unordered_map<uint64_t, uint64_t>(); } else if (s == t) { return std::unordered_map<uint64_t, uint64_t>({{0, 1}}); } const auto size = this->m_vertices.size(); auto currentPath = new std::unordered_map<uint64_t, std::deque<std::unordered_set<uint64_t>>>(); auto nextPath = new std::unordered_map<uint64_t, std::deque<std::unordered_set<uint64_t>>>(); auto results = std::unordered_map<uint64_t, uint64_t>(size); nextPath->insert(std::make_pair(sIdx, std::deque<std::unordered_set<uint64_t>>())); nextPath->at(sIdx).push_back(std::unordered_set<uint64_t>({sIdx})); for (auto distance = 1UL; distance < size; ++distance) { std::swap(currentPath, nextPath); for (auto it = currentPath->cbegin(); it != currentPath->cend(); ++it) { const auto i = it->first; for (auto j = 0UL; j < size; ++j) { if (this->m_matrix[i][j] == MAX(T) || i == j) { continue; } else if (j == tIdx) { if (results.count(distance)) { results.at(distance) += it->second.size(); } else { results.insert(std::make_pair(distance, it->second.size())); } continue; } for (const auto path : it->second) { if (path.count(j)) { continue; } auto copyPath = path; copyPath.insert(j); if (!nextPath->count(j)) { nextPath->insert(std::make_pair(j, std::deque<std::unordered_set<uint64_t>>())); } nextPath->at(j).push_back(copyPath); } } } if (nextPath->empty()) { break; } for (auto it = currentPath->begin(); it != currentPath->end(); ++it) { for (auto path : it->second) { path.clear(); } it->second.clear(); } currentPath->clear(); } for (auto it = currentPath->begin(); it != currentPath->end(); ++it) { for (auto path : it->second) { path.clear(); } it->second.clear(); } currentPath->clear(); delete currentPath; for (auto it = nextPath->begin(); it != nextPath->end(); ++it) { for (auto path : it->second) { path.clear(); } it->second.clear(); } nextPath->clear(); delete nextPath; if (results.empty()) { return std::unordered_map<uint64_t, uint64_t>(); } return results; } template<typename T> const uint64_t Graph<T>::getVertexIdx(const std::string v) const { if (this->m_vertexMapping.empty() || !this->m_vertexMapping.count(v)) { return MAX(uint64_t); } return this->m_vertexMapping.at(v); } template<typename T> const uint64_t Graph<T>::getOrInsertVertexIdx(const std::string v) { if (this->m_vertexMapping.count(v)) { return this->m_vertexMapping[v]; } else if (this->m_idx >= this->m_size) { return MAX(uint64_t); } this->m_vertices[this->m_idx] = v; this->m_vertexMapping.insert(std::make_pair(v, this->m_idx)); return this->m_idx++; } Graph<uint8_t> *readGraph(std::istream &in, uint64_t size) { if (!in.good()) { return nullptr; } auto graph = new Graph<uint8_t>(size); std::string line; while (std::getline(in, line)) { if (line.size() < 3) { continue; } std::istringstream iss(line); std::string v1, v2; iss >> v1 >> v2; if (!iss.eof()) { continue; } graph->addUndirectedEdge(v1, v2, 1u); } return graph; } int main(int argc, char *argv[]) { #ifdef __TIME_STAT auto start = std::chrono::system_clock::now(); #endif if (argc < 2) { std::cerr << "Unspecified the input file\n"; return ERROR; } auto fin = std::ifstream(argv[1], std::ios::in); if (!fin.good()) { std::cerr << "Cannot open the input file: " << argv[1] << '\n'; fin.close(); return ERROR; } uint64_t n; std::string line, s, t; fin >> n >> s >> t; auto graph = readGraph(fin, n << 1); fin.close(); auto results = graph->calculateDistances(s, t); auto fout = std::ofstream(OUTPUT_FILE, std::ios::out); for (auto result : results) { if (result.first < 2) { for (auto i = 0UL; i < result.second; ++i) { fout << "0\n"; } continue; } const auto p = std::to_string(result.first - 1) + '\n'; for (auto i = 0UL; i < result.second; ++i) { fout << p; } } fout.close(); #ifdef __TIME_STAT auto elapsed = std::chrono::system_clock::now() - start; std::cerr << "Elapsed time: " << elapsed.count() / 1000000.0 << "ms\n"; #endif return SUCCESS; }
30.651515
117
0.56525
chenying-wang
f07ffc54071b476d8d723231960477f04b4172c9
173
cpp
C++
Serna_Esteban.assignment2.0/Blast.cpp
Este-iv/Space_nvaders
dc3fbe00047584a04b43b8228bbc484dcf6bee50
[ "MIT" ]
null
null
null
Serna_Esteban.assignment2.0/Blast.cpp
Este-iv/Space_nvaders
dc3fbe00047584a04b43b8228bbc484dcf6bee50
[ "MIT" ]
null
null
null
Serna_Esteban.assignment2.0/Blast.cpp
Este-iv/Space_nvaders
dc3fbe00047584a04b43b8228bbc484dcf6bee50
[ "MIT" ]
null
null
null
#include "Blast.h" #include "space.h" Blast::Blast(char s, int d, point p, point v){ source = s; damage = d; position = p; velocity = v; }
15.727273
46
0.514451
Este-iv
f084067ac272b1ed58680e5d4016dae85163a38f
1,833
cc
C++
src/developer/debug/zxdb/client/pretty_frame_glob_unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/developer/debug/zxdb/client/pretty_frame_glob_unittest.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/developer/debug/zxdb/client/pretty_frame_glob_unittest.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// 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/debug/zxdb/client/pretty_frame_glob.h" #include <gtest/gtest.h> #include "src/developer/debug/zxdb/symbols/function.h" #include "src/developer/debug/zxdb/symbols/location.h" namespace zxdb { TEST(PrettyFrameGlob, Matches) { auto func = fxl::MakeRefCounted<Function>(DwarfTag::kSubprogram); func->set_assigned_name("MyFunction"); SymbolContext symbol_context = SymbolContext::ForRelativeAddresses(); // Wildcard matches any location, even unsymbolized. EXPECT_TRUE(PrettyFrameGlob::Wildcard().Matches(Location(Location::State::kAddress, 0x23723))); // File/function exact matches: Location loc(0x1234, FileLine("file.cc", 23), 0, symbol_context, func); EXPECT_TRUE(PrettyFrameGlob::File("file.cc").Matches(loc)); EXPECT_FALSE(PrettyFrameGlob::File("otherfile.cc").Matches(loc)); EXPECT_TRUE(PrettyFrameGlob::Func("MyFunction").Matches(loc)); EXPECT_FALSE(PrettyFrameGlob::Func("OtherFunction").Matches(loc)); // Test a template. This needs to be a new function object because the name will be cached. auto template_func = fxl::MakeRefCounted<Function>(DwarfTag::kSubprogram); template_func->set_assigned_name("MyFunction<int>"); Location template_loc(0x1234, FileLine("file.cc", 23), 0, symbol_context, template_func); // This just tests that the templates and wildcards are hooked up. The globs are covered by the // IdentifierGlob tests. EXPECT_TRUE(PrettyFrameGlob::Func("MyFunction<int>").Matches(template_loc)); EXPECT_FALSE(PrettyFrameGlob::Func("MyFunction<char>").Matches(template_loc)); EXPECT_TRUE(PrettyFrameGlob::Func("MyFunction<*>").Matches(template_loc)); } } // namespace zxdb
41.659091
97
0.762139
allansrc
f086727a8eede7721dfbd3cbf0bde48e01ee9a24
18,983
cpp
C++
src/client/ClientTests.cpp
oakdoor/enterprisediodefiletransfer
64cf04f47fd48fa4723b022968babdd8d62702d3
[ "MIT" ]
1
2021-05-27T09:53:20.000Z
2021-05-27T09:53:20.000Z
src/client/ClientTests.cpp
oakdoor/enterprisediodefiletransfer
64cf04f47fd48fa4723b022968babdd8d62702d3
[ "MIT" ]
null
null
null
src/client/ClientTests.cpp
oakdoor/enterprisediodefiletransfer
64cf04f47fd48fa4723b022968babdd8d62702d3
[ "MIT" ]
1
2021-09-16T14:12:27.000Z
2021-09-16T14:12:27.000Z
// Copyright PA Knowledge Ltd 2021 // MIT License. For licence terms see LICENCE.md file. #include <cstdint> #include <vector> #include <string> #include <future> #include "test/catch.hpp" #include "test/EnterpriseDiodeTestHelpers.hpp" #include "enterprisediode/EnterpriseDiodeHeader.hpp" #include "Client.hpp" #include "Timer.hpp" #include "IngressBufferLevelInterface.hpp" #include "DataSendPeriodController.hpp" #include "PacketGeneratorInterface.hpp" using namespace std::chrono_literals; TEST_CASE("Client. Stream data is sent using the ED client") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream ss("B"); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.size() == 2); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); SECTION("Filename is set") { REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == '{'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 1) == 'n'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 13) == 'r'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 20) == 'd'); } } TEST_CASE("Client. Filename can be set dynamically.") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt, "testFilename")); std::stringstream ss("B"); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.size() == 2); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); SECTION("Filename is set") { REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == '{'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 1) == 'n'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 13) == 't'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 17) == 'F'); } } TEST_CASE("Client. File is sent with appropriate file name if partial file path is provided") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt, "example/testFilename")); std::stringstream ss("B"); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.size() == 2); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); SECTION("Filename is set") { REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == '{'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 1) == 'n'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 13) == 't'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes + 17) == 'F'); } } TEST_CASE("Client. Stream data is sent using the ED client, where maxPayloadSize is larger than data") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 10, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream ss("BA"); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.size() == 2); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); } TEST_CASE("Client. Two packets are sent using ED client when packet length is 1 and data is length 2") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream ss("AB"); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'A'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE_FALSE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } TEST_CASE("Client. Empty frame is sent when there is no source data") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream ss(""); edClient.send(ss); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); } TEST_CASE("Client. Throws exception if given a non-existent stream") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::fstream stream("doesNotExist"); REQUIRE_THROWS_AS(edClient.send(stream), std::runtime_error); } TEST_CASE("Client. For a payload split into two packets, each packet is sent on a timer tick") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); auto timerfake = std::make_shared<ManualTimer>(); Client edClient(udpClientSpy, timerfake, 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream payload("AB"); edClient.send(payload); REQUIRE(udpClientSpy->buffersSent.size() == 1); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(0).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'A'); timerfake->tick(); REQUIRE(udpClientSpy->buffersSent.size() == 2); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE_FALSE(udpClientSpy->buffersSent.at(1).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == 'B'); timerfake->tick(); REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } TEST_CASE("Client. The same packet is sent multiple times when a value is specified in the client's constructor") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); auto timerfake = std::make_shared<ManualTimer>(); SECTION("Payload size of one and maxPayloadSize of 1") { Client edClient(udpClientSpy, timerfake, 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, 2)); std::stringstream payload("A"); edClient.send(payload); for (size_t i : {0u, 1u}) { REQUIRE(udpClientSpy->buffersSent.size() == i + 1); REQUIRE(udpClientSpy->buffersSent.at(i).at(EDHeader::FrameCountIndex) == i + 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(i).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.at(i).at(EDHeader::HeaderSizeInBytes) == 'A'); timerfake->tick(); } REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } SECTION("Payload size greater than one") { Client edClient(udpClientSpy, timerfake, 3, nullptr, createPacketGenerator(DiodeVariant::type::Basic, 2)); std::stringstream payload("ABC"); edClient.send(payload); for (size_t i : {0u, 1u}) { REQUIRE(udpClientSpy->buffersSent.size() == i + 1); REQUIRE(udpClientSpy->buffersSent.at(i).at(EDHeader::FrameCountIndex) == i + 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(i).at(EDHeader::EOFFlagIndex)); auto bufferString = std::string( std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes), std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes + 3)); REQUIRE(bufferString == "ABC"); timerfake->tick(); } REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } SECTION("If the size data to be sent is less than maxPayloadSize, return size of data and " "don't pad payload with zeroes") { Client edClient(udpClientSpy, timerfake, 10, nullptr, createPacketGenerator(DiodeVariant::type::Basic, 2)); std::stringstream payload("ABC"); edClient.send(payload); for (size_t i : {0u, 1u}) { REQUIRE(udpClientSpy->buffersSent.size() == i + 1); REQUIRE(udpClientSpy->buffersSent.at(i).at(EDHeader::FrameCountIndex) == i + 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(i).at(EDHeader::EOFFlagIndex)); auto bufferString = std::string( std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes), std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes + 3)); REQUIRE(bufferString == "ABC"); REQUIRE(udpClientSpy->buffersSent.at(i).size() - EDHeader::HeaderSizeInBytes == 3); timerfake->tick(); } REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } SECTION("If the size data to be sent is greater than maxPayloadSize, return only maxPayloadSize worth of data") { Client edClient(udpClientSpy, timerfake, 2, nullptr, createPacketGenerator(DiodeVariant::type::Basic, 2)); std::stringstream payload("ABC"); edClient.send(payload); for (size_t i : {0u, 1u}) { REQUIRE(udpClientSpy->buffersSent.size() == i + 1); REQUIRE(udpClientSpy->buffersSent.at(i).at(EDHeader::FrameCountIndex) == i + 1); REQUIRE_FALSE(udpClientSpy->buffersSent.at(i).at(EDHeader::EOFFlagIndex)); auto bufferString = std::string( std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes), std::next(udpClientSpy->buffersSent.at(i).cbegin(), EDHeader::HeaderSizeInBytes + 2)); REQUIRE(bufferString == "AB"); REQUIRE(udpClientSpy->buffersSent.at(i).size() - EDHeader::HeaderSizeInBytes == 2); timerfake->tick(); } REQUIRE(udpClientSpy->buffersSent.size() == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); } } TEST_CASE("Client. For a payload split into two packets, each packet is sent after 1 second", "[integration]") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(1000000), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream payload("AB"); edClient.send(payload); BytesBuffer testBytes = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytes.at(EDHeader::HeaderSizeInBytes) = 'A'; testBytes.at(EDHeader::FrameCountIndex) = 1; BytesBuffer testBytesB = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytesB.at(EDHeader::HeaderSizeInBytes) = 'B'; testBytesB.at(EDHeader::FrameCountIndex) = 2; BytesBuffer testBytesEOF = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytesEOF.at(EDHeader::FrameCountIndex) = 3; testBytesEOF.at(EDHeader::EOFFlagIndex) = true; REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'A'); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(1).at(EDHeader::FrameCountIndex) == 2); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::FrameCountIndex) == 3); REQUIRE(udpClientSpy->buffersSent.at(2).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.size() == 3); } TEST_CASE("Client. For a multi-packet payload, with 1500B packet size, packets are sent at 100 Mbps", "[integration]") { std::stringstream payload("ABABAB"); auto udpClientSpy = std::make_shared<UdpClientSpy>(); auto realTimer = std::make_shared<Timer>(calculateTimerPeriod(100, 1500)); Client edClient(udpClientSpy, realTimer, 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); edClient.send(payload); BytesBuffer testBytes = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytes.at(EDHeader::HeaderSizeInBytes) = 'A'; testBytes.at(EDHeader::FrameCountIndex) = 1; BytesBuffer testBytesB = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytesB.at(EDHeader::HeaderSizeInBytes) = 'B'; testBytesB.at(EDHeader::FrameCountIndex) = 6; BytesBuffer testBytesEOF = BytesBuffer(EDHeader::HeaderSizeInBytes + 1); testBytesEOF.at(EDHeader::FrameCountIndex) = 7; testBytesEOF.at(EDHeader::EOFFlagIndex) = true; REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::HeaderSizeInBytes) == 'A'); REQUIRE(udpClientSpy->buffersSent.at(0).at(EDHeader::FrameCountIndex) == 1); REQUIRE(udpClientSpy->buffersSent.at(5).at(EDHeader::HeaderSizeInBytes) == 'B'); REQUIRE(udpClientSpy->buffersSent.at(5).at(EDHeader::FrameCountIndex) == 6); REQUIRE(udpClientSpy->buffersSent.at(6).at(EDHeader::FrameCountIndex) == 7); REQUIRE(udpClientSpy->buffersSent.at(6).at(EDHeader::EOFFlagIndex)); REQUIRE(udpClientSpy->buffersSent.size() == 7); } TEST_CASE("Client. Packets are sent with a random session ID") { auto udpClientSpy = std::make_shared<UdpClientSpy>(); Client edClient( udpClientSpy, std::make_shared<Timer>(0), 1, nullptr, createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)); std::stringstream ss("Hello"); edClient.send(ss); auto lastSessionID = *reinterpret_cast<std::uint32_t*>(&udpClientSpy->latestPacket.at(0)); std::stringstream nextInputStream("Diode"); edClient.send(nextInputStream); REQUIRE(lastSessionID != *reinterpret_cast<std::uint32_t*>(&udpClientSpy->latestPacket.at(0))); } TEST_CASE("Client. When the buffer level is too high, then the client data rate is decreased") { class IngressBufferLevelReporterStub : public IngressBufferLevelInterface { public: [[nodiscard]] std::uint32_t getLevel() const override { return 100; } }; class ManualTimerAndIntervalSpy: public ManualTimer { public: ManualTimerAndIntervalSpy() : capturedInterval{std::chrono::microseconds{10000}} {} [[nodiscard]] std::chrono::microseconds getTickInterval() const override { return capturedInterval.load(); } void setTickInterval(const std::chrono::microseconds& newInterval) override { capturedInterval = newInterval; } std::atomic<std::chrono::microseconds> capturedInterval; }; auto udpClientSpy = std::make_shared<UdpClientSpy>(); auto bufferLevelReporter = std::make_unique<IngressBufferLevelReporterStub>(); auto dataSendTimer = std::make_shared<ManualTimerAndIntervalSpy>(); auto bufferQueryTimer = MakeTestableUniquePtr<ManualTimer>(); const auto initialTickInterval = 1000ms; dataSendTimer->setTickInterval(initialTickInterval); auto client = Client { udpClientSpy, dataSendTimer, 1, std::make_unique<DataSendPeriodController>(10000us, 80.0, bufferQueryTimer.move(), std::move(bufferLevelReporter)), createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)}; std::stringstream payload("AB"); client.send(payload); dataSendTimer->tick(); bufferQueryTimer->tick(); REQUIRE(dataSendTimer->getTickInterval().count() > initialTickInterval.count()); } TEST_CASE("Client. When the buffer level and data rate are below max, then the client data rate is increased") { class IngressBufferLevelReporterStub : public IngressBufferLevelInterface { public: [[nodiscard]] std::uint32_t getLevel() const override { return 70; } }; class ManualTimerAndIntervalSpy: public ManualTimer { public: ManualTimerAndIntervalSpy() : capturedInterval{std::chrono::microseconds{10000}} {} [[nodiscard]] std::chrono::microseconds getTickInterval() const override { return capturedInterval.load(); } void setTickInterval(const std::chrono::microseconds& newInterval) override { capturedInterval = newInterval; } std::atomic<std::chrono::microseconds> capturedInterval; }; auto udpClientSpy = std::make_shared<UdpClientSpy>(); auto bufferLevelReporter = std::make_unique<IngressBufferLevelReporterStub>(); auto timer = std::make_shared<ManualTimerAndIntervalSpy>(); auto bufferQueryTimer = MakeTestableUniquePtr<ManualTimer>(); const auto initialTickInterval = 20000us; auto client = Client { udpClientSpy, timer, 1, std::make_unique<DataSendPeriodController>(10000us, 80.0, bufferQueryTimer.move(), std::move(bufferLevelReporter)), createPacketGenerator(DiodeVariant::type::Basic, std::nullopt)}; timer->setTickInterval(initialTickInterval); std::stringstream payload("AB"); client.send(payload); timer->tick(); bufferQueryTimer->tick(); REQUIRE(timer->getTickInterval().count() < initialTickInterval.count()); }
40.561966
119
0.724069
oakdoor
f08e91e7cdace12b90ee16361d8e87c14dbe37a2
1,890
cpp
C++
puzzles/2020/day03/main.cpp
apathyboy/aoc2020cpp
0e02feca98a11ef530953c1d314f605edbbdea9c
[ "MIT" ]
null
null
null
puzzles/2020/day03/main.cpp
apathyboy/aoc2020cpp
0e02feca98a11ef530953c1d314f605edbbdea9c
[ "MIT" ]
null
null
null
puzzles/2020/day03/main.cpp
apathyboy/aoc2020cpp
0e02feca98a11ef530953c1d314f605edbbdea9c
[ "MIT" ]
null
null
null
#include <fmt/core.h> #include <range/v3/all.hpp> #include <fstream> #include <string> namespace rs = ranges; namespace rv = ranges::views; auto slope_type1_hits(const std::vector<std::string>& input, int slope) { auto hit_test = [slope](auto&& p) { auto&& [depth, line] = p; return (line[(depth * slope) % line.length()] == '#') ? 1 : 0; }; return rs::accumulate(rv::enumerate(input) | rv::transform(hit_test), 0); } auto slope_type2_hits(const std::vector<std::string>& input) { auto hit_test = [](auto&& p) { auto&& [depth, line] = p; return (depth % 2 == 0 && line[(depth / 2) % line.length()] == '#') ? 1 : 0; }; return rs::accumulate(rv::enumerate(input) | rv::transform(hit_test), 0); } int part1(const std::vector<std::string>& input) { return slope_type1_hits(input, 3); } int part2(const std::vector<std::string>& input) { return slope_type1_hits(input, 1) * slope_type1_hits(input, 3) * slope_type1_hits(input, 5) * slope_type1_hits(input, 7) * slope_type2_hits(input); } #ifndef UNIT_TESTING int main() { fmt::print("Advent of Code 2020 - Day 03\n"); std::ifstream ifs{"puzzle.in"}; auto input = rs::getlines(ifs) | rs::to<std::vector>; fmt::print("Part 1 Solution: {}\n", part1(input)); fmt::print("Part 2 Solution: {}\n", part2(input)); return 0; } #else #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <sstream> TEST_CASE("Can solve day 3 problems") { std::stringstream ss; ss << R"(..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#)"; auto input = rs::getlines(ss) | rs::to<std::vector>; SECTION("Can solve part 1 example") { REQUIRE(7 == part1(input)); } SECTION("Can solve part 2 example") { REQUIRE(336 == part2(input)); } } #endif
21.477273
95
0.575132
apathyboy
f091b649d9f9a2c42e5dee8b491dd451c5a55b4e
1,470
hpp
C++
include/HighPerMeshes/dsl/buffers/LocalBuffer.hpp
HighPerMeshes/highpermeshes-dsl
3019cadcc7c2504f3bf55be1d69da2ee66159c07
[ "MIT" ]
3
2020-04-24T11:10:34.000Z
2021-07-07T09:41:08.000Z
include/HighPerMeshes/dsl/buffers/LocalBuffer.hpp
HighPerMeshes/highpermeshes-dsl
3019cadcc7c2504f3bf55be1d69da2ee66159c07
[ "MIT" ]
1
2020-03-09T18:28:24.000Z
2020-03-09T18:28:24.000Z
include/HighPerMeshes/dsl/buffers/LocalBuffer.hpp
HighPerMeshes/highpermeshes-dsl
3019cadcc7c2504f3bf55be1d69da2ee66159c07
[ "MIT" ]
1
2020-04-22T12:49:46.000Z
2020-04-22T12:49:46.000Z
// Copyright (c) 2017-2020 // // Distributed under the MIT Software License // (See accompanying file LICENSE) #ifndef DSL_BUFFERS_LOCALBUFFER_HPP #define DSL_BUFFERS_LOCALBUFFER_HPP #include <cassert> #include <cstdint> #include <type_traits> #include <vector> #include <HighPerMeshes/dsl/data_access/AccessMode.hpp> namespace HPM::internal { // A type that signals an invalid local buffer entry: see 'GetLocalBuffer() in LocalView.hpp'. class InvalidLocalBuffer { }; template <typename GlobalBufferT, AccessMode Mode> class LocalBuffer { protected: using BlockT = typename GlobalBufferT::ValueT; using QualifiedBlockT = std::conditional_t<Mode == AccessMode::Read, const BlockT, BlockT>; GlobalBufferT* global_buffer; const std::size_t global_offset; public: LocalBuffer(GlobalBufferT* global_buffer, std::integral_constant<AccessMode, Mode>, size_t global_offset) : global_buffer(global_buffer), global_offset(global_offset) {} inline auto operator[](const int index) -> QualifiedBlockT& { assert(global_buffer != nullptr); return (*global_buffer)[global_offset + index]; } inline auto operator[](const int index) const -> const QualifiedBlockT& { assert(global_buffer != nullptr); return (*global_buffer)[global_offset + index]; } }; } // namespace HPM::internal #endif
27.735849
177
0.679592
HighPerMeshes
f099c65429d8ff4dfd5e6663bfd4934ebd311e19
571
cpp
C++
Volume110/11029 - Leading and Trailing/11029.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
1
2017-01-25T18:07:49.000Z
2017-01-25T18:07:49.000Z
Volume110/11029 - Leading and Trailing/11029.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
Volume110/11029 - Leading and Trailing/11029.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
// Author: Stancioiu Nicu Razvan // Problem: http://uva.onlinejudge.org/external/110/11029.html #include <bits/stdc++.h> #define MOD 1000 using namespace std; unsigned int n,k; int t; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>t; int first,second; while(t--) { cin>>n>>k; int p=n%MOD; second=1; for(unsigned int j=0;(1<<j)<=k;j++) { if((1<<j)&k) { second=(second*p)%MOD; } p=(p*p)%MOD; } double mant=log10(n)*k; mant-=(int)mant-2; first=floor(pow(10,mant)); printf("%d...%.3d\n",first,second); } return 0; }
15.861111
62
0.597198
rstancioiu
f09a77ed465b33ff038f3f716365b8d3ffc690c0
2,319
hpp
C++
src/runtime/c4g_glsl.hpp
slightech/c4gpu
82dda2014fd2ae5c745ebdc6a797bb5f87793816
[ "MIT" ]
7
2019-04-26T20:25:53.000Z
2022-02-08T06:48:35.000Z
src/runtime/c4g_glsl.hpp
c4gpu/c4gpu_runtime
82dda2014fd2ae5c745ebdc6a797bb5f87793816
[ "MIT" ]
null
null
null
src/runtime/c4g_glsl.hpp
c4gpu/c4gpu_runtime
82dda2014fd2ae5c745ebdc6a797bb5f87793816
[ "MIT" ]
3
2021-12-22T02:02:42.000Z
2022-02-08T06:48:38.000Z
/* ** C4GPU. ** ** For the latest info, see https://github.com/c4gpu/c4gpu_runtime/ ** ** Copyright (C) 2017 Wang Renxin. All rights reserved. */ #ifndef __C4G_GLSL_H__ #define __C4G_GLSL_H__ #include "c4g_runtime.h" #ifdef C4G_RUNTIME_OS_WIN # include <GL/glew.h> # include <GL/glut.h> #elif defined C4G_RUNTIME_OS_APPLE # if defined C4G_RUNTIME_OS_IOS || defined C4G_RUNTIME_OS_IOS_SIM # include <OpenGLES/ES3/gl.h> # else # include <OpenGL/gl3.h> # endif #elif defined C4G_RUNTIME_OS_LINUX # include <GL/glew.h> # include <GL/glut.h> # include <GL/gl.h> # include <GL/glu.h> # include <GL/glext.h> #endif /* C4G_RUNTIME_OS_WIN */ #include <functional> #include <vector> #ifndef GL_INVALID_INDEX # define GL_INVALID_INDEX -1 #endif /* GL_INVALID_INDEX */ namespace c4g { namespace gl { typedef std::vector<GLuint> GLuintArray; typedef std::function<void (struct C4GRT_Runtime*, C4GRT_PassId, const char* const)> ErrorHandler; typedef std::function<bool (const char* const)> SimpleErrorHandler; enum ShaderTypes { ST_NONE, ST_VERT, ST_FRAG }; class C4G_RUNTIME_IMPL Shader final { public: Shader(); Shader(ShaderTypes type); ~Shader(); bool readFile(const char* const file); bool readString(const char* const str); bool compile(const SimpleErrorHandler &&callback); GLuint object(void); private: ShaderTypes _type = ST_NONE; GLchar* _code = nullptr; GLuint _object = 0; }; class C4G_RUNTIME_IMPL Program final { public: Program(); ~Program(); bool link(Shader &&vert, Shader &&frag); bool link(Shader &&vert, Shader &&frag, const char* const varyings[], size_t vs); bool use(void); GLint attributeLocation(const char* const name); GLint uniformLocation(const char* const name); void uniform(int loc, float f0); void uniform(int loc, float f0, float f1); void uniform(int loc, float f0, float f1, float f2); void uniform(int loc, float f0, float f1, float f2, float f3); void uniform(int loc, int i0); void uniform(int loc, int i0, int i1); void uniform(int loc, int i0, int i1, int i2); void uniform(int loc, int i0, int i1, int i2, int i3); GLuint object(void); private: Shader _vert; Shader _frag; GLuint _prog = 0; }; } } #endif /* __C4G_GLSL_H__ */
21.672897
99
0.688228
slightech
f09a7b28c8064b1024115f9006be8e36b1a3a2e5
2,988
cpp
C++
src/gromacs/linearalgebra/gmx_lapack/dlarft.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
src/gromacs/linearalgebra/gmx_lapack/dlarft.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
168
2017-05-27T14:43:32.000Z
2021-04-12T08:07:11.000Z
src/gromacs/linearalgebra/gmx_lapack/dlarft.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
#include <cmath> #include "gromacs/utility/real.h" #include "../gmx_blas.h" #include "../gmx_lapack.h" void F77_FUNC(dlarft,DLARFT)(const char *direct, const char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt) { /* System generated locals */ int t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3; double d__1; /* Local variables */ int i__, j; double vii; int c__1 = 1; double zero = 0.0; v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; --tau; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; if (*n == 0) { return; } if (*direct=='F' || *direct=='f') { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { if (std::abs(tau[i__])<GMX_DOUBLE_MIN) { i__2 = i__; for (j = 1; j <= i__2; ++j) { t[j + i__ * t_dim1] = 0.; } } else { vii = v[i__ + i__ * v_dim1]; v[i__ + i__ * v_dim1] = 1.; if (*storev=='C' || *storev=='c') { i__2 = *n - i__ + 1; i__3 = i__ - 1; d__1 = -tau[i__]; F77_FUNC(dgemv,DGEMV)("Transpose", &i__2, &i__3, &d__1, &v[i__ + v_dim1], ldv, &v[i__ + i__ * v_dim1], &c__1, &zero, &t[ i__ * t_dim1 + 1], &c__1); } else { i__2 = i__ - 1; i__3 = *n - i__ + 1; d__1 = -tau[i__]; F77_FUNC(dgemv,DGEMV)("No transpose", &i__2, &i__3, &d__1, &v[i__ * v_dim1 + 1], ldv, &v[i__ + i__ * v_dim1], ldv, & zero, &t[i__ * t_dim1 + 1], &c__1); } v[i__ + i__ * v_dim1] = vii; i__2 = i__ - 1; F77_FUNC(dtrmv,DTRMV)("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); t[i__ + i__ * t_dim1] = tau[i__]; } } } else { for (i__ = *k; i__ >= 1; --i__) { if (std::abs(tau[i__])<GMX_DOUBLE_MIN) { i__1 = *k; for (j = i__; j <= i__1; ++j) { t[j + i__ * t_dim1] = 0.; } } else { if (i__ < *k) { if (*storev=='C' || *storev=='c') { vii = v[*n - *k + i__ + i__ * v_dim1]; v[*n - *k + i__ + i__ * v_dim1] = 1.; i__1 = *n - *k + i__; i__2 = *k - i__; d__1 = -tau[i__]; F77_FUNC(dgemv,DGEMV)("Transpose", &i__1, &i__2, &d__1, &v[(i__ + 1) * v_dim1 + 1], ldv, &v[i__ * v_dim1 + 1], & c__1, &zero, &t[i__ + 1 + i__ * t_dim1], & c__1); v[*n - *k + i__ + i__ * v_dim1] = vii; } else { vii = v[i__ + (*n - *k + i__) * v_dim1]; v[i__ + (*n - *k + i__) * v_dim1] = 1.; i__1 = *k - i__; i__2 = *n - *k + i__; d__1 = -tau[i__]; F77_FUNC(dgemv,DGEMV)("No transpose", &i__1, &i__2, &d__1, &v[i__ + 1 + v_dim1], ldv, &v[i__ + v_dim1], ldv, & zero, &t[i__ + 1 + i__ * t_dim1], &c__1); v[i__ + (*n - *k + i__) * v_dim1] = vii; } i__1 = *k - i__; F77_FUNC(dtrmv,DTRMV)("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1 + (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1], &c__1) ; } t[i__ + i__ * t_dim1] = tau[i__]; } } } return; }
23.162791
79
0.477912
hejamu
f09ccdbb4aa5049e1e6a7362e34ff9994bf804f5
15,421
cpp
C++
Ambit/Source/Ambit/Mode/BulkScenarioConfiguration.spec.cpp
aws-samples/aws-ambit-scenario-designer-ue4
96843bccab3325a36dff6451b7e46837a9e918de
[ "Apache-2.0" ]
32
2021-12-01T04:28:53.000Z
2022-03-12T18:22:56.000Z
Ambit/Source/Ambit/Mode/BulkScenarioConfiguration.spec.cpp
aws-samples/aws-ambit-scenario-designer-ue4
96843bccab3325a36dff6451b7e46837a9e918de
[ "Apache-2.0" ]
10
2021-12-01T18:35:26.000Z
2022-02-15T00:32:00.000Z
Ambit/Source/Ambit/Mode/BulkScenarioConfiguration.spec.cpp
aws-samples/aws-ambit-scenario-designer-ue4
96843bccab3325a36dff6451b7e46837a9e918de
[ "Apache-2.0" ]
10
2021-12-01T06:59:41.000Z
2022-02-23T23:37:44.000Z
// Copyright 2022 Amazon.com, Inc. or its affiliates. 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 "BulkScenarioConfiguration.h" #include "ScenarioDefinition.h" #include "Dom/JsonObject.h" #include "Misc/AutomationTest.h" #include <AmbitUtils/JsonHelpers.h> BEGIN_DEFINE_SPEC(BulkScenarioConfigurationSpec, "Ambit.Unit.BulkScenarioConfiguration", EAutomationTestFlags::ProductFilter | EAutomationTestFlags::ApplicationContextMask) FBulkScenarioConfiguration BulkConfig; TSharedPtr<FJsonObject> Json; END_DEFINE_SPEC(BulkScenarioConfigurationSpec) void BulkScenarioConfigurationSpec::Define() { Describe("SerializeToJson()", [this]() { BeforeEach([this]() { BulkConfig = FBulkScenarioConfiguration{}; }); It("Configuration name is the same as the setup", [this]() { BulkConfig.ConfigurationName = "TestConfigurationName"; const FString ConfigurationName = BulkConfig.SerializeToJson()->GetStringField( JsonConstants::KConfigurationNameKey); TestEqual("Configuration Name", ConfigurationName, "TestConfigurationName"); }); It("Batch name is the same as the setup", [this]() { BulkConfig.BatchName = "TestBatchName"; const FString BatchName = BulkConfig.SerializeToJson()->GetStringField(JsonConstants::KBatchNameKey); TestEqual("BatchName", BatchName, "TestBatchName"); }); It("Time of day types is the same as the setup", [this]() { FTimeOfDayTypes TimeOfDay; TimeOfDay.SetMorning(true); BulkConfig.TimeOfDayTypes = TimeOfDay; const bool IsMorning = BulkConfig.SerializeToJson()->GetObjectField(JsonConstants::KTimeOfDayTypesKey)-> GetBoolField(TimeOfDay::KMorning); TestTrue("The morning in time of day type is true", IsMorning); }); It("Weather types is the same as the setup", [this]() { FWeatherTypes WeatherTypes; WeatherTypes.SetSunny(true); BulkConfig.WeatherTypes = WeatherTypes; const bool IsSunny = BulkConfig.SerializeToJson()->GetObjectField(JsonConstants::KWeatherTypesKey)-> GetBoolField(Weather::KSunny); TestTrue("Sunny in weather type is true", IsSunny); }); It("Batch pedestrian density is the same as the setup", [this]() { FPedestrianTraffic PedestrianDensity; PedestrianDensity.Min = 0.1f; PedestrianDensity.Max = 0.3f; BulkConfig.PedestrianDensity = PedestrianDensity; const float DensityMin = BulkConfig.SerializeToJson()->GetObjectField( JsonConstants::KBatchPedestrianDensityKey)->GetNumberField(JsonConstants::KMinKey); const float DensityMax = BulkConfig.SerializeToJson()->GetObjectField( JsonConstants::KBatchPedestrianDensityKey)->GetNumberField(JsonConstants::KMaxKey); TestEqual("The minimum of pedestrian density", DensityMin, 0.1f); TestEqual("The maximum of pedestrian density", DensityMax, 0.3f); }); It("Batch vehicle density is the same as the setup", [this]() { FVehicleTraffic VehicleDensity; VehicleDensity.Min = 0.2f; VehicleDensity.Max = 0.4f; BulkConfig.VehicleDensity = VehicleDensity; const float DensityMin = BulkConfig.SerializeToJson()->GetObjectField( JsonConstants::KBatchTrafficDensityKey)->GetNumberField(JsonConstants::KMinKey); const float DensityMax = BulkConfig.SerializeToJson()->GetObjectField( JsonConstants::KBatchTrafficDensityKey)->GetNumberField(JsonConstants::KMaxKey); TestEqual("The minimum of vehicle density", DensityMin, 0.2f); TestEqual("The maximum of vehicle density", DensityMax, 0.4f); }); }); Describe("DeserializeFromJson()", [this]() { BeforeEach([this]() { BulkConfig = FBulkScenarioConfiguration{}; const FString JsonFString = FString( "{" " 'Version': '1.0.0'," " 'ConfigurationName' : 'AmbitScenarioConfiguration'," " 'BulkScenarioName' : 'AmbitScenario'," " 'TimeOfDayTypes' :" " {" " 'Morning': true," " 'Noon' : false," " 'Evening' : true," " 'Night': false" " }," " 'WeatherTypes':" " {" " 'Sunny': true," " 'Rainy' : true," " 'Foggy' : false" " }," " 'PedestrianDensity':" " {" " 'Min': 0," " 'Max' : 0.10000000149011612," " 'Increment' : 0.10000000149011612" " }," " 'TrafficDensity':" " {" " 'Min': 0," " 'Max' : 0.10000000149011612," " 'Increment' : 0.10000000149011612" " }," " 'NumberOfPermutations': 16" "}" ).Replace(TEXT("'"), TEXT("\"")); Json = FJsonHelpers::DeserializeJson(JsonFString); }); It("when ConfigurationName is 'AmbitScenarioConfiguration'", [this]() { BulkConfig.DeserializeFromJson(Json); TestEqual("Configuration Name", BulkConfig.ConfigurationName, "AmbitScenarioConfiguration"); }); It("When BulkScenarioName is 'AmbitScenario'", [this]() { BulkConfig.DeserializeFromJson(Json); TestEqual("BulkScenario Name", BulkConfig.BatchName, "AmbitScenario"); }); It("When Morning and Evening in time of day types are true", [this]() { BulkConfig.DeserializeFromJson(Json); TestTrue("Time of day types: Morning", BulkConfig.TimeOfDayTypes.GetMorning()); TestTrue("Time of day types: Evening", BulkConfig.TimeOfDayTypes.GetEvening()); }); It("When Sunny and Rainy in weather types are true", [this]() { BulkConfig.DeserializeFromJson(Json); TestTrue("Weather types: Sunny", BulkConfig.WeatherTypes.GetSunny()); TestTrue("Weather types: Rainy", BulkConfig.WeatherTypes.GetRainy()); }); It("Pedestrian Density min and max", [this]() { BulkConfig.DeserializeFromJson(Json); TestEqual("The minimum of pedestrian density is", BulkConfig.PedestrianDensity.Min, 0.0f); TestEqual("The maximum of pedestrian density is", BulkConfig.PedestrianDensity.Max, 0.1f); }); It("Vehicle Density min and max", [this]() { BulkConfig.DeserializeFromJson(Json); TestEqual("The minimum of vehicle density is", BulkConfig.VehicleDensity.Min, 0.0f); TestEqual("The maximum of vehicle density is", BulkConfig.VehicleDensity.Max, 0.1f); }); }); Describe("GenerateScenarios()", [this]() { BeforeEach([this]() { BulkConfig = FBulkScenarioConfiguration{}; }); It("when single permutation is expected", [this]() { // Configure for single weather variant. BulkConfig.WeatherTypes.SetRainy(true); // Configure for single pedestrian traffic variant. BulkConfig.PedestrianDensity.Min = 0.2f; BulkConfig.PedestrianDensity.Max = 0.2f; // Configure for single traffic variant. BulkConfig.VehicleDensity.Min = 0.5f; BulkConfig.VehicleDensity.Max = 0.5f; const TArray<FScenarioDefinition> GeneratedScenarios = BulkConfig.GenerateScenarios(); // Test for expected number of permutations. TestEqual("Scenario count", GeneratedScenarios.Num(), 1); if (HasAnyErrors()) { return; } // Test that the correct scenario was generated. const FScenarioDefinition Scenario = GeneratedScenarios[0]; TestEqual("Precipitation", Scenario.AmbitWeatherParameters.Precipitation, 80.0f); TestEqual("Pedestrian Density", Scenario.PedestrianDensity, 0.2f); TestEqual("Vehicle Density", Scenario.VehicleDensity, 0.5f); }); It("when single permutation is expected with no weather and time of day types", [this]() { // Configure for single pedestrian traffic variant. BulkConfig.PedestrianDensity.Min = 0.0f; BulkConfig.PedestrianDensity.Max = 0.0f; // Configure for single traffic variant. BulkConfig.VehicleDensity.Min = 0.0f; BulkConfig.VehicleDensity.Max = 0.0f; const TArray<FScenarioDefinition> GeneratedScenarios = BulkConfig.GenerateScenarios(); // Test for expected number of permutations. TestEqual("Scenario count", GeneratedScenarios.Num(), 1); if (HasAnyErrors()) { return; } // Test that the correct scenario was generated. const FScenarioDefinition Scenario = GeneratedScenarios[0]; TestEqual("Pedestrian Density", Scenario.PedestrianDensity, 0.0f); TestEqual("Vehicle Density", Scenario.VehicleDensity, 0.0f); }); It("when 2 weather variants are configured", [this]() { // Configure for two weather variants. BulkConfig.WeatherTypes.SetSunny(true); BulkConfig.WeatherTypes.SetRainy(true); // Configure for single pedestrian traffic variant. BulkConfig.PedestrianDensity.Min = 0.2; BulkConfig.PedestrianDensity.Max = 0.2; // Configure for single traffic variant. BulkConfig.VehicleDensity.Min = 0.5; BulkConfig.VehicleDensity.Max = 0.5; const TArray<FScenarioDefinition> GeneratedScenarios = BulkConfig.GenerateScenarios(); // Test for expected number of permutations. TestEqual("scenario count", GeneratedScenarios.Num(), 2); if (HasAnyErrors()) { return; } // Test that the correct scenarios were generated. TestEqual("The Cloudiness in Sunny day", GeneratedScenarios[0].AmbitWeatherParameters.Cloudiness, 20.0f); TestEqual("The Cloudiness in Rainy day", GeneratedScenarios[1].AmbitWeatherParameters.Cloudiness, 90.0f); }); It("when 2 weather variant and 3 pedestrian variants are configured", [this]() { // Configure for two weather variants. BulkConfig.WeatherTypes.SetSunny(true); BulkConfig.WeatherTypes.SetFoggy(true); // Configure for single pedestrian traffic variant. BulkConfig.PedestrianDensity.Min = 0.2; BulkConfig.PedestrianDensity.Max = 0.4; // Configure for single traffic variant. BulkConfig.VehicleDensity.Min = 0.5; BulkConfig.VehicleDensity.Max = 0.5; const TArray<FScenarioDefinition> GeneratedScenarios = BulkConfig.GenerateScenarios(); // Test for expected number of permutations. TestEqual("scenario count", GeneratedScenarios.Num(), 6); if (HasAnyErrors()) { return; } // Test that the correct scenarios were generated. const auto FirstScenario = GeneratedScenarios[0]; TestEqual("The Cloudiness in the first scenario", FirstScenario.AmbitWeatherParameters.Cloudiness, 20.0f); TestEqual("Pedestrian Density in the first scenario", FirstScenario.PedestrianDensity, 0.2f); const auto LastScenario = GeneratedScenarios[5]; TestEqual("Cloudiness in the last scenario", LastScenario.AmbitWeatherParameters.Cloudiness, 30.f); TestEqual("Pedestrian Density in the last scenario", LastScenario.PedestrianDensity, 0.4f); }); It( "when 3 weather variants, 4 time of day variants, 11 pedestrian variants and 11 traffic variants are configured", [this]() { // Configure for all weather variants. BulkConfig.WeatherTypes.SetSunny(true); BulkConfig.WeatherTypes.SetRainy(true); BulkConfig.WeatherTypes.SetFoggy(true); // Configure for all time of day variants. BulkConfig.TimeOfDayTypes.SetMorning(true); BulkConfig.TimeOfDayTypes.SetNoon(true); BulkConfig.TimeOfDayTypes.SetEvening(true); BulkConfig.TimeOfDayTypes.SetNight(true); // Configure for single pedestrian traffic variant. BulkConfig.PedestrianDensity.Min = 0; BulkConfig.PedestrianDensity.Max = 1; // Configure for single traffic variant. BulkConfig.VehicleDensity.Min = 0; BulkConfig.VehicleDensity.Max = 1; const TArray<FScenarioDefinition> GeneratedScenarios = BulkConfig.GenerateScenarios(); // Test for expected number of permutations. TestEqual("scenario count", GeneratedScenarios.Num(), 3 * 4 * 11 * 11); // Test that the correct scenarios were generated. const auto FirstScenario = GeneratedScenarios[0]; TestEqual("The Cloudiness in the first scenario", FirstScenario.AmbitWeatherParameters.Cloudiness, 20.0f); TestEqual("The Time of day in the first scenario", FirstScenario.TimeOfDay, 6.0f); TestEqual("Pedestrian Density in the first scenario", FirstScenario.PedestrianDensity, 0.0f); TestEqual("Vehicle Density in the first scenario", FirstScenario.VehicleDensity, 0.0f); const auto LastScenario = GeneratedScenarios[3 * 4 * 11 * 11 - 1]; TestEqual("Cloudiness in the last scenario", LastScenario.AmbitWeatherParameters.Cloudiness, 30.f); TestEqual("The Time of day in the last scenario", LastScenario.TimeOfDay, 0.0f); TestEqual("Pedestrian Density in the last scenario", LastScenario.PedestrianDensity, 1.0f); TestEqual("Vehicle Density in the last scenario", LastScenario.VehicleDensity, 1.0f); }); }); }
43.934473
125
0.599702
aws-samples
f09e26bfae754f2005d371eb252ef42a8edd05ad
4,060
cc
C++
Analyses/src/SimParticlesWithHitsExample_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Analyses/src/SimParticlesWithHitsExample_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Analyses/src/SimParticlesWithHitsExample_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // Plugin to show how to use the SimParticlesWithHits class. // // $Id: SimParticlesWithHitsExample_module.cc,v 1.6 2013/10/21 21:13:18 kutschke Exp $ // $Author: kutschke $ // $Date: 2013/10/21 21:13:18 $ // // Original author Rob Kutschke. // // C++ includes. #include <iostream> #include <string> // Framework includes. #include "art/Framework/Core/EDAnalyzer.h" #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Principal/Event.h" #include "messagefacility/MessageLogger/MessageLogger.h" // Mu2e includes. #include "GeometryService/inc/GeomHandle.hh" #include "TrackerGeom/inc/Tracker.hh" #include "Mu2eUtilities/inc/SimParticlesWithHits.hh" using namespace std; namespace mu2e { class SimParticlesWithHitsExample : public art::EDAnalyzer { public: explicit SimParticlesWithHitsExample(fhicl::ParameterSet const& pset): art::EDAnalyzer(pset), _g4ModuleLabel(pset.get<std::string>("g4ModuleLabel")), _hitMakerModuleLabel(pset.get<std::string>("hitMakerModuleLabel")), _trackerStepPoints(pset.get<std::string>("trackerStepPoints")), _minEnergyDep(pset.get<double>("minEnergyDep")), _minHits(pset.get<unsigned>("minHits")){ } virtual ~SimParticlesWithHitsExample() { } void analyze( art::Event const& e ); private: // Label of the modules that created the data products. std::string _g4ModuleLabel; std::string _hitMakerModuleLabel; // Name of the tracker StepPoint collection std::string _trackerStepPoints; // Cuts used inside SimParticleWithHits: // - drop hits with too little energy deposited. // - drop SimParticles with too few hits. double _minEnergyDep; size_t _minHits; }; void SimParticlesWithHitsExample::analyze(art::Event const& evt ) { const Tracker& tracker = *GeomHandle<Tracker>(); // Construct an object that ties together all of the simulated particle and hit info. SimParticlesWithHits sims( evt, _g4ModuleLabel, _hitMakerModuleLabel, _trackerStepPoints, _minEnergyDep, _minHits ); typedef SimParticlesWithHits::map_type map_type; // int n(0); for ( map_type::const_iterator i=sims.begin(); i != sims.end(); ++i ){ // All information about this SimParticle SimParticleInfo const& simInfo = i->second; // Information about StrawHits that belong on this SimParticle. vector<StrawHitMCInfo> const& infos = simInfo.strawHitInfos(); cout << "SimParticle: " << " Event: " << evt.id().event() << " Track: " << i->first << " PdgId: " << simInfo.simParticle().pdgId() << " |p|: " << simInfo.simParticle().startMomentum().vect().mag() << " Hits: " << infos.size() << endl; // Loop over all StrawsHits to which this SimParticle contributed. for ( size_t j=0; j<infos.size(); ++j){ StrawHitMCInfo const& info = infos.at(j); StrawHit const& hit = info.hit(); Straw const& straw = tracker.getStraw(hit.strawId()); cout << " Straw Hit: " << info.index() << " " << hit.strawId().asUint16() << " " << hit.time() << " " << info.isShared() << " " << straw.getMidPoint().z() << " " << info.time() << " | StepPointMCs: "; // Loop over all StepPointMC's that contribute to this StrawHit. std::vector<StepPointMC const *> const& steps = info.steps(); for ( size_t k=0; k<steps.size(); ++k){ StepPointMC const& step = *(steps[k]); cout << " (" << step.time() << "," << step.momentum().mag() << "," << step.trackId() << ")"; } cout << endl; } } } // end of ::analyze. } using mu2e::SimParticlesWithHitsExample; DEFINE_ART_MODULE(SimParticlesWithHitsExample);
32.741935
103
0.598522
bonventre
f0a0d9b01b46fa45294ec5f4bf7290b07ed81974
3,339
cc
C++
demo/client/client_demo.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
9
2015-08-14T08:59:06.000Z
2018-08-20T13:46:46.000Z
demo/client/client_demo.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
null
null
null
demo/client/client_demo.cc
haveTryTwo/csutil
7cb071f6927db4c52832d3074fb69f273968d66e
[ "BSD-2-Clause" ]
1
2018-08-20T13:46:29.000Z
2018-08-20T13:46:29.000Z
// Copyright (c) 2015 The CSUTIL 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 <iostream> #include <stdio.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <pthread.h> #include "base/mutex.h" #include "base/status.h" #include "cs/client.h" namespace test { int TestClient() { base::Client client; base::EventType event_type = base::kPoll; #if defined(__linux__) event_type = base::kEPoll; #endif base::Code ret = client.Init(event_type); assert(ret == base::kOk); std::string ip("127.0.0.1"); uint16_t port = 9090; ret = client.Connect(ip, port); assert(ret == base::kOk); std::string buf_out("hello world"); ret = client.Write(buf_out); fprintf(stderr, "buf_out:%s\n", buf_out.c_str()); assert(ret == base::kOk); std::string buf_in; ret = client.Read(&buf_in); assert(ret == base::kOk); fprintf(stderr, "buf_in:%s\n", buf_in.c_str()); return base::kOk; } static base::Mutex g_mu; static int g_flow_count = 0; static int g_success_count = 0; void* ThreadFunc(void *param) { base::Client client; base::EventType event_type = base::kPoll; #if defined(__linux__) event_type = base::kEPoll; #endif base::Code ret = client.Init(event_type); assert(ret == base::kOk); std::string ip("127.0.0.1"); uint16_t port = 9090; ret = client.Connect(ip, port); assert(ret == base::kOk); pthread_t self = pthread_self(); for (int i = 0; i < 10000; ++i) { std::string buf_out("hello world"); ret = client.Write(buf_out); #if defined(__linux__) || defined(__unix__) fprintf(stderr, "pthread_id:%#llx, buf_out:%s\n", (uint64_t)self, buf_out.c_str()); #elif defined(__APPLE__) fprintf(stderr, "pthread_id:%p, buf_out:%s\n", self, buf_out.c_str()); #endif assert(ret == base::kOk); std::string buf_in; ret = client.Read(&buf_in); assert(ret == base::kOk); #if defined(__linux__) || defined(__unix__) fprintf(stderr, "pthread_id:%#llx, buf_in:%s\n", (uint64_t)self, buf_in.c_str()); #elif defined(__APPLE__) fprintf(stderr, "pthread_id:%p, buf_in:%s\n", self, buf_in.c_str()); #endif { base::MutexLock mlock(&g_mu); if (buf_in == base::FlowInfo) g_flow_count++; else g_success_count++; } usleep(1000); } pthread_exit(NULL); } int MultiThreadTestClient() { pthread_t pth[100]; int ret = 0; for (int i = 0; i < (int)(sizeof(pth)/sizeof(pth[0])); ++i) { ret = pthread_create(pth+i, NULL, ThreadFunc, NULL); if (ret != 0) { fprintf(stderr, "[%s:%s:%d] Failed to pthread_create, errno:%d\n", __FILE__, __func__, __LINE__, ret); return base::kPthreadCreateFailed; } } for (int i = 0; i < (int)(sizeof(pth)/sizeof(pth[0])); ++i) { pthread_join(pth[i], NULL); } fprintf(stderr, "flow_count:%d, success_count:%d\n", g_flow_count, g_success_count); return base::kOk; } } int main(int argc, char *argv[]) { // test::TestClient(); test::MultiThreadTestClient(); return 0; }
24.021583
91
0.59988
haveTryTwo
f0a13569cb49e9429fd227682aece1f8a0ae1f26
1,223
cpp
C++
src/Model/CFrameModel.cpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
1
2019-06-14T08:24:17.000Z
2019-06-14T08:24:17.000Z
src/Model/CFrameModel.cpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
src/Model/CFrameModel.cpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
#include "CFrameModel.hpp" namespace OMGL3D { namespace MODEL { CFrameModel::CFrameModel(const std::string & name) : IFrameModel(name) { } CFrameModel::~CFrameModel() { } void CFrameModel::SetRootMesh(CORE::IMesh * mesh) { } void CFrameModel::AddFrameInfo(const FrameInfo & frame) { _frames.push_back(frame); } unsigned int CFrameModel::GetMaxFrames() const { return _frames.size(); } void CFrameModel::Animate(unsigned int frame, unsigned int next_frame, float fPercent) { } void CFrameModel::Draw(const CORE::AlphaTest & alpha) const { _rootMesh.GetPtr()->Draw(alpha); } void CFrameModel::Draw(const CORE::BlendingMode & blending) const { _rootMesh.GetPtr()->Draw(blending); } void CFrameModel::Draw(const CORE::AlphaTest & alpha, const CORE::BlendingMode & blending) const { _rootMesh.GetPtr()->Draw(alpha, blending); } void CFrameModel::Draw()const { _rootMesh.GetPtr()->Draw(); } } }
22.648148
104
0.54211
Sebajuste
f0a31a4f8a39524e1c8f0452c049d426976f200a
1,586
cc
C++
chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" using JavaScriptDialogTest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(JavaScriptDialogTest, ReloadDoesntHang) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kAutoDismissingDialogs); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); JavaScriptDialogTabHelper* js_helper = JavaScriptDialogTabHelper::FromWebContents(tab); // Show a dialog. scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; js_helper->SetDialogShownCallbackForTesting(runner->QuitClosure()); tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()")); runner->Run(); // Try reloading. tab->GetController().Reload(false); content::WaitForLoadStop(tab); // If the WaitForLoadStop doesn't hang forever, we've passed. }
36.883721
79
0.785624
xzhan96
f0a654f13bad1f4110544661d84ced551a9a7581
3,165
cpp
C++
Scene.cpp
Excelsus4/Eat-emAll
5f701e764e9d7a27542ae9c88b20f26497090232
[ "MIT" ]
null
null
null
Scene.cpp
Excelsus4/Eat-emAll
5f701e764e9d7a27542ae9c88b20f26497090232
[ "MIT" ]
null
null
null
Scene.cpp
Excelsus4/Eat-emAll
5f701e764e9d7a27542ae9c88b20f26497090232
[ "MIT" ]
null
null
null
#pragma once #include "stdafx.h" #include "Device.h" #include "Vertex.h" #include "RectObject.h" #include "Random.h" Shader* shader; ID3D11Buffer* vertexBuffer; const int VNUM = 32; const int VSIZE = 6; Vertex vertices[VNUM*VSIZE]; RectObject player = RectObject(D3DXVECTOR3(50.0f, 50.0f, 0), 25.0f, D3DXVECTOR3(1, 1, 1), vertices); float speed = 0.25f; vector<RectObject*> foodVector; vector<RectObject*> foodPool; D3DXMATRIX W, V, P; void InitScene() { shader = new Shader(L"../_Shaders/005_WVP.fx"); random_device rd; Random::gen = new mt19937(rd()); player.SetVertex(); for (int idx = 1; idx < VNUM; idx++) { foodPool.push_back(new RectObject(&vertices[idx * VSIZE])); } //for (auto a : foodVector) { // a->SetVertex(); //} //Create Vertex Buffer { D3D11_BUFFER_DESC desc = { 0 }; desc.Usage = D3D11_USAGE_DEFAULT; desc.ByteWidth = sizeof(Vertex) * VNUM * VSIZE; desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA data = { 0 }; data.pSysMem = vertices; HRESULT hr = Device->CreateBuffer(&desc, &data, &vertexBuffer); assert(SUCCEEDED(hr)); } } void DestroyScene() { for (auto p : foodPool) { delete p; } for (auto a : foodVector) { delete a; } vertexBuffer->Release(); delete Random::gen; delete shader; } void Update() { // WVP D3DXMatrixIdentity(&W); D3DXMatrixIdentity(&V); D3DXMatrixIdentity(&P); //View D3DXVECTOR3 eye(0, 0, -1); D3DXVECTOR3 at(0, 0, 0); D3DXVECTOR3 up(0, 1, 0); D3DXMatrixLookAtLH(&V, &eye, &at, &up); //Projection D3DXMatrixOrthoOffCenterLH(&P, 0, (float)Width, 0, (float)Height, -1, 1); shader->AsMatrix("World")->SetMatrix(W); shader->AsMatrix("View")->SetMatrix(V); shader->AsMatrix("Projection")->SetMatrix(P); // Character Movement if (Key->Press('A') == true) player.Translate(D3DXVECTOR3(-speed, 0, 0)); else if (Key->Press('D') == true) player.Translate(D3DXVECTOR3(+speed, 0, 0)); if (Key->Press('W') == true) player.Translate(D3DXVECTOR3(0, +speed, 0)); else if (Key->Press('S') == true) player.Translate(D3DXVECTOR3(0, -speed, 0)); //Check Collision auto it = foodVector.begin(); while (it != foodVector.end()) { if (player.CollisionCheck(**it)) { player.Consume(**it); (*it)->DisableVertex(); foodPool.push_back(*it); it = foodVector.erase(it); } else { ++it; } } for (auto a : foodVector) { } //always player.SetVertex(); DeviceContext->UpdateSubresource( vertexBuffer, 0, NULL, vertices, sizeof(Vertex) * VNUM * VSIZE, 0); } void Render() { D3DXCOLOR bgColor = D3DXCOLOR(0.1f, 0.1f, 0.1f, 1); DeviceContext->ClearRenderTargetView(RTV, (float*)bgColor); { //ImGUI if (ImGui::Button("Create")) { if (foodPool.size() > 0) { auto t = foodPool.begin(); foodVector.push_back(*t); (*t)->Randomize(); foodPool.erase(t); } } UINT stride = sizeof(Vertex); UINT offset = 0; DeviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset); DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //DeviceContext->Draw(VNUM * VSIZE, 0); shader->Draw(0, 0, VNUM*VSIZE); } ImGui::Render(); SwapChain->Present(0, 0); }
22.132867
100
0.660979
Excelsus4
f0a9db2283b19824b65822056aa3ebbb2f9cb0bb
5,912
cpp
C++
InformationScripting/src/queries/Join.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
75
2015-01-18T13:29:43.000Z
2022-01-14T08:02:01.000Z
InformationScripting/src/queries/Join.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
364
2015-01-06T10:20:21.000Z
2018-12-17T20:12:28.000Z
InformationScripting/src/queries/Join.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
14
2015-01-09T00:44:24.000Z
2022-02-22T15:01:44.000Z
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "Join.h" #include "../query_framework/QueryRegistry.h" namespace InformationScripting { const QStringList Join::VALUE_ARGUMENT_NAMES{"v", "values"}; const QStringList Join::AS_ARGUMENT_NAMES{"a", "as"}; const QStringList Join::ON_ARGUMENT_NAMES{"o", "on"}; Optional<TupleSet> Join::executeLinear(TupleSet input) { QList<TaggedValue> values; QString tag1; QString tag2; std::pair<TaggedValue, TaggedValue> joinOn; const QRegularExpression onRegex{"(\\w+)\\.(\\w+)=(\\w+)\\.(\\w+)"}; auto onMatches = onRegex.match(arguments_.argument(ON_ARGUMENT_NAMES[1])); if (onMatches.hasMatch()) { tag1 = onMatches.captured(1); tag2 = onMatches.captured(3); joinOn = {{tag1, onMatches.captured(2)}, {tag2, onMatches.captured(4)}}; } const QRegularExpression valueMatch{"((\\w+)\\.)?(\\w+)"}; auto valueMatchIt = valueMatch.globalMatch(arguments_.argument(VALUE_ARGUMENT_NAMES[1])); while (valueMatchIt.hasNext()) { auto match = valueMatchIt.next(); if (!match.hasMatch()) return {"join values need the following format: tag.value"}; auto tag = match.captured(2); auto value = match.captured(3); values.push_back({tag, value}); if (!tag.isEmpty()) { if (tag1.isNull() || tag1 == tag) tag1 = tag; else if (tag1 != tag && tag2.isNull()) tag2 = tag; else if (tag2 != tag) return {"join values can only be from 2 different tuples"}; } } if (tag1.isNull() || tag2.isNull()) return {"join only works on 2 different tuples"}; // By default join on id if (joinOn.first.first.isEmpty()) joinOn = {{tag1, "id"}, {tag2, "id"}}; auto tag1Tuples = input.tuples(tag1); auto tag2Tuples = input.tuples(tag2); if (tag1Tuples.isEmpty() || tag2Tuples.isEmpty()) return {input, "Not enough input for join"}; if (tag1 != joinOn.first.first) std::swap(joinOn.first, joinOn.second); auto id1Name = joinOn.first.second; auto id2Name = joinOn.second.second; for (const auto& tuple1 : tag1Tuples) { auto it = tuple1.find(id1Name); if (it == tuple1.end()) return {QString{"Tuple %1 does not contain %2 which is required for join"}.arg(tag1, id1Name)}; Property id1 = it->second; bool attributeNotFound = false; auto it2 = std::find_if(tag2Tuples.begin(), tag2Tuples.end(), [id1, &attributeNotFound, id2Name](const Tuple& t) { auto idIt = t.find(id2Name); if (idIt == t.end()) { attributeNotFound = true; return false; } return idIt->second == id1; }); if (attributeNotFound) return {QString{"Tuple %1 does not contain %2 which is required for join"}.arg(tag2, id2Name)}; if (it2 != tag2Tuples.end()) { // Found a match auto props1 = extractProperties(tuple1, values); if (props1.hasErrors()) return props1.errors()[0]; auto props2 = extractProperties(*it2, values); if (props2.hasErrors()) return props2.errors()[0]; input.add(Tuple{arguments_.argument(AS_ARGUMENT_NAMES[1]), props1.value() + props2.value()}); } } return input; } void Join::registerDefaultQueries() { QueryRegistry::registerQuery<Join>("join", std::vector<ArgumentRule>{{ArgumentRule::RequireAll, {{VALUE_ARGUMENT_NAMES[1]}, {AS_ARGUMENT_NAMES[1]}}}}); } Join::Join(Model::Node* target, QStringList args, std::vector<ArgumentRule> argumentRules) : LinearQuery{target}, arguments_{{ {AS_ARGUMENT_NAMES, "Name of the joined tuple", AS_ARGUMENT_NAMES[1]}, {ON_ARGUMENT_NAMES, "Name of the attributes to join on", ON_ARGUMENT_NAMES[1]} }, {PositionalArgument{VALUE_ARGUMENT_NAMES[1], "Name of the attribute(s) that will be in the joined tuple"}}, args} { for (const auto& rule : argumentRules) rule.check(arguments_); } Optional<QList<NamedProperty>> Join::extractProperties(const Tuple& t, const QList<std::pair<QString, QString>>& values) { QList<NamedProperty> result; for (const auto& v : values) { if (v.first.isEmpty() || v.first == t.tag()) { auto it = t.find(v.second); if (it == t.end() && v.first.isEmpty()) continue; else if (it == t.end()) return QString{"Tuple %1 does not have any value %2"}.arg(t.tag(), v.second); else result.push_back(*it); } } return result; } }
36.95
120
0.677605
dimitar-asenov
f0ad1feed8b5215c4a58b3ee5082286b10100e98
14,149
cpp
C++
WRK-V1.2/clr/src/vm/securitytransparentassembly.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/clr/src/vm/securitytransparentassembly.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/clr/src/vm/securitytransparentassembly.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== //-------------------------------------------------------------------------- // securityTransparentAssembly.cpp // // Implementation for transparent code feature // //-------------------------------------------------------------------------- #include "common.h" #include "field.h" #include "securitydeclarative.h" #include "security.h" #include "securitydescriptor.h" #include "comreflectioncommon.h" #include "customattribute.h" #include "securitytransparentassembly.h" #include "securitymeta.h" // Check for Disable Transparency Enforcement BOOL IsTransparencyDisabled() { return (g_pConfig->TransparencyDisabled()); } BOOL SecurityTransparent::CheckNonPublicCriticalAccess(MethodDesc* pCurrentMD, MethodDesc* pOptionalTargetMethod, FieldDesc* pOptionalTargetField, MethodTable * pOptionalTargetType) { // Atmost one of these should be non-NULL _ASSERTE(1 >= ((pOptionalTargetMethod ? 1 : 0) + (pOptionalTargetField ? 1 : 0) + (pOptionalTargetType ? 1 : 0))); BOOL fIsCallerTransparent = FALSE; if (pCurrentMD != NULL) { fIsCallerTransparent = IsMethodTransparent(pCurrentMD); } // if caller is critical, so we are fine, no more checks needed if (!fIsCallerTransparent) return TRUE; // okay caller is transparent, additional checks needed BOOL fIsTargetCritical = FALSE; // check if target is critical BOOL fIsTargetSafe = FALSE; // check if target is marked safe if (pOptionalTargetMethod != NULL) { MethodSecurityDescriptor methSecurityDescriptor(pOptionalTargetMethod); fIsTargetCritical = methSecurityDescriptor.IsCritical(); fIsTargetSafe = methSecurityDescriptor.IsTreatAsSafe(); } else if (pOptionalTargetField != NULL) { FieldSecurityDescriptor fieldSecurityDescriptor(pOptionalTargetField); fIsTargetCritical = fieldSecurityDescriptor.IsCritical(); fIsTargetSafe = fieldSecurityDescriptor.IsTreatAsSafe(); } else if (pOptionalTargetType != NULL) { TypeSecurityDescriptor typeSecurityDescriptor(pOptionalTargetType->GetClass()); fIsTargetCritical = typeSecurityDescriptor.IsAllCritical(); // check for only all critical classes fIsTargetSafe = typeSecurityDescriptor.IsTreatAsSafe(); } // if target is not critical, we are fine, no more checks needed // if the target is critical and is marked as TreatAsSafe, we are fine, no more checks needed. if (!fIsTargetCritical || fIsTargetSafe) return TRUE; // otherwise we disallow access, no access to non public critical targets (that don't have TreatAsSafe attribute) from transparent callers return FALSE; } CorInfoCanSkipVerificationResult SecurityTransparent::JITCanSkipVerification(MethodDesc * pMD, BOOL fQuickCheckOnly) { BOOL hasSkipVerificationPermisson = false; if (fQuickCheckOnly) hasSkipVerificationPermisson = Security::CanSkipVerification(pMD->GetAssembly()->GetDomainAssembly(), FALSE); // fCommit == FALSE else hasSkipVerificationPermisson = Security::CanSkipVerification(pMD->GetAssembly()->GetDomainAssembly(), TRUE); CorInfoCanSkipVerificationResult canSkipVerif = hasSkipVerificationPermisson ? CORINFO_VERIFICATION_CAN_SKIP : CORINFO_VERIFICATION_CANNOT_SKIP; // also check to see if the method is marked transparent if (hasSkipVerificationPermisson) { // also check to see if the method is marked transparent if (SecurityTransparent::IsMethodTransparent(pMD)) { canSkipVerif = CORINFO_VERIFICATION_RUNTIME_CHECK; } } return canSkipVerif; } CorInfoCanSkipVerificationResult SecurityTransparent::JITCanSkipVerification(DomainAssembly * pAssembly, BOOL fQuickCheckOnly) { BOOL hasSkipVerificationPermisson = false; if (fQuickCheckOnly) { hasSkipVerificationPermisson = Security::CanSkipVerification(pAssembly, FALSE); // fCommit } else hasSkipVerificationPermisson = Security::CanSkipVerification(pAssembly); CorInfoCanSkipVerificationResult canSkipVerif = hasSkipVerificationPermisson ? CORINFO_VERIFICATION_CAN_SKIP : CORINFO_VERIFICATION_CANNOT_SKIP; if (hasSkipVerificationPermisson) { // also check to see if the assembly is marked transparent /*if (SecurityTransparent::IsAssemblyTransparent(pAssembly->GetAssembly())) { canSkipVerif = CORINFO_VERIFICATION_RUNTIME_CHECK; }*/ } return canSkipVerif; } CorInfoIsCallAllowedResult SecurityTransparent::RequiresTransparentAssemblyChecks(MethodDesc* pCallerMD, MethodDesc* pCalleeMD) { return RequiresTransparentCodeChecks(pCallerMD, pCalleeMD); } CorInfoIsCallAllowedResult SecurityTransparent::RequiresTransparentCodeChecks(MethodDesc* pCallerMD, MethodDesc* pCalleeMD) { CONTRACTL { THROWS; GC_TRIGGERS; PRECONDITION(CheckPointer(pCallerMD)); PRECONDITION(CheckPointer(pCalleeMD)); } CONTRACTL_END; // check if the caller assembly is transparent if (IsMethodTransparent(pCallerMD)) { if( pCalleeMD->RequiresLinktimeCheck() ) { return CORINFO_CALL_RUNTIME_CHECK; } else { return CORINFO_CALL_ALLOWED; } } return CORINFO_CALL_ALLOWED; } // Perform appropriate Transparency checks if the caller to the Load(byte[] ) without passing in an input Evidence is Transparent VOID SecurityTransparent::PerformTransparencyChecksForLoadByteArray(MethodDesc* pCallerMD, AssemblySecurityDescriptor* pLoadedSecDesc) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END GCX_COOP(); // check to see if the method that does the Load(byte[] ) is transparent if (IsMethodTransparent(pCallerMD)) { Assembly* pLoadedAssembly = pLoadedSecDesc->GetAssembly(); // check to see if the byte[] being loaded is critical, i.e. not Transparent if (!ModuleSecurityDescriptor::IsMarkedTransparent(pLoadedAssembly)) { // if transparent code loads a byte[] that is critical, need to inject appropriate demands if (Security::IsFullyTrusted(pLoadedSecDesc)) // if the loaded code is full-trust { // do a full-demand for Full-Trust OBJECTREF permSet = NULL; GCPROTECT_BEGIN(permSet); Security::GetPermissionInstance(&permSet, SECURITY_FULL_TRUST); Security::DemandSet(SSWT_LATEBOUND_LINKDEMAND, permSet); GCPROTECT_END();// do a full-demand for Full-Trust } else { // otherwise inject a Demand for permissions being granted? struct _localGC { OBJECTREF granted; OBJECTREF denied; } localGC; ZeroMemory(&localGC, sizeof(localGC)); GCPROTECT_BEGIN(localGC); { localGC.granted = Security::GetGrantedPermissionSet(pLoadedSecDesc, &(localGC.denied)); Security::DemandSet(SSWT_LATEBOUND_LINKDEMAND, localGC.granted); } GCPROTECT_END(); } } } } static void ConvertLinkDemandToFullDemand(MethodDesc* pCallerMD, MethodDesc* pCalleeMD) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; BOOL isEveryoneFullyTrusted = FALSE; BOOL isSecurityOn = Security::IsSecurityOn(); if (!isSecurityOn) { return; } isEveryoneFullyTrusted = Security::AllDomainsOnStackFullyTrusted(); if (isEveryoneFullyTrusted) { return; } if (!pCalleeMD->RequiresLinktimeCheck()) { return; } struct _gc { OBJECTREF refClassNonCasDemands; OBJECTREF refClassCasDemands; OBJECTREF refMethodNonCasDemands; OBJECTREF refMethodCasDemands; OBJECTREF refThrowable; } gc; ZeroMemory(&gc, sizeof(gc)); GCPROTECT_BEGIN(gc); BOOL fCallerIsAPTCA = pCallerMD->GetClass()->GetAssembly()->AllowUntrustedCaller(); // Fetch link demand sets from all the places in metadata where we might // find them (class and method). These might be split into CAS and non-CAS // sets as well. Security::RetrieveLinktimeDemands(pCalleeMD, &gc.refClassCasDemands, &gc.refClassNonCasDemands, &gc.refMethodCasDemands, &gc.refMethodNonCasDemands); // The following logic turns link demands on the target method into full // stack walks in order to close security holes in poorly written // reflection users. _ASSERTE(pCalleeMD); if (fCallerIsAPTCA && Security::IsUntrustedCallerCheckNeeded(pCalleeMD, pCallerMD->GetAssembly()) ) { // if caller is APTCA convert Non-APTCA full-trust LinkDemands to Full-Demands OBJECTREF permSet = NULL; GCPROTECT_BEGIN(permSet); Security::GetPermissionInstance(&permSet, SECURITY_FULL_TRUST); Security::DemandSet(SSWT_LATEBOUND_LINKDEMAND, permSet); GCPROTECT_END(); } // CAS Link Demands if (gc.refClassCasDemands != NULL) Security::DemandSet(SSWT_LATEBOUND_LINKDEMAND, gc.refClassCasDemands); if (gc.refMethodCasDemands != NULL) Security::DemandSet(SSWT_LATEBOUND_LINKDEMAND, gc.refMethodCasDemands); // Non-CAS demands are not applied against a grant // set, they're standalone. if (gc.refClassNonCasDemands != NULL) Security::CheckNonCasDemand(&gc.refClassNonCasDemands); if (gc.refMethodNonCasDemands != NULL) Security::CheckNonCasDemand(&gc.refMethodNonCasDemands); // We perform automatic linktime checks for UnmanagedCode in three cases: // o P/Invoke calls. // o Calls through an interface that have a suppress runtime check // attribute on them (these are almost certainly interop calls). // o Interop calls made through method impls. if (pCalleeMD->IsNDirect() || (pCalleeMD->IsInterface() && (pCalleeMD->GetMDImport()->GetCustomAttributeByName(pCalleeMD->GetMethodTable()->GetCl(), COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI, NULL, NULL) == S_OK || pCalleeMD->GetMDImport()->GetCustomAttributeByName(pCalleeMD->GetMemberDef(), COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI, NULL, NULL) == S_OK) ) || (pCalleeMD->IsComPlusCall() && !pCalleeMD->IsInterface()) ) { if (fCallerIsAPTCA) { // if the caller assembly is APTCA, then only inject this demand, for NON-APTCA we will allow supress unmanaged code // NOTE: the JIT would have already performed the LinkDemand for this anyways Security::SpecialDemand(SSWT_LATEBOUND_LINKDEMAND, SECURITY_UNMANAGED_CODE); } } GCPROTECT_END(); /* if (isSecurityOn && !fRet) { if (checkSkipVer) Security::SpecialDemand(SSWT_LATEBOUND_LINKDEMAND, SECURITY_SKIP_VER); } */ } VOID SecurityTransparent::EnforceTransparentAssemblyChecks(MethodDesc* pCallerMD, MethodDesc* pCalleeMD) { CONTRACTL { THROWS; GC_TRIGGERS; PRECONDITION(CheckPointer(pCallerMD)); PRECONDITION(CheckPointer(pCalleeMD)); INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; ConvertLinkDemandToFullDemand(pCallerMD, pCalleeMD); } BOOL SecurityTransparent::IsMethodTransparent(MethodDesc* pMD) { // if Transparency is disabled, then Ignore all Transparency aspects if (IsTransparencyDisabled()) return FALSE; MethodSecurityDescriptor methSecurityDescriptor(pMD); return !methSecurityDescriptor.IsCritical(); } BOOL SecurityTransparent::IsFieldTransparent(FieldDesc* pFD) { // if Transparency is disabled, then Ignore all Transparency aspects if (IsTransparencyDisabled()) return FALSE; FieldSecurityDescriptor fieldSecurityDescriptor(pFD); return !fieldSecurityDescriptor.IsCritical(); } BOOL SecurityTransparent::IsAssemblyTransparent(Assembly* pAssembly) { ModuleSecurityDescriptor* pModuleSecDesc = ModuleSecurityDescriptor::GetModuleSecurityDescriptor(pAssembly); return !pModuleSecDesc->IsCritical(); } BOOL SecurityTransparent::CheckAssemblyHasSecurityTransparentAttribute(Assembly* pAssembly) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END BOOL fIsTransparent = FALSE; BOOL fIsCritical = FALSE; IMDInternalImport *mdImport = pAssembly->GetManifestImport(); GCX_COOP(); if (mdImport->GetCustomAttributeByName(pAssembly->GetManifestToken(), g_SecurityTransparentAttribute, NULL, NULL) == S_OK) { fIsTransparent = TRUE; if (mdImport->GetCustomAttributeByName(pAssembly->GetManifestToken(), g_SecurityCriticalAttribute, NULL, NULL) == S_OK) fIsCritical = TRUE; } // We cannot have both critical and transparent attributes on the assembly level. if (fIsTransparent && fIsCritical) COMPlusThrow(kInvalidOperationException, L"InvalidOperation_CriticalTransparentAreMutuallyExclusive"); return fIsTransparent; }
34.25908
148
0.670365
intj-t
f0ae554202b769de7508fba055dbfed89228d22d
979
cpp
C++
libminimsgbus/PubTable.cpp
jinyuttt/libminimsgbus
7e5265b3d48bebf7ced93ee27d73b7414b4b6f8b
[ "MIT" ]
null
null
null
libminimsgbus/PubTable.cpp
jinyuttt/libminimsgbus
7e5265b3d48bebf7ced93ee27d73b7414b4b6f8b
[ "MIT" ]
null
null
null
libminimsgbus/PubTable.cpp
jinyuttt/libminimsgbus
7e5265b3d48bebf7ced93ee27d73b7414b4b6f8b
[ "MIT" ]
null
null
null
#include "PubTable.h" namespace libminimsgbus { PubTable::PubTable() { } bool PubTable::add(string topic, string address) { auto v = topicPub.find(topic); if (v != topicPub.end()) { for (auto lst : v->second) { if (lst == address) { return false; } } v->second.push_back(address); } else { list<string> lst; lst.push_back(address); topicPub[topic] = lst; } return true; } list<string> PubTable::getAddress(string topic) { list<string> lst; auto v = topicPub.find(topic); if (v != topicPub.end()) { lst = v->second; } return lst; } map<string, list<string>> PubTable::getPairs() { map<string, list<string>> tmp(topicPub); return tmp; } }
18.12963
51
0.444331
jinyuttt
f0aee4b76de3ef7afabda480aaf80e98d0431508
5,239
cpp
C++
apps/experiments/fluidDemo/src/testApp.cpp
HellicarAndLewis/ProjectDonk
96fde869c469f8312843333e51c862bd3b143222
[ "MIT" ]
1
2015-12-05T04:53:15.000Z
2015-12-05T04:53:15.000Z
apps/experiments/fluidDemo/src/testApp.cpp
HellicarAndLewis/ProjectDonk
96fde869c469f8312843333e51c862bd3b143222
[ "MIT" ]
null
null
null
apps/experiments/fluidDemo/src/testApp.cpp
HellicarAndLewis/ProjectDonk
96fde869c469f8312843333e51c862bd3b143222
[ "MIT" ]
null
null
null
#include "testApp.h" using namespace MSA; //-------------------------------------------------------------- void testApp::setup() { // setup fluid stuff fluidSolver.setup(100, 100); fluidSolver.enableRGB(true); //fluidSolver.setFadeSpeed(0.000001); fluidSolver.setFadeSpeed(0.002f); //fluidSolver.setFadeSpeed(1.0); fluidSolver.setDeltaT(1); fluidSolver.setColorDiffusion(0); fluidSolver.setVisc(0.00015); fluidDrawer.setup( &fluidSolver ); particleSystem.setFluidSolver( &fluidSolver ); particleSystem.setWindowSize(ofVec2f(ofGetWidth(), ofGetHeight())); fluidCellsX = 150; drawFluid = true; drawParticles = true; ofSetFrameRate(60); ofBackground(1, 1, 1);//ofBackground(0, 0, 0); ofSetVerticalSync(false); windowResized(ofGetWidth(), ofGetHeight()); // force this at start (cos I don't think it is called) pMouse = ofVec2f(ofGetWidth()/2, ofGetHeight()/2); resizeFluid = true; currentEmitter = 0; float inc = ofGetWidth()/3.f; for(int i = 0; i<NUM_EMITTERS/2; i++) { forceEmitters[i].set(i*inc, ofGetHeight()); } for(int i = NUM_EMITTERS/2; i<NUM_EMITTERS; i++) { forceEmitters[i].set((i-NUM_EMITTERS/2)*inc, ofGetHeight()/2); } ofEnableAlphaBlending(); ofSetBackgroundAuto(true); } void testApp::fadeToColor(float r, float g, float b, float speed) { glColor4f(r, g, b, speed); ofRect(0, 0, ofGetWidth(), ofGetHeight()); } void testApp::update(){ /*if(resizeFluid) { //float hwRatio = ofGetHeight()/ofGetWidth(); float hwRatio = 1200/800; fluidSolver.setSize(fluidCellsX, fluidCellsX / hwRatio); fluidDrawer.setup(&fluidSolver); resizeFluid = false; }*/ fluidSolver.update(); for(int i = 0 ; i<NUM_EMITTERS; i++) { ofVec2f vel(0,ofRandom(1.f) * -1); ofVec2f constrainPos( ofMap(forceEmitters[i].x, 0, 1024, 0.f, 1.f, true), ofMap(forceEmitters[i].y, 0, 768, 0.f, 1.f, true) ); const float colorMult = 100; const float velocityMult = 0.3; //addToFluid(forceEmitters[i], vel, true, true); int index = fluidSolver.getIndexForPos(constrainPos); fluidSolver.addForceAtIndex(index, vel * velocityMult); } if(ofGetFrameNum() % 2 == 0 ) { ofVec2f pos(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); ofVec2f vel(sin(ofGetFrameNum()), cos(ofGetFrameNum())); addToFluid(pos, vel, true, true); } } void testApp::draw() { glColor3f(0.3, 0.09, 0.07); //fluidDrawer.draw(0, 0, ofGetWidth(), ofGetHeight()); particleSystem.updateAndDraw( drawFluid ); } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ ofVec2f eventPos = ofVec2f(x, y); ofVec2f mouseNorm = ofVec2f( eventPos ) / ofGetWidth(); ofVec2f mouseVel = ofVec2f( eventPos - pMouse ) / ofVec2f(ofGetWidth(), ofGetHeight()); addToFluid( mouseNorm * ofVec2f( ofGetWindowSize()), mouseVel, true, true ); pMouse = eventPos; } void testApp::mousePressed(int x, int y, int button) { /*if(addForces) //{ ofVec2f eventPos = ofVec2f(x, y); ofVec2f mouseNorm = ofVec2f( eventPos ) / ofVec2f(ofGetWidth(), ofGetHeight()); ofVec2f mouseVel = ofVec2f( eventPos - pMouse ) / ofVec2f(ofGetWidth(), ofGetHeight()); //addToFluid( mouseNorm, mouseVel, false, true ); //addToFluid( eventPos, mouseVel, true, true ); mouseVel *= 100.f; //ofVec2f vel(0, -10.f); fluidSolver.addForceAtIndex(fluidSolver.getIndexForPos(eventPos), mouseVel); pMouse = eventPos; //}*/ } void testApp::mouseDragged(int x, int y, int button) { /*ofVec2f eventPos = ofVec2f(x, y); ofVec2f mouseNorm(eventPos.x/ofGetWidth(), eventPos.y/ofGetHeight()); ofVec2f mouseVel = ofVec2f( (eventPos.x - pMouse.x) / ofGetWidth(), (eventPos.y - pMouse.y) / ofGetHeight()); //addToFluid( mouseNorm, mouseVel, false, true ); addToFluid( mouseNorm, mouseVel, true, true ); pMouse = eventPos;*/ } void testApp::keyPressed (int key) { if(key == '1') { drawFluid = !drawFluid; } else if( key == '2') { drawParticles = !drawParticles; } else if( key == '3') { } else if( key == '4') { } else if( key == '5') { } else if( key == '6') { } } // add force and dye to fluid, and create particles void testApp::addToFluid( ofVec2f pos, ofVec2f vel, bool addColor, bool addForce ) { //float speed = vel.x * vel.x + vel.y * vel.y * getWindowAspectRatio() * getWindowAspectRatio(); //balance the x and y components of speed with the screen aspect ratio float aspectRatio = ofGetWidth()/ofGetHeight(); float speed = vel.x * vel.x + vel.y * vel.y * aspectRatio * aspectRatio; if(speed > 0) { ofVec2f constrainPos( ofMap(pos.x, 0, 1024, 0.f, 1.f, true), ofMap(pos.y, 0, 768, 0.f, 1.f, true) ); const float colorMult = 100; const float velocityMult = 30; int index = fluidSolver.getIndexForPos(constrainPos); if(addColor) { ofColor drawColor; drawColor.setHex(0x5E2612, 1.0); //drawColor.setHsb((ofGetFrameNum() % 360 ) / 360.0f, 1, 1); fluidSolver.addColorAtIndex(index, drawColor);// * colorMult); } //particleSystem.addParticles( pos * ofVec2f( ofGetWindowSize() ), 5 ); particleSystem.addParticles( pos, 3 ); //fluidSolver.addForceAtIndex(index, vel * velocityMult); } }
26.459596
110
0.650124
HellicarAndLewis
f0b16322c4cdb3ec8f95a8623130941f374af0aa
9,425
cpp
C++
ThreeDog/tdslider.cpp
602985142/TD-FrameWork
1870be856c01fd46d48c8f6db1ba10d97ad4127c
[ "MIT" ]
32
2017-03-02T11:12:21.000Z
2021-08-02T00:49:15.000Z
ThreeDog/tdslider.cpp
602985142/TD-FrameWork
1870be856c01fd46d48c8f6db1ba10d97ad4127c
[ "MIT" ]
1
2020-04-26T02:01:33.000Z
2020-04-26T09:14:13.000Z
ThreeDog/tdslider.cpp
602985142/TD-FrameWork
1870be856c01fd46d48c8f6db1ba10d97ad4127c
[ "MIT" ]
17
2017-03-09T06:10:32.000Z
2022-02-25T05:37:51.000Z
#if _MSC_BUILD #pragma execution_character_set("utf-8") #endif /************************************************************** * File Name : tdslider.cpp * Author : ThreeDog * Date : Tue Jan 03 15:59:31 2017 * Description : 自定义滑块窗体,参数传递底色,前景色和滑块颜色,采用绘图事件 * 在鼠标松开时触发操作,接口和QSlider尽量保持一致。 * **************************************************************/ #include "tdslider.h" #include <QDebug> TDSlider::TDSlider(TDWidget *parent,Qt::Orientation ot) :TDWidget(parent) { col_background = Qt::darkGray; col_front = Qt::lightGray; col_button = Qt::white; orientation = ot; minimum = 0; maximum = 100; slider_position = 0; slider_radius = 4; slider_width = 3; value = 0; ispress = false; } TDSlider::TDSlider(const QColor col_bak , const QColor col_fro , const QColor col_btn , TDWidget *parent , Qt::Orientation ot) :TDWidget(parent) { col_background = col_bak; col_front = col_fro; col_button = col_btn; orientation = ot; minimum = 0; maximum = 100; slider_position = 0; slider_radius = 4; slider_width = 3; value = 0; ispress = false; } //私有属性的外部接口 void TDSlider::setMinimum(const int min) { minimum = min; } void TDSlider::setMaximum(const int max) { maximum = max; } void TDSlider::setRange(const int min, const int max) { minimum = min; maximum = max; } void TDSlider::setOrientation(Qt::Orientation ot) { if(ot != orientation){ orientation = ot; //更换布局重绘 update(); } } void TDSlider::setSliderPosition(const int position) { //以像素为参数设置位置,注意如果是纵向,slider_position值得是从顶部到滑块的距离 if(Qt::Horizontal == orientation) slider_position = position; else if(Qt::Vertical == orientation){ slider_position = this->height()-position; } //重绘 update(); } void TDSlider::setValue(int v) { if(v < minimum) v = minimum; else if(v > maximum) v = maximum; this->value = v; //按照value的值在本窗体所占的比例改变位置 double val = value; double min = minimum; double max = maximum; //必须要用double,否则会整形除法会得出0 if(Qt::Horizontal == orientation){ double position = (val - min)/(max-min)*this->width(); slider_position = position; }else if(Qt::Vertical == orientation){ double position = (val - min)/(max-min)*this->height(); slider_position = this->height()-position; //垂直方向上用总高度减去position,得到距顶部的高度,才是需要的效果 } update(); } void TDSlider::setSliderWidth(const int width) { this->slider_width = width; update(); } void TDSlider::setSliderRadius(const int radius) { this->slider_radius = radius; update(); } void TDSlider::setBackgroundColor(const QColor &color) { this->col_background = color; } void TDSlider::setFrontColor(const QColor &color) { this->col_front = color; } void TDSlider::setButtonColor(const QColor &color) { this->col_button = color; } int TDSlider::getMinimum() const { return minimum; } int TDSlider::getMaximum() const { return maximum; } int TDSlider::getSliderPosition() const { if(Qt::Horizontal == orientation) return slider_position; else if(Qt::Vertical == orientation) return this->height() - slider_position; //注意如果是纵向的话,获取到的slider_position应该是从底部开始的 return -1; } int TDSlider::getValue() const { return this->value; } int TDSlider::getSliderWidth() const { return slider_width; } int TDSlider::getSliderRadius() const { return slider_radius; } TDSlider::~TDSlider() { } void TDSlider::paintEvent(QPaintEvent *) { //QRect四个参数 //left top width height!!!! QPainter p(this); //如果方向是水平方向 if(Qt::Horizontal == orientation){ //先更正滑块位置,如果位置小于半径,则设置为半径,如果位置大于宽度,设置为宽度-半径 if(slider_position < slider_radius/*/2+1*/) slider_position = slider_radius/*/2+2*/; if(slider_position > this->width()-slider_radius*5/4) slider_position = this->width()-slider_radius*5/4; QRect rect(0,slider_radius,this->width(),slider_width); //先绘制一个与窗体等长的背景色矩形 p.fillRect(rect,col_background); QRect rect2(0,slider_radius,slider_position,slider_width); //然后绘制一个从0到当前滑块位置的前景色矩形 p.fillRect(rect2,col_front); //圆心坐标 QPoint center(slider_position,slider_radius+slider_width/2); p.setBrush(col_button); p.setPen(col_button); //在的滑块的位置画一个半径为4的小圆,作为滑块 p.drawEllipse(center,slider_radius,slider_radius); }//如果方向是垂直方向 else if(Qt::Vertical == orientation){ //先更正滑块位置,如果位置大于高度,则设置为高度-5,如果位置小于3,设置为4 if(slider_position<slider_radius/*/2+1*/) slider_position = slider_radius/*/2+2*/; if(slider_position>this->height()-slider_radius*5/4) slider_position = this->height()-slider_radius*5/4; //注意此时的sliderposition位置是从上到下的距离 QRect rect(slider_radius,0,slider_width,this->height()); //注意竖着的矩形是从上往下画的,所以跟刚才反过来 //先用前景色画一个等高的矩形 p.fillRect(rect,col_front); QRect rect2(slider_radius,0,slider_width,slider_position); //再用背景色画一个从最高点到指定位置的矩形 p.fillRect(rect2,col_background); if(slider_position < slider_radius) slider_position = slider_radius; QPoint center(slider_radius+slider_width/2,slider_position); p.setBrush(col_button); p.setPen(col_button); //在滑块的位置画一个小圆作为滑块 p.drawEllipse(center,slider_radius,slider_radius); } } void TDSlider::mousePressEvent(QMouseEvent *e) { if(Qt::Horizontal == orientation){ //如果要是落在了范围之外,要把位置校准回来 if(e->x()>slider_radius && e->x()<this->width()-slider_radius*5/4) this->slider_position = e->pos().x(); else if(e->x() <= slider_radius) this->slider_position = slider_radius; else if(e->x() >= this->width()-slider_radius*5/4) this->slider_position = this->width()-slider_radius*5/4; update(); ispress = true; }else if(Qt::Vertical == orientation){ if(e->y() > slider_radius && e->y()<this->height()-slider_radius*5/4){ this->slider_position = e->pos().y(); }else if(e->y() < slider_radius){ this->slider_position = slider_radius; }else if(e->y() > this->height()-slider_radius*5/4){ this->slider_position = this->height()-slider_radius*5/4; } update(); ispress = true; } } void TDSlider::mouseReleaseEvent(QMouseEvent *e) { if(Qt::Horizontal == orientation){ if(e->x() > slider_radius && e->y()<this->width()-slider_radius*5/4) slider_position = e->pos().x(); //如果超出边界y就不再等于e.y() double x = e->pos().x(); if(e->x() < 0) x = 0; if(e->x() > this->width()) x = this->width(); double w = this->width(); //发送数值改变信号,通过相对位置计算得到数值大小 double value = x/w*(maximum-minimum)+minimum; emit valueChanged(value); emit positionChanged(x); }else if(Qt::Vertical == orientation){ if(e->y()>slider_radius && e->y()<this->height()-slider_radius*5/4) slider_position = e->pos().y(); //如果超出边界y就不再等于e.y() double y = e->y(); if(e->y()< 0) y = 0; else if(e->y()>this->height()) y = this->height(); double w = this->height(); //发送数值改变信号,通过相对位置计算得到数值大小 //而垂直方向的是从顶部到滑槽点的距离,所以value要减一下 double value = maximum - y/w*(maximum-minimum); //注意锁定范围 emit valueChanged(value); emit positionChanged(this->height()-y);//同样这里要用高度减一下 } update(); ispress = false; } void TDSlider::mouseMoveEvent(QMouseEvent *e) { if(Qt::Horizontal == orientation){ if(e->x()>slider_radius && e->x()<this->width()-slider_radius*5/4){ this->slider_position = e->pos().x(); }else if(e->x() <= slider_radius){ this->slider_position = slider_radius; }else if(e->x() >= this->width()-slider_radius*5/4){ this->slider_position = this->width()-slider_radius*5/4; } //以上校准滑块位置 //以下校准发送的数据 double x = e->pos().x(); if(x < 0) x = 0; if(x > this->width()) x = this->width(); double w = this->width(); double value = x/w*(maximum-minimum)+minimum; emit valueChanging(value); emit positionChanging(x); }else if(Qt::Vertical == orientation){ if(e->y()> slider_radius &&e->y()<this->height()-slider_radius*5/4){ this->slider_position = e->pos().y(); }else if(e->y() < slider_radius){ this->slider_position = slider_radius; }else if(e->y() > this->height()-slider_radius*5/4){ this->slider_position = this->height()-slider_radius*5/4; } //以上校准滑块位置 //以下校准发送的数据 double y = e->y(); if(e->y()< 0) y = 0; else if(e->y()>this->height()) y = this->height(); double w = this->height(); //发送数值改变信号,通过相对位置计算得到数值大小 //而垂直方向的是从顶部到滑槽点的距离,所以value要减一下 double value = maximum - y/w*(maximum-minimum); emit valueChanging(value); emit positionChanging(this->height() - y);//同样这里要用高度减一下 } update(); }
27.318841
78
0.588117
602985142
f0b2cef226b8716776d3bba24c7fd46eca6389cb
363
cpp
C++
Covid19QuizApp/studentgraderecord.cpp
AnkitKafle2020/HonorsProject
f02488e46ec06728c6edd4803781aeea87808867
[ "MIT" ]
null
null
null
Covid19QuizApp/studentgraderecord.cpp
AnkitKafle2020/HonorsProject
f02488e46ec06728c6edd4803781aeea87808867
[ "MIT" ]
null
null
null
Covid19QuizApp/studentgraderecord.cpp
AnkitKafle2020/HonorsProject
f02488e46ec06728c6edd4803781aeea87808867
[ "MIT" ]
null
null
null
#include "studentgraderecord.h" #include "ui_studentgraderecord.h" studentGradeRecord::studentGradeRecord(QWidget *parent) : QDialog(parent), ui(new Ui::studentGradeRecord) { ui->setupUi(this); } studentGradeRecord::~studentGradeRecord() { delete ui; } void studentGradeRecord::on_buttonBox_accepted() { this->close(); }
18.15
58
0.69146
AnkitKafle2020
f0c56e520757162ecc9caff4bfa7b063bbf65c3f
4,147
cpp
C++
book_samples/birds-eye/opencv-birdsEyeView.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
220
2016-03-20T00:48:58.000Z
2022-03-31T09:46:21.000Z
book_samples/birds-eye/opencv-birdsEyeView.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
28
2016-06-16T19:17:41.000Z
2021-09-16T16:19:18.000Z
book_samples/birds-eye/opencv-birdsEyeView.cpp
jwinarske/openvx_tutorial
3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c
[ "MIT" ]
84
2016-03-24T01:13:07.000Z
2022-03-22T04:37:03.000Z
/* * Copyright (c) 2019 Victor Erukhimov * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /*! * \file opencv-birdsEyeView.cpp * \example opencv-birdsEyeView * \brief This sample implements the bird's eye view algorithm from * the OpenVX sample birdsEyeView.c using OpenCV. * \author Victor Erukhimov <relrotciv@gmail.com> */ #include <math.h> #include <opencv2/opencv.hpp> using namespace cv; int main(int argc, char** argv) { if(argc != 3) { printf("opencv-birdsEyeView <input image> <output image>\n"); exit(0); } Mat input = imread(argv[1]); Mat temp; Mat K = (Mat_<float>(3,3) << 8.4026236186715255e+02, 0., 3.7724917600845038e+02, 0., 8.3752885759166338e+02, 4.6712164335800873e+02, 0., 0., 1.); K = K*4.0f; K.at<float>(2, 2) = 1.0f; std::cout << "K = " << K << std::endl; std::cout << "Kinv = " << K.inv() << std::endl; Point3f p0(482.0f*4, 332.0f*4, 1.0f); Point3f pu = Mat(K.inv()*Mat(p0)).at<Point3f>(0); float phi = acos(-1) + atan(1.0f/pu.y); std::cout << "p0 = (" << p0 << "), pu = (" << pu << "), phi = " << phi << std::endl; // calculate homography, rotation around x axis to make the camera look down Mat H1 = Mat::zeros(3, 3, CV_32F); H1.at<float>(0, 0) = 1.0f; H1.at<float>(1, 1) = cos(phi); H1.at<float>(1, 2) = sin(phi); H1.at<float>(2, 1) = -sin(phi); H1.at<float>(2, 2) = cos(phi); std::cout << "phi = " << phi << std::endl; std::cout << "H1 = " << H1 << std::endl; // now we need to adjust offset and scale to map input image to // visible coordinates in the output image. Mat H = K*H1*K.inv(); const Point3f p1(p0.x, p0.y*1.2, 1); const Point3f p2(p0.x, input.rows, 1); Point3f p1h = Mat(H*Mat(p1)).at<Point3f>(0, 0); p1h *= 1/p1h.z; Point3f p2h = Mat(H*Mat(p2)).at<Point3f>(0, 0); p2h *= 1/p2h.z; Mat scaleY = Mat::eye(3, 3, CV_32F); float scale = (p2h.y - p1h.y)/input.rows; scaleY.at<float>(0, 2) = input.cols*scale/2 - p0.x; scaleY.at<float>(1, 2) = -p1h.y; scaleY.at<float>(2, 2) = scale; std::cout << "scaleY = " << scaleY << std::endl << std::endl; std::cout << "H = " << H << std::endl << std::endl; std::cout << "K*H1 = " << K*H1 << std::endl << std::endl; H = scaleY*H; std::cout << "scaleY*H = " << H << std::endl << std::endl; Point3f corners[]= {Point3f(0, p0.y*1.15, 1), Point3f(input.cols, p0.y*1.15, 1), Point3f(input.cols, input.rows, 1), Point3f(0, input.rows, 1), p0, Point3f(p0.x, p0.y*1.1, 1)}; for(int i = 0; i < sizeof(corners)/sizeof(Point3f); i++) { Point3f ph1 = Mat(K.inv()*Mat(corners[i])).at<Point3f>(0, 0); Point3f ph2 = Mat(H*Mat(corners[i])).at<Point3f>(0, 0); std::cout << "point " << i << " maps to: " << std::endl << " uni: (" << ph1.x/ph1.z << " " << ph1.y/ph1.z << ")" << std::endl << " output: (" << ph2.x/ph2.z << " " << ph2.y/ph2.z << ")" << std::endl; } Mat output; warpPerspective(input, output, H, input.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0)); imwrite(argv[2], output); return(0); }
35.444444
98
0.612732
jwinarske
f0d18f2ca2a4029e18003345fd3bd89a24db5f9f
1,610
cpp
C++
EZOJ/Contests/1533/A.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
EZOJ/Contests/1533/A.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1533/A.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <map> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool neg=c=='-'; neg?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return neg?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} template<class T>inline void mset(T a[],int v,int n){memset(a,v,n*sizeof(T));} template<class T>inline void mcpy(T a[],T b[],int n){memcpy(a,b,n*sizeof(T));} const int N=100010,D=52,O=1e9+7; bool vis[D]; int basis; struct State{ int cnt[D]; inline friend bool operator < (const State &a,const State &b){ for(int i=0;i<D;i++){ if(!vis[i])continue; int ta=a.cnt[i]-a.cnt[basis]; int tb=b.cnt[i]-b.cnt[basis]; if(ta!=tb)return ta<tb; } return false; } }; char s[N]; int c[N]; int main(){ #ifndef ONLINE_JUDGE freopen("magic.in","r",stdin); freopen("magic.out","w",stdout); #endif const int n=ni; scanf("%s",s); mset(vis,0,D); for(int i=0;i<n;i++){ c[i]=s[i]>='A'&&s[i]<='Z'?(s[i]-'A'):(s[i]-'a'+D/2); vis[c[i]]=true; } basis=c[0]; typedef map<State,int>mp; mp m; State cur; mset(cur.cnt,0,D); ++m[cur]; for(int i=0;i<n;i++){ ++cur.cnt[c[i]]; ++m[cur]; } lint ans=0; for(mp::iterator it=m.begin(),ti=m.end();it!=ti;++it){ ans+=(lint)it->second*(it->second-1); } ans>>=1; ans%=O; printf("%lld\n",ans); return 0; }
22.676056
78
0.612422
sshockwave
f0d1b0143f4b0c30385f92e8e22f006dce6403c9
4,405
cpp
C++
src/net/host.cpp
suprafun/smalltowns
c722da7dd3a1d210d07f22a6c322117b540e63da
[ "BSD-3-Clause" ]
null
null
null
src/net/host.cpp
suprafun/smalltowns
c722da7dd3a1d210d07f22a6c322117b540e63da
[ "BSD-3-Clause" ]
null
null
null
src/net/host.cpp
suprafun/smalltowns
c722da7dd3a1d210d07f22a6c322117b540e63da
[ "BSD-3-Clause" ]
null
null
null
/********************************************* * * Author: David Athay * * License: New BSD License * * Copyright (c) 2009, CT Games * 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 CT Games 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. * * * Date of file creation: 09-01-28 * * $Id$ * ********************************************/ #include "host.h" #include "packet.h" namespace ST { Host::Host(): mServer(NULL), mConnected(false) { // create a new client host for connecting to the server #ifdef ENET_VERSION mClient = enet_host_create(NULL, 1, 0, 57600 / 8, 14400 / 8); #else mClient = enet_host_create (NULL /* create a client host */, 1 /* only allow 1 outgoing connection */, 57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */, 14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */); #endif } Host::~Host() { enet_host_destroy(mClient); } void Host::connect(const std::string &hostname, unsigned int port) { // set the address of the server to connect to enet_address_set_host(&mAddress, hostname.c_str()); mAddress.port = port; // connect to the server #ifdef ENET_VERSION mServer = enet_host_connect(mClient, &mAddress, 0, 1); #else mServer = enet_host_connect (mClient, &mAddress, 1); #endif } void Host::process() { // check for data ENetEvent event; while (enet_host_service(mClient, &event, 0) > 0) { switch (event.type) { case ENET_EVENT_TYPE_CONNECT: { mConnected = true; } break; case ENET_EVENT_TYPE_RECEIVE: { Packet *packet = new Packet((char*)event.packet->data, event.packet->dataLength); mPackets.push_back(packet); enet_packet_destroy (event.packet); } break; case ENET_EVENT_TYPE_DISCONNECT: { mConnected = false; } break; } } } Packet* Host::getPacket() { if (mPackets.size() > 0) { Packet *p = mPackets.front(); mPackets.pop_front(); return p; } return NULL; } bool Host::isConnected() { return mConnected; } void Host::disconnect() { if (mServer) enet_peer_disconnect(mServer, 0); } void Host::sendPacket(Packet *packet) { if (packet && mServer) { ENetPacket *p = enet_packet_create(packet->getData(), packet->getSize(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(mServer, 0, p); enet_host_flush(mClient); } } }
31.241135
87
0.585244
suprafun
f0d76724b9ab2ec34a634810f883c1294812b1ac
496
cpp
C++
cpp/example/tst/UniquePaths/UniquePaths-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:33:45.000Z
2022-01-26T16:33:45.000Z
cpp/example/tst/UniquePaths/UniquePaths-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
null
null
null
cpp/example/tst/UniquePaths/UniquePaths-test.cpp
zcemycl/algoTest
9518fb2b60fd83c85aeb2ab809ff647aaf643f0a
[ "MIT" ]
1
2022-01-26T16:35:44.000Z
2022-01-26T16:35:44.000Z
#include "UniquePaths/uniquePaths.h" #include "gtest/gtest.h" using namespace std; class uniquePaths_MultipleParamsTests : public ::testing::TestWithParam<tuple<int,int>>{ }; TEST_P(uniquePaths_MultipleParamsTests, CheckAns){ int n = get<0>(GetParam()); int expected = get<1>(GetParam()); ASSERT_EQ(expected,uniquePaths::naive(n)); }; INSTANTIATE_TEST_CASE_P( UniquePathsTests, uniquePaths_MultipleParamsTests, ::testing::Values( make_tuple(0,0) ) );
21.565217
52
0.707661
zcemycl
f0d81a94aabc5bc8a7cde7a0a09ce3ea042bd277
234
hpp
C++
src/gfx/Mesh.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/gfx/Mesh.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/gfx/Mesh.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#pragma once #include "SubMesh.hpp" namespace ari::gfx { ARI_HANDLE(MeshHandle) struct Mesh { core::Array<SubMeshHandle> SubMeshes; }; Mesh* GetMesh(const MeshHandle& mesh_handle); } // namespace ari::gfx
13.764706
47
0.662393
kochol
f0d8d3537216398725a220d921ed107a5a2274f0
584
cpp
C++
sbb/primeNumbers.cpp
cwboden/coding-practice
a80aea59d57bfdd55c15ef2fdf01f73aff168031
[ "MIT" ]
null
null
null
sbb/primeNumbers.cpp
cwboden/coding-practice
a80aea59d57bfdd55c15ef2fdf01f73aff168031
[ "MIT" ]
null
null
null
sbb/primeNumbers.cpp
cwboden/coding-practice
a80aea59d57bfdd55c15ef2fdf01f73aff168031
[ "MIT" ]
null
null
null
// Carson Boden / November 2016 // Prints out prime numbers between 1 and 100,000 int main() { // Range from 1 to 100,000 for (size_t i = 1; i <= 100000; ++i) { // Flag to confirm if number is prime bool isPrime = true; // Checks factors up to half of the number (Since 2 is the smallest divisor) for (size_t j = 2; j <= i / 2; ++j) { // If the number i is cleanly divisible if (i % j == 0) { isPrime = false; break; } // if } // for // Print the number if it's prime if (isPrime) { cout << i << endl; } // if } // for return 0; }
17.69697
78
0.568493
cwboden
f0db573b0382faf97c1e7879f93c59c9c55ad1d5
10,931
cpp
C++
graphics/cgal/Triangulation_3/benchmark/Triangulation_3/Triangulation_benchmark_3.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/cgal/Triangulation_3/benchmark/Triangulation_3/Triangulation_benchmark_3.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/cgal/Triangulation_3/benchmark/Triangulation_3/Triangulation_benchmark_3.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
// Benchmark program for the Triangulation_3 package. // // Sylvain Pion, 2009. // // The data produced by this program is meant to be used // in the Benchmarks section of the User Manual. // // We measure : // - construction time // - point location time function of triangulation size // - vertex removal time // - memory usage // // And this, for the following 4 configurations : // - Delaunay // - Delaunay<Fast_location> // - Regular // - Regular<hidden points discarded> // // Notes : // - points are randomly generated using drand48() // - weights are zero for regular // // TODO (?) : // - impact of the choice of various kernels // - impact of the kind of data set ? More or less degenerate... // - replace drand48() by CGAL Generators // - move/document Time_accumulator to CGAL/Profiling_tools (?) #define CGAL_TRIANGULATION_3_PROFILING //#define CGAL_CONCURRENT_TRIANGULATION_3_ADD_TEMPORARY_POINTS_ON_FAR_SPHERE #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Bbox_3.h> #include <CGAL/Delaunay_triangulation_3.h> #include <CGAL/Regular_triangulation_3.h> #include <CGAL/Regular_triangulation_euclidean_traits_3.h> #include <CGAL/Random.h> #include <CGAL/Real_timer.h> #include <CGAL/Memory_sizer.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> // for drand48 #ifdef SHOW_ITERATIONS # undef SHOW_ITERATIONS # define SHOW_ITERATIONS "\t( " << iterations << " iterations used)" << endl #else # define SHOW_ITERATIONS endl #endif #ifndef BENCH_MIN_TIME # define BENCH_MIN_TIME 1 // minimum time for a bench #endif using namespace std; using namespace CGAL; // Choose the kernel type by defining one of those macros: // - SC_DOUBLE, // - EPEC, // - or EPIC (the default) #ifdef SC_DOUBLE typedef Simple_cartesian<double> K; #elif C_LEDA # include <CGAL/leda_rational.h> # include <CGAL/Cartesian.h> typedef Cartesian<leda_rational> K; #elif defined(ONLY_STATIC_FILTERS) typedef CGAL::internal::Static_filters<CGAL::Simple_cartesian<double> > K; #elif defined(EPEC) # ifdef CGAL_DONT_USE_LAZY_KERNEL typedef Epeck K; # else // not CGAL_DONT_USE_LAZY_KERNEL # ifdef CGAL_USE_LEDA # include <CGAL/leda_rational.h> # include <CGAL/Cartesian.h> typedef Cartesian<leda_rational> SK; # else // not CGAL_USE_LEDA typedef Simple_cartesian<Gmpq> SK; # endif // not CGAL_USE_LEDA typedef Lazy_kernel<SK> K; # endif // not CGAL_DONT_USE_LAZY_KERNEL #else // EPIC typedef Exact_predicates_inexact_constructions_kernel K; #endif // EPIC typedef Regular_triangulation_euclidean_traits_3<K> WK; typedef K::Point_3 Point; #ifdef CGAL_CONCURRENT_TRIANGULATION_3 typedef CGAL::Spatial_lock_grid_3< CGAL::Tag_priority_blocking> Lock_ds; // Delaunay T3 typedef CGAL::Triangulation_data_structure_3< CGAL::Triangulation_vertex_base_3<K>, CGAL::Triangulation_cell_base_3<K>, CGAL::Parallel_tag > DT_Tds; typedef CGAL::Delaunay_triangulation_3< K, DT_Tds, CGAL::Default, Lock_ds> DT3; /*typedef CGAL::Delaunay_triangulation_3< K, DT_Tds, Fast_location, Lock_ds> DT3_FastLoc;*/ // (no parallel fast location for now) // Regular T3 with hidden points kept typedef CGAL::Triangulation_data_structure_3< CGAL::Triangulation_vertex_base_3<WK>, CGAL::Regular_triangulation_cell_base_3<WK>, CGAL::Parallel_tag> RT_Tds_WithHP; typedef CGAL::Regular_triangulation_3< WK, RT_Tds_WithHP, Lock_ds> RT3_WithHP; // Regular T3 with hidden points discarded typedef CGAL::Triangulation_data_structure_3< CGAL::Triangulation_vertex_base_3<WK>, CGAL::Triangulation_cell_base_3<WK>, CGAL::Parallel_tag > RT_Tds_NoHP; typedef CGAL::Regular_triangulation_3< WK, RT_Tds_NoHP, Lock_ds> RT3_NoHP; #else typedef CGAL::Delaunay_triangulation_3<K> DT3; typedef CGAL::Delaunay_triangulation_3<K, Fast_location> DT3_FastLoc; // Regular T3 with hidden points kept typedef CGAL::Regular_triangulation_3<WK> RT3_WithHP; // Regular T3 with hidden points discarded typedef CGAL::Triangulation_data_structure_3< CGAL::Triangulation_vertex_base_3<WK>, CGAL::Triangulation_cell_base_3<WK> > RT_Tds_NoHP; typedef CGAL::Regular_triangulation_3<WK, RT_Tds_NoHP> RT3_NoHP; #endif vector<Point> pts, pts2; Bbox_3 pts_bbox, pts2_bbox; size_t min_pts = 100; size_t max_pts = 1000000; bool input_file_selected = false; std::ifstream input_file; class Time_accumulator { double &accumulator; Real_timer timer; public: Time_accumulator(double &acc) : accumulator(acc) { timer.reset(); timer.start(); } ~Time_accumulator() { timer.stop(); accumulator += timer.time(); } }; #define drand48 CGAL::get_default_random().get_double Point rnd_point() { return Point(drand48(), drand48(), drand48()); } void generate_points() { if (input_file_selected) { Point p; if (input_file >> p) { pts.push_back(p); pts_bbox = Bbox_3(p.bbox()); while (input_file >> p) { pts.push_back(p); pts_bbox = pts_bbox + p.bbox(); } } cout << " [ Read " << pts.size() << " points from file ] " << endl; min_pts = max_pts = pts.size(); } else { pts.reserve(max_pts); pts2.reserve(max_pts); Point p = rnd_point(); pts.push_back(p); pts_bbox = Bbox_3(p.bbox()); p = rnd_point(); pts2.push_back(p); pts2_bbox = Bbox_3(p.bbox()); for(size_t i = 1; i < (std::max)(std::size_t(100000), max_pts); ++i) { p = rnd_point(); pts.push_back(p); pts_bbox = pts_bbox + p.bbox(); p = rnd_point(); pts2.push_back(p); pts2_bbox = pts2_bbox + p.bbox(); } } cout << "Bounding box = " << "[" << pts_bbox.xmin() << ", " << pts_bbox.xmax() << "], " << "[" << pts_bbox.ymin() << ", " << pts_bbox.ymax() << "], " << "[" << pts_bbox.zmin() << ", " << pts_bbox.zmax() << "]" << endl; } // Triangulation construction template < typename Tr > void benchmark_construction() { cout << "\nTriangulation construction : " << endl; cout << "#pts\tTime" << endl; size_t mem_size_init = Memory_sizer().virtual_size(); size_t mem_size = 0; for (size_t nb_pts = min_pts; nb_pts <= max_pts; nb_pts *= 10) { double time = 0; size_t iterations = 0; do { ++iterations; Time_accumulator tt(time); #ifdef CGAL_CONCURRENT_TRIANGULATION_3 Lock_ds locking_ds(pts_bbox, 50); Tr tr(pts.begin(), pts.begin() + nb_pts, &locking_ds); #else Tr tr(pts.begin(), pts.begin() + nb_pts); #endif mem_size = Memory_sizer().virtual_size(); // cout << "#vertices = " << tr.number_of_vertices() << endl; // cout << "#cells = " << tr.number_of_cells() << endl; } while (time < BENCH_MIN_TIME); cout << nb_pts << "\t" << time/iterations << SHOW_ITERATIONS; } cout << "\nMemory usage : " << (mem_size - mem_size_init)*1./max_pts << " Bytes/Point" << " (observed for the largest data set, and may be unreliable)" << endl; } // Point location template < typename Tr > void benchmark_location() { cout << "\nPoint location : " << endl; cout << "#pts\tTime" << endl; for (size_t nb_pts = min_pts; nb_pts <= max_pts; nb_pts *= 10) { #ifdef CGAL_CONCURRENT_TRIANGULATION_3 Lock_ds locking_ds(pts_bbox, 50); Tr tr(pts.begin(), pts.begin() + nb_pts, &locking_ds); #else Tr tr(pts.begin(), pts.begin() + nb_pts); #endif double time = 0; size_t iterations = 0; do { ++iterations; Time_accumulator tt(time); // We do chunks of 100000 point locations at once. for(size_t i = 0; i < 100000; ++i) tr.locate(pts2[i]); } while (time < BENCH_MIN_TIME); cout << nb_pts << "\t" << (time/iterations)/100000 << SHOW_ITERATIONS; } } // Vertex removal template < typename Tr > void benchmark_remove() { typedef typename Tr::Vertex_handle Vertex_handle; typedef typename Tr::Vertex_iterator Vertex_iterator; cout << "\nVertex removal : " << endl; cout << "#pts\tTime\tTime/removal" << endl; size_t nb_pts = 1000000; // only one size of triangulation hard-coded. const size_t NUM_VERTICES_TO_REMOVE = 100000; double time = 0; size_t iterations = 0; if (nb_pts > max_pts) { std::cerr << "ERROR: nb_pts > max_pts. Cancelling..." << std::endl; return; } do { #ifdef CGAL_CONCURRENT_TRIANGULATION_3 Lock_ds locking_ds(pts_bbox, 50); Tr tr(pts.begin(), pts.begin() + nb_pts, &locking_ds); #else Tr tr(pts.begin(), pts.begin() + nb_pts); #endif vector<Vertex_handle> vhs; for (Vertex_iterator vit = tr.finite_vertices_begin(), end = tr.finite_vertices_end(); vit != end; ++vit) vhs.push_back(vit); Time_accumulator tt(time); tr.remove(&vhs[0], &vhs[NUM_VERTICES_TO_REMOVE - 1]); ++iterations; //std::cout<<"\b\b\b\b\b\b"<<i<<std::flush; //tr.is_valid(); } } while (time < BENCH_MIN_TIME); cout << NUM_VERTICES_TO_REMOVE << "\t" << (time/iterations) << "\t" << (time/iterations)/NUM_VERTICES_TO_REMOVE << SHOW_ITERATIONS; } template < typename Tr > void do_benchmarks(string name) { cout << "\n\nBenchmarking configuration : " << name << endl; // tbb::task_scheduler_init tbb_init(10); // Set number of threads benchmark_construction<Tr>(); if (input_file_selected) return; benchmark_location<Tr>(); benchmark_remove<Tr>(); } int main(int argc, char **argv) { if (argc >= 2) { input_file.open(argv[1], std::ios::in); if (input_file.is_open()) input_file_selected = true; else { input_file_selected = false; max_pts = atoi(argv[1]); } } cout << "Usage : " << argv[0] << " [filename]" << " [max_points = " << max_pts << ", and please use a power of 10]" << endl; cout << "Benchmarking the Triangulation_3 package for "; if (input_file_selected) cout << "data file : " << argv[1] << endl; else cout << "up to " << max_pts << " random points." << endl; cout.precision(3); generate_points(); cout << "\nProcessor : " << ((sizeof(void*)==4) ? 32 : (sizeof(void*)==8) ? 64 : -1) << " bits\n"; cout << "Kernel typeid: " << typeid(K).name() << "\n"; do_benchmarks<DT3>("Delaunay [Compact_location]"); if (input_file_selected) return 0; #ifndef CGAL_CONCURRENT_TRIANGULATION_3 do_benchmarks<DT3_FastLoc>("Delaunay with Fast_location"); #endif do_benchmarks<RT3_WithHP>("Regular [with hidden points kept, except there's none in the data sets]"); do_benchmarks<RT3_NoHP>("Regular with hidden points discarded"); }
29.86612
104
0.654377
hlzz
f0db72dce53a713876d31a7f4dbb58d6e20f8f3b
2,273
cpp
C++
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
/** * * Author : D.Dinesh * Licence : Refer the license file * **/ #include "Callflow.h" struct Node { int m_line; int m_level; Node *m_next; const char *m_szFunc; const char *m_szFile; }; static int g_level = 0; static Node *g_base = 0; static Node *g_last = 0; static int g_max_level = 0; static void ShutCallflow(int sig); static int SslExistAtLevel(int level, Node *node); static void InitCallflow() __attribute__((constructor)); static void InitCallflow() { static Node node; g_last = g_base = &node; signal(SIGSEGV, ShutCallflow); } static int SslExistAtLevel(int level, Node *node) { for(node = node->m_next; node; node = node->m_next) if(node->m_level < level) return 0; else if(node->m_level == level) return 1; return 0; } static void ShutCallflow(int sig) { Node *node = g_base->m_next; bool *pSsl = new bool[g_max_level - 1]; /* succeeding sibling */ printf("%s [%s:%d]\n", node->m_szFunc, node->m_szFile, node->m_line); for(node = node->m_next; node; node = node->m_next) { /* I -> Index */ /* L -> Level */ /* M -> Memory */ int I = 0; int M = node->m_level - 1; memset(pSsl, true, g_max_level - 1); for(int L = 1; L < M; L++) { I = L - 1; if(pSsl[I]) { pSsl[I] = SslExistAtLevel(L + 1, node); if(pSsl[I]) printf("| "); else printf(" "); } else { printf(" "); } } if(0 == node->m_next || node->m_level > node->m_next->m_level || (node->m_level < node->m_next->m_level && !SslExistAtLevel(node->m_next->m_level - 1, node->m_next))) putchar('`'); else putchar('|'); printf("-- %s [%s:%d]\n", node->m_szFunc, node->m_szFile, node->m_line); } exit(0); } Callflow::Callflow(int line, const char *szFunc, const char *szFile) { g_level++; if(g_level > g_max_level) g_max_level = g_level; Node *node = new Node; node->m_next = 0; node->m_line = line; node->m_level = g_level; node->m_szFunc = szFunc; node->m_szFile = szFile; g_last->m_next = node; g_last = node; } Callflow::~Callflow() { g_level--; }
20.853211
78
0.556093
DineshDevaraj
f0de20d8f5185bf47585f5d7a7b526d35f267688
558
cc
C++
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
#include "draw/table.hpp" using namespace Faceless; int main() { Table table; Terminal term; table[0][0].setContent("root ").setAlign(Cell::Right).setFiller('-'); table[0][1].setContent("--> child1 ").setAlign(Cell::Right).setFiller('-'); table[0][2].setContent("--> child2 ").setAlign(Cell::Right).setFiller('-'); table[1][2].setContent("|-> child3 ").setAlign(Cell::Left).setFiller('-'); table[1][1].setContent("| ").setAlign(Cell::Left); table[2][1].setContent("|-> child4 ").setAlign(Cell::Left).setFiller('-'); table.dump(term); }
37.2
79
0.639785
FacelessManipulator
f0e216d09ebc3a5af228ec7be530f0fcf5bcee62
3,106
cpp
C++
LUPI/Test/alias/alias.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
LUPI/Test/alias/alias.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
LUPI/Test/alias/alias.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
/* # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> */ #include <stdlib.h> #include <iostream> #include <LUPI.hpp> static char const *description = "The alias checker."; void main2( int argc, char **argv ); /* ========================================================= */ int main( int argc, char **argv ) { try { main2( argc, argv ); } catch (std::exception &exception) { std::cerr << exception.what( ) << std::endl; exit( EXIT_FAILURE ); } catch (char const *str) { std::cerr << str << std::endl; exit( EXIT_FAILURE ); } catch (std::string &str) { std::cerr << str << std::endl; exit( EXIT_FAILURE ); } exit( EXIT_SUCCESS ); } /* ========================================================= */ void main2( int argc, char **argv ) { LUPI::ArgumentParser argumentParser( __FILE__, description ); LUPI::OptionTrue *optionTrue = argumentParser.add<LUPI::OptionTrue>( "--true", "First option with aliases." ); argumentParser.addAlias( "--true", "-t" ); argumentParser.addAlias( "--true", "-y" ); argumentParser.addAlias( "--true", "-yes" ); argumentParser.addAlias( optionTrue, "--yeap" ); LUPI::OptionFalse *optionFalse = argumentParser.add<LUPI::OptionFalse>( "--false", "Testing the 'OptionFalse' class." ); LUPI::OptionCounter *optionCounter = argumentParser.add<LUPI::OptionCounter>( "--veryVeryLongCounterNameVeryVeryLong", "A very long counter name, very long." ); argumentParser.addAlias( optionCounter, "-v" ); LUPI::OptionStore *optionStore = argumentParser.add<LUPI::OptionStore>( "--store", "The path to a pops file to load." ); LUPI::OptionAppend *optionAppend = argumentParser.add<LUPI::OptionAppend>( "--pops", "Second option with aliases.", 0, -1 ); argumentParser.addAlias( "--pops", "-p" ); argumentParser.addAlias( "--pops", "--pop" ); argumentParser.parse( argc, argv ); std::cout << " " << optionTrue->name( ) << " option: number entered " << optionTrue->numberEntered( ) << ", value = " << optionTrue->value( ) << std::endl; std::cout << " " << optionFalse->name( ) << " option: number entered " << optionFalse->numberEntered( ) << ", value = " << optionFalse->value( ) << std::endl; std::cout << " " << optionCounter->name( ) << " option: number entered " << optionCounter->numberEntered( ) << ", counts = " << optionCounter->counts( ) << std::endl; std::cout << " " << optionStore->name( ) << " option: number entered " << optionStore->numberEntered( ) << ", value = '" << optionStore->value( ) << "'" << std::endl; std::cout << " " << optionAppend->name( ) << " option: number entered " << optionAppend->numberEntered( ) << std::endl; std::cout << " "; for( int index = 0; index < optionAppend->numberEntered( ); ++index ) { std::cout << " '" << optionAppend->value( index ) << "'"; } std::cout << std::endl; }
40.337662
175
0.580167
Mathnerd314
f0e57372332d296a00d367ae4aacf0908d850604
7,712
cc
C++
case_studies/allocate/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
case_studies/allocate/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
case_studies/allocate/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
#include <cassert> #include <cstdio> #include <cstring> #include <vector> #include <hpx/hpx.h> // The size of the array - this is to mimic the DASHMM use case constexpr size_t kRecordSize = 48; constexpr size_t kNumRecords = 2000000; constexpr size_t kArraySize = kRecordSize * kNumRecords; // The size of the LCO data constexpr size_t kKB = 1024; constexpr size_t kLCOInitSize = kKB; constexpr size_t kLCOSize = 4 * kKB; // The number of LCOs - this will scale with the number of particles constexpr size_t kPrefactor = 10; constexpr size_t kLCOCount = kPrefactor * kNumRecords / 40; // The size of the 'local' memory allocation constexpr size_t kLocalAllocCount = 300000000; struct Junk { char data[24]; }; struct Data { int count; char payload[]; }; void init_handler(Data *i, size_t bytes, Data *init, size_t init_bytes) { i->count = 1; memcpy(i->payload, init, init_bytes); } HPX_ACTION(HPX_FUNCTION, HPX_ATTR_NONE, init_action, init_handler, HPX_POINTER, HPX_SIZE_T, HPX_POINTER, HPX_SIZE_T); void operation_handler(Data *lhs, const void *rhs, size_t bytes) { lhs->count -= 1; memcpy(lhs->payload, rhs, bytes); } HPX_ACTION(HPX_FUNCTION, HPX_ATTR_NONE, operation_action, operation_handler, HPX_POINTER, HPX_POINTER, HPX_SIZE_T); bool predicate_handler(const Data *i, size_t bytes) { return (i->count == 0); } HPX_ACTION(HPX_FUNCTION, HPX_ATTR_NONE, predicate_action, predicate_handler, HPX_POINTER, HPX_SIZE_T); // We have to forward declare the handler because this is a recursive action int lco_tree_alloc_handler(size_t idx, hpx_addr_t *lcos, hpx_addr_t done); HPX_ACTION(HPX_DEFAULT, HPX_ATTR_NONE, lco_tree_alloc_action, lco_tree_alloc_handler, HPX_SIZE_T, HPX_POINTER, HPX_ADDR); int lco_tree_set_handler(size_t idx, hpx_addr_t *lcos, hpx_addr_t done); HPX_ACTION(HPX_DEFAULT, HPX_ATTR_NONE, lco_tree_set_action, lco_tree_set_handler, HPX_SIZE_T, HPX_POINTER, HPX_ADDR); // This is a tree spawn that treats the array as if it were an implicit binary // tree. If needed, we could do this instead as an implicit octtree to better // match the DASHMM case. int lco_tree_alloc_handler(size_t idx, hpx_addr_t *lcos, hpx_addr_t done) { // create child done detection lco hpx_addr_t cdone = hpx_lco_and_new(2); assert(cdone != HPX_NULL); // spawn work at children if they exist size_t l_child = 2 * idx + 1; if (l_child < kLCOCount) { hpx_call(HPX_HERE, lco_tree_alloc_action, HPX_NULL, &l_child, &lcos, &cdone); } else { hpx_lco_and_set(cdone, HPX_NULL); } size_t r_child = 2 * idx + 2; if (r_child < kLCOCount) { hpx_call(HPX_HERE, lco_tree_alloc_action, HPX_NULL, &r_child, &lcos, &cdone); } else { hpx_lco_and_set(cdone, HPX_NULL); } // allocate my lco //lcos[idx] = hpx_lco_future_new(kLCOSize); char *initdata = new char[kLCOInitSize]; lcos[idx] = hpx_lco_user_new(kLCOSize + sizeof(int), init_action, operation_action, predicate_action, initdata, kLCOInitSize); assert(lcos[idx] != HPX_NULL); delete [] initdata; // setup dependent call of done when cdone triggers hpx_call_when(cdone, cdone, hpx_lco_delete_action, done, nullptr, 0); return HPX_SUCCESS; } int lco_tree_set_handler(size_t idx, hpx_addr_t *lcos, hpx_addr_t done) { // create child done detection lco hpx_addr_t cdone = hpx_lco_and_new(2); assert(cdone != HPX_NULL); // spawn work at children if they exist size_t l_child = 2 * idx + 1; if (l_child < kLCOCount) { hpx_call(HPX_HERE, lco_tree_set_action, HPX_NULL, &l_child, &lcos, &cdone); } else { hpx_lco_and_set(cdone, HPX_NULL); } size_t r_child = 2 * idx + 2; if (r_child < kLCOCount) { hpx_call(HPX_HERE, lco_tree_set_action, HPX_NULL, &r_child, &lcos, &cdone); } else { hpx_lco_and_set(cdone, HPX_NULL); } // set my lco char *data = new char[kLCOSize]; assert(data != nullptr); hpx_lco_set_lsync(lcos[idx], kLCOSize, data, HPX_NULL); delete [] data; // setup dependent call of done when cdone triggers hpx_call_when(cdone, cdone, hpx_lco_delete_action, done, nullptr, 0); return HPX_SUCCESS; } int rankwise_handler(hpx_addr_t array_alloc_done, hpx_addr_t lco_alloc_done, hpx_addr_t array_clear_done) { int rank = hpx_get_my_rank(); fprintf(stdout, "Hello from rank %d\n", rank); // Allocate a large block of memory hpx_addr_t array_gas = hpx_gas_alloc_local(1, kArraySize, 0); assert(array_gas != HPX_NULL); hpx_lco_and_set(array_alloc_done, HPX_NULL); fprintf(stdout, " %d: array allocated\n", rank); hpx_lco_wait(array_alloc_done); // allocate some local memory std::vector<Junk> local_junk{}; for (size_t i = 0; i < kLocalAllocCount; ++i) { //Junk toadd{}; //toadd.data[14] = 'c'; local_junk.push_back(Junk{}); } // in parallel allocate a bunch of LCOs hpx_addr_t *lcos = new hpx_addr_t[kLCOCount]; assert(lcos != nullptr); hpx_addr_t local_alloc_done = hpx_lco_and_new(1); assert(local_alloc_done != HPX_NULL); hpx_call_when(local_alloc_done, local_alloc_done, hpx_lco_delete_action, lco_alloc_done, nullptr, 0); size_t root_idx{0}; hpx_call(HPX_HERE, lco_tree_alloc_action, HPX_NULL, &root_idx, &lcos, &local_alloc_done); fprintf(stdout, " %d: lco allocation spawned\n", rank); hpx_lco_wait(lco_alloc_done); // set the large chunk to zero double *array_local{nullptr}; assert(hpx_gas_try_pin(array_gas, (void **)&array_local)); size_t count = kArraySize / sizeof(double); for (size_t i = 0; i < count; ++i) { array_local[i] = 0.0; } hpx_lco_and_set(array_clear_done, HPX_NULL); fprintf(stdout, " %d: array cleared\n", rank); hpx_lco_wait(array_clear_done); // in parallel, start setting the LCOs hpx_addr_t local_set_done = hpx_lco_and_new(1); hpx_call_when(local_set_done, local_set_done, hpx_lco_delete_action, HPX_NULL, nullptr, 0); hpx_call(HPX_HERE, lco_tree_set_action, HPX_NULL, &root_idx, &lcos, &local_set_done); fprintf(stdout, " %d: array set spawned\n", rank); // wait for all of those to finish hpx_lco_wait_all(kLCOCount, lcos, nullptr); fprintf(stdout, " %d: array sets done\n", rank); // clean up this rank's resources hpx_gas_free_sync(array_gas); for (size_t i = 0; i < kLCOCount; ++i) { hpx_lco_delete_sync(lcos[i]); } delete [] lcos; return HPX_SUCCESS; } HPX_ACTION(HPX_DEFAULT, HPX_ATTR_NONE, rankwise_action, rankwise_handler, HPX_ADDR, HPX_ADDR, HPX_ADDR); int main_handler(int UNUSED) { fprintf(stdout, "Hello from main_handler!\n"); // First allocate the shared synchronization LCOs int n_ranks = hpx_get_num_ranks(); hpx_addr_t array_alloc_done = hpx_lco_and_new(n_ranks); hpx_addr_t lco_alloc_done = hpx_lco_and_new(n_ranks); hpx_addr_t array_clear_done = hpx_lco_and_new(n_ranks); // Then broadcast so each rank will do its work hpx_bcast_rsync(rankwise_action, &array_alloc_done, &lco_alloc_done, &array_clear_done); // Clean up the shared resources hpx_lco_delete_sync(array_alloc_done); hpx_lco_delete_sync(lco_alloc_done); hpx_lco_delete_sync(array_clear_done); hpx_exit(0, nullptr); } HPX_ACTION(HPX_DEFAULT, HPX_ATTR_NONE, main_action, main_handler, HPX_INT); int main(int argc, char **argv) { if (HPX_SUCCESS != hpx_init(&argc, &argv)) { return -1; } int unused{7}; hpx_run(&main_action, nullptr, &unused); hpx_finalize(); return 0; }
29.776062
78
0.698781
luglio
f0e6e482ffe222966f3744c15bb1d40b14e77ae0
4,329
cpp
C++
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
/* Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true: 1. S(B) ≠ S(C); that is, sums of subsets cannot be equal. 2. If B contains more elements than C then S(B) > S(C). For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and S(A) = 1286. Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets containing seven to twelve elements (the two examples given above are the first two sets in the file), identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak). NOTE: This problem is related to Problem 103 and Problem 106. Solution comment: ~15 ms. Purely reuse of code from 103. Only thing of note was to remember to sort the set before testing, as the code from 103 assumed to set to be in ascending order for some efficient checks. */ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <cstdlib> #include <cmath> #include <chrono> #include <vector> #include <numeric> #include <algorithm> /* * Return a vector of sums, where sum[i] is the sum of the set * containing A[k] where k is the index of all the set bits in i. * * Example: * A = {1, 2, 3} * sum[3] = sum[0b011] = A[0] + A[1] * sum[4] = sum[0b100] = A[3] */ template<typename Container> auto all_subset_sums(const Container &A) { const auto n = std::distance(A.begin(), A.end()); std::vector<int> subset_sums((std::size_t) std::pow(2, n)); for (std::size_t i = 1; i < subset_sums.size(); i++) { auto selector = i; for (int element : A) { if (selector & 1) { subset_sums[i] += element; } selector >>= 1; } } return subset_sums; } template<typename Container> bool is_special(const Container &A) { // Computing size of A. Workaround for cppitertools classes // which don't have a .size() method. const auto n = std::distance(A.begin(), A.end()); // Rule 1: Smaller subsets have smaller sums. // Shortcut, since A is sorted: a1 + a2 > an, a1+a2+a3 > a(n-1) + an etc. // is a sufficient condition to check. // We check this first, as this is _much_ easier to do. int left_sum = A[0]; int right_sum = 0; for (int i = 0; i < n / 2; i++) { left_sum += A[i + 1]; right_sum += A[n - 1 - i]; if (left_sum <= right_sum) return false; } // Rule 2: No duplicate subset sums. // If two duplicate sums are found, we check if // the corresponding sets are disjoint (meaning // set i and set k have no common set bits). If // both conditions are met, no special sum for you. const auto sums = all_subset_sums(A); auto n_sums = std::distance(sums.begin(), sums.end()); for (int i = 0; i < n_sums; ++i) { auto k = std::distance(sums.begin(), std::find(sums.begin() + i + 1, sums.end(), sums[i]) ); if (k != n_sums and not (i & k)) return false; } return true; } int main() { auto start = std::chrono::high_resolution_clock::now(); long total = 0; std::ifstream input("../../105/p105_sets.txt"); std::string line; while (std::getline(input, line)) { std::stringstream linestream(line); std::vector<int> A; std::string number; while (std::getline(linestream, number, ',')) { A.push_back(std::stoi(number)); } // Important! Needs to be sorted! std::sort(A.begin(), A.end()); if (is_special(A)) { total = std::accumulate(A.begin(), A.end(), total); } } printf("Answer: %ld\n", total); auto end = std::chrono::high_resolution_clock::now(); auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / (double) 1e6; printf("Found in time: %g ms\n", time); }
33.55814
105
0.584893
bsamseth
f0e802d21d2a747063a6c3c6ca1dd4419fb4ea63
1,428
cpp
C++
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
1
2019-05-15T09:46:40.000Z
2019-05-15T09:46:40.000Z
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
null
null
null
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
null
null
null
#include "RGraphicsPolylineItem.h" #include <QPainterPath> #include <QPainterPathStroker> rce::gui::RGraphicsPolylineItem:: RGraphicsPolylineItem(const QPolygonF &path, const QPen &pen, QGraphicsItem *parent): QGraphicsPathItem(parent), polyline_(path), penWidth_(pen.widthF()) { setBrush(QBrush(Qt::transparent)); setPen(pen); regenerate(); } QPainterPath rce::gui::RGraphicsPolylineItem:: lineShape() const { return lineShape_; } void rce::gui::RGraphicsPolylineItem:: regenerate() { QPainterPath path; if(polyline_.size() != 1) path.addPolygon(polyline_); else { path.addRect(polyline_.first().x() - 0.5f, polyline_.first().y() - 0.5f, 1,1); } setPath(path); QPainterPathStroker stroker; stroker.setCapStyle(pen().capStyle()); stroker.setDashOffset(pen().dashOffset()); stroker.setDashPattern(pen().dashPattern()); stroker.setJoinStyle(pen().joinStyle()); stroker.setMiterLimit(pen().miterLimit()); stroker.setWidth(pen().widthF()); lineShape_ = stroker.createStroke(path); } void rce::gui::RGraphicsPolylineItem:: setPenWidth(const double penWidth) { if (penWidth >= 0) { penWidth_ = penWidth; QPen newPen = pen(); newPen.setWidth(penWidth_); setPen(newPen); } regenerate(); }
20.112676
50
0.62395
Timie
f0ea5e2a0dd12c21431427276e3402e14e3dd423
1,567
hpp
C++
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#pragma once #include <XEngine.hpp> #include "TestController.hpp" namespace XE { class GraphicsManager; class OgreConsole; class XEngine; } namespace XET { class TestControllerSystem : public entityx::System < TestControllerSystem > , public XE::SDLInputHandler { public: TestControllerSystem(XE::XEngine& engine); ~TestControllerSystem(); void setBasicInputEvents(TestControllerComponent& controller); virtual void onPointMoved(XE::ActionContext context); virtual void onPointSelectStart(XE::ActionContext context); virtual void onPointSelectEnd(XE::ActionContext context); virtual void onResized(XE::ActionContext context); virtual void onKeyDown(XE::ActionContext context); virtual void onKeyPressed(XE::ActionContext context); virtual void onTextEntered(XE::ActionContext context); virtual void onQuit(); virtual void menuNav(XE::ActionContext context, TestControllerComponent& controller); //realtime action virtual void move(entityx::Entity entity, float dt); void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override; inline XE::XEngine& getEngine() { return mEngine; } private: float _turn_speed; float _zoom_speed; XE::XEngine& mEngine; bool mDecalDestroy; XE::Vector2 mMousePos; XE::Vector2 _lastMousePos; bool _mousePressed; XE::Vector3 moveDirection; // set to null per frame /// Mouse movement since last frame. XE::Vector2 m_mouseMove; /// Mouse wheel movement since last frame. int m_mouseMoveWheel; }; } // namespace XET
24.484375
106
0.758775
devxkh
f0ecd75c90b1397381cc270c29c3cc394e32feee
8,784
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "DWriteHitTesting.h" using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Core; using namespace Windows::ApplicationModel::Activation; using namespace Windows::UI::Core; using namespace Windows::System; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::Storage; DWriteHitTesting::DWriteHitTesting() { } void DWriteHitTesting::CreateDeviceIndependentResources() { DirectXBase::CreateDeviceIndependentResources(); m_text = "Touch Me To Change My Underline!"; // Create a DirectWrite text format object. DX::ThrowIfFailed( m_dwriteFactory->CreateTextFormat( L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_LIGHT, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 64.0f, L"en-US", // locale &m_textFormat ) ); // Center the text horizontally. DX::ThrowIfFailed( m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER) ); // Center the text vertically. DX::ThrowIfFailed( m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER) ); // Boolean array to keep track of which characters are underlined m_underlineArray = ref new Platform::Array<bool>(m_text->Length()); // Initialize the array to all false in order to represent the initial un-underlined text for (unsigned int i = 0; i < m_text->Length(); i++) { m_underlineArray[i] = false; } } void DWriteHitTesting::CreateDeviceResources() { DirectXBase::CreateDeviceResources(); m_sampleOverlay = ref new SampleOverlay(); m_sampleOverlay->Initialize( m_d2dDevice.Get(), m_d2dContext.Get(), m_wicFactory.Get(), m_dwriteFactory.Get(), "DirectWrite hit testing sample" ); DX::ThrowIfFailed( m_d2dContext->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Black), &m_blackBrush ) ); } void DWriteHitTesting::CreateWindowSizeDependentResources() { DirectXBase::CreateWindowSizeDependentResources(); D2D1_SIZE_F size = m_d2dContext->GetSize(); // Create a DirectWrite Text Layout object DX::ThrowIfFailed( m_dwriteFactory->CreateTextLayout( m_text->Data(), // Text to be displayed m_text->Length(), // Length of the text m_textFormat.Get(), // DirectWrite Text Format object size.width, // Width of the Text Layout size.height, // Height of the Text Layout &m_textLayout ) ); SetUnderlineOnRedraw(); } void DWriteHitTesting::Render() { m_d2dContext->BeginDraw(); m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue)); m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity()); m_d2dContext->DrawTextLayout( D2D1::Point2F(0.0f, 0.0f), m_textLayout.Get(), m_blackBrush.Get() ); // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device // is lost. It will be handled during the next call to Present. HRESULT hr = m_d2dContext->EndDraw(); if (hr != D2DERR_RECREATE_TARGET) { DX::ThrowIfFailed(hr); } m_sampleOverlay->Render(); } void DWriteHitTesting::Initialize( _In_ CoreApplicationView^ applicationView ) { applicationView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteHitTesting::OnActivated); CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &DWriteHitTesting::OnSuspending); CoreApplication::Resuming += ref new EventHandler<Platform::Object^>(this, &DWriteHitTesting::OnResuming); } void DWriteHitTesting::SetWindow( _In_ CoreWindow^ window ) { window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); window->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteHitTesting::OnWindowSizeChanged); window->PointerPressed += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DWriteHitTesting::OnPointerPressed); DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnLogicalDpiChanged); DisplayProperties::DisplayContentsInvalidated += ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnDisplayContentsInvalidated); DirectXBase::Initialize(window, DisplayProperties::LogicalDpi); } void DWriteHitTesting::Load( _In_ Platform::String^ entryPoint ) { // Retrieve any stored variables from the LocalSettings collection. IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values; if (settingsValues->HasKey("m_underlineArray")) { safe_cast<IPropertyValue^>(settingsValues->Lookup("m_underlineArray"))->GetBooleanArray(&m_underlineArray); SetUnderlineOnRedraw(); } } void DWriteHitTesting::Run() { Render(); Present(); m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit); } void DWriteHitTesting::Uninitialize() { } void DWriteHitTesting::OnWindowSizeChanged( _In_ CoreWindow^ sender, _In_ WindowSizeChangedEventArgs^ args ) { UpdateForWindowSizeChange(); m_sampleOverlay->UpdateForWindowSizeChange(); Render(); Present(); } void DWriteHitTesting::OnPointerPressed( _In_ CoreWindow^ sender, _In_ PointerEventArgs^ args ) { DWRITE_HIT_TEST_METRICS hitTestMetrics; BOOL isTrailingHit; BOOL isInside; Windows::UI::Input::PointerPoint^ point = args->CurrentPoint; DX::ThrowIfFailed( m_textLayout->HitTestPoint( point->Position.X, point->Position.Y, &isTrailingHit, &isInside, &hitTestMetrics ) ); if (isInside) { BOOL underline; DX::ThrowIfFailed( m_textLayout->GetUnderline(hitTestMetrics.textPosition, &underline) ); DWRITE_TEXT_RANGE textRange = {hitTestMetrics.textPosition, 1}; DX::ThrowIfFailed( m_textLayout->SetUnderline(!underline, textRange) ); m_underlineArray[hitTestMetrics.textPosition] = !underline; } Render(); Present(); } // This function is used to keep track of which elements are underlined - in order to redraw // the underline if the text layout needs to be recreated void DWriteHitTesting::SetUnderlineOnRedraw() { for (unsigned int i = 0; i < m_text->Length(); i++) { DWRITE_TEXT_RANGE textRange = {i, 1}; DX::ThrowIfFailed( m_textLayout->SetUnderline(m_underlineArray[i], textRange) ); } } void DWriteHitTesting::OnLogicalDpiChanged( _In_ Platform::Object^ sender ) { SetDpi(DisplayProperties::LogicalDpi); Render(); Present(); } void DWriteHitTesting::OnDisplayContentsInvalidated( _In_ Platform::Object^ sender ) { // Ensure the D3D Device is available for rendering. ValidateDevice(); Render(); Present(); } void DWriteHitTesting::OnActivated( _In_ CoreApplicationView^ applicationView, _In_ IActivatedEventArgs^ args ) { m_window->Activate(); } void DWriteHitTesting::OnSuspending( _In_ Platform::Object^ sender, _In_ SuspendingEventArgs^ args ) { IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values; if (settingsValues->HasKey("m_underlineArray")) { settingsValues->Remove("m_underlineArray"); } settingsValues->Insert("m_underlineArray", PropertyValue::CreateBooleanArray(m_underlineArray)); } void DWriteHitTesting::OnResuming( _In_ Platform::Object^ sender, _In_ Platform::Object^ args ) { } IFrameworkView^ DirectXAppSource::CreateView() { return ref new DWriteHitTesting(); } [Platform::MTAThread] int main(Platform::Array<Platform::String^>^) { auto directXAppSource = ref new DirectXAppSource(); CoreApplication::Run(directXAppSource); return 0; }
27.111111
122
0.675546
alonmm
f0ee749e1a3d95496f8274ffbe8edb9ea3eb2222
2,778
cpp
C++
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
2
2016-09-28T02:23:07.000Z
2019-07-13T15:53:47.000Z
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
#include "firewalldiscoverymanager.h" #include "irequest.h" #include "iproxyconnection.h" #include "idatabasesettings.h" #include "isession.h" #include "isettings.h" #include <QThread> #include <QTimer> bool FirewallDiscoveryManager::m_wasPingedBack = false; bool FirewallDiscoveryManager::m_statusChecked = false; FirewallDiscoveryManager::FirewallDiscoveryManager(IProxyConnection *proxyConnection, QObject *parent) : QObject(parent), m_proxyConnection(proxyConnection) { connect(this, SIGNAL(finishedPing()), this, SLOT(deleteLater())); } void FirewallDiscoveryManager::ping(const QString &clientId) { m_clientToPingId = clientId; QThread* thread = new QThread; this->moveToThread(thread); connect(thread, SIGNAL(started()), this, SLOT(startPing())); connect(this, SIGNAL(finishedPing()), thread, SLOT(quit())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); } void FirewallDiscoveryManager::checkFirewallStatus() { if (m_statusChecked) { emit finishedPing(); return; } QObject parent; QString myId = m_proxyConnection->databaseSettings(&parent)->clientId(); QVariantMap availableClients = m_proxyConnection->session(&parent)->availableClients(); m_statusChecked = true; foreach (QString id, availableClients.keys()) { if (id == myId) continue; IRequest *request = m_proxyConnection->createRequest(IRequest::GET, "clients", QString("%1/firewall/ping_me?my_id=%2") .arg(id) .arg(myId), &parent); if (m_proxyConnection->callModule(request)->status() == IResponse::OK) { QTimer::singleShot(5 * 1000, this, SLOT(checkPingResponse())); return; } } m_statusChecked = false; emit finishedPing(); } void FirewallDiscoveryManager::setPingedBack(bool pingedBack) { m_wasPingedBack = pingedBack; } void FirewallDiscoveryManager::startPing() { IRequest *request = m_proxyConnection->createRequest(IRequest::GET, "clients", QString("%1/firewall/ping") .arg(m_clientToPingId), this); m_proxyConnection->callModule(request); emit finishedPing(); } void FirewallDiscoveryManager::checkPingResponse() { if (!m_wasPingedBack) { QObject parent; int port = m_proxyConnection->settings(&parent)->listenPort(); m_proxyConnection->message(tr("Firewall was detected that prevents OwNet from functioning properly. Please deactivate the firewall on port %1.").arg(port), tr("Firewall Detected"), IProxyConnection::CriticalPopup); } emit finishedPing(); }
32.302326
222
0.662707
OwNet
f0f05bf693f7d79fd2726994ede303576e1af4e4
1,044
cpp
C++
String Processing/Suffix Trie, Tree, Array/DNA Sequencing.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
String Processing/Suffix Trie, Tree, Array/DNA Sequencing.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
String Processing/Suffix Trie, Tree, Array/DNA Sequencing.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; string a, b; int dp[500][500]; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int cas = 1; while(cin >> a >> b){ if(cas != 1) cout << "\n"; cas++; memset(dp, 0, sizeof dp); int max1 = -1; for(int i=0; i<a.size(); i++){ for(int j=0; j<b.size(); j++){ if(a[i] == b[j]) dp[i+1][j+1] = max(1, dp[i][j] + 1); max1 = max(max1, dp[i+1][j+1]); } } if(max1 == 0){ cout << "No common sequence.\n"; continue; } set <string> names; for(int i=1; i<=a.size(); i++){ for(int j=1; j<=b.size(); j++){ if(dp[i][j] == max1){ names.insert(a.substr(i - max1, max1)); } } } for(auto el:names) cout << el << "\n"; } return 0; }
26.769231
69
0.423372
satvik007
f0f0ace72afa4202406e02c8721c07cb503b134a
908
cpp
C++
leetcode/baseball-game/solution.cpp
kpagacz/comp-programming
15482d762ede4d3b7f8ff45a193f6e6bcd85672a
[ "MIT" ]
1
2021-12-06T16:01:55.000Z
2021-12-06T16:01:55.000Z
leetcode/baseball-game/solution.cpp
kpagacz/comp-programming
15482d762ede4d3b7f8ff45a193f6e6bcd85672a
[ "MIT" ]
null
null
null
leetcode/baseball-game/solution.cpp
kpagacz/comp-programming
15482d762ede4d3b7f8ff45a193f6e6bcd85672a
[ "MIT" ]
null
null
null
// link to the problem: https://leetcode.com/problems/baseball-game/ #include <algorithm> #include <array> #include <cassert> #include <iostream> #include <iterator> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> class Solution { public: int calPoints(std::vector<std::string>& ops) { std::vector<int> scores; for (const auto& op : ops) { if (op == "C") { scores.pop_back(); } else if (op == "D") { scores.push_back(scores.back() * 2); } else if (op == "+") { scores.push_back(scores[scores.size() - 1] + scores[scores.size() - 2]); } else { scores.push_back(std::stoi(op)); } } return std::accumulate(scores.begin(), scores.end(), 0); } }; int main(int argc, char** argv) {}
23.894737
80
0.612335
kpagacz
f0f3edf65ada39edd4d875628f77efab8c768201
270
cpp
C++
old/practice/lesson2/special.cpp
Lyuminarskiy/oop
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
3
2018-02-16T11:22:55.000Z
2018-03-23T14:10:33.000Z
old/practice/lesson2/special.cpp
OOP-course/OOP-course
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
null
null
null
old/practice/lesson2/special.cpp
OOP-course/OOP-course
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
1
2020-04-28T17:13:02.000Z
2020-04-28T17:13:02.000Z
#include <string> using namespace std; struct Backup final { static void makeBakup(string path) {} }; struct Printer final { static void print(string text) {} }; int main() { Backup::makeBakup("C:/myBackups/"); Printer::print("Hello, world!"); return 0; }
12.857143
39
0.666667
Lyuminarskiy
e7c5dbbea0bd5fbe6f6afa015267f64f2c5b80dc
2,224
hpp
C++
modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/is_aligned.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/is_aligned.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/include/boost/simd/sdk/memory/meta/is_aligned.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SDK_MEMORY_META_IS_ALIGNED_HPP_INCLUDED #define BOOST_SIMD_SDK_MEMORY_META_IS_ALIGNED_HPP_INCLUDED #include <cstddef> #include <boost/mpl/bool.hpp> #include <boost/mpl/size_t.hpp> #include <boost/mpl/assert.hpp> #include <boost/simd/sdk/memory/parameters.hpp> #include <boost/simd/sdk/memory/meta/is_power_of_2.hpp> namespace boost { namespace simd { namespace meta { ////////////////////////////////////////////////////////////////////////////// // Boolean meta-function checking if a integral constant is aligned on a given // power of 2 boundary. // Documentation: reference/sdk/aligned/meta/is_aligned_c.rst ////////////////////////////////////////////////////////////////////////////// template<std::size_t V, std::size_t N = BOOST_SIMD_CONFIG_ALIGNMENT> struct is_aligned_c : boost::mpl::bool_<!(V & (N-1) )> { //========================================================================== /* * Alignment done on a non-power of two boundary */ //========================================================================== BOOST_MPL_ASSERT_MSG ( (meta::is_power_of_2_c<N>::value) , BOOST_SIMD_INVALID_ALIGNMENT_VALUE , (boost::mpl::int_<N>) ); }; ////////////////////////////////////////////////////////////////////////////// // Boolean meta-function checking if a Integral Constant is aligned on a given // power of 2 boundary. // Documentation: reference/sdk/aligned/meta/is_aligned.rst ////////////////////////////////////////////////////////////////////////////// template<class V, class N = boost::mpl::size_t<BOOST_SIMD_CONFIG_ALIGNMENT> > struct is_aligned : is_aligned_c<V::value,N::value> {}; } } } #endif
42.769231
80
0.498201
pbrunet
e7cb87db2e716639f7eb980466689cac07891275
1,593
cpp
C++
src/prod/src/Management/BackupRestore/BA/BackupConfiguration.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/BackupRestore/BA/BackupConfiguration.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/BackupRestore/BA/BackupConfiguration.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Management; using namespace BackupRestoreAgentComponent; BackupConfiguration::BackupConfiguration() : operationTimeoutMilliseconds_(0), backupStoreInfo_() { } BackupConfiguration::~BackupConfiguration() { } Common::ErrorCode BackupConfiguration::ToPublicApi( __in Common::ScopedHeap & heap, __out FABRIC_BACKUP_CONFIGURATION & fabricBackupConfiguration) const { ErrorCode error(ErrorCodeValue::Success); auto storeInfo = heap.AddItem<FABRIC_BACKUP_STORE_INFORMATION>(); fabricBackupConfiguration.OperationTimeoutMilliseconds = operationTimeoutMilliseconds_; error = backupStoreInfo_.ToPublicApi(heap, *storeInfo); fabricBackupConfiguration.StoreInformation = storeInfo.GetRawPointer(); fabricBackupConfiguration.Reserved = NULL; return ErrorCodeValue::Success; } Common::ErrorCode BackupConfiguration::FromPublicApi( FABRIC_BACKUP_CONFIGURATION const & fabricBackupConfiguration) { ErrorCode error(ErrorCodeValue::Success); operationTimeoutMilliseconds_ = fabricBackupConfiguration.OperationTimeoutMilliseconds; if (fabricBackupConfiguration.StoreInformation != NULL) { error = backupStoreInfo_.FromPublicApi(*fabricBackupConfiguration.StoreInformation); } return error; }
31.86
98
0.723792
gridgentoo
e7cc78d92806210ceb5c2003c6ddbce43886464a
16,811
cpp
C++
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#include "generator.h" #include <sstream> #include <regex> using namespace natus::nsl::glsl ; natus::ntd::string_t generator::replace_buildin_symbols( natus::ntd::string_t code ) noexcept { natus::nsl::repl_syms_t repls = { { natus::ntd::string_t( "mul" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "mul ( INVALID_ARGS ) " ; return args[ 0 ] + " * " + args[ 1 ] ; } }, { natus::ntd::string_t( "mmul" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "mmul ( INVALID_ARGS ) " ; return args[ 0 ] + " * " + args[ 1 ] ; } }, { natus::ntd::string_t( "add" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "add ( INVALID_ARGS ) " ; return args[ 0 ] + " + " + args[ 1 ] ; } }, { natus::ntd::string_t( "sub" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "sub ( INVALID_ARGS ) " ; return args[ 0 ] + " - " + args[ 1 ] ; } }, { natus::ntd::string_t( "div" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "div ( INVALID_ARGS ) " ; return args[ 0 ] + " / " + args[ 1 ] ; } }, { natus::ntd::string_t( "pulse" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 3 ) return "pulse ( INVALID_ARGS ) " ; return "( step ( " + args[ 0 ] + " , " + args[ 2 ] + " ) - " + "step ( " + args[ 1 ] + " , " + args[ 2 ] + " ) )" ; } }, { natus::ntd::string_t( "texture" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "texture ( INVALID_ARGS ) " ; return "texture( " + args[ 0 ] + " , " + args[ 1 ] + " ) " ; } }, { natus::ntd::string_t( "rt_texture" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "rt_texture ( INVALID_ARGS ) " ; return "texture( " + args[ 0 ] + " , " + args[ 1 ] + " ) " ; } }, { natus::ntd::string_t( "lt" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "lt ( INVALID_ARGS ) " ; return args[ 0 ] + " < " + args[ 1 ] ; } }, { natus::ntd::string_t( "gt" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "gt ( INVALID_ARGS ) " ; return args[ 0 ] + " > " + args[ 1 ] ; } }, { natus::ntd::string_t( "ret" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 1 ) return "ret ( INVALID_ARGS ) " ; return "return " + args[ 0 ] ; } }, { natus::ntd::string_t( "mix" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 3 ) return "mix ( INVALID_ARGS ) " ; return "mix (" + args[ 0 ] + " , " + args[ 1 ] + " , " + args[ 2 ] + " ) " ; } } } ; return natus::nsl::perform_repl( std::move( code ), repls ) ; } natus::ntd::string_t generator::map_variable_type( natus::nsl::type_cref_t type ) noexcept { typedef std::pair< natus::nsl::type_t, natus::ntd::string_t > mapping_t ; static mapping_t const __mappings[] = { mapping_t( natus::nsl::type_t(), "unknown" ), mapping_t( natus::nsl::type_t::as_float(), "float" ), mapping_t( natus::nsl::type_t::as_vec2(), "vec2" ), mapping_t( natus::nsl::type_t::as_vec3(), "vec3" ), mapping_t( natus::nsl::type_t::as_vec4(), "vec4" ), mapping_t( natus::nsl::type_t::as_mat2(), "mat2" ), mapping_t( natus::nsl::type_t::as_mat3(), "mat3" ), mapping_t( natus::nsl::type_t::as_mat4(), "mat4" ), mapping_t( natus::nsl::type_t::as_tex1d(), "sampler1D" ), mapping_t( natus::nsl::type_t::as_tex2d(), "sampler2D" ) } ; for( auto const& m : __mappings ) if( m.first == type ) return m.second ; return __mappings[ 0 ].second ; } natus::ntd::string_cref_t generator::to_texture_type( natus::nsl::type_cref_t t ) noexcept { typedef std::pair< natus::nsl::type_ext, natus::ntd::string_t > __mapping_t ; static __mapping_t const __mappings[] = { __mapping_t( natus::nsl::type_ext::unknown, "unknown" ), __mapping_t( natus::nsl::type_ext::texture_1d, "sampler1D" ), __mapping_t( natus::nsl::type_ext::texture_2d, "sampler2D" ) } ; for( auto const& m : __mappings ) if( m.first == t.ext ) return m.second ; return __mappings[ 0 ].second ; } natus::ntd::string_t generator::replace_types( natus::ntd::string_t code ) noexcept { size_t p0 = 0 ; size_t p1 = code.find_first_of( ' ' ) ; while( p1 != std::string::npos ) { auto const dist = p1 - p0 ; auto token = code.substr( p0, dist ) ; natus::nsl::type_t const t = natus::nsl::to_type( token ) ; if( t.base != natus::nsl::type_base::unknown ) { code.replace( p0, dist, this_t::map_variable_type( t ) ) ; } p0 = p1 + 1 ; p1 = code.find_first_of( ' ', p0 ) ; } return std::move( code ) ; } natus::nsl::generated_code_t::shaders_t generator::generate( natus::nsl::generatable_cref_t genable_, natus::nsl::variable_mappings_cref_t var_map_ ) noexcept { natus::nsl::variable_mappings_t var_map = var_map_ ; natus::nsl::generatable_t genable = genable_ ; // start renaming internal variables { for( auto& var : var_map ) { if( var.fq == natus::nsl::flow_qualifier::out && var.st == natus::nsl::shader_type::vertex_shader && var.binding == natus::nsl::binding::position ) { var.new_name = "gl_Position" ; } } } // replace buildins { for( auto& s : genable.config.shaders ) { for( auto& c : s.codes ) { for( auto& l : c.lines ) { l = this_t::replace_buildin_symbols( std::move( l ) ) ; } } } for( auto& frg : genable.frags ) { for( auto& f : frg.fragments ) { //for( auto& l : c.lines ) { f = this_t::replace_buildin_symbols( std::move( f ) ) ; } } } } natus::nsl::generated_code_t::shaders_t ret ; for( auto const& s : genable.config.shaders ) { natus::nsl::shader_type const s_type = s.type ; natus::nsl::generated_code_t::shader_t shd ; for( auto& var : var_map ) { if( var.st != s_type ) continue ; natus::nsl::generated_code_t::variable_t v ; v.binding = var.binding ; v.fq = var.fq ; v.name = var.new_name ; shd.variables.emplace_back( std::move( v ) ) ; } // generate the code { if( s_type == natus::nsl::shader_type::unknown ) { natus::log::global_t::warning( "[glsl generator] : unknown shader type" ) ; continue; } shd.type = s_type ; shd.codes.emplace_back( this_t::generate( genable, s, var_map, natus::nsl::api_type::es3 ) ) ; shd.codes.emplace_back( this_t::generate( genable, s, var_map, natus::nsl::api_type::gl3 ) ) ; } ret.emplace_back( std::move( shd ) ) ; } return std::move( ret ) ; } natus::nsl::generated_code_t::code_t generator::generate( natus::nsl::generatable_cref_t genable, natus::nsl::post_parse::config_t::shader_cref_t s, natus::nsl::variable_mappings_cref_t var_mappings, natus::nsl::api_type const type ) noexcept { natus::nsl::generated_code_t::code code ; std::stringstream text ; // 1. glsl stuff at the front { switch( type ) { case natus::nsl::api_type::gl3: text << "#version 130" << std::endl << std::endl ; break ; case natus::nsl::api_type::es3: text << "#version 300 es" << std::endl ; text << "precision mediump float ;" << std::endl << std::endl ; break ; default: text << "#version " << "glsl_type case missing" << std::endl << std::endl ; break ; } } // add extensions for pixel shader if( s.type == natus::nsl::shader_type::pixel_shader ) { size_t num_color = 0 ; for( auto const& var : s.variables ) { num_color += natus::nsl::is_color( var.binding ) ? 1 : 0 ; } // mrt requires extensions for glsl 130 if( num_color > 1 && type == natus::nsl::api_type::gl3 ) { text << "#extension GL_ARB_separate_shader_objects : enable" << std::endl << "#extension GL_ARB_explicit_attrib_location : enable" << std::endl << std::endl ; } } // 2. make prototypes declarations from function signatures // the prototype help with not having to sort funk definitions { text << "// Declarations // " << std::endl ; for( auto const& f : genable.frags ) { text << this_t::map_variable_type( f.sig.return_type ) << " " ; text << f.sym_long.expand( "_" ) << " ( " ; for( auto const& a : f.sig.args ) { text << this_t::map_variable_type( a.type ) + ", " ; } text.seekp( -2, std::ios_base::end ) ; text << " ) ; " << std::endl ; } text << std::endl ; } // 3. make all functions with replaced symbols { text << "// Definitions // " << std::endl ; for( auto const& f : genable.frags ) { // make signature { text << this_t::map_variable_type( f.sig.return_type ) << " " ; text << f.sym_long.expand( "_" ) << " ( " ; for( auto const& a : f.sig.args ) { text << this_t::map_variable_type( a.type ) + " " + a.name + ", " ; } text.seekp( -2, std::ios_base::end ) ; text << " )" << std::endl ; } // make body { text << "{" << std::endl ; for( auto const& l : f.fragments ) { text << this_t::replace_types( l ) << std::endl ; } text << "}" << std::endl ; } } text << std::endl ; } // 4. make all glsl uniforms from shader variables { size_t num_color = 0 ; for( auto const& var : s.variables ) { num_color += natus::nsl::is_color( var.binding ) ? 1 : 0 ; } size_t layloc_id = 0 ; text << "// Uniforms and in/out // " << std::endl ; for( auto const& v : s.variables ) { if( v.fq == natus::nsl::flow_qualifier::out && v.binding == natus::nsl::binding::position ) continue ; natus::ntd::string_t name = v.name ; natus::ntd::string_t const type_ = this_t::map_variable_type( v.type ) ; size_t const idx = natus::nsl::find_by( var_mappings, v.name, v.binding, v.fq, s.type ) ; if( idx != size_t( -1 ) ) { name = var_mappings[ idx ].new_name ; } // do some regex replacements { //type_ = std::regex_replace( type_, std::regex( "tex([1-3]+)d" ), "sampler$1D" ) ; } natus::ntd::string_t layloc ; if( v.fq == natus::nsl::flow_qualifier::out && s.type == natus::nsl::shader_type::pixel_shader && num_color > 1 ) { layloc = "layout( location = " + std::to_string( layloc_id++ ) + " ) " ; } natus::ntd::string_t const flow = v.fq == natus::nsl::flow_qualifier::global ? "uniform" : natus::nsl::to_string( v.fq ) ; text << layloc << flow << " " << type_ << " " << name << " ; " << std::endl ; } text << std::endl ; } // 5. insert main/shader from config { text << "// The shader // " << std::endl ; for( auto const& c : s.codes ) { for( auto const& l : c.lines ) { text << this_t::replace_types( l ) << std::endl ; } } } // 6. post over the code and replace all dependencies and in/out { auto shd = text.str() ; // variable dependencies { for( auto const& v : genable.vars ) { size_t const p0 = shd.find( v.sym_long.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + v.value + shd.substr( p1 ) ; } } // fragment dependencies { for( auto const& f : genable.frags ) { for( auto const& d : f.deps ) { size_t const p0 = shd.find( d.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + d.expand( "_" ) + shd.substr( p1 ) ; } } } // shader dependencies { for( auto const& d : s.deps ) { size_t const p0 = shd.find( d.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + d.expand( "_" ) + shd.substr( p1 ) ; } } // replace in code in/out/globals { size_t const off = shd.find( "// The shader" ) ; for( auto const& v : var_mappings ) { if( v.st != s.type ) continue ; natus::ntd::string_t flow ; if( v.fq == natus::nsl::flow_qualifier::in ) flow = "in." ; else if( v.fq == natus::nsl::flow_qualifier::out ) flow = "out." ; { natus::ntd::string_t const repl = flow + v.old_name ; size_t p0 = shd.find( repl, off ) ; while( p0 != std::string::npos ) { shd.replace( p0, repl.size(), v.new_name ) ; p0 = shd.find( repl, p0 + 3 ) ; } } } } // replace numbers { shd = std::regex_replace( shd, std::regex( " num_float \\( ([0-9]+) \\, ([0-9]+) \\) " ), " $1.$2 " ) ; shd = std::regex_replace( shd, std::regex( " num_uint \\( ([0-9]+) \\) " ), " $1u " ) ; shd = std::regex_replace( shd, std::regex( " num_int \\( ([0-9]+) \\) " ), " $1 " ) ; } { shd = this_t::replace_buildin_symbols( std::move( shd ) ) ; } code.shader = shd ; } code.api = type ; //ret.emplace_back( std::move( code ) ) ; return std::move( code ) ; }
33.893145
242
0.454762
aconstlink
e7cf06b3e60825044f85863d5f24f3f9fae10376
8,733
cpp
C++
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /** * @file Streamline.cpp * @author Yukio Yasuhra, Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: Streamline.cpp 1778 2014-05-28 10:16:57Z naohisa.sakamoto@gmail.com $ */ /*****************************************************************************/ #include "Streamline.h" #include <kvs/Type> #include <kvs/IgnoreUnusedVariable> #include <kvs/Message> #include <kvs/RGBColor> #include <kvs/Vector3> #include <kvs/VolumeObjectBase> #include <kvs/UniformGrid> #include <kvs/RectilinearGrid> #include <kvs/TetrahedralCell> #include <kvs/HexahedralCell> #include <kvs/QuadraticTetrahedralCell> #include <kvs/QuadraticHexahedralCell> #include <kvs/PyramidalCell> #include <kvs/PrismaticCell> #include <kvs/CellTreeLocator> namespace kvs { Streamline::StructuredVolumeInterpolator::StructuredVolumeInterpolator( const kvs::StructuredVolumeObject* volume ) { switch ( volume->gridType() ) { case kvs::StructuredVolumeObject::Uniform: m_grid = new kvs::UniformGrid( volume ); break; case kvs::StructuredVolumeObject::Rectilinear: m_grid = new kvs::RectilinearGrid( volume ); break; default: m_grid = NULL; break; } } Streamline::StructuredVolumeInterpolator::~StructuredVolumeInterpolator() { if ( m_grid ) { delete m_grid; } } kvs::Vec3 Streamline::StructuredVolumeInterpolator::interpolatedValue( const kvs::Vec3& point ) { m_grid->bind( point ); return m_grid->vector(); } bool Streamline::StructuredVolumeInterpolator::containsInVolume( const kvs::Vec3& point ) { const kvs::Vec3& min_coord = m_grid->referenceVolume()->minObjectCoord(); const kvs::Vec3& max_coord = m_grid->referenceVolume()->maxObjectCoord(); if ( point.x() < min_coord.x() || max_coord.x() <= point.x() ) return false; if ( point.y() < min_coord.y() || max_coord.y() <= point.y() ) return false; if ( point.z() < min_coord.z() || max_coord.z() <= point.z() ) return false; return true; } Streamline::UnstructuredVolumeInterpolator::UnstructuredVolumeInterpolator( const kvs::UnstructuredVolumeObject* volume ) { switch ( volume->cellType() ) { case kvs::UnstructuredVolumeObject::Tetrahedra: m_cell = new kvs::TetrahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::Hexahedra: m_cell = new kvs::HexahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::QuadraticTetrahedra: m_cell = new kvs::QuadraticTetrahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::QuadraticHexahedra: m_cell = new kvs::QuadraticHexahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::Pyramid: m_cell = new kvs::PyramidalCell( volume ); break; case kvs::UnstructuredVolumeObject::Prism: m_cell = new kvs::PrismaticCell( volume ); break; default: m_cell = NULL; break; } m_locator = new kvs::CellTreeLocator( volume ); } Streamline::UnstructuredVolumeInterpolator::~UnstructuredVolumeInterpolator() { if ( m_cell ) { delete m_cell; } if ( m_locator ) { delete m_locator; } } kvs::Vec3 Streamline::UnstructuredVolumeInterpolator::interpolatedValue( const kvs::Vec3& point ) { int index = m_locator->findCell( point ); if ( index < 0 ) { return kvs::Vec3::Zero(); } m_cell->bindCell( kvs::UInt32( index ) ); return m_cell->vector(); } bool Streamline::UnstructuredVolumeInterpolator::containsInVolume( const kvs::Vec3& point ) { const kvs::Vec3& min_obj = m_cell->referenceVolume()->minObjectCoord(); const kvs::Vec3& max_obj = m_cell->referenceVolume()->maxObjectCoord(); if ( point.x() < min_obj.x() || max_obj.x() <= point.x() ) return false; if ( point.y() < min_obj.y() || max_obj.y() <= point.y() ) return false; if ( point.z() < min_obj.z() || max_obj.z() <= point.z() ) return false; return m_locator->findCell( point ) != -1; } kvs::Vec3 Streamline::EulerIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; return point + k1; } kvs::Vec3 Streamline::RungeKutta2ndIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; const kvs::Vec3 v2 = point + k1 / 2.0f; if ( !contains( v2 ) ) { return point; } const kvs::Vec3 k2 = direction( v2 ) * k0; return point + k2; } kvs::Vec3 Streamline::RungeKutta4thIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; const kvs::Vec3 v2 = point + k1 / 2.0f; if ( !contains( v2 ) ) { return point; } const kvs::Vec3 k2 = direction( v2 ) * k0; const kvs::Vec3 v3 = point + k2 / 2.0f; if ( !contains( v3 ) ) { return point; } const kvs::Vec3 k3 = direction( v3 ) * k0; const kvs::Vec3 v4 = point + k3; if ( !contains( v4 ) ) { return point; } const kvs::Vec3 k4 = direction( v4 ) * k0; return point + ( k1 + 2.0f * ( k2 + k3 ) + k4 ) / 6.0f; } /*===========================================================================*/ /** * @brief Constructs a new streamline class and executes this class. * @param volume [in] pointer to the input volume object * @param seed_points [in] pointer to the seed points */ /*===========================================================================*/ Streamline::Streamline( const kvs::VolumeObjectBase* volume, const kvs::PointObject* seed_points, const kvs::TransferFunction& transfer_function ): kvs::StreamlineBase() { BaseClass::setTransferFunction( transfer_function ); BaseClass::setSeedPoints( seed_points ); this->exec( volume ); } /*===========================================================================*/ /** * @brief Executes the mapper process. * @param object [in] pointer to the volume object * @return line object */ /*===========================================================================*/ Streamline::BaseClass::SuperClass* Streamline::exec( const kvs::ObjectBase* object ) { if ( !object ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is NULL."); return NULL; } const kvs::VolumeObjectBase* volume = kvs::VolumeObjectBase::DownCast( object ); if ( !volume ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is not volume dat."); return NULL; } // Check whether the volume can be processed or not. if ( volume->veclen() != 3 ) { BaseClass::setSuccess( false ); kvsMessageError("Input volume is not vector field data."); return NULL; } // Attach the pointer to the volume object. BaseClass::attachVolume( volume ); BaseClass::setRange( volume ); BaseClass::setMinMaxCoords( volume, this ); // set the min/max vector length. if ( !volume->hasMinMaxValues() ) { volume->updateMinMaxValues(); } Interpolator* interpolator = NULL; switch ( volume->volumeType() ) { case kvs::VolumeObjectBase::Structured: { const kvs::StructuredVolumeObject* svolume = kvs::StructuredVolumeObject::DownCast( volume ); interpolator = new StructuredVolumeInterpolator( svolume ); break; } case kvs::VolumeObjectBase::Unstructured: { const kvs::UnstructuredVolumeObject* uvolume = kvs::UnstructuredVolumeObject::DownCast( volume ); interpolator = new UnstructuredVolumeInterpolator( uvolume ); break; } default: break; } Integrator* integrator = NULL; switch ( m_integration_method ) { case BaseClass::Euler: integrator = new EulerIntegrator(); break; case BaseClass::RungeKutta2nd: integrator = new RungeKutta2ndIntegrator(); break; case BaseClass::RungeKutta4th: integrator = new RungeKutta4thIntegrator(); break; default: break; } integrator->setInterpolator( interpolator ); integrator->setStep( m_integration_interval * m_integration_direction ); BaseClass::mapping( integrator ); delete interpolator; delete integrator; return this; } } // end of namespace kvs
31.189286
105
0.612504
CCSEPBVR
e7d5b7e1336a699fc45f5c704060073b301168fb
2,385
cpp
C++
ext/nuvo_image/src/Gif.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
null
null
null
ext/nuvo_image/src/Gif.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
5
2016-08-02T13:33:02.000Z
2020-11-03T15:22:52.000Z
ext/nuvo_image/src/Gif.cpp
crema/nuvo-image
365e4a54429fe4180e03adb1968ab9989e7ee5fb
[ "MIT" ]
null
null
null
#include "Gif.h" #include <cstring> bool Gif::TryReadFromBuffer(const std::shared_ptr<std::vector<unsigned char>>& buffer, Gif& gif, Flatten flatten) { GifBuffer readBuffer(buffer->data(), buffer->size()); int error = 0; auto gifFile = DGifOpen(&readBuffer, GifBuffer::ReadFromData, &error); if (gifFile == NULL) return false; if (DGifSlurp(gifFile) != GIF_OK) return false; cv::Mat mat(gifFile->SHeight, gifFile->SWidth, CV_8UC3); if (flatten == Flatten::Black) { mat.setTo(cv::Scalar(0, 0, 0)); } else if (flatten == Flatten::White) { mat.setTo(cv::Scalar(255, 255, 255)); } for (int i = 0; i < gifFile->ImageCount; ++i) { GraphicsControlBlock gcb; DGifSavedExtensionToGCB(gifFile, i, &gcb); mat = ReadFrame(mat.clone(), gifFile, i, gcb.TransparentColor); gif.frames->push_back(GifFrame(mat, gcb.DelayTime)); } DGifCloseFile(gifFile, &error); return true; } cv::Mat Gif::ReadFrame(cv::Mat mat, GifFileType* gifFile, int index, int transparentColor) { auto gifImage = &gifFile->SavedImages[index]; auto& imageDesc = gifImage->ImageDesc; const auto row = imageDesc.Top; /* Image Position relative to Screen. */ const auto col = imageDesc.Left; const auto width = imageDesc.Width; const auto bottom = row + imageDesc.Height; auto colorMap = imageDesc.ColorMap == nullptr ? gifFile->SColorMap : imageDesc.ColorMap; unsigned char* srcPtr = gifImage->RasterBits; for (int i = row; i < bottom; ++i) { auto destPtr = mat.data + mat.step * i + mat.channels() * col; for (int x = 0; x < width; ++x) { SetPixel(destPtr, srcPtr, colorMap, transparentColor); destPtr += mat.channels(); srcPtr++; } } return mat; } void Gif::SetPixel(unsigned char* dest, const unsigned char* src, ColorMapObject* colorMap, int transparentColor) { if (transparentColor >= 0 && transparentColor == *src) return; auto colorEntry = colorMap->Colors[*src]; dest[0] = colorEntry.Blue; dest[1] = colorEntry.Green; dest[2] = colorEntry.Red; } int GifBuffer::ReadFromData(GifFileType* gif, GifByteType* bytes, int size) { return ((GifBuffer*)gif->UserData)->Read(bytes, size); } int GifBuffer::Read(GifByteType* bytes, int size) { if (length - position < size) size = length - position; std::memcpy(bytes, buffer + position, size); position += size; return size; }
29.085366
115
0.67086
crema
e7db49fd1820aac516d688f41489b6279c002c05
857
cpp
C++
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
1
2020-12-26T03:55:08.000Z
2020-12-26T03:55:08.000Z
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
null
null
null
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
null
null
null
#include "Application.h" ApplicationLayer::ApplicationLayer(GLFWwindow* window, int weight, int height) { m_imGuiLayer = new ImGuiLayer(window, ImVec2((float)weight, (float)height)); } ApplicationLayer ::~ApplicationLayer() { delete m_imGuiLayer; } void ApplicationLayer::OnAttach() { RenderSettings rDesc; rDesc.height = 380; rDesc.width = 640; rDesc.spp = 1; sRenderer.SetupRenderer(rDesc); m_imGuiLayer->Init(); } void ApplicationLayer::OnStartFrame() { m_imGuiLayer->StartFrame(); bool show_app_dockspace = true; m_imGuiLayer->SetupDockspace(&show_app_dockspace); sRenderer.RenderUI(); } void ApplicationLayer::OnUpdate() { ImGui::ShowDemoWindow(); m_imGuiLayer->Render(); } void ApplicationLayer::OnEndFrame() { } void ApplicationLayer::OnDettach() { m_imGuiLayer->Shutdown(); }
18.234043
80
0.705951
TheJoKeR15
e7dc42015308bdc9fb045fa832b2a7afcf101cc3
1,314
hpp
C++
f9_os/inc/os/ktimer.hpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/inc/os/ktimer.hpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/inc/os/ktimer.hpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
1
2020-03-08T01:08:38.000Z
2020-03-08T01:08:38.000Z
/* * ktimer.hpp * * Created on: Apr 30, 2017 * Author: warlo */ #ifndef OS_KTIMER_HPP_ #define OS_KTIMER_HPP_ #include "list.hpp" namespace os { static constexpr bool CONFIG_KTIMER_TICKLESS=true; static constexpr bool CONFIG_KTIMER_TICKLESS_VERIFY=false; static constexpr size_t CONFIG_KTIMER_TICKLESS_COMPENSATION=0; static constexpr size_t CONFIG_KTIMER_TICKLESS_INT_COMPENSATION=0; static constexpr size_t CONFIG_KTIMER_HEARTBEAT=65536; static constexpr size_t CONFIG_KTIMER_MINTICKS=128; void ktimer_handler(void); /* Returns 0 if successfully handled * or number ticks if need to be rescheduled */ struct ktimer_event_t; typedef uint32_t (*ktimer_event_handler_t)(ktimer_event_t& data); struct ktimer_event_t { list::entry<ktimer_event_t> link; ktimer_event_handler_t handler; uint32_t delta; void *data; } ; void ktimer_event_init(void); int ktimer_event_schedule(uint32_t ticks, ktimer_event_t *kte); ktimer_event_t *ktimer_event_create(uint32_t ticks, ktimer_event_handler_t handler, void *data); void ktimer_event_handler(void); #ifdef CONFIG_KTIMER_TICKLESS void ktimer_enter_tickless(void); #endif /* CONFIG_KTIMER_TICKLESS */ class ktimer { }; } /* namespace os */ #endif /* OS_KTIMER_HPP_ */
23.464286
67
0.749619
ghsecuritylab
e7dc9cc36818cacc1b256cc8333ebf8286fbefed
215
cpp
C++
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
#include "NodeHandler.h" void NodeHandler::ReceiveRenderPosition(core::vector3df pos) { irrNode->setPosition(pos); } void NodeHandler::ReceiveRenderRotation(core::vector3df rot) { irrNode->setRotation(rot); }
15.357143
60
0.767442
LibreGames
e7e21691c1e63353a0f8d4b3921fd608f4703eb1
940
cpp
C++
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
2
2021-02-01T13:19:37.000Z
2021-02-25T10:39:46.000Z
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
#include "2015_10.h" namespace Day10_2015 { pair<size_t, size_t> both_parts(string input) { size_t p1 = 0; size_t p2 = 0; for (int j = 1; j <= 50; j++) { string next; int cnt = 0; char ch = 0; for (size_t i = 0; i < input.size(); i++) { if (input[i] != ch) { if (ch) next += to_string(cnt) + ch; ch = input[i]; cnt = 1; } else cnt++; } if (ch) next += to_string(cnt) + ch; input = next; if (j == 40) p1 = input.size(); if (j == 50) p2 = input.size(); } return make_pair(p1, p2); } t_output main(const t_input& input) { auto t0 = chrono::steady_clock::now(); auto px = both_parts(input[0]); auto t1 = chrono::steady_clock::now(); vector<string> solutions; solutions.push_back(to_string(px.first)); solutions.push_back(to_string(px.second)); return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count()); } }
18.431373
82
0.565957
tbielak
e7e59a8104e8fabe05e8d54858ac8af31f80afc9
5,253
cpp
C++
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <qi/log.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char **argv) { po::options_description desc("Allowed options"); int globalVerbosity; // Used to parse options, as well as to put help message desc.add_options() ("help,h", "Produces help message") ("version", "Output NAOqi version.") ("verbose,v", "Set verbose verbosity.") ("debug,d", "Set debug verbosity.") ("quiet,q", "Do not show logs on console.") ("context,c", po::value<int>(), "Show context logs: [0-7] (0: none, 1: categories, 2: date, 3: file+line, 4: date+categories, 5: date+line+file, 6: categories+line+file, 7: all (date+categories+line+file+function)).") ("synchronous-log", "Activate synchronous logs.") ("log-level,L", po::value<int>(&globalVerbosity), "Change the log minimum level: [0-6] (0: silent, 1: fatal, 2: error, 3: warning, 4: info, 5: verbose, 6: debug). Default: 4 (info)") ; // Map containing all the options with their values po::variables_map vm; // program option library throws all kind of errors, we just catch them // all, print usage and exit try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (po::error &e) { std::cerr << e.what() << std::endl; std::cout << desc << std::endl; exit(1); } if (vm.count("help")) { std::cout << desc << std::endl; return 0; } // set default log verbosity // set default log context if (vm.count("log-level")) { if (globalVerbosity > 0 && globalVerbosity <= 6) qi::log::setLogLevel((qi::LogLevel)globalVerbosity); if (globalVerbosity > 6) qi::log::setLogLevel(qi::LogLevel_Debug); if (globalVerbosity <= 0) qi::log::setLogLevel(qi::LogLevel_Silent); } // Remove consoleloghandler (default log handler) if (vm.count("quiet")) qi::log::removeHandler("consoleloghandler"); if (vm.count("debug")) qi::log::setLogLevel(qi::LogLevel_Debug); if (vm.count("verbose")) qi::log::setLogLevel(qi::LogLevel_Verbose); if (vm.count("context")) { int globalContext = vm["context"].as<int>(); if (globalContext < 0) { qi::log::setContext(0); } else { qi::log::setContext(globalContext); } } if (vm.count("synchronous-log")) qi::log::setSynchronousLog(true); qiLogFatal("core.log.example.1", "%d\n", 41); qiLogError("core.log.example.1", "%d\n", 42); qiLogWarning("core.log.example.1", "%d\n", 43); qiLogInfo("core.log.example.1", "%d\n", 44); qiLogVerbose("core.log.example.1", "%d\n", 45); qiLogDebug("core.log.example.1", "%d\n", 46); qiLogFatal("core.log.example.2") << "f" << 4 << std::endl; qiLogError("core.log.example.2") << "e" << 4 << std::endl; qiLogWarning("core.log.example.2") << "w" << 4 << std::endl; qiLogInfo("core.log.example.2") << "i" << 4 << std::endl; qiLogVerbose("core.log.example.2") << "v" << 4 << std::endl; qiLogDebug("core.log.example.2") << "d" << 4 << std::endl; qiLogFatal("core.log.example.1", "without '\\n': %d", 41); qiLogError("core.log.example.1", "without '\\n': %d", 42); qiLogWarning("core.log.example.1", "without '\\n': %d", 43); qiLogInfo("core.log.example.1", "without '\\n': %d", 44); qiLogVerbose("core.log.example.1", "without '\\n': %d", 45); qiLogDebug("core.log.example.1", "without '\\n': %d", 46); qiLogFatal("core.log.example.1", ""); qiLogFatal("core.log.example.1", "\n"); qiLogFatal("core.log.example.2") << "f " << "without '\\n'"; qiLogError("core.log.example.2") << "e " << "without '\\n'"; qiLogWarning("core.log.example.2") << "w " << "without '\\n'"; qiLogInfo("core.log.example.2") << "i " << "without '\\n'"; qiLogVerbose("core.log.example.2") << "v " << "without '\\n'"; qiLogDebug("core.log.example.2") << "d " << "without '\\n'"; qiLogFatal("core.log.example.2") << ""; qiLogFatal("core.log.example.2") << std::endl; qiLogFatal("core.log.example.3", "%d", 21) << "f" << 4 << std::endl; qiLogError("core.log.example.3", "%d", 21) << "e" << 4 << std::endl; qiLogWarning("core.log.example.3", "%d", 21) << "w" << 4 << std::endl; qiLogInfo("core.log.example.3", "%d", 21) << "i" << 4 << std::endl; qiLogVerbose("core.log.example.3", "%d", 21) << "v" << 4 << std::endl; qiLogDebug("core.log.example.3", "%d", 21) << "d" << 4 << std::endl; //c style qiLogWarning("core.log.example.4", "Oups my buffer is too bad: %x\n", 0x0BADCAFE); //c++ style qiLogError("core.log.example.4") << "Where is nao?" << " - Nao is in the kitchen." << " - How many are they? " << 42 << std::endl; //mixup style qiLogInfo("core.log.example.4", "%d %d ", 41, 42) << 43 << " " << 44 << std::endl; std::cout << "I've just finished to log!" << std::endl; }
35.734694
227
0.570912
yumilceh
e7e5d5107266ecb4fcb40f9eae3608ef75bab634
1,826
cpp
C++
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/opencl/opencl.hpp> #include <gtest/gtest.h> #include <algorithm> #define EXPECT_MATRIX_NEAR(A, B, DELTA) \ for (int i = 0; i < A.size(); i++) \ EXPECT_NEAR(A(i), B(i), DELTA); TEST(MathGpu, make_kernel) { stan::math::matrix_d m0(3, 3); stan::math::matrix_d m0_dst(3, 3); m0 << 1, 2, 3, 4, 5, 6, 7, 8, 9; stan::math::matrix_cl<double> m00(m0); stan::math::matrix_cl<double> m00_dst(m0.cols(), m0.rows()); stan::math::opencl_kernels::transpose(cl::NDRange(m00.rows(), m00.cols()), m00_dst, m00, m00.rows(), m00.cols()); m0_dst = stan::math::from_matrix_cl(m00_dst); } TEST(MathGpu, write_after_write) { using stan::math::matrix_cl; for (int j = 0; j < 1000; j++) { matrix_cl<double> m_cl(3, 3); for (int i = 0; i < 4; i++) { stan::math::opencl_kernels::fill(cl::NDRange(3, 3), m_cl, i, 3, 3, stan::math::matrix_cl_view::Entire); } stan::math::matrix_d res = stan::math::from_matrix_cl(m_cl); stan::math::matrix_d correct = stan::math::matrix_d::Constant(3, 3, 3); EXPECT_MATRIX_NEAR(res, correct, 1e-13); } } TEST(MathGpu, read_after_write_and_write_after_read) { using stan::math::matrix_cl; matrix_cl<double> m_cl(3, 3); matrix_cl<double> ms_cl[1000]; for (int j = 0; j < 1000; j++) { stan::math::opencl_kernels::fill(cl::NDRange(3, 3), m_cl, j, 3, 3, stan::math::matrix_cl_view::Entire); ms_cl[j] = m_cl; } for (int j = 0; j < 1000; j++) { stan::math::matrix_d res = stan::math::from_matrix_cl(ms_cl[j]); stan::math::matrix_d correct = stan::math::matrix_d::Constant(3, 3, j); EXPECT_MATRIX_NEAR(res, correct, 1e-13); } } #endif
29.451613
78
0.594195
peterwicksstringfield
e7e609a2ee5b0ac3c5d65d3452624fc99092084e
13,267
cpp
C++
src/atta/fileSystem/project/projectSerializer.cpp
brenocq/atta
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
5
2021-11-18T02:44:45.000Z
2021-12-21T17:46:10.000Z
src/atta/fileSystem/project/projectSerializer.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
1
2021-11-18T02:56:14.000Z
2021-12-04T15:09:16.000Z
src/atta/fileSystem/project/projectSerializer.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
3
2020-09-10T07:17:00.000Z
2020-11-05T10:24:41.000Z
//-------------------------------------------------- // Atta File System // projectSerializer.cpp // Date: 2021-09-15 // By Breno Cunha Queiroz //-------------------------------------------------- #include <atta/fileSystem/project/projectSerializer.h> #include <atta/fileSystem/serializer/serializer.h> #include <atta/cmakeConfig.h> #include <atta/componentSystem/componentManager.h> #include <atta/componentSystem/components/components.h> #include <atta/resourceSystem/resourceManager.h> #include <atta/resourceSystem/resources/mesh.h> #include <atta/resourceSystem/resources/texture.h> #include <atta/graphicsSystem/graphicsManager.h> #include <atta/core/config.h> namespace atta { ProjectSerializer::ProjectSerializer(std::shared_ptr<Project> project): _project(project) { } ProjectSerializer::~ProjectSerializer() { } void ProjectSerializer::serialize() { fs::path attaTemp = _project->getFile(); attaTemp.replace_extension(".atta.temp"); std::ofstream os(attaTemp, std::ofstream::trunc | std::ofstream::binary); serializeHeader(os); serializeConfig(os); serializeComponentSystem(os); serializeGraphicsSystem(os); write(os, "end"); os.close(); // Override atta file with temp file fs::rename(attaTemp, _project->getFile()); } void ProjectSerializer::deserialize() { fs::path attaFile = _project->getFile(); std::ifstream is(attaFile, std::ifstream::in | std::ifstream::binary); Header header = deserializeHeader(is); //LOG_VERBOSE("ProjectSerializer", "[*y]Header:[]\n\tversion:$0.$1.$2.$3\n\tproj:$4\n\tcounter:$5", // header.version[0], header.version[1], header.version[2], header.version[3], // header.projectName, header.saveCounter); while(is) { std::string marker; read(is, marker); if(marker == "config") deserializeConfig(is); else if(marker == "comp") deserializeComponentSystem(is); else if(marker == "gfx") deserializeGraphicsSystem(is); else if(marker == "end") break; else { LOG_WARN("ProjectSerializer", "Unknown marker [w]$0[]. The file may be corrupted", marker); break; } } is.close(); } void ProjectSerializer::serializeHeader(std::ofstream& os) { // Atta info write(os, "atta"); uint16_t version[] = { ATTA_VERSION_MAJOR, ATTA_VERSION_MINOR, ATTA_VERSION_PATCH, ATTA_VERSION_TWEAK }; write(os, version);// Version // Project info write(os, "proj"); write(os, _project->getName());// Project name uint32_t saveCounter = 0; write(os, saveCounter);// Save counter (number of times that was saved) write(os, "hend"); } ProjectSerializer::Header ProjectSerializer::deserializeHeader(std::ifstream& is) { std::string marker; Header header; while(true) { read(is, marker); if(marker == "hend") { return header; } else if(marker == "atta") { read(is, header.version); } else if(marker == "proj") { read(is, header.projectName); read(is, header.saveCounter); } else { LOG_WARN("ProjectSerializer", "Unknown marker found at the header [w]$0[]", marker); return header; } } return header; } void ProjectSerializer::serializeConfig(std::ofstream& os) { write(os, "config"); // Dt write(os, "dt"); write(os, Config::getDt()); write(os, "cend"); } void ProjectSerializer::deserializeConfig(std::ifstream& is) { std::string marker; while(true) { read(is, marker); if(marker == "dt") { float dt; read(is, dt); Config::setDt(dt); } else if(marker == "cend") { return; } else { LOG_WARN("ProjectSerializer", "Unknown marker found at the config [w]$0[]", marker); } } } void ProjectSerializer::serializeComponentSystem(std::ofstream& os) { std::stringstream oss; std::basic_ostream<char>::pos_type posBefore = oss.tellp(); //---------- Write to temporary buffer ----------// // Serialize entity ids std::vector<EntityId> entities = ComponentManager::getNoCloneView(); write(oss, "id");// Entity id marker write<uint64_t>(oss, entities.size()); for(EntityId entity : entities) write(oss, entity); // Serialize number of components write<uint32_t>(oss, ComponentManager::getComponentRegistries().size()); // Serialize components for(auto compReg : ComponentManager::getComponentRegistries()) { // Write name write(oss, compReg->getDescription().name); // Get all entities that have this component std::vector<std::pair<EntityId,Component*>> pairs; for(auto entity : entities) { Component* comp = ComponentManager::getEntityComponentById(compReg->getId(), entity); if(comp != nullptr) pairs.push_back(std::make_pair(entity, comp)); } // Write size in bytes of this next section (can be useful if the component is unknown and can't be deserialized) unsigned totalSectionSize = 0; for(auto compPair : pairs) totalSectionSize += compReg->getSerializedSize(compPair.second) + sizeof(EntityId); write<uint32_t>(oss, totalSectionSize); std::basic_ostream<char>::pos_type posBef = oss.tellp(); for(auto compPair : pairs) { // TODO Open vector write(oss, compPair.first); compReg->serialize(oss, compPair.second); } ASSERT(oss.tellp()-posBef == totalSectionSize, "Serialized section size and calculated section size does not match"); } //---------- Flush buffer to file ----------// // Write section header size_t size = (int)oss.tellp() - posBefore; write(os, "comp");// Section title write(os, size);// Section size // Write section body char* buffer = new char[size]; oss.rdbuf()->pubseekpos(0);// Return to first position oss.rdbuf()->sgetn(buffer, size);// Copy to buffer os.write(reinterpret_cast<const char*>(buffer), size); delete[] buffer; } void ProjectSerializer::deserializeComponentSystem(std::ifstream& is) { // Read section size in bytes size_t sizeBytes; read(is, sizeBytes); int endSectionPos = int(is.tellg()) + sizeBytes;// Used to validate position at the end // Read section std::string marker; uint32_t numComponents = 0; // Read entity ids { read(is, marker); if(marker != "id") { LOG_WARN("ProjectSerializer", "First component marker must be [w]id[], but it is [w]$0[]. Could not load atta file", marker); return; } uint64_t numIds; read(is, numIds); for(uint64_t i = 0; i < numIds; i++) { EntityId id; read(is, id); EntityId res = ComponentManager::createEntity(id); if(res != id) LOG_WARN("ProjectSerializer","Could not create entity with id $0", id); } } // Read number of components read(is, numComponents); for(uint32_t i = 0; i < numComponents; i++) { uint32_t componentSectionSize;// Can be used to skip the component data if it is an unknown component // Read component name read(is, marker); read(is, componentSectionSize); ComponentRegistry* compReg = nullptr; int componentSectionEndPos = int(is.tellg()) + componentSectionSize; // Find correct component registry for(auto componentRegistry : ComponentManager::getComponentRegistries()) { if(componentRegistry->getDescription().name == marker) { compReg = componentRegistry; break; } } // If not found the component, skip this section if(compReg == nullptr) { is.ignore(componentSectionEndPos); continue; } // Deserialize while(int(is.tellg()) < componentSectionEndPos) { EntityId eid; read(is, eid); Component* component = ComponentManager::addEntityComponentById(compReg->getId(), eid); compReg->deserialize(is, component); } // Check finished at right position if(int(is.tellg()) != componentSectionEndPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for [*w]component $2 section[]. Some data may have been incorrectly initialized for this component", (int)is.tellg(), componentSectionEndPos, compReg->getDescription().name); is.seekg(componentSectionEndPos, std::ios_base::beg); } } if(int(is.tellg()) != endSectionPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for the [*w]component system section[]. Some data may have been incorrectly initialized", (int)is.tellg(), endSectionPos); is.seekg(endSectionPos, std::ios_base::beg); } } void ProjectSerializer::serializeGraphicsSystem(std::ofstream& os) { std::stringstream oss; std::basic_ostream<char>::pos_type posBefore = oss.tellp(); //---------- Write to temporary buffer ----------// // Number of subsections write<uint32_t>(oss, 1); //----- Viewport subsection -----// write(oss, "viewports"); std::vector<std::shared_ptr<Viewport>> viewports = GraphicsManager::getViewports(); unsigned sectionSize = 0; for(auto viewport : viewports) sectionSize += viewport->getSerializedSize(); // Serialize section size in bytes write<uint32_t>(oss, sectionSize); // Serialize number of viewports write<uint32_t>(oss, viewports.size()); // Serialize for(auto viewport : viewports) viewport->serialize(oss); //---------- Flush buffer to file ----------// // Write section header size_t size = (int)oss.tellp() - posBefore; write(os, "gfx");// Section title write(os, size);// Section size // Write section body char* buffer = new char[size]; oss.rdbuf()->pubseekpos(0);// Return to first position oss.rdbuf()->sgetn(buffer, size);// Copy to buffer os.write(reinterpret_cast<const char*>(buffer), size); delete[] buffer; } void ProjectSerializer::deserializeGraphicsSystem(std::ifstream& is) { size_t sizeBytes; read(is, sizeBytes); int sectionEndPos = int(is.tellg()) + sizeBytes;// Used to validate position at the end unsigned numSections; read(is, numSections); unsigned curr = numSections; while(curr--) { std::string marker; read(is, marker); if(marker == "viewports") { // Read section size in bytes unsigned sectionSize; read(is, sectionSize); // Read number of viewports unsigned numViewports; read(is, numViewports); // Deserialize GraphicsManager::clearViewports(); for(unsigned i = 0; i < numViewports; i++) { std::shared_ptr<Viewport> viewport; viewport = std::make_shared<Viewport>(Viewport::CreateInfo{}); viewport->deserialize(is); GraphicsManager::addViewport(viewport); } } } if(int(is.tellg()) != sectionEndPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for the [*w]graphics system section[]. Some data may have been incorrectly initialized", (int)is.tellg(), sectionEndPos); is.seekg(sectionEndPos, std::ios_base::beg); } } }
33.587342
293
0.544434
brenocq
e7ecbe09ed03cde709de89e8bf0cb077e84f8009
1,689
cpp
C++
UInterfaceLib/UInterfaceLib/CConfigBase.cpp
hanbox/UInterfaceLib
6724d5eda486fe604c13bc1bc11a66d3c53dec56
[ "MIT" ]
14
2017-02-24T15:37:27.000Z
2021-12-30T11:13:49.000Z
UInterfaceLib/UInterfaceLib/CConfigBase.cpp
HanBox2016/UInterfaceLib
6724d5eda486fe604c13bc1bc11a66d3c53dec56
[ "MIT" ]
null
null
null
UInterfaceLib/UInterfaceLib/CConfigBase.cpp
HanBox2016/UInterfaceLib
6724d5eda486fe604c13bc1bc11a66d3c53dec56
[ "MIT" ]
11
2017-09-01T08:13:32.000Z
2021-12-30T11:13:44.000Z
#include "StdAfx.h" #include "CConfigBase.h" CConfigBase::CConfigBase(void) { } CConfigBase::~CConfigBase(void) { } int CConfigBase::LoadConfig(string strPath, vector<STPAIR> &v_stPair) { int iRet = ULIB_FALSE; m_strPath = strPath; iRet = m_pFile->InitFile(strPath); for ( int i = 0; i < v_stPair.size(); i++ ) { string strData = m_pFile->Get(v_stPair[i].strTitle, v_stPair[i].strA); v_stPair[i].strB = strData; } return iRet; } int CConfigBase::SaveConfig(string strPath, vector<STPAIR> v_stPair) { int iRet = ULIB_FALSE; m_pFile->InitFile(strPath); m_pFile->ClearnFile(); m_pFile->Add(v_stPair); m_pFile->WriteFile(strPath); return iRet; } boolean CConfigBase::SetFileType(int iType) { boolean bRet = true; m_iType = iType; if ( iType == ULIB_FILE_TYPE_XML ) { m_pFile = boost::shared_ptr<CCFileBase>(new CCFileXml()); } else if ( iType == ULIB_FILE_TYPE_INI ) { m_pFile = boost::shared_ptr<CCFileBase>(new CCFileIni()); } else { bRet = false; } return bRet; } boost::shared_ptr<CConfigBase> m_pConfig = nullptr; extern "C" __declspec(dllexport) int LoadConfig(int iType, string strPath, vector<STPAIR> &v_stPair) { if ( m_pConfig == nullptr ) { m_pConfig = boost::shared_ptr<CConfigBase>(new CConfigBase()); } m_pConfig->SetFileType(iType); int iRet = m_pConfig->LoadConfig(strPath, v_stPair); return iRet; } extern "C" __declspec(dllexport) int SaveConfig(int iType, string strPath, vector<STPAIR> &v_stPair) { if ( m_pConfig == nullptr ) { m_pConfig = boost::shared_ptr<CConfigBase>(new CConfigBase()); } m_pConfig->SetFileType(iType); int iRet = m_pConfig->SaveConfig(strPath, v_stPair); return iRet; }
18.16129
100
0.702783
hanbox
e7efd444fb854946efc856df366d11f249d692db
233
cpp
C++
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
#include <ncurses.h> int main(void) { initscr(); char text[] = "Greetings from NCurses!"; char *t = text; while(*t) { addch(*t++); refresh(); napms(100); } endwin(); return 0; }
12.944444
44
0.472103
ADITYA-CS
e7f039a3480d5001ccc2814ae9898acf0a79cdaf
483
cpp
C++
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
#include "node.h" Node::Node() { } Node::Node(char value_, int rate_, bool isLeaf_) { value = value_; rate = rate_; isLeaf = isLeaf_; } Node::~Node() { } void Node::addChild(Node node) { children.push_back(node); } bool operator<(const Node& n1, const Node& n2) { return n1.rate < n2.rate; } bool operator>(const Node& n1, const Node& n2) { return n1.rate > n2.rate; } bool operator==(const Node& n1, const Node& n2) { return n1.rate == n2.rate; }
13.054054
48
0.619048
pedroccrp
e7f492461bfc00bb977f00bfedf19f318ec6a485
807
cpp
C++
Source/FSD/Private/EnemyPawn.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/EnemyPawn.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/EnemyPawn.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#include "EnemyPawn.h" #include "Net/UnrealNetwork.h" #include "EnemyHealthComponent.h" #include "PawnStatsComponent.h" #include "EnemyPawnAfflictionComponent.h" #include "EnemyComponent.h" void AEnemyPawn::OnRep_QueuedMontage() { } void AEnemyPawn::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AEnemyPawn, QueuedMontage); } AEnemyPawn::AEnemyPawn() { this->Health = CreateDefaultSubobject<UEnemyHealthComponent>(TEXT("Health")); this->Stats = CreateDefaultSubobject<UPawnStatsComponent>(TEXT("Stats")); this->Affliction = CreateDefaultSubobject<UEnemyPawnAfflictionComponent>(TEXT("Affliction")); this->enemy = CreateDefaultSubobject<UEnemyComponent>(TEXT("enemy")); }
31.038462
97
0.77943
trumank
e7f4dc026ad488f4a4b3e4f1f385c222346d1ab6
1,901
cpp
C++
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
4
2019-05-31T22:55:49.000Z
2020-11-26T11:55:34.000Z
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
null
null
null
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
1
2018-04-11T02:50:47.000Z
2018-04-11T02:50:47.000Z
#include "UIInputComponent.h" #include "ZooidUI.h" #include "ZEGameContext.h" #include "Input/InputManager.h" #include "Input/Keys.h" namespace ZE { IMPLEMENT_CLASS_1(UIInputComponent, Component); UIInputComponent::UIInputComponent(GameContext* gameContext) : Component(gameContext) { } void UIInputComponent::setupComponent() { Component::setupComponent(); addEventDelegate(Event_UPDATE, &UIInputComponent::handleUpdateEvent); addEventDelegate(Event_MOUSE_SCROLL, &UIInputComponent::handleMouseScroll); addEventDelegate(Event_KEY_UP, &UIInputComponent::handleKeyUp); addEventDelegate(Event_KEY_DOWN, &UIInputComponent::handleKeyDown); addEventDelegate(Event_TEXT_INPUT, &UIInputComponent::handleTextInput); } void UIInputComponent::handleUpdateEvent(Event* _event) { Int32 mouseX = 0; Int32 mouseY = 0; EButtonState buttonState = EButtonState::BUTTON_DOWN; InputManager* inputManager = m_gameContext->getInputManager(); inputManager->getMousePosition(mouseX, mouseY); buttonState = inputManager->IsKeyDown(Key::MouseLeftButton) ? EButtonState::BUTTON_DOWN : EButtonState::BUTTON_UP; ZE::UI::UpdateMouseState((Float32)mouseX, (Float32)mouseY, buttonState); } void UIInputComponent::handleMouseScroll(Event* _event) { Event_MOUSE_SCROLL* pRealEvent = (Event_MOUSE_SCROLL*)_event; ZE::UI::RecordMouseScroll(pRealEvent->m_deltaScrollY); } void UIInputComponent::handleKeyUp(Event* _event) { Event_INPUT* inputEvent = (Event_INPUT*)_event; ZE::UI::RecordKeyboardButton(inputEvent->m_keyId, 1); } void UIInputComponent::handleKeyDown(Event* _event) { Event_INPUT* inputEvent = (Event_INPUT*)_event; ZE::UI::RecordKeyboardButton(inputEvent->m_keyId, 0); } void UIInputComponent::handleTextInput(Event* _event) { Event_TEXT_INPUT* inputEvent = (Event_TEXT_INPUT*)_event; ZE::UI::RecordTextInput(inputEvent->m_charCode); } }
27.550725
116
0.776433
azon04
e7fa714d7f40dcea1a236b7ac245bc545bbac3b3
2,190
cpp
C++
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
33
2017-01-13T20:47:21.000Z
2022-03-21T23:29:17.000Z
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
null
null
null
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
4
2016-12-10T16:10:42.000Z
2020-06-28T04:44:11.000Z
// Implements a settings menu for end-user. This is in a separate module // so that it can be shared between multiple small example games. #include "common.hpp" #include "renderer.hpp" #include "glrenderer/renderdevice.hpp" #include "audio.hpp" #include "gui.hpp" #include "../game.hpp" #include <json11/json11.hpp> using json11::Json; MODULE_EXPORT void MODULE_FUNC_NAME(uint msg, void* param) { Game& game = *static_cast<Game*>(param); switch (msg) { case $id(INIT): case $id(RELOAD): { game.moduleInit(); break; } case $id(DRAW_SETTINGS_MENU): { RenderSystem& renderer = game.entities.get_system<RenderSystem>(); AudioSystem& audio = game.entities.get_system<AudioSystem>(); bool vsync = game.engine.vsync(); bool oldVsync = vsync; ImGui::Checkbox("V-sync", &vsync); if (vsync != oldVsync) game.engine.vsync(vsync); ImGui::SameLine(); bool fullscreen = game.engine.fullscreen(); bool oldFullscreen = fullscreen; ImGui::Checkbox("Fullscreen", &fullscreen); if (fullscreen != oldFullscreen) { game.engine.fullscreen(fullscreen); renderer.device().resizeRenderTargets(RenderDevice::RENDER_TARGET_SCREEN); } float volume = audio.soloud->getGlobalVolume(); float oldVolume = volume; ImGui::SliderFloat("Volume", &volume, 0.f, 1.25f); if (volume != oldVolume) audio.soloud->setGlobalVolume(volume); ImGui::SliderInt("Threads", (int*)&game.engine.threads, 0, 8); if (CVar<int>* cvar_msaa = CVar<int>::getCVar("r.msaaSamples")) { int oldMsaa = glm::max((*cvar_msaa)(), 1); float msaa = log2(oldMsaa); ImGui::SliderFloat("MSAA", &msaa, 0.f, 3.f, "%.0f"); int newMsaa = powf(2, msaa); ImGui::SameLine(); ImGui::Text("%dx", newMsaa); if (newMsaa != oldMsaa) { cvar_msaa->value = newMsaa; renderer.device().resizeRenderTargets(RenderDevice::RENDER_TARGET_SCREEN); } } bool fxaa = renderer.env().postAA == Environment::POST_AA_FXAA; ImGui::Checkbox("FXAA", &fxaa); renderer.env().postAA = fxaa ? Environment::POST_AA_FXAA : Environment::POST_AA_NONE; ImGui::SameLine(); ImGui::Checkbox("Shadows", &renderer.settings.shadows); break; } } }
30
88
0.677626
tapio
e7fc661eb3da78393138874d92b0124b6335f4fb
4,069
cpp
C++
StyleFramework/StyleGridCtrl.cpp
edwig/StyleFramework
c9b19af74f5298c3da348cdbdc988191e76ed807
[ "MIT" ]
2
2021-04-03T12:50:30.000Z
2022-02-08T23:23:56.000Z
StyleFramework/StyleGridCtrl.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
10
2022-01-14T13:28:32.000Z
2022-02-13T12:46:34.000Z
StyleFramework/StyleGridCtrl.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////// // // File: StyleGridCtrl.cpp // Function: Styling frame for the Chris Maunder CGridCtrl grid. // // _____ _ _ _ ______ _ // / ____| | | (_) | ____| | | // | (___ | |_ _ _| |_ _ __ __ _| |__ _ __ __ _ _ __ ___ _____ _____ _ __| | __ // \___ \| __| | | | | | '_ \ / _` | __| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ / // ____) | |_| |_| | | | | | | (_| | | | | | (_| | | | | | | __/\ V V / (_) | | | < // |_____/ \__|\__, |_|_|_| |_|\__, |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\ // __/ | __/ | // |___/ |___/ // // // Author: ir. W.E. Huisman // For license: See the file "LICENSE.txt" in the root folder // #include "stdafx.h" #include "StyleGridCtrl.h" #include "StyleFonts.h" #include "Stylecolors.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // StyleGridCtrl StyleGridCtrl::StyleGridCtrl() { } StyleGridCtrl::~StyleGridCtrl() { } BEGIN_MESSAGE_MAP(StyleGridCtrl, CGridCtrl) ON_WM_PAINT() ON_WM_SHOWWINDOW() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // message handlers void StyleGridCtrl::InitSkin() { // Test if init already done if(GetWindowLongPtr(GetSafeHwnd(),GWLP_USERDATA) != NULL) { return; } // Skin our grid SetFont(&STYLEFONTS.DialogTextFont); SkinScrollWnd* skin = SkinWndScroll(this,1); skin->SetScrollbarBias(0); } void StyleGridCtrl::ResetSkin() { UnskinWndScroll(this); } LRESULT StyleGridCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if(message == WM_VSCROLL || message == WM_HSCROLL) { WORD sbCode = LOWORD(wParam); if (sbCode == SB_THUMBTRACK || sbCode == SB_THUMBPOSITION) { SCROLLINFO siv = { 0 }; siv.cbSize = sizeof(SCROLLINFO); siv.fMask = SIF_ALL; SCROLLINFO sih = siv; int nPos = HIWORD(wParam); GetScrollInfo(SB_VERT, &siv); GetScrollInfo(SB_HORZ, &sih); // Rather clunky: but it gets the job done // But this is what CGridCtrl also does: translate to single scroll actions if (WM_VSCROLL == message) { return SendMessage(message,nPos > siv.nPos ? SB_LINEDOWN : SB_LINEUP,0); } else { return SendMessage(message,nPos > sih.nPos ? SB_RIGHT : SB_LEFT); } } } return CGridCtrl::WindowProc(message, wParam, lParam); } void StyleGridCtrl::DrawFrame() { COLORREF color = ThemeColor::_Color1; SkinScrollWnd* skin = (SkinScrollWnd*)GetWindowLongPtr(m_hWnd,GWLP_USERDATA); if(skin) { skin->DrawFrame(color); } } void StyleGridCtrl::OnPaint() { if(!m_inPaint) { m_inPaint = true; CGridCtrl::OnPaint(); DrawFrame(); m_inPaint = false; } } SkinScrollWnd* StyleGridCtrl::GetSkin() { return (SkinScrollWnd*)GetWindowLongPtr(GetSafeHwnd(), GWLP_USERDATA); } // Propagate the ShowWindow command void StyleGridCtrl::OnShowWindow(BOOL bShow, UINT nStatus) { SkinScrollWnd* skin = GetSkin(); if (skin && nStatus == 0) { // nStatus == 0 means: Message sent is caused by an explict "ShowWindow" call skin->ShowWindow(bShow ? SW_SHOW : SW_HIDE); } else { CGridCtrl::OnShowWindow(bShow, nStatus); } } ////////////////////////////////////////////////////////////////////////// // // SUPPORT FOR DynamicDataEXchange in Dialogs // ////////////////////////////////////////////////////////////////////////// void WINAPI DDX_Control(CDataExchange* pDX,int nIDC,StyleGridCtrl& p_gridControl) { CWnd& control = reinterpret_cast<CWnd&>(p_gridControl); DDX_Control(pDX,nIDC,control); p_gridControl.InitSkin(); }
25.753165
91
0.529123
edwig
e7fcefc0e0a7f5b05a9d3530c85fee061e89034e
15,397
cpp
C++
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
2
2020-09-08T15:58:16.000Z
2020-09-09T12:44:18.000Z
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
null
null
null
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
null
null
null
/** * GaussLegendreQuad.cpp : xyfd class for representing Gauss-Legendre quadrature rules. * * @author * Xiasu Yang <xiasu.yang@sorbonne-universite.fr> */ /*------------------------------------------------------------------*\ Dependencies \*------------------------------------------------------------------*/ #include "GaussLegendreQuad.h" #include <iostream> #include <cmath> #include <vector> #include <array> /*------------------------------------------------------------------*\ Aliases \*------------------------------------------------------------------*/ using StdArray2d = std::array<double, 2>; using DoubleVec = std::vector<double>; //-More comments in GaussLegendreQuad.h // namespace xyfd { void GaussLegendreQuad::_setX() { int deg = floor((order_ - 1)/2) + 1; if (deg < 1) throw std::invalid_argument("Gauss-Legendre degree must >= 1!!!"); else if (deg > 12) throw std::invalid_argument("deg > 12 data not available for Gauss-Legendre rule!!!"); else if (deg == 1) x_ = {0.}; else if (deg == 2) x_ = {-1./sqrt(3.), 1./sqrt(3.)}; else if (deg == 3) x_ = {-sqrt(3.)/sqrt(5.), 0., sqrt(3.)/sqrt(5.)}; else if (deg == 4) x_= {-sqrt(15.+2.*sqrt(30.))/sqrt(35.), -sqrt(15.-2.*sqrt(30.))/sqrt(35.), sqrt(15.-2.*sqrt(30.))/sqrt(35.), sqrt(15.+2.*sqrt(30.))/sqrt(35.)}; else if (deg == 5) x_ = {-sqrt(35.+2.*sqrt(70.))/(3.*sqrt(7.)), -sqrt(35.-2.*sqrt(70.))/(3.*sqrt(7.)), 0., sqrt(35.-2.*sqrt(70.))/(3.*sqrt(7.)), sqrt(35.+2.*sqrt(70.))/(3.*sqrt(7.))}; else if (deg == 6) x_ = {-0.932469514203152027812301554493994609134765737712289824872549616526613, -0.661209386466264513661399595019905347006448564395170070814526705852183, -0.238619186083196908630501721680711935418610630140021350181395164574274, 0.238619186083196908630501721680711935418610630140021350181395164574274, 0.661209386466264513661399595019905347006448564395170070814526705852183, 0.932469514203152027812301554493994609134765737712289824872549616526613}; else if (deg == 7) x_ = {-0.949107912342758524526189684047851262400770937670617783548769103913063, -0.741531185599394439863864773280788407074147647141390260119955351967429, -0.405845151377397166906606412076961463347382014099370126387043251794663, 0., 0.405845151377397166906606412076961463347382014099370126387043251794663, 0.741531185599394439863864773280788407074147647141390260119955351967429, 0.949107912342758524526189684047851262400770937670617783548769103913063}; else if (deg == 8) x_ = {-0.960289856497536231683560868569472990428235234301452038271639777372424, -0.796666477413626739591553936475830436837171731615964832070170295039217, -0.525532409916328985817739049189246349041964243120392857750857099272454, -0.183434642495649804939476142360183980666757812912973782317188473699204, 0.183434642495649804939476142360183980666757812912973782317188473699204, 0.525532409916328985817739049189246349041964243120392857750857099272454, 0.796666477413626739591553936475830436837171731615964832070170295039217, 0.960289856497536231683560868569472990428235234301452038271639777372424}; else if (deg == 9) x_ = {-0.968160239507626089835576202903672870049404800491925329550023311849080, -0.836031107326635794299429788069734876544106718124675996104371979639455, -0.613371432700590397308702039341474184785720604940564692872812942281267, -0.324253423403808929038538014643336608571956260736973088827047476842186, 0., 0.324253423403808929038538014643336608571956260736973088827047476842186, 0.613371432700590397308702039341474184785720604940564692872812942281267, 0.836031107326635794299429788069734876544106718124675996104371979639455, 0.968160239507626089835576202903672870049404800491925329550023311849080}; else if (deg == 10) x_ = {-0.973906528517171720077964012084452053428269946692382119231212066696595, -0.865063366688984510732096688423493048527543014965330452521959731845374, -0.679409568299024406234327365114873575769294711834809467664817188952558, -0.433395394129247190799265943165784162200071837656246496502701513143766, -0.148874338981631210884826001129719984617564859420691695707989253515903, 0.148874338981631210884826001129719984617564859420691695707989253515903, 0.433395394129247190799265943165784162200071837656246496502701513143766, 0.679409568299024406234327365114873575769294711834809467664817188952558, 0.865063366688984510732096688423493048527543014965330452521959731845374, 0.973906528517171720077964012084452053428269946692382119231212066696595}; else if (deg == 11) x_ = {-0.978228658146056992803938001122857390771422408919784415425801065983663, -0.887062599768095299075157769303927266631675751225314384967411055537611, -0.730152005574049324093416252031153458049643062026130311978378339687013, -0.519096129206811815925725669458609554480227115119928489020922611486695, -0.269543155952344972331531985400861524679621862439052281623925631880057, 0., 0.269543155952344972331531985400861524679621862439052281623925631880057, 0.519096129206811815925725669458609554480227115119928489020922611486695, 0.730152005574049324093416252031153458049643062026130311978378339687013, 0.887062599768095299075157769303927266631675751225314384967411055537611, 0.978228658146056992803938001122857390771422408919784415425801065983663}; else if (deg == 12) x_ = {-0.981560634246719250690549090149280822960155199813731510462682121807793, -0.904117256370474856678465866119096192537596709213297546554075760681234, -0.769902674194304687036893833212818075984925750018931637664419064249116, -0.587317954286617447296702418940534280369098514048052481510270879667340, -0.367831498998180193752691536643717561256360141335409621311799879504089, -0.125233408511468915472441369463853129983396916305444273212921754748462, 0.125233408511468915472441369463853129983396916305444273212921754748462, 0.367831498998180193752691536643717561256360141335409621311799879504089, 0.587317954286617447296702418940534280369098514048052481510270879667340, 0.769902674194304687036893833212818075984925750018931637664419064249116, 0.904117256370474856678465866119096192537596709213297546554075760681234, 0.981560634246719250690549090149280822960155199813731510462682121807793}; } void GaussLegendreQuad::_setW() { int deg = floor((order_ - 1)/2) + 1; if (deg < 1) throw std::invalid_argument("Gauss-Legendre degree must >= 1!!!"); else if (deg > 12) throw std::invalid_argument("deg > 12 data not available for Gauss-Legendre rule!!!"); else if (deg == 1) w_ = {2.}; else if (deg == 2) w_ = {1., 1.}; else if (deg == 3) w_ = {5./9., 8./9., 5./9.}; else if (deg == 4) w_ = {49./(6.*(18.+sqrt(30.))), 49./(6.*(18.-sqrt(30.))), 49./(6.*(18.-sqrt(30.))), 49./(6.*(18.+sqrt(30.)))}; else if (deg == 5) w_ = {5103./(50.*(322.+13.*sqrt(70.))), 5103./(50.*(322.-13.*sqrt(70.))), 128./225., 5103./(50.*(322.-13.*sqrt(70.))), 5103./(50.*(322.+13.*sqrt(70.)))}; else if (deg == 6) w_ = {0.171324492379170345040296142172732893526822501484043982398635439798945, 0.360761573048138607569833513837716111661521892746745482289739240237140, 0.467913934572691047389870343989550994811655605769210535311625319963914, 0.467913934572691047389870343989550994811655605769210535311625319963914, 0.360761573048138607569833513837716111661521892746745482289739240237140, 0.171324492379170345040296142172732893526822501484043982398635439798945}; else if (deg == 7) w_ = {0.129484966168869693270611432679082018328587402259946663977208638724655, 0.279705391489276667901467771423779582486925065226598764537014032693618, 0.381830050505118944950369775488975133878365083533862734751083451030705, 0.417959183673469387755102040816326530612244897959183673469387755102040, 0.381830050505118944950369775488975133878365083533862734751083451030705, 0.279705391489276667901467771423779582486925065226598764537014032693618, 0.129484966168869693270611432679082018328587402259946663977208638724655}; else if (deg == 8) w_ = {0.101228536290376259152531354309962190115394091051684957059003698064740, 0.222381034453374470544355994426240884430130870051249564725909289293616, 0.313706645877887287337962201986601313260328999002734937690263945074656, 0.362683783378361982965150449277195612194146039894330540524823067566686, 0.362683783378361982965150449277195612194146039894330540524823067566686, 0.313706645877887287337962201986601313260328999002734937690263945074956, 0.222381034453374470544355994426240884430130870051249564725909289293616, 0.101228536290376259152531354309962190115394091051684957059003698064740}; else if (deg == 9) w_ = {0.0812743883615744119718921581105236506756617207824107507111076768806866, 0.180648160694857404058472031242912809514337821732040484498335906471357, 0.260610696402935462318742869418632849771840204437299951939997002119610, 0.312347077040002840068630406584443665598754861261904645554011165599143, 0.330239355001259763164525069286974048878810783572688334593096497858402, 0.312347077040002840068630406584443665598754861261904645554011165599143, 0.260610696402935462318742869418632849771840204437299951939997002119610, 0.180648160694857404058472031242912809514337821732040484498335906471357, 0.0812743883615744119718921581105236506756617207824107507111076768806866}; else if (deg == 10) w_ = {0.0666713443086881375935688098933317928578648343201581451286948816134120, 0.149451349150580593145776339657697332402556639669427367835477268753238, 0.219086362515982043995534934228163192458771870522677089880956543635199, 0.269266719309996355091226921569469352859759938460883795800563276242153, 0.295524224714752870173892994651338329421046717026853601354308029755995, 0.295524224714752870173892994651338329421046717026853601354308029755995, 0.269266719309996355091226921569469352859759938460883795800563276242153, 0.219086362515982043995534934228163192458771870522677089880956543635199, 0.149451349150580593145776339657697332402556639669427367835477268753238, 0.0666713443086881375935688098933317928578648343201581451286948816134120}; else if (deg == 11) w_ = {0.0556685671161736664827537204425485787285156256968981483483842856741554, 0.125580369464904624634694299223940100197615791395403500663934010817914, 0.186290210927734251426097641431655891691284748040203411781506404173872, 0.233193764591990479918523704843175139431798172316958509027319722121932, 0.262804544510246662180688869890509195372764677603144556380055371485512, 0.272925086777900630714483528336342189156041969894783747597600411453225, 0.262804544510246662180688869890509195372764677603144556380055371485512, 0.233193764591990479918523704843175139431798172316958509027319722121932, 0.186290210927734251426097641431655891691284748040203411781506404173872, 0.125580369464904624634694299223940100197615791395403500663934010817914, 0.0556685671161736664827537204425485787285156256968981483483842856741554}; else if (deg == 12) w_ = {0.0471753363865118271946159614850170603170290739948470895605053470038097, 0.106939325995318430960254718193996224214570173470324880005126042102818, 0.160078328543346226334652529543359071872011730490864177909899544157954, 0.203167426723065921749064455809798376506518147274590146398594565797645, 0.233492536538354808760849898924878056259409972199754874730523497821492, 0.249147045813402785000562436042951210830460902569618831395351003116279, 0.249147045813402785000562436042951210830460902569618831395351003116279, 0.233492536538354808760849898924878056259409972199754874730523497821492, 0.203167426723065921749064455809798376506518147274590146398594565797645, 0.160078328543346226334652529543359071872011730490864177909899544157954, 0.106939325995318430960254718193996224214570173470324880005126042102818, 0.0471753363865118271946159614850170603170290739948470895605053470038097}; } GaussLegendreQuad::GaussLegendreQuad(int order) //-Remark : use member initializer list when possible // to limit parameter copying : order_(order) { _setX(); _setW(); } GaussLegendreQuad::GaussLegendreQuad(const GaussLegendreQuad &obj) : order_(obj.order_), x_(obj.x_), w_(obj.w_) {} GaussLegendreQuad &GaussLegendreQuad::operator=(const GaussLegendreQuad &obj) { order_ = obj.order_; x_ = obj.x_; w_ = obj.w_; return *this; } int GaussLegendreQuad::getOrder() const { return order_; } DoubleVec GaussLegendreQuad::getX() const { return x_; } DoubleVec GaussLegendreQuad::getW() const { return w_; } } // namespace xyfd
58.543726
98
0.673053
xxxiasu
f004013521faa90ad816c94861c38780108d8daa
1,568
cpp
C++
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/Ui/FlowUiScrollerNodes.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/Ui/FlowUiScrollerNodes.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/CryEngine/CryAction/FlowSystem/Nodes/Ui/FlowUiScrollerNodes.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.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 "StdAfx.h" #include "UiFlow.h" #include <LyShine/Bus/UiScrollerBus.h> //////////////////////////////////////////////////////////////////////////////////////////////////// // Get/Set flow nodes //////////////////////////////////////////////////////////////////////////////////////////////////// UI_FLOW_NODE__GET_AND_SET_FLOAT(Scroller, Value, "Get the value of the Scroller (0 - 1)", "Set the value of the Scroller (0 - 1)", "Value", "The value (0 - 1) of element [ElementID]"); UI_FLOW_NODE__GET_AND_SET_AZ_STRING(Scroller, ValueChangingActionName, "Get the action triggered while the value of the Scroller is changing", "Set the action triggered while the value of the Scroller is changing", "ChangingAction", "The action name"); UI_FLOW_NODE__GET_AND_SET_AZ_STRING(Scroller, ValueChangedActionName, "Get the action triggered when the value of the Scroller is done changing", "Set the action triggered when the value of the Scroller is done changing", "ChangedAction", "The action name");
46.117647
100
0.649872
crazyskateface
f0054f2b37a8b3f7886ec48108958a54d0fe74b6
2,670
cpp
C++
android/android_42/native/services/sensorservice/LinearAccelerationSensor.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/native/services/sensorservice/LinearAccelerationSensor.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/native/services/sensorservice/LinearAccelerationSensor.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdint.h> #include <math.h> #include <sys/types.h> #include <utils/Errors.h> #include <hardware/sensors.h> #include "LinearAccelerationSensor.h" #include "SensorDevice.h" #include "SensorFusion.h" namespace android { // --------------------------------------------------------------------------- LinearAccelerationSensor::LinearAccelerationSensor(sensor_t const* list, size_t count) : mSensorDevice(SensorDevice::getInstance()), mGravitySensor(list, count) { } bool LinearAccelerationSensor::process(sensors_event_t* outEvent, const sensors_event_t& event) { bool result = mGravitySensor.process(outEvent, event); if (result && event.type == SENSOR_TYPE_ACCELEROMETER) { outEvent->data[0] = event.acceleration.x - outEvent->data[0]; outEvent->data[1] = event.acceleration.y - outEvent->data[1]; outEvent->data[2] = event.acceleration.z - outEvent->data[2]; outEvent->sensor = '_lin'; outEvent->type = SENSOR_TYPE_LINEAR_ACCELERATION; return true; } return false; } status_t LinearAccelerationSensor::activate(void* ident, bool enabled) { return mGravitySensor.activate(this, enabled); } status_t LinearAccelerationSensor::setDelay(void* ident, int handle, int64_t ns) { return mGravitySensor.setDelay(this, handle, ns); } Sensor LinearAccelerationSensor::getSensor() const { Sensor gsensor(mGravitySensor.getSensor()); sensor_t hwSensor; hwSensor.name = "Linear Acceleration Sensor"; hwSensor.vendor = "Google Inc."; hwSensor.version = gsensor.getVersion(); hwSensor.handle = '_lin'; hwSensor.type = SENSOR_TYPE_LINEAR_ACCELERATION; hwSensor.maxRange = gsensor.getMaxValue(); hwSensor.resolution = gsensor.getResolution(); hwSensor.power = gsensor.getPowerUsage(); hwSensor.minDelay = gsensor.getMinDelay(); Sensor sensor(&hwSensor); return sensor; } // --------------------------------------------------------------------------- }; // namespace android
33.375
86
0.669663
yakuizhao
f0069085f03a6eff49cae6b18f4a5eed49d722e6
766
hpp
C++
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
5
2017-03-28T00:36:54.000Z
2019-08-06T00:05:44.000Z
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
4
2017-03-28T01:36:05.000Z
2017-04-17T20:34:46.000Z
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
null
null
null
#ifndef FUNCTION_CALL_EXPR_HPP #define FUNCTION_CALL_EXPR_HPP class FunctionDecl; #include "expr.hpp" class FunctionCallExpr : virtual public Expr { private: FunctionDecl* func; std::vector<std::unique_ptr<Expr>> args; public: FunctionCallExpr() = delete; FunctionCallExpr(ScopeCreator* owner, Expr* pe, FunctionDecl* fd) : Stmt(owner), Expr(owner, pe), func(fd) {} virtual ~FunctionCallExpr() = default; FunctionDecl* getFunc() { return func; } const FunctionDecl* getFunc() const { return func; } void setFunc(FunctionDecl* fd) { func = fd; } std::vector<Expr*> getArgs(); std::vector<const Expr*> getArgs() const; void addArg(std::unique_ptr<Expr> arg) { args.emplace_back(std::move(arg)); } }; #include "function_decl.hpp" #endif
26.413793
79
0.715405
bfeip
f00ac9b055704cdea5f7e2c8677c5d0a2c99a793
369
cpp
C++
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
2
2022-03-11T20:13:05.000Z
2022-03-12T07:49:01.000Z
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
null
null
null
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
1
2022-03-11T20:13:07.000Z
2022-03-11T20:13:07.000Z
#include "Functions.h" void memcpy(byte* dst, byte* src, u32 len) { for (u32 i = 0; i < len; i++) dst[i] = src[i]; } void memset(byte* buffer, byte value, u32 len) { for (u32 i = 0; i < len; i++) buffer[i] = value; } bool32 memcmp(byte* a, byte* b, u32 len) { for (u32 i = 0; i < len; i++) if (a[i] != b[i]) return false; return true; }
20.5
49
0.531165
feudalnate
f00ae0c4d6b14bdbcc46d71681d471d764c2956f
1,037
hpp
C++
include/src/TypeErasure/areAllConstexpr.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
10
2018-09-09T04:13:12.000Z
2021-04-20T06:23:11.000Z
include/src/TypeErasure/areAllConstexpr.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
3
2018-10-04T01:56:47.000Z
2020-07-01T15:20:26.000Z
include/src/TypeErasure/areAllConstexpr.hpp
zeta1999/METL-recursed
495aaa610eb7a98fa720429ebccf9bb98abc3e55
[ "Apache-2.0" ]
3
2018-09-28T16:04:46.000Z
2020-01-12T10:55:57.000Z
// File: areAllConstexpr.h // // Copyright 2017-2018 Till Heinzel // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once namespace metl { namespace internal { template<class UntypedExpression_t> bool areAllConstexpr(const UntypedExpression_t& e) { return e.isConstexpr(); } template<class UntypedExpression_t> bool areAllConstexpr(const std::vector<UntypedExpression_t>& v) { for(const auto &expr : v) { if(!expr.isConstexpr()) { return false; } } return true; } } }
24.116279
75
0.711668
zeta1999
f00e98f5d3a2c856b1735eb7addc1bc7971531e8
3,377
cpp
C++
04 Drawing/contextinterface.cpp
mld2443/D3D12-Tutorial-04-Drawing
da8812f9b93b24740c0c1ecfcb54a1ad4505ca85
[ "MIT" ]
1
2018-11-25T02:53:56.000Z
2018-11-25T02:53:56.000Z
04 Drawing/contextinterface.cpp
mld2443/D3D12-Tutorial-04-Drawing
da8812f9b93b24740c0c1ecfcb54a1ad4505ca85
[ "MIT" ]
10
2018-10-25T21:15:33.000Z
2020-08-14T15:06:01.000Z
04 Drawing/contextinterface.cpp
mld2443/D3D12-Tutorial-04-Drawing
da8812f9b93b24740c0c1ecfcb54a1ad4505ca85
[ "MIT" ]
1
2018-11-24T17:51:28.000Z
2018-11-24T17:51:28.000Z
//////////////////////////////////////////////////////////////////////////////// // Filename: contextinterface.cpp //////////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "contextinterface.h" ContextInterface::ConstantBufferType::ConstantBufferType(ID3D12Device *device, SIZE_T size) : size(size) , stride(BYTE_ALIGNED_WIDTH(size, 0xFFull)) { // Because CPU and GPU are asynchronus, we need to make room for multiple frames worth of buffers. UINT64 bufferSize = stride * FRAME_BUFFER_COUNT; // Create description for our constant buffer heap type. D3D12_HEAP_PROPERTIES heapProps{}; heapProps.Type = D3D12_HEAP_TYPE_UPLOAD; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; // Create a description for the memory resource itself. D3D12_RESOURCE_DESC resourceDesc{}; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; resourceDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; resourceDesc.Width = bufferSize; resourceDesc.Height = 1; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = 1; resourceDesc.Format = DXGI_FORMAT_UNKNOWN; resourceDesc.SampleDesc.Count = 1; resourceDesc.SampleDesc.Quality = 0; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; // Allocate the memory on the GPU. THROW_IF_FAILED( device->CreateCommittedResource( &heapProps, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(buffer.ReleaseAndGetAddressOf())), "Unable to allocate space for the constant buffer on the graphics device." ); } D3D12_GPU_VIRTUAL_ADDRESS ContextInterface::ConstantBufferType::SetConstantBuffer(UINT frameIndex, BYTE *data) { // Calculate the offset of the constant buffer for the current frame. SIZE_T bufferOffset = static_cast<SIZE_T>(frameIndex) * stride; // Create a zero-width read range, [0, 0]. // This is a signal to the GPU that we won't be reading the data within. D3D12_RANGE range{}; // Lock the constant buffer so it can be written to. BYTE *mappedResource; THROW_IF_FAILED( buffer->Map(0, &range, reinterpret_cast<void**>(&mappedResource)), "Unable to access the constant buffer on the graphics device." ); // Copy the data to the buffer. memcpy(mappedResource + bufferOffset, data, size); // Set the range of data that we wrote to. range.Begin = bufferOffset; range.End = bufferOffset + size; // Unlock the constant buffer. buffer->Unmap(0, &range); // Calculate the address of the data we just wrote to. return buffer->GetGPUVirtualAddress() + bufferOffset; } ContextInterface::ContextInterface(const UINT &frameIndex) : r_frameIndex(frameIndex) { } ID3D12PipelineState * ContextInterface::GetState() { return m_state.Get(); }
36.706522
111
0.639325
mld2443
f01827da3aaf42c2b8e6c91563718b54dacc7769
73
cpp
C++
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
1
2020-07-17T14:03:34.000Z
2020-07-17T14:03:34.000Z
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
null
null
null
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
null
null
null
#include "log.hpp" std::shared_ptr<spdlog::logger> Mud::Logger::logger_;
24.333333
53
0.739726
stridera
f01a432d3b2cff15bd77f551c4995fbcd8bc80a4
1,760
cc
C++
test/mnist_test.cc
WaizungTaam/nn
1d2c9ac6ae59b85c3493be683a2133ac38e00e62
[ "Apache-2.0" ]
null
null
null
test/mnist_test.cc
WaizungTaam/nn
1d2c9ac6ae59b85c3493be683a2133ac38e00e62
[ "Apache-2.0" ]
null
null
null
test/mnist_test.cc
WaizungTaam/nn
1d2c9ac6ae59b85c3493be683a2133ac38e00e62
[ "Apache-2.0" ]
null
null
null
#include "../include/data/mnist.h" #include <iostream> #include <vector> #include "../include/tensor/vector.h" #include "../include/tensor/matrix.h" #include "../include/model/mlp.h" #include "../include/optimizer.h" #include "../include/activ.h" #include "../include/loss.h" int main() { nn::data::MNIST mnist("data/MNIST/"); tensor::Matrix<double> img_train, lbl_train, img_test, lbl_test; mnist.load_train(img_train, lbl_train); mnist.load_test(img_test, lbl_test); std::cout << "Data Loaded.\n"; nn::model::MLP<nn::optimizer::Adam, nn::activ::Sigmoid, nn::loss::Squared> model({784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}); model.train(img_train, lbl_train, 50, 6000); tensor::Matrix<double> raw_pred = model.predict(img_test); tensor::Matrix<double> pred(raw_pred.shape()[0], raw_pred.shape()[1]); for (std::size_t i = 0; i < pred.shape()[0]; ++i) { pred[i] = (raw_pred[i] == raw_pred[i].max()); } std::size_t num_correct = 0; for (std::size_t i = 0; i < pred.shape()[0]; ++i) { if (pred[i].equal(lbl_test[i])) ++num_correct; } std::cout << "Accuracy: " << static_cast<double>(num_correct) / lbl_test.shape()[0] << "\n"; } /* Accuracy: 0.8951 => Adam, Sigmoid, Squared, {784, 100, 10}, {1e-2, 0.5, 0.5, 1e-8}, 10, 2000 Accuracy: 0.8956 => Adam, Sigmoid, Squared, {784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}, 10, 200 Accuracy: 0.8905 => Adam, Sigmoid, Squared, {784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}, 10, 6000 Accuracy: 0.9151 => Adam, Sigmoid, Squared, {784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}, 20, 6000 Accuracy: 0.9307 => Adam, Sigmoid, Squared, {784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}, 40, 6000 Accuracy: 0.9311 => Adam, Sigmoid, Squared, {784, 100, 10}, {2e-2, 0.5, 0.5, 1e-8}, 50, 6000 */
37.446809
92
0.613636
WaizungTaam
f01b3c73bf5c9a48a978288b48022b83aa893a29
34,690
hxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // 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 // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX #define SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace schema { namespace simxml { namespace ResourcesGeneral { class SimMaterial_EquivGlazingMaterial_Blind; } } } #include <memory> // ::std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "simmaterial_equivglazingmaterial.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { class SimMaterial_EquivGlazingMaterial_Blind: public ::schema::simxml::ResourcesGeneral::SimMaterial_EquivGlazingMaterial { public: // SimMaterial_SlatWidth // typedef ::xml_schema::double_ SimMaterial_SlatWidth_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatWidth_type > SimMaterial_SlatWidth_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatWidth_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatWidth_traits; const SimMaterial_SlatWidth_optional& SimMaterial_SlatWidth () const; SimMaterial_SlatWidth_optional& SimMaterial_SlatWidth (); void SimMaterial_SlatWidth (const SimMaterial_SlatWidth_type& x); void SimMaterial_SlatWidth (const SimMaterial_SlatWidth_optional& x); // SimMaterial_SlatAngle // typedef ::xml_schema::double_ SimMaterial_SlatAngle_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatAngle_type > SimMaterial_SlatAngle_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatAngle_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatAngle_traits; const SimMaterial_SlatAngle_optional& SimMaterial_SlatAngle () const; SimMaterial_SlatAngle_optional& SimMaterial_SlatAngle (); void SimMaterial_SlatAngle (const SimMaterial_SlatAngle_type& x); void SimMaterial_SlatAngle (const SimMaterial_SlatAngle_optional& x); // SimMaterial_SlatOrientation // typedef ::xml_schema::string SimMaterial_SlatOrientation_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatOrientation_type > SimMaterial_SlatOrientation_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatOrientation_type, char > SimMaterial_SlatOrientation_traits; const SimMaterial_SlatOrientation_optional& SimMaterial_SlatOrientation () const; SimMaterial_SlatOrientation_optional& SimMaterial_SlatOrientation (); void SimMaterial_SlatOrientation (const SimMaterial_SlatOrientation_type& x); void SimMaterial_SlatOrientation (const SimMaterial_SlatOrientation_optional& x); void SimMaterial_SlatOrientation (::std::auto_ptr< SimMaterial_SlatOrientation_type > p); // SimMaterial_SlatSeparation // typedef ::xml_schema::double_ SimMaterial_SlatSeparation_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatSeparation_type > SimMaterial_SlatSeparation_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatSeparation_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatSeparation_traits; const SimMaterial_SlatSeparation_optional& SimMaterial_SlatSeparation () const; SimMaterial_SlatSeparation_optional& SimMaterial_SlatSeparation (); void SimMaterial_SlatSeparation (const SimMaterial_SlatSeparation_type& x); void SimMaterial_SlatSeparation (const SimMaterial_SlatSeparation_optional& x); // SimMaterial_SlatCrown // typedef ::xml_schema::double_ SimMaterial_SlatCrown_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatCrown_type > SimMaterial_SlatCrown_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatCrown_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatCrown_traits; const SimMaterial_SlatCrown_optional& SimMaterial_SlatCrown () const; SimMaterial_SlatCrown_optional& SimMaterial_SlatCrown (); void SimMaterial_SlatCrown (const SimMaterial_SlatCrown_type& x); void SimMaterial_SlatCrown (const SimMaterial_SlatCrown_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type > SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_traits; const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans () const; SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (); void SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type > SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_traits; const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarTrans () const; SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (); void SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type& x); void SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type > SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_traits; const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect () const; SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (); void SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type > SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_traits; const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarReflect () const; SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (); void SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type& x); void SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type > SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_traits; const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans () const; SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type > SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_traits; const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans () const; SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (); void SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type& x); void SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type > SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_traits; const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect () const; SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type > SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_traits; const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect () const; SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (); void SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type& x); void SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& x); // SimMaterial_SlatDiffuse_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_SlatDiffuse_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatDiffuse_DiffuseSolarTrans_type > SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatDiffuse_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatDiffuse_DiffuseSolarTrans_traits; const SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& SimMaterial_SlatDiffuse_DiffuseSolarTrans () const; SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& SimMaterial_SlatDiffuse_DiffuseSolarTrans (); void SimMaterial_SlatDiffuse_DiffuseSolarTrans (const SimMaterial_SlatDiffuse_DiffuseSolarTrans_type& x); void SimMaterial_SlatDiffuse_DiffuseSolarTrans (const SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& x); // SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type > SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_traits; const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect () const; SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (); void SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type& x); void SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& x); // SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type > SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_traits; const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect () const; SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (); void SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type& x); void SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& x); // SimMaterial_SlatDiffuse_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type > SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatDiffuse_DiffuseVisibleTrans_traits; const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& SimMaterial_SlatDiffuse_DiffuseVisibleTrans () const; SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& SimMaterial_SlatDiffuse_DiffuseVisibleTrans (); void SimMaterial_SlatDiffuse_DiffuseVisibleTrans (const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type& x); void SimMaterial_SlatDiffuse_DiffuseVisibleTrans (const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& x); // SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type > SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_traits; const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect () const; SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (); void SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type& x); void SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& x); // SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type > SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_traits; const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect () const; SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (); void SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type& x); void SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& x); // SimMaterial_SlatInfraredTrans // typedef ::xml_schema::double_ SimMaterial_SlatInfraredTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatInfraredTrans_type > SimMaterial_SlatInfraredTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatInfraredTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatInfraredTrans_traits; const SimMaterial_SlatInfraredTrans_optional& SimMaterial_SlatInfraredTrans () const; SimMaterial_SlatInfraredTrans_optional& SimMaterial_SlatInfraredTrans (); void SimMaterial_SlatInfraredTrans (const SimMaterial_SlatInfraredTrans_type& x); void SimMaterial_SlatInfraredTrans (const SimMaterial_SlatInfraredTrans_optional& x); // SimMaterial_FrontSideSlatInfraredEmissivity // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatInfraredEmissivity_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatInfraredEmissivity_type > SimMaterial_FrontSideSlatInfraredEmissivity_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatInfraredEmissivity_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatInfraredEmissivity_traits; const SimMaterial_FrontSideSlatInfraredEmissivity_optional& SimMaterial_FrontSideSlatInfraredEmissivity () const; SimMaterial_FrontSideSlatInfraredEmissivity_optional& SimMaterial_FrontSideSlatInfraredEmissivity (); void SimMaterial_FrontSideSlatInfraredEmissivity (const SimMaterial_FrontSideSlatInfraredEmissivity_type& x); void SimMaterial_FrontSideSlatInfraredEmissivity (const SimMaterial_FrontSideSlatInfraredEmissivity_optional& x); // SimMaterial_BackSideSlatInfraredEmissivity // typedef ::xml_schema::double_ SimMaterial_BackSideSlatInfraredEmissivity_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatInfraredEmissivity_type > SimMaterial_BackSideSlatInfraredEmissivity_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatInfraredEmissivity_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatInfraredEmissivity_traits; const SimMaterial_BackSideSlatInfraredEmissivity_optional& SimMaterial_BackSideSlatInfraredEmissivity () const; SimMaterial_BackSideSlatInfraredEmissivity_optional& SimMaterial_BackSideSlatInfraredEmissivity (); void SimMaterial_BackSideSlatInfraredEmissivity (const SimMaterial_BackSideSlatInfraredEmissivity_type& x); void SimMaterial_BackSideSlatInfraredEmissivity (const SimMaterial_BackSideSlatInfraredEmissivity_optional& x); // SimMaterial_SlatAngleCntrl // typedef ::xml_schema::string SimMaterial_SlatAngleCntrl_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatAngleCntrl_type > SimMaterial_SlatAngleCntrl_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatAngleCntrl_type, char > SimMaterial_SlatAngleCntrl_traits; const SimMaterial_SlatAngleCntrl_optional& SimMaterial_SlatAngleCntrl () const; SimMaterial_SlatAngleCntrl_optional& SimMaterial_SlatAngleCntrl (); void SimMaterial_SlatAngleCntrl (const SimMaterial_SlatAngleCntrl_type& x); void SimMaterial_SlatAngleCntrl (const SimMaterial_SlatAngleCntrl_optional& x); void SimMaterial_SlatAngleCntrl (::std::auto_ptr< SimMaterial_SlatAngleCntrl_type > p); // Constructors. // SimMaterial_EquivGlazingMaterial_Blind (); SimMaterial_EquivGlazingMaterial_Blind (const RefId_type&); SimMaterial_EquivGlazingMaterial_Blind (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); SimMaterial_EquivGlazingMaterial_Blind (const SimMaterial_EquivGlazingMaterial_Blind& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual SimMaterial_EquivGlazingMaterial_Blind* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; SimMaterial_EquivGlazingMaterial_Blind& operator= (const SimMaterial_EquivGlazingMaterial_Blind& x); virtual ~SimMaterial_EquivGlazingMaterial_Blind (); // Implementation. // protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: SimMaterial_SlatWidth_optional SimMaterial_SlatWidth_; SimMaterial_SlatAngle_optional SimMaterial_SlatAngle_; SimMaterial_SlatOrientation_optional SimMaterial_SlatOrientation_; SimMaterial_SlatSeparation_optional SimMaterial_SlatSeparation_; SimMaterial_SlatCrown_optional SimMaterial_SlatCrown_; SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_; SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_; SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_; SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_; SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_; SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_; SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_; SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_; SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional SimMaterial_SlatDiffuse_DiffuseSolarTrans_; SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_; SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_; SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional SimMaterial_SlatDiffuse_DiffuseVisibleTrans_; SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_; SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_; SimMaterial_SlatInfraredTrans_optional SimMaterial_SlatInfraredTrans_; SimMaterial_FrontSideSlatInfraredEmissivity_optional SimMaterial_FrontSideSlatInfraredEmissivity_; SimMaterial_BackSideSlatInfraredEmissivity_optional SimMaterial_BackSideSlatInfraredEmissivity_; SimMaterial_SlatAngleCntrl_optional SimMaterial_SlatAngleCntrl_; }; } } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX
45.228162
212
0.769155
EnEff-BIM
f01d7722a7494aa12536d92b9f4445bdc7bd5b43
1,875
inl
C++
samples/extensions/open_cl_interop/open_cl_functions.inl
samhsw/Vulkan-Samples
53b75db552330772c3c08734adf1ca983bedbf88
[ "Apache-2.0" ]
20
2020-03-25T17:57:32.000Z
2022-03-12T08:16:10.000Z
samples/extensions/open_cl_interop/open_cl_functions.inl
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-02-18T07:08:52.000Z
2020-02-18T07:08:52.000Z
samples/extensions/open_cl_interop/open_cl_functions.inl
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-04-12T16:23:18.000Z
2020-04-12T16:23:18.000Z
/* Copyright (c) 2021, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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. */ // Core OpenCL functions, loaded from libOpenCL.so #if !defined(OPENCL_EXPORTED_FUNCTION) #define OPENCL_EXPORTED_FUNCTION(fun) #endif OPENCL_EXPORTED_FUNCTION(clCreateContext); OPENCL_EXPORTED_FUNCTION(clGetDeviceIDs); OPENCL_EXPORTED_FUNCTION(clGetPlatformIDs); OPENCL_EXPORTED_FUNCTION(clCreateBuffer); OPENCL_EXPORTED_FUNCTION(clReleaseMemObject); OPENCL_EXPORTED_FUNCTION(clCreateProgramWithSource); OPENCL_EXPORTED_FUNCTION(clBuildProgram); OPENCL_EXPORTED_FUNCTION(clCreateKernel); OPENCL_EXPORTED_FUNCTION(clSetKernelArg); OPENCL_EXPORTED_FUNCTION(clEnqueueNDRangeKernel); OPENCL_EXPORTED_FUNCTION(clFlush); OPENCL_EXPORTED_FUNCTION(clFinish); OPENCL_EXPORTED_FUNCTION(clCreateCommandQueue); OPENCL_EXPORTED_FUNCTION(clReleaseContext); OPENCL_EXPORTED_FUNCTION(clGetPlatformInfo); OPENCL_EXPORTED_FUNCTION(clGetExtensionFunctionAddressForPlatform); #undef OPENCL_EXPORTED_FUNCTION // Extension functions, loaded using clGetExtensionFunctionAddressForPlatform #if !defined(OPENCL_EXPORTED_EXTENSION_FUNCTION) #define OPENCL_EXPORTED_EXTENSION_FUNCTION(fun) #endif OPENCL_EXPORTED_EXTENSION_FUNCTION(clImportMemoryARM); #undef OPENCL_EXPORTED_EXTENSION_FUNCTION
38.265306
78
0.817067
samhsw
f01dd885b659ab3d2b3487bdf047fed9020df4e3
179
hpp
C++
llarp/path_types.hpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
llarp/path_types.hpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
llarp/path_types.hpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
#ifndef LLARP_PATH_TYPES_HPP #define LLARP_PATH_TYPES_HPP #include <aligned.hpp> #include <crypto.h> namespace llarp { using PathID_t = AlignedBuffer< PATHIDSIZE >; } #endif
13.769231
47
0.77095
KeeJef
f01fe3c9503dab7dd0139d26787f423f83d77dd2
3,389
cpp
C++
code_reading/oceanbase-master/src/sql/engine/cmd/ob_udf_executor.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/cmd/ob_udf_executor.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/cmd/ob_udf_executor.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "sql/engine/cmd/ob_udf_executor.h" #include "lib/mysqlclient/ob_mysql_proxy.h" #include "share/ob_common_rpc_proxy.h" #include "sql/resolver/ddl/ob_create_func_stmt.h" #include "sql/resolver/ddl/ob_drop_func_stmt.h" #include "sql/engine/ob_exec_context.h" #include "sql/engine/ob_physical_plan.h" #include "sql/session/ob_sql_session_info.h" #include "sql/code_generator/ob_expr_generator_impl.h" namespace oceanbase { using namespace common; using namespace share::schema; namespace sql { int ObCreateFuncExecutor::execute(ObExecContext& ctx, ObCreateFuncStmt& stmt) { int ret = OB_SUCCESS; ObTaskExecutorCtx* task_exec_ctx = NULL; obrpc::ObCommonRpcProxy* common_rpc_proxy = NULL; const obrpc::ObCreateUserDefinedFunctionArg& create_udf_arg = stmt.get_create_func_arg(); ObString first_stmt; if (OB_FAIL(stmt.get_first_stmt(first_stmt))) { LOG_WARN("fail to get first stmt", K(ret)); } else { const_cast<obrpc::ObCreateUserDefinedFunctionArg&>(create_udf_arg).ddl_stmt_str_ = first_stmt; } if (OB_FAIL(ret)) { } else if (OB_ISNULL(task_exec_ctx = GET_TASK_EXECUTOR_CTX(ctx))) { ret = OB_NOT_INIT; LOG_WARN("get task executor context failed", K(ret)); } else if (OB_FAIL(task_exec_ctx->get_common_rpc(common_rpc_proxy))) { LOG_WARN("get common rpc proxy failed", K(ret)); } else if (OB_ISNULL(common_rpc_proxy)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("common rpc proxy should not be null", K(ret)); } else if (OB_FAIL(common_rpc_proxy->create_udf(create_udf_arg))) { LOG_WARN("rpc proxy create udf failed", K(ret), "dst", common_rpc_proxy->get_server()); } return ret; } int ObDropFuncExecutor::execute(ObExecContext& ctx, ObDropFuncStmt& stmt) { int ret = OB_SUCCESS; ObTaskExecutorCtx* task_exec_ctx = NULL; obrpc::ObCommonRpcProxy* common_rpc_proxy = NULL; const obrpc::ObDropUserDefinedFunctionArg& drop_func_arg = stmt.get_drop_func_arg(); ObString first_stmt; if (OB_FAIL(stmt.get_first_stmt(first_stmt))) { LOG_WARN("fail to get first stmt", K(ret)); } else { const_cast<obrpc::ObDropUserDefinedFunctionArg&>(drop_func_arg).ddl_stmt_str_ = first_stmt; } if (OB_FAIL(ret)) { } else if (OB_ISNULL(task_exec_ctx = GET_TASK_EXECUTOR_CTX(ctx))) { ret = OB_NOT_INIT; LOG_WARN("get task executor context failed", K(ret)); } else if (OB_FAIL(task_exec_ctx->get_common_rpc(common_rpc_proxy))) { LOG_WARN("get common rpc proxy failed", K(ret)); } else if (OB_ISNULL(common_rpc_proxy)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("common rpc proxy should not be null", K(ret)); } else if (OB_FAIL(common_rpc_proxy->drop_udf(drop_func_arg))) { LOG_WARN("rpc proxy create udf failed", K(ret), "dst", common_rpc_proxy->get_server()); } return ret; } } // end namespace sql } // end namespace oceanbase
40.345238
98
0.740041
wangcy6
f026eb7a1d592f75bed531fdd748786e38ecc01e
2,990
cpp
C++
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Tom Westerhout // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "nqs.hpp" #include <pybind11/pybind11.h> #include <torch/extension.h> namespace py = pybind11; namespace { auto bind_polynomial_state(py::module m) -> void { using namespace tcm; py::class_<PolynomialStateV2>(m, "PolynomialState") .def(py::init([](std::shared_ptr<Polynomial> polynomial, std::string const& state, std::pair<size_t, size_t> input_shape) { return std::make_unique<PolynomialStateV2>( std::move(polynomial), load_forward_fn(state), input_shape); })) .def("__call__", [](PolynomialStateV2& self, py::array_t<SpinVector, py::array::c_style> spins) { return self({spins.data(0), static_cast<size_t>(spins.shape(0))}); }); } } // namespace #if defined(TCM_CLANG) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wmissing-prototypes" #endif PYBIND11_MODULE(_C_nqs, m) { #if defined(TCM_CLANG) # pragma clang diagnostic pop #endif m.doc() = R"EOF()EOF"; using namespace tcm; bind_spin(m.ptr()); bind_heisenberg(m); bind_explicit_state(m); bind_polynomial(m); // bind_options(m); // bind_chain_result(m); // bind_sampling(m); // bind_networks(m); // bind_dataloader(m); bind_monte_carlo(m.ptr()); bind_polynomial_state(m); }
37.375
81
0.692308
BagrovAndrey
f028f2117657c1d0797202d543d5684b021cfe4b
14,173
cc
C++
chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/webui/browser_command/browser_command_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/bind.h" #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/browser_features.h" #include "chrome/browser/command_updater_impl.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/browser_command/browser_command_handler.h" #include "chrome/common/chrome_features.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/common/pref_names.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/safe_browsing/core/common/safe_browsing_prefs.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/window_open_disposition.h" #include "ui/webui/resources/js/browser_command/browser_command.mojom.h" using browser_command::mojom::ClickInfo; using browser_command::mojom::ClickInfoPtr; using browser_command::mojom::Command; using browser_command::mojom::CommandHandler; namespace { std::vector<Command> supported_commands = { Command::kUnknownCommand, // Included for SupportedCommands test Command::kOpenSafetyCheck, Command::kOpenSafeBrowsingEnhancedProtectionSettings, Command::kOpenFeedbackForm, Command::kOpenPrivacyReview, }; class TestCommandHandler : public BrowserCommandHandler { public: explicit TestCommandHandler(Profile* profile) : BrowserCommandHandler(mojo::PendingReceiver<CommandHandler>(), profile, supported_commands) {} ~TestCommandHandler() override = default; void NavigateToURL(const GURL&, WindowOpenDisposition) override { // The functionality of opening a URL is removed, as it cannot be executed // in a unittest. } void OpenFeedbackForm() override { // The functionality of opening the feedback form is removed, as it cannot // be executed in a unittes. } CommandUpdater* GetCommandUpdater() override { if (command_updater_) return command_updater_.get(); return BrowserCommandHandler::GetCommandUpdater(); } void SetCommandUpdater(std::unique_ptr<CommandUpdater> command_updater) { command_updater_ = std::move(command_updater); // Ensure that all commands are also updated in the new |command_updater|. EnableSupportedCommands(); } std::unique_ptr<CommandUpdater> command_updater_; }; class MockCommandHandler : public TestCommandHandler { public: explicit MockCommandHandler(Profile* profile) : TestCommandHandler(profile) {} ~MockCommandHandler() override = default; MOCK_METHOD2(NavigateToURL, void(const GURL&, WindowOpenDisposition)); MOCK_METHOD0(OpenFeedbackForm, void()); }; class MockCommandUpdater : public CommandUpdaterImpl { public: explicit MockCommandUpdater(CommandUpdaterDelegate* delegate) : CommandUpdaterImpl(delegate) {} ~MockCommandUpdater() override = default; MOCK_CONST_METHOD1(IsCommandEnabled, bool(int id)); MOCK_CONST_METHOD1(SupportsCommand, bool(int id)); }; // Callback used for testing // BrowserCommandHandler::CanExecuteCommand(). void CanExecuteCommandCallback(base::OnceClosure quit_closure, bool* expected_can_show, bool can_show) { *expected_can_show = can_show; std::move(quit_closure).Run(); } // Callback used for testing BrowserCommandHandler::ExecuteCommand(). void ExecuteCommandCallback(base::OnceClosure quit_closure, bool* expected_command_executed, bool command_executed) { *expected_command_executed = command_executed; std::move(quit_closure).Run(); } // A shorthand for conversion between ClickInfo and WindowOpenDisposition. WindowOpenDisposition DispositionFromClick(const ClickInfo& info) { return ui::DispositionFromClick(info.middle_button, info.alt_key, info.ctrl_key, info.meta_key, info.shift_key); } class TestingChildProfile : public TestingProfile { public: bool IsChild() const override { return true; } }; } // namespace class BrowserCommandHandlerTest : public testing::Test { public: BrowserCommandHandlerTest() = default; ~BrowserCommandHandlerTest() override = default; void SetUp() override { command_handler_ = std::make_unique<MockCommandHandler>(&profile_); } void TearDown() override { testing::Test::TearDown(); } MockCommandUpdater* mock_command_updater() { return static_cast<MockCommandUpdater*>( command_handler_->GetCommandUpdater()); } bool CanExecuteCommand(Command command_id) { base::RunLoop run_loop; bool can_show = false; command_handler_->CanExecuteCommand( command_id, base::BindOnce(&CanExecuteCommandCallback, run_loop.QuitClosure(), &can_show)); run_loop.Run(); return can_show; } bool ExecuteCommand(Command command_id, ClickInfoPtr click_info) { base::RunLoop run_loop; bool command_executed = false; command_handler_->ExecuteCommand( command_id, std::move(click_info), base::BindOnce(&ExecuteCommandCallback, run_loop.QuitClosure(), &command_executed)); run_loop.Run(); return command_executed; } protected: content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; std::unique_ptr<MockCommandHandler> command_handler_; }; TEST_F(BrowserCommandHandlerTest, SupportedCommands) { base::HistogramTester histogram_tester; // Mock out the command updater to test enabling and disabling commands. command_handler_->SetCommandUpdater( std::make_unique<MockCommandUpdater>(command_handler_.get())); // Unsupported commands do not get executed and no histogram is logged. EXPECT_CALL(*mock_command_updater(), SupportsCommand(static_cast<int>(Command::kUnknownCommand))) .WillOnce(testing::Return(false)); EXPECT_FALSE(ExecuteCommand(Command::kUnknownCommand, ClickInfo::New())); histogram_tester.ExpectTotalCount( BrowserCommandHandler::kPromoBrowserCommandHistogramName, 0); // Disabled commands do not get executed and no histogram is logged. EXPECT_CALL(*mock_command_updater(), SupportsCommand(static_cast<int>(Command::kUnknownCommand))) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_command_updater(), IsCommandEnabled(static_cast<int>(Command::kUnknownCommand))) .WillOnce(testing::Return(false)); EXPECT_FALSE(ExecuteCommand(Command::kUnknownCommand, ClickInfo::New())); histogram_tester.ExpectTotalCount( BrowserCommandHandler::kPromoBrowserCommandHistogramName, 0); // Only supported and enabled commands get executed for which a histogram is // logged. EXPECT_CALL(*mock_command_updater(), SupportsCommand(static_cast<int>(Command::kUnknownCommand))) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_command_updater(), IsCommandEnabled(static_cast<int>(Command::kUnknownCommand))) .WillOnce(testing::Return(true)); EXPECT_TRUE(ExecuteCommand(Command::kUnknownCommand, ClickInfo::New())); histogram_tester.ExpectBucketCount( BrowserCommandHandler::kPromoBrowserCommandHistogramName, 0, 1); } TEST_F(BrowserCommandHandlerTest, CanExecuteCommand_OpenSafetyCheck) { // By default, showing the Safety Check promo is allowed. EXPECT_TRUE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); // If the browser is managed, showing the Safety Check promo is not allowed. TestingProfile::Builder builder; builder.OverridePolicyConnectorIsManagedForTesting(true); std::unique_ptr<TestingProfile> profile = builder.Build(); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE(CanExecuteCommand(Command::kOpenSafetyCheck)); } TEST_F(BrowserCommandHandlerTest, OpenSafetyCheckCommand) { // The OpenSafetyCheck command opens a new settings window with the Safety // Check, and the correct disposition. ClickInfoPtr info = ClickInfo::New(); info->middle_button = true; info->meta_key = true; EXPECT_CALL( *command_handler_, NavigateToURL(GURL(chrome::GetSettingsUrl(chrome::kSafetyCheckSubPage)), DispositionFromClick(*info))); EXPECT_TRUE(ExecuteCommand(Command::kOpenSafetyCheck, std::move(info))); } TEST_F(BrowserCommandHandlerTest, CanShowSafeBrowsingEnhancedProtectionCommandPromo_NoPolicies) { EXPECT_TRUE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); } TEST_F( BrowserCommandHandlerTest, CanShowSafeBrowsingEnhancedProtectionCommandPromo_EnhancedProtectionEnabled) { TestingProfile::Builder builder; std::unique_ptr<TestingProfile> profile = builder.Build(); profile->GetTestingPrefService()->SetUserPref( prefs::kSafeBrowsingEnhanced, std::make_unique<base::Value>(true)); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); } TEST_F( BrowserCommandHandlerTest, CanShowSafeBrowsingEnhancedProtectionCommandPromo_HasSafeBrowsingManaged_NoProtection) { TestingProfile::Builder builder; std::unique_ptr<TestingProfile> profile = builder.Build(); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnabled, std::make_unique<base::Value>(false)); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnhanced, std::make_unique<base::Value>(false)); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); } TEST_F( BrowserCommandHandlerTest, CanShowSafeBrowsingEnhancedProtectionCommandPromo_HasSafeBrowsingManaged_StandardProtection) { TestingProfile::Builder builder; std::unique_ptr<TestingProfile> profile = builder.Build(); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnabled, std::make_unique<base::Value>(true)); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnhanced, std::make_unique<base::Value>(false)); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); } TEST_F( BrowserCommandHandlerTest, CanShowSafeBrowsingEnhancedProtectionCommandPromo_HasSafeBrowsingManaged_EnhancedProtection) { TestingProfile::Builder builder; std::unique_ptr<TestingProfile> profile = builder.Build(); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnabled, std::make_unique<base::Value>(true)); profile->GetTestingPrefService()->SetManagedPref( prefs::kSafeBrowsingEnhanced, std::make_unique<base::Value>(true)); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE( CanExecuteCommand(Command::kOpenSafeBrowsingEnhancedProtectionSettings)); } TEST_F(BrowserCommandHandlerTest, OpenSafeBrowsingEnhancedProtectionCommand) { // The kOpenSafeBrowsingEnhancedProtectionSettings command opens a new // settings window with the Safe Browsing settings with the Enhanced // Protection section expanded, and the correct disposition. ClickInfoPtr info = ClickInfo::New(); info->middle_button = true; info->meta_key = true; EXPECT_CALL( *command_handler_, NavigateToURL(GURL(chrome::GetSettingsUrl( chrome::kSafeBrowsingEnhancedProtectionSubPage)), DispositionFromClick(*info))); EXPECT_TRUE(ExecuteCommand( Command::kOpenSafeBrowsingEnhancedProtectionSettings, std::move(info))); } TEST_F(BrowserCommandHandlerTest, OpenFeedbackFormCommand) { // Open feedback form command calls open feedback form. ClickInfoPtr info = ClickInfo::New(); EXPECT_CALL(*command_handler_, OpenFeedbackForm()); EXPECT_TRUE(ExecuteCommand(Command::kOpenFeedbackForm, std::move(info))); } TEST_F(BrowserCommandHandlerTest, CanExecuteCommand_OpenPrivacyReview) { // Showing the Privacy Review promo is not allowed if the experimental // flag is disabled. base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kPrivacyReview); EXPECT_FALSE(CanExecuteCommand(Command::kOpenPrivacyReview)); // Once the flag is enabled, it is allowed. feature_list.Reset(); feature_list.InitAndEnableFeature(features::kPrivacyReview); EXPECT_TRUE(CanExecuteCommand(Command::kOpenPrivacyReview)); // If the browser is managed, it is again not allowed. { TestingProfile::Builder builder; builder.OverridePolicyConnectorIsManagedForTesting(true); std::unique_ptr<TestingProfile> profile = builder.Build(); command_handler_ = std::make_unique<MockCommandHandler>(profile.get()); EXPECT_FALSE(CanExecuteCommand(Command::kOpenPrivacyReview)); } // Neither is it if the profile belongs to a child. { TestingChildProfile profile; command_handler_ = std::make_unique<MockCommandHandler>(&profile); EXPECT_FALSE(CanExecuteCommand(Command::kOpenPrivacyReview)); } } TEST_F(BrowserCommandHandlerTest, OpenPrivacyReviewCommand) { // The OpenPrivacyReview command opens a new settings window with the Privacy // Review, and the correct disposition. ClickInfoPtr info = ClickInfo::New(); info->middle_button = true; info->meta_key = true; EXPECT_CALL( *command_handler_, NavigateToURL(GURL(chrome::GetSettingsUrl(chrome::kPrivacyReviewSubPage)), DispositionFromClick(*info))); EXPECT_TRUE(ExecuteCommand(Command::kOpenPrivacyReview, std::move(info))); }
38.830137
98
0.757144
chromium
f02b78616e68539c658bb9cda3d87c6f870efa5a
461
cpp
C++
find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
13
2019-10-12T14:36:32.000Z
2021-06-08T04:26:30.000Z
find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
1
2020-02-29T14:02:39.000Z
2020-02-29T14:02:39.000Z
find-first-and-last-position-of-element-in-sorted-array/find-first-and-last-position-of-element-in-sorted-array.cpp
JanaSabuj/Leetcode-solutions
78d10926b15252a969df598fbf1f9b69b2760b79
[ "MIT" ]
3
2020-02-08T12:04:28.000Z
2020-03-17T11:53:00.000Z
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int idx1 = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int idx2 = upper_bound(nums.begin(), nums.end(), target) - nums.begin(); idx2--; if(idx1 >= 0 and idx1 < (int)nums.size() and nums[idx1] == target) return {idx1, idx2}; else return {-1, -1}; } };
30.733333
92
0.501085
JanaSabuj
f0350516c718cdc55f6f2895200a149b9a4b4197
30,949
cpp
C++
middleware/queue/unittest/source/group/test_queuebase.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/queue/unittest/source/group/test_queuebase.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/queue/unittest/source/group/test_queuebase.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
1
2022-02-21T18:30:25.000Z
2022-02-21T18:30:25.000Z
//! //! Copyright (c) 2015, The casual project //! //! This software is licensed under the MIT license, https://opensource.org/licenses/MIT //! #include "common/unittest.h" #include "queue/group/queuebase.h" #include "common/file.h" #include "common/environment.h" #include "common/chronology.h" #include "common/buffer/type.h" namespace casual { namespace queue::group { namespace local { namespace { std::string file() { return ":memory:"; } static const common::transaction::ID nullId{}; auto message( const queuebase::Queue& queue, const common::transaction::ID& trid = nullId) { ipc::message::group::enqueue::Request result; result.queue = queue.id; result.trid = trid; result.message.id = common::uuid::make(); result.message.reply = "someQueue"; result.message.type = common::buffer::type::binary(); common::algorithm::copy( common::uuid::string( common::uuid::make()), result.message.payload); result.message.available = std::chrono::time_point_cast< std::chrono::microseconds>( platform::time::clock::type::now()); //result.message.timestamp = platform::time::clock::type::now(); return result; } template< typename Q> auto request( const Q& queue, const common::transaction::ID& trid = nullId) { ipc::message::group::dequeue::Request result; result.queue = queue.id; result.trid = trid; return result; } namespace peek { auto information( common::strong::queue::id queue) { ipc::message::group::message::meta::peek::Request result; result.queue = queue; return result; } } // peek std::optional< ipc::message::group::state::Queue> get_queue( group::Queuebase& queuebase, common::strong::queue::id id) { auto result = queuebase.queues(); auto found = common::algorithm::find( result, id); if( found) return { std::move( *found)}; return {}; } } // <unnamed> } // local TEST( casual_queue_group_database, create_database) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); } TEST( casual_queue_group_database, create_queue) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); database.update( { queuebase::Queue{ "unittest_queue"}}, {}); auto queues = database.queues(); // there is always an error-queue ASSERT_TRUE( queues.size() == 2); EXPECT_TRUE( queues.at( 0).name == "unittest_queue.error"); EXPECT_TRUE( queues.at( 1).name == "unittest_queue"); EXPECT_TRUE( queues.at( 1).metric.count == 0) << "count: " << queues.at( 2).metric.count; EXPECT_TRUE( queues.at( 1).metric.size == 0); EXPECT_TRUE( queues.at( 1).metric.uncommitted == 0); } TEST( casual_queue_group_database, remove_queue) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.update( {queuebase::Queue{ "unittest_queue"}}, {}); database.update( {}, { queue.at( 0).id}); EXPECT_TRUE( database.queues().empty()) << database.queues().size(); } TEST( casual_queue_group_database, update_queue) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.update( { queuebase::Queue{ "unittest_queue"}}, {}); queue.at( 0).name = "foo-bar"; database.update( { queue.at( 0)}, {}); auto queues = database.queues(); ASSERT_TRUE( queues.size() == 2) << queues.size(); EXPECT_TRUE( queues.at( 0).name == "foo-bar.error"); EXPECT_TRUE( queues.at( 1).name == "foo-bar"); } namespace local { namespace { auto path() { common::file::scoped::Path result{ common::environment::directory::temporary()}; result /= common::uuid::string( common::uuid::make()); result += "unittest_queue_server_database.db"; return result; } } // } // local TEST( casual_queue_group_database, create_queue_on_disc_and_open_again) { common::unittest::Trace trace; auto path = local::path(); { group::Queuebase database( path); database.create( queuebase::Queue{ "unittest_queue"}); } { // open again group::Queuebase database( path); auto queues = database.queues(); // there is always a error-queue ASSERT_TRUE( queues.size() == 2); //EXPECT_TRUE( queues.at( 0).name == "unittest_queue_server_database-error-queue") << queues.at( 0).name; EXPECT_TRUE( queues.at( 0).name == "unittest_queue.error"); EXPECT_TRUE( queues.at( 1).name == "unittest_queue"); } } TEST( casual_queue_group_database, create_5_queue_on_disc_and_open_again) { common::unittest::Trace trace; auto path = local::path(); { group::Queuebase database( path); for( int index = 1; index <= 5; ++index) { database.create( queuebase::Queue{ "unittest_queue_" + std::to_string( index)}); } } { // open again group::Queuebase database( path); auto queues = database.queues(); // there is always a error-queue, and a global error-queue ASSERT_TRUE( queues.size() == 5 * 2); //EXPECT_TRUE( queues.at( 0).name == "unittest_queue_server_database-error-queue") << queues.at( 0).name; EXPECT_TRUE( queues.at( 0).name == "unittest_queue_1.error") << queues.at( 1).name; EXPECT_TRUE( queues.at( 1).name == "unittest_queue_1") << queues.at( 2).name; } } TEST( casual_queue_group_database, create_100_queues) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase queuebase( path); common::algorithm::for_n< 100>( [&queuebase]( auto index) { queuebase.create( queuebase::Queue{ "unittest_queue" + std::to_string( index)}); }); queuebase.persist(); auto queues = queuebase.queues(); // there is always an error-queue for each queue ASSERT_TRUE( queues.size() == 200) << "size: " << queues.size(); EXPECT_TRUE( queues.at( 0).name == "unittest_queue0.error") << queues.at( 0).name; } TEST( casual_queue_group_database, enqueue_one_message) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ EXPECT_TRUE( static_cast< bool>( database.enqueue( message).id)); }); } TEST( casual_queue_group_database, enqueue_one_message__get_queue_info) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ database.enqueue( message); }); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.name == "unittest_queue"); EXPECT_TRUE( info.metric.count == 1) << "info.metric.count: " << info.metric.count; EXPECT_TRUE( info.metric.size == static_cast< platform::size::type>( message.message.payload.size())); } TEST( casual_queue_group_database, enqueue_one_message__get_message_info) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ database.enqueue( message); }); auto messages = database.meta( queue.id); ASSERT_TRUE( messages.size() == 1); EXPECT_TRUE( messages.at( 0).id == message.message.id); } TEST( casual_queue_group_database, dequeue_one_message) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); } TEST( casual_queue_group_database, enqueue_deque__info__expect__count_0__size_0) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "enqueue_deque__info__expect__count_0__size_0"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue), platform::time::clock::type::now()); EXPECT_TRUE( fetched.message.size() == 1); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.count == 0) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.size == 0); } TEST( casual_queue_group_database, enqueue_deque__info__expect_metric_to_reflect) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "enqueue_deque__info__expect_metric_to_reflect"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue), platform::time::clock::type::now()); EXPECT_TRUE( fetched.message.size() == 1); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.enqueued == 1) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.dequeued == 1) << CASUAL_NAMED_VALUE( info); } TEST( casual_queue_group_database, enqueue_deque__metric_reset__info__expect_no_metric) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "enqueue_deque__info__expect_metric_to_reflect"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue), platform::time::clock::type::now()); EXPECT_TRUE( fetched.message.size() == 1); database.metric_reset( { queue.id }); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.enqueued == 0) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.dequeued == 0) << CASUAL_NAMED_VALUE( info); } TEST( casual_queue_group_database, dequeue_message__from_id) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "dequeue_message__from_id"}); auto origin = local::message( queue); database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.id = origin.message.id; auto fetched = database.dequeue( reqest, platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); } TEST( casual_queue_group_database, dequeue_message__from_properties) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); origin.message.properties = "some: properties"; database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.properties = origin.message.properties; auto fetched = database.dequeue( reqest, platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); } TEST( casual_queue_group_database, dequeue_message__from_non_existent_properties__expect_0_messages) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); origin.message.properties = "some: properties"; database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.properties = "some other properties"; auto fetched = database.dequeue( reqest, platform::time::clock::type::now()); EXPECT_TRUE( fetched.message.size() == 0); } TEST( casual_queue_group_database, dequeue_100_message) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto messages = common::algorithm::generate_n< 100>( [&]( auto index) { auto message = local::message( queue); message.message.type = std::to_string( index); return message; }); common::algorithm::for_each( messages, [&]( auto& message) { database.enqueue( message); }); database.persist(); common::algorithm::for_each( messages,[&]( auto& origin) { auto fetched = database.dequeue( local::request( queue), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type) << "origin.type: " << origin.message.type << " fetched.type; " << fetched.message.at( 0).type; EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); //EXPECT_TRUE( origin.message.timestamp <= fetched.timestamp) << "origin: " << origin.timestamp.time_since_epoch().count() << " fetched: " << fetched.timestamp.time_since_epoch().count(); }); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.enqueued == 100) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.dequeued == 100) << CASUAL_NAMED_VALUE( info); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::id::create(); auto origin = local::message( queue, xid); { database.enqueue( origin); // Message should not be available. EXPECT_TRUE( database.dequeue( local::request( queue), platform::time::clock::type::now()).message.empty()); // Not even within the same transaction EXPECT_TRUE( database.dequeue( local::request( queue, xid), platform::time::clock::type::now()).message.empty()); database.commit( xid); } { common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( queue, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1) << CASUAL_NAMED_VALUE( fetched) << "\n" << CASUAL_NAMED_VALUE( database.queues()); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); } } TEST( casual_queue_group_database, dequeue_one_message_in_transaction) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); { common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( queue, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.commit( xid); } // Should be empty EXPECT_TRUE( database.dequeue( local::request( queue), platform::time::clock::type::now()).message.empty()); } TEST( casual_queue_group_database, deque_in_transaction__info__expect__count_0__size_0) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); { common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( queue, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.commit( xid); } auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.count == 0) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.size == 0); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction_rollback) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::id::create(); auto origin = local::message( queue, xid); database.enqueue( origin); database.rollback( xid); // Should be empty //local::print( database.queues()); EXPECT_TRUE( database.dequeue( local::request( queue), platform::time::clock::type::now()).message.empty()); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction_rollback__info__expect__count_0__size_0) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::id::create(); auto origin = local::message( queue, xid); database.enqueue( origin); database.rollback( xid); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.count == 0) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.size == 0); } TEST( casual_queue_group_database, enqueue_dequeue_one_message_in_transaction_rollback) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto origin = local::message( queue); { common::transaction::ID xid = common::transaction::id::create(); database.enqueue( origin); database.commit( xid); auto info = local::get_queue( database, queue.id).value(); EXPECT_TRUE( info.metric.count == 1) << CASUAL_NAMED_VALUE( info); EXPECT_TRUE( info.metric.size == static_cast< platform::size::type>( origin.message.payload.size())); } { common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( queue, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.rollback( xid); auto affected = database.affected(); EXPECT_TRUE( affected == 1) << "affected: " << affected; EXPECT_TRUE( database.dequeue( local::request( queue, xid), platform::time::clock::type::now()).message.empty()); } // Should be in error queue { auto error = local::get_queue( database, queue.error).value(); EXPECT_TRUE( error.metric.count == 1) << " queues.at( 1).count: " << error.metric.count; EXPECT_TRUE( error.metric.size == static_cast< platform::size::type>( origin.message.payload.size())); common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( error, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1) << CASUAL_NAMED_VALUE( error); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.rollback( xid); } // Should still be in error queue { auto error = local::get_queue( database, queue.error).value(); EXPECT_TRUE( error.metric.count == 1) << " queues.at( 1).count: " << error.metric.count; EXPECT_TRUE( error.metric.size == static_cast< platform::size::type>( origin.message.payload.size())); common::transaction::ID xid = common::transaction::id::create(); auto fetched = database.dequeue( local::request( error, xid), platform::time::clock::type::now()); database.commit( xid); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); } // All queues should have count = 0 and size = 0 auto is_empty = []( auto& queue){ return queue.metric.count == 0 && queue.metric.size == 0;}; EXPECT_TRUE( common::algorithm::all_of( database.queues(), is_empty)); } TEST( casual_queue_group_database, dequeue_100_message_in_transaction) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); using message_type = decltype( local::message( queue)); std::vector< message_type > messages; messages.reserve( 100); { common::transaction::ID xid = common::transaction::id::create(); auto count = 0; while( count++ < 100) { auto m = local::message( queue, xid); m.message.type = std::to_string( count); database.enqueue( m); messages.push_back( std::move( m)); } database.commit( xid); } common::transaction::ID xid = common::transaction::id::create(); common::algorithm::for_each( messages,[&]( const message_type& origin){ auto fetched = database.dequeue( local::request( queue, xid), platform::time::clock::type::now()); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type) << "origin.type: " << origin.message.type << " fetched.type; " << fetched.message.at( 0).type; EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.available == fetched.message.at( 0).available); //EXPECT_TRUE( origin.message.timestamp <= fetched.timestamp) << "origin: " << origin.timestamp.time_since_epoch().count() << " fetched: " << fetched.timestamp.time_since_epoch().count(); }); database.commit( xid); EXPECT_TRUE( database.dequeue( local::request( queue), platform::time::clock::type::now()).message.empty()); } TEST( casual_queue_group_database, restore_empty_error_queue__expect_0_affected) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto restored = database.restore( queue.id); EXPECT_TRUE( restored == 0) << "restored: " << restored; } TEST( casual_queue_group_database, restore__1_message_in_error_queue__expect_1_affected) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue"}); auto message = local::message( queue); { database.enqueue( message); auto trid = common::transaction::id::create(); database.dequeue( local::request( queue, trid), platform::time::clock::type::now()); database.rollback( trid); auto info = database.peek( local::peek::information( queue.error)); ASSERT_TRUE( info.messages.size() == 1); EXPECT_TRUE( info.messages.at( 0).id == message.message.id); EXPECT_TRUE( info.messages.at( 0).origin == queue.id); EXPECT_TRUE( info.messages.at( 0).queue == queue.error); } auto restored = database.restore( queue.id); EXPECT_TRUE( restored == 1) << CASUAL_NAMED_VALUE( restored); { auto reply = database.dequeue( local::request(queue), platform::time::clock::type::now()); ASSERT_TRUE( reply.message.size() == 1) << CASUAL_NAMED_VALUE( reply); EXPECT_TRUE( reply.message.at( 0).payload == message.message.payload); } } TEST( casual_queue_group_database, retry_count_3_delay_1h__rollback___expect_unabvailable) { common::unittest::Trace trace; // start time so we can make sure that available will be later thant this + 1h auto now = platform::time::clock::type::now(); auto path = local::file(); group::Queuebase database( path); auto queue = database.create( queuebase::Queue{ "unittest_queue", queuebase::queue::Retry{ 3, std::chrono::hours{ 1}}}); { auto message = local::message( queue); database.enqueue( message); auto trid = common::transaction::id::create(); database.dequeue( local::request( queue, trid), platform::time::clock::type::now()); database.rollback( trid); auto info = database.peek( local::peek::information( queue.id)); ASSERT_TRUE( info.messages.size() == 1); EXPECT_TRUE( info.messages.at( 0).id == message.message.id); EXPECT_TRUE( info.messages.at( 0).origin == queue.id); EXPECT_TRUE( info.messages.at( 0).queue == queue.id); EXPECT_TRUE( info.messages.at( 0).available > now + std::chrono::hours{ 1}) << "available: " << common::chronology::utc::offset( info.messages.at( 0).available) << "\nlimit: " << common::chronology::utc::offset( now + std::chrono::hours{ 1}); // check that we've not over-delayed it ( 2s to be safe on really slow machines) EXPECT_TRUE( info.messages.at( 0).available < now + std::chrono::hours{ 1} + std::chrono::seconds{ 2}); } // message is not availiable until next hour EXPECT_TRUE( database.dequeue( local::request( queue), platform::time::clock::type::now()).message.empty()); } TEST( casual_queue_group, expect_version_3_0) { common::unittest::Trace trace; auto path = local::file(); group::Queuebase database( path); auto version = database.version(); EXPECT_TRUE( version.major == 3); EXPECT_TRUE( version.minor == 0); } } // queue::group } // casual
35.614499
199
0.588032
casualcore