hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
9ebdcfefd1371b705898dbc6c5aa52e1265c67a0
4,056
hpp
C++
include/Wg/ListView.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
include/Wg/ListView.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
include/Wg/ListView.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2010 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #pragma once #include "Wg/Base.hpp" #include "Wg/Widget.hpp" #include "Wg/CancelableEvent.hpp" #include "Wg/ImageList.hpp" #include <vector> namespace Wg { // ====================================================================== /** @see ListViewType */ struct ListViewTypeEnum { enum enumeration { Icon, Report, SmallIcon, List }; static const enumeration default_value = List; }; /** Kind of ListView. */ typedef Enum<ListViewTypeEnum> ListViewType; // ====================================================================== typedef std::vector<ListItem *> ListItemList; typedef std::vector<ListColumn *> ListColumnList; /** A ListView control. */ class VACA_DLL ListView : public Widget { ListItemList m_items; ListColumnList m_columns; ImageList m_imageList; ImageList m_smallImageList; ImageList m_stateImageList; /** To use LPSTR_TEXTCALLBACK we need some space to allocate text temporally. */ String m_tmpBuffer; public: struct VACA_DLL Styles { static const Style Default; static const Style SingleSelection; static const Style ShowSelectionAlways; }; ListView(Widget *parent, const Style &style = Styles::Default); ~ListView() override; void setBgColor(const Color &color) override; [[nodiscard]] Color getTextColor() const; void setTextColor(const Color &color); [[nodiscard]] Color getTextBgColor() const; void setTextBgColor(const Color &color); [[nodiscard]] ListViewType getType() const; void setType(ListViewType type); void setImageList(const ImageList &imageList); void setSmallImageList(const ImageList &imageList); void setStateImageList(const ImageList &imageList); [[nodiscard]] ImageList getImageList() const; [[nodiscard]] ImageList getSmallImageList() const; [[nodiscard]] ImageList getStateImageList() const; int addColumn(ListColumn *column); // int insertColumn(int columnIndex, const String& header, TextAlign textAlign = TextAlign::Left); void removeColumn(ListColumn *column); void removeAllColumns(); [[nodiscard]] int getColumnCount() const; [[nodiscard]] ListColumn *getColumn(size_t columnIndex) const; int addItem(ListItem *item); // int insertItem(int itemIndex, const String& text, int imageIndex = -1); void removeItem(ListItem *item); void removeAllItems(); [[nodiscard]] int getItemCount() const; [[nodiscard]] ListItem *getItem(size_t index) const; // Rect getItemBounds(int itemIndex, int code = LVIR_BOUNDS); // void editItemText(int itemIndex); [[nodiscard]] int getSelectedItemCount() const; // void sortItems(std::less<ListItem> functor); // int getCurrentItem(); // Signals Signal1<void, ListViewEvent &> BeforeSelect; Signal1<void, ListViewEvent &> AfterSelect; Signal1<void, ListViewEvent &> ColumnClick; protected: // Events void onResize(ResizeEvent &ev) override; // New events virtual void onBeforeSelect(ListViewEvent &ev); virtual void onAfterSelect(ListViewEvent &ev); virtual void onColumnClick(ListViewEvent &ev); // Reflected notifications bool onReflectedNotify(LPNMHDR lpnmhdr, LRESULT &lResult) override; private: void insertDummyColumn(); void removeDummyColumn(); }; /** Event where interact a ListView. */ class ListViewEvent : public CancelableEvent { ListItem *m_item; ListColumn *m_column; public: ListViewEvent(ListView *listView, ListItem *item, ListColumn *column) : CancelableEvent(listView), m_item(item), m_column(column) { } [[nodiscard]] ListItem *getItem() const { return m_item; } [[nodiscard]] ListColumn *getColumn() const { return m_column; } }; } // namespace Wg
23.445087
102
0.670118
[ "vector" ]
9ec87c3d5a54d4541478dd57f8b2ddeba7654bfc
9,307
cpp
C++
tests/Futures/Promise-test.cpp
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
1
2018-12-08T01:58:16.000Z
2018-12-08T01:58:16.000Z
tests/Futures/Promise-test.cpp
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
null
null
null
tests/Futures/Promise-test.cpp
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
1
2018-11-04T01:30:53.000Z
2018-11-04T01:30:53.000Z
//////////////////////////////////////////////////////////////////////////////// /// @brief test case for Futures/Try object /// /// @file /// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include "Futures/Promise.h" #include "catch.hpp" using namespace arangodb::futures; namespace { auto makeValid() { auto valid = Promise<int>(); REQUIRE(valid.valid()); return valid; } auto makeInvalid() { auto invalid = Promise<int>::makeEmpty(); REQUIRE_FALSE(invalid.valid()); return invalid; } template <typename T> constexpr typename std::decay<T>::type copy(T&& value) noexcept(noexcept(typename std::decay<T>::type(std::forward<T>(value)))) { return std::forward<T>(value); } typedef std::domain_error eggs_t; static eggs_t eggs("eggs"); } // namespace // ----------------------------------------------------------------------------- // --SECTION-- test suite // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief setup //////////////////////////////////////////////////////////////////////////////// TEST_CASE("Promise", "[futures][Promise]") { SECTION("makeEmpty") { auto p = Promise<int>::makeEmpty(); REQUIRE(p.isFulfilled()); } SECTION("special") { REQUIRE_FALSE(std::is_copy_constructible<Promise<int>>::value); REQUIRE_FALSE(std::is_copy_assignable<Promise<int>>::value); REQUIRE(std::is_move_constructible<Promise<int>>::value); REQUIRE(std::is_move_assignable<Promise<int>>::value); } SECTION("getFuture") { Promise<int> p; Future<int> f = p.getFuture(); REQUIRE_FALSE(f.isReady()); } SECTION("setValueUnit") { Promise<Unit> p; p.setValue(); } SECTION("ctorPostconditionValid") { // Ctors/factories that promise valid -- postcondition: valid() #define DOIT(CREATION_EXPR) \ do { \ auto p1 = (CREATION_EXPR); \ REQUIRE(p1.valid()); \ auto p2 = std::move(p1); \ REQUIRE_FALSE(p1.valid()); \ REQUIRE(p2.valid()); \ } while (false) DOIT(makeValid()); DOIT(Promise<int>()); DOIT(Promise<int>{}); DOIT(Promise<Unit>()); DOIT(Promise<Unit>{}); #undef DOIT } SECTION("ctorPostconditionInvalid") { // Ctors/factories that promise invalid -- postcondition: !valid() #define DOIT(CREATION_EXPR) \ do { \ auto p1 = (CREATION_EXPR); \ REQUIRE_FALSE(p1.valid()); \ auto p2 = std::move(p1); \ REQUIRE_FALSE(p1.valid()); \ REQUIRE_FALSE(p2.valid()); \ } while (false) DOIT(makeInvalid()); DOIT(Promise<int>::makeEmpty()); #undef DOIT } SECTION("lacksPreconditionValid") { // Ops that don't throw PromiseInvalid if !valid() -- // without precondition: valid() #define DOIT(STMT) \ do { \ auto p = makeValid(); \ { STMT; } \ copy(std::move(p)); \ STMT; \ } while (false) // misc methods that don't require isValid() DOIT(p.valid()); DOIT(p.isFulfilled()); // move-ctor - move-copy to local, copy(), pass-by-move-value DOIT(auto other = std::move(p)); DOIT(copy(std::move(p))); DOIT(([](auto) {})(std::move(p))); // move-assignment into either {valid | invalid} DOIT({ auto other = makeValid(); other = std::move(p); }); DOIT({ auto other = makeInvalid(); other = std::move(p); }); #undef DOIT } SECTION("hasPreconditionValid") { // Ops that require validity; precondition: valid(); // throw PromiseInvalid if !valid() #define DOIT(STMT) \ do { \ auto p = makeValid(); \ STMT; \ ::copy(std::move(p)); \ REQUIRE_THROWS(STMT); \ } while (false) auto const except = std::logic_error("foo"); auto const ewrap = std::make_exception_ptr(except); DOIT(p.getFuture()); DOIT(p.setException(except)); DOIT(p.setException(ewrap)); //DOIT(p.setInterruptHandler([](auto&) {})); DOIT(p.setValue(42)); DOIT(p.setTry(Try<int>(42))); DOIT(p.setTry(Try<int>(ewrap))); DOIT(p.setWith([] { return 42; })); #undef DOIT } SECTION("hasPostconditionValid") { // Ops that preserve validity -- postcondition: valid() #define DOIT(STMT) \ do { \ auto p = makeValid(); \ STMT; \ REQUIRE(p.valid()); \ } while (false) auto const swallow = [](auto) {}; DOIT(swallow(p.valid())); // p.valid() itself preserves validity DOIT(swallow(p.isFulfilled())); #undef DOIT } SECTION("hasPostconditionInvalid") { // Ops that consume *this -- postcondition: !valid() #define DOIT(CTOR, STMT) \ do { \ auto p = (CTOR); \ STMT; \ REQUIRE_FALSE(p.valid()); \ } while (false) // move-ctor of {valid|invalid} DOIT(makeValid(), { auto other{std::move(p)}; }); DOIT(makeInvalid(), { auto other{std::move(p)}; }); // move-assignment of {valid|invalid} into {valid|invalid} DOIT(makeValid(), { auto other = makeValid(); other = std::move(p); }); DOIT(makeValid(), { auto other = makeInvalid(); other = std::move(p); }); DOIT(makeInvalid(), { auto other = makeValid(); other = std::move(p); }); DOIT(makeInvalid(), { auto other = makeInvalid(); other = std::move(p); }); // pass-by-value of {valid|invalid} DOIT(makeValid(), { auto const byval = [](auto) {}; byval(std::move(p)); }); DOIT(makeInvalid(), { auto const byval = [](auto) {}; byval(std::move(p)); }); #undef DOIT } SECTION("setValue") { Promise<int> fund; auto ffund = fund.getFuture(); fund.setValue(42); REQUIRE(42 == ffund.get()); struct Foo { std::string name; int value; }; Promise<Foo> pod; auto fpod = pod.getFuture(); Foo f = {"the answer", 42}; pod.setValue(f); Foo f2 = fpod.get(); REQUIRE(f.name == f2.name); REQUIRE(f.value == f2.value); pod = Promise<Foo>(); fpod = pod.getFuture(); pod.setValue(std::move(f2)); Foo f3 = fpod.get(); REQUIRE(f.name == f3.name); REQUIRE(f.value == f3.value); Promise<std::unique_ptr<int>> mov; auto fmov = mov.getFuture(); mov.setValue(std::make_unique<int>(42)); std::unique_ptr<int> ptr = std::move(fmov).get(); REQUIRE(42 == *ptr); Promise<Unit> v; auto fv = v.getFuture(); v.setValue(); REQUIRE(fv.isReady()); } SECTION("setException") { { Promise<int> p; auto f = p.getFuture(); p.setException(eggs); REQUIRE_THROWS_AS(f.get(), eggs_t); } { Promise<int> p; auto f = p.getFuture(); p.setException(std::make_exception_ptr(eggs)); REQUIRE_THROWS_AS(f.get(), eggs_t); } } SECTION("setWith") { { Promise<int> p; auto f = p.getFuture(); p.setWith([] { return 42; }); REQUIRE(42 == f.get()); } { Promise<int> p; auto f = p.getFuture(); p.setWith([]() -> int { throw eggs; }); REQUIRE_THROWS_AS(f.get(), eggs_t); } } SECTION("isFulfilled") { Promise<int> p; REQUIRE_FALSE(p.isFulfilled()); p.setValue(42); REQUIRE(p.isFulfilled()); } SECTION("isFulfilledWithFuture") { Promise<int> p; auto f = p.getFuture(); // so core_ will become null REQUIRE_FALSE(p.isFulfilled()); p.setValue(42); // after here REQUIRE(p.isFulfilled()); } SECTION("brokenOnDelete") { auto p = std::make_unique<Promise<int>>(); auto f = p->getFuture(); REQUIRE_FALSE(f.isReady()); p.reset(); REQUIRE(f.isReady()); auto t = f.getTry(); REQUIRE(t.hasException()); REQUIRE_THROWS_AS(t.throwIfFailed(), FutureException); //REQUIRE(t.hasException<BrokenPromise>()); } /*SECTION("brokenPromiseHasTypeInfo") { auto pInt = std::make_unique<Promise<int>>(); auto fInt = pInt->getFuture(); auto pFloat = std::make_unique<Promise<float>>(); auto fFloat = pFloat->getFuture(); pInt.reset(); pFloat.reset(); try { auto whatInt = fInt.getTry().exception().what(); } catch(e) { } auto whatFloat = fFloat.getTry().exception().what(); REQUIRE(whatInt != whatFloat); }*/ }
25.018817
131
0.545181
[ "object" ]
9ec9db1996de8040f5f0e49af52402991b8e29cf
7,763
hpp
C++
hpx/parallel/executors/thread_execution.hpp
atrantan/hpx
6c214b2f3e3fc58648513c9f1cfef37fde59333c
[ "BSL-1.0" ]
1
2019-09-26T09:10:13.000Z
2019-09-26T09:10:13.000Z
hpx/parallel/executors/thread_execution.hpp
atrantan/hpx
6c214b2f3e3fc58648513c9f1cfef37fde59333c
[ "BSL-1.0" ]
null
null
null
hpx/parallel/executors/thread_execution.hpp
atrantan/hpx
6c214b2f3e3fc58648513c9f1cfef37fde59333c
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// \file parallel/executors/thread_execution.hpp #if !defined(HPX_PARALLEL_EXECUTORS_THREAD_EXECUTION_JAN_03_2017_1145AM) #define HPX_PARALLEL_EXECUTORS_THREAD_EXECUTION_JAN_03_2017_1145AM #include <hpx/config.hpp> #include <hpx/apply.hpp> #include <hpx/async.hpp> #include <hpx/lcos/future.hpp> #include <hpx/runtime/threads/thread_executor.hpp> #include <hpx/traits/is_launch_policy.hpp> #include <hpx/traits/future_access.hpp> #include <hpx/util/bind.hpp> #include <hpx/util/detail/pack.hpp> #include <hpx/util/deferred_call.hpp> #include <hpx/util/range.hpp> #include <hpx/util/tuple.hpp> #include <hpx/util/unwrap.hpp> #include <hpx/parallel/executors/execution.hpp> #include <algorithm> #include <type_traits> #include <utility> #include <vector> /////////////////////////////////////////////////////////////////////////////// // define customization point specializations for thread executors namespace hpx { namespace threads { /////////////////////////////////////////////////////////////////////////// // async_execute() template <typename Executor, typename F, typename ... Ts> HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, hpx::lcos::future< typename hpx::util::detail::invoke_deferred_result<F, Ts...>::type > >::type async_execute(Executor && exec, F && f, Ts &&... ts) { return hpx::async(std::forward<Executor>(exec), std::forward<F>(f), std::forward<Ts>(ts)...); } /////////////////////////////////////////////////////////////////////////// // sync_execute() template <typename Executor, typename F, typename ... Ts> HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, typename hpx::util::detail::invoke_deferred_result<F, Ts...>::type >::type sync_execute(Executor && exec, F && f, Ts &&... ts) { return hpx::async(std::forward<Executor>(exec), std::forward<F>(f), std::forward<Ts>(ts)...).get(); } /////////////////////////////////////////////////////////////////////////// // then_execute() template <typename Executor, typename F, typename Future, typename ... Ts> HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, hpx::lcos::future< typename hpx::util::detail::invoke_deferred_result< F, Future, Ts... >::type > >::type then_execute(Executor && exec, F && f, Future& predecessor, Ts &&... ts) { typedef typename hpx::util::detail::invoke_deferred_result< F, Future, Ts... >::type result_type; auto func = hpx::util::bind( hpx::util::one_shot(std::forward<F>(f)), hpx::util::placeholders::_1, std::forward<Ts>(ts)...); typename hpx::traits::detail::shared_state_ptr<result_type>::type p = hpx::lcos::detail::make_continuation_thread_exec<result_type>( predecessor, std::forward<Executor>(exec), std::move(func)); return hpx::traits::future_access<hpx::lcos::future<result_type> >:: create(std::move(p)); } /////////////////////////////////////////////////////////////////////////// // post() template <typename Executor, typename F, typename ... Ts> HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value >::type post(Executor && exec, F && f, Ts &&... ts) { hpx::apply(std::forward<Executor>(exec), std::forward<F>(f), std::forward<Ts>(ts)...); } /////////////////////////////////////////////////////////////////////////// // bulk_async_execute() template <typename Executor, typename F, typename Shape, typename ... Ts> typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, std::vector<hpx::lcos::future< typename parallel::execution::detail::bulk_function_result< F, Shape, Ts... >::type > > >::type bulk_async_execute(Executor && exec, F && f, Shape const& shape, Ts &&... ts) { std::vector<hpx::future< typename parallel::execution::detail::bulk_function_result< F, Shape, Ts... >::type > > results; results.reserve(util::size(shape)); for (auto const& elem: shape) { results.push_back(hpx::async(exec, std::forward<F>(f), elem, ts...)); } return results; } /////////////////////////////////////////////////////////////////////////// // bulk_sync_execute() template <typename Executor, typename F, typename Shape, typename ... Ts> typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, typename parallel::execution::detail::bulk_execute_result< F, Shape, Ts... >::type >::type bulk_sync_execute(Executor && exec, F && f, Shape const& shape, Ts &&... ts) { std::vector<hpx::future< typename parallel::execution::detail::bulk_function_result< F, Shape, Ts... >::type > > results; results.reserve(util::size(shape)); for (auto const& elem: shape) { results.push_back(hpx::async(exec, std::forward<F>(f), elem, ts...)); } return hpx::util::unwrap(results); } /////////////////////////////////////////////////////////////////////////// // bulk_then_execute() template <typename Executor, typename F, typename Shape, typename Future, typename ... Ts> HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_threads_executor<Executor>::value, hpx::future< typename parallel::execution::detail::bulk_then_execute_result< F, Shape, Future, Ts... >::type > >::type bulk_then_execute(Executor && exec, F && f, Shape const& shape, Future& predecessor, Ts &&... ts) { typedef typename parallel::execution::detail::then_bulk_function_result< F, Shape, Future, Ts... >::type func_result_type; typedef std::vector<hpx::lcos::future<func_result_type> > result_type; typedef hpx::lcos::future<result_type> result_future_type; // older versions of gcc are not able to capture parameter // packs (gcc < 4.9) auto args = hpx::util::make_tuple(std::forward<Ts>(ts)...); auto func = [exec, f, shape, args](Future predecessor) mutable -> result_type { return parallel::execution::detail::fused_bulk_async_execute( exec, f, shape, predecessor, typename hpx::util::detail::make_index_pack< sizeof...(Ts) >::type(), args); }; typedef typename hpx::traits::detail::shared_state_ptr< result_type >::type shared_state_type; shared_state_type p = lcos::detail::make_continuation_thread_exec<result_type>( predecessor, std::forward<Executor>(exec), std::move(func)); return hpx::traits::future_access<result_future_type>:: create(std::move(p)); } }} #endif
35.447489
81
0.544506
[ "shape", "vector" ]
19b66aac5b10bd8e0156f8a3f14480e764a832bd
5,345
cpp
C++
src/c/objective.cpp
rupea/LabelFilters
a70b1f90427fe44bd43fee842aad34704d51854c
[ "BSD-3-Clause" ]
4
2019-04-23T01:32:47.000Z
2019-12-12T07:02:52.000Z
src/c/objective.cpp
rupea/LabelFilters
a70b1f90427fe44bd43fee842aad34704d51854c
[ "BSD-3-Clause" ]
1
2019-01-21T22:05:09.000Z
2019-03-06T15:37:35.000Z
src/c/objective.cpp
rupea/LabelFilters
a70b1f90427fe44bd43fee842aad34704d51854c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2017 NEC Laboratories America, Inc. ("NECLA"). All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. An additional grant of patent rights * can be found in the PATENTS file in the same directory. */ #include "objective.h" #include "typedefs.h" #include "parameter.h" #include "boolmatrix.h" #include "WeightVector.h" namespace mcsolver_detail{ // ***************************************** // Function to calculate the objective for one example // this almost duplicates the function compute_objective // the two functions should be unified // this functions is easier to use with the finite_diff_test because // it does not require the entire projection vector double calculate_ex_objective_hinge(size_t i, double proj, const SparseMb& y, const VectorXi& nclasses, const VectorXd& inside_weight, const VectorXd& outside_weight, const std::vector<int>& sorted_class, const std::vector<int>& class_order, const VectorXd& sortedLU, const boolmatrix& filtered, bool none_filtered, double C1, double C2, const param_struct& params) { double obj_val=0; int noClasses = y.cols(); double class_weight, other_weight; std::vector<int> classes; std::vector<int>::iterator class_iter; classes.reserve(nclasses.coeff(i)+1); int left_classes, right_classes; double left_weight, right_weight; int sc,cp; const double* sortedLU_iter; class_weight = C1*inside_weight.coeff(i); other_weight = C2*outside_weight.coeff(i); left_classes = 0; //number of classes to the left of the current one left_weight = 0; // left_classes * other_weight right_classes = nclasses.coeff(i); //number of classes to the right of the current one right_weight = other_weight * right_classes; // calling y.coeff is expensive so get the classes here classes.resize(0); for (SparseMb::InnerIterator it(y,i); it; ++it) { if (it.value()) { classes.push_back(class_order[it.col()]); } } classes.push_back(noClasses); // this will always be the last std::sort(classes.begin(),classes.end()); sc=0; class_iter = classes.begin(); sortedLU_iter=sortedLU.data(); while (sc < noClasses) { while(sc < *class_iter) { // while example is not of class cp cp = sorted_class[sc]; if (none_filtered || !(filtered.get(i,cp))) { obj_val += (left_classes?(left_weight * hinge_loss(*sortedLU_iter - proj)):0) + (right_classes?(right_weight * hinge_loss(proj - *(sortedLU_iter+1))):0); } sc++; sortedLU_iter+=2; } if (sc < noClasses) // test if we are done { // example has class cp cp = sorted_class[sc]; // compute the loss incured by the example no being withing the bounds // of class cp // could also test if params.remove_class_constraints is set. If not, this constarint can not be filtered // essentially add || !params.remove_class_constraint to the conditions below // would speed things up by a tiny bit .. not significant if (none_filtered || !(filtered.get(i,cp))) { obj_val += (class_weight * (hinge_loss(proj - *sortedLU_iter) + hinge_loss(*(sortedLU_iter+1) - proj))); } left_classes++; right_classes--; left_weight += other_weight; right_weight -= other_weight; ++class_iter; sc++; sortedLU_iter+=2; } } return obj_val; } // ******************************* // Calculates the objective function double calculate_objective_hinge(const VectorXd& projection, const SparseMb& y, const VectorXi& nclasses, const VectorXd& inside_weight, const VectorXd& outside_weight, const std::vector<int>& sorted_class, const std::vector<int>& class_order, const double norm, const VectorXd& sortedLU, const boolmatrix& filtered, double lambda, double C1, double C2, const param_struct& params) { double obj_val = 0; bool none_filtered = filtered.count()==0; #if MCTHREADS #pragma omp parallel for default(shared) reduction(+:obj_val) #endif for (size_t i = 0; i < projection.size(); i++) { obj_val += calculate_ex_objective_hinge(i, projection.coeff(i), y, nclasses, inside_weight, outside_weight, sorted_class,class_order, sortedLU, filtered, none_filtered, C1, C2, params); } obj_val += .5 * lambda * norm * norm; return obj_val; } double calculate_objective_hinge(const VectorXd& projection, const SparseMb& y, const VectorXi& nclasses, const VectorXd& inside_weight, const VectorXd& outside_weight, const std::vector<int>& sorted_class, const std::vector<int>& class_order, const double norm, const VectorXd& sortedLU, double lambda, double C1, double C2, const param_struct& params) { const int noClasses = y.cols(); const int n = projection.size(); boolmatrix filtered(n,noClasses); return calculate_objective_hinge(projection, y,nclasses, inside_weight, outside_weight, sorted_class, class_order, norm, sortedLU, filtered, lambda, C1, C2, params); } }
34.707792
169
0.658185
[ "vector" ]
19bbf129ebdc2f615bacac395926f6c8ddd481d0
1,179
cpp
C++
PrutEngine/src/Renderer.cpp
valvy/PrutEngine
1865dba7e441b2ab9415bc45506284c4b28f8779
[ "MIT" ]
null
null
null
PrutEngine/src/Renderer.cpp
valvy/PrutEngine
1865dba7e441b2ab9415bc45506284c4b28f8779
[ "MIT" ]
null
null
null
PrutEngine/src/Renderer.cpp
valvy/PrutEngine
1865dba7e441b2ab9415bc45506284c4b28f8779
[ "MIT" ]
null
null
null
#include "prutengine/Renderer.hpp" #include "prutengine/AssetManager.hpp" using namespace PrutEngine; Renderer::~Renderer(){ } void Renderer::set(const std::string& mesh, const std::string& texture, std::shared_ptr<Data::GraphicsProgram> program){ const auto assetManager = Application::getInstance()->getAssetManager(); this->program = program; this->mesh = assetManager->loadMesh(mesh); this->texture = assetManager->loadTexture(texture); } std::shared_ptr<Data::Mesh> Renderer::getMesh() const{ return this->mesh; } std::shared_ptr<Data::GraphicsProgram> Renderer::getProgram() const{ return this->program; } std::shared_ptr<Data::Texture> Renderer::getTexture() const{ return this->texture; } GLRenderer::~GLRenderer(){ } GLRenderer::GLRenderer(const std::string& mesh, const std::string& texture, std::shared_ptr<Data::GraphicsProgram> program){ const Data::GLProgram* progr = static_cast<Data::GLProgram*>(program.get()); this->pos_reference = glGetUniformLocation(progr->getProgram(), "mv_matrix"); this->set(mesh,texture,program); } GLint GLRenderer::getPositionRef() const{ return this->pos_reference; }
26.795455
124
0.721798
[ "mesh" ]
19c27ce4262d6e28d9f78ebcca49d0995c51268a
9,084
cpp
C++
src/editor/InspectorEditor.cpp
Guarneri1743/SoftRasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
4
2020-12-14T10:58:35.000Z
2020-12-14T16:38:18.000Z
src/editor/InspectorEditor.cpp
J-Mat/CPU-Rasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
null
null
null
src/editor/InspectorEditor.cpp
J-Mat/CPU-Rasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
null
null
null
#include "InspectorEditor.hpp" #include <algorithm> #include <filesystem> #include "imgui/imgui.h" #include "Define.hpp" #include "InputManager.hpp" #include "Window.hpp" #include "Singleton.hpp" #include "Scene.hpp" #include "Utility.hpp" #include "Logger.hpp" #include "Serialization.hpp" #include "Time.hpp" #include "CGL.h" #undef near #undef far namespace CpuRasterizer { bool show = true; int rt_size[2]; int shadowmap_size[2]; int sub_samples = 4; bool enable_msaa = false; InspectorEditor::InspectorEditor(int x, int y, int w, int h) : BaseEditor(x, y, w, h) { no_scrollbar = true; no_titlebar = true; no_menu = true; no_collapse = true; no_resize = true; no_close = true; no_move = true; title = "Setting"; } void InspectorEditor::draw_inspector() { if (Scene::current() == nullptr) return; Scene& scene = *Scene::current(); if (scene.selection != nullptr) { Model* model = scene.selection->get_model(); if (model != nullptr) { if (model->transform != nullptr) { transform_inspector.on_gui(*model->transform); } if (model->material != nullptr) { material_inspector.on_gui(*model->material); } } } } void InspectorEditor::draw_settings() { { if (ImGui::InputInt2("RT Size", rt_size)) { cglSetViewPort(0, 0, rt_size[0], rt_size[1]); } else { size_t x, y, width, height; cglGetViewport(x, y, width, height); rt_size[0] = (int)width; rt_size[1] = (int)height; } ImGui::Text("FPS: %.1f", ImGui::GetIO().Framerate); } Scene& scene = *Scene::current(); light_inspector.on_gui(*scene.main_light); if (ImGui::CollapsingHeader("Camera", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Position: %f, %f, %f", scene.main_cam->transform->world_position().x , scene.main_cam->transform->world_position().y, scene.main_cam->transform->world_position().z); ImGui::Text("Direction: %f, %f, %f", scene.main_cam->transform->world_euler_angles().x, scene.main_cam->transform->world_euler_angles().y, scene.main_cam->transform->world_euler_angles().z); bool cam_update = false; if (scene.main_cam->frustum_param.projection_mode == tinymath::Projection::kPerspective) { cam_update = ImGui::SliderFloat("Near", &scene.main_cam->frustum_param.perspective_param.near, 0.0f, 5.0f); cam_update = ImGui::SliderFloat("Far", &scene.main_cam->frustum_param.perspective_param.far, 5.0f, 10000.0f) || cam_update; cam_update = ImGui::SliderFloat("Fov", &scene.main_cam->frustum_param.perspective_param.fov, 0.0f, 180.0f) || cam_update; cam_update = ImGui::SliderFloat("Aspect", &scene.main_cam->frustum_param.perspective_param.aspect, 0.0f, 2.0f) || cam_update; } else { } if (cam_update) scene.main_cam->update_projection_matrix(); if (ImGui::Checkbox("MSAA", &enable_msaa)) { if (enable_msaa) { cglSetSubSampleCount((uint8_t)sub_samples); } else { cglSetSubSampleCount((uint8_t)0); } } if (enable_msaa) { const char* frequencies[] = { "PixelFrequency", "SubsampleFrequency", }; const MultiSampleFrequency frequency_flags[] = { MultiSampleFrequency::kPixelFrequency, MultiSampleFrequency::kSubsampleFrequency }; static int selected_frequency = 0; if (ImGui::Button("MultiSampleFrequency..")) ImGui::OpenPopup("frequencies"); ImGui::SameLine(); ImGui::TextUnformatted(selected_frequency == -1 ? "<None>" : frequencies[selected_frequency]); if (ImGui::BeginPopup("frequencies")) { ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(frequencies); i++) if (ImGui::Selectable(frequencies[i])) { selected_frequency = i; cglSetMultisampleFrequency(frequency_flags[i]); } ImGui::EndPopup(); } if (ImGui::InputInt("Subsamples", &sub_samples)) { cglSetSubSampleCount((uint8_t)sub_samples); } else { sub_samples = (int)cglGetSubSampleCount(); } } } if (ImGui::CollapsingHeader("Shadow", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("ShadowOn", &CpuRasterSharedData.enable_shadow); if (CpuRasterSharedData.enable_shadow) { if (ImGui::InputInt2("ShadowMap Resolution", shadowmap_size)) { Scene::current()->resize_shadowmap(shadowmap_size[0], shadowmap_size[1]); } else { size_t sw, sh; Scene::current()->get_shadowmap_size(sw, sh); shadowmap_size[0] = (int)sw; shadowmap_size[1] = (int)sh; } ImGui::Checkbox("PCF", &CpuRasterSharedData.pcf_on); ImGui::SliderFloat("Bias", &CpuRasterSharedData.shadow_bias, 0.0f, 0.01f); } } if (ImGui::CollapsingHeader("IBL", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("IBL_On", &CpuRasterSharedData.enable_ibl); std::string hdri_path[] = { "None", "valley", "ballroom", "cave_room", "fireplace", "green_house", "kloppenheim", "loft_hall", "man_outside", "memorial", "nave", "preller", "veranda" }; static int selected_view = 0; if (ImGui::Button("HDRI..")) ImGui::OpenPopup("hdri"); ImGui::SameLine(); ImGui::TextUnformatted(selected_view == -1 ? "<None>" : hdri_path[selected_view].c_str()); if (ImGui::BeginPopup("hdri")) { ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(hdri_path); i++) if (ImGui::Selectable(hdri_path[i].c_str())) { selected_view = i; Scene::current()->set_cubemap("/hdri/" + hdri_path[selected_view] + ".hdri"); } ImGui::EndPopup(); } } if (ImGui::CollapsingHeader("Debug", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("Gizmos", &CpuRasterSharedData.enable_gizmos); ImGui::Checkbox("Mipmap", &CpuRasterSharedData.enable_mipmap); const char* debug_views[] = { "None", "WireFrame", "ShadowMap", "Depth", "Stencil", "UV", "Normal", "VertexColor", "Specular", "Tiles", "IrradianceMap", "Albedo", "Roughness", "Metallic", "AO", "IndirectDiffuse", "IndirectSpecular", "Mipmap" }; const RenderFlag view_flags[] = { RenderFlag::kNone, RenderFlag::kWireFrame, RenderFlag::kShadowMap, RenderFlag::kDepth, RenderFlag::kStencil, RenderFlag::kUV, RenderFlag::kNormal, RenderFlag::kVertexColor, RenderFlag::kSpecular, RenderFlag::kFrameTile, RenderFlag::kIrradianceMap, RenderFlag::kAlbedo, RenderFlag::kRoughness, RenderFlag::kMetallic, RenderFlag::kAO, RenderFlag::kIndirectDiffuse, RenderFlag::kIndirectSpecular, RenderFlag::kMipmap }; static int selected_view = 0; if (ImGui::Button("Views..")) ImGui::OpenPopup("debug_views"); ImGui::SameLine(); ImGui::TextUnformatted(selected_view == -1 ? "<None>" : debug_views[selected_view]); if (ImGui::BeginPopup("debug_views")) { ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(debug_views); i++) if (ImGui::Selectable(debug_views[i])) { selected_view = i; CpuRasterSharedData.debug_flag = RenderFlag::kNone; CpuRasterSharedData.debug_flag = view_flags[i]; } ImGui::EndPopup(); } } if (ImGui::CollapsingHeader("Others")) { const char* work_flows[] = { "Metallic", "Specular" }; static int selected_flow = (int)CpuRasterSharedData.workflow; if (ImGui::Button("Workflows..")) ImGui::OpenPopup("work_flows"); ImGui::SameLine(); ImGui::TextUnformatted(selected_flow == -1 ? "<None>" : work_flows[selected_flow]); if (ImGui::BeginPopup("work_flows")) { ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(work_flows); i++) if (ImGui::Selectable(work_flows[i])) { selected_flow = i; CpuRasterSharedData.workflow = (PBRWorkFlow)selected_flow; } ImGui::EndPopup(); } const char* color_spaces[] = { "Gamma", "Linear" }; static int selected_color_space = (int)CpuRasterSharedData.color_space; if (ImGui::Button("ColorSpaces..")) ImGui::OpenPopup("color_spaces"); ImGui::SameLine(); ImGui::TextUnformatted(selected_color_space == -1 ? "<None>" : color_spaces[selected_color_space]); if (ImGui::BeginPopup("color_spaces")) { ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(color_spaces); i++) if (ImGui::Selectable(color_spaces[i])) { selected_color_space = i; CpuRasterSharedData.color_space = (ColorSpace)selected_color_space; } ImGui::EndPopup(); } } } void InspectorEditor::on_gui() { rect = tinymath::Rect((int)Window::main()->get_width() - kRightWidth, kTopHeight, kRightWidth, (int)Window::main()->get_height() - kTopHeight - kBottomHeight); ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; if (ImGui::BeginTabBar("Inspector", tab_bar_flags)) { if (ImGui::BeginTabItem("Inspector")) { draw_inspector(); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Setting")) { draw_settings(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } } }
26.639296
193
0.648943
[ "model", "transform" ]
19d54e63ba62708d9484ab2f3c050f9c20cd51cf
1,086
hpp
C++
src/editor/property_integer_limited.hpp
acidicMercury8/xray-1.6
52fba7348a93a52ff9694f2c9dd40c0d090e791e
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
src/editor/property_integer_limited.hpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/editor/property_integer_limited.hpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2021-11-07T16:57:19.000Z
2021-12-05T13:17:12.000Z
//////////////////////////////////////////////////////////////////////////// // Module : property_integer_limited.hpp // Created : 12.12.2007 // Modified : 12.12.2007 // Author : Dmitriy Iassenev // Description : limited integer property implementation class //////////////////////////////////////////////////////////////////////////// #ifndef PROPERTY_INTEGER_LIMITED_HPP_INCLUDED #define PROPERTY_INTEGER_LIMITED_HPP_INCLUDED #include "property_integer.hpp" public ref class property_integer_limited : public property_integer { private: typedef property_integer inherited; public: typedef System::Object Object; public: property_integer_limited( integer_getter_type const &getter, integer_setter_type const &setter, int const %min, int const %max ); virtual Object ^get_value () override; virtual void set_value (System::Object ^object) override; private: int m_min; int m_max; }; // ref class property_integer_limited #endif // ifndef PROPERTY_INTEGER_LIMITED_HPP_INCLUDED
30.166667
77
0.616943
[ "object" ]
19e70f1e92436dbacaf3bece72ab00a0e38580f6
3,114
cc
C++
bssopenapi/src/model/DescribeResourceCoverageTotalResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
bssopenapi/src/model/DescribeResourceCoverageTotalResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
bssopenapi/src/model/DescribeResourceCoverageTotalResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/bssopenapi/model/DescribeResourceCoverageTotalResult.h> #include <json/json.h> using namespace AlibabaCloud::BssOpenApi; using namespace AlibabaCloud::BssOpenApi::Model; DescribeResourceCoverageTotalResult::DescribeResourceCoverageTotalResult() : ServiceResult() {} DescribeResourceCoverageTotalResult::DescribeResourceCoverageTotalResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeResourceCoverageTotalResult::~DescribeResourceCoverageTotalResult() {} void DescribeResourceCoverageTotalResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; auto allPeriodCoverageNode = dataNode["PeriodCoverage"]["Item"]; for (auto dataNodePeriodCoverageItem : allPeriodCoverageNode) { Data::Item itemObject; if(!dataNodePeriodCoverageItem["Period"].isNull()) itemObject.period = dataNodePeriodCoverageItem["Period"].asString(); if(!dataNodePeriodCoverageItem["CoveragePercentage"].isNull()) itemObject.coveragePercentage = std::stof(dataNodePeriodCoverageItem["CoveragePercentage"].asString()); data_.periodCoverage.push_back(itemObject); } auto totalCoverageNode = dataNode["TotalCoverage"]; if(!totalCoverageNode["CoveragePercentage"].isNull()) data_.totalCoverage.coveragePercentage = std::stof(totalCoverageNode["CoveragePercentage"].asString()); if(!totalCoverageNode["DeductQuantity"].isNull()) data_.totalCoverage.deductQuantity = std::stof(totalCoverageNode["DeductQuantity"].asString()); if(!totalCoverageNode["TotalQuantity"].isNull()) data_.totalCoverage.totalQuantity = std::stof(totalCoverageNode["TotalQuantity"].asString()); if(!totalCoverageNode["CapacityUnit"].isNull()) data_.totalCoverage.capacityUnit = totalCoverageNode["CapacityUnit"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string DescribeResourceCoverageTotalResult::getMessage()const { return message_; } DescribeResourceCoverageTotalResult::Data DescribeResourceCoverageTotalResult::getData()const { return data_; } std::string DescribeResourceCoverageTotalResult::getCode()const { return code_; } bool DescribeResourceCoverageTotalResult::getSuccess()const { return success_; }
34.21978
106
0.774888
[ "model" ]
19e9abb49653d0275edb443cbc512b2bd90ea776
9,048
cpp
C++
src/linux_parser.cpp
epengc/Udacity_System_Monitor
81441161221445c17f00df9023978e0cfa1224ea
[ "MIT" ]
null
null
null
src/linux_parser.cpp
epengc/Udacity_System_Monitor
81441161221445c17f00df9023978e0cfa1224ea
[ "MIT" ]
null
null
null
src/linux_parser.cpp
epengc/Udacity_System_Monitor
81441161221445c17f00df9023978e0cfa1224ea
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <string> #include <vector> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; using std::size_t; using std::map; using std::stoi; using std::stol; // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, version, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } // TODO: Read and return the system memory utilization float LinuxParser::MemoryUtilization() { string line; string key; string value; string kb; float memtotal=1; float memfree=1; std::ifstream filestream(kProcDirectory+kMeminfoFilename); if(filestream.is_open()){ while(std::getline(filestream, line)){ std::istringstream linestream(line); while(linestream>>key>>value>>kb){ if(key=="MemTotal:"){ memtotal = stof(value); } if(key=="MemFree:"){ memfree = stof(value); } } } } float loadavg = (memtotal-memfree)/memtotal; return loadavg; } // TODO: Read and return the system uptime long LinuxParser::UpTime() { string line; string val; std::ifstream filestream(kProcDirectory+kUptimeFilename); if(filestream.is_open()){ while(std::getline(filestream, line)){ std::istringstream linestream(line); while(linestream>>val){ return stoi(val); } } } return 0; } // TODO: Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return LinuxParser::UpTime()*sysconf(_SC_CLK_TCK); } // TODO: Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid) { string line; string item; vector<string> values; std::ifstream filestream(LinuxParser::kProcDirectory+to_string(pid)+kStatFilename); if(filestream.is_open()){ std::getline(filestream, line); std::istringstream linestream(line); while(linestream>>item){ values.push_back(item); } } long int actJif = 0; if(values.size()>21){ // https://man7.org/linux/man-pages/man5/proc.5.html // // utime = Amount of time that this process has been scheduled in user mode. long int utime = stol(values[13]); // stime = Amount of time that this process has been scheduled in kernel mode. long int stime = stol(values[14]); // cutime = Amount of time that this process's waited-for children have been scheduled in user mode. long cutime = stol(values[15]); // cstime = Amount of time that this process's waited-for children have been scheduled in kernel mode. long cstime = stol(values[16]); actJif = utime+stime+cutime+cstime; } return actJif; } // TODO: Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { vector<string> cpu_table = LinuxParser::CpuUtilization(); long int actJif=0; for(int i=0; i<8; i++){ actJif += stol(cpu_table[0]); } return actJif; } // TODO: Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { vector<string> cpu_table = LinuxParser::CpuUtilization(); long int idlJif = stol(cpu_table[CPUStates::kIdle_])+stol(cpu_table[CPUStates::kIOwait_]); return idlJif; } // TODO: Read and return CPU utilization vector<string> LinuxParser::CpuUtilization() { string line; string str_cpu; string value; vector<string> values; std::ifstream filestream(kProcDirectory+kStatFilename); if(filestream.is_open()){ while(std::getline(filestream, line)){ std::istringstream linestream(line); linestream>>str_cpu; if (str_cpu=="cpu"){ while(linestream>>value){ values.push_back(value); } } } } return values; } // TODO: Read and return the total number of processes int LinuxParser::TotalProcesses() { string line; string key; string val; std::ifstream filestream(kProcDirectory+kStatFilename); if(filestream.is_open()){ while(std::getline(filestream, line)){ std::istringstream linestream(line); while(linestream>>key>>val){ if(key=="processes"){ return stoi(val); } } } } return 0; } // TODO: Read and return the number of running processes int LinuxParser::RunningProcesses() { string line; string key; string val; std::ifstream filestream(kProcDirectory+kStatFilename); if(filestream.is_open()){ while(std::getline(filestream, line)){ std::istringstream linestream(line); while(linestream>>key>>val){ if(key=="procs_running"){ return stoi(val); } } } } return 0; } // TODO: Read and return the command associated with a process string LinuxParser::Command(int pid) { string line; string value; std::ifstream filestream(kProcDirectory+to_string(pid)+kCmdlineFilename); if (filestream.is_open()){ std::getline(filestream, line); return line; } return ""; } // TODO: Read and return the memory used by a process string LinuxParser::Ram(int pid) { string name; string value; std::ifstream filestream(kProcDirectory+to_string(pid)+kStatusFilename); if (filestream.is_open()){ while(filestream>>name){ if (name=="VmSize:"){ filestream>>value; return to_string(stoi(value)/1024); } } } return string("0"); } // TODO: Read and return the user ID associated with a process string LinuxParser::Uid(int pid) { string line; string value; string name; std::ifstream filestream(kProcDirectory+to_string(pid)+kStatusFilename); if(filestream.is_open()){ std::getline(filestream, line); std::istringstream linestream(line); while(linestream>>name){ if(name=="Uid:"){ linestream>>value; return value; } } } return string(""); } // TODO: Read and return the user associated with a process string LinuxParser::User(int pid) { string line; string name; string value; std::ifstream filestream(kPasswordPath); if(filestream.is_open()){ std::getline(filestream, line); name = "x:"+Uid(pid); if(line.find(name)!=string::npos){ return line.substr(0,line.find(name)-1); } } return string("0"); } // TODO: Read and return the uptime of a process long int LinuxParser::UpTime(int pid) { string item; long int uptime{0}; std::ifstream filestream(kProcDirectory+to_string(pid)+kStatFilename); if(filestream.is_open()){ for(int i=0; filestream>>item;++i) if (i==13){ long int uptime{stol(item)}; // Amount of time that this process has been scheduled in user mode, // measured in clock ticks :devided by sysconf(_SC_CLK_TCKSC_CLK_TCK). uptime /= sysconf(_SC_CLK_TCK); return uptime; } } return uptime; }
28.186916
110
0.599691
[ "vector" ]
19e9e99d887a33a1e280b149dce6129d7df4b8bb
1,183
cpp
C++
Algorithms/UnionFind/0839-similar-string-groups.cpp
sandychn/LeetCode-Solutions
d0dd55d62b099c5b7db947822ab2111a4ecdc941
[ "MIT" ]
null
null
null
Algorithms/UnionFind/0839-similar-string-groups.cpp
sandychn/LeetCode-Solutions
d0dd55d62b099c5b7db947822ab2111a4ecdc941
[ "MIT" ]
null
null
null
Algorithms/UnionFind/0839-similar-string-groups.cpp
sandychn/LeetCode-Solutions
d0dd55d62b099c5b7db947822ab2111a4ecdc941
[ "MIT" ]
null
null
null
class UnionFind { public: UnionFind(int size): parent(size), setCount(size) { iota(parent.begin(), parent.end(), 0); } int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); } void join(int x, int y) { if ((x = find(x)) == (y = find(y))) return; parent[x] = y; --setCount; } int size() const { return setCount; } private: vector<int> parent; int setCount; }; class Solution { public: int numSimilarGroups(vector<string>& strs) { const int n = strs.size(); UnionFind uf(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (isSimilar(strs[i], strs[j])) { uf.join(i, j); } } } return uf.size(); } bool isSimilar(const string& a, const string& b) { int cnt = 0; const int n = a.size(); for (int i = 0; i < n; i++) { if (a[i] != b[i]) { if (++cnt > 2) return false; } } return true; } };
21.907407
65
0.411665
[ "vector" ]
19ea353cf51868a1ebb0eb0d0b4fd464a0cfca8b
2,642
cpp
C++
src/apps/debuganalyzer/model/ThreadModel.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/debuganalyzer/model/ThreadModel.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/debuganalyzer/model/ThreadModel.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include "ThreadModel.h" #include <new> // #pragma mark - WaitObjectGroup ThreadModel::WaitObjectGroup::WaitObjectGroup( Model::ThreadWaitObject** waitObjects, int32 count) : fWaitObjects(waitObjects), fCount(count), fWaits(0), fTotalWaitTime(0) { for (int32 i = 0; i < fCount; i++) { fWaits += fWaitObjects[i]->Waits(); fTotalWaitTime += fWaitObjects[i]->TotalWaitTime(); } } ThreadModel::WaitObjectGroup::~WaitObjectGroup() { delete[] fWaitObjects; } // #pragma mark - ThreadModel ThreadModel::ThreadModel(Model* model, Model::Thread* thread) : fModel(model), fThread(thread), fWaitObjectGroups(10, true) { } ThreadModel::~ThreadModel() { } ThreadModel::WaitObjectGroup* ThreadModel::AddWaitObjectGroup( const BObjectList<Model::ThreadWaitObject>& waitObjects, int32 start, int32 end) { // check params int32 count = end - start; if (start < 0 || count <= 0 || waitObjects.CountItems() < end) return NULL; // create an array of the wait object Model::ThreadWaitObject** objects = new(std::nothrow) Model::ThreadWaitObject*[count]; if (objects == NULL) return NULL; for (int32 i = 0; i < count; i++) objects[i] = waitObjects.ItemAt(start + i); // create and add the group WaitObjectGroup* group = new(std::nothrow) WaitObjectGroup(objects, count); if (group == NULL) { delete[] objects; return NULL; } if (!fWaitObjectGroups.BinaryInsert(group, &WaitObjectGroup::CompareByTypeName)) { delete group; return NULL; } return group; } bool ThreadModel::AddSchedulingEvent(const system_profiler_event_header* eventHeader) { return fSchedulingEvents.AddItem(eventHeader); } int32 ThreadModel::FindSchedulingEvent(nanotime_t time) { if (time < 0) return 0; time += fModel->BaseTime(); int32 lower = 0; int32 upper = CountSchedulingEvents() - 1; while (lower < upper) { int32 mid = (lower + upper) / 2; const system_profiler_event_header* header = SchedulingEventAt(mid); system_profiler_thread_scheduling_event* event = (system_profiler_thread_scheduling_event*)(header + 1); if (event->time < time) lower = mid + 1; else upper = mid; } // We've found the first event that has a time >= the given time. If its // time is >, we rather return the previous event. if (lower > 0) { const system_profiler_event_header* header = SchedulingEventAt(lower); system_profiler_thread_scheduling_event* event = (system_profiler_thread_scheduling_event*)(header + 1); if (event->time > time) lower--; } return lower; }
20.323077
80
0.708176
[ "object", "model" ]
19ef3ff4f7f284c3196ceae52be9a8080ed68a78
7,916
cc
C++
mojo/edk/system/handle_table_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
null
null
null
mojo/edk/system/handle_table_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
null
null
null
mojo/edk/system/handle_table_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "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 "mojo/edk/system/handle_table.h" #include <vector> #include "mojo/edk/system/dispatcher.h" #include "mojo/edk/system/handle.h" #include "mojo/edk/system/mock_simple_dispatcher.h" #include "testing/gtest/include/gtest/gtest.h" using mojo::util::MakeRefCounted; using mojo::util::RefPtr; namespace mojo { namespace system { namespace { TEST(HandleTableTest, Basic) { HandleTable ht(1000u); Handle h(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_TRANSFER | MOJO_HANDLE_RIGHT_READ); MojoHandle hv = ht.AddHandle(h.Clone()); ASSERT_NE(hv, MOJO_HANDLE_INVALID); // Save the pointer value (without taking a ref), so we can check that we get // the same object back. Dispatcher* dv = h.dispatcher.get(); // Reset this, to make sure that the handle table takes a ref. h.reset(); EXPECT_EQ(MOJO_RESULT_OK, ht.GetHandle(hv, &h)); EXPECT_EQ(dv, h.dispatcher.get()); EXPECT_EQ(MOJO_HANDLE_RIGHT_TRANSFER | MOJO_HANDLE_RIGHT_READ, h.rights); h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv, &h)); ASSERT_EQ(dv, h.dispatcher.get()); EXPECT_EQ(MOJO_HANDLE_RIGHT_TRANSFER | MOJO_HANDLE_RIGHT_READ, h.rights); EXPECT_EQ(MOJO_RESULT_OK, h.dispatcher->Close()); // We removed |hv|, so it should no longer be valid. h.reset(); EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, ht.GetHandle(hv, &h)); } TEST(HandleTableTest, AddHandlePair) { HandleTable ht(1000u); Handle h1(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_NONE); Handle h2(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_DUPLICATE); auto hp = ht.AddHandlePair(h1.Clone(), h2.Clone()); ASSERT_NE(hp.first, MOJO_HANDLE_INVALID); ASSERT_NE(hp.second, MOJO_HANDLE_INVALID); ASSERT_NE(hp.first, hp.second); Handle h; ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hp.first, &h)); ASSERT_EQ(h1, h); h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hp.second, &h)); ASSERT_EQ(h2, h); EXPECT_EQ(MOJO_RESULT_OK, h1.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h2.dispatcher->Close()); } TEST(HandleTableTest, AddHandleTooMany) { HandleTable ht(2u); Handle h1(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_NONE); Handle h2(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_DUPLICATE); Handle h3(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_TRANSFER); MojoHandle hv1 = ht.AddHandle(h1.Clone()); ASSERT_NE(hv1, MOJO_HANDLE_INVALID); MojoHandle hv2 = ht.AddHandle(h2.Clone()); ASSERT_NE(hv2, MOJO_HANDLE_INVALID); EXPECT_NE(hv2, hv1); // Table should be full; adding |h3| should fail. EXPECT_EQ(MOJO_HANDLE_INVALID, ht.AddHandle(h3.Clone())); // Remove |hv2|/|h2|. Handle h; ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv2, &h)); ASSERT_EQ(h2, h); // Now adding |h3| should succeed. MojoHandle hv3 = ht.AddHandle(h3.Clone()); ASSERT_NE(hv3, MOJO_HANDLE_INVALID); EXPECT_NE(hv3, hv1); // Note: |hv3| may be equal to |hv2| (handle values may be reused). h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv1, &h)); ASSERT_EQ(h1, h); h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv3, &h)); ASSERT_EQ(h3, h); EXPECT_EQ(MOJO_RESULT_OK, h1.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h2.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h3.dispatcher->Close()); } TEST(HandleTableTest, AddHandlePairTooMany) { HandleTable ht(2u); Handle h1(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_NONE); Handle h2(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_TRANSFER); Handle h3(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_READ); Handle h4(MakeRefCounted<test::MockSimpleDispatcher>(), MOJO_HANDLE_RIGHT_WRITE); auto hp = ht.AddHandlePair(h1.Clone(), h2.Clone()); auto hv1 = hp.first; auto hv2 = hp.second; ASSERT_NE(hv1, MOJO_HANDLE_INVALID); ASSERT_NE(hv2, MOJO_HANDLE_INVALID); ASSERT_NE(hv1, hv2); // Table should be full; adding |h3| should fail. EXPECT_EQ(MOJO_HANDLE_INVALID, ht.AddHandle(h3.Clone())); // Adding |h3| and |h4| as a pair should also fail. auto hp2 = ht.AddHandlePair(h3.Clone(), h4.Clone()); EXPECT_EQ(MOJO_HANDLE_INVALID, hp2.first); EXPECT_EQ(MOJO_HANDLE_INVALID, hp2.second); // Remove |hv2|/|h2|. Handle h; ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv2, &h)); ASSERT_EQ(h2, h); // Trying to add |h3| and |h4| as a pair should still fail. hp2 = ht.AddHandlePair(h3.Clone(), h4.Clone()); EXPECT_EQ(MOJO_HANDLE_INVALID, hp2.first); EXPECT_EQ(MOJO_HANDLE_INVALID, hp2.second); // Remove |hv1|/|h1|. h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv1, &h)); ASSERT_EQ(h1, h); // Add |h3| and |h4| as a pair should now succeed fail. hp2 = ht.AddHandlePair(h3.Clone(), h4.Clone()); auto hv3 = hp2.first; auto hv4 = hp2.second; ASSERT_NE(hv3, MOJO_HANDLE_INVALID); ASSERT_NE(hv4, MOJO_HANDLE_INVALID); ASSERT_NE(hv3, hv4); h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv3, &h)); ASSERT_EQ(h3, h); h.reset(); ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(hv4, &h)); ASSERT_EQ(h4, h); EXPECT_EQ(MOJO_RESULT_OK, h1.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h2.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h3.dispatcher->Close()); EXPECT_EQ(MOJO_RESULT_OK, h4.dispatcher->Close()); } TEST(HandleTableTest, AddHandleVector) { static constexpr size_t kNumHandles = 10u; HandleTable ht(1000u); HandleVector handles; for (size_t i = 0u; i < kNumHandles; i++) { handles.push_back(Handle(MakeRefCounted<test::MockSimpleDispatcher>(), static_cast<MojoHandleRights>(i))); ASSERT_TRUE(handles[i]) << i; } std::vector<MojoHandle> handle_values(kNumHandles, MOJO_HANDLE_INVALID); HandleVector handles_copy = handles; ASSERT_TRUE(ht.AddHandleVector(&handles_copy, handle_values.data())); for (size_t i = 0u; i < kNumHandles; i++) { ASSERT_NE(handle_values[i], MOJO_HANDLE_INVALID) << i; EXPECT_FALSE(handles_copy[i]) << i; Handle h; ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(handle_values[i], &h)) << i; ASSERT_EQ(handles[i], h) << i; EXPECT_EQ(MOJO_RESULT_OK, handles[i].dispatcher->Close()) << i; } } TEST(HandleTableTest, AddHandleVectorTooMany) { static constexpr size_t kHandleTableSize = 10u; static constexpr size_t kNumHandles = kHandleTableSize + 1u; HandleTable ht(kHandleTableSize); HandleVector handles; for (size_t i = 0u; i < kNumHandles; i++) { handles.push_back(Handle(MakeRefCounted<test::MockSimpleDispatcher>(), static_cast<MojoHandleRights>(i))); ASSERT_TRUE(handles[i]) << i; } std::vector<MojoHandle> handle_values(kNumHandles, MOJO_HANDLE_INVALID); HandleVector handles_copy = handles; EXPECT_FALSE(ht.AddHandleVector(&handles_copy, handle_values.data())); handles_copy.pop_back(); handle_values.pop_back(); ASSERT_TRUE(ht.AddHandleVector(&handles_copy, handle_values.data())); for (size_t i = 0u; i < kNumHandles - 1u; i++) { ASSERT_NE(handle_values[i], MOJO_HANDLE_INVALID) << i; EXPECT_FALSE(handles_copy[i]) << i; Handle h; ASSERT_EQ(MOJO_RESULT_OK, ht.GetAndRemoveHandle(handle_values[i], &h)) << i; ASSERT_EQ(handles[i], h) << i; } for (size_t i = 0u; i < kNumHandles; i++) EXPECT_EQ(MOJO_RESULT_OK, handles[i].dispatcher->Close()) << i; } // TODO(vtl): Figure out how to test |MarkBusyAndStartTransport()|. } // namespace } // namespace system } // namespace mojo
31.043137
80
0.708818
[ "object", "vector" ]
19f732136a25d894d833bccea0c18179c07841d0
14,125
hpp
C++
examples/common_glut/bicali/bicali.hpp
lucasb-eyer/bouge
0ac49789101a6c42c1ef404cc324d1f5ec05d1d8
[ "Zlib" ]
3
2015-10-10T21:27:00.000Z
2016-05-29T05:48:23.000Z
examples/common_glut/bicali/bicali.hpp
lucasb-eyer/bouge
0ac49789101a6c42c1ef404cc324d1f5ec05d1d8
[ "Zlib" ]
null
null
null
examples/common_glut/bicali/bicali.hpp
lucasb-eyer/bouge
0ac49789101a6c42c1ef404cc324d1f5ec05d1d8
[ "Zlib" ]
1
2019-03-18T05:23:45.000Z
2019-03-18T05:23:45.000Z
//////////////////////////////////////////////////////////// // // BiCali - OpenGL 3 bitmap font system // Copyright (C) 2011 Lucas Beyer (pompei2@gmail.com) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef D_BICALI_HPP #define D_BICALI_HPP // TODO: documentation, tutorial // TODO: multiple glyph pages // TODO: text formatting // TODO: example // TODO: benchmark // Setup/Cleanup: // // init(0, 0, 800, 600); // deinit(); // // Basic Usage: // // Font* pFont = load("Arial.png", "Arial.fnt"); // pFont->drawUtf8("Hello,\nWorld!", 10, 10); // unload(pFont); // // // Optimized usage: // // BufferedText* pText = pFont->bufferUtf8("Hello,\nWorld!"); // pText->draw(10, 10); // // // More specific usage: // // Format f; // f.drawbox(10, 10, 200, 200); // f.align(right); // f.wrap(true); // pFont->drawUtf8("Hello,\nWorld!", f); // // Oneliner: // // pFont->drawUtf8("Hello,\nWorld!", Format(10, 10, 200, 200).align(right).wrap(true)); // // // Multiple viewports: // // FontManager *pMgr1 = FontManager::create(); // pMgr1->viewport(0, 0, 400, 600); // Font* pFont = pMgr1->load("Arial.png", "Arial.fnt"); // pFont->...; // pMgr1->unload(pFont); // FontManager::destroy(pMgr1); #ifdef D_BICALI_NO_PNG # define D_BICALI_EMBED_PICOPNG 0 #else # define D_BICALI_EMBED_PICOPNG 1 #endif #ifdef D_BICALI_NO_DEFAULTFONTS # define D_BICALI_DEFAULTFONTS 0 #else # define D_BICALI_DEFAULTFONTS 1 #endif #include <string> #include <vector> #include <map> #include <set> #include <list> namespace bicali { typedef unsigned long utf32; //////////////////////////////////////////////////////////////////////////////// // Detail stuff. Uninteresting for most, but needs to be here. // // Except the shader class, which might be of more interest. Maybe take out? // //////////////////////////////////////////////////////////////////////////////// void* getEntryPoint(const char* name); namespace detail { class TextVBO { public: TextVBO(const std::vector<float>& data, unsigned int type, unsigned int vert_coords_per_vert, unsigned int tex_coords_per_vert, unsigned int aVertex, unsigned int aTexCo); ~TextVBO(); void upload(const std::vector<float>& data); void render() const; private: unsigned int m_vaoid; unsigned int m_vboid; unsigned int m_type; unsigned int m_floats_per_vert; int m_nVerts; }; class Shader { public: Shader(const char* sVertCode, const char* sFragCode, const char* sGeomCode = 0); ~Shader(); void use() const; unsigned int id() const { return m_progId; }; bool hasAttrib(const char* name) const; bool hasAttrib(const std::string& name) const; unsigned int attrib(const char* name) const; unsigned int attrib(const std::string& name) const; bool hasUniform(const char* name) const; bool hasUniform(const std::string& name) const; unsigned int uniform(const char* name) const; unsigned int uniform(const std::string& name) const; bool uniformMatrix3fv(const std::string& name, unsigned int count, bool transpose, const float *value); bool uniformMatrix4fv(const std::string& name, unsigned int count, bool transpose, const float *value); bool uniformf(const std::string& name, float value); bool uniform1fv(const std::string& name, unsigned int count, const float *value); bool uniform2fv(const std::string& name, unsigned int count, const float *value); bool uniform3fv(const std::string& name, unsigned int count, const float *value); bool uniform4fv(const std::string& name, unsigned int count, const float *value); bool uniformi(const std::string& name, int value); bool uniform1iv(const std::string& name, unsigned int count, const int *value); bool uniform2iv(const std::string& name, unsigned int count, const int *value); bool uniform3iv(const std::string& name, unsigned int count, const int *value); bool uniform4iv(const std::string& name, unsigned int count, const int *value); static unsigned int load(const char* sVertCode, const char* sFragCode, const char* sGeomCode = 0, std::map<std::string, unsigned int>* out_attribs = 0, std::map<std::string, unsigned int>* out_uniforms = 0); private: unsigned int m_progId; std::map<std::string, unsigned int> m_Attribs; std::map<std::string, unsigned int> m_Uniforms; }; class Matrix4f { public: Matrix4f(); Matrix4f(const float* entries16f); ~Matrix4f(); static Matrix4f viewproj(int w, int h); static Matrix4f transscale(float tx, float ty, float tz, float sx = 1.0f, float sy = 1.0f, float sz = 1.0f); inline operator const float*() const {return m;}; Matrix4f operator*(const Matrix4f& other) const; private: float m[16]; }; } // namespace bicali::detail //////////////////////////////////////////////////////////////////////////////// // Glyph class. Describes one glyph, where it is and how it behaves. // //////////////////////////////////////////////////////////////////////////////// struct Glyph { unsigned int x, y, w, h; int xoffs, yoffs; int xadv, yadv; utf32 codepoint; Glyph(); ~Glyph(); }; /// \TODO Optimize by using, for example, a vector of maps, indexed by simple hash values. typedef std::map<utf32, Glyph> GlyphHashMap; // class GlyphHashMap { // public: // Glyph& operator[](utf32 codepoint); // private: // std::vector< std::list<Glyph> > map; // }; //////////////////////////////////////////////////////////////////////////////// // Format class. For describing the formatting of the text. // //////////////////////////////////////////////////////////////////////////////// enum Align { left, right, center, }; class Format { public: Format(int w = 0, int h = 0); Format& align(Align align); Format& wrap(bool wrap = true); protected: int m_w, m_h; Align m_align; bool m_bWrap; }; //////////////////////////////////////////////////////////////////////////////// // Static text class. Everything is fixed, set in stone. Forever. Ever. // //////////////////////////////////////////////////////////////////////////////// class StaticText { public: StaticText& draw(); protected: StaticText(const char* str, int x, int y, const class BitmapFont* pFont, Format fmt, const float* tint4f = 0); ~StaticText(); friend class BitmapFont; const class BitmapFont* m_pFont; detail::TextVBO m_vbo; float m_tint[4]; }; //////////////////////////////////////////////////////////////////////////////// // Buffered text class. Fixed text string and mode, but free pos and tint. // //////////////////////////////////////////////////////////////////////////////// class BufferedText { public: BufferedText& draw(int x, int y, const float *in_vTint4f = 0); protected: BufferedText(const char* str, Format fmt, const class BitmapFont* pFont); ~BufferedText(); friend class BitmapFont; const class BitmapFont* m_pFont; detail::TextVBO m_vbo; }; //////////////////////////////////////////////////////////////////////////////// // Dynamic text class. Text potentially changing every frame. // //////////////////////////////////////////////////////////////////////////////// class DynamicText { public: DynamicText& draw(const char* text, int x, int y, Format fmt = Format(), const float* in_vTint4f = 0); protected: DynamicText(const class BitmapFont* pFont); ~DynamicText(); friend class BitmapFont; const class BitmapFont* m_pFont; detail::TextVBO m_vbo; }; //////////////////////////////////////////////////////////////////////////////// // Bitmap class. This is a small present for you, to draw a simple 2D bitmap // // on the screen without further ado. // //////////////////////////////////////////////////////////////////////////////// class Bitmap { public: const Bitmap& draw(int x, int y, const float* in_vTint4f = 0) const; const detail::Matrix4f& viewproj() const; int selectTexture(unsigned int slot = 0) const; int deselectTexture(unsigned int slot = 0) const; protected: Bitmap(const void* in_pixels, unsigned int w, unsigned int h, float z, const detail::Matrix4f& viewproj); ~Bitmap(); friend class BitmapFontManager; private: unsigned int m_TexId; unsigned int m_w, m_h; const detail::Matrix4f& m_viewproj; detail::TextVBO m_myTexVBO; }; //////////////////////////////////////////////////////////////////////////////// // BitmapFont class. Represents one bitmap font and its corresponding graphic // // resources, as well as all glyphs in it. // // Use to create [Static|Buffered|Dynamic]Text objects to draw text. // //////////////////////////////////////////////////////////////////////////////// class BitmapFont : public Bitmap { public: void glyph(utf32 codepoint, Glyph glyph); Glyph glyph(utf32 codepoint) const; Glyph& glyph(utf32 codepoint); bool hasGlyph(utf32 codepoint) const; unsigned int glyphCount() const; BitmapFont& drawUtf8(const char* str, int x, int y, Format fmt = Format(), const float* in_vTint4f = 0); StaticText* bufferUtf8(const char* str, int x = 0, int y = 0, Format fmt = Format(), const float* tint4f = 0); BufferedText* bufferUtf8(const char* str, const Format& fmt); std::pair<int, int> sizeUtf8(const char* str, Format fmt = Format()); BitmapFont& free(BufferedText* bt); BitmapFont& free(StaticText* st); unsigned int m_lineH; unsigned int m_base; protected: BitmapFont(const void* in_pixels, unsigned int w, unsigned int h, const detail::Matrix4f& viewproj); ~BitmapFont(); friend class BitmapFontManager; private: GlyphHashMap m_glyphs; /// Used only for automatic cleanup. std::set<StaticText*> m_staticTexts; /// Used only for automatic cleanup. std::set<BufferedText*> m_bufferedTexts; /// Each font has one dynamic text object, for use with their unbuffered draw methods. DynamicText m_dynText; }; //////////////////////////////////////////////////////////////////////////////// // BitmapFont manager class. One per viewport is enough. Holds per-vp data. // //////////////////////////////////////////////////////////////////////////////// class BitmapFontManager { public: static BitmapFontManager* create(); static void destroy(BitmapFontManager* mgr); BitmapFontManager& viewport(/*int x, int y, */int w, int h); #if D_BICALI_EMBED_PICOPNG /// \throws std::runtime_error If anything failed. (init GL, load texture, ...) BitmapFont* load(const char* imgFilename, const char*descFilename); /// \throws std::runtime_error If anything failed. (init GL, load texture, ...) Bitmap* loadImage(const char* imgFilename); #endif #if D_BICALI_DEFAULTFONTS BitmapFont* default_small(); #endif BitmapFont* make(const std::vector<unsigned char>& in_pixels, unsigned int w, unsigned int h, const char* desc); BitmapFont* make(const void* in_pixels, unsigned int w, unsigned int h, const char* desc); Bitmap* makeImage(const std::vector<unsigned char>& in_pixels, unsigned int w, unsigned int h, float z = 0.5f); Bitmap* makeImage(const void* in_pixels, unsigned int w, unsigned int h, float z = 0.5f); BitmapFontManager& unload(BitmapFont* pFont); BitmapFontManager& unload(Bitmap* pImage); protected: BitmapFontManager(); ~BitmapFontManager(); friend void init(/*int x, int y,*/ int w, int h); friend void deinit(); std::set<BitmapFont*> m_fonts; std::set<Bitmap*> m_images; detail::Matrix4f m_viewproj; #if D_BICALI_DEFAULTFONTS BitmapFont m_defaultSmall; #endif #if D_BICALI_EMBED_PICOPNG void loadCommon(const char* imgFilename, std::vector<unsigned char>& imgData, unsigned long& w, unsigned long& h); #endif }; //////////////////////////////////////////////////////////////////////////////// // Global functions easing the basic use. Actually just hiding a default // // manager behind the scenes, as only one is needed in most cases anyway. // //////////////////////////////////////////////////////////////////////////////// void init(/*int x = 0, int y = 0,*/ int w = 0, int h = 0); void deinit(); void viewport(/*int x, int y, */int w, int h); #if D_BICALI_EMBED_PICOPNG /// \throws std::runtime_error If anything failed. (init GL, load texture, ...) BitmapFont* load_font(const char* imgFilename, const char* descFilename); /// \throws std::runtime_error If anything failed. (init GL, load texture, ...) Bitmap* load_image(const char* imgFilename); #endif #if D_BICALI_DEFAULTFONTS BitmapFont* default_small_font(); #endif BitmapFont* make_font(const std::vector<unsigned char>& in_pixels, unsigned int w, unsigned int h, const char* desc); BitmapFont* make_font(const void* in_pixels, unsigned int w, unsigned int h, const char* desc); Bitmap* make_image(const std::vector<unsigned char>& in_pixels, unsigned int w, unsigned int h); Bitmap* make_image(const void* in_pixels, unsigned int w, unsigned int h); void unload_font(BitmapFont* pFont); void unload_image(Bitmap* pImage); } // namespace bicali #endif // D_BICALI_HPP
34.620098
211
0.606442
[ "render", "object", "vector" ]
19f9a5772488a31572b237309142b792246c2674
703
cpp
C++
src/Or.cpp
amelk002/test11
adb6be15f75f05b50b6a7c3359bdfcbb1d2e1f18
[ "BSD-3-Clause" ]
null
null
null
src/Or.cpp
amelk002/test11
adb6be15f75f05b50b6a7c3359bdfcbb1d2e1f18
[ "BSD-3-Clause" ]
null
null
null
src/Or.cpp
amelk002/test11
adb6be15f75f05b50b6a7c3359bdfcbb1d2e1f18
[ "BSD-3-Clause" ]
null
null
null
#ifndef __OR_CPP__ #define __OR_CPP__ #include <iostream> #include <iostream> #include <string> #include <cstdlib> #include <fstream> #include <vector> #include <cmath> #include <sstream> #include <stdio.h> #include <unistd.h> using namespace std; #include "Base.h" #include "Connector.h" #include "Cmd.h" Or::Or() { lhs = 0; rhs = 0; } Or::Or(Base* lhs, Base* rhs) { this->lhs = lhs; this->rhs = rhs; } Or::Or(Base* lhs, Cmd* rhs) { this->lhs = lhs; this->rhs = rhs; } int Or::Executor() { int currStatus = 0; currStatus = lhs->Executor(); if(currStatus != 0) { currStatus = rhs->Executor(); return currStatus; } return currStatus; }
14.957447
37
0.607397
[ "vector" ]
c20e6714e85dad64eaddc92ad78cd468078dce81
744
cpp
C++
spoj/STAMPS.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
5
2020-06-30T12:44:25.000Z
2021-07-14T06:35:57.000Z
spoj/STAMPS.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
spoj/STAMPS.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; void f(){ ll m, n; cin>>m>>n; vector<ll> a(n); for(ll i=0;i<n;i++){ cin>>a[i]; } sort(a.begin(), a.end(), greater<ll>()); ll sum=0; for(ll i=0;i<n;i++){ sum+=a[i]; if(sum>=m){ cout<<i+1<<endl; return; } } cout<<"impossible"<<endl; return; } int main(){ ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int test_cases=1; cin>>test_cases; for(ll j=0;j<test_cases;j++){ cout<<"Scenario #"<<j+1<<":"<<endl; f(); cout<<endl; } return 0; }
18.146341
44
0.467742
[ "vector" ]
c2189494ede932682a3f4844fc967fec7016d73d
3,311
hpp
C++
join/crypto/include/join/base64.hpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
1
2021-09-14T13:53:07.000Z
2021-09-14T13:53:07.000Z
join/crypto/include/join/base64.hpp
joinframework/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
15
2021-08-09T23:55:02.000Z
2021-11-22T11:05:41.000Z
join/crypto/include/join/base64.hpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2021 Mathieu Rabine * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __JOIN_BASE64_HPP__ #define __JOIN_BASE64_HPP__ // libjoin. #include <join/openssl.hpp> // C++. #include <string> namespace join { /// bytes array. using BytesArray = std::vector <uint8_t>; /** * @brief class used to manage base64 encoding and decoding. */ class Base64 { public: /** * @brief create the Base64 instance. */ Base64 () = delete; /** * @brief destroy the Base64 instance. */ ~Base64 () = delete; public: /** * @brief encode data in base 64. * @param message the message to encode. * @return the string encoded. */ static std::string encode (const std::string& message); /** * @brief encode data in base 64. * @param data the data to encode. * @return the string encoded. */ static std::string encode (const BytesArray& data); /** * @brief encode data in base 64. * @param data the data buffer to encode. * @param size the data buffer size to encode. * @return the string encoded. */ static std::string encode (const uint8_t* data, size_t size); /** * @brief decode a base64 encoded string. * @param data string to decode. * @return the string decoded. */ static BytesArray decode (const std::string& data); private: /// encode table. static const std::string _base64Table; /// filling character. static const char _fillChar = '='; /// bytes mask. static const uint32_t _mask1 = 0xFC000000; /// bytes mask. static const uint32_t _mask2 = 0x03F00000; /// bytes mask. static const uint32_t _mask3 = 0x000FC000; /// bytes mask. static const uint32_t _mask4 = 0x00003F00; /// union. typedef union { uint32_t l; /**< access the variable as an unsigned integer. */ char c[4]; /**< access the variable bytes per bytes. */ }un32; }; } #endif
29.04386
83
0.61341
[ "vector" ]
c2196237ac6b155d6ea7fd47de2a2acf7c44de33
461
hpp
C++
src/core/lifetime_tracker.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
1
2021-04-17T21:42:12.000Z
2021-04-17T21:42:12.000Z
src/core/lifetime_tracker.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
null
null
null
src/core/lifetime_tracker.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
1
2021-04-27T06:06:58.000Z
2021-04-27T06:06:58.000Z
#pragma once #include "berkeley_gfx.hpp" #include <vulkan/vulkan.hpp> namespace BG { class Tracker { private: int m_numFramesInFlight = 3; int m_currentFrame = 0; struct FrameObjects { std::vector<vk::UniqueFramebuffer> framebuffers; void ClearAll(); }; std::vector<FrameObjects> m_frames; public: void DisposeFramebuffer(vk::UniqueFramebuffer fb); void NewFrame(); Tracker(int maxFrames); }; }
14.870968
54
0.659436
[ "vector" ]
c21c580460c7c44ef815f726aef3fdd7c9630b11
34,889
cpp
C++
src/if/os_interface.cpp
open-switch/opx-nas-linux
073b287c7c998b0dc16bc732fa37bbdddfd69d66
[ "CC-BY-4.0" ]
1
2017-12-28T16:57:02.000Z
2017-12-28T16:57:02.000Z
src/if/os_interface.cpp
open-switch/opx-nas-linux
073b287c7c998b0dc16bc732fa37bbdddfd69d66
[ "CC-BY-4.0" ]
10
2017-08-07T22:43:34.000Z
2021-06-09T13:34:01.000Z
src/if/os_interface.cpp
open-switch/opx-nas-linux
073b287c7c998b0dc16bc732fa37bbdddfd69d66
[ "CC-BY-4.0" ]
14
2017-01-05T19:18:42.000Z
2020-03-06T10:01:04.000Z
/* * Copyright (c) 2019 Dell Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS * FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ /*! * \file os_interface.cpp */ #include "private/nas_os_if_priv.h" #include "private/os_if_utils.h" #include "private/os_interface_cache_utils.h" #include "private/nas_os_if_conversion_utils.h" #include "private/nas_os_l3_utils.h" #include "netlink_tools.h" #include "nas_nlmsg.h" #include "nas_nlmsg_object_utils.h" #include "nas_os_int_utils.h" #include "nas_os_interface.h" #include "vrf-mgmt.h" #include "std_utils.h" #include "cps_api_operation.h" #include "cps_api_object_key.h" #include "cps_class_map.h" #include "std_time_tools.h" #include "std_assert.h" #include "std_mac_utils.h" #include "event_log.h" #include "dell-interface.h" #include "dell-base-if.h" #include "dell-base-if-linux.h" #include "dell-base-if-vlan.h" #include "dell-base-common.h" #include "ds_api_linux_interface.h" #include "iana-if-type.h" #include "ietf-interfaces.h" #include "ietf-ip.h" #include "ietf-network-instance.h" #include <sys/socket.h> #include <linux/if_link.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/if.h> #include <pthread.h> #include <sys/socket.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <map> #include <unordered_map> #define NAS_OS_IF_OBJ_ID_RES_START 4 #define NAS_OS_IF_FLAGS_ID (NAS_OS_IF_OBJ_ID_RES_START) //reserve 4 inside the object for flags #define NAS_OS_IF_ALIAS (NAS_OS_IF_OBJ_ID_RES_START+1) #define NAS_LINK_MTU_HDR_SIZE 32 #define NL_MSG_INTF_BUFF_LEN 2048 /* * API to mask *any* interface publish event. * e.g admin-state in case of LAG member port add */ extern "C" bool os_interface_mask_event(hal_ifindex_t ifix, if_change_t mask_val) { INTERFACE *fill = os_get_if_db_hdlr(); if(fill) { return fill->if_info_setmask(ifix, mask_val); } return true; } static bool is_reserved_interface (if_details &details) { if ((strncmp(details.if_name.c_str(), "eth", strlen("eth")) == 0) || (strncmp(details.if_name.c_str(), "mgmt", strlen("mgmt")) == 0) || (strncmp(details.if_name.c_str(), "veth-", strlen("veth-")) == 0) || (strncmp(details.if_name.c_str(), "vdef-", strlen("vdef-")) == 0)) { return true; } return false; } std::string nas_os_if_name_get(hal_ifindex_t ifix) { INTERFACE *fill = os_get_if_db_hdlr(); if (!fill) return nullptr; EV_LOGGING(NAS_OS, INFO, "NAS-OS-CACHE", "get name for ifindex %d", ifix); return (fill->if_info_get_name(ifix)); } t_std_error os_intf_type_get(hal_ifindex_t ifix, BASE_CMN_INTERFACE_TYPE_t *if_type) { INTERFACE *fill = os_get_if_db_hdlr(); if (!fill) return STD_ERR(INTERFACE,FAIL,0); EV_LOGGING(NAS_OS, INFO, "NAS-OS-CACHE", "get type for ifindex %d", ifix); BASE_CMN_INTERFACE_TYPE_t _type; _type = fill->if_info_get_type(ifix); if ( _type != BASE_CMN_INTERFACE_TYPE_NULL) { EV_LOGGING(NAS_OS, INFO, "NAS-OS-CACHE", "get type %d for ifindex %d", _type, ifix ); *if_type = _type; return STD_ERR_OK; } return STD_ERR(INTERFACE,FAIL,0); } t_std_error os_intf_master_get(hal_ifindex_t ifix, hal_ifindex_t *master_idx) { if (master_idx == NULL) return STD_ERR(INTERFACE,FAIL,0); INTERFACE *fill = os_get_if_db_hdlr(); if (!fill) return STD_ERR(INTERFACE,FAIL,0); *master_idx = fill->if_info_get_master(ifix); EV_LOGGING(NAS_OS, INFO, "NAS-OS-CACHE", "Master is %d for ifindex %d", *master_idx, ifix ); return STD_ERR_OK; } static auto info_kind_to_intf_type = new std::unordered_map<std::string,BASE_CMN_INTERFACE_TYPE_t> { {"tun", BASE_CMN_INTERFACE_TYPE_L3_PORT}, {"bond", BASE_CMN_INTERFACE_TYPE_LAG}, {"bridge", BASE_CMN_INTERFACE_TYPE_BRIDGE}, {"vlan", BASE_CMN_INTERFACE_TYPE_VLAN_SUBINTF}, {"macvlan", BASE_CMN_INTERFACE_TYPE_MACVLAN}, {"vxlan", BASE_CMN_INTERFACE_TYPE_VXLAN}, {"dummy", BASE_CMN_INTERFACE_TYPE_LOOPBACK}, }; static t_std_error nas_os_info_kind_to_intf_type(const char *info_kind, BASE_CMN_INTERFACE_TYPE_t *if_type) { auto it = info_kind_to_intf_type->find(std::string(info_kind)); if(it != info_kind_to_intf_type->end()){ *if_type = it->second; return STD_ERR_OK; } return STD_ERR(INTERFACE,FAIL,0); } static bool get_if_detail_from_netlink (int sock, int rt_msg_type, struct nlmsghdr *hdr, void *data, uint32_t vrf_id) { if (rt_msg_type > RTM_SETLINK) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "Wrong netlink msg msgType %d", rt_msg_type); return false; } if_details *details = (if_details *)data; struct ifinfomsg *ifmsg = (struct ifinfomsg *)NLMSG_DATA(hdr); if(hdr->nlmsg_len < NLMSG_LENGTH(sizeof(*ifmsg))) return false; details->_ifindex = ifmsg->ifi_index; details->_op = cps_api_oper_NULL; details->_family = ifmsg->ifi_family; details->_flags = ifmsg->ifi_flags; details->_type = BASE_CMN_INTERFACE_TYPE_L3_PORT; EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "## msgType %d, ifindex %d change %x\n", rt_msg_type, ifmsg->ifi_index, ifmsg->ifi_change); int nla_len = nlmsg_attrlen(hdr,sizeof(*ifmsg)); struct nlattr *head = nlmsg_attrdata(hdr, sizeof(struct ifinfomsg)); memset(details->_attrs,0,sizeof(details->_attrs)); if (nla_parse(details->_attrs,__IFLA_MAX,head,nla_len)!=0) { EV_LOGGING(NAS_OS, ERR,"NL-PARSE","Failed to parse attributes"); return false; } return true; } bool nas_os_if_index_get(std::string &if_name , hal_ifindex_t &index) { INTERFACE *fill = os_get_if_db_hdlr(); if (!fill) return false; if_info_t ifinfo; if(!fill->get_ifindex_from_name(if_name, index)) { /* if not present then check in the kernel */ index = cps_api_interface_name_to_if_index(if_name.c_str()); } return true; } bool check_bridge_membership_in_os(hal_ifindex_t bridge_idx, hal_ifindex_t mem_idx) { int if_sock = 0; if((if_sock = nas_nl_sock_create(NL_DEFAULT_VRF_NAME, nas_nl_sock_T_INT,false)) < 0) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "Socket create failure"); return false; } const int BUFF_LEN=4196; char buff[BUFF_LEN]; if_details details; memset(buff,0,sizeof(buff)); memset(static_cast<void *>(&details),0,sizeof(details)); struct ifinfomsg ifmsg; memset(&ifmsg,0,sizeof(ifmsg)); nas_os_pack_if_hdr(&ifmsg, AF_NETLINK, 0, mem_idx ); int seq = (int)std_get_uptime(NULL); if (nl_send_request(if_sock, RTM_GETLINK, (NLM_F_REQUEST | NLM_F_ACK ), seq,&ifmsg, sizeof(ifmsg))) { netlink_tools_process_socket(if_sock,get_if_detail_from_netlink, &details,buff,sizeof(buff),&seq,NULL, NL_DEFAULT_VRF_ID); } if (details._ifindex != mem_idx) { // returned msg is not for the same member EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "member index %d and received index %d mismatch", mem_idx, details._ifindex); close(if_sock); return false; } if(details._attrs[IFLA_MASTER]!=NULL){ hal_ifindex_t master_idx = *(int *)nla_data(details._attrs[IFLA_MASTER]); EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "member name %d and received bridge index %d", details._ifindex, master_idx); if (master_idx == bridge_idx) { // interface is the member of the bridge in OS close(if_sock); return true; } } EV_LOGGING(NAS_OS, INFO, "NET-MAIN", " no bridge info or wrong bridge found with the interface %d bridge idx %d ", details._ifindex, bridge_idx); close(if_sock); return false; } t_std_error os_interface_to_object (int rt_msg_type, struct nlmsghdr *hdr, cps_api_object_t obj, bool* p_pub_evt, uint32_t vrf_id) { struct ifinfomsg *ifmsg = (struct ifinfomsg *)NLMSG_DATA(hdr); if(hdr->nlmsg_len < NLMSG_LENGTH(sizeof(*ifmsg))) { EV_LOGGING(NAS_OS, ERR, "NL-PARSE", "Invalid msg length in netlink header: %d", hdr->nlmsg_len); return STD_ERR(INTERFACE, PARAM, 0); } int track_change = OS_IF_CHANGE_NONE; if_details details; if_info_t ifinfo; details._op = cps_api_oper_NULL; details._family = ifmsg->ifi_family; static const std::unordered_map<int,cps_api_operation_types_t> _to_op_type = { { RTM_NEWLINK, cps_api_oper_CREATE }, { RTM_DELLINK, cps_api_oper_DELETE } }; EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "VRF-id:%d msgType %d, ifindex %d change 0x%x flags 0x%x\n", vrf_id, rt_msg_type, ifmsg->ifi_index, ifmsg->ifi_change, ifmsg->ifi_flags); auto it = _to_op_type.find(rt_msg_type); if (it==_to_op_type.end()) { details._op = cps_api_oper_SET; } else { details._op = it->second; } details._flags = ifmsg->ifi_flags; details._type = BASE_CMN_INTERFACE_TYPE_L3_PORT; details._ifindex = ifmsg->ifi_index; details.master_idx = 0; details.parent_idx = 0; // Check if the interface already exists in the local database. // If present then mark it as SET operation otherwise CREATE operation. if ((vrf_id == NAS_DEFAULT_VRF_ID) && (details._op == cps_api_oper_CREATE)) { bool present = false; if (nas_os_check_intf_exists(details._ifindex, &present) != STD_ERR_OK) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", " Failed to get cached info"); return false; } if (present) { details._op = cps_api_oper_SET; } } cps_api_operation_types_t _if_op = details._op; cps_api_object_attr_add_u32(obj,BASE_IF_LINUX_IF_INTERFACES_INTERFACE_IF_FLAGS, details._flags); cps_api_object_attr_add_u32(obj, DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_IF_INDEX,ifmsg->ifi_index); cps_api_object_attr_add_u32(obj,IF_INTERFACES_INTERFACE_ENABLED, (ifmsg->ifi_flags & IFF_UP) ? true :false); ifinfo.parent_idx = 0; ifinfo.ev_mask = OS_IF_CHANGE_NONE; ifinfo.admin = (ifmsg->ifi_flags & IFF_UP) ? true :false; ifinfo.oper = (ifmsg->ifi_flags & IFF_RUNNING) ? true :false; int nla_len = nlmsg_attrlen(hdr,sizeof(*ifmsg)); struct nlattr *head = nlmsg_attrdata(hdr, sizeof(struct ifinfomsg)); memset(details._attrs,0,sizeof(details._attrs)); memset(details._linkinfo,0,sizeof(details._linkinfo)); details._info_kind = nullptr; if (nla_parse(details._attrs,__IFLA_MAX,head,nla_len)!=0) { EV_LOGGING(NAS_OS,ERR,"NL-PARSE","Failed to parse attributes"); return STD_ERR(INTERFACE, FAIL, 0); } if (details._attrs[IFLA_LINKINFO]) { nla_parse_nested(details._linkinfo,IFLA_INFO_MAX,details._attrs[IFLA_LINKINFO]); } if (details._attrs[IFLA_LINKINFO] != nullptr && details._linkinfo[IFLA_INFO_KIND]!=nullptr) { details._info_kind = (const char *)nla_data(details._linkinfo[IFLA_INFO_KIND]); ifinfo.os_link_type.assign(details._info_kind,strlen(details._info_kind)); EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Intf type %s ifindex %d", ifinfo.os_link_type.c_str(), ifmsg->ifi_index); } if (details._attrs[IFLA_ADDRESS]!=NULL) { char buff[40]; const char *_p = std_mac_to_string((const hal_mac_addr_t *)(nla_data(details._attrs[IFLA_ADDRESS])), buff, sizeof(buff)); cps_api_object_attr_add(obj,DELL_IF_IF_INTERFACES_INTERFACE_PHYS_ADDRESS,_p,strlen(_p)+1); memcpy(ifinfo.phy_addr, (nla_data(details._attrs[IFLA_ADDRESS])), sizeof(hal_mac_addr_t)); } if (details._attrs[IFLA_IFNAME]!=NULL) { rta_add_name(details._attrs[IFLA_IFNAME],obj,IF_INTERFACES_INTERFACE_NAME); details.if_name = static_cast <char *> (nla_data(details._attrs[IFLA_IFNAME])); } if(details._attrs[IFLA_MTU]!=NULL) { int *mtu = (int *) nla_data(details._attrs[IFLA_MTU]); cps_api_object_attr_add_u32(obj, DELL_IF_IF_INTERFACES_INTERFACE_MTU,(*mtu + NAS_LINK_MTU_HDR_SIZE)); ifinfo.mtu = *mtu; } if (details._attrs[IFLA_LINK] != NULL) { EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Rcvd Link index index %d", *(int *)nla_data(details._attrs[IFLA_LINK])); } if(details._attrs[IFLA_MASTER]!=NULL) { /* This gives us the bridge index, which should be sent to * NAS for correlation */ EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Rcvd master index %d", *(int *)nla_data(details._attrs[IFLA_MASTER])); ifinfo.master_idx = *(int *)nla_data(details._attrs[IFLA_MASTER]); cps_api_object_attr_add_u32(obj,BASE_IF_LINUX_IF_INTERFACES_INTERFACE_IF_MASTER, *(int *)nla_data(details._attrs[IFLA_MASTER])); } if (details._info_kind != nullptr) { if ( nas_os_info_kind_to_intf_type(details._info_kind, &details._type) != STD_ERR_OK) { EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "info kind not known %s",details._info_kind); } } else { // In case if info_kind not present in the netlink event then look into // the local cache. EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "info kind not present in netlink %d",details._ifindex); if (os_intf_type_get(details._ifindex, &details._type) != STD_ERR_OK) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "unknown interface %d", details._ifindex); } } INTERFACE *fill = os_get_if_db_hdlr(); if_change_t mask = OS_IF_CHANGE_NONE; if(fill && !(fill->if_hdlr(&details, obj))) { EV_LOGGING(NAS_OS, INFO, "NL-PARSE", "Failure on sub-interface handling"); return STD_ERR(INTERFACE, FAIL, 0); // Return in case of sub-interfaces etc (Handler will return false) } ifinfo.if_type = details._type; ifinfo.if_name = details.if_name; ifinfo.parent_idx = details.parent_idx; bool evt_publish = true; /* Dont update the intf cache for non-default VRF since if-index can be same in multiple VRFs */ if (vrf_id == NAS_DEFAULT_VRF_ID) { if (!fill) { track_change = OS_IF_CHANGE_ALL; } else { track_change = fill->if_info_update(ifmsg->ifi_index, ifinfo); } /* * Delete the interface from cache if interface type is not vlan or lag * If lag, check for lag member delete vs actual bond interface delete. */ EV_LOGGING(NAS_OS,INFO,"NET-MAIN","ifidx %d, if-type %d track %d", ifmsg->ifi_index,details._type, track_change); if(_if_op == cps_api_oper_DELETE) { if((details._type != BASE_CMN_INTERFACE_TYPE_L2_PORT)&& (details._type != BASE_CMN_INTERFACE_TYPE_LAG)&& (details._type != BASE_CMN_INTERFACE_TYPE_MACVLAN)) { if(fill) fill->if_info_delete(ifmsg->ifi_index, details.if_name); } else if(details._type == BASE_CMN_INTERFACE_TYPE_LAG && (!strncmp(details._info_kind, "bond", 4))) { if(fill) fill->if_info_delete(ifmsg->ifi_index, details.if_name); } if(details._type == BASE_CMN_INTERFACE_TYPE_L2_PORT) { ifinfo.master_idx = 0; // in case of L2 PORT member delete. fill->if_info_update(ifmsg->ifi_index, ifinfo); } } if ((details._type == BASE_CMN_INTERFACE_TYPE_L2_PORT) || ((details._type == BASE_CMN_INTERFACE_TYPE_LAG) && (details._attrs[IFLA_MASTER] != NULL))) { /* * If member addition/deletion in the LAG or bridge */ int ifix = *(int *)nla_data(details._attrs[IFLA_MASTER]); std::string if_name = nas_os_if_name_get(ifix); if (if_name.empty()) { EV_LOGGING(NAS_OS,ERR,"NET-MAIN"," Interface not present, index %d ", ifix); return STD_ERR(INTERFACE, FAIL, 0); } EV_LOGGING(NAS_OS,INFO,"NET-MAIN"," ifidx %d Remove attrs in case of member add/del to master %s", ifmsg->ifi_index, if_name.c_str()); if (details._type == BASE_CMN_INTERFACE_TYPE_L2_PORT) { // Delete the previously filled attributes in case of Vlan/Lag member add/del cps_api_object_attr_delete(obj, DELL_IF_IF_INTERFACES_INTERFACE_MTU); cps_api_object_attr_delete(obj, DELL_IF_IF_INTERFACES_INTERFACE_PHYS_ADDRESS); cps_api_object_attr_delete(obj, IF_INTERFACES_INTERFACE_NAME); cps_api_object_attr_delete(obj, IF_INTERFACES_INTERFACE_ENABLED); cps_api_object_attr_delete(obj, DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_IF_INDEX); cps_api_object_attr_add(obj, IF_INTERFACES_INTERFACE_NAME, if_name.c_str(), (strlen(if_name.c_str())+1)); cps_api_object_attr_add_u32(obj, DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_IF_INDEX,ifix); cps_api_object_attr_add_u32(obj, BASE_IF_LINUX_IF_INTERFACES_INTERFACE_MBR_IFINDEX, ifmsg->ifi_index); } } else if (!track_change) { /* * If track change is false, check for interface type - Return false ONLY in the individual update case * If the handler has identified it as VLAN or Bond member addition, then continue with publishing */ if (details._op != cps_api_oper_DELETE && details._type != BASE_CMN_INTERFACE_TYPE_L2_PORT) { /* * Avoid filtering netlink events for reserved interface (eth0/mgmtxxx-xx). * check if its not a reserved interface return false otherwise contiue publishing * the CPS interface object. */ if (!is_reserved_interface(details)) { evt_publish = false; } } // If mask is set to disable admin state publish event, remove the attribute } else if(fill && (mask = fill->if_info_getmask(ifmsg->ifi_index))) { EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Masking set for %d, mask %d, track_chg %d", ifmsg->ifi_index, mask, track_change); if(track_change != OS_IF_ADM_CHANGE && mask == OS_IF_ADM_CHANGE) cps_api_object_attr_delete(obj, IF_INTERFACES_INTERFACE_ENABLED); else if (mask == OS_IF_ADM_CHANGE) evt_publish = false; } } if (p_pub_evt != NULL) { *p_pub_evt = evt_publish; } const char *vrf_name = nas_os_get_vrf_name(vrf_id); if (vrf_name == NULL) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "VRF id:%d to name mapping not present, index %d type %d!", vrf_id, details._ifindex, details._type); return STD_ERR(INTERFACE, PARAM, 0); } cps_api_object_attr_add(obj, NI_IF_INTERFACES_INTERFACE_BIND_NI_NAME, vrf_name, strlen(vrf_name)+1); cps_api_object_attr_add_u32(obj, VRF_MGMT_NI_IF_INTERFACES_INTERFACE_VRF_ID, vrf_id); EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "VRF:%s(%d) Publishing index %d type %d", vrf_name, vrf_id, details._ifindex, details._type); cps_api_key_from_attr_with_qual(cps_api_object_key(obj),BASE_IF_LINUX_IF_INTERFACES_INTERFACE_OBJ, cps_api_qualifier_OBSERVED); cps_api_object_set_type_operation(cps_api_object_key(obj),details._op); cps_api_object_attr_add_u32(obj, BASE_IF_LINUX_IF_INTERFACES_INTERFACE_DELL_TYPE, details._type); EV_LOGGING(NAS_OS, INFO, "NET-MAIN"," NAS OS interface event type \n %s", (track_change ==OS_IF_CHANGE_ALL) ? "Change all" : "Interface Update"); EV_LOGGING(NAS_OS, INFO, "NET-MAIN"," NAS OS interface event publish\n %s", cps_api_object_to_c_string(obj).c_str()); return STD_ERR_OK; } static bool get_netlink_data(int sock, int rt_msg_type, struct nlmsghdr *hdr, void *data, uint32_t vrf_id) { if (rt_msg_type <= RTM_SETLINK) { cps_api_object_list_t * list = (cps_api_object_list_t*)data; cps_api_object_guard og(cps_api_object_create()); if (!og.valid()) return false; if (os_interface_to_object(rt_msg_type,hdr,og.get(), NULL, vrf_id) == STD_ERR_OK) { if (cps_api_object_list_append(*list,og.get())) { og.release(); return true; } } return false; } return true; } static bool os_interface_info_to_object(hal_ifindex_t ifix, if_info_t& ifinfo, cps_api_object_t obj) { char if_name[HAL_IF_NAME_SZ+1]; if(cps_api_interface_if_index_to_name(ifix, if_name, sizeof(if_name)) == NULL) { EV_LOGGING(NAS_OS, ERR, "NAS-OS", "Failure getting interface name for %d", ifix); return false; } else cps_api_object_attr_add(obj, IF_INTERFACES_INTERFACE_NAME, if_name, (strlen(if_name)+1)); cps_api_key_from_attr_with_qual(cps_api_object_key(obj), BASE_IF_LINUX_IF_INTERFACES_INTERFACE_OBJ, cps_api_qualifier_OBSERVED); cps_api_object_attr_add_u32(obj, DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_IF_INDEX, ifix); cps_api_object_attr_add_u32(obj,IF_INTERFACES_INTERFACE_ENABLED, ifinfo.admin); char buff[HAL_INET6_TEXT_LEN]; const char *_p = std_mac_to_string((const hal_mac_addr_t *)ifinfo.phy_addr, buff, sizeof(buff)); cps_api_object_attr_add(obj,DELL_IF_IF_INTERFACES_INTERFACE_PHYS_ADDRESS,_p,strlen(_p)+1); cps_api_object_attr_add_u32(obj, DELL_IF_IF_INTERFACES_INTERFACE_MTU, (ifinfo.mtu + NAS_LINK_MTU_HDR_SIZE)); cps_api_object_attr_add_u32(obj, BASE_IF_LINUX_IF_INTERFACES_INTERFACE_DELL_TYPE, ifinfo.if_type); return true; } static cps_api_return_code_t _get_db_interface( cps_api_object_list_t *list, hal_ifindex_t ifix, bool get_all, uint_t if_type ) { INTERFACE *fill = os_get_if_db_hdlr(); if (!fill) return cps_api_ret_code_ERR; if_info_t ifinfo; if(!get_all && fill->if_info_get(ifix, ifinfo)) { EV_LOGGING(NAS_OS, INFO,"NET-MAIN", "Get ifinfo for %d", ifix); cps_api_object_t obj = cps_api_object_create(); if(obj == nullptr) return cps_api_ret_code_ERR; if(!os_interface_info_to_object(ifix, ifinfo, obj)) { cps_api_object_delete(obj); return cps_api_ret_code_ERR; } cps_api_object_set_type_operation(cps_api_object_key(obj),cps_api_oper_NULL); if (cps_api_object_list_append(*list,obj)) { return cps_api_ret_code_OK; } else { cps_api_object_delete(obj); return cps_api_ret_code_ERR; } } else if (get_all) { fill->for_each_mbr([if_type, &list](int idx, if_info_t& ifinfo) { if(if_type != 0 && ifinfo.if_type != static_cast<BASE_CMN_INTERFACE_TYPE_t>(if_type)) { return; } EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Get all ifinfo for %d", idx); cps_api_object_t obj = cps_api_object_create(); if(obj == nullptr) return; if(!os_interface_info_to_object(idx, ifinfo, obj)) { cps_api_object_delete(obj); return; } cps_api_object_attr_t attr_id = cps_api_object_attr_get(obj, BASE_IF_LINUX_IF_INTERFACES_INTERFACE_DELL_TYPE); if (attr_id != NULL) { BASE_CMN_INTERFACE_TYPE_t type = (BASE_CMN_INTERFACE_TYPE_t) cps_api_object_attr_data_uint(attr_id); if (type == BASE_CMN_INTERFACE_TYPE_MANAGEMENT) { attr_id = cps_api_object_attr_get(obj, IF_INTERFACES_INTERFACE_NAME); if (attr_id != NULL) { char if_name[HAL_IF_NAME_SZ+1]; safestrncpy(if_name, (const char*)cps_api_object_attr_data_bin(attr_id), HAL_IF_NAME_SZ); os_get_interface_ethtool_cmd_data(if_name, obj); os_get_interface_oper_status(if_name, obj); } } } cps_api_object_set_type_operation(cps_api_object_key(obj),cps_api_oper_NULL); if (cps_api_object_list_append(*list,obj)) { return; } else { cps_api_object_delete(obj); return; } }); return cps_api_ret_code_OK; } return cps_api_ret_code_ERR; } cps_api_return_code_t _get_interfaces( cps_api_object_list_t list, hal_ifindex_t ifix, bool get_all, uint_t if_type ) { if(_get_db_interface(&list, ifix, get_all, if_type) == cps_api_ret_code_OK) return cps_api_ret_code_OK; EV_LOGGING(NAS_OS, INFO, "NET-MAIN", "Get interface info for ifindex %d", ifix); int if_sock = 0; if((if_sock = nas_nl_sock_create(NL_DEFAULT_VRF_NAME, nas_nl_sock_T_INT,false)) < 0) { EV_LOGGING(NAS_OS, ERR, "NET-MAIN", "soc create failure for get ifindex %d", ifix); return cps_api_ret_code_ERR; } const int BUFF_LEN=4196; char buff[BUFF_LEN]; memset(buff,0,sizeof(buff)); struct ifinfomsg ifmsg; memset(&ifmsg,0,sizeof(ifmsg)); nas_os_pack_if_hdr(&ifmsg, AF_NETLINK, 0, ifix ); int seq = (int)pthread_self(); int dump_flags = NLM_F_ROOT| NLM_F_DUMP; if (nl_send_request(if_sock, RTM_GETLINK, (NLM_F_REQUEST | NLM_F_ACK | (get_all ? dump_flags : 0)), seq,&ifmsg, sizeof(ifmsg))) { netlink_tools_process_socket(if_sock,get_netlink_data, &list,buff,sizeof(buff),&seq,NULL, NL_DEFAULT_VRF_ID); } size_t mx = cps_api_object_list_size(list); for (size_t ix = 0 ; ix < mx ; ++ix ) { cps_api_object_t ret = cps_api_object_list_get(list,ix); STD_ASSERT(ret!=NULL); cps_api_object_set_type_operation(cps_api_object_key(ret),cps_api_oper_NULL); cps_api_object_attr_t attr_id = cps_api_object_attr_get(ret, BASE_IF_LINUX_IF_INTERFACES_INTERFACE_DELL_TYPE); if (attr_id != NULL) { BASE_CMN_INTERFACE_TYPE_t type = (BASE_CMN_INTERFACE_TYPE_t) cps_api_object_attr_data_uint(attr_id); if (type == BASE_CMN_INTERFACE_TYPE_MANAGEMENT) { attr_id = cps_api_object_attr_get(ret, IF_INTERFACES_INTERFACE_NAME); if (attr_id != NULL) { char if_name[HAL_IF_NAME_SZ+1]; safestrncpy(if_name, (const char*)cps_api_object_attr_data_bin(attr_id), HAL_IF_NAME_SZ); os_get_interface_ethtool_cmd_data(if_name, ret); os_get_interface_oper_status(if_name, ret); } } } } close(if_sock); return cps_api_ret_code_OK; } cps_api_return_code_t __rd(void * context, cps_api_get_params_t * param, size_t key_ix) { cps_api_object_t obj = cps_api_object_list_get(param->filters,key_ix); STD_ASSERT(obj!=nullptr); if (nas_os_get_interface(obj,param->list)==STD_ERR_OK) { return cps_api_ret_code_OK; } return cps_api_ret_code_ERR; } cps_api_return_code_t __wr(void * context, cps_api_transaction_params_t * param,size_t ix) { return cps_api_ret_code_ERR; } t_std_error os_interface_object_reg(cps_api_operation_handle_t handle) { cps_api_registration_functions_t f; memset(&f,0,sizeof(f)); char buff[CPS_API_KEY_STR_MAX]; if (!cps_api_key_from_attr_with_qual(&f.key, BASE_IF_LINUX_IF_INTERFACES_INTERFACE,cps_api_qualifier_TARGET)) { EV_LOGGING(NAS_OS, ERR,"NAS-IF-REG","Could not translate %d to key %s", (int)(BASE_IF_LINUX_IF_INTERFACES_INTERFACE),cps_api_key_print(&f.key,buff,sizeof(buff)-1)); return STD_ERR(INTERFACE,FAIL,0); } f.handle = handle; f._read_function = __rd; f._write_function = __wr; if (cps_api_register(&f)!=cps_api_ret_code_OK) { return STD_ERR(INTERFACE,FAIL,0); } return STD_ERR_OK; } extern "C" t_std_error os_intf_admin_state_get(hal_ifindex_t ifix, bool *p_admin_status) { INTERFACE *fill = os_get_if_db_hdlr(); bool admin = false; if (!fill) return STD_ERR(INTERFACE,FAIL,0); if(fill->if_info_get_admin(ifix, admin)) { *p_admin_status = admin; return STD_ERR_OK; } return STD_ERR(INTERFACE,FAIL,0); } extern "C" t_std_error os_intf_mac_addr_get(hal_ifindex_t ifix, hal_mac_addr_t mac) { INTERFACE *fill = os_get_if_db_hdlr(); if_info_t if_info; if (!fill) return STD_ERR(INTERFACE,FAIL,0); if(fill->if_info_get(ifix, if_info)) { memcpy(mac, if_info.phy_addr, HAL_MAC_ADDR_LEN); return STD_ERR_OK; } return STD_ERR(INTERFACE,FAIL,0); } extern "C" t_std_error os_get_interface_oper_status(const char *ifname, cps_api_object_t obj) { IF_INTERFACES_STATE_INTERFACE_OPER_STATUS_t oper_status; cps_api_object_attr_t attr = cps_api_object_attr_get(obj, VRF_MGMT_NI_IF_INTERFACES_INTERFACE_VRF_ID); uint32_t vrf_id = NAS_DEFAULT_VRF_ID; const char *vrf_name = NULL; if (attr != NULL) { vrf_id = cps_api_object_attr_data_uint(attr); vrf_name = nas_os_get_vrf_name(vrf_id); } t_std_error ret = nas_os_util_int_oper_status_get(vrf_name, ifname, &oper_status); if (ret == STD_ERR_OK) { cps_api_object_attr_add_u32(obj, IF_INTERFACES_STATE_INTERFACE_OPER_STATUS, oper_status); } return ret; } extern "C" t_std_error os_get_interface_ethtool_cmd_data(const char *ifname, cps_api_object_t obj) { ethtool_cmd_data_t eth_cmd; uint32_t idx = 0; cps_api_object_attr_t attr = cps_api_object_attr_get(obj, VRF_MGMT_NI_IF_INTERFACES_INTERFACE_VRF_ID); uint32_t vrf_id = NAS_DEFAULT_VRF_ID; const char *vrf_name = NULL; if (attr != NULL) { vrf_id = cps_api_object_attr_data_uint(attr); vrf_name = nas_os_get_vrf_name(vrf_id); } memset(&eth_cmd, 0, sizeof(eth_cmd)); t_std_error ret = nas_os_util_int_ethtool_cmd_data_get(vrf_name, ifname, &eth_cmd); if (ret == STD_ERR_OK) { cps_api_object_attr_add_u32(obj, DELL_IF_IF_INTERFACES_INTERFACE_SPEED, eth_cmd.speed); cps_api_object_attr_add_u32(obj, DELL_IF_IF_INTERFACES_STATE_INTERFACE_DUPLEX, eth_cmd.duplex); cps_api_object_attr_add(obj, DELL_IF_IF_INTERFACES_STATE_INTERFACE_AUTO_NEGOTIATION, &eth_cmd.autoneg, sizeof(eth_cmd.autoneg)); for (idx = 0; idx < BASE_IF_SPEED_MAX; idx++) { if (eth_cmd.supported_speed[idx] == true) { cps_api_object_attr_add_u32(obj, DELL_IF_IF_INTERFACES_STATE_INTERFACE_SUPPORTED_SPEED, idx); } } } return ret; } extern "C" t_std_error os_set_interface_ethtool_cmd_data (const char *ifname, cps_api_object_t obj) { ethtool_cmd_data_t eth_cmd; t_std_error ret = STD_ERR_OK; cps_api_object_attr_t sp_attr, dup_attr, an_attr; cps_api_object_attr_t attr = cps_api_object_attr_get(obj, VRF_MGMT_NI_IF_INTERFACES_INTERFACE_VRF_ID); uint32_t vrf_id = NAS_DEFAULT_VRF_ID; const char *vrf_name = NULL; if (attr != NULL) { vrf_id = cps_api_object_attr_data_uint(attr); vrf_name = nas_os_get_vrf_name(vrf_id); } memset(&eth_cmd, 0, sizeof(eth_cmd)); sp_attr = cps_api_object_attr_get(obj, DELL_IF_IF_INTERFACES_INTERFACE_SPEED); dup_attr = cps_api_object_attr_get(obj, DELL_IF_IF_INTERFACES_INTERFACE_DUPLEX); an_attr = cps_api_object_attr_get(obj, DELL_IF_IF_INTERFACES_INTERFACE_AUTO_NEGOTIATION); eth_cmd.speed = BASE_IF_SPEED_AUTO; eth_cmd.duplex = BASE_CMN_DUPLEX_TYPE_AUTO; eth_cmd.autoneg = true; if (sp_attr != NULL) { eth_cmd.speed = (BASE_IF_SPEED_t)cps_api_object_attr_data_uint(sp_attr); } if (dup_attr != NULL) { eth_cmd.duplex = (BASE_CMN_DUPLEX_TYPE_t)cps_api_object_attr_data_uint(dup_attr); } if (an_attr != NULL) { eth_cmd.autoneg = cps_api_object_attr_data_uint(an_attr); } ret = nas_os_util_int_ethtool_cmd_data_set(vrf_name, ifname, &eth_cmd); return ret; } extern "C" t_std_error os_get_interface_stats (const char *ifname, cps_api_object_t obj) { os_int_stats_t data; uint32_t vrf_id = NAS_DEFAULT_VRF_ID; const char *vrf_name = NULL; cps_api_object_attr_t attr = cps_api_object_attr_get(obj, VRF_MGMT_NI_IF_INTERFACES_INTERFACE_VRF_ID); if (attr != NULL) { vrf_id = cps_api_object_attr_data_uint(attr); vrf_name = nas_os_get_vrf_name(vrf_id); } memset(&data, 0, sizeof(data)); t_std_error ret = nas_os_util_int_stats_get(vrf_name, ifname, &data); if (ret == STD_ERR_OK) { cps_api_object_attr_add_u64(obj, DELL_IF_IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_PKTS, data.input_packets); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_OCTETS, data.input_bytes); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_MULTICAST_PKTS, data.input_multicast); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_ERRORS, data.input_errors); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_IN_DISCARDS, data.input_discards); cps_api_object_attr_add_u64(obj, DELL_IF_IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_PKTS, data.output_packets); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_OCTETS, data.output_bytes); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_MULTICAST_PKTS, data.output_multicast); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_ERRORS, data.output_errors); cps_api_object_attr_add_u64(obj, IF_INTERFACES_STATE_INTERFACE_STATISTICS_OUT_DISCARDS, data.output_invalid_protocol); } return ret; }
40.287529
129
0.670699
[ "object" ]
c21e33b076c25fa1d55bafbc5a667dc523bc1521
2,406
cpp
C++
test/core/src/test_atomistics.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
14
2019-11-16T10:34:04.000Z
2022-03-28T09:32:42.000Z
test/core/src/test_atomistics.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
5
2019-11-21T05:54:07.000Z
2022-03-29T07:56:34.000Z
test/core/src/test_atomistics.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
4
2020-09-28T14:28:23.000Z
2021-03-05T14:11:44.000Z
// // Created by dominik on 02.06.21. // #include "types.hpp" #include "atomistics.hpp" #include <gtest/gtest.h> using namespace sqsgenerator::utils::atomistics; namespace sqsgenerator::test { class AtomisticsTestFixture : public ::testing::Test { protected: size_t m_numSpecies; std::vector<species_t> m_zNumbers; AtomisticsTestFixture() : m_numSpecies(114), m_zNumbers(m_numSpecies) { std::iota(m_zNumbers.begin(), m_zNumbers.end(), 1); } }; void vectorCompare(const std::vector<Atom> &lhs, const std::vector<Atom> &rhs) { ASSERT_EQ(lhs.size(), rhs.size()) << "Vectors x and y are of unequal length"; for (int i = 0; i < lhs.size(); ++i) { ASSERT_EQ(lhs[i].Z, rhs[i].Z) << "Vectors x and y differ at index " << i; } } TEST_F(AtomisticsTestFixture, TestAtomFromZComplete) { ASSERT_EQ(Atoms::from_z(1).Z, 1); ASSERT_EQ(Atoms::from_z(1).symbol, "H"); ASSERT_EQ(Atoms::from_z(1).name, "Hydrogen"); ASSERT_EQ(Atoms::from_z(m_numSpecies).Z, m_numSpecies); ASSERT_EQ(Atoms::from_z(m_numSpecies).symbol, "Fl"); ASSERT_EQ(Atoms::from_z(m_numSpecies).name, "Flerovium"); for (const auto& spec: m_zNumbers) { ASSERT_EQ(Atoms::from_z(spec).Z, spec); } } TEST_F(AtomisticsTestFixture, TestAtomfrom_symbolComplete) { ASSERT_EQ(Atoms::from_symbol("H").Z, 1); ASSERT_EQ(Atoms::from_symbol("H").symbol, "H"); ASSERT_EQ(Atoms::from_symbol("H").name, "Hydrogen"); ASSERT_EQ(Atoms::from_symbol("Fl").Z, m_numSpecies); ASSERT_EQ(Atoms::from_symbol("Fl").symbol, "Fl"); ASSERT_EQ(Atoms::from_symbol("Fl").name, "Flerovium"); auto symbols = Atoms::from_z(m_zNumbers); for (const auto& sym: symbols) { ASSERT_EQ(sym.Z, Atoms::from_symbol(sym.symbol).Z); } } TEST_F(AtomisticsTestFixture, TestFromZAndFromSymbols) { auto atoms = Atoms::from_z(m_zNumbers); std::vector<std::string> symbols; for (const auto& atom : atoms) symbols.push_back(atom.symbol); std::vector<std::string> empty; // ASSERT_EQ(empty, symbols); //vectorCompare(atoms, Atoms::from_symbol(symbols)); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.657895
85
0.620948
[ "vector" ]
c221bbe7c227c3cd34e89fd97607933959793bf2
1,145
cpp
C++
DinoLasers/ProgressBar.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
DinoLasers/ProgressBar.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
DinoLasers/ProgressBar.cpp
QRayarch/DinoLasers
500f4144fad2a813cd140d6067b41a41f4573e8c
[ "MIT" ]
null
null
null
#include "ProgressBar.h" ProgressBar::ProgressBar(String name, float maxValue) : UI(name) { width = 20; maxVal = maxValue; currentVal = maxVal; fillColor = REWHITE; } ProgressBar::~ProgressBar() { } void ProgressBar::SetCurrentValue(float newValue) { currentVal = glm::clamp(newValue, 0.0f, maxVal); } float ProgressBar::GetCurrentValue() { return currentVal; } void ProgressBar::SetFillColor(vector3 newColor){ fillColor = newColor; } void ProgressBar::Update(float dt) { } void ProgressBar::Render() { MeshManagerSingleton::GetInstance()->SetFont("Font_UI.png"); String bar = ""; float normal = currentVal / maxVal; float wid = width; for (int w = 0; w < width; w++) { int prog = static_cast<int>(normal * width); if (prog == w) { int next = static_cast<int>(((currentVal - (prog / wid) * maxVal) / maxVal * wid) * 10); if (next >= 10) { bar += "0"; } else if (next <= 0) { bar += "#"; } else { bar += std::to_string(next); } //bar += "@"; } else if (prog < w) { bar += "#"; } else { bar += "0"; } } MeshManagerSingleton::GetInstance()->PrintLine(bar, fillColor); }
19.741379
92
0.620087
[ "render" ]
c225d4e542a0cab9fbf7aefe806c172b403c86f0
7,477
hpp
C++
LocalSpace.hpp
simbuerg/isl-
28a72cbebcb20cb722dc8712af145ed9af200865
[ "MIT" ]
null
null
null
LocalSpace.hpp
simbuerg/isl-
28a72cbebcb20cb722dc8712af145ed9af200865
[ "MIT" ]
null
null
null
LocalSpace.hpp
simbuerg/isl-
28a72cbebcb20cb722dc8712af145ed9af200865
[ "MIT" ]
null
null
null
#ifndef ISL_CXX_LocalSpace_IMPL_H #define ISL_CXX_LocalSpace_IMPL_H #include "isl/LocalSpace.h" #include "isl/Aff.hpp" #include "isl/BasicMap.hpp" #include "isl/Id.hpp" #include "isl/Space.hpp" #include "isl/Bool.h" #include "isl/DimType.h" #include "isl/Format.h" #include "isl/IslBase.h" #include "isl/IslException.h" #include <string> #include <cassert> namespace isl { inline isl_local_space *LocalSpace::GetCopy() const { return isl_local_space_copy((isl_local_space *)This); } inline LocalSpace &LocalSpace::operator=(const LocalSpace &Other) { isl_local_space *New = Other.GetCopy(); ctx = Other.Context(); isl_local_space_free((isl_local_space *)This); This = New; return *this; } inline LocalSpace LocalSpace::fromSpace(const Space &dim) { const Ctx &_ctx = dim.Context(); _ctx.lock(); isl_local_space *That = isl_local_space_from_space((dim).GetCopy()); _ctx.unlock(); if (_ctx.hasError()) { handleError("isl_local_space_from_space returned a NULL pointer."); } return LocalSpace(_ctx, That); } inline LocalSpace::~LocalSpace() { isl_local_space_free((isl_local_space *)This); This = nullptr; } /// rief Release ownership of the wrapped object. /// /// You are on your own now buddy. /// The wrapper cannot be used anymore after calling Give() /// ///@return the wrapped isl object. inline isl_local_space *LocalSpace::Give() { isl_local_space *res = (isl_local_space *)This; This = nullptr; return res; } /// \brief Unwrap the stored isl object. /// \returns A the wrapped isl object. inline isl_local_space *LocalSpace::Get() const { return (isl_local_space *)This; } inline LocalSpace LocalSpace::addDims(DimType type, unsigned int n) const { ctx.lock(); isl_local_space * res = isl_local_space_add_dims((*this).GetCopy(), (enum isl_dim_type)type, n); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_add_dims returned a NULL pointer."); } return LocalSpace(ctx, res); } inline int LocalSpace::dim(DimType type) const { ctx.lock(); int res = isl_local_space_dim((*this).Get(), (enum isl_dim_type)type); ctx.unlock(); return res; } inline LocalSpace LocalSpace::domain() const { ctx.lock(); isl_local_space * res = isl_local_space_domain((*this).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_domain returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::dropDims(DimType type, unsigned int first, unsigned int n) const { ctx.lock(); isl_local_space * res = isl_local_space_drop_dims((*this).GetCopy(), (enum isl_dim_type)type, first, n); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_drop_dims returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::fromDomain() const { ctx.lock(); isl_local_space * res = isl_local_space_from_domain((*this).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_from_domain returned a NULL pointer."); } return LocalSpace(ctx, res); } inline Id LocalSpace::getDimId(DimType type, unsigned int pos) const { ctx.lock(); isl_id * res = isl_local_space_get_dim_id((*this).Get(), (enum isl_dim_type)type, pos); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_get_dim_id returned a NULL pointer."); } return Id(ctx, res); } inline std::string LocalSpace::getDimName(DimType type, unsigned int pos) const { ctx.lock(); const char * res = isl_local_space_get_dim_name((*this).Get(), (enum isl_dim_type)type, pos); ctx.unlock(); std::string res_; if (ctx.hasError()) { handleError("isl_local_space_get_dim_name returned a NULL pointer."); } res_ = res; return res_; } inline Aff LocalSpace::getDiv(int pos) const { ctx.lock(); isl_aff * res = isl_local_space_get_div((*this).Get(), pos); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_get_div returned a NULL pointer."); } return Aff(ctx, res); } inline Space LocalSpace::getSpace() const { ctx.lock(); isl_space * res = isl_local_space_get_space((*this).Get()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_get_space returned a NULL pointer."); } return Space(ctx, res); } inline Bool LocalSpace::hasDimId(DimType type, unsigned int pos) const { ctx.lock(); isl_bool res = isl_local_space_has_dim_id((*this).Get(), (enum isl_dim_type)type, pos); ctx.unlock(); return (Bool)res; } inline Bool LocalSpace::hasDimName(DimType type, unsigned int pos) const { ctx.lock(); isl_bool res = isl_local_space_has_dim_name((*this).Get(), (enum isl_dim_type)type, pos); ctx.unlock(); return (Bool)res; } inline LocalSpace LocalSpace::insertDims(DimType type, unsigned int first, unsigned int n) const { ctx.lock(); isl_local_space * res = isl_local_space_insert_dims((*this).GetCopy(), (enum isl_dim_type)type, first, n); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_insert_dims returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::intersect(const LocalSpace &ls2) const { ctx.lock(); isl_local_space * res = isl_local_space_intersect((*this).GetCopy(), (ls2).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_intersect returned a NULL pointer."); } return LocalSpace(ctx, res); } inline Bool LocalSpace::isEqual(const LocalSpace &ls2) const { ctx.lock(); isl_bool res = isl_local_space_is_equal((*this).Get(), (ls2).Get()); ctx.unlock(); return (Bool)res; } inline Bool LocalSpace::isSet() const { ctx.lock(); isl_bool res = isl_local_space_is_set((*this).Get()); ctx.unlock(); return (Bool)res; } inline BasicMap LocalSpace::lifting() const { ctx.lock(); isl_basic_map * res = isl_local_space_lifting((*this).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_lifting returned a NULL pointer."); } return BasicMap(ctx, res); } inline LocalSpace LocalSpace::range() const { ctx.lock(); isl_local_space * res = isl_local_space_range((*this).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_range returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::setDimId(DimType type, unsigned int pos, const Id &id) const { ctx.lock(); isl_local_space * res = isl_local_space_set_dim_id((*this).GetCopy(), (enum isl_dim_type)type, pos, (id).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_set_dim_id returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::setDimName(DimType type, unsigned int pos, std::string s) const { ctx.lock(); isl_local_space * res = isl_local_space_set_dim_name((*this).GetCopy(), (enum isl_dim_type)type, pos, s.c_str()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_set_dim_name returned a NULL pointer."); } return LocalSpace(ctx, res); } inline LocalSpace LocalSpace::setTupleId(DimType type, const Id &id) const { ctx.lock(); isl_local_space * res = isl_local_space_set_tuple_id((*this).GetCopy(), (enum isl_dim_type)type, (id).GetCopy()); ctx.unlock(); if (ctx.hasError()) { handleError("isl_local_space_set_tuple_id returned a NULL pointer."); } return LocalSpace(ctx, res); } } // namespace isl #endif //ISL_CXX_LocalSpace_IMPL_H
29.670635
119
0.707236
[ "object" ]
ea4d43833467de94a92d00a859d49f9df8ecda19
838
cpp
C++
tests/test_class.cpp
Time0o/fire-llvm
5694116ff64ccc6e8f17a7220c1f3015b548173e
[ "MIT" ]
23
2021-12-27T14:56:07.000Z
2022-03-07T18:42:56.000Z
tests/test_class.cpp
Time0o/fire-llvm
5694116ff64ccc6e8f17a7220c1f3015b548173e
[ "MIT" ]
null
null
null
tests/test_class.cpp
Time0o/fire-llvm
5694116ff64ccc6e8f17a7220c1f3015b548173e
[ "MIT" ]
2
2021-12-28T07:11:41.000Z
2022-03-24T07:20:47.000Z
#include <fire-llvm/fire.hpp> #include <iostream> #include <optional> #include <string> #include <vector> struct S { std::string hello(std::string const &msg) { return msg; } int add(int a, int b) { return a + b; } bool flag(bool f) { return f; } int default_arg(int d = 0) { return d; } void optional(std::optional<int> opt) { if (opt) std::cout << "opt = " << opt.value() << std::endl; else std::cout << "opt = nothing" << std::endl; } void variadic(std::vector<int> const &variadic) { std::cout << "variadic = {"; if (!variadic.empty()) { std::cout << variadic[0]; for (std::size_t i = 1; i < variadic.size(); ++i) std::cout << ", " << variadic[i]; } std::cout << "}"; } }; S s; int main() { fire::fire_llvm(s); }
14.448276
56
0.52148
[ "vector" ]
ea53e6975551720aaada063d07f6ce819626f253
3,455
cpp
C++
testdbwindow.cpp
ifconfig/besetzungsrechnerqt
7efc291b05bba5a350bdd75a3ecb6a7d33c3f5ec
[ "Apache-2.0" ]
null
null
null
testdbwindow.cpp
ifconfig/besetzungsrechnerqt
7efc291b05bba5a350bdd75a3ecb6a7d33c3f5ec
[ "Apache-2.0" ]
null
null
null
testdbwindow.cpp
ifconfig/besetzungsrechnerqt
7efc291b05bba5a350bdd75a3ecb6a7d33c3f5ec
[ "Apache-2.0" ]
null
null
null
#include "testdbwindow.h" #include "ui_testdbwindow.h" TestDbWindow::TestDbWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::TestDbWindow) { ui->setupUi(this); } TestDbWindow::~TestDbWindow() { delete ui; } void TestDbWindow::on_pushButton_clicked() { QJsonObject configurationObject = loadConfObject(); createQualificationSliders(configurationObject); createVehicleSpinBoxes(configurationObject); } QJsonObject TestDbWindow::loadConfObject() { QString val; QFile file; //file.setFileName("/Users/heyne/workspaces/workspace_qt/names.json"); file.setFileName("names.json"); bool ok = file.open(QIODevice::ReadOnly | QIODevice::Text); if(!ok){ QString filename = QFileDialog::getOpenFileName(this, "JSON öffnen", "./","JSON Files (*.json)"); file.setFileName(filename); ok = file.open(QIODevice::ReadOnly | QIODevice::Text); if(!ok){ return QJsonObject(); } } val = file.readAll(); file.close(); QJsonDocument confFile = QJsonDocument::fromJson(val.toUtf8()); return confFile.object(); } void TestDbWindow::createQualificationSliders(QJsonObject configurationObject) { QWidget* sliderArea = new QWidget(ui->groupBox_qualifications); sliderArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); sliderArea->setLayout(new QVBoxLayout(sliderArea)); ui->scrollArea_qualifications->setWidget(sliderArea); QJsonArray qualificationsArray = configurationObject["qualifications"].toArray(); m_qualiList = QSharedPointer<QualificationList>(new QualificationList(qualificationsArray)); // show sliders foreach (QSharedPointer<Qualification> quali, m_qualiList->getHashList()) { auto sliderWidget = new QualificationSliderWidget(quali, sliderArea); m_sliderHashList.insert(quali->qualiShortName(), sliderWidget); sliderArea->layout()->addWidget(sliderWidget); } } void TestDbWindow::createVehicleSpinBoxes(QJsonObject configurationObject) { QWidget* spinBoxArea = new QWidget(ui->groupBox_vehicles); spinBoxArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); spinBoxArea->setLayout(new QVBoxLayout(spinBoxArea)); ui->scrollArea_vehicles->setWidget(spinBoxArea); QJsonArray vehiclesArray = configurationObject["vehicles"].toArray(); m_vehicleList = QSharedPointer<VehicleList>(new VehicleList(vehiclesArray)); foreach (QSharedPointer<Vehicle> vehicle, m_vehicleList->vehicles()) { VehicleSpinBoxWidget* vehicleSpinBoxWidget = new VehicleSpinBoxWidget(vehicle, spinBoxArea); spinBoxArea->layout()->addWidget(vehicleSpinBoxWidget); m_vehicleSpinBoxList.insert(vehicle->name(), vehicleSpinBoxWidget); } } // generieren Button pressed void TestDbWindow::on_pushButton_2_clicked() { // gather Qualification percentages foreach (auto qualificationSliderWidget, m_sliderHashList) { m_qualiList->qualificationPercentages()->insert( qualificationSliderWidget->qualification()->qualiShortName(), qualificationSliderWidget->qualificationSlider()->value()); } // gather Vehicle number foreach (auto vehicleSpinBox, m_vehicleSpinBoxList) { m_vehicleList->vehicleNumber()->insert( vehicleSpinBox->vehicle()->name(), vehicleSpinBox->vehicleSpinBox()->value()); } }
31.990741
105
0.723589
[ "object" ]
ea68d25553f9a55846a9933aff49b64254b1fa7f
513
cpp
C++
card_karuba_lib/util.cpp
MariusUrbonas/karuba-card-game-learning-enviroment
eee638229f045cd8563209c81aee6f2f319292cf
[ "MIT" ]
1
2019-05-19T16:24:51.000Z
2019-05-19T16:24:51.000Z
card_karuba_lib/util.cpp
MariusUrbonas/karuba-card-game-learning-enviroment
eee638229f045cd8563209c81aee6f2f319292cf
[ "MIT" ]
null
null
null
card_karuba_lib/util.cpp
MariusUrbonas/karuba-card-game-learning-enviroment
eee638229f045cd8563209c81aee6f2f319292cf
[ "MIT" ]
null
null
null
// // Created by Marius Urbonas on 2019-05-07. // #include "util.h" #include <string> #include <vector> namespace card_karuba_env { std::string RankIndexToString(int rank) { if (rank >= 0 && rank <= kMaxNumRanks) { std::vector<std::string> str_ranks = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"}; return str_ranks[rank]; } else { return "X"; } } }
24.428571
118
0.448343
[ "vector" ]
ea6ed0a1b7fe8d9b4a567e048b22044fbf155c5b
83,147
cpp
C++
printscan/ui/wiaacmgr/acqmgrcw.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/ui/wiaacmgr/acqmgrcw.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/ui/wiaacmgr/acqmgrcw.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************************************************************* * * (C) COPYRIGHT MICROSOFT CORPORATION, 1998 * * TITLE: ACQMGRCW.CPP * * VERSION: 1.0 * * AUTHOR: ShaunIv * * DATE: 9/27/1999 * * DESCRIPTION: * *******************************************************************************/ #include "precomp.h" #pragma hdrstop #include <windows.h> #include <simcrack.h> #include <commctrl.h> #include <wiatextc.h> #include <pviewids.h> #include <commctrl.h> #include "resource.h" #include "acqmgrcw.h" #include "wia.h" #include "wiadevdp.h" #include "evntparm.h" #include "itranhlp.h" #include "bkthread.h" #include "wiaitem.h" #include "errors.h" #include "isuppfmt.h" #include "uiexthlp.h" #include "gphelper.h" #include "svselfil.h" #include "gwiaevnt.h" #include "modlock.h" #include "comfin.h" #include "comprog.h" #include "upquery.h" #include "comdelp.h" #include "devprop.h" #include "mboxex.h" #include "dumpprop.h" #include "psutil.h" #undef TRY_SMALLER_THUMBNAILS #if defined(TRY_SMALLER_THUMBNAILS) static const int c_nDefaultThumbnailWidth = 80; static const int c_nDefaultThumbnailHeight = 80; static const int c_nMaxThumbnailWidth = 80; static const int c_nMaxThumbnailHeight = 80; static const int c_nMinThumbnailWidth = 80; static const int c_nMinThumbnailHeight = 80; #else static const int c_nDefaultThumbnailWidth = 90; static const int c_nDefaultThumbnailHeight = 90; static const int c_nMaxThumbnailWidth = 120; static const int c_nMaxThumbnailHeight = 120; static const int c_nMinThumbnailWidth = 80; static const int c_nMinThumbnailHeight = 80; #endif // // Property sheet pages' window class declarations // #include "comfirst.h" #include "camsel.h" #include "comtrans.h" #include "scansel.h" // ------------------------------------------------- // CAcquisitionManagerControllerWindow // ------------------------------------------------- CAcquisitionManagerControllerWindow::CAcquisitionManagerControllerWindow( HWND hWnd ) : m_hWnd(hWnd), m_pEventParameters(NULL), m_DeviceTypeMode(UnknownMode), m_hWizardIconSmall(NULL), m_hWizardIconBig(NULL), m_guidOutputFormat(IID_NULL), m_bDeletePicturesIfSuccessful(false), m_nThreadNotificationMessage(RegisterWindowMessage(STR_THREAD_NOTIFICATION_MESSAGE)), m_nWiaEventMessage(RegisterWindowMessage(STR_WIAEVENT_NOTIFICATION_MESSAGE)), m_bDisconnected(false), m_pThreadMessageQueue(NULL), m_bStampTimeOnSavedFiles(true), m_bOpenShellAfterDownload(true), m_bSuppressFirstPage(false), m_nFailedImagesCount(0), m_nDestinationPageIndex(-1), m_nFinishPageIndex(-1), m_nDeleteProgressPageIndex(-1), m_nSelectionPageIndex(-1), m_hWndWizard(NULL), m_bTakePictureIsSupported(false), m_nWiaWizardPageCount(0), m_nUploadWizardPageCount(0), m_bUploadToWeb(false), m_cRef(1), m_nScannerType(ScannerTypeUnknown), m_OnDisconnect(0), m_dwLastEnumerationTickCount(0) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::CAcquisitionManagerControllerWindow")); // This sets up the map that maps thread messages to message handlers, which are declared to be static // member functions. static CThreadMessageMap s_MsgMap[] = { { TQ_DESTROY, OnThreadDestroy}, { TQ_DOWNLOADIMAGE, OnThreadDownloadImage}, { TQ_DOWNLOADTHUMBNAIL, OnThreadDownloadThumbnail}, { TQ_SCANPREVIEW, OnThreadPreviewScan}, { TQ_DELETEIMAGES, OnThreadDeleteImages}, { 0, NULL} }; // Assume the default thumbnail size, in case we aren't able to calculate it m_sizeThumbnails.cx = c_nDefaultThumbnailWidth; m_sizeThumbnails.cy = c_nDefaultThumbnailHeight; // // Read the initial settings // CSimpleReg reg( HKEY_CURRENT_USER, REGSTR_PATH_USER_SETTINGS_WIAACMGR, false, KEY_READ ); m_bOpenShellAfterDownload = (reg.Query( REG_STR_OPENSHELL, m_bOpenShellAfterDownload ) != FALSE); m_bSuppressFirstPage = (reg.Query( REG_STR_SUPRESSFIRSTPAGE, m_bSuppressFirstPage ) != FALSE); // // Initialize the background thread queue, which will handle all of our background requests // m_pThreadMessageQueue = new CThreadMessageQueue; if (m_pThreadMessageQueue) { // // Note that CBackgroundThread takes ownership of m_pThreadMessageQueue, and it doesn't have to be deleted in this thread // m_hBackgroundThread = CBackgroundThread::Create( m_pThreadMessageQueue, s_MsgMap, m_CancelEvent.Event(), NULL ); } ZeroMemory( m_PublishWizardPages, sizeof(m_PublishWizardPages) ); } CAcquisitionManagerControllerWindow::~CAcquisitionManagerControllerWindow(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::~CAcquisitionManagerControllerWindow")); if (m_pEventParameters) { if (m_pEventParameters->pWizardSharedMemory) { delete m_pEventParameters->pWizardSharedMemory; } m_pEventParameters = NULL; } } LRESULT CAcquisitionManagerControllerWindow::OnDestroy( WPARAM, LPARAM ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::OnDestroy")); // // Tell the publishing wizard to release us // if (m_pPublishingWizard) { IUnknown_SetSite( m_pPublishingWizard, NULL ); } // // Release the publishing wizard and its data // m_pPublishingWizard = NULL; // // Stop downloading thumbnails // m_EventThumbnailCancel.Signal(); // // Unpause the background thread // m_EventPauseBackgroundThread.Signal(); // // Tell the background thread to destroy itself // m_pThreadMessageQueue->Enqueue( new CThreadMessage(TQ_DESTROY),CThreadMessageQueue::PriorityUrgent); // // Issue a cancel io command for this item // WiaUiUtil::IssueWiaCancelIO(m_pWiaItemRoot); // // Tell other instances we are done before the background thread is finished, // so we can immediately start again // if (m_pEventParameters && m_pEventParameters->pWizardSharedMemory) { m_pEventParameters->pWizardSharedMemory->Close(); } // // Wait for the thread to exit // WiaUiUtil::MsgWaitForSingleObject( m_hBackgroundThread, INFINITE ); CloseHandle( m_hBackgroundThread ); // // Clean up the icons // if (m_hWizardIconSmall) { DestroyIcon( m_hWizardIconSmall ); m_hWizardIconSmall = NULL; } if (m_hWizardIconBig) { DestroyIcon( m_hWizardIconBig ); m_hWizardIconBig = NULL; } return 0; } BOOL WINAPI CAcquisitionManagerControllerWindow::OnThreadDestroy( CThreadMessage *pMsg ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::OnThreadDestroy")); // Return false to close the queue return FALSE; } BOOL WINAPI CAcquisitionManagerControllerWindow::OnThreadDownloadImage( CThreadMessage *pMsg ) { CDownloadImagesThreadMessage *pDownloadImageThreadMessage = dynamic_cast<CDownloadImagesThreadMessage*>(pMsg); if (pDownloadImageThreadMessage) { pDownloadImageThreadMessage->Download(); } else { WIA_ERROR((TEXT("pDownloadImageThreadMessage was NULL"))); } return TRUE; } BOOL WINAPI CAcquisitionManagerControllerWindow::OnThreadDownloadThumbnail( CThreadMessage *pMsg ) { CDownloadThumbnailsThreadMessage *pDownloadThumnailsThreadMessage = dynamic_cast<CDownloadThumbnailsThreadMessage*>(pMsg); if (pDownloadThumnailsThreadMessage) { pDownloadThumnailsThreadMessage->Download(); } else { WIA_ERROR((TEXT("pDownloadThumnailThreadMessage was NULL"))); } return TRUE; } BOOL WINAPI CAcquisitionManagerControllerWindow::OnThreadPreviewScan( CThreadMessage *pMsg ) { CPreviewScanThreadMessage *pPreviewScanThreadMessage = dynamic_cast<CPreviewScanThreadMessage*>(pMsg); if (pPreviewScanThreadMessage) { pPreviewScanThreadMessage->Scan(); } else { WIA_ERROR((TEXT("pPreviewScanThreadMessage was NULL"))); } return TRUE; } BOOL WINAPI CAcquisitionManagerControllerWindow::OnThreadDeleteImages( CThreadMessage *pMsg ) { CDeleteImagesThreadMessage *pDeleteImagesThreadMessage = dynamic_cast<CDeleteImagesThreadMessage*>(pMsg); if (pDeleteImagesThreadMessage) { pDeleteImagesThreadMessage->DeleteImages(); } else { WIA_ERROR((TEXT("pPreviewScanThreadMessage was NULL"))); } return TRUE; } HRESULT CAcquisitionManagerControllerWindow::CreateDevice(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::CreateDevice")); CComPtr<IWiaDevMgr> pWiaDevMgr; HRESULT hr = CoCreateInstance( CLSID_WiaDevMgr, NULL, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr, (void**)&pWiaDevMgr ); if (SUCCEEDED(hr)) { bool bRetry = true; for (DWORD dwRetryCount = 0;dwRetryCount < CREATE_DEVICE_RETRY_MAX_COUNT && bRetry;dwRetryCount++) { hr = pWiaDevMgr->CreateDevice( CSimpleBStr(m_pEventParameters->strDeviceID), &m_pWiaItemRoot ); WIA_PRINTHRESULT((hr,TEXT("pWiaDevMgr->CreateDevice returned"))); if (SUCCEEDED(hr)) { // // Break out of loop // bRetry = false; // // Register for events // CGenericWiaEventHandler::RegisterForWiaEvent( m_pEventParameters->strDeviceID, WIA_EVENT_DEVICE_DISCONNECTED, &m_pDisconnectEventObject, m_hWnd, m_nWiaEventMessage ); CGenericWiaEventHandler::RegisterForWiaEvent( m_pEventParameters->strDeviceID, WIA_EVENT_ITEM_DELETED, &m_pDeleteItemEventObject, m_hWnd, m_nWiaEventMessage ); CGenericWiaEventHandler::RegisterForWiaEvent( m_pEventParameters->strDeviceID, WIA_EVENT_DEVICE_CONNECTED, &m_pConnectEventObject, m_hWnd, m_nWiaEventMessage ); CGenericWiaEventHandler::RegisterForWiaEvent( m_pEventParameters->strDeviceID, WIA_EVENT_ITEM_CREATED, &m_pCreateItemEventObject, m_hWnd, m_nWiaEventMessage ); } else if (WIA_ERROR_BUSY == hr) { // // Wait a little while before retrying // Sleep(CREATE_DEVICE_RETRY_WAIT); } else { // // All other errors are considered fatal // bRetry = false; } } } return hr; } void CAcquisitionManagerControllerWindow::GetCookiesOfSelectedImages( CWiaItem *pCurr, CSimpleDynamicArray<DWORD> &Cookies ) { while (pCurr) { GetCookiesOfSelectedImages(pCurr->Children(),Cookies); if (pCurr->IsDownloadableItemType() && pCurr->SelectedForDownload()) { Cookies.Append(pCurr->GlobalInterfaceTableCookie()); } pCurr = pCurr->Next(); } } void CAcquisitionManagerControllerWindow::MarkAllItemsUnselected( CWiaItem *pCurrItem ) { while (pCurrItem) { pCurrItem->SelectedForDownload(false); MarkAllItemsUnselected( pCurrItem->Children() ); pCurrItem = pCurrItem->Next(); } } void CAcquisitionManagerControllerWindow::MarkItemSelected( CWiaItem *pItem, CWiaItem *pCurrItem ) { while (pCurrItem) { if (pItem == pCurrItem && !pCurrItem->Deleted()) { pCurrItem->SelectedForDownload(true); } MarkItemSelected( pItem, pCurrItem->Children() ); pCurrItem = pCurrItem->Next(); } } void CAcquisitionManagerControllerWindow::GetSelectedItems( CWiaItem *pCurr, CSimpleDynamicArray<CWiaItem*> &Items ) { while (pCurr) { GetSelectedItems(pCurr->Children(),Items); if (pCurr->IsDownloadableItemType() && pCurr->SelectedForDownload()) { Items.Append(pCurr); } pCurr = pCurr->Next(); } } void CAcquisitionManagerControllerWindow::GetRotationOfSelectedImages( CWiaItem *pCurr, CSimpleDynamicArray<int> &Rotation ) { while (pCurr) { GetRotationOfSelectedImages(pCurr->Children(),Rotation); if (pCurr->IsDownloadableItemType() && pCurr->SelectedForDownload()) { Rotation.Append(pCurr->Rotation()); } pCurr = pCurr->Next(); } } void CAcquisitionManagerControllerWindow::GetCookiesOfAllImages( CWiaItem *pCurr, CSimpleDynamicArray<DWORD> &Cookies ) { while (pCurr) { GetCookiesOfAllImages(pCurr->Children(),Cookies); if (pCurr->IsDownloadableItemType()) { Cookies.Append(pCurr->GlobalInterfaceTableCookie()); } pCurr = pCurr->Next(); } } int CAcquisitionManagerControllerWindow::GetSelectedImageCount( void ) { CSimpleDynamicArray<DWORD> Cookies; CSimpleDynamicArray<int> Rotation; GetCookiesOfSelectedImages( m_WiaItemList.Root(), Cookies ); GetRotationOfSelectedImages( m_WiaItemList.Root(), Rotation ); if (Rotation.Size() != Cookies.Size()) { return 0; } return Cookies.Size(); } bool CAcquisitionManagerControllerWindow::DeleteDownloadedImages( HANDLE hCancelDeleteEvent ) { // // Make sure we are not paused // m_EventPauseBackgroundThread.Signal(); CSimpleDynamicArray<DWORD> Cookies; for (int i=0;i<m_DownloadedFileInformationList.Size();i++) { Cookies.Append(m_DownloadedFileInformationList[i].Cookie()); } if (Cookies.Size()) { CDeleteImagesThreadMessage *pDeleteImageThreadMessage = new CDeleteImagesThreadMessage( m_hWnd, Cookies, hCancelDeleteEvent, m_EventPauseBackgroundThread.Event(), true ); if (pDeleteImageThreadMessage) { m_pThreadMessageQueue->Enqueue( pDeleteImageThreadMessage, CThreadMessageQueue::PriorityNormal ); } else { WIA_TRACE((TEXT("Uh-oh! Couldn't allocate the thread message"))); return false; } } else { WIA_TRACE((TEXT("Uh-oh! No selected items! Cookies.Size() = %d"), Cookies.Size())); return false; } return true; } bool CAcquisitionManagerControllerWindow::DeleteSelectedImages(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::DeleteSelectedImages")); CSimpleDynamicArray<DWORD> Cookies; GetCookiesOfSelectedImages( m_WiaItemList.Root(), Cookies ); // // Make sure we are not paused // m_EventPauseBackgroundThread.Signal(); if (Cookies.Size()) { CDeleteImagesThreadMessage *pDeleteImageThreadMessage = new CDeleteImagesThreadMessage( m_hWnd, Cookies, NULL, m_EventPauseBackgroundThread.Event(), false ); if (pDeleteImageThreadMessage) { m_pThreadMessageQueue->Enqueue( pDeleteImageThreadMessage, CThreadMessageQueue::PriorityNormal ); } else { WIA_TRACE((TEXT("Uh-oh! Couldn't allocate the thread message"))); return false; } } else { WIA_TRACE((TEXT("Uh-oh! No selected items! Cookies.Size() = %d"), Cookies.Size())); return false; } return true; } bool CAcquisitionManagerControllerWindow::DownloadSelectedImages( HANDLE hCancelDownloadEvent ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::DownloadSelectedImages")); CSimpleDynamicArray<DWORD> Cookies; CSimpleDynamicArray<int> Rotation; GetCookiesOfSelectedImages( m_WiaItemList.Root(), Cookies ); GetRotationOfSelectedImages( m_WiaItemList.Root(), Rotation ); // // Make sure we are not paused // m_EventPauseBackgroundThread.Signal(); if (Cookies.Size() && Rotation.Size() == Cookies.Size()) { CDownloadImagesThreadMessage *pDownloadImageThreadMessage = new CDownloadImagesThreadMessage( m_hWnd, Cookies, Rotation, m_szDestinationDirectory, m_szRootFileName, m_guidOutputFormat, hCancelDownloadEvent, m_bStampTimeOnSavedFiles, m_EventPauseBackgroundThread.Event() ); if (pDownloadImageThreadMessage) { m_pThreadMessageQueue->Enqueue( pDownloadImageThreadMessage, CThreadMessageQueue::PriorityNormal ); } else { WIA_TRACE((TEXT("Uh-oh! Couldn't allocate the thread message"))); return false; } } else { WIA_TRACE((TEXT("Uh-oh! No selected items! Cookies.Size() = %d, Rotation.Size() = %d"), Cookies.Size(), Rotation.Size())); return false; } return true; } bool CAcquisitionManagerControllerWindow::DirectoryExists( LPCTSTR pszDirectoryName ) { // Try to determine if this directory exists DWORD dwFileAttributes = GetFileAttributes(pszDirectoryName); if (dwFileAttributes == 0xFFFFFFFF || !(dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return false; else return true; } bool CAcquisitionManagerControllerWindow::RecursiveCreateDirectory( CSimpleString strDirectoryName ) { // If this directory already exists, return true. if (DirectoryExists(strDirectoryName)) return true; // Otherwise try to create it. CreateDirectory(strDirectoryName,NULL); // If it now exists, return true if (DirectoryExists(strDirectoryName)) return true; else { // Remove the last subdir and try again int nFind = strDirectoryName.ReverseFind(TEXT('\\')); if (nFind >= 0) { RecursiveCreateDirectory( strDirectoryName.Left(nFind) ); // Now try to create it. CreateDirectory(strDirectoryName,NULL); } } //Does it exist now? return DirectoryExists(strDirectoryName); } bool CAcquisitionManagerControllerWindow::IsCameraThumbnailDownloaded( const CWiaItem &WiaItem, LPARAM lParam ) { CAcquisitionManagerControllerWindow *pControllerWindow = reinterpret_cast<CAcquisitionManagerControllerWindow*>(lParam); if (pControllerWindow && (pControllerWindow->m_DeviceTypeMode==CameraMode || pControllerWindow->m_DeviceTypeMode==VideoMode) && WiaItem.IsDownloadableItemType() && !WiaItem.BitmapData()) { return true; } else { return false; } } int CAcquisitionManagerControllerWindow::GetCookies( CSimpleDynamicArray<DWORD> &Cookies, CWiaItem *pCurr, ComparisonCallbackFuntion pfnCallback, LPARAM lParam ) { while (pCurr) { GetCookies(Cookies, pCurr->Children(), pfnCallback, lParam ); if (pfnCallback && pfnCallback(*pCurr,lParam)) { Cookies.Append(pCurr->GlobalInterfaceTableCookie()); } pCurr = pCurr->Next(); } return Cookies.Size(); } // Download all of the camera's thumbnails that haven't been downloaded yet void CAcquisitionManagerControllerWindow::DownloadAllThumbnails() { // // Get all of the images in the device // CSimpleDynamicArray<DWORD> Cookies; GetCookies( Cookies, m_WiaItemList.Root(), IsCameraThumbnailDownloaded, reinterpret_cast<LPARAM>(this) ); if (Cookies.Size()) { m_EventThumbnailCancel.Reset(); CDownloadThumbnailsThreadMessage *pDownloadThumbnailsThreadMessage = new CDownloadThumbnailsThreadMessage( m_hWnd, Cookies, m_EventThumbnailCancel.Event() ); if (pDownloadThumbnailsThreadMessage) { m_pThreadMessageQueue->Enqueue( pDownloadThumbnailsThreadMessage, CThreadMessageQueue::PriorityNormal ); } } } bool CAcquisitionManagerControllerWindow::PerformPreviewScan( CWiaItem *pWiaItem, HANDLE hCancelPreviewEvent ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::PerformPreviewScan")); if (pWiaItem) { CPreviewScanThreadMessage *pPreviewScanThreadMessage = new CPreviewScanThreadMessage( m_hWnd, pWiaItem->GlobalInterfaceTableCookie(), hCancelPreviewEvent ); if (pPreviewScanThreadMessage) { m_pThreadMessageQueue->Enqueue( pPreviewScanThreadMessage, CThreadMessageQueue::PriorityNormal ); return true; } } return false; } void CAcquisitionManagerControllerWindow::DisplayDisconnectMessageAndExit(void) { // // Make sure we are not doing this more than once // if (!m_bDisconnected) { // // Don't do this again // m_bDisconnected = true; // // Close the shared memory section so another instance can start up // if (m_pEventParameters && m_pEventParameters->pWizardSharedMemory) { m_pEventParameters->pWizardSharedMemory->Close(); } if (m_OnDisconnect & OnDisconnectFailDownload) { // // Set an appropriate error message // m_hrDownloadResult = WIA_ERROR_OFFLINE; m_strErrorMessage.LoadString( IDS_DEVICE_DISCONNECTED, g_hInstance ); } if ((m_OnDisconnect & OnDisconnectGotoLastpage) && m_hWndWizard) { // // Find any active dialogs and close them // HWND hWndLastActive = GetLastActivePopup(m_hWndWizard); if (hWndLastActive && hWndLastActive != m_hWndWizard) { SendMessage( hWndLastActive, WM_CLOSE, 0, 0 ); } // // Go to the finish page // PropSheet_SetCurSelByID( m_hWndWizard, IDD_COMMON_FINISH ); } } } void CAcquisitionManagerControllerWindow::SetMainWindowInSharedMemory( HWND hWnd ) { // // Try to grab the mutex // if (m_pEventParameters && m_pEventParameters->pWizardSharedMemory) { HWND *pHwnd = m_pEventParameters->pWizardSharedMemory->Lock(); if (pHwnd) { // // Save the hWnd // *pHwnd = hWnd; // // Release the mutex // m_pEventParameters->pWizardSharedMemory->Release(); } m_hWndWizard = hWnd; } } bool CAcquisitionManagerControllerWindow::GetAllImageItems( CSimpleDynamicArray<CWiaItem*> &Items, CWiaItem *pCurr ) { while (pCurr) { if (pCurr->IsDownloadableItemType()) { Items.Append( pCurr ); } GetAllImageItems( Items, pCurr->Children() ); pCurr = pCurr->Next(); } return(Items.Size() != 0); } bool CAcquisitionManagerControllerWindow::GetAllImageItems( CSimpleDynamicArray<CWiaItem*> &Items ) { return GetAllImageItems( Items, m_WiaItemList.Root() ); } bool CAcquisitionManagerControllerWindow::CanSomeSelectedImagesBeDeleted(void) { CSimpleDynamicArray<CWiaItem*> Items; GetSelectedItems( m_WiaItemList.Root(), Items ); // // Since we get these access flags in the background, if we don't actually have any yet, // we will assume some images CAN be deleted // bool bNoneAreInitialized = true; for (int i=0;i<Items.Size();i++) { if (Items[i]) { if (Items[i]->AccessRights()) { // At least one of the selected images has been initialized bNoneAreInitialized = false; // If at least one can be deleted, return true immediately if (Items[i]->AccessRights() & WIA_ITEM_CAN_BE_DELETED) { return true; } } } } // If none of the images have been initialized, then we will report true if (bNoneAreInitialized) { return true; } else { return false; } } CWiaItem *CAcquisitionManagerControllerWindow::FindItemByName( LPCWSTR pwszItemName ) { WIA_PUSH_FUNCTION((TEXT("CAcquisitionManagerControllerWindow::FindItemByName( %ws )"), pwszItemName )); if (!pwszItemName) return NULL; if (!m_pWiaItemRoot) return NULL; return m_WiaItemList.Find(pwszItemName); } BOOL CAcquisitionManagerControllerWindow::ConfirmWizardCancel( HWND hWndParent ) { // // Always let it exit, for now. // return FALSE; } int CALLBACK CAcquisitionManagerControllerWindow::PropSheetCallback( HWND hWnd, UINT uMsg, LPARAM lParam ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::PropSheetCallback")); if (PSCB_INITIALIZED == uMsg) { // // Try to bring the window to the foreground. // SetForegroundWindow(hWnd); } return 0; } void CAcquisitionManagerControllerWindow::DetermineScannerType(void) { LONG nProps = ScannerProperties::GetDeviceProps( m_pWiaItemRoot ); m_nScannerType = ScannerTypeUnknown; // // Determine which scanner type we have, based on which properties the scanner has, as follows: // // HasFlatBed HasDocumentFeeder SupportsPreview SupportsPageSize // 1 1 1 1 ScannerTypeFlatbedAdf // 1 0 1 0 ScannerTypeFlatbed // 0 1 1 1 ScannerTypeFlatbedAdf // 0 1 0 0 ScannerTypeScrollFed // // otherwise it is ScannerTypeUnknown // const int nMaxControllingProps = 4; static struct { LONG ControllingProps[nMaxControllingProps]; int nScannerType; } s_DialogResourceData[] = { { ScannerProperties::HasFlatBed, ScannerProperties::HasDocumentFeeder, ScannerProperties::SupportsPreview, ScannerProperties::SupportsPageSize, NULL }, { ScannerProperties::HasFlatBed, ScannerProperties::HasDocumentFeeder, ScannerProperties::SupportsPreview, ScannerProperties::SupportsPageSize, ScannerTypeFlatbedAdf }, { ScannerProperties::HasFlatBed, 0, ScannerProperties::SupportsPreview, 0, ScannerTypeFlatbed }, { 0, ScannerProperties::HasDocumentFeeder, ScannerProperties::SupportsPreview, ScannerProperties::SupportsPageSize, ScannerTypeFlatbedAdf }, { 0, ScannerProperties::HasDocumentFeeder, 0, 0, ScannerTypeScrollFed }, { 0, ScannerProperties::HasDocumentFeeder, 0, ScannerProperties::SupportsPageSize, ScannerTypeFlatbedAdf }, { ScannerProperties::HasFlatBed, ScannerProperties::HasDocumentFeeder, 0, ScannerProperties::SupportsPageSize, ScannerTypeFlatbedAdf }, }; // // Find the set of flags that match this device. If they match, use this scanner type. // Loop through each type description. // for (int nCurrentResourceFlags=1;nCurrentResourceFlags<ARRAYSIZE(s_DialogResourceData) && (ScannerTypeUnknown == m_nScannerType);nCurrentResourceFlags++) { // // Loop through each controlling property // for (int nControllingProp=0;nControllingProp<nMaxControllingProps;nControllingProp++) { // // If this property DOESN'T match, break out prematurely // if ((nProps & s_DialogResourceData[0].ControllingProps[nControllingProp]) != s_DialogResourceData[nCurrentResourceFlags].ControllingProps[nControllingProp]) { break; } } // // If the current controlling property is equal to the maximum controlling property, // we had matches all the way through, so use this type // if (nControllingProp == nMaxControllingProps) { m_nScannerType = s_DialogResourceData[nCurrentResourceFlags].nScannerType; } } } CSimpleString CAcquisitionManagerControllerWindow::GetCurrentDate(void) { SYSTEMTIME SystemTime; TCHAR szText[MAX_PATH] = TEXT(""); GetLocalTime( &SystemTime ); GetDateFormat( LOCALE_USER_DEFAULT, 0, &SystemTime, CSimpleString(IDS_DATEFORMAT,g_hInstance), szText, ARRAYSIZE(szText) ); return szText; } bool CAcquisitionManagerControllerWindow::SuppressFirstPage(void) { return m_bSuppressFirstPage; } bool CAcquisitionManagerControllerWindow::IsSerialCamera(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::IsSerialCamera")); // // Only check for serial devices if we are a camera // if (m_DeviceTypeMode==CameraMode) { #if defined(WIA_DIP_HW_CONFIG) // // Get the hardware configuration information // LONG nHardwareConfig = 0; if (PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DIP_HW_CONFIG, nHardwareConfig )) { // // If this is a serial device, return true // if (nHardwareConfig & STI_HW_CONFIG_SERIAL) { return true; } } #else CSimpleStringWide strwPortName; if (PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DIP_PORT_NAME, strwPortName )) { // // Compare the leftmost 3 characters to the word COM (as in COM1, COM2, ... ) // if (strwPortName.Left(3).CompareNoCase(CSimpleStringWide(L"COM"))==0) { WIA_TRACE((TEXT("A comparison of %ws and COM succeeded"), strwPortName.Left(3).String() )); return true; } // // Compare the portname to the word AUTO // else if (strwPortName.CompareNoCase(CSimpleStringWide(L"AUTO"))==0) { WIA_TRACE((TEXT("A comparison of %ws and AUTO succeeded"), strwPortName.String() )); return true; } } #endif } // // Not a serial camera // return false; } HRESULT CAcquisitionManagerControllerWindow::CreateAndExecuteWizard(void) { // // Structure used to setup our data-driven property sheet factory // enum CPageType { NormalPage = 0, FirstPage = 1, LastPage = 2 }; struct CPropertyPageInfo { LPCTSTR pszTemplate; DLGPROC pfnDlgProc; int nIdTitle; int nIdSubTitle; TCHAR szTitle[256]; TCHAR szSubTitle[1024]; CPageType PageType; bool *pbDisplay; int *pnPageIndex; }; // // Maximum number of statically created wizard pages // const int c_nMaxWizardPages = 7; HRESULT hr = S_OK; // // Register common controls // INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(icce); icce.dwICC = ICC_WIN95_CLASSES | ICC_LISTVIEW_CLASSES | ICC_USEREX_CLASSES | ICC_PROGRESS_CLASS | ICC_LINK_CLASS; InitCommonControlsEx( &icce ); // // Register custom window classes // CWiaTextControl::RegisterClass( g_hInstance ); RegisterWiaPreviewClasses( g_hInstance ); // // These are the pages we'll use for the scanner wizard, if it doesn't have an ADF // CPropertyPageInfo ScannerPropSheetPageInfo[] = { { MAKEINTRESOURCE(IDD_SCANNER_FIRST), CCommonFirstPage::DialogProc, 0, 0, TEXT(""), TEXT(""), FirstPage, NULL, NULL }, { MAKEINTRESOURCE(IDD_SCANNER_SELECT), CScannerSelectionPage::DialogProc, IDS_SCANNER_SELECT_TITLE, IDS_SCANNER_SELECT_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nSelectionPageIndex }, { MAKEINTRESOURCE(IDD_SCANNER_TRANSFER), CCommonTransferPage::DialogProc, IDS_SCANNER_TRANSFER_TITLE, IDS_SCANNER_TRANSFER_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDestinationPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_PROGRESS), CCommonProgressPage::DialogProc, IDS_SCANNER_PROGRESS_TITLE, IDS_SCANNER_PROGRESS_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nProgressPageIndex }, { MAKEINTRESOURCE(IDD_UPLOAD_QUERY), CCommonUploadQueryPage::DialogProc, IDS_COMMON_UPLOAD_TITLE, IDS_COMMON_UPLOAD_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nUploadQueryPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_DELETE), CCommonDeleteProgressPage::DialogProc, IDS_COMMON_DELETE_TITLE, IDS_COMMON_DELETE_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDeleteProgressPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_FINISH), CCommonFinishPage::DialogProc, 0, 0, TEXT(""), TEXT(""), LastPage, NULL, &m_nFinishPageIndex } }; // // These are the pages we'll use for the scanner wizard, if it is a scroll-fed scanner // CPropertyPageInfo ScannerScrollFedPropSheetPageInfo[] = { { MAKEINTRESOURCE(IDD_SCANNER_FIRST), CCommonFirstPage::DialogProc, 0, 0, TEXT(""), TEXT(""), FirstPage, NULL, NULL }, { MAKEINTRESOURCE(IDD_SCANNER_SELECT), CScannerSelectionPage::DialogProc, IDS_SCROLLFED_SELECT_TITLE, IDS_SCROLLFED_SELECT_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nSelectionPageIndex }, { MAKEINTRESOURCE(IDD_SCANNER_TRANSFER), CCommonTransferPage::DialogProc, IDS_SCANNER_TRANSFER_TITLE, IDS_SCANNER_TRANSFER_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDestinationPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_PROGRESS), CCommonProgressPage::DialogProc, IDS_SCANNER_PROGRESS_TITLE, IDS_SCANNER_PROGRESS_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nProgressPageIndex }, { MAKEINTRESOURCE(IDD_UPLOAD_QUERY), CCommonUploadQueryPage::DialogProc, IDS_COMMON_UPLOAD_TITLE, IDS_COMMON_UPLOAD_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nUploadQueryPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_DELETE), CCommonDeleteProgressPage::DialogProc, IDS_COMMON_DELETE_TITLE, IDS_COMMON_DELETE_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDeleteProgressPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_FINISH), CCommonFinishPage::DialogProc, 0, 0, TEXT(""), TEXT(""), LastPage, NULL, &m_nFinishPageIndex } }; // // These are the pages we'll use for the scanner wizard, if it does have an ADF // CPropertyPageInfo ScannerADFPropSheetPageInfo[] = { { MAKEINTRESOURCE(IDD_SCANNER_FIRST), CCommonFirstPage::DialogProc, 0, 0, TEXT(""), TEXT(""), FirstPage, NULL, NULL }, { MAKEINTRESOURCE(IDD_SCANNER_ADF_SELECT), CScannerSelectionPage::DialogProc, IDS_SCANNER_SELECT_TITLE, IDS_SCANNER_SELECT_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nSelectionPageIndex }, { MAKEINTRESOURCE(IDD_SCANNER_TRANSFER), CCommonTransferPage::DialogProc, IDS_SCANNER_TRANSFER_TITLE, IDS_SCANNER_TRANSFER_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDestinationPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_PROGRESS), CCommonProgressPage::DialogProc, IDS_SCANNER_PROGRESS_TITLE, IDS_SCANNER_PROGRESS_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nProgressPageIndex }, { MAKEINTRESOURCE(IDD_UPLOAD_QUERY), CCommonUploadQueryPage::DialogProc, IDS_COMMON_UPLOAD_TITLE, IDS_COMMON_UPLOAD_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nUploadQueryPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_DELETE), CCommonDeleteProgressPage::DialogProc, IDS_COMMON_DELETE_TITLE, IDS_COMMON_DELETE_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDeleteProgressPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_FINISH), CCommonFinishPage::DialogProc, 0, 0, TEXT(""), TEXT(""), LastPage, NULL, &m_nFinishPageIndex } }; // // These are the pages we'll use for the camera wizard // CPropertyPageInfo CameraPropSheetPageInfo[] = { { MAKEINTRESOURCE(IDD_CAMERA_FIRST), CCommonFirstPage::DialogProc, 0, 0, TEXT(""), TEXT(""), FirstPage, NULL, NULL }, { MAKEINTRESOURCE(IDD_CAMERA_SELECT), CCameraSelectionPage::DialogProc, IDS_CAMERA_SELECT_TITLE, IDS_CAMERA_SELECT_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nSelectionPageIndex }, { MAKEINTRESOURCE(IDD_CAMERA_TRANSFER), CCommonTransferPage::DialogProc, IDS_CAMERA_TRANSFER_TITLE, IDS_CAMERA_TRANSFER_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDestinationPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_PROGRESS), CCommonProgressPage::DialogProc, IDS_CAMERA_PROGRESS_TITLE, IDS_CAMERA_PROGRESS_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nProgressPageIndex }, { MAKEINTRESOURCE(IDD_UPLOAD_QUERY), CCommonUploadQueryPage::DialogProc, IDS_COMMON_UPLOAD_TITLE, IDS_COMMON_UPLOAD_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nUploadQueryPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_DELETE), CCommonDeleteProgressPage::DialogProc, IDS_COMMON_DELETE_TITLE, IDS_COMMON_DELETE_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDeleteProgressPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_FINISH), CCommonFinishPage::DialogProc, 0, 0, TEXT(""), TEXT(""), LastPage, NULL, &m_nFinishPageIndex } }; // // These are the pages we'll use for the video wizard // CPropertyPageInfo VideoPropSheetPageInfo[] = { { MAKEINTRESOURCE(IDD_VIDEO_FIRST), CCommonFirstPage::DialogProc, 0, 0, TEXT(""), TEXT(""), FirstPage, NULL, NULL }, { MAKEINTRESOURCE(IDD_VIDEO_SELECT), CCameraSelectionPage::DialogProc, IDS_VIDEO_SELECT_TITLE, IDS_VIDEO_SELECT_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nSelectionPageIndex }, { MAKEINTRESOURCE(IDD_CAMERA_TRANSFER), CCommonTransferPage::DialogProc, IDS_CAMERA_TRANSFER_TITLE, IDS_CAMERA_TRANSFER_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDestinationPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_PROGRESS), CCommonProgressPage::DialogProc, IDS_CAMERA_PROGRESS_TITLE, IDS_CAMERA_PROGRESS_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nProgressPageIndex }, { MAKEINTRESOURCE(IDD_UPLOAD_QUERY), CCommonUploadQueryPage::DialogProc, IDS_COMMON_UPLOAD_TITLE, IDS_COMMON_UPLOAD_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nUploadQueryPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_DELETE), CCommonDeleteProgressPage::DialogProc, IDS_COMMON_DELETE_TITLE, IDS_COMMON_DELETE_SUBTITLE, TEXT(""), TEXT(""), NormalPage, NULL, &m_nDeleteProgressPageIndex }, { MAKEINTRESOURCE(IDD_COMMON_FINISH), CCommonFinishPage::DialogProc, 0, 0, TEXT(""), TEXT(""), LastPage, NULL, &m_nFinishPageIndex } }; // // Initialize all of these variables, which differ depending on which type of device we are loading // LPTSTR pszbmWatermark = NULL; LPTSTR pszbmHeader = NULL; CPropertyPageInfo *pPropSheetPageInfo = NULL; int nPropPageCount = 0; int nWizardIconId = 0; CSimpleString strDownloadManagerTitle = TEXT(""); // // Decide which pages to use. // switch (m_DeviceTypeMode) { case CameraMode: pszbmWatermark = MAKEINTRESOURCE(IDB_CAMERA_WATERMARK); pszbmHeader = MAKEINTRESOURCE(IDB_CAMERA_HEADER); pPropSheetPageInfo = CameraPropSheetPageInfo; nPropPageCount = ARRAYSIZE(CameraPropSheetPageInfo); strDownloadManagerTitle.LoadString( IDS_DOWNLOAD_MANAGER_TITLE, g_hInstance ); nWizardIconId = IDI_CAMERA_WIZARD; break; case VideoMode: pszbmWatermark = MAKEINTRESOURCE(IDB_VIDEO_WATERMARK); pszbmHeader = MAKEINTRESOURCE(IDB_VIDEO_HEADER); pPropSheetPageInfo = VideoPropSheetPageInfo; nPropPageCount = ARRAYSIZE(VideoPropSheetPageInfo); strDownloadManagerTitle.LoadString( IDS_DOWNLOAD_MANAGER_TITLE, g_hInstance ); nWizardIconId = IDI_VIDEO_WIZARD; break; case ScannerMode: DetermineScannerType(); pszbmWatermark = MAKEINTRESOURCE(IDB_SCANNER_WATERMARK); pszbmHeader = MAKEINTRESOURCE(IDB_SCANNER_HEADER); strDownloadManagerTitle.LoadString( IDS_DOWNLOAD_MANAGER_TITLE, g_hInstance ); nWizardIconId = IDI_SCANNER_WIZARD; if (m_nScannerType == ScannerTypeFlatbedAdf) { pPropSheetPageInfo = ScannerADFPropSheetPageInfo; nPropPageCount = ARRAYSIZE(ScannerADFPropSheetPageInfo); } else if (m_nScannerType == ScannerTypeFlatbed) { pPropSheetPageInfo = ScannerPropSheetPageInfo; nPropPageCount = ARRAYSIZE(ScannerPropSheetPageInfo); } else if (m_nScannerType == ScannerTypeScrollFed) { pPropSheetPageInfo = ScannerScrollFedPropSheetPageInfo; nPropPageCount = ARRAYSIZE(ScannerScrollFedPropSheetPageInfo); } else { // // Unknown scanner type // } break; default: return E_INVALIDARG; } HICON hIconSmall=NULL, hIconBig=NULL; if (!SUCCEEDED(WiaUiExtensionHelper::GetDeviceIcons( CSimpleBStr(m_strwDeviceUiClassId), m_nDeviceType, &hIconSmall, &hIconBig ))) { // // Load the icons. They will be set using WM_SETICON in the first pages. // hIconSmall = reinterpret_cast<HICON>(LoadImage( g_hInstance, MAKEINTRESOURCE(nWizardIconId), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR )); hIconBig = reinterpret_cast<HICON>(LoadImage( g_hInstance, MAKEINTRESOURCE(nWizardIconId), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR )); } // // Make copies of these icons to work around NTBUG 351806 // if (hIconSmall) { m_hWizardIconSmall = CopyIcon(hIconSmall); DestroyIcon(hIconSmall); } if (hIconBig) { m_hWizardIconBig = CopyIcon(hIconBig); DestroyIcon(hIconBig); } // // Make sure we have a valid set of data // if (pszbmWatermark && pszbmHeader && pPropSheetPageInfo && nPropPageCount) { const int c_MaxPageCount = 20; HPROPSHEETPAGE PropSheetPages[c_MaxPageCount] = {0}; // // We might not be adding all of the pages. // int nTotalPageCount = 0; for (int nCurrPage=0;nCurrPage<nPropPageCount && nCurrPage<c_MaxPageCount;nCurrPage++) { // // Only add the page if the controlling pbDisplay variable is NULL or points to a non-FALSE value // if (!pPropSheetPageInfo[nCurrPage].pbDisplay || *(pPropSheetPageInfo[nCurrPage].pbDisplay)) { PROPSHEETPAGE CurrentPropSheetPage = {0}; // // Set up all of the required fields from out static info. // CurrentPropSheetPage.dwSize = sizeof(PROPSHEETPAGE); CurrentPropSheetPage.hInstance = g_hInstance; CurrentPropSheetPage.lParam = reinterpret_cast<LPARAM>(this); CurrentPropSheetPage.pfnDlgProc = pPropSheetPageInfo[nCurrPage].pfnDlgProc; CurrentPropSheetPage.pszTemplate = pPropSheetPageInfo[nCurrPage].pszTemplate; CurrentPropSheetPage.pszTitle = strDownloadManagerTitle.String(); CurrentPropSheetPage.dwFlags = PSP_DEFAULT; // // Add in the fusion flags to get COMCTLV6 // WiaUiUtil::PreparePropertyPageForFusion( &CurrentPropSheetPage ); // // If we want to save the index of this page, save it // if (pPropSheetPageInfo[nTotalPageCount].pnPageIndex) { *(pPropSheetPageInfo[nTotalPageCount].pnPageIndex) = nTotalPageCount; } if (FirstPage == pPropSheetPageInfo[nCurrPage].PageType) { // // No title or subtitle needed for "first pages" // CurrentPropSheetPage.dwFlags |= PSP_PREMATURE | PSP_HIDEHEADER | PSP_USETITLE; } else if (LastPage == pPropSheetPageInfo[nCurrPage].PageType) { // // No title or subtitle needed for "last pages" // CurrentPropSheetPage.dwFlags |= PSP_HIDEHEADER | PSP_USETITLE; } else { // // Add header and subtitle // CurrentPropSheetPage.dwFlags |= PSP_PREMATURE | PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE | PSP_USETITLE; // // Load the header and subtitle // LoadString( g_hInstance, pPropSheetPageInfo[nCurrPage].nIdTitle, pPropSheetPageInfo[nCurrPage].szTitle, ARRAYSIZE(pPropSheetPageInfo[nCurrPage].szTitle) ); LoadString( g_hInstance, pPropSheetPageInfo[nCurrPage].nIdSubTitle, pPropSheetPageInfo[nCurrPage].szSubTitle, ARRAYSIZE(pPropSheetPageInfo[nCurrPage].szSubTitle) ); // // Assign the title and subtitle strings // CurrentPropSheetPage.pszHeaderTitle = pPropSheetPageInfo[nCurrPage].szTitle; CurrentPropSheetPage.pszHeaderSubTitle = pPropSheetPageInfo[nCurrPage].szSubTitle; } // // Create and add one more page // HPROPSHEETPAGE hPropSheetPage = CreatePropertySheetPage(&CurrentPropSheetPage); if (!hPropSheetPage) { WIA_PRINTHRESULT((HRESULT_FROM_WIN32(GetLastError()),TEXT("CreatePropertySheetPage failed on page %d"), nCurrPage )); return E_FAIL; } PropSheetPages[nTotalPageCount++] = hPropSheetPage; } } // // Save the count of our pages // m_nWiaWizardPageCount = nTotalPageCount; // // Create the property sheet header // PROPSHEETHEADER PropSheetHeader = {0}; PropSheetHeader.hwndParent = NULL; PropSheetHeader.dwSize = sizeof(PROPSHEETHEADER); PropSheetHeader.dwFlags = PSH_NOAPPLYNOW | PSH_WIZARD97 | PSH_WATERMARK | PSH_HEADER | PSH_USECALLBACK; PropSheetHeader.pszbmWatermark = pszbmWatermark; PropSheetHeader.pszbmHeader = pszbmHeader; PropSheetHeader.hInstance = g_hInstance; PropSheetHeader.nPages = m_nWiaWizardPageCount; PropSheetHeader.phpage = PropSheetPages; PropSheetHeader.pfnCallback = PropSheetCallback; PropSheetHeader.nStartPage = SuppressFirstPage() ? 1 : 0; // // Display the property sheet // INT_PTR nResult = PropertySheet( &PropSheetHeader ); // // Check for an error // if (nResult == -1) { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { // // Generic failure will have to do // hr = E_FAIL; // // Dismiss the wait dialog before we display the message box // if (m_pWiaProgressDialog) { m_pWiaProgressDialog->Destroy(); m_pWiaProgressDialog = NULL; } // // Display an error message telling the user this is not a supported device // CMessageBoxEx::MessageBox( m_hWnd, CSimpleString(IDS_UNSUPPORTED_DEVICE,g_hInstance), CSimpleString(IDS_ERROR_TITLE,g_hInstance), CMessageBoxEx::MBEX_ICONWARNING ); WIA_ERROR((TEXT("Unknown device type"))); } // // Make sure the status dialog has been dismissed by now // if (m_pWiaProgressDialog) { m_pWiaProgressDialog->Destroy(); m_pWiaProgressDialog = NULL; } return hr; } bool CAcquisitionManagerControllerWindow::EnumItemsCallback( CWiaItemList::CEnumEvent EnumEvent, UINT nData, LPARAM lParam, bool bForceUpdate ) { // // We would return false to cancel enumeration // bool bResult = true; // // Get the instance of the controller window // CAcquisitionManagerControllerWindow *pThis = reinterpret_cast<CAcquisitionManagerControllerWindow*>(lParam); if (pThis) { // // Which event are we being called for? // switch (EnumEvent) { case CWiaItemList::ReadingItemInfo: // // This is the event that is sent while the tree is being built // if (pThis->m_pWiaProgressDialog && pThis->m_bUpdateEnumerationCount && nData) { // // We don't want to update the status text any more often than this (minimizes flicker) // const DWORD dwMinDelta = 200; // // Get the current tick count and see if it has been more than dwMinDelta milliseconds since our last update // DWORD dwCurrentTickCount = GetTickCount(); if (bForceUpdate || dwCurrentTickCount - pThis->m_dwLastEnumerationTickCount >= dwMinDelta) { // // Assume we haven't been cancelled // BOOL bCancelled = FALSE; // // Set the progress message // pThis->m_pWiaProgressDialog->SetMessage( CSimpleStringWide().Format( IDS_ENUMERATIONCOUNT, g_hInstance, nData ) ); // // Find out if we've been cancelled // pThis->m_pWiaProgressDialog->Cancelled(&bCancelled); // // If we have been cancelled, we'll return false to stop the enumeration // if (bCancelled) { bResult = false; } // // Save the current tick count for next time // pThis->m_dwLastEnumerationTickCount = dwCurrentTickCount; } } break; } } return bResult; } LRESULT CAcquisitionManagerControllerWindow::OnPostInitialize( WPARAM, LPARAM ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::OnInitialize")); // // Try to get the correct animation for this device type. If we can't get the type, // just use the camera animation. If there is a real error, it will get handled later // int nAnimationType = WIA_PROGRESSDLG_ANIM_CAMERA_COMMUNICATE; LONG nAnimationDeviceType = 0; // // We don't want to update our enumeration count in the progress dialog for scanners, but we do for cameras // m_bUpdateEnumerationCount = true; if (SUCCEEDED(WiaUiUtil::GetDeviceTypeFromId( CSimpleBStr(m_pEventParameters->strDeviceID), &nAnimationDeviceType ))) { if (StiDeviceTypeScanner == GET_STIDEVICE_TYPE(nAnimationDeviceType)) { nAnimationType = WIA_PROGRESSDLG_ANIM_SCANNER_COMMUNICATE; m_bUpdateEnumerationCount = false; } else if (StiDeviceTypeStreamingVideo == GET_STIDEVICE_TYPE(nAnimationDeviceType)) { nAnimationType = WIA_PROGRESSDLG_ANIM_VIDEO_COMMUNICATE; } } // // Put up a wait dialog // HRESULT hr = CoCreateInstance( CLSID_WiaDefaultUi, NULL, CLSCTX_INPROC_SERVER, IID_IWiaProgressDialog, (void**)&m_pWiaProgressDialog ); if (SUCCEEDED(hr)) { m_pWiaProgressDialog->Create( m_hWnd, nAnimationType|WIA_PROGRESSDLG_NO_PROGRESS ); m_pWiaProgressDialog->SetTitle( CSimpleStringConvert::WideString(CSimpleString(IDS_DOWNLOADMANAGER_NAME,g_hInstance))); m_pWiaProgressDialog->SetMessage( CSimpleStringConvert::WideString(CSimpleString(IDS_PROGDLG_MESSAGE,g_hInstance))); // // Show the progress dialog // m_pWiaProgressDialog->Show(); // // Create the global interface table // hr = CoCreateInstance( CLSID_StdGlobalInterfaceTable, NULL, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable, (VOID**)&m_pGlobalInterfaceTable ); if (SUCCEEDED(hr)) { // // Create the device // hr = WIA_FORCE_ERROR(FE_WIAACMGR,100,CreateDevice()); if (SUCCEEDED(hr)) { // // Save a debug snapshot, if the entry is in the registry // WIA_SAVEITEMTREELOG(HKEY_CURRENT_USER,REGSTR_PATH_USER_SETTINGS_WIAACMGR,TEXT("CreateDeviceTreeSnapshot"),true,m_pWiaItemRoot); // // First, figure out what kind of device it is and get the UI class ID // if (PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DIP_DEV_TYPE, m_nDeviceType ) && PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DIP_UI_CLSID, m_strwDeviceUiClassId )) { switch (GET_STIDEVICE_TYPE(m_nDeviceType)) { case StiDeviceTypeScanner: m_DeviceTypeMode = ScannerMode; break; case StiDeviceTypeDigitalCamera: m_DeviceTypeMode = CameraMode; break; case StiDeviceTypeStreamingVideo: m_DeviceTypeMode = VideoMode; break; default: m_DeviceTypeMode = UnknownMode; hr = E_FAIL; break; } } else { hr = E_FAIL; WIA_ERROR((TEXT("Unable to read the device type"))); } if (SUCCEEDED(hr)) { // // Get the device name // PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DIP_DEV_NAME, m_strwDeviceName ); // // Find out if Take Picture is supported // m_bTakePictureIsSupported = WiaUiUtil::IsDeviceCommandSupported( m_pWiaItemRoot, WIA_CMD_TAKE_PICTURE ); // // Enumerate all the items in the device tree // hr = m_WiaItemList.EnumerateAllWiaItems(m_pWiaItemRoot,EnumItemsCallback,reinterpret_cast<LPARAM>(this)); if (S_OK == hr) { if (ScannerMode == m_DeviceTypeMode) { // // Mark only one scanner item as selected, and save it as the current scanner item // MarkAllItemsUnselected( m_WiaItemList.Root() ); CSimpleDynamicArray<CWiaItem*> Items; GetAllImageItems( Items, m_WiaItemList.Root() ); if (Items.Size() && Items[0]) { m_pCurrentScannerItem = Items[0]; MarkItemSelected(Items[0],m_WiaItemList.Root()); // // Make sure we have all of the properties we need to construct the device // hr = WiaUiUtil::VerifyScannerProperties(Items[0]->WiaItem()); } else { hr = E_FAIL; WIA_ERROR((TEXT("There don't seem to be any transfer items on this scanner"))); } } else if (VideoMode == m_DeviceTypeMode || CameraMode == m_DeviceTypeMode) { // // Get the thumbnail width // LONG nWidth, nHeight; if (PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DPC_THUMB_WIDTH, nWidth ) && PropStorageHelpers::GetProperty( m_pWiaItemRoot, WIA_DPC_THUMB_HEIGHT, nHeight )) { int nMax = max(nWidth,nHeight); // Allow for rotation m_sizeThumbnails.cx = max(c_nMinThumbnailWidth,min(nMax,c_nMaxThumbnailWidth)); m_sizeThumbnails.cy = max(c_nMinThumbnailHeight,min(nMax,c_nMaxThumbnailHeight)); } } } } } } } if (!SUCCEEDED(hr)) { // // Dismiss the wait dialog // if (m_pWiaProgressDialog) { m_pWiaProgressDialog->Destroy(); m_pWiaProgressDialog = NULL; } // // Choose an appropriate error message if we have a recognizable error. // CSimpleString strMessage; int nIconId = 0; switch (hr) { case WIA_ERROR_BUSY: strMessage.LoadString( IDS_DEVICE_BUSY, g_hInstance ); nIconId = MB_ICONINFORMATION; break; case WIA_S_NO_DEVICE_AVAILABLE: strMessage.LoadString( IDS_DEVICE_NOT_FOUND, g_hInstance ); nIconId = MB_ICONINFORMATION; break; case HRESULT_FROM_WIN32(ERROR_SERVICE_DISABLED): strMessage = WiaUiUtil::GetErrorTextFromHResult(HRESULT_FROM_WIN32(ERROR_SERVICE_DISABLED)); nIconId = MB_ICONINFORMATION; break; default: strMessage.LoadString( IDS_UNABLETOCREATE, g_hInstance ); nIconId = MB_ICONINFORMATION; break; } // // Tell the user we had a problem creating the device // MessageBox( m_hWnd, strMessage, CSimpleString( IDS_DOWNLOAD_MANAGER_TITLE, g_hInstance ), nIconId ); } else if (S_OK == hr) { hr = CreateAndExecuteWizard(); } // // If we were cancelled, shut down the progress UI // else if (m_pWiaProgressDialog) { m_pWiaProgressDialog->Destroy(); m_pWiaProgressDialog = NULL; } // // Make sure we kill this window, and thus, this thread. // PostMessage( m_hWnd, WM_CLOSE, 0, 0 ); return 0; } LRESULT CAcquisitionManagerControllerWindow::OnCreate( WPARAM, LPARAM lParam ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::OnCreate")); // // Ensure the background thread was started // if (!m_hBackgroundThread || !m_pThreadMessageQueue) { WIA_ERROR((TEXT("There was an error starting the background thread"))); return -1; } // // Make sure we got a valid lParam // LPCREATESTRUCT pCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); if (!pCreateStruct) { WIA_ERROR((TEXT("pCreateStruct was NULL"))); return -1; } // // Get the event parameters // m_pEventParameters = reinterpret_cast<CEventParameters*>(pCreateStruct->lpCreateParams); if (!m_pEventParameters) { WIA_ERROR((TEXT("m_pEventParameters was NULL"))); return -1; } SetForegroundWindow(m_hWnd); // // Center ourselves on the parent window // WiaUiUtil::CenterWindow( m_hWnd, m_pEventParameters->hwndParent ); PostMessage( m_hWnd, PWM_POSTINITIALIZE, 0, 0 ); return 0; } void CAcquisitionManagerControllerWindow::OnNotifyDownloadImage( UINT nMsg, CThreadNotificationMessage *pThreadNotificationMessage ) { CDownloadImagesThreadNotifyMessage *pDownloadImageThreadNotifyMessage = dynamic_cast<CDownloadImagesThreadNotifyMessage*>(pThreadNotificationMessage); if (pDownloadImageThreadNotifyMessage) { switch (pDownloadImageThreadNotifyMessage->Status()) { case CDownloadImagesThreadNotifyMessage::End: { switch (pDownloadImageThreadNotifyMessage->Operation()) { case CDownloadImagesThreadNotifyMessage::DownloadImage: { if (S_OK != pDownloadImageThreadNotifyMessage->hr()) { m_nFailedImagesCount++; } } break; case CDownloadImagesThreadNotifyMessage::DownloadAll: { if (S_OK == pDownloadImageThreadNotifyMessage->hr()) { m_DownloadedFileInformationList = pDownloadImageThreadNotifyMessage->DownloadedFileInformation(); } else { m_DownloadedFileInformationList.Destroy(); } } break; } } break; case CDownloadImagesThreadNotifyMessage::Begin: { switch (pDownloadImageThreadNotifyMessage->Operation()) { case CDownloadImagesThreadNotifyMessage::DownloadAll: { m_nFailedImagesCount = 0; } break; } } break; } } } void CAcquisitionManagerControllerWindow::OnNotifyDownloadThumbnail( UINT nMsg, CThreadNotificationMessage *pThreadNotificationMessage ) { WIA_PUSH_FUNCTION((TEXT("CAcquisitionManagerControllerWindow::OnNotifyDownloadThumbnail( %d, %p )"), nMsg, pThreadNotificationMessage )); CDownloadThumbnailsThreadNotifyMessage *pDownloadThumbnailsThreadNotifyMessage= dynamic_cast<CDownloadThumbnailsThreadNotifyMessage*>(pThreadNotificationMessage); if (pDownloadThumbnailsThreadNotifyMessage) { switch (pDownloadThumbnailsThreadNotifyMessage->Status()) { case CDownloadThumbnailsThreadNotifyMessage::Begin: { } break; case CDownloadThumbnailsThreadNotifyMessage::Update: { } break; case CDownloadThumbnailsThreadNotifyMessage::End: { switch (pDownloadThumbnailsThreadNotifyMessage->Operation()) { case CDownloadThumbnailsThreadNotifyMessage::DownloadThumbnail: { WIA_TRACE((TEXT("Handling CDownloadThumbnailsThreadNotifyMessage::DownloadThumbnail"))); // // Find the item in the list // CWiaItem *pWiaItem = m_WiaItemList.Find( pDownloadThumbnailsThreadNotifyMessage->Cookie() ); if (pWiaItem) { // // Set the flag that indicates we've tried this image already // pWiaItem->AttemptedThumbnailDownload(true); // // Make sure we have valid thumbnail data // if (pDownloadThumbnailsThreadNotifyMessage->BitmapData()) { // // Don't replace existing thumbnail data // if (!pWiaItem->BitmapData()) { // // Set the item's thumbnail data. Take ownership of the thumbnail data // WIA_TRACE((TEXT("Found the thumbnail for the item with the GIT cookie %08X"), pDownloadThumbnailsThreadNotifyMessage->Cookie() )); pWiaItem->BitmapData(pDownloadThumbnailsThreadNotifyMessage->DetachBitmapData()); pWiaItem->Width(pDownloadThumbnailsThreadNotifyMessage->Width()); pWiaItem->Height(pDownloadThumbnailsThreadNotifyMessage->Height()); pWiaItem->BitmapDataLength(pDownloadThumbnailsThreadNotifyMessage->BitmapDataLength()); pWiaItem->ImageWidth(pDownloadThumbnailsThreadNotifyMessage->PictureWidth()); pWiaItem->ImageHeight(pDownloadThumbnailsThreadNotifyMessage->PictureHeight()); pWiaItem->AnnotationType(pDownloadThumbnailsThreadNotifyMessage->AnnotationType()); pWiaItem->DefExt(pDownloadThumbnailsThreadNotifyMessage->DefExt()); } else { WIA_TRACE((TEXT("Already got the image data for item %08X!"), pDownloadThumbnailsThreadNotifyMessage->Cookie())); } } else { WIA_ERROR((TEXT("pDownloadThumbnailsThreadNotifyMessage->BitmapData was NULL!"))); } // // Assign the default format // pWiaItem->DefaultFormat(pDownloadThumbnailsThreadNotifyMessage->DefaultFormat()); // // Assign the access flags // pWiaItem->AccessRights(pDownloadThumbnailsThreadNotifyMessage->AccessRights()); // // Make sure we discard rotation angles if rotation is not possible // pWiaItem->DiscardRotationIfNecessary(); } else { WIA_ERROR((TEXT("Can't find %08X in the item list"), pDownloadThumbnailsThreadNotifyMessage->Cookie() )); } } break; } } break; } } } LRESULT CAcquisitionManagerControllerWindow::OnThreadNotification( WPARAM wParam, LPARAM lParam ) { WIA_PUSH_FUNCTION((TEXT("CAcquisitionManagerControllerWindow::OnThreadNotification( %d, %08X )"), wParam, lParam )); CThreadNotificationMessage *pThreadNotificationMessage = reinterpret_cast<CThreadNotificationMessage*>(lParam); if (pThreadNotificationMessage) { switch (pThreadNotificationMessage->Message()) { case TQ_DOWNLOADTHUMBNAIL: OnNotifyDownloadThumbnail( static_cast<UINT>(wParam), pThreadNotificationMessage ); break; case TQ_DOWNLOADIMAGE: OnNotifyDownloadImage( static_cast<UINT>(wParam), pThreadNotificationMessage ); break; } // // Notify all the registered windows // m_WindowList.SendMessage( m_nThreadNotificationMessage, wParam, lParam ); // // Free the message structure // delete pThreadNotificationMessage; } return HANDLED_THREAD_MESSAGE; } void CAcquisitionManagerControllerWindow::AddNewItemToList( CGenericWiaEventHandler::CEventMessage *pEventMessage ) { WIA_PUSHFUNCTION((TEXT("CAcquisitionManagerControllerWindow::AddNewItemToList"))); // // Check to see if the item is already in our list // CWiaItem *pWiaItem = m_WiaItemList.Find(pEventMessage->FullItemName()); if (pWiaItem) { // // If it is already in our list, just return. // return; } // // Get an IWiaItem interface pointer for this item // CComPtr<IWiaItem> pItem; HRESULT hr = m_pWiaItemRoot->FindItemByName( 0, CSimpleBStr(pEventMessage->FullItemName()).BString(), &pItem ); if (SUCCEEDED(hr) && pItem) { // // Add it to the root of the item tree // m_WiaItemList.Add( NULL, new CWiaItem(pItem) ); } } void CAcquisitionManagerControllerWindow::RequestThumbnailForNewItem( CGenericWiaEventHandler::CEventMessage *pEventMessage ) { WIA_PUSHFUNCTION((TEXT("CAcquisitionManagerControllerWindow::RequestThumbnailForNewItem"))); // // Find the item in our list // CWiaItem *pWiaItem = m_WiaItemList.Find(pEventMessage->FullItemName()); if (pWiaItem) { // // Add this item's cookie to an empty list // CSimpleDynamicArray<DWORD> Cookies; Cookies.Append( pWiaItem->GlobalInterfaceTableCookie() ); if (Cookies.Size()) { // // Reset the cancel event // m_EventThumbnailCancel.Reset(); // // Prepare and send the request // CDownloadThumbnailsThreadMessage *pDownloadThumbnailsThreadMessage = new CDownloadThumbnailsThreadMessage( m_hWnd, Cookies, m_EventThumbnailCancel.Event() ); if (pDownloadThumbnailsThreadMessage) { m_pThreadMessageQueue->Enqueue( pDownloadThumbnailsThreadMessage, CThreadMessageQueue::PriorityNormal ); } } } } LRESULT CAcquisitionManagerControllerWindow::OnEventNotification( WPARAM wParam, LPARAM lParam ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::OnEventNotification")); CGenericWiaEventHandler::CEventMessage *pEventMessage = reinterpret_cast<CGenericWiaEventHandler::CEventMessage *>(lParam); if (pEventMessage) { // // If we got an item created message, add the item to the list // if (pEventMessage->EventId() == WIA_EVENT_ITEM_CREATED) { AddNewItemToList( pEventMessage ); } // // On Disconnect, perform disconnection operations // else if (pEventMessage->EventId() == WIA_EVENT_DEVICE_DISCONNECTED) { DisplayDisconnectMessageAndExit(); } // // Propagate the message to all currently registered windows // m_WindowList.SendMessage( m_nWiaEventMessage, wParam, lParam ); // // Make sure we ask for the new thumbnail *AFTER* we tell the views the item exists // if (pEventMessage->EventId() == WIA_EVENT_ITEM_CREATED) { RequestThumbnailForNewItem( pEventMessage ); } // // If this is a deleted item event, mark this item deleted // if (pEventMessage->EventId() == WIA_EVENT_ITEM_DELETED) { CWiaItem *pWiaItem = m_WiaItemList.Find(pEventMessage->FullItemName()); if (pWiaItem) { pWiaItem->MarkDeleted(); } } // // On a connect event for this device, close the wizard // if (pEventMessage->EventId() == WIA_EVENT_DEVICE_CONNECTED) { if (m_bDisconnected && m_hWndWizard) { PropSheet_PressButton(m_hWndWizard,PSBTN_CANCEL); } } // // Free the event message // delete pEventMessage; } return HANDLED_EVENT_MESSAGE; } LRESULT CAcquisitionManagerControllerWindow::OnPowerBroadcast( WPARAM wParam, LPARAM lParam ) { if (PBT_APMQUERYSUSPEND == wParam) { } return TRUE; } LRESULT CALLBACK CAcquisitionManagerControllerWindow::WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { SC_BEGIN_REFCOUNTED_MESSAGE_HANDLERS(CAcquisitionManagerControllerWindow) { SC_HANDLE_MESSAGE( WM_CREATE, OnCreate ); SC_HANDLE_MESSAGE( WM_DESTROY, OnDestroy ); SC_HANDLE_MESSAGE( PWM_POSTINITIALIZE, OnPostInitialize ); SC_HANDLE_MESSAGE( WM_POWERBROADCAST, OnPowerBroadcast ); } SC_HANDLE_REGISTERED_MESSAGE(m_nThreadNotificationMessage,OnThreadNotification); SC_HANDLE_REGISTERED_MESSAGE(m_nWiaEventMessage,OnEventNotification); SC_END_MESSAGE_HANDLERS(); } bool CAcquisitionManagerControllerWindow::Register( HINSTANCE hInstance ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::Register")); WNDCLASSEX WndClassEx; memset( &WndClassEx, 0, sizeof(WndClassEx) ); WndClassEx.cbSize = sizeof(WNDCLASSEX); WndClassEx.lpfnWndProc = WndProc; WndClassEx.hInstance = hInstance; WndClassEx.hCursor = LoadCursor(NULL,IDC_ARROW); WndClassEx.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); WndClassEx.lpszClassName = ACQUISITION_MANAGER_CONTROLLER_WINDOW_CLASSNAME; BOOL bResult = (::RegisterClassEx(&WndClassEx) != 0); DWORD dw = GetLastError(); return(bResult != 0); } HWND CAcquisitionManagerControllerWindow::Create( HINSTANCE hInstance, CEventParameters *pEventParameters ) { return CreateWindowEx( 0, ACQUISITION_MANAGER_CONTROLLER_WINDOW_CLASSNAME, TEXT("WIA Acquisition Manager Controller Window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, pEventParameters ); } // // Reference counting for our object // STDMETHODIMP_(ULONG) CAcquisitionManagerControllerWindow::AddRef(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::AddRef")); ULONG nRes = InterlockedIncrement(&m_cRef); WIA_TRACE((TEXT("m_cRef: %d"),m_cRef)); return nRes; } STDMETHODIMP_(ULONG) CAcquisitionManagerControllerWindow::Release(void) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::Release")); if (InterlockedDecrement(&m_cRef)==0) { WIA_TRACE((TEXT("m_cRef: 0"))); // // Cause this thread to exit // PostQuitMessage(0); // // Delete this instance of the wizard // delete this; return 0; } WIA_TRACE((TEXT("m_cRef: %d"),m_cRef)); return(m_cRef); } HRESULT CAcquisitionManagerControllerWindow::QueryInterface( REFIID riid, void **ppvObject ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::QueryInterface")); HRESULT hr = S_OK; *ppvObject = NULL; if (IsEqualIID( riid, IID_IUnknown )) { *ppvObject = static_cast<IWizardSite*>(this); reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); } else if (IsEqualIID( riid, IID_IWizardSite )) { *ppvObject = static_cast<IWizardSite*>(this); reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); } else if (IsEqualIID( riid, IID_IServiceProvider )) { *ppvObject = static_cast<IServiceProvider*>(this); reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); } else { WIA_PRINTGUID((riid,TEXT("Unknown interface"))); *ppvObject = NULL; hr = E_NOINTERFACE; } return hr; } // // IWizardSite // HRESULT CAcquisitionManagerControllerWindow::GetPreviousPage(HPROPSHEETPAGE *phPage) { if (!phPage) { return E_INVALIDARG; } *phPage = PropSheet_IndexToPage( m_hWndWizard, m_nUploadQueryPageIndex ); if (*phPage) { return S_OK; } return E_FAIL; } HRESULT CAcquisitionManagerControllerWindow::GetNextPage(HPROPSHEETPAGE *phPage) { if (!phPage) { return E_INVALIDARG; } *phPage = PropSheet_IndexToPage( m_hWndWizard, m_nFinishPageIndex ); if (*phPage) { return S_OK; } return E_FAIL; } HRESULT CAcquisitionManagerControllerWindow::GetCancelledPage(HPROPSHEETPAGE *phPage) { return GetNextPage(phPage); } // // IServiceProvider // HRESULT CAcquisitionManagerControllerWindow::QueryService( REFGUID guidService, REFIID riid, void **ppv ) { WIA_PUSHFUNCTION(TEXT("CAcquisitionManagerControllerWindow::QueryService")); WIA_PRINTGUID((guidService,TEXT("guidService"))); WIA_PRINTGUID((riid,TEXT("riid"))); if (!ppv) { return E_INVALIDARG; } // // Initialize result // *ppv = NULL; if (guidService == SID_PublishingWizard) { } else { } return E_FAIL; } static CSimpleString GetDisplayName( IShellItem *pShellItem ) { CSimpleString strResult; if (pShellItem) { LPOLESTR pszStr = NULL; if (SUCCEEDED(pShellItem->GetDisplayName( SIGDN_FILESYSPATH, &pszStr )) && pszStr) { strResult = CSimpleStringConvert::NaturalString(CSimpleStringWide(pszStr)); CComPtr<IMalloc> pMalloc; if (SUCCEEDED(SHGetMalloc(&pMalloc))) { pMalloc->Free( pszStr ); } } } return strResult; } // // These two functions are needed to use the generic event handler class // void DllAddRef(void) { #if !defined(DBG_GENERATE_PRETEND_EVENT) _Module.Lock(); #endif } void DllRelease(void) { #if !defined(DBG_GENERATE_PRETEND_EVENT) _Module.Unlock(); #endif }
37.966667
218
0.578036
[ "object" ]
ea6f25cba74cdb0c0d4b322f6971270cf04ad68d
13,485
cpp
C++
src/tensors/cpu/sharp/sse_gemm.cpp
hieuhoang/marian-dev
f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2
[ "MIT" ]
13
2020-06-01T13:00:23.000Z
2022-01-29T01:40:40.000Z
src/tensors/cpu/sharp/sse_gemm.cpp
hieuhoang/marian-dev
f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2
[ "MIT" ]
2
2020-10-21T23:38:48.000Z
2021-03-25T05:40:35.000Z
src/tensors/cpu/sharp/sse_gemm.cpp
hieuhoang/marian-dev
f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2
[ "MIT" ]
5
2020-06-05T13:10:40.000Z
2021-01-19T07:37:23.000Z
// Copyright (c) 2017 Microsoft Corporation // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <emmintrin.h> #include <immintrin.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tmmintrin.h> #include <xmmintrin.h> #include <cassert> namespace marian { namespace cpu { namespace int16 { // This is a reference implementation of 16-bit matrix multiplication described // in "Sharp Models on Dull Hardware: Fast and Accurate Neural Machine // Translation Decoding on the CPU". This model is not as fast as the one in the // paper, becuase it uses SSE2 instead of AVX2. AVX2 instructions are only // available on more modern CPUs (Haswell or later). The only difference between // SSE2 and AVX2 is that SSE operates on 128-bit vectors and AVX2 operates on // 256-bit vecetors. So AVX2 can fit 16 16-bit integers intead of 8 8-bit // integers. The algorithm is the same, you just replace these instructions with // their 256-bit counterpart, i.e., _mm256_add_epi32, _mm256_madd_epi16, // _mm256_hadd_epi32, ... Additional improvements can also be made from // unrolling the for loop over num_B_rows in SSE_MatrixMult, which is not done // here for clarity. // *************************************** // ************** IMPORTANT ************** // *************************************** // The biggest "gotcha" when using this type of multiplication is dealing with // overflow related to quantization. It is NOT enough to simply ensure that A // and B fit into 16 bit integers. If A and B are quantized with $n$ bits, the // result of multiplying them together will be quantized to $n^2$ bits. So if // they are near the boundary of the 16-bit mark, then the result will be near // 32-bits and overflow. However, if we use, say, n = 10 bits, then the product // is 20 bits. This gives us 12 bits left over for the accumulation. So as long // as the width of the common dimension is less than 2^12 = 4096, it is // *impossible* to overflow. If we used, say, n = 12 bits, then we have // 32-(12*2) = 8 bits left over. So we *could* overflow if width > 2^8. // // So, the tradeoff is between quantization precision and possibility of // overflow. A good general value is 10 bits, since this gives high precision // (precision is 1/2^10 ~= 0.001, which is more than what's needed for almost // all neural nets), and cannot overflow unless the matrix width is > 4096. // This quantizes floating point values into fixed-point 16-bit integers. // Effectively, we are performing an SSE version of float x = ...; int16_t y = // (int16_t)(quant_mult*x); // // Except that the casting is saturated. However, you should always ensure that // the input fits into a fixed range anyways. I.e., you should ensure that // quant_mult*x fits into the range [-2^15, 2^15]. This should always be // possible because the value you're quantizing will either be NN weights or NN // activations, both of which can be clipped to a fixed range during training. void SSE_Quantize16(const float* input, __m128i* output, float quant_mult, int num_rows, int width) { assert(width % 8 == 0); int num_input_chunks = width / 8; // Fill an SSE float with 4 copies of the quant mult __m128 sse_quant_mult = _mm_set_ps(quant_mult, quant_mult, quant_mult, quant_mult); for(int i = 0; i < num_rows; i++) { const float* input_row = input + i * width; __m128i* output_row = output + i * num_input_chunks; for(int j = 0; j < num_input_chunks; j++) { const float* x = input_row + j * 8; // Process 8 floats at once, since each __m128i can contain 8 16-bit // integers. // Load floats floats into SSE registers. __m128 f_0 = _mm_loadu_ps(x); __m128 f_1 = _mm_loadu_ps(x + 4); // Multiply by quantization factor (e.g., if quant_mult = 1000.0, 0.34291 // --> 342.21) __m128 m_0 = _mm_mul_ps(f_0, sse_quant_mult); __m128 m_1 = _mm_mul_ps(f_1, sse_quant_mult); // Cast float to 32-bit int (e.g., 342.21 --> 342) __m128i i_0 = _mm_cvtps_epi32(m_0); __m128i i_1 = _mm_cvtps_epi32(m_1); // Cast 32-bit int to 16-bit int. You must ensure that these fit into the // 16-bit range by clipping values during training. *(output_row + j) = _mm_packs_epi32(i_0, i_1); } } } // We are multiplying A * B^T, as opposed to A * B. This is important because it // means we can do consecutive memory access on A * B^T which allows to to take // the most advantage of L1 cache. // // B is typically a weight matrix, so it can be pre-processed offline, and // therefore this transpose does not cost anything. A is typically an activation // minibatch matrix. void SSE_MatrixMult16(const __m128i* qA, const __m128i* qB, float* fC, float unquant_mult, int num_A_rows, int num_B_rows, int width) { assert(width % 8 == 0); int sse_width = width / 8; // We do loop unrolling over A. This is *significantly* faster // since B can live in the registers. We are assuming that // A is a multiple of 4, but we can add extra code to handle values of 1, // 2, 3. // // We could also do loop unrolling over B, which adds some additional speedup. // We don't do that for the sake of clarity. // // There are other memory access patterns we could do, e.g., put B on the // outer loop. The justification is that A is typically small enough that it // can live in L1 cache. B is usually a larger weight matrix, so it might not // be able to. However, we are using each element of B four times while it's // still in a register, so caching is not as important. int mult4 = (num_A_rows / 4) * 4; int rest = num_A_rows % 4; int i = 0; for(; i < mult4; i += 4) { const __m128i* A1_row = qA + (i + 0) * sse_width; const __m128i* A2_row = qA + (i + 1) * sse_width; const __m128i* A3_row = qA + (i + 2) * sse_width; const __m128i* A4_row = qA + (i + 3) * sse_width; for(int j = 0; j < num_B_rows; j++) { const __m128i* B_row = qB + j * sse_width; __m128i sum1 = _mm_setzero_si128(); __m128i sum2 = _mm_setzero_si128(); __m128i sum3 = _mm_setzero_si128(); __m128i sum4 = _mm_setzero_si128(); // This is just a simple dot product, unrolled four ways. for(int k = 0; k < sse_width; k++) { __m128i b = *(B_row + k); __m128i a1 = *(A1_row + k); __m128i a2 = *(A2_row + k); __m128i a3 = *(A3_row + k); __m128i a4 = *(A4_row + k); // _mm_madd_epi16 does multiply add on 8 16-bit integers and accumulates // into a four 32-bit register. E.g., a1 = [f1, f2, f3, f4, f5, f6, f7, // h8] (16-bit ints) b1 = [h1, h2, h3, h4, h5, h6, h7, h8] (16-bit ints) // result = [f1*h1 + f2*h2, f3*h3 + f4*h4, f5*h5 + f6*h6, f7*h7 + f8*h8] // (32-bit ints) Then _mm_add_epi32 just effectively does a += on these // 32-bit integers. sum1 = _mm_add_epi32(sum1, _mm_madd_epi16(b, a1)); sum2 = _mm_add_epi32(sum2, _mm_madd_epi16(b, a2)); sum3 = _mm_add_epi32(sum3, _mm_madd_epi16(b, a3)); sum4 = _mm_add_epi32(sum4, _mm_madd_epi16(b, a4)); } // We now have each sum spread across 4 32-bit ints in SSE register, e.g., // sum1 = [r1, r2, r3, r4]. We need to compute r1 + r2 + r3 + r4. // // This uses 'horizontal add' to do that efficiently. The first add gets // us [r1 + r2, r2 + r3, r1 + r2, r2 + r3] Then the second gets us. [r1 + // r2 + r2 + r3, r2 + r3 + r1 + r2, r1 + r2 + r2 + r3, r2 + r3 + r1 + r2] // E.g., each 32-bit in contains the full sum. sum1 = _mm_hadd_epi32(sum1, sum1); sum1 = _mm_hadd_epi32(sum1, sum1); sum2 = _mm_hadd_epi32(sum2, sum2); sum2 = _mm_hadd_epi32(sum2, sum2); sum3 = _mm_hadd_epi32(sum3, sum3); sum3 = _mm_hadd_epi32(sum3, sum3); sum4 = _mm_hadd_epi32(sum4, sum4); sum4 = _mm_hadd_epi32(sum4, sum4); float* C1 = fC + (i + 0) * num_B_rows + j; float* C2 = fC + (i + 1) * num_B_rows + j; float* C3 = fC + (i + 2) * num_B_rows + j; float* C4 = fC + (i + 3) * num_B_rows + j; // Now that we have the full sum in each 32-bit register, we convert them // to an integer with _mm_cvtepi32_ps and take the first one with // _mm_store_ss. We don't use an SSE instruction to unquantize, although // we could. It doesn't really matter since most of the computation is in // the above loop over the width. // // Also note that the memory acceses on C are not consecutive, but this is // a tradeoff that we have to make. We can't have consecutive accesses of // qA, qB, *and* C. But we access qA and qB a lot more so it makes sense // to do it this way. _mm_store_ss(C1, _mm_cvtepi32_ps(sum1)); *(C1) *= unquant_mult; _mm_store_ss(C2, _mm_cvtepi32_ps(sum2)); *(C2) *= unquant_mult; _mm_store_ss(C3, _mm_cvtepi32_ps(sum3)); *(C3) *= unquant_mult; _mm_store_ss(C4, _mm_cvtepi32_ps(sum4)); *(C4) *= unquant_mult; } } if(rest == 1) { const __m128i* A1_row = qA + (i + 0) * sse_width; for(int j = 0; j < num_B_rows; j++) { const __m128i* B_row = qB + j * sse_width; __m128i sum1 = _mm_setzero_si128(); // This is just a simple dot product, unrolled four ways. for(int k = 0; k < sse_width; k++) { __m128i b = *(B_row + k); __m128i a1 = *(A1_row + k); sum1 = _mm_add_epi32(sum1, _mm_madd_epi16(b, a1)); } sum1 = _mm_hadd_epi32(sum1, sum1); sum1 = _mm_hadd_epi32(sum1, sum1); float* C1 = fC + (i + 0) * num_B_rows + j; _mm_store_ss(C1, _mm_cvtepi32_ps(sum1)); *(C1) *= unquant_mult; } } else if(rest == 2) { const __m128i* A1_row = qA + (i + 0) * sse_width; const __m128i* A2_row = qA + (i + 1) * sse_width; for(int j = 0; j < num_B_rows; j++) { const __m128i* B_row = qB + j * sse_width; __m128i sum1 = _mm_setzero_si128(); __m128i sum2 = _mm_setzero_si128(); for(int k = 0; k < sse_width; k++) { __m128i b = *(B_row + k); __m128i a1 = *(A1_row + k); __m128i a2 = *(A2_row + k); sum1 = _mm_add_epi32(sum1, _mm_madd_epi16(b, a1)); sum2 = _mm_add_epi32(sum2, _mm_madd_epi16(b, a2)); } sum1 = _mm_hadd_epi32(sum1, sum1); sum1 = _mm_hadd_epi32(sum1, sum1); sum2 = _mm_hadd_epi32(sum2, sum2); sum2 = _mm_hadd_epi32(sum2, sum2); float* C1 = fC + (i + 0) * num_B_rows + j; float* C2 = fC + (i + 1) * num_B_rows + j; _mm_store_ss(C1, _mm_cvtepi32_ps(sum1)); *(C1) *= unquant_mult; _mm_store_ss(C2, _mm_cvtepi32_ps(sum2)); *(C2) *= unquant_mult; } } else if(rest == 3) { const __m128i* A1_row = qA + (i + 0) * sse_width; const __m128i* A2_row = qA + (i + 1) * sse_width; const __m128i* A3_row = qA + (i + 2) * sse_width; for(int j = 0; j < num_B_rows; j++) { const __m128i* B_row = qB + j * sse_width; __m128i sum1 = _mm_setzero_si128(); __m128i sum2 = _mm_setzero_si128(); __m128i sum3 = _mm_setzero_si128(); for(int k = 0; k < sse_width; k++) { __m128i b = *(B_row + k); __m128i a1 = *(A1_row + k); __m128i a2 = *(A2_row + k); __m128i a3 = *(A3_row + k); sum1 = _mm_add_epi32(sum1, _mm_madd_epi16(b, a1)); sum2 = _mm_add_epi32(sum2, _mm_madd_epi16(b, a2)); sum3 = _mm_add_epi32(sum3, _mm_madd_epi16(b, a3)); } sum1 = _mm_hadd_epi32(sum1, sum1); sum1 = _mm_hadd_epi32(sum1, sum1); sum2 = _mm_hadd_epi32(sum2, sum2); sum2 = _mm_hadd_epi32(sum2, sum2); sum3 = _mm_hadd_epi32(sum3, sum3); sum3 = _mm_hadd_epi32(sum3, sum3); float* C1 = fC + (i + 0) * num_B_rows + j; float* C2 = fC + (i + 1) * num_B_rows + j; float* C3 = fC + (i + 2) * num_B_rows + j; _mm_store_ss(C1, _mm_cvtepi32_ps(sum1)); *(C1) *= unquant_mult; _mm_store_ss(C2, _mm_cvtepi32_ps(sum2)); *(C2) *= unquant_mult; _mm_store_ss(C3, _mm_cvtepi32_ps(sum3)); *(C3) *= unquant_mult; } } } } // namespace int16 } // namespace cpu } // namespace marian
39.429825
80
0.628254
[ "model" ]
ea70a6b93ea45f68fc9ccabd66934b0387148c10
4,499
hpp
C++
src/framework/protocol/carrier.hpp
deepgrace/carrier
64e37cb426c4b0d8fc97902347fb056b6925c3ed
[ "BSL-1.0" ]
23
2019-04-02T07:47:30.000Z
2022-03-15T03:32:42.000Z
src/framework/protocol/carrier.hpp
deepgrace/carrier
64e37cb426c4b0d8fc97902347fb056b6925c3ed
[ "BSL-1.0" ]
null
null
null
src/framework/protocol/carrier.hpp
deepgrace/carrier
64e37cb426c4b0d8fc97902347fb056b6925c3ed
[ "BSL-1.0" ]
6
2018-12-12T09:18:31.000Z
2021-08-11T07:51:20.000Z
// // Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/deepgrace/carrier // #ifndef CARRIER_HPP #define CARRIER_HPP #include <memory> #include <vector> #include <cstddef> #include <protocol.hpp> using byte_t = std::byte; using buffer_t = std::vector<byte_t>; inline constexpr size_t header_size() { return sizeof(protocol); } inline constexpr size_t length_size() { return sizeof(length_t); } template <typename ProtocolBuffer> class carrier { public: using protocol_t = std::shared_ptr<protocol>; using message_t = std::shared_ptr<ProtocolBuffer>; carrier() : header_(std::make_shared<protocol>()), message_(std::make_shared<ProtocolBuffer>()) { } message_t message() { return message_; } void set_message(message_t message) { message_ = message; } protocol_t header() { return header_; } void set_header(protocol_t header) { header_ = header; } length_t decode_header(buffer_t& buffer) { size_t i = 0; auto mark = header_->mark(); mark[0] = std::to_integer<char>(buffer[i++]); mark[1] = std::to_integer<char>(buffer[i++]); header_->set_version(std::to_integer<uint8_t>(buffer[i++])); header_->set_crypt(std::to_integer<uint8_t>(buffer[i++])); length_t bytes_transferred = to_size<length_t>(buffer, i); header_->set_length(bytes_transferred); header_->set_mode(std::to_integer<uint8_t>(buffer[i++])); header_->set_type(std::to_integer<uint8_t>(buffer[i++])); header_->set_service(to_size<uint16_t>(buffer, i)); header_->set_agent(to_size<uint16_t>(buffer, i)); header_->set_error(to_size<uint16_t>(buffer, i)); header_->set_seq(to_size<uint32_t>(buffer, i)); header_->set_res(to_size<uint32_t>(buffer, i)); buffer.resize(header_size() + bytes_transferred); return bytes_transferred; } bool decode_message(const buffer_t& buffer) { return message_->ParseFromArray(std::addressof(buffer[header_size()]), buffer.size() - header_size()); } void pack(buffer_t& buffer) { length_t bytes_transferred = message_->ByteSizeLong(); header_->set_length(bytes_transferred); buffer.resize(header_size() + bytes_transferred); encode_header(buffer); message_->SerializeToArray(std::addressof(buffer[header_size()]), bytes_transferred); } private: template <typename T> T to_size(const buffer_t& buffer, size_t& i) { T size = 0; for (size_t j = 0; j != sizeof(T); ++j) size = (size << 8) + (std::to_integer<T>(buffer[i++]) & 0xFF); return size; } template <typename T, typename B> void to_byte(buffer_t& buffer, size_t& i, T value) { for (size_t j = 0; j != sizeof(T); ++j) buffer[i++] = static_cast<B>((value >> ((sizeof(T) - j - 1) * 8)) & 0xFF); } void encode_header(buffer_t& buffer) { size_t i = 0; auto mark = header_->mark(); buffer[i++] = static_cast<byte_t>(mark[0]); buffer[i++] = static_cast<byte_t>(mark[1]); buffer[i++] = static_cast<byte_t>(header_->version()); buffer[i++] = static_cast<byte_t>(header_->crypt()); to_byte<length_t, byte_t>(buffer, i, header_->length()); buffer[i++] = static_cast<byte_t>(header_->mode()); buffer[i++] = static_cast<byte_t>(header_->type()); to_byte<uint16_t, byte_t>(buffer, i, header_->service()); to_byte<uint16_t, byte_t>(buffer, i, header_->agent()); to_byte<uint16_t, byte_t>(buffer, i, header_->error()); to_byte<length_t, byte_t>(buffer, i, header_->seq()); to_byte<length_t, byte_t>(buffer, i, header_->res()); } private: protocol_t header_; message_t message_; }; #endif
32.366906
114
0.572572
[ "vector" ]
ea74a3857a2d5b486c5f2277abdccb13fa60b8cb
1,108
cpp
C++
HackerBlocks/More/ROTATE THE MATRIX - ADHOC - HACKERBLOCKS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
HackerBlocks/More/ROTATE THE MATRIX - ADHOC - HACKERBLOCKS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
HackerBlocks/More/ROTATE THE MATRIX - ADHOC - HACKERBLOCKS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// https://csacademy.com/contest/archive/task/matrix_rotations/statement/ #include<bits/stdc++.h> #include<unordered_set> using namespace std; #define fio ios_base::sync_with_stdio(false) #define ll long long int #define s(x) scanf("%lld",&x) #define s2(x,y) s(x)+s(y) #define s3(x,y,z) s(x)+s(y)+s(z) #define p(x) printf("%lld\n",x) #define p2(x,y) p(x)+p(y) #define p3(x,y,z) p(x)+p(y)+p(z) #define F(i,a,b) for(ll i = (ll)(a); i <= (ll)(b); i++) #define RF(i,a,b) for(ll i = (ll)(a); i >= (ll)(b); i--) #define ff first #define ss second #define mp(x,y) make_pair(x,y) #define pll pair<ll,ll> #define pb push_back ll inf = 1e18; ll mod = 1e9 + 7 ; ll gcd(ll a , ll b){return b==0?a:gcd(b,a%b);} int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ll t=1; //s(t); while(t--){ ll n; s(n); vector<vector<ll>> a(n+1); F(i,1,n){ a[i].resize(n+1); F(j,1,n){ cin>>a[i][j]; } } F(i,1,n){ F(j,1,n){ // Basic Observation ll res = a[i][j]|a[j][n-i+1]|a[n-j+1][i]|a[n-i+1][n-j+1]; cout<<res<<" "; } cout<<endl; } } }
19.785714
73
0.555054
[ "vector" ]
ea79c660eff3d54d76d4d5eb74f0ed8fb3c358cc
4,600
cpp
C++
vlp16-viewer/src/velodyne_driver/driver.cpp
jdj2261/Velodyne-Object-Clustering
14dde5e96490e6f1e83799babca702b7a6d3b128
[ "MIT" ]
2
2021-08-04T04:26:04.000Z
2021-12-07T15:07:20.000Z
vlp16-viewer/src/velodyne_driver/driver.cpp
jdj2261/Velodyne-Object-Clustering
14dde5e96490e6f1e83799babca702b7a6d3b128
[ "MIT" ]
1
2021-05-20T02:30:36.000Z
2021-05-20T02:30:36.000Z
vlp16-viewer/src/velodyne_driver/driver.cpp
jdj2261/velodyne-object-clustering
14dde5e96490e6f1e83799babca702b7a6d3b128
[ "MIT" ]
null
null
null
/** @author Dae Jong Jin ** @date 2021. 05. 15 ** @file Velodyne 3D LIDAR data driver classes */ #include "velodyne_driver/driver.h" #include <iostream> #include <cmath> #include <vector> #include <fcntl.h> namespace velodyne_driver { void VelodyneDriver::init_driver() { config_.model = "VLP16"; std::string model_full_name("VLP-16"); std::string deviceName(std::string("Velodyne ") + model_full_name); config_.rpm = 600; double frequency(config_.rpm / 60.0); config_.npackets = static_cast<u_int16_t>(ceil(packet_rate_ / frequency)) ; // Convert cut_angle from radian to one-hundredth degree, config_.cut_angle = int((cut_angle_*360/(2*M_PI))*100); print_driver_info(deviceName); config_.time_offset = 0.0; if (pcap_file_ != "") input_.reset(new velodyne_driver::InputPCAP(port_, packet_rate_, pcap_file_)); else input_.reset(new velodyne_driver::InputSocket(port_)); trans_.reset(new velodyne_pointcloud::Transfrom); } void VelodyneDriver::print_driver_info(const std::string &name) { std::cout << "******** velodyne driver Info *********" << std::endl; std::cout << "Name : " << name << std::endl; std::cout <<"publishing " << config_.npackets << " packets per scan"<<std::endl; if (cut_angle_ < 0.0) std::cout<<"Cut at specific angle feature deactivated."<< std::endl; else if (cut_angle_ < (2 * std::asin(1))) { std::cout<<"Cut at specific angle feature activated. "<<std::endl; std::cout<<"Cutting velodyne points always at %f " << cut_angle_ << " rad."<<std::endl; } else { std::cout<<"cut_angle parameter is out of range. Allowed range is "<<std::endl; std::cout<<"between 0.0 and 2*PI or negative values to deactivate this feature."<<std::endl; cut_angle_ = -0.01; } } bool VelodyneDriver::poll(velodyne_pcl::pointcloud::Ptr &cloud) { // Allocate a new shared pointer for zero-copy sharing with other nodelets. std::vector<VelodynePacket> scan_packets; //InputSocket* input_ = new InputSocket(DATA_PORT_NUMBER); //velodyne_pointcloud::Convert conv; if( config_.cut_angle >= 0) //Cut at specific angle feature enabled { scan_packets.reserve(config_.npackets); VelodynePacket tmp_packet; while(true) { while(true) { int rc = input_->getPacket(&tmp_packet, config_.time_offset); if (rc == 0) break; // got a full packet? if (rc < 0) return false; // end of file reached? } scan_packets.emplace_back(tmp_packet); // Extract base rotation of first block in packet std::size_t azimuth_data_pos = 100*0+2; u_int8_t azimuth = *(static_cast<u_int8_t*>(&tmp_packet.data[azimuth_data_pos])); //if first packet in scan, there is no "valid" last_azimuth_ if (last_azimuth_ == -1) { last_azimuth_ = azimuth; continue; } if((last_azimuth_ < config_.cut_angle && config_.cut_angle <= azimuth) || ( config_.cut_angle <= azimuth && azimuth < last_azimuth_) || (azimuth < last_azimuth_ && last_azimuth_ < config_.cut_angle)) { last_azimuth_ = azimuth; break; // Cut angle passed, one full revolution collected } last_azimuth_ = azimuth; } } else // standard behaviour { // Since the velodyne delivers data at a very high rate, keep // reading and publishing scans as fast as possible. scan_packets.resize(config_.npackets); for (int i = 0; i < config_.npackets; ++i) { while (true) { // keep reading until full packet received int rc = input_->getPacket(&scan_packets[i], config_.time_offset); if (rc == 0) break; // got a full packet? if (rc < 0) return false; // end of file reached? } } } trans_->processScan(scan_packets, cloud); return true; } } // namespace velodyne_driver
38.983051
104
0.548478
[ "vector", "model", "3d" ]
ea848959b651eb04effc25ad9efb7eb497ef2025
2,248
cc
C++
deploy/lite_shitu/src/vector_search.cc
PaddlePaddle/PaddleImgClass
f5265a1f2ab7aa113ae5245223f0528e3239a5e7
[ "Apache-2.0" ]
7
2020-03-30T04:32:01.000Z
2020-03-30T07:51:00.000Z
deploy/lite_shitu/src/vector_search.cc
PaddlePaddle/PaddleClassification
51c1bdb27af15441995bf9840f7020cca9b7d9a8
[ "Apache-2.0" ]
null
null
null
deploy/lite_shitu/src/vector_search.cc
PaddlePaddle/PaddleClassification
51c1bdb27af15441995bf9840f7020cca9b7d9a8
[ "Apache-2.0" ]
1
2020-04-07T17:03:24.000Z
2020-04-07T17:03:24.000Z
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "include/vector_search.h" #include <cstdio> #include <faiss/index_io.h> #include <fstream> #include <iostream> #include <regex> namespace PPShiTu { // load the vector.index void VectorSearch::LoadIndexFile() { std::string file_path = this->index_dir + OS_PATH_SEP + "vector.index"; const char *fname = file_path.c_str(); this->index = faiss::read_index(fname, 0); } // load id_map.txt void VectorSearch::LoadIdMap() { std::string file_path = this->index_dir + OS_PATH_SEP + "id_map.txt"; std::ifstream in(file_path); std::string line; std::vector<std::string> m_vec; if (in) { while (getline(in, line)) { std::regex ws_re("\\s+"); std::vector<std::string> v( std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1), std::sregex_token_iterator()); if (v.size() != 2) { std::cout << "The number of element for each line in : " << file_path << "must be 2, exit the program..." << std::endl; exit(1); } else this->id_map.insert(std::pair<long int, std::string>( std::stol(v[0], nullptr, 10), v[1])); } } } // doing search const SearchResult &VectorSearch::Search(float *feature, int query_number) { this->D.resize(this->return_k * query_number); this->I.resize(this->return_k * query_number); this->index->search(query_number, feature, return_k, D.data(), I.data()); this->sr.return_k = this->return_k; this->sr.D = this->D; this->sr.I = this->I; return this->sr; } const std::string &VectorSearch::GetLabel(faiss::Index::idx_t ind) { return this->id_map.at(ind); } }
33.552239
77
0.66548
[ "vector" ]
ea8cb2e6041692a5d1eaa936b04ac2a61f60a230
4,195
cpp
C++
geometry/3d/tetra.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
geometry/3d/tetra.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
geometry/3d/tetra.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #include "tetra.h" #include "../mesh/polygon_mesh.h" using namespace so_geo ; using namespace so_geo::so_3d ; //************************************************************************************* so_geo::result tetra::make( polygon_mesh_ptr_t m_out_ptr, input_params_cref_t ip ) { if( so_core::is_nullptr(m_out_ptr) ) return so_geo::invalid_argument ; so_geo::polygon_mesh m ; m.position_format = so_geo::vector_component_format::xyz ; m.normal_format = so_geo::vector_component_format::xyz ; m.texcoord_format = so_geo::texcoord_component_format::uv ; so_math::vec3f_t const c_positions[] = { so_math::vec3f_t{ -1.0f, -1.0f, -1.0f }, // bottom left so_math::vec3f_t{ 1.0f, -1.0f, -1.0f }, // bottom right so_math::vec3f_t{ 0.0f, -1.0f, 1.0f }, // bottom back so_math::vec3f_t{ 0.0f, 1.0f, 0.0f } // tip } ; so_math::vec3f_t const c_normals[] = { so_math::vec3f_t{ -0.5f, 0.5f, 0.5f }, // left so_math::vec3f_t{ 0.5f, 0.5f, 0.5f }, // right so_math::vec3f_t{ 0.0f, 0.5f, -0.5f }, // front so_math::vec3f_t{ 0.0f, -1.0f, 0.0f } // bottom } ; so_math::vec2f_t const c_tex[] = { so_math::vec2f_t{ +0.0f, +0.0f }, // front so_math::vec2f_t{ +1.0f, +0.0f }, // front so_math::vec2f_t{ +0.0f, +1.0f } // front } ; // vertices { m.positions.resize( 12 ) ; m.normals.resize( 1 ) ; m.normals[0].resize( 12 ) ; m.texcoords.resize( 1 ) ; m.texcoords[0].resize( 12 ) ; for( size_t i = 0; i < 4; ++i ) { size_t const i3 = i * 3 ; size_t const i2 = i * 2 ; { m.positions[i3 + 0] = c_positions[i].x() ; m.positions[i3 + 1] = c_positions[i].y() ; m.positions[i3 + 2] = c_positions[i].z() ; } { m.normals[0][i3 + 0] = c_normals[i].x() ; m.normals[0][i3 + 1] = c_normals[i].y() ; m.normals[0][i3 + 2] = c_normals[i].z() ; } { m.texcoords[0][i2 + 0] = c_tex[i].x() ; m.texcoords[0][i2 + 1] = c_tex[i].y() ; } } } // indices { struct vertex { uint_t pos_i ; uint_t nrm_i ; uint_t tex_i ; }; std::vector<vertex> vertices( 24 ) ; // bottom vertices[0] = vertex{ 0, 3, 0 } ; vertices[1] = vertex{ 1, 3, 1 } ; vertices[2] = vertex{ 2, 3, 2 } ; // front vertices[3] = vertex{ 0, 2, 0 } ; vertices[4] = vertex{ 1, 2, 1 } ; vertices[5] = vertex{ 3, 2, 2 } ; // left vertices[6] = vertex{ 2, 0, 0 } ; vertices[7] = vertex{ 0, 0, 1 } ; vertices[8] = vertex{ 3, 0, 2 } ; // right vertices[9] = vertex{ 1, 1, 0 } ; vertices[10] = vertex{ 2, 1, 1 } ; vertices[11] = vertex{ 3, 1, 2 } ; // polygons { m.polygons.resize( 4 ) ; m.polygons[0] = 3 ; m.polygons[1] = 3 ; m.polygons[2] = 3 ; m.polygons[3] = 3 ; } // positions indices { m.indices.resize( 12 ) ; for( size_t i = 0; i < 12; ++i ) { m.indices[i] = vertices[i].pos_i ; } } // normal indices { m.normals_indices.resize( 1 ) ; m.normals_indices[0].resize( 12 ) ; for( size_t i = 0; i < 12; ++i ) { m.normals_indices[0][i] = vertices[i].nrm_i ; } } // texcoords indices { m.texcoords_indices.resize( 1 ) ; m.texcoords_indices[0].resize( 12 ) ; for( size_t i = 0; i < 12; ++i ) { m.texcoords_indices[0][i] = vertices[i].tex_i ; } } } *m_out_ptr = std::move( m ) ; return so_geo::ok ; }
26.719745
87
0.442908
[ "mesh", "vector" ]
ea8d09e516f1a579a47922986a34d4141334b71d
20,087
cpp
C++
libtang/src/Bitstream.cpp
TechnoMancer/prjtang
ffce01342c4fa301d408089d419a2c1ee391b599
[ "ISC" ]
6
2019-12-06T14:31:57.000Z
2019-12-06T23:24:20.000Z
libtang/src/Bitstream.cpp
TechnoMancer/prjtang
ffce01342c4fa301d408089d419a2c1ee391b599
[ "ISC" ]
null
null
null
libtang/src/Bitstream.cpp
TechnoMancer/prjtang
ffce01342c4fa301d408089d419a2c1ee391b599
[ "ISC" ]
null
null
null
#include "Bitstream.hpp" #include <bitset> #include <boost/algorithm/string/predicate.hpp> #include <cstring> #include <iostream> namespace Tang { // Add a single byte to the running CRC16 accumulator void Crc16::update_crc16(uint8_t val) { int bit_flag; for (int i = 7; i >= 0; i--) { bit_flag = crc16 >> 15; /* Get next bit: */ crc16 <<= 1; crc16 |= (val >> i) & 1; // item a) work from the least significant bits /* Cycle check: */ if (bit_flag) crc16 ^= CRC16_POLY; } } uint16_t Crc16::finalise_crc16() { // item b) "push out" the last 16 bits uint16_t crc = crc16; int i; bool bit_flag; for (i = 0; i < 16; ++i) { bit_flag = bool(crc >> 15); crc <<= 1; if (bit_flag) crc ^= CRC16_POLY; } return crc; } void Crc16::reset_crc16(uint16_t init) { crc16 = init; } uint16_t Crc16::calc(const std::vector<uint8_t> &data, int start, int end) { reset_crc16(CRC16_INIT); for (int i = start; i < end; i++) update_crc16(data[i]); return finalise_crc16(); } uint16_t Crc16::update_block(const std::vector<uint8_t> &data, int start, int end) { for (int i = start; i < end; i++) update_crc16(data[i]); return finalise_crc16(); } Bitstream::Bitstream(const std::vector<uint8_t> &data, const std::vector<std::string> &metadata) : data(data), metadata(metadata), cpld(false), fuse_started(false), deviceid(0x12006c31) { } Bitstream Bitstream::read(std::istream &in) { std::vector<uint8_t> bytes; std::vector<std::string> meta; auto hdr1 = uint8_t(in.get()); auto hdr2 = uint8_t(in.get()); if (hdr1 != 0x23 || hdr2 != 0x20) { throw BitstreamParseError("Anlogic .BIT files must start with comment", 0); } std::string temp; uint8_t c; in.seekg(0, in.beg); while ((c = uint8_t(in.get())) != 0x00) { if (in.eof()) throw BitstreamParseError("Encountered end of file before start of bitstream data"); if (c == '\n') { meta.push_back(temp); temp = ""; } else { temp += char(c); } } size_t start_pos = size_t(in.tellg()) - 1; in.seekg(0, in.end); size_t length = size_t(in.tellg()) - start_pos; in.seekg(start_pos, in.beg); bytes.resize(length); in.read(reinterpret_cast<char *>(&(bytes[0])), length); return Bitstream(bytes, meta); } std::string Bitstream::vector_to_string(const std::vector<uint8_t> &data) { std::ostringstream os; for (size_t i = 0; i < data.size(); i++) { os << std::hex << std::setw(2) << std::setfill('0') << int(data[i]); } return os.str(); } #define BIN(byte) \ (byte & 0x80 ? '1' : '0'), (byte & 0x40 ? '1' : '0'), (byte & 0x20 ? '1' : '0'), (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), (byte & 0x04 ? '1' : '0'), (byte & 0x02 ? '1' : '0'), (byte & 0x01 ? '1' : '0') void Bitstream::parse_command(const uint8_t command, const uint16_t size, const std::vector<uint8_t> &data, const uint16_t crc16) { switch (command) { case 0xf0: // JTAG ID if (verbose) printf("0xf0 DEVICEID:%s\n", vector_to_string(data).c_str()); deviceid = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; break; case 0xc1: if (verbose) printf("0xc1 VERSION:%02x UCODE:00000000%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", data[0], BIN(data[1]), BIN(data[2]), BIN(data[3])); break; case 0xc2: if (verbose) printf("0xc2 hswapen %c mclk_freq_div %c%c%c%c%c unk %c%c active_done %c unk %c%c%c cascade_mode %c%c " "security " "%c unk %c auto_clear_en %c unk %c%c persist_bit %c UNK %c%c%c%c%c%c%c%c%c%c%c close_osc %c\n", BIN(data[0]), BIN(data[1]), BIN(data[2]), BIN(data[3])); break; case 0xc3: if (verbose) printf("0xc3 UNK %c%c%c%c%c PLL %c%c%c%c unk %c%c%c done_sync %c pll_lock_wait %c%c%c%c done_phase %c%c%c " "goe_phase %c%c%c gsr_phase %c%c%c gwd_phase %c%c%c usr_gsrn_en %c gsrn_sync_sel %c UNK %c\n", BIN(data[0]), BIN(data[1]), BIN(data[2]), BIN(data[3])); break; case 0xc7: if (verbose) printf("0xc7 FRAMES:%d BYTES_PER_FRAME:%d (%d bits)\n", (data[0] * 256 + data[1]), (data[2] * 256 + data[3]), (data[2] * 256 + data[3]) * 8); frames = data[0] * 256 + data[1]; frame_bytes = data[2] * 256 + data[3]; break; case 0xc8: if (verbose) printf("0xc8 BYTES_PER_MEM_FRAME:%d (%d bits)\n", (data[2] * 256 + data[3]), (data[2] * 256 + data[3]) * 8); mem_frame_bytes = data[2] * 256 + data[3]; break; case 0xf1: if (verbose) printf("0xf1 set CRC16 to :%04x\n", (data[0] * 256 + data[1])); crc.reset_crc16(data[0] * 256 + data[1]); break; case 0xf7: if (verbose) printf("0xf7 DONE\n"); break; case 0xf3: case 0xc4: case 0xc5: case 0xca: if (verbose) printf("0x%02x [%04x] [crc %04x]:%s \n", command, size, crc16, vector_to_string(data).c_str()); break; default: std::ostringstream os; os << "Unknown command in bitstream " << std::hex << std::setw(2) << std::setfill('0') << int(command); throw BitstreamParseError(os.str()); } } void Bitstream::parse_command_cpld(const uint8_t command, const uint16_t size, const std::vector<uint8_t> &data, const uint16_t crc16) { switch (command) { case 0x90: // JTAG ID cpld = true; if (verbose) printf("0x90 DEVICEID:%s\n", vector_to_string(std::vector<uint8_t>(data.begin() + 3, data.end())).c_str()); deviceid = (data[3] << 24) + (data[4] << 16) + (data[5] << 8) + data[6]; frame_bytes = 86; // for elf_3/6 break; case 0xa8: if (verbose) printf("0xa8 set CRC16 to :%04x\n", (data[2] * 256 + data[3])); crc.reset_crc16(data[2] * 256 + data[3]); break; case 0xa1: case 0xa3: case 0xac: case 0xb1: case 0xc4: if (verbose) printf("0x%02x [%04x] [crc %04x]:%s \n", command, size, crc16, vector_to_string(data).c_str()); break; default: std::ostringstream os; os << "Unknown command in bitstream " << std::hex << std::setw(2) << std::setfill('0') << int(command); throw BitstreamParseError(os.str()); } } void Bitstream::parse_block(const std::vector<uint8_t> &data) { Crc16 crc; if (verbose) printf("block:%s\n", vector_to_string(data).c_str()); switch (data[0]) { // Common section case 0xff: // all 0xff header break; case 0xcc: if (data[1] == 0x55 && data[2] == 0xaa && data[3] == 0x33) { // proper header } break; case 0xc4: { if (cpld) { uint16_t size = data.size() - 3; uint16_t crc16 = (data[data.size() - 2] << 8) + data[data.size() - 1]; uint16_t calc_crc16 = crc.calc(data, 0, data.size() - 2); if (crc16 != calc_crc16) throw BitstreamParseError("CRC16 error"); parse_command_cpld(data[0], size, std::vector<uint8_t>(data.begin() + 1, data.begin() + 1 + size), crc16); } else { uint8_t flags = data[1]; uint16_t size = (data[2] << 8) + data[3]; uint16_t crc16 = (data[4 + size - 2] << 8) + data[4 + size - 1]; uint16_t calc_crc16 = crc.calc(data, 0, data.size() - 2); if (crc16 != calc_crc16) throw BitstreamParseError("CRC16 error"); if (flags != 0) throw BitstreamParseError("Byte after command should be zero"); parse_command(data[0], size, std::vector<uint8_t>(data.begin() + 4, data.begin() + 4 + size - 2), crc16); } } break; // CPLD section case 0xaa: if (data[1] == 0x00) { data_blocks = (data[2] << 8) + data[3]; } break; case 0xac: case 0xb1: case 0x90: case 0xa1: case 0xa8: case 0xa3: { uint16_t size = data.size() - 3; uint16_t crc16 = (data[data.size() - 2] << 8) + data[data.size() - 1]; uint16_t calc_crc16 = crc.calc(data, 0, data.size() - 2); if (crc16 != calc_crc16) throw BitstreamParseError("CRC16 error"); parse_command_cpld(data[0], size, std::vector<uint8_t>(data.begin() + 1, data.begin() + 1 + size), crc16); } break; // FPGA section case 0xec: if (data[1] == 0xf0) { data_blocks = (data[2] << 8) + data[3] + 1; if (((data[2] << 8) + data[3]) == frames) fuse_started = true; } break; case 0xf0: case 0xf1: case 0xf3: case 0xf7: case 0xc1: case 0xc2: case 0xc3: case 0xc5: case 0xc7: case 0xc8: case 0xca: { uint8_t flags = data[1]; uint16_t size = (data[2] << 8) + data[3]; uint16_t crc16 = (data[4 + size - 2] << 8) + data[4 + size - 1]; uint16_t calc_crc16 = crc.calc(data, 0, data.size() - 2); if (crc16 != calc_crc16) throw BitstreamParseError("CRC16 error"); if (flags != 0) throw BitstreamParseError("Byte after command should be zero"); parse_command(data[0], size, std::vector<uint8_t>(data.begin() + 4, data.begin() + 4 + size - 2), crc16); } break; default: break; } } void Bitstream::parse(bool verbose_info, bool verbose_data) { size_t pos = 0; data_blocks = 0; verbose = verbose_info; crc.reset_crc16(); do { uint16_t len = (data[pos++] << 8); len += data[pos++]; if ((len & 7) != 0) throw BitstreamParseError("Invalid size value in bitstream"); len >>= 3; if ((pos + len) > data.size()) throw BitstreamParseError("Invalid data in bitstream"); std::vector<uint8_t> block = std::vector<uint8_t>(data.begin() + pos, data.begin() + pos + len); blocks.push_back(block); if (data_blocks == 0) { crc.update_block(block, 0, block.size()); parse_block(block); if (fuse_started) { fuse_start_block = blocks.size(); fuse_started = false; } } else { if (verbose_data) printf("data:%s\n", vector_to_string(block).c_str()); if (frame_bytes > block.size()) { crc.update_block(block, 0, block.size()); } else { uint16_t crc_calc = crc.update_block(block, 0, frame_bytes); uint16_t crc_file = block[frame_bytes] * 256 + block[frame_bytes + 1]; if (crc_calc != crc_file) throw BitstreamParseError("CRC16 error"); crc.update_block(block, frame_bytes, block.size()); } data_blocks--; } pos += len; } while (pos < data.size()); } uint16_t Bitstream::calculate_bitstream_crc() { crc.reset_crc16(); for (const auto &block : blocks) { crc.update_block(block, 0, block.size()); } return crc.finalise_crc16(); } void Bitstream::write_bin(std::ostream &file) { for (const auto &block : blocks) { file.write((const char *)&block[0], block.size()); } } void Bitstream::write_bas(std::ostream &file) { for (const auto &meta : metadata) { file << meta << std::endl; } for (const auto &block : blocks) { for (size_t pos = 0; pos < block.size(); pos++) { file << std::bitset<8>(block[pos]); } file << std::endl; } } void Bitstream::write_bmk(std::ostream &file) { for (const auto &meta : metadata) { if (boost::starts_with(meta, "# Bitstream CRC:")) continue; if (boost::starts_with(meta, "# USER CODE:")) continue; file << meta << std::endl; } for (auto it = blocks.begin(); it != (blocks.begin() + fuse_start_block); ++it) { uint16_t size = it->size() << 3; file << uint8_t(size >> 8) << uint8_t(size & 0xff); for (size_t pos = 0; pos < it->size(); pos++) { file << ((*it)[pos]); } } for (auto it = blocks.begin() + fuse_start_block; it != (blocks.begin() + fuse_start_block + frames + 1); ++it) { uint16_t size = it->size() << 3; file << uint8_t(size >> 8) << uint8_t(size & 0xff); for (size_t pos = 0; pos < it->size(); pos++) { file << uint8_t(0); } } for (auto it = blocks.begin() + fuse_start_block + frames + 1; it != blocks.end(); ++it) { if ((*it)[0] == 0) break; uint16_t size = it->size() << 3; file << uint8_t(size >> 8) << uint8_t(size & 0xff); for (size_t pos = 0; pos < it->size(); pos++) { file << (*it)[pos]; } } } void Bitstream::write_bma(std::ostream &file) { for (const auto &meta : metadata) { if (boost::starts_with(meta, "# Bitstream CRC:")) continue; if (boost::starts_with(meta, "# USER CODE:")) continue; file << meta << std::endl; } for (auto it = blocks.begin(); it != (blocks.begin() + fuse_start_block); ++it) { for (size_t pos = 0; pos < it->size(); pos++) { file << std::bitset<8>((*it)[pos]); } file << std::endl; } for (auto it = blocks.begin() + fuse_start_block; it != (blocks.begin() + fuse_start_block + frames + 1); ++it) { for (size_t pos = 0; pos < it->size(); pos++) { file << std::bitset<8>(0); } file << std::endl; } for (auto it = blocks.begin() + fuse_start_block + frames + 1; it != blocks.end(); ++it) { if ((*it)[0] == 0) break; for (size_t pos = 0; pos < it->size(); pos++) { file << std::bitset<8>((*it)[pos]); } file << std::endl; } } void Bitstream::write_fuse(std::ostream &file) { for (auto it = (blocks.begin() + fuse_start_block); it != (blocks.begin() + fuse_start_block + frames); ++it) { for (size_t pos = 0; pos < frame_bytes; pos++) { file << std::bitset<8>((*it)[pos]); } file << std::endl; } } void Bitstream::extract_bits() { int row = 0; for (auto it = (blocks.begin() + fuse_start_block); it != (blocks.begin() + fuse_start_block + frames); ++it) { int col = 0; for (size_t pos = 0; pos < frame_bytes; pos++) { uint8_t data = (*it)[pos]; if (data != 0x00) { std::bitset<8> b(data); for (int i = 7; i >= 0; i--) { if (b.test(i)) { printf("row:%d col:%d\n", row, col + 7 - i); } } } col += 8; } row++; } } uint8_t reverse_byte(uint8_t byte) { uint8_t rev = 0; for (int i = 0; i < 8; i++) if (byte & (1 << i)) rev |= (1 << (7 - i)); return rev; } void Bitstream::write_svf(std::ostream &file) { file << "// Created using Project Tang Software" << std::endl; file << "// Date: 2018/12/27 14:58" << std::endl; file << "// Architecture: eagle_s20" << std::endl; file << "// Package: BG256" << std::endl; file << std::endl; file << "TRST OFF;" << std::endl; file << "ENDIR IDLE;" << std::endl; file << "ENDDR IDLE;" << std::endl; file << "STATE RESET;" << std::endl; file << "STATE IDLE;" << std::endl; file << "FREQUENCY 1E6 HZ;" << std::endl; // Operation: Program file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; // Loading device with 'idcode' instruction. file << "SIR 8 TDI (06) SMASK (ff) ;" << std::endl; file << "RUNTEST 15 TCK;" << std::endl; file << "SDR 32 TDI (00000000) SMASK (ffffffff) TDO (" << std::setw(8) << std::hex << std::setfill('0') << deviceid << ") MASK (ffffffff) ;" << std::endl; // Boundary Scan Chain Contents // Position 1: BG256 file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; // Loading device with 'idcode' instruction. file << "SIR 8 TDI (06) SMASK (ff) ;" << std::endl; file << "SDR 32 TDI (00000000) SMASK (ffffffff) TDO (" << std::setw(8) << std::hex << std::setfill('0') << deviceid << ") MASK (ffffffff) ;" << std::endl; // Loading device with 'refresh' instruction. file << "SIR 8 TDI (01) SMASK (ff) ;" << std::endl; // Loading device with 'bypass' instruction. file << "SIR 8 TDI (1f) ;" << std::endl; file << "SIR 8 TDI (39) ;" << std::endl; file << "RUNTEST 50000 TCK;" << std::endl; // Loading device with 'jtag program' instruction. file << "SIR 8 TDI (30) SMASK (ff) ;" << std::endl; file << "RUNTEST 15 TCK;" << std::endl; // Loading device with a `cfg_in` instruction. file << "SIR 8 TDI (3b) SMASK (ff) ;" << std::endl; file << "RUNTEST 15 TCK;" << std::endl; size_t count = 0; for (auto const block : blocks) { count += block.size(); } // Begin of bitstream data file << "SDR " << std::dec << int(count * 8) << " TDI (" << std::endl; int i = 0; for (auto it = blocks.rbegin(); it != blocks.rend(); ++it) { for (size_t pos = 0; pos < it->size(); pos++) { file << std::hex << std::setw(2) << std::setfill('0') << int(reverse_byte(((*it)[it->size() - pos - 1]))); i++; if ((i % 1024) == 0) file << std::endl; } } file << std::endl << ") SMASK (" << std::endl; for (size_t j = 1; j < count + 1; j++) { file << "ff"; if ((j % 1024) == 0) file << std::endl; } file << std::endl << ") ;" << std::endl; file << "RUNTEST 100 TCK;" << std::endl; // Loading device with a `jtag start` instruction. file << "SIR 8 TDI (3d) ;" << std::endl; file << "RUNTEST 15 TCK;" << std::endl; // Loading device with 'bypass' instruction. file << "SIR 8 TDI (1f) ;" << std::endl; file << "RUNTEST 1000 TCK;" << std::endl; file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; file << "TIR 0 ;" << std::endl; file << "HIR 0 ;" << std::endl; file << "HDR 0 ;" << std::endl; file << "TDR 0 ;" << std::endl; // Loading device with 'bypass' instruction. file << "SIR 8 TDI (1f) ;" << std::endl; } BitstreamParseError::BitstreamParseError(const std::string &desc) : runtime_error(desc.c_str()), desc(desc), offset(-1) { } BitstreamParseError::BitstreamParseError(const std::string &desc, size_t offset) : runtime_error(desc.c_str()), desc(desc), offset(int(offset)) { } const char *BitstreamParseError::what() const noexcept { std::ostringstream ss; ss << "Bitstream Parse Error: "; ss << desc; if (offset != -1) ss << " [at 0x" << std::hex << offset << "]"; return strdup(ss.str().c_str()); } } // namespace Tang
34.219761
120
0.512521
[ "vector", "3d" ]
ea9082a013a103f6390d8e84867a60217d90550e
268
cpp
C++
libs/core/render/src/gl/detail/egl/bksge_core_render_gl_detail_egl_egl_context.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/src/gl/detail/egl/bksge_core_render_gl_detail_egl_egl_context.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/src/gl/detail/egl/bksge_core_render_gl_detail_egl_egl_context.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file bksge_core_render_gl_detail_egl_egl_context.cpp * * @brief EglContext の実装 * * @author myoukaku */ #include <bksge/fnd/config.hpp> #if !defined(BKSGE_HEADER_ONLY) #include <bksge/core/render/gl/detail/egl/inl/egl_context_inl.hpp> #endif
20.615385
67
0.712687
[ "render" ]
ea9fcd66924fdb9415179cbb3b765a34363f6c57
459
hpp
C++
tinytemplate.hpp
comargo/tinytemplate
0182eb7acb029ce85eaf668323a24e71034f87bf
[ "MIT" ]
null
null
null
tinytemplate.hpp
comargo/tinytemplate
0182eb7acb029ce85eaf668323a24e71034f87bf
[ "MIT" ]
null
null
null
tinytemplate.hpp
comargo/tinytemplate
0182eb7acb029ce85eaf668323a24e71034f87bf
[ "MIT" ]
null
null
null
#ifndef TINYTEMPLATE_HPP #define TINYTEMPLATE_HPP #include <string> #include <map> #include <stdexcept> namespace tinytemplate { class render_error : public std::runtime_error { public: explicit render_error(const std::string &what_arg); explicit render_error(const char *what_arg); }; std::string render(const std::string &source, const std::map<std::string, std::string> &variables, bool ignoreErrors=false); } #endif//TINYTEMPLATE_HPP
20.863636
124
0.747277
[ "render" ]
eaa17c952ef2879d1a8289332d23fa13a73dab5c
4,676
cc
C++
app/src/main.cc
rkaminsk/clingo-lpx
9188371b56652549b9a045e868ab22517d555f9f
[ "MIT" ]
null
null
null
app/src/main.cc
rkaminsk/clingo-lpx
9188371b56652549b9a045e868ab22517d555f9f
[ "MIT" ]
5
2021-04-26T10:26:00.000Z
2021-11-16T09:58:23.000Z
app/src/main.cc
rkaminsk/simplex
9188371b56652549b9a045e868ab22517d555f9f
[ "MIT" ]
null
null
null
// {{{ MIT License // Copyright Roland Kaminski // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // }}} #include <clingo.hh> #include <clingo-lpx.h> #include <clingo-lpx-app/app.hh> #include <sstream> #include <fstream> #include <limits> namespace ClingoLPX { using Clingo::Detail::handle_error; //! Application class to run clingo-lpx. class App : public Clingo::Application, private Clingo::SolveEventHandler { public: App() { handle_error(clingolpx_create(&theory_)); } App(App const &) = default; App(App &&) = default; App &operator=(App const &) = default; App &operator=(App &&) = default; ~App() override { clingolpx_destroy(theory_); } //! Set program name to clingo-lpx. [[nodiscard]] char const *program_name() const noexcept override { return "clingo-lpx"; } //! Set the version. [[nodiscard]] char const *version() const noexcept override { return CLINGOLPX_VERSION; } void print_model(Clingo::Model const &model, std::function<void()> default_printer) noexcept override { try { auto symbols = model.symbols(); std::sort(symbols.begin(), symbols.end()); bool comma = false; for (auto const &sym : symbols) { if (comma) { std::cout << " "; } std::cout << sym; comma = true; } std::cout << "\nAssignment:\n"; symbols = model.symbols(Clingo::ShowType::Theory); std::sort(symbols.begin(), symbols.end()); comma = false; for (auto const &sym : symbols) { if (std::strcmp("__lpx", sym.name()) != 0) { continue; } if (comma) { std::cout << " "; } auto args = sym.arguments(); std::cout << args.front() << "=" << args.back().string(); comma = true; } std::cout << std::endl; } catch(...) { } } //! Pass models to the theory. bool on_model(Clingo::Model &model) override { handle_error(clingolpx_on_model(theory_, model.to_c())); return true; } //! Pass statistics to the theory. void on_statistics(Clingo::UserStatistics step, Clingo::UserStatistics accu) override { handle_error(clingolpx_on_statistics(theory_, step.to_c(), accu.to_c())); } //! Run main solving function. void main(Clingo::Control &ctl, Clingo::StringSpan files) override { // NOLINT handle_error(clingolpx_register(theory_, ctl.to_c())); Clingo::AST::with_builder(ctl, [&](Clingo::AST::ProgramBuilder &builder) { Rewriter rewriter{theory_, builder.to_c()}; rewriter.rewrite(files); }); ctl.ground({{"base", {}}}); ctl.solve(Clingo::SymbolicLiteralSpan{}, this, false, false).get(); } //! Register options of the theory and optimization related options. void register_options(Clingo::ClingoOptions &options) override { handle_error(clingolpx_register_options(theory_, options.to_c())); } //! Validate options of the theory. void validate_options() override { handle_error(clingolpx_validate_options(theory_)); } private: clingolpx_theory_t *theory_{nullptr}; //!< The underlying DL theory. }; } // namespace ClingoLPX //! Run the clingo-lpx application. int main(int argc, char *argv[]) { ClingoLPX::App app; return Clingo::clingo_main(app, {argv + 1, static_cast<size_t>(argc - 1)}); }
35.969231
107
0.619333
[ "model" ]
eaa7bc2ecf170f65984068ab53d693a771326636
5,529
cpp
C++
moos-ivp/ivp/src/app_aloghelm/main.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/app_aloghelm/main.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
moos-ivp/ivp/src/app_aloghelm/main.cpp
EasternEdgeRobotics/2018
24df2fe56fa6d172ba3c34c1a97f249dbd796787
[ "MIT" ]
null
null
null
/*****************************************************************/ /* NAME: Michael Benjamin */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: main.cpp */ /* DATE: June 3rd, 2008 */ /* */ /* This file is part of MOOS-IvP */ /* */ /* MOOS-IvP is free software: you can redistribute it and/or */ /* modify it under the terms of the GNU General Public License */ /* as published by the Free Software Foundation, either version */ /* 3 of the License, or (at your option) any later version. */ /* */ /* MOOS-IvP 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 MOOS-IvP. If not, see */ /* <http://www.gnu.org/licenses/>. */ /*****************************************************************/ #include <string> #include <cstdlib> #include <iostream> #include "MBUtils.h" #include "ReleaseInfo.h" #include "HelmReporter.h" using namespace std; //-------------------------------------------------------- // Procedure: main int main(int argc, char *argv[]) { // Look for a request for version information if(scanArgs(argc, argv, "-v", "--version", "-version")) { showReleaseInfo("aloghelm", "gpl"); return(0); } // Look for a request for usage information if(scanArgs(argc, argv, "-h", "--help", "-help")) { cout << "Usage: " << endl; cout << " aloghelm file.alog [OPTIONS] [MOOSVARS] " << endl; cout << " " << endl; cout << "Synopsis: " << endl; cout << " Perform one of several optional helm reports based on " << endl; cout << " helm output logged in the given .alog file. " << endl; cout << " " << endl; cout << "Options: " << endl; cout << " -h,--help Displays this help message " << endl; cout << " -v,--version Displays the current release version " << endl; cout << " -l,--life Show report on IvP Helm Life Events " << endl; cout << " -b,--bhvs Show helm behavior state changes " << endl; cout << " -m,--modes Show helm mode changes " << endl; cout << " --watch=bhv Watch a particular behavior for state change" << endl; cout << " --nocolor Turn off use of color coding " << endl; cout << " --notrunc Don't truncate MOOSVAR output (on by default)" << endl; cout << " " << endl; cout << "Further Notes: " << endl; cout << " (1) The order of arguments is irrelevent. " << endl; cout << " (2) Only the first specified .alog file is reported on. " << endl; cout << " (3) Arguments that are not one of the above options or an" << endl; cout << " alog file, are interpreted as MOOS variables on which" << endl; cout << " to report as encountered. " << endl; cout << endl; return(0); } vector<string> keys; vector<string> watch_vars; string alogfile_in; string watch_behavior; bool report_bhv_changes = false; bool report_life_events = false; bool report_mode_changes = false; bool use_colors = true; bool var_trunc = true; for(int i=1; i<argc; i++) { string argi = argv[i]; if((argi == "-b") || (argi == "--bhvs")) report_bhv_changes = true; else if((argi == "-m") || (argi == "--modes")) report_mode_changes = true; else if((argi == "-l") || (argi == "--life")) report_life_events = true; else if((argi == "-l") || (argi == "--notrunc")) var_trunc = false; else if(strBegins(argi, "--watch=")) watch_behavior = argi.substr(8); else if(argi == "--nocolor") use_colors = false; if(strEnds(argi, ".alog") && (alogfile_in == "")) alogfile_in = argi; else watch_vars.push_back(argi); } if(alogfile_in == "") { cout << "No alog file given - exiting" << endl; exit(0); } HelmReporter hreporter; if(report_life_events) hreporter.reportLifeEvents(); if(report_mode_changes) hreporter.reportModeChanges(); if(report_bhv_changes) hreporter.reportBehaviorChanges(); if(watch_behavior != "") hreporter.setWatchBehavior(watch_behavior); hreporter.setColorActive(use_colors); hreporter.setUseColor(use_colors); hreporter.setVarTrunc(var_trunc); for(unsigned int k=0; k<watch_vars.size(); k++) hreporter.addWatchVar(watch_vars[k]); bool handled = hreporter.handle(alogfile_in); if(handled) hreporter.printReport(); }
38.664336
84
0.490866
[ "vector" ]
eaadd4da19753830b5d444433917f3d46acee492
7,258
hpp
C++
cpp/src/utils/NeedlemanWunsch.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
8
2018-10-08T15:47:21.000Z
2021-11-09T07:13:05.000Z
cpp/src/utils/NeedlemanWunsch.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2018-11-05T09:16:27.000Z
2020-04-09T12:32:56.000Z
cpp/src/utils/NeedlemanWunsch.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2019-09-03T15:46:39.000Z
2021-06-04T07:28:33.000Z
// All content Copyright (C) 2018 Genomics plc #ifndef NEEDLEMAN_WUNSCH_HPP #define NEEDLEMAN_WUNSCH_HPP #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/optional/optional.hpp> #include "utils/referenceSequence.hpp" #include "variant/type/variant.hpp" namespace wecall { namespace utils { class NWVariant { private: int64_t m_start; int64_t m_end; utils::BasePairSequence m_alt; public: NWVariant( int64_t start, int64_t end, utils::BasePairSequence alt ) : m_start( start ), m_end( end ), m_alt( alt ) { } bool operator==( const NWVariant & A ) const { return ( this->m_start == A.m_start && this->m_end == A.m_end && this->m_alt == A.m_alt ); } friend std::ostream & operator<<( std::ostream & out, const NWVariant & nWVariant ); std::shared_ptr< variant::Variant > getVariant( std::string contig, int64_t base, const utils::referenceSequencePtr_t & referenceSequence ) const { const auto region = caller::Region( contig, base + m_start, base + m_end ); return std::make_shared< variant::Variant >( referenceSequence, region, m_alt ); } }; struct NWPenalties { private: const int32_t m_baseMatch; const int32_t m_baseMismatch; // A gap of size n incurs a penalty of gapConstant + n times gapLinear + a multiple of gapPosition that depends // on the position it starts at const int32_t m_insertionConstant; const int32_t m_insertionLinear; const int32_t m_insertionOpen; const int32_t m_deletionConstant; const int32_t m_deletionLinear; const int32_t m_deletionOpen; const int32_t m_indelPosition; public: NWPenalties( int32_t baseMatchPenalty = 0, int32_t baseMismatchPenalty = -1000, int32_t indelConstantPenalty = -2000, int32_t indelLinearPenalty = -300, int32_t indelPositionPenalty = -1 ) : m_baseMatch( baseMatchPenalty ), m_baseMismatch( baseMismatchPenalty ), m_insertionConstant( indelConstantPenalty ), m_insertionLinear( indelLinearPenalty ), m_insertionOpen( indelConstantPenalty + indelLinearPenalty ), m_deletionConstant( indelConstantPenalty ), m_deletionLinear( indelLinearPenalty ), m_deletionOpen( indelConstantPenalty + indelLinearPenalty ), m_indelPosition( indelPositionPenalty ) { } NWPenalties( int32_t baseMatchPenalty, int32_t baseMismatchPenalty, int32_t insertionConstantPenalty, int32_t insertionLinearPenalty, int32_t deletionConstantPenalty, int32_t deletionLinearPenalty, int32_t indelPositionPenalty ) : m_baseMatch( baseMatchPenalty ), m_baseMismatch( baseMismatchPenalty ), m_insertionConstant( insertionConstantPenalty ), m_insertionLinear( insertionLinearPenalty ), m_insertionOpen( insertionConstantPenalty + insertionLinearPenalty ), m_deletionConstant( deletionConstantPenalty ), m_deletionLinear( deletionLinearPenalty ), m_deletionOpen( deletionConstantPenalty + deletionLinearPenalty ), m_indelPosition( indelPositionPenalty ) { } bool operator==( const NWPenalties & A ) const { return ( this->m_baseMatch == A.m_baseMatch && this->m_baseMismatch == A.m_baseMismatch && this->m_insertionConstant == A.m_insertionConstant && this->m_insertionLinear == A.m_insertionLinear && this->m_insertionOpen == A.m_insertionOpen && this->m_deletionConstant == A.m_deletionConstant && this->m_deletionLinear == A.m_deletionLinear && this->m_deletionOpen == A.m_deletionOpen && this->m_indelPosition == A.m_indelPosition ); } friend std::ostream & operator<<( std::ostream & out, const NWPenalties & nWPenalties ); int32_t matchFunction( const char first, const char second ) const { return ( first != constants::gapChar and first == second ) ? m_baseMatch : m_baseMismatch; } int32_t insertionOpen() const { return m_insertionOpen; } int32_t deletionOpen() const { return m_deletionOpen; } int32_t insertionFunction( const std::size_t position, const std::size_t insertionLength ) const { // The position argument should be the location of the start of the insertion in the reference sequence, // where the very start is counted as 0 return 0 == insertionLength ? 0 : m_insertionConstant + m_insertionLinear * insertionLength + m_indelPosition * position; } int32_t deletionFunction( const std::size_t position, const std::size_t deletionLength ) const { // The position argument should be the location of the start of the deletion in the alt sequence, where the // very start is counted as 0 return 0 == deletionLength ? 0 : m_deletionConstant + m_deletionLinear * deletionLength + m_indelPosition * position; } int32_t extendInsertion() const { return m_insertionLinear; } int32_t extendDeletion() const { return m_deletionLinear; } }; class NeedlemanWunsch { using scoreMatrix_t = boost::numeric::ublas::matrix< int32_t >; using bitType_t = int64_t; using traceMatrix_t = boost::numeric::ublas::matrix< bitType_t >; public: NeedlemanWunsch( const utils::BasePairSequence & referenceString, const utils::BasePairSequence & altString, const NWPenalties & nWPenalties ) : m_referenceString( referenceString ), m_altString( altString ), m_nWPenalties( nWPenalties ) { } int32_t getScoreMatrix(); std::vector< NWVariant > traceBack() const; private: struct Backtrace { std::vector< NWVariant > variants; std::size_t refIndex; std::size_t altIndex; bitType_t trace; bool previousIsDeletion; }; scoreMatrix_t m_scoreMatrix; traceMatrix_t m_traceMatrix; const utils::BasePairSequence & m_referenceString; const utils::BasePairSequence & m_altString; const NWPenalties & m_nWPenalties; const bitType_t m_matchBit = 1; const bitType_t m_snpBit = 2; const bitType_t m_insertSingleBit = 4; const bitType_t m_deleteSingleBit = 8; const bitType_t m_insertMultiBit = 16; const bitType_t m_deleteMultiBit = 32; }; } } #endif
39.879121
120
0.611325
[ "vector" ]
eab468d6f52ffaa9fc87783475815282a593095e
30,548
cpp
C++
sources/DirectoryServer.cpp
KhaledSoliman/P2P-Image-App
ef3cdd083aef1871f8383e44205c81aab2799257
[ "MIT" ]
null
null
null
sources/DirectoryServer.cpp
KhaledSoliman/P2P-Image-App
ef3cdd083aef1871f8383e44205c81aab2799257
[ "MIT" ]
11
2019-10-23T17:10:36.000Z
2019-11-22T19:59:48.000Z
sources/DirectoryServer.cpp
KhaledSoliman/Distributed-Systems-Fall19
ef3cdd083aef1871f8383e44205c81aab2799257
[ "MIT" ]
null
null
null
#include "../headers/DirectoryServer.h" #include "../headers/MessageStructures.h" #include <boost/algorithm/string.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/random/random_device.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/thread.hpp> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-noreturn" #define ERROR_AUTH "Failed to authenticate credentials" #define USER_NOT_FOUND "User does not exist" #define USER_EXISTS "User already exists" #define IMAGE_EXISTS "Image already exists" #define IMAGE_DOES_NOT_EXIST "Image does not exist for this user" #define LOGIN_FAILURE "Incorrect username or password" #define REGISTER_SUCCESS "User registered successfully." #define THUMBNAIL_SAVE_ERR "Couldnt save thumbnail" DirectoryServer::DirectoryServer(const std::string &hostname) : Server(hostname, DEFAULT_LISTEN_PORT) { this->hostname = hostname; this->port = DEFAULT_LISTEN_PORT; this->databasePath = DATABASE_DIR; this->directoryFile = DIRECTORY_FILE; this->usersFile = USER_FILE; } DirectoryServer::DirectoryServer(const std::string &hostname, int port, const std::string &databasePath, const std::string &directoryFile, const std::string &usersFile) : Server(hostname, port) { this->hostname = hostname; this->port = port; this->usersFile = usersFile; this->databasePath = databasePath; this->directoryFile = directoryFile; } void DirectoryServer::init() { this->loadDatabase(); boost::thread helloListener(&DirectoryServer::helloListener, boost::shared_ptr<DirectoryServer>(this)); boost::thread serverListener(&DirectoryServer::listen, boost::shared_ptr<DirectoryServer>(this)); boost::thread databasePersist(&DirectoryServer::databasePersistence, boost::shared_ptr<DirectoryServer>(this)); while (true); } void DirectoryServer::databasePersistence(boost::shared_ptr<DirectoryServer> directoryServer) { for (;;) { std::cout << "saving databases..." << std::endl; directoryServer->saveDatabase(); boost::this_thread::sleep(boost::posix_time::minutes(1)); } } void DirectoryServer::listen(boost::shared_ptr<DirectoryServer> directoryServer) { while (true) { Message *message = directoryServer->Server::receive(); std::cout << "Recieved: " << message->getOperation() << std::endl; boost::thread serverThread(&DirectoryServer::handleRequest, message, directoryServer); if (message->getOperation() == Message::OperationType::FEED || message->getOperation() == Message::OperationType::FEED_PROFILE) boost::this_thread::sleep(boost::posix_time::seconds(5)); } } void DirectoryServer::helloListener(boost::shared_ptr<DirectoryServer> directoryServer) { directoryServer->Server::initBroadcast(BROADCAST_PORT); while (true) { Message *message = directoryServer->listenToBroadcasts(); auto hello = load<Hello>(message->getMessage()); if (hello.getMessage() == "DoS") hello.setMessage("ME"); Message *reply = directoryServer->Server::saveAndGetMessage(hello, Message::MessageType::Reply, Message::OperationType::HELLO); directoryServer->Server::send(reply); } } void DirectoryServer::loadDatabase() { std::ifstream in; std::string username; in.open(databasePath + usersFile); if (in.is_open()) { std::string line; std::string password; while (std::getline(in, line) && !line.empty()) { std::stringstream lineStream(line); while (lineStream >> username >> password) { User user = User(); user.setUsername(username); user.setPassword(password); user.setAuthenticated(false); this->users[username] = user; } } } in.close(); in.open(databasePath + directoryFile); if (in.is_open()) { std::string imageList; std::string line; while (std::getline(in, line) && !line.empty()) { std::stringstream lineStream(line); while (lineStream >> username >> imageList) { if (imageList != "none") { std::vector<std::string> images; boost::split(images, imageList, boost::is_any_of(",")); this->users[username].setImages(images); } } } in.close(); } } void DirectoryServer::saveDatabase() { std::ofstream out; out.open(databasePath + usersFile); if (out.is_open()) for (const User &user : this->users | boost::adaptors::map_values) { out << user.getUsername() << " " << user.getPassword() << std::endl; } out.close(); out.open(databasePath + directoryFile); if (out.is_open()) for (const User &user : this->users | boost::adaptors::map_values) { std::string imageList; if (!user.getImages().empty()) { imageList = boost::algorithm::join(user.getImages(), ","); } else { imageList = "none"; } out << user.getUsername() << " " << imageList << std::endl; } out.close(); } bool DirectoryServer::userExists(const std::string &username) { return this->users.find(username) != this->users.end(); } bool DirectoryServer::authorize(const std::string &username, const std::string &token) { return this->users[username].isAuthenticated() && this->users[username].getToken() == token; } std::string DirectoryServer::generateAuthToken() { std::string chars( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890"); boost::random::random_device rng; boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1); std::string token; for (int i = 0; i < 256; ++i) { token += chars[index_dist(rng)]; } return token; } bool DirectoryServer::authenticate(const std::string &username, const std::string &hashedPassword) { return this->userExists(username) && this->users[username].getPassword() == hashedPassword; } void DirectoryServer::handleRequest(Message *message, boost::shared_ptr<DirectoryServer> directoryServer) { switch (message->getMessageType()) { case Message::MessageType::Request: Message *reply; switch (message->getOperation()) { case Message::OperationType::REGISTER: reply = directoryServer->Server::saveAndGetMessage( directoryServer->registerUser(load<RegisterRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::REGISTER); break; case Message::OperationType::LOGIN: reply = directoryServer->Server::saveAndGetMessage( directoryServer->loginUser(load<LoginRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::LOGIN); break; case Message::OperationType::LOGOUT: reply = directoryServer->Server::saveAndGetMessage( directoryServer->logoutUser(load<LogoutRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::LOGOUT); break; case Message::OperationType::SHOW_ONLINE: reply = directoryServer->Server::saveAndGetMessage( directoryServer->showOnline(load<ShowOnlineRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::SHOW_ONLINE); break; case Message::OperationType::FEED: reply = directoryServer->Server::saveAndGetMessage( directoryServer->feed(load<FeedRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::FEED); break; case Message::OperationType::FEED_PROFILE: reply = directoryServer->Server::saveAndGetMessage( directoryServer->feedProfile(load<FeedProfileRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::FEED_PROFILE); break; case Message::OperationType::SEARCH: reply = directoryServer->Server::saveAndGetMessage( directoryServer->searchUser(load<SearchRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::SEARCH); break; case Message::OperationType::ADD_IMAGE: reply = directoryServer->Server::saveAndGetMessage( directoryServer->addImage(load<AddImageRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::ADD_IMAGE); break; case Message::OperationType::DELETE_IMAGE: reply = directoryServer->Server::saveAndGetMessage( directoryServer->delImage(load<DeleteImageRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::DELETE_IMAGE); break; case Message::OperationType::VIEW_IMAGE: reply = directoryServer->Server::saveAndGetMessage( directoryServer->viewImage(load<ViewImageRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::VIEW_IMAGE); break; case Message::OperationType::ADD_VIEWER: reply = directoryServer->Server::saveAndGetMessage( directoryServer->acceptRequest(load<AddViewerRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::ADD_VIEWER); break; case Message::OperationType::DENY_VIEWER: reply = directoryServer->Server::saveAndGetMessage( directoryServer->denyRequest(load<DenyViewerRequest>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::DENY_VIEWER); break; case Message::OperationType::GET_REQUESTS: reply = directoryServer->Server::saveAndGetMessage( directoryServer->getRequests(load<GetRequests>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::GET_REQUESTS); break; case Message::OperationType::GET_PENDING_REQUESTS: reply = directoryServer->Server::saveAndGetMessage( directoryServer->getPendingRequests(load<GetPendingRequests>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::GET_PENDING_REQUESTS); break; case Message::OperationType::ECHO: reply = directoryServer->Server::saveAndGetMessage(load<Echo>(message->getMessage()), Message::MessageType::Reply, Message::OperationType::ECHO); break; case Message::OperationType::HELLO: reply = directoryServer->Server::saveAndGetMessage( directoryServer->handleHello(load<Hello>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::ACK); break; case Message::OperationType::AUTH_HELLO: reply = directoryServer->Server::saveAndGetMessage( directoryServer->handleAuthHello(load<AuthenticatedHello>(message->getMessage())), Message::MessageType::Reply, Message::OperationType::ACK); break; default: break; } directoryServer->Server::send(reply); break; case Message::MessageType::Reply: switch (message->getOperation()) { case Message::OperationType::ACK: break; default: break; } break; default: break; } } Ack DirectoryServer::handleHello(Hello req) { return Ack(); } SearchReply DirectoryServer::searchUser(const SearchRequest &req) { SearchReply reply = SearchReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->authorize(username, token)) { const std::string &targetUsername = req.getTargetUsername(); if (this->userExists(targetUsername)) { reply.setAddress(this->users[targetUsername].getAddress()); reply.setPort(this->users[targetUsername].getPortNum()); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } return reply; } LoginReply DirectoryServer::loginUser(const LoginRequest &req) { LoginReply reply = LoginReply(); const std::string &username = req.getUserName(); const std::string &password = req.getHashedPassword(); bool authenticated = this->authenticate(username, password); if (authenticated) { std::string token = this->generateAuthToken(); this->users[username].setToken(token); this->users[username].setAuthenticated(true); reply.setFlag(false); reply.setToken(token); } else { reply.setFlag(true); reply.setMsg(LOGIN_FAILURE); } return reply; } LogoutReply DirectoryServer::logoutUser(const LogoutRequest &req) { LogoutReply reply = LogoutReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { this->users[username].setToken(""); this->users[username].setAuthenticated(false); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } RegisterReply DirectoryServer::registerUser(const RegisterRequest &req) { const std::string &username = req.getUserName(); const std::string &password = req.getHashedPassword(); RegisterReply reply = RegisterReply(); if (!this->userExists(username)) { User user = User(); user.setUsername(username); user.setPassword(password); user.setAuthenticated(false); this->users[username] = user; reply.setRegistered(true); reply.setFlag(false); reply.setMsg(REGISTER_SUCCESS); } else { reply.setRegistered(false); reply.setFlag(true); reply.setMsg(USER_EXISTS); } return reply; } AddImageReply DirectoryServer::addImage(const AddImageRequest &req) { AddImageReply reply = AddImageReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { const std::string &imageName = req.getImageName(); if (!this->users[username].imageExists(imageName)) { this->users[username].addImage(imageName); std::ofstream out; std::string path = THUMBNAILS_DIR + username + "-" + imageName; out.open(path); if (out.is_open()) { out << req.getThumbnail(); out.close(); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(THUMBNAIL_SAVE_ERR); } } else { reply.setFlag(true); reply.setMsg(IMAGE_EXISTS); } } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } DeleteImageReply DirectoryServer::delImage(const DeleteImageRequest &req) { DeleteImageReply reply = DeleteImageReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { const std::string &imageName = req.getImageName(); if (this->users[username].imageExists(imageName)) { std::string path = THUMBNAILS_DIR + username + "-" + imageName; remove(path.c_str()); this->users[username].delImage(imageName); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(IMAGE_DOES_NOT_EXIST); } } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } FeedReply DirectoryServer::feed(const FeedRequest &req) { FeedReply reply = FeedReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); int index = 0; std::unordered_map<std::string, std::pair<std::string, std::string>> thumbnails; if (this->userExists(username)) { if (this->authorize(username, token)) { for (const User &user : this->users | boost::adaptors::map_values) { if (user.getUsername() != username) { for (const std::string &image : user.getImages()) { std::cout << index << std::endl; if (index < req.getLastIndex()) { index++; continue; } std::ifstream in; std::string path = THUMBNAILS_DIR + user.getUsername() + "-" + image; std::cout << path << std::endl; in.open(path); std::string thumbnail((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); thumbnails[image] = std::pair(user.getUsername(), thumbnail); in.close(); index++; } } } reply.setCurrentIndex(index); reply.setImages(thumbnails); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } DirectoryServer::~DirectoryServer() { this->saveDatabase(); } Ack DirectoryServer::handleAuthHello(AuthenticatedHello req) { const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { this->users[username].setAddress(req.getIpAddress()); this->users[username].setPortNum(req.getPort()); } } return Ack(); } ShowOnlineReply DirectoryServer::showOnline(const ShowOnlineRequest &req) { ShowOnlineReply reply = ShowOnlineReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { std::vector<std::string> onlineUsers; for (const User &user : this->users | boost::adaptors::map_values) { if (user.getUsername() != username && user.isAuthenticated()) { onlineUsers.push_back(user.getUsername()); } } reply.setFlag(false); reply.setUsers(onlineUsers); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } FeedProfileReply DirectoryServer::feedProfile(const FeedProfileRequest &req) { FeedProfileReply reply = FeedProfileReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); const std::string &targetUsername = req.getTargetUsername(); if (this->userExists(username) && this->userExists(targetUsername)) { if (this->authorize(username, token)) { if (targetUsername != username) { std::vector<std::pair<std::string, std::string>> thumbnails; int index = 0; for (const std::string &image : this->users[targetUsername].getImages()) { if (index < req.getLastIndex()) { index++; continue; } std::ifstream in; std::string path = THUMBNAILS_DIR + targetUsername + "-" + image; in.open(path); std::string thumbnail((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); thumbnails.push_back(std::pair(image, thumbnail)); in.close(); index++; } reply.setFlag(false); reply.setTargetUsername(targetUsername); reply.setImages(thumbnails); reply.setCurrentIndex(index); } else { reply.setFlag(true); reply.setMsg("Cannot feed yourself."); } } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } ViewImageReply DirectoryServer::viewImage(const ViewImageRequest &req) { ViewImageReply reply = ViewImageReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); const std::string &targetUsername = req.getTargetUsername(); if (this->userExists(username) && this->userExists(targetUsername)) { if (this->authorize(username, token)) { this->users[targetUsername].addRequest(req); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } GetRequestsReply DirectoryServer::getRequests(const GetRequests &req) { GetRequestsReply reply = GetRequestsReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { reply.setFlag(false); reply.setRequests(this->users[username].getImageRequests()); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } const boost::shared_ptr<DirectoryServer> &DirectoryServer::getDirectoryServer() const { return directoryServer; } void DirectoryServer::setDirectoryServer(const boost::shared_ptr<DirectoryServer> &directoryServer) { DirectoryServer::directoryServer = directoryServer; } GetPendingRequestsReply DirectoryServer::getPendingRequests(const GetPendingRequests &req) { GetPendingRequestsReply reply = GetPendingRequestsReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { reply.setRequests(this->users[username].getUserPendingRequests()); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } AddViewerReply DirectoryServer::acceptRequest(const AddViewerRequest &req) { AddViewerReply reply = AddViewerReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { int i = 0; for (const auto &request: this->users[username].getUserRequests()) { i++; if (req.getViewerName() == request.getUserName() && req.getImageName() == request.getImageName() && req.getViewNum() == request.getViewNum()) { this->users[request.getUserName()].addPendingRequest(request, true); break; } } this->users[username].removeRequest(i-1); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } DenyViewerReply DirectoryServer::denyRequest(const DenyViewerRequest &req) { DenyViewerReply reply = DenyViewerReply(); const std::string &username = req.getUserName(); const std::string &token = req.getToken(); if (this->userExists(username)) { if (this->authorize(username, token)) { int i = 0; for (const auto &request: this->users[username].getUserRequests()) { i++; if (req.getViewerName() == request.getUserName() && req.getImageName() == request.getImageName() && req.getViewNum() == request.getViewNum()) { this->users[request.getUserName()].addPendingRequest(request, false); break; } } this->users[username].removeRequest(i-1); reply.setFlag(false); } else { reply.setFlag(true); reply.setMsg(ERROR_AUTH); } } else { reply.setFlag(true); reply.setMsg(USER_NOT_FOUND); } return reply; } const std::string &DirectoryServer::User::getUsername() const { return username; } void DirectoryServer::User::setUsername(const std::string &username) { this->username = username; } const std::string &DirectoryServer::User::getPassword() const { return password; } void DirectoryServer::User::setPassword(const std::string &password) { this->password = password; } const std::string &DirectoryServer::User::getAddress() const { return address; } void DirectoryServer::User::setAddress(const std::string &address) { this->address = address; } const std::string &DirectoryServer::User::getToken() const { return token; } void DirectoryServer::User::setToken(const std::string &token) { this->token = token; } bool DirectoryServer::User::isAuthenticated() const { return authenticated; } void DirectoryServer::User::setAuthenticated(bool isAuthenticated) { this->authenticated = isAuthenticated; } int DirectoryServer::User::getPortNum() const { return portNum; } void DirectoryServer::User::setPortNum(int portNum) { this->portNum = portNum; } const std::vector<std::string> &DirectoryServer::User::getImages() const { return images; } void DirectoryServer::User::setImages(const std::vector<std::string> &images) { this->images = images; } time_t DirectoryServer::User::getLastSeen() const { return lastSeen; } void DirectoryServer::User::setLastSeen(time_t lastSeen) { this->lastSeen = lastSeen; } void DirectoryServer::User::addImage(const std::string &imageName) { this->images.push_back(imageName); } bool DirectoryServer::User::imageExists(const std::string &imageName) { return std::find(this->images.begin(), this->images.end(), imageName) != this->images.end(); } void DirectoryServer::User::addRequest(MessageStructures::User::ViewImageRequest request) { this->requests.push_back(request); } void DirectoryServer::User::delImage(const std::string &imageName) { images.erase(std::find(this->images.begin(), this->images.end(), imageName)); } const std::vector<MessageStructures::User::ViewImageRequest> &DirectoryServer::User::getImageRequests() const { return requests; } void DirectoryServer::User::setRequests(const std::vector<MessageStructures::User::ViewImageRequest> &requests) { User::requests = requests; } void DirectoryServer::User::addPendingRequest(MessageStructures::User::ViewImageRequest request, bool accepted) { this->pendingRequests.push_back(std::pair(request, accepted)); } const std::vector<std::pair<MessageStructures::User::ViewImageRequest, bool>> & DirectoryServer::User::getUserPendingRequests() const { return pendingRequests; } const std::vector<MessageStructures::User::ViewImageRequest> &DirectoryServer::User::getUserRequests() const { return requests; } void DirectoryServer::User::removeRequest(int index) { this->requests.erase(this->requests.begin() + index); } void DirectoryServer::User::removePendingRequest(int index) { this->pendingRequests.erase(this->pendingRequests.begin() + index); } #pragma clang diagnostic pop
39.014049
115
0.589269
[ "vector" ]
eab80c97162d0e696f7fe17c51f7f6417c051813
794
cpp
C++
atcoder/abc068/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc068/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc068/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; int N, M; vector<int> A, B; bool solve() { unordered_set<int> is; for (int i = 0; i < M; ++i) { if (A[i] == 0) { is.insert(B[i]); } if (B[i] == 0) { is.insert(A[i]); } } for (int i = 0; i < M; ++i) { if (A[i] == N-1 && is.count(B[i]) > 0) return true; if (B[i] == N-1 && is.count(A[i]) > 0) return true; } return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> N >> M; A.assign(M, 0); B.assign(M, 0); for (int i = 0; i < M; ++i) { cin >> A[i] >> B[i]; --A[i], --B[i]; } auto ans = solve() ? "POSSIBLE" : "IMPOSSIBLE"; cout << ans << endl; return 0; }
19.85
59
0.420655
[ "vector" ]
eab9f8160cd8955b2e80a37b032af1961a460f12
4,123
cc
C++
src/bgp/test/bgp_test_util.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
3
2019-01-11T06:16:40.000Z
2021-02-24T23:48:21.000Z
src/bgp/test/bgp_test_util.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
null
null
null
src/bgp/test/bgp_test_util.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
18
2017-01-12T09:28:44.000Z
2019-04-18T20:47:42.000Z
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include "bgp/test/bgp_test_util.h" #include <assert.h> #include <stdio.h> #include <pugixml/pugixml.hpp> using pugi::xml_document; using pugi::xml_node; using pugi::node_pcdata; using namespace std; namespace bgp_util { string NetworkConfigGenerate( const vector<string> &instance_names, const multimap<string, string> &connections, const vector<string> &networks, const vector<int> &network_ids) { assert(networks.empty() || instance_names.size() == networks.size()); assert(networks.size() == network_ids.size()); int index; xml_document xdoc; xml_node env = xdoc.append_child("Envelope"); xml_node update = env.append_child("Body").append_child("response"). append_child("pollResult").append_child("updateResult"); index = 0; for (vector<string>::const_iterator iter = instance_names.begin(); iter != instance_names.end(); ++iter) { xml_node item = update.append_child("resultItem"); xml_node id = item.append_child("identity"); string vn("virtual-network:"); if (networks.empty()) { vn.append(*iter); } else { vn.append(networks[index]); } id.append_attribute("name") = vn.c_str(); xml_node meta = item.append_child("metadata"); xml_node vn_properties = meta.append_child("virtual-network-properties"); xml_node net_id = vn_properties.append_child("network-id"); int value; if (network_ids.empty()) { value = index + 1; } else { value = network_ids[index]; } char value_str[16]; snprintf(value_str, sizeof(value), "%d", value); net_id.append_child(node_pcdata).set_value(value_str); index++; } index = 0; for (vector<string>::const_iterator iter = instance_names.begin(); iter != instance_names.end(); ++iter) { xml_node item = update.append_child("resultItem"); xml_node id1 = item.append_child("identity"); string instance("routing-instance:"); instance.append(*iter); id1.append_attribute("name") = instance.c_str(); xml_node id2 = item.append_child("identity"); ostringstream target; target << "route-target:target:64496:" << (index + 1); id2.append_attribute("name") = target.str().c_str(); xml_node meta = item.append_child("metadata"); meta.append_child("instance-target"); index++; } index = 0; for (vector<string>::const_iterator iter = instance_names.begin(); iter != instance_names.end(); ++iter) { xml_node item = update.append_child("resultItem"); xml_node id1 = item.append_child("identity"); string vn("virtual-network:"); if (networks.empty()) { vn.append(*iter); } else { vn.append(networks[index]); } id1.append_attribute("name") = vn.c_str(); xml_node id2 = item.append_child("identity"); string instance("routing-instance:"); instance.append(*iter); id2.append_attribute("name") = instance.c_str(); xml_node meta = item.append_child("metadata"); meta.append_child("virtual-network-routing-instance"); index++; } for (multimap<string, string>::const_iterator iter = connections.begin(); iter != connections.end(); ++iter) { xml_node item = update.append_child("resultItem"); xml_node id1 = item.append_child("identity"); string instance1("routing-instance:"); instance1.append(iter->first); id1.append_attribute("name") = instance1.c_str(); xml_node id2 = item.append_child("identity"); string instance2("routing-instance:"); instance2.append(iter->second); id2.append_attribute("name") = instance2.c_str(); xml_node meta = item.append_child("metadata"); meta.append_child("connection"); } ostringstream oss; xdoc.save(oss); return oss.str(); } }
36.486726
81
0.617997
[ "vector" ]
eabc0ace137d1b0d786599bee874aff9507dd5b0
7,287
cc
C++
voro++/examples/no_release/sphere_mesh.cc
lsmo-epfl/zeoplusplus
b8acd8d08d7256aecdbb92454250760314a00b06
[ "BSD-3-Clause-LBNL" ]
2
2019-11-14T02:27:33.000Z
2020-05-05T23:17:47.000Z
voro++/examples/no_release/sphere_mesh.cc
lsmo-epfl/zeoplusplus
b8acd8d08d7256aecdbb92454250760314a00b06
[ "BSD-3-Clause-LBNL" ]
4
2018-10-17T08:20:58.000Z
2020-12-19T03:28:01.000Z
voro++/examples/no_release/sphere_mesh.cc
lsmo-epfl/zeopp-lsmo
b8acd8d08d7256aecdbb92454250760314a00b06
[ "BSD-3-Clause-LBNL" ]
3
2019-03-04T11:25:44.000Z
2019-05-29T16:37:12.000Z
// Voronoi calculation example code // // Author : Chris H. Rycroft (LBL / UC Berkeley) // Email : chr@alum.mit.edu // Date : August 30th 2011 #include "voro++.hh" using namespace voro; #include <vector> using namespace std; // Set up constants for the container geometry const double boxl = 1.2; // Set up the number of blocks that the container is divided into const int bl = 14; // Set the number of particles that are going to be randomly introduced const int particles = 2000; const int nface = 11; // This function returns a random double between 0 and 1 double rnd() { return double(rand()) / RAND_MAX; } struct wall_shell : public wall { public: wall_shell(double xc_, double yc_, double zc_, double rc, double sc, int w_id_ = -99) : w_id(w_id_), xc(xc_), yc(yc_), zc(zc_), lc(rc - sc), uc(rc + sc) {} bool point_inside(double x, double y, double z) { double rsq = (x - xc) * (x - xc) + (y - yc) * (y - yc) + (z - zc) * (z - zc); return rsq > lc * lc && rsq < uc * uc; } template <class v_cell> bool cut_cell_base(v_cell &c, double x, double y, double z) { double xd = x - xc, yd = y - yc, zd = z - zc, dq = xd * xd + yd * yd + zd * zd, dq2; if (dq > 1e-5) { dq2 = 2 * (sqrt(dq) * lc - dq); dq = 2 * (sqrt(dq) * uc - dq); return c.nplane(xd, yd, zd, dq, w_id) && c.nplane(-xd, -yd, -zd, -dq2, w_id); } return true; } bool cut_cell(voronoicell &c, double x, double y, double z) { return cut_cell_base(c, x, y, z); } bool cut_cell(voronoicell_neighbor &c, double x, double y, double z) { return cut_cell_base(c, x, y, z); } private: const int w_id; const double xc, yc, zc, lc, uc; }; int main() { int i = 0, j, k, l, ll, o; double x, y, z, r, dx, dy, dz; int faces[nface], *fp; double p[3 * particles]; // Create a container with the geometry given above, and make it // non-periodic in each of the three coordinates. Allocate space for // eight particles within each computational block container con(-boxl, boxl, -boxl, boxl, -boxl, boxl, bl, bl, bl, false, false, false, 8); wall_shell ws(0, 0, 0, 1, 0.00001); con.add_wall(ws); // Randomly add particles into the container while (i < particles) { x = boxl * (2 * rnd() - 1); y = boxl * (2 * rnd() - 1); z = boxl * (2 * rnd() - 1); r = x * x + y * y + z * z; if (r > 1e-5) { r = 1 / sqrt(r); x *= r; y *= r; z *= r; con.put(i, x, y, z); i++; } } for (l = 0; l < 100; l++) { c_loop_all vl(con); voronoicell c; for (fp = faces; fp < faces + nface; fp++) *fp = 0; if (vl.start()) do if (con.compute_cell(c, vl)) { vl.pos(i, x, y, z, r); c.centroid(dx, dy, dz); p[3 * i] = x + dx; p[3 * i + 1] = y + dy; p[3 * i + 2] = z + dz; i = c.number_of_faces() - 4; if (i < 0) i = 0; if (i >= nface) i = nface - 1; faces[i]++; } while (vl.inc()); con.clear(); double fac = 0; // l<9000?0.1/sqrt(double(l)):0; for (i = 0; i < particles; i++) con.put(i, p[3 * i] + fac * (2 * rnd() - 1), p[3 * i + 1] + fac * (2 * rnd() - 1), p[3 * i + 2] + fac * (2 * rnd() - 1)); printf("%d", l); for (fp = faces; fp < faces + nface; fp++) printf(" %d", *fp); puts(""); } // Output the particle positions in gnuplot format con.draw_particles("sphere_mesh_p.gnu"); // Output the Voronoi cells in gnuplot format con.draw_cells_gnuplot("sphere_mesh_v.gnu"); // Allocate memory for neighbor relations int *q = new int[particles * nface], *qn = new int[particles], *qp; for (l = 0; l < particles; l++) qn[l] = 0; // Create a table of all neighbor relations vector<int> vi; voronoicell_neighbor c; c_loop_all vl(con); if (vl.start()) do if (con.compute_cell(c, vl)) { i = vl.pid(); qp = q + i * nface; c.neighbors(vi); if (vi.size() > nface + 2) voro_fatal_error("Too many faces; boost nface", 5); for (l = 0; l < (signed int)vi.size(); l++) if (vi[l] >= 0) qp[qn[i]++] = vi[l]; } while (vl.inc()); // Sort the connections in anti-clockwise order bool connect; int tote = 0; for (l = 0; l < particles; l++) { tote += qn[l]; for (i = 0; i < qn[l] - 2; i++) { o = q[l * nface + i]; // printf("---> %d,%d\n",i,o); j = i + 1; while (j < qn[l] - 1) { ll = q[l * nface + j]; // printf("-> %d %d\n",j,ll); connect = false; for (k = 0; k < qn[ll]; k++) { // printf("%d %d %d\n",ll,k,q[ll*nface+k]); if (q[ll * nface + k] == o) { connect = true; break; } } if (connect) break; j++; } // Swap the connected vertex into this location // printf("%d %d\n",i+1,j); o = q[l * nface + i + 1]; q[l * nface + i + 1] = q[l * nface + j]; q[l * nface + j] = o; } // Reverse all connections if the have the wrong handedness j = 3 * l; k = 3 * q[l * nface]; o = 3 * q[l * nface + 1]; x = p[j] - p[k]; dx = p[j] - p[o]; y = p[j + 1] - p[k + 1]; dy = p[j + 1] - p[o + 1]; z = p[j + 2] - p[k + 2]; dz = p[j + 2] - p[o + 2]; if (p[j] * (y * dz - z * dy) + p[j + 1] * (z * dx - x * dz) + p[j + 2] * (x * dy - y * dx) < 0) { for (i = 0; i < qn[l] / 2; i++) { o = q[l * nface + i]; q[l * nface + i] = q[l * nface + qn[l] - 1 - i]; q[l * nface + qn[l] - 1 - i] = o; } } } FILE *ff = safe_fopen("sphere_mesh.net", "w"); int *mp = new int[particles], *mpi = new int[particles]; for (i = 0; i < particles; i++) mp[i] = -1; *mpi = 0; *mp = 0; l = 1; o = 0; while (o < l) { i = mpi[o]; for (j = 0; j < qn[i]; j++) { k = q[i * nface + j]; if (mp[k] == -1) { mpi[l] = k; mp[k] = l++; } if (mp[i] < mp[k]) fprintf(ff, "%g %g %g\n%g %g %g\n\n\n", p[3 * i], p[3 * i + 1], p[3 * i + 2], p[3 * k], p[3 * k + 1], p[3 * k + 2]); } o++; } fclose(ff); // Save binary representation of the mesh FILE *fb = safe_fopen("sphere_mesh.bin", "wb"); // Write header int kk[3], sz = tote + particles + 2, *red(new int[sz]), *rp = red; *kk = 1; kk[1] = sz; kk[2] = 3 * particles; fwrite(kk, sizeof(int), 3, fb); // Assemble the connections and write them *(rp++) = particles; *(rp++) = tote; for (l = 0; l < particles; l++) *(rp++) = qn[mpi[l]]; for (l = 0; l < particles; l++) { i = mpi[l]; printf("%d", l); for (j = 0; j < qn[i]; j++) { *(rp++) = mp[q[i * nface + j]]; printf(" %d", *(rp - 1)); } puts(""); } fwrite(red, sizeof(int), sz, fb); double *pm = new double[3 * particles], *a = pm, *b; for (i = 0; i < particles; i++) { b = p + 3 * mpi[i]; *(a++) = *(b++); *(a++) = *(b++); *(a++) = *b; } fwrite(pm, sizeof(double), 3 * particles, fb); delete[] pm; // Free dynamically allocated arrays delete[] red; delete[] mpi; delete[] mp; delete[] qn; delete[] q; }
27.498113
80
0.4777
[ "mesh", "geometry", "vector" ]
eac1732d1963ebb2186fc3589738098bd4004f26
814
hpp
C++
templates/projects/sfml_window/include/Window.hpp
Lehdari/Pulautin
5f5b5221b33a1c1c18e75d0d041c9aad6c4b4af6
[ "MIT" ]
null
null
null
templates/projects/sfml_window/include/Window.hpp
Lehdari/Pulautin
5f5b5221b33a1c1c18e75d0d041c9aad6c4b4af6
[ "MIT" ]
null
null
null
templates/projects/sfml_window/include/Window.hpp
Lehdari/Pulautin
5f5b5221b33a1c1c18e75d0d041c9aad6c4b4af6
[ "MIT" ]
null
null
null
// // Created by Lehdari on 29.9.2018. // #ifndef TYPES_HPP #define TYPES_HPP #include <SFML/Window.hpp> class Window { public: struct Settings { std::string windowName; sf::VideoMode videoMode; int64_t framerateLimit; Settings(const std::string& windowName = "", const sf::VideoMode& videoMode = sf::VideoMode(800, 600), int64_t framerateLimit = 60) : windowName (windowName), videoMode (videoMode), framerateLimit (framerateLimit) {} }; Window(const Settings& settings = Settings()); void loop(void); private: Settings _settings; sf::Window _window; void handleEvents(sf::Event& event); void render(void); }; #endif // TYPES_HPP
19.853659
74
0.578624
[ "render" ]
eac7295521e957a1960ee5e1b62c4b07dd53b1d5
14,492
hpp
C++
patch/patch_undo.hpp
ePi5131/patch.aul
cfdea967549ad8527b2c0830eb0f40a8cbec149a
[ "MIT" ]
14
2022-03-29T09:23:39.000Z
2022-03-31T10:03:52.000Z
patch/patch_undo.hpp
ePi5131/patch.aul
cfdea967549ad8527b2c0830eb0f40a8cbec149a
[ "MIT" ]
5
2022-03-30T07:53:18.000Z
2022-03-31T10:07:08.000Z
patch/patch_undo.hpp
ePi5131/patch.aul
cfdea967549ad8527b2c0830eb0f40a8cbec149a
[ "MIT" ]
1
2022-03-30T07:02:24.000Z
2022-03-30T07:02:24.000Z
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "macro.h" #ifdef PATCH_SWITCH_UNDO #include <exedit.hpp> #include "util_magic.hpp" #include "global.hpp" #include "offset_address.hpp" #include "config_rw.hpp" // ty saunazo namespace patch { // init at exedit load inline class undo_t { inline static ExEdit::Object** ObjectArrayPointer_ptr; inline static ExEdit::LayerSetting** layer_setting_ofsptr_ptr; inline static void** exdata_buffer_ptr; inline static int* timeline_obj_click_mode_ptr; inline static int* ObjDlg_ObjectIndex_ptr; inline static int* timeline_edit_both_adjacent_ptr; inline static int* UndoInfo_current_id_ptr; inline static ExEdit::SceneSetting* scene_setting; inline static void(__cdecl*set_undo)(unsigned int, unsigned int); inline static void(__cdecl*AddUndoCount)(); inline static int(__cdecl*efDraw_func_WndProc)(HWND, UINT, WPARAM, LPARAM, AviUtl::EditHandle*, ExEdit::Filter*); inline static int(__cdecl*NormalizeExeditTimelineY)(int); inline static void(__cdecl *add_track_value)(ExEdit::Filter*, int, int); inline constexpr static int UNDO_INTERVAL = 1000; static void __cdecl set_undo_wrap_42878(unsigned int object_idx, int layer_id) { if (layer_id < (*ObjectArrayPointer_ptr)[object_idx].layer_disp) { set_undo(object_idx, 8); } } static void __cdecl set_undo_wrap_40e5c(unsigned int object_idx, unsigned int flag) { // select_idx_list set_undo(reinterpret_cast<int*>(GLOBAL::exedit_base + 0x179230)[object_idx], flag); } inline constexpr static int FILTER_ID_MOVIE = 0; // track 0 check 0 exdata 268 = maxframe inline constexpr static int FILTER_ID_AUDIO = 2; // track 0 check 0,1 exdata 268 = maxframe inline constexpr static int FILTER_ID_WAVEFORM = 6; // track 0 check 3 exdata 268 = maxframe inline constexpr static int FILTER_ID_SCENE = 7; // track 0 check 0 exdata 0 = sceneid inline constexpr static int FILTER_ID_SCENE_AUDIO = 8; // track 0 check 0,1 exdata 0 = sceneid inline constexpr static int FILTER_ID_MOVIE_MIX = 82; // track 0 check 0 exdata 268 = maxframe static void __cdecl set_undo_wrap_3e037(unsigned int object_idx, unsigned int flag); static int __cdecl efDraw_func_WndProc_wrap_06e2b4(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, AviUtl::EditHandle* editp, ExEdit::Filter* efp); static int __stdcall f8b97f(HWND hwnd, ExEdit::Filter* efp, WPARAM wparam, LPARAM lparam); static int __stdcall f8ba87_8bad5(ExEdit::Filter* efp, HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); static int __stdcall f8bb4d_8bbcc(int value, int8_t* exdata, int offset, ExEdit::Filter* efp); static int* __stdcall f59e27(WPARAM wparam, LPARAM lparam, ExEdit::Filter* efp, UINT message); static int __stdcall f8b9f0(ExEdit::Filter* efp, HWND hWnd, LPWSTR lpString, int nMaxCount); static int __stdcall f875ef(ExEdit::Filter* efp, HWND hWnd, LPWSTR lpString); static int __cdecl NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a(int timeline_y); static int __cdecl NormalizeExeditTimelineY_wrap_4253e(int timeline_y); static ExEdit::Object* __stdcall f42617(); static void __stdcall f4355c(ExEdit::Object* obj); static void __stdcall f435bd(ExEdit::Object* obj); static void __cdecl add_track_value_wrap(ExEdit::Filter* efp, int track_id, int add_value); static void interval_set_undo(int object_idx, int flag) { static ULONGLONG pretime = 0; static int pre_undo_id = 0; int& UndoInfo_current_id = *UndoInfo_current_id_ptr; ULONGLONG time = GetTickCount64(); if (pretime < time - UNDO_INTERVAL || pre_undo_id != UndoInfo_current_id) { AddUndoCount(); set_undo(object_idx, flag); } pretime = time; pre_undo_id = UndoInfo_current_id; } bool enabled = true; bool enabled_i; inline static const char key[] = "undo"; public: void init() { enabled_i = enabled; if (!enabled_i) return; ObjectArrayPointer_ptr = reinterpret_cast<decltype(ObjectArrayPointer_ptr)>(GLOBAL::exedit_base + OFS::ExEdit::ObjectArrayPointer); layer_setting_ofsptr_ptr = reinterpret_cast<decltype(layer_setting_ofsptr_ptr)>(GLOBAL::exedit_base + 0x0a4058); exdata_buffer_ptr = reinterpret_cast<void**>(GLOBAL::exedit_base + 0x1e0fa8); timeline_obj_click_mode_ptr = reinterpret_cast<int*>(GLOBAL::exedit_base + 0x177a24); ObjDlg_ObjectIndex_ptr = reinterpret_cast<int*>(GLOBAL::exedit_base + 0x177a10); timeline_edit_both_adjacent_ptr = reinterpret_cast<int*>(GLOBAL::exedit_base + 0x14ea00); scene_setting = reinterpret_cast<decltype(scene_setting)>(GLOBAL::exedit_base + 0x177a50); UndoInfo_current_id_ptr = reinterpret_cast<decltype(UndoInfo_current_id_ptr)>(GLOBAL::exedit_base + 0x244e14); set_undo = reinterpret_cast<decltype(set_undo)>(GLOBAL::exedit_base + 0x08d290); AddUndoCount = reinterpret_cast<decltype(AddUndoCount)>(GLOBAL::exedit_base + 0x08d150); efDraw_func_WndProc = reinterpret_cast<decltype(efDraw_func_WndProc)>(GLOBAL::exedit_base + 0x01b550); NormalizeExeditTimelineY = reinterpret_cast<decltype(NormalizeExeditTimelineY)>(GLOBAL::exedit_base + 0x032c10); add_track_value = reinterpret_cast<decltype(add_track_value)>(GLOBAL::exedit_base + 0x01c0f0); // レイヤー削除→元に戻すで他シーンのオブジェクトが消える { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x042875, 2); h.store_i8(0, '\x56'); // push esi=layer_id h.store_i8(1, '\x90'); // nop ReplaceNearJmp(GLOBAL::exedit_base + 0x042879, &set_undo_wrap_42878); } // Ctrlで複数オブジェクトを選択しながら設定ダイアログのトラックバーを動かすと一部オブジェクトが正常に戻らない ReplaceNearJmp(GLOBAL::exedit_base + 0x040e5d, &set_undo_wrap_40e5c); // オブジェクトの左端をつまんで動かすと再生位置パラメータが変わるが、それが元に戻らない ReplaceNearJmp(GLOBAL::exedit_base + 0x03e038, &set_undo_wrap_3e037); // 一部フィルタのファイル参照を変更→元に戻すで設定ダイアログが更新されない(音声波形など) OverWriteOnProtectHelper(GLOBAL::exedit_base + 0x08d50e, 4).store_i32(0, '\x0f\x1f\x40\x00'); // nop // 部分フィルタのマスクの種類を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x06e2b5, &efDraw_func_WndProc_wrap_06e2b4); // テキストオブジェクトのフォントを変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08b97c, 8); h.store_i32(0, '\x90\x57\x51\xe8'); // nop; push edi=efp; push ecx; call (rel32) h.replaceNearJmp(4, &f8b97f); } // テキストオブジェクトの影付き・縁付きを変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08ba86, 2); h.store_i16(0, '\x57\xe8'); // push edi=efp; call (rel32) ReplaceNearJmp(GLOBAL::exedit_base + 0x08ba88, &f8ba87_8bad5); } // テキストオブジェクトの文字配置(左寄せ[上]など)を変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08bad4, 6); h.store_i16(0, '\x57\xe8'); // push edi=efp; call (rel32) h.replaceNearJmp(2, &f8ba87_8bad5); } // テキストオブジェクトの字間を変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08bb48, 10); h.store_i32(0, '\x57\x6a\x05\x56'); // push edi=efp; push 5; push esi=exdata h.store_i16(4, '\x50\xe8'); // push eax=value; call rel32 h.replaceNearJmp(6, &f8bb4d_8bbcc); } // テキストオブジェクトの行間を変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08bbc7, 10); h.store_i32(0, '\x57\x6a\x06\x56'); // push edi=efp; push 6; push esi=exdata h.store_i16(4, '\x50\xe8'); // push eax=value; call rel32 h.replaceNearJmp(6, &f8bb4d_8bbcc); } // グループ制御とかの対象レイヤー数を変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x059e1b, 20); char patch[] = { 0x51, // push ecx=message 0x50, // push eax=efp 0x8b, 0x4c, 0x24, 0x28, // mov ecx, dword ptr[esp + 0x28]=lparam 0x51, // push ecx 0x8b, 0x4c, 0x24, 0x28, // mov ecx, dword ptr[esp + 0x28]=wparam 0x51, // push ecx 0xe8, 0, 0, 0, 0, // call rel32 0x85, 0xc0, // test eax, eax 0x74, /* 0x6e */ // JZ +0x6e }; memcpy(reinterpret_cast<void*>(h.address()), patch, sizeof(patch)); h.replaceNearJmp(13, &f59e27); } // テキストを変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x08b9ef, 6); h.store_i16(0, '\x57\xe8'); // push edi; call (rel32) h.replaceNearJmp(2, &f8b9f0); } // スクリプト制御・カメラスクリプトを変更してもUndoデータが生成されない { // 100875e7 68 00 04 00 00 PUSH 0x400 // 100875ec 56 PUSH ESI // 100875ed 51 PUSH ECX // 100875ee ff 15 54 a2 09 10 CALL dword ptr [->USER32.DLL::GetWindowTextW] = 0009bc30 // ↓ // 100875e7 8b 54 24 38 MOV EDX, DWORD PTR [ESP+38H] // 100875eb 90 NOP // 100875ec 56 PUSH ESI // 100875ed 51 PUSH ECX // 100875ee 52 PUSH EDX // 100875ef e8 XXXX CALL rel32 OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x0875e7, 13); h.store_i32(0, '\x8b\x54\x24\x38'); h.store_i32(4, '\x90\x56\x51\x52'); h.store_i8(8, '\xe8'); h.replaceNearJmp(9, &f875ef); } // 左クリックよりレイヤーの表示状態を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x03c8fb, &NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a); // 右クリックメニューよりレイヤーの表示状態を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x04262a, &NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a); // 右クリックメニューよりレイヤーのロック状態を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x042663, &NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a); // 右クリックメニューよりレイヤーの座標のリンク状態を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x042925, &NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a); // 右クリックメニューより上クリッピング状態を変更してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x042a0b, &NormalizeExeditTimelineY_wrap_3c8fa_42629_42662_42924_42a0a); // 右クリックメニューより他のレイヤーを全表示/非表示を押してもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x04253f, &NormalizeExeditTimelineY_wrap_4253e); // ショートカットよりレイヤーの表示状態を変更してもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x042617, 5); h.store_i8(0, '\xe8'); h.replaceNearJmp(1, &f42617); } // カメラ制御の対象 を切り替えてもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x04355b, 6); h.store_i16(0, '\x51\xe8'); // push ecx, call (rel32) h.replaceNearJmp(2, &f4355c); } // 上のオブジェクトでクリッピング を切り替えてもUndoデータが生成されない { OverWriteOnProtectHelper h(GLOBAL::exedit_base + 0x0435ba, 8); h.store_i32(0, '\x90\x90\x50\xe8'); // nop, push eax, call (rel32) h.replaceNearJmp(4, &f435bd); } // テンキー2468+-*/ Ctrl+テンキー2468 で(座標XY 回転 拡大率 中心XY)トラックバーを変えてもUndoデータが生成されない ReplaceNearJmp(GLOBAL::exedit_base + 0x01b611, &add_track_value_wrap); // テンキー4座標X- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b646, &add_track_value_wrap); // Ctrl+テンキー6中心X+ ReplaceNearJmp(GLOBAL::exedit_base + 0x01b674, &add_track_value_wrap); // テンキー6座標X+ ReplaceNearJmp(GLOBAL::exedit_base + 0x01b6ab, &add_track_value_wrap); // Ctrl+テンキー8中心Y- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b6db, &add_track_value_wrap); // テンキー8座標Y- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b710, &add_track_value_wrap); // Ctrl+テンキー2中心Y+, Ctrl+テンキー4中心X- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b73e, &add_track_value_wrap); // テンキー2座標Y+ ReplaceNearJmp(GLOBAL::exedit_base + 0x01b765, &add_track_value_wrap); // テンキー-拡大率- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b78c, &add_track_value_wrap); // テンキー+拡大率+ ReplaceNearJmp(GLOBAL::exedit_base + 0x01b7b0, &add_track_value_wrap); // テンキー/回転- ReplaceNearJmp(GLOBAL::exedit_base + 0x01b7d4, &add_track_value_wrap); // テンキー*回転+ } void switching(bool flag) { enabled = flag; } bool is_enabled() { return enabled; } bool is_enabled_i() { return enabled_i; } void switch_load(ConfigReader& cr) { cr.regist(key, [this](json_value_s* value) { ConfigReader::load_variable(value, enabled); }); } void switch_store(ConfigWriter& cw) { cw.append(key, enabled); } } undo; } #endif
45.716088
162
0.634488
[ "object" ]
eacab1e88baa19853bc2f25f7b13d86fe9a240b6
8,284
hpp
C++
src/Viewer/src/Geometry2DBeam.hpp
LBNL-ETA/Windows-CalcEngine
c81528f25ffb79989fcb15b03f00b7c18da138c4
[ "BSD-3-Clause-LBNL" ]
15
2018-04-20T19:16:50.000Z
2022-02-11T04:11:41.000Z
src/Viewer/src/Geometry2DBeam.hpp
LBNL-ETA/Windows-CalcEngine
c81528f25ffb79989fcb15b03f00b7c18da138c4
[ "BSD-3-Clause-LBNL" ]
31
2016-04-05T20:56:28.000Z
2022-03-31T22:02:46.000Z
src/Viewer/src/Geometry2DBeam.hpp
LBNL-ETA/Windows-CalcEngine
c81528f25ffb79989fcb15b03f00b7c18da138c4
[ "BSD-3-Clause-LBNL" ]
6
2018-04-20T19:38:58.000Z
2020-04-06T00:30:47.000Z
#ifndef GEOMETRY2DBEAM_H #define GEOMETRY2DBEAM_H #include <memory> #include <vector> namespace FenestrationCommon { enum class Side; } namespace Viewer { class CViewSegment2D; class CGeometry2D; class CSegment2D; class CPoint2D; //////////////////////////////////////////////////////////////////////////////////////// // BeamViewFactor //////////////////////////////////////////////////////////////////////////////////////// struct BeamViewFactor { BeamViewFactor(size_t const t_Geometry2DIndex, size_t const t_SegmentIndex, double const t_Value, double const t_PercentHit); bool operator==(BeamViewFactor const & t_BVF1) const; // static bool isEqual( const BeamViewFactor& t_VF1, const BeamViewFactor& t_VF2 ); size_t enclosureIndex; size_t segmentIndex; double value; double percentHit; }; //////////////////////////////////////////////////////////////////////////////////////// // CDirect2DBeam //////////////////////////////////////////////////////////////////////////////////////// // Keeps information about single beam and segments that are intersected with it class CDirect2DBeam { public: explicit CDirect2DBeam(std::shared_ptr<const CViewSegment2D> const & t_Beam); // Checks if segments intersects with the beam void checkSegment(std::shared_ptr<const CViewSegment2D> const & t_Segment) const; double Side() const; // Check if passed segment is part of the beam std::shared_ptr<const CViewSegment2D> getClosestCommonSegment(std::shared_ptr<const CDirect2DBeam> const & t_Beam) const; double cosAngle(std::shared_ptr<const CViewSegment2D> const & t_Segment) const; private: // Checks if segment is aleardy part of beam hit bool isSegmentIn(std::shared_ptr<const CViewSegment2D> const & t_Segment) const; // Direct beam std::shared_ptr<const CViewSegment2D> m_Beam; // Segments that beam is intersecting with std::shared_ptr<std::vector<std::shared_ptr<const CViewSegment2D>>> m_Segments; }; //////////////////////////////////////////////////////////////////////////////////////// // CDirect2DRay //////////////////////////////////////////////////////////////////////////////////////// // Keeps information about direct ray. Ray is containing of two direct beams. class CDirect2DRay { public: CDirect2DRay(std::shared_ptr<CDirect2DBeam> const & t_Beam1, std::shared_ptr<CDirect2DBeam> const & t_Beam2); CDirect2DRay(std::shared_ptr<CViewSegment2D> const & t_Ray1, std::shared_ptr<CViewSegment2D> const & t_Ray2); // Returns ray height. Projection of the ray to the normal plane. double rayNormalHeight() const; // Checks if segments intersects with the ray void checkSegment(std::shared_ptr<const CViewSegment2D> const & t_Segment) const; // Return segment hit by the ray std::shared_ptr<const CViewSegment2D> closestSegmentHit() const; double cosAngle(std::shared_ptr<const CViewSegment2D> const & t_Segment) const; private: std::shared_ptr<CDirect2DBeam> m_Beam1; std::shared_ptr<CDirect2DBeam> m_Beam2; }; //////////////////////////////////////////////////////////////////////////////////////// // CDirect2DRayResult //////////////////////////////////////////////////////////////////////////////////////// // Keeps result of beam ViewFactors. It is expensive operation to recalculate them every time // so this will just save results for the next call class CDirect2DRaysResult { public: CDirect2DRaysResult(double const t_ProfileAngle, double const t_DirectToDirect, std::shared_ptr<std::vector<BeamViewFactor>> const & t_BeamViewFactors); // Beam view factors for given profile angle std::shared_ptr<std::vector<BeamViewFactor>> beamViewFactors() const; // Direct to direct transmitted beam component double directToDirect() const; double profileAngle() const; private: std::shared_ptr<std::vector<BeamViewFactor>> m_ViewFactors; double m_DirectToDirect; double m_ProfileAngle; }; //////////////////////////////////////////////////////////////////////////////////////// // CDirect2DRayResults //////////////////////////////////////////////////////////////////////////////////////// // Keeps result of beam ViewFactors. It is expensive operation to recalculate them every time // so this will just save results for the next call class CDirect2DRaysResults { public: CDirect2DRaysResults(); // Beam view factors for given profile angle std::shared_ptr<CDirect2DRaysResult> getResult(double const t_ProfileAngle); // append results std::shared_ptr<CDirect2DRaysResult> append(double const t_ProfileAngle, double const t_DirectToDirect, std::shared_ptr<std::vector<BeamViewFactor>> const & t_BeamViewFactor) const; // clear all results void clear() const; private: std::shared_ptr<std::vector<std::shared_ptr<CDirect2DRaysResult>>> m_Results; }; //////////////////////////////////////////////////////////////////////////////////////// // CDirect2DRays //////////////////////////////////////////////////////////////////////////////////////// // Keeps information about group of direct rays entering or exiting the enclosure class CDirect2DRays { public: explicit CDirect2DRays(FenestrationCommon::Side const t_Side); void appendGeometry2D(std::shared_ptr<const CGeometry2D> const & t_Geometry2D); // Beam view factors for given profile angle std::shared_ptr<std::vector<BeamViewFactor>> beamViewFactors(double const t_ProfileAngle); // Direct to direct transmitted beam component double directToDirect(double const t_ProfileAngle); private: void calculateAllProperties(double const t_ProfileAngle); // Finds lower and upper ray of every enclosure in the system void findRayBoundaries(double const t_ProfileAngle); // Finds all points that are on the path of the ray void findInBetweenRays(double const t_ProfileAngle); // Calculate beam view factors void calculateBeamProperties(double const t_ProfileAngle); // Check if given point is in possible path of the ray bool isInRay(CPoint2D const & t_Point) const; std::shared_ptr<CViewSegment2D> createSubBeam(CPoint2D const & t_Point, double const t_ProfileAngle) const; FenestrationCommon::Side m_Side; std::vector<std::shared_ptr<const CGeometry2D>> m_Geometries2D; std::shared_ptr<CViewSegment2D> m_LowerRay; std::shared_ptr<CViewSegment2D> m_UpperRay; std::vector<std::shared_ptr<CDirect2DRay>> m_Rays; CDirect2DRaysResults m_Results; std::shared_ptr<CDirect2DRaysResult> m_CurrentResult; }; //////////////////////////////////////////////////////////////////////////////////////// // CGeometry2DBeam //////////////////////////////////////////////////////////////////////////////////////// // Class to handle beam view factors class CGeometry2DBeam { public: CGeometry2DBeam(); void appendGeometry2D(std::shared_ptr<const CGeometry2D> const & t_Geometry2D); std::shared_ptr<std::vector<BeamViewFactor>> beamViewFactors(double const t_ProfileAngle, FenestrationCommon::Side const t_Side); // Direct to direct transmitted beam component double directToDirect(double const t_ProfileAngle, FenestrationCommon::Side const t_Side); private: CDirect2DRays * getRay(FenestrationCommon::Side const t_Side); CDirect2DRays m_Incoming; CDirect2DRays m_Outgoing; }; } // namespace Viewer #endif
36.817778
100
0.566997
[ "vector" ]
ead07fb500e8f3a32785b87c9e078320a891dd53
62,652
cpp
C++
common/bpcodec/test/TestBundleViewV7.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
common/bpcodec/test/TestBundleViewV7.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
common/bpcodec/test/TestBundleViewV7.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include "codec/BundleViewV7.h" #include <iostream> #include <string> #include <inttypes.h> #include <vector> #include "Uri.h" #include <boost/next_prior.hpp> #include <boost/make_unique.hpp> #include "PaddedVectorUint8.h" static const uint64_t PRIMARY_SRC_NODE = 100; static const uint64_t PRIMARY_SRC_SVC = 1; static const uint64_t PRIMARY_DEST_NODE = 200; static const uint64_t PRIMARY_DEST_SVC = 2; static const uint64_t PRIMARY_TIME = 10000; static const uint64_t PRIMARY_LIFETIME = 2000; static const uint64_t PRIMARY_SEQ = 1; static void AppendCanonicalBlockAndRender(BundleViewV7 & bv, BPV7_BLOCK_TYPE_CODE newType, std::string & newBlockBody, uint64_t blockNumber, const BPV7_CRC_TYPE crcTypeToUse) { //std::cout << "append " << (int)newType << "\n"; std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; block.m_blockTypeCode = newType; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_dataLength = newBlockBody.size(); block.m_dataPtr = (uint8_t*)newBlockBody.data(); //blockBodyAsVecUint8 must remain in scope until after render block.m_crcType = crcTypeToUse; block.m_blockNumber = blockNumber; bv.AppendMoveCanonicalBlock(blockPtr); uint64_t expectedRenderSize; BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); //check again after render BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); } static void PrependCanonicalBlockAndRender(BundleViewV7 & bv, BPV7_BLOCK_TYPE_CODE newType, std::string & newBlockBody, uint64_t blockNumber, const BPV7_CRC_TYPE crcTypeToUse) { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; block.m_blockTypeCode = newType; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_dataLength = newBlockBody.size(); block.m_dataPtr = (uint8_t*)newBlockBody.data(); //blockBodyAsVecUint8 must remain in scope until after render block.m_crcType = crcTypeToUse; block.m_blockNumber = blockNumber; bv.PrependMoveCanonicalBlock(blockPtr); uint64_t expectedRenderSize; BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); //check again after render BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); } static void PrependCanonicalBlockAndRender_AllocateOnly(BundleViewV7 & bv, BPV7_BLOCK_TYPE_CODE newType, uint64_t dataLengthToAllocate, uint64_t blockNumber, const BPV7_CRC_TYPE crcTypeToUse) { //std::cout << "append " << (int)newType << "\n"; std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; block.m_blockTypeCode = newType; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_dataLength = dataLengthToAllocate; block.m_dataPtr = NULL; block.m_crcType = crcTypeToUse; block.m_blockNumber = blockNumber; bv.PrependMoveCanonicalBlock(blockPtr); uint64_t expectedRenderSize; BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); //check again after render BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); } static void ChangeCanonicalBlockAndRender(BundleViewV7 & bv, BPV7_BLOCK_TYPE_CODE oldType, BPV7_BLOCK_TYPE_CODE newType, std::string & newBlockBody) { //std::cout << "change " << (int)oldType << " to " << (int)newType << "\n"; std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(oldType, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7CanonicalBlock & block = *(blocks[0]->headerPtr); block.m_blockTypeCode = newType; block.m_dataLength = newBlockBody.size(); block.m_dataPtr = (uint8_t*)newBlockBody.data(); //blockBodyAsVecUint8 must remain in scope until after render blocks[0]->SetManuallyModified(); uint64_t expectedRenderSize; BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); //check again after render BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); } static void GenerateBundle(const std::vector<BPV7_BLOCK_TYPE_CODE> & canonicalTypesVec, const std::vector<uint8_t> & blockNumbersToUse, const std::vector<std::string> & canonicalBodyStringsVec, BundleViewV7 & bv, const BPV7_CRC_TYPE crcTypeToUse) { Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT; //All BP endpoints identified by ipn-scheme endpoint IDs are singleton endpoints. primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); primary.m_destinationEid.Set(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); for (std::size_t i = 0; i < canonicalTypesVec.size(); ++i) { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; //block.SetZero(); block.m_blockTypeCode = canonicalTypesVec[i]; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = blockNumbersToUse[i]; block.m_crcType = crcTypeToUse; const std::string & blockBody = canonicalBodyStringsVec[i]; block.m_dataLength = blockBody.size(); block.m_dataPtr = (uint8_t*)blockBody.data(); //blockBodyAsVecUint8 must remain in scope until after render BOOST_REQUIRE(blockPtr); bv.AppendMoveCanonicalBlock(blockPtr); BOOST_REQUIRE(!blockPtr); } BOOST_REQUIRE(bv.Render(5000)); } BOOST_AUTO_TEST_CASE(BundleViewV7TestCase) { const std::vector<BPV7_BLOCK_TYPE_CODE> canonicalTypesVec = { BPV7_BLOCK_TYPE_CODE::UNUSED_5, BPV7_BLOCK_TYPE_CODE::UNUSED_3, BPV7_BLOCK_TYPE_CODE::UNUSED_2, BPV7_BLOCK_TYPE_CODE::PAYLOAD //last block must be payload block }; const std::vector<uint8_t> blockNumbersToUse = { 2,3,4,1 }; //The block number of the payload block is always 1. const std::vector<std::string> canonicalBodyStringsVec = { "The ", "quick ", " brown", " fox" }; const std::vector<BPV7_CRC_TYPE> crcTypesVec = { BPV7_CRC_TYPE::NONE, BPV7_CRC_TYPE::CRC16_X25, BPV7_CRC_TYPE::CRC32C }; for (std::size_t crcI = 0; crcI < crcTypesVec.size(); ++crcI) { const BPV7_CRC_TYPE crcTypeToUse = crcTypesVec[crcI]; BundleViewV7 bv; GenerateBundle(canonicalTypesVec, blockNumbersToUse, canonicalBodyStringsVec, bv, crcTypeToUse); std::vector<uint8_t> bundleSerializedOriginal(bv.m_frontBuffer); //std::cout << "renderedsize: " << bv.m_frontBuffer.size() << "\n"; BOOST_REQUIRE_GT(bundleSerializedOriginal.size(), 0); std::vector<uint8_t> bundleSerializedCopy(bundleSerializedOriginal); //the copy can get modified by bundle view on first load BOOST_REQUIRE(bundleSerializedOriginal == bundleSerializedCopy); bv.Reset(); //std::cout << "sz " << bundleSerializedCopy.size() << std::endl; BOOST_REQUIRE(bv.LoadBundle(&bundleSerializedCopy[0], bundleSerializedCopy.size())); BOOST_REQUIRE(bv.m_backBuffer != bundleSerializedCopy); BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedCopy); Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; BOOST_REQUIRE_EQUAL(primary.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(primary.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC)); BOOST_REQUIRE_EQUAL(primary.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primary.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bv.m_primaryBlockView.actualSerializedPrimaryBlockPtr.size(), primary.GetSerializationSize()); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), canonicalTypesVec.size()); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 0); for (std::size_t i = 0; i < canonicalTypesVec.size(); ++i) { BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(canonicalTypesVec[i]), 1); std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(canonicalTypesVec[i], blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const char * strPtr = (const char *)blocks[0]->headerPtr->m_dataPtr; std::string s(strPtr, strPtr + blocks[0]->headerPtr->m_dataLength); BOOST_REQUIRE_EQUAL(s, canonicalBodyStringsVec[i]); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockTypeCode, canonicalTypesVec[i]); } uint64_t expectedRenderSize; BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE(bv.m_backBuffer != bundleSerializedCopy); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedCopy.size()); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); //check again after render BOOST_REQUIRE(bv.GetSerializationSize(expectedRenderSize)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), expectedRenderSize); BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedCopy); //change 2nd block from quick to slow and type from 3 to 4 and render const uint32_t quickCrc = (crcTypeToUse == BPV7_CRC_TYPE::NONE) ? 0 : (crcTypeToUse == BPV7_CRC_TYPE::CRC16_X25) ? boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc16 : boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc32; std::string slowString("slow "); ChangeCanonicalBlockAndRender(bv, BPV7_BLOCK_TYPE_CODE::UNUSED_3, BPV7_BLOCK_TYPE_CODE::UNUSED_4, slowString); const uint32_t slowCrc = (crcTypeToUse == BPV7_CRC_TYPE::NONE) ? 1 : (crcTypeToUse == BPV7_CRC_TYPE::CRC16_X25) ? boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc16 : boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc32; BOOST_REQUIRE_NE(quickCrc, slowCrc); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bv.m_backBuffer.size() - 1); //"quick" to "slow" BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedOriginal); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bv.m_renderedBundle.size()); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), canonicalTypesVec.size()); //Render again //std::cout << "render again\n"; BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE(bv.m_frontBuffer == bv.m_backBuffer); //revert 2nd block std::string quickString("quick "); ChangeCanonicalBlockAndRender(bv, BPV7_BLOCK_TYPE_CODE::UNUSED_4, BPV7_BLOCK_TYPE_CODE::UNUSED_3, quickString); const uint32_t quickCrc2 = (crcTypeToUse == BPV7_CRC_TYPE::NONE) ? 0 : (crcTypeToUse == BPV7_CRC_TYPE::CRC16_X25) ? boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc16 : boost::next(bv.m_listCanonicalBlockView.begin())->headerPtr->m_computedCrc32; //std::cout << "crc=" << quickCrc << "\n"; BOOST_REQUIRE_EQUAL(quickCrc, quickCrc2); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size()); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bv.m_renderedBundle.size()); BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedOriginal); { //change PRIMARY_SEQ from 1 to 65539 (adding 4 bytes) bv.m_primaryBlockView.header.m_creationTimestamp.sequenceNumber = 65539; bv.m_primaryBlockView.SetManuallyModified(); BOOST_REQUIRE(bv.m_primaryBlockView.dirty); //std::cout << "render increase primary seq\n"; BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size() + 4); BOOST_REQUIRE(!bv.m_primaryBlockView.dirty); //render removed dirty BOOST_REQUIRE_EQUAL(primary.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(primary.m_creationTimestamp.sequenceNumber, 65539); //restore PRIMARY_SEQ bv.m_primaryBlockView.header.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; bv.m_primaryBlockView.SetManuallyModified(); //std::cout << "render restore primary seq\n"; BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size()); BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedOriginal); //back to equal } //delete and re-add 1st block { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(canonicalTypesVec.front(), blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const uint64_t blockNumber = blocks[0]->headerPtr->m_blockNumber; blocks[0]->markedForDeletion = true; //std::cout << "render delete last block\n"; BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), canonicalTypesVec.size() - 1); const uint64_t canonicalSize = //uint64_t bufferSize 1 + //cbor initial byte denoting cbor array 1 + //block type code byte 1 + //block number 1 + //m_blockProcessingControlFlags 1 + //crc type code byte 1 + //byte string header canonicalBodyStringsVec.front().length() + //data = len("The ") ((crcTypeToUse == BPV7_CRC_TYPE::NONE) ? 0 : (crcTypeToUse == BPV7_CRC_TYPE::CRC16_X25) ? 3 : 5); //crc byte array //std::cout << "canonicalSize=" << canonicalSize << "\n"; BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size() - canonicalSize); std::string frontString(canonicalBodyStringsVec.front()); PrependCanonicalBlockAndRender(bv, canonicalTypesVec.front(), frontString, blockNumber, crcTypeToUse); //0 was block number 0 from GenerateBundle BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size()); BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedOriginal); //back to equal } //delete and re-add 1st block by preallocation { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(canonicalTypesVec.front(), blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const uint64_t blockNumber = blocks[0]->headerPtr->m_blockNumber; blocks[0]->markedForDeletion = true; //std::cout << "render delete last block\n"; BOOST_REQUIRE(bv.Render(5000)); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), canonicalTypesVec.size() - 1); const uint64_t canonicalSize = //uint64_t bufferSize 1 + //cbor initial byte denoting cbor array 1 + //block type code byte 1 + //block number 1 + //m_blockProcessingControlFlags 1 + //crc type code byte 1 + //byte string header canonicalBodyStringsVec.front().length() + //data = len("The ") ((crcTypeToUse == BPV7_CRC_TYPE::NONE) ? 0 : (crcTypeToUse == BPV7_CRC_TYPE::CRC16_X25) ? 3 : 5); //crc byte array BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size() - canonicalSize); bv.m_backBuffer.assign(bv.m_backBuffer.size(), 0); //make sure zeroed out PrependCanonicalBlockAndRender_AllocateOnly(bv, canonicalTypesVec.front(), canonicalBodyStringsVec.front().length(), blockNumber, crcTypeToUse); //0 was block number 0 from GenerateBundle BOOST_REQUIRE_EQUAL(bv.m_frontBuffer.size(), bundleSerializedOriginal.size()); BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedOriginal); //still not equal, need to copy data bv.GetCanonicalBlocksByType(canonicalTypesVec.front(), blocks); //get new preallocated block BOOST_REQUIRE_EQUAL(blocks.size(), 1); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_dataLength, canonicalBodyStringsVec.front().length()); //make sure preallocated BOOST_REQUIRE_EQUAL((unsigned int)blocks[0]->headerPtr->m_dataPtr[0], 0); //make sure was zeroed out from above memcpy(blocks[0]->headerPtr->m_dataPtr, canonicalBodyStringsVec.front().data(), canonicalBodyStringsVec.front().length()); //copy data if (crcTypeToUse != BPV7_CRC_TYPE::NONE) { BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedOriginal); //still not equal, need to recompute crc blocks[0]->headerPtr->RecomputeCrcAfterDataModification((uint8_t*)blocks[0]->actualSerializedBlockPtr.data(), blocks[0]->actualSerializedBlockPtr.size()); //recompute crc } BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedOriginal); //back to equal } //test loads. { BOOST_REQUIRE(bundleSerializedCopy == bundleSerializedOriginal); //back to equal BOOST_REQUIRE(bv.CopyAndLoadBundle(&bundleSerializedCopy[0], bundleSerializedCopy.size())); //calls reset BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedCopy); BOOST_REQUIRE(bv.SwapInAndLoadBundle(bundleSerializedCopy)); //calls reset BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedCopy); BOOST_REQUIRE(bv.m_frontBuffer == bundleSerializedOriginal); } } } BOOST_AUTO_TEST_CASE(Bpv7ExtensionBlocksTestCase) { static const uint64_t PREVIOUS_NODE = 12345; static const uint64_t PREVIOUS_SVC = 678910; static const uint64_t BUNDLE_AGE_MS = 135791113; static const uint8_t HOP_LIMIT = 250; static const uint8_t HOP_COUNT = 200; const std::string payloadString = { "This is the data inside the bpv7 payload block!!!" }; const std::vector<BPV7_CRC_TYPE> crcTypesVec = { BPV7_CRC_TYPE::NONE, BPV7_CRC_TYPE::CRC16_X25, BPV7_CRC_TYPE::CRC32C }; for (std::size_t crcI = 0; crcI < crcTypesVec.size(); ++crcI) { const BPV7_CRC_TYPE crcTypeToUse = crcTypesVec[crcI]; BundleViewV7 bv; Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT; //All BP endpoints identified by ipn-scheme endpoint IDs are singleton endpoints. primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); primary.m_destinationEid.Set(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); //add previous node block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7PreviousNodeCanonicalBlock>(); Bpv7PreviousNodeCanonicalBlock & block = *(reinterpret_cast<Bpv7PreviousNodeCanonicalBlock*>(blockPtr.get())); //block.SetZero(); block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 2; block.m_crcType = crcTypeToUse; block.m_previousNode.Set(PREVIOUS_NODE, PREVIOUS_SVC); bv.AppendMoveCanonicalBlock(blockPtr); BOOST_REQUIRE_EQUAL(bv.GetNextFreeCanonicalBlockNumber(), 3); } //add bundle age block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7BundleAgeCanonicalBlock>(); Bpv7BundleAgeCanonicalBlock & block = *(reinterpret_cast<Bpv7BundleAgeCanonicalBlock*>(blockPtr.get())); //block.SetZero(); block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 3; block.m_crcType = crcTypeToUse; block.m_bundleAgeMilliseconds = BUNDLE_AGE_MS; bv.AppendMoveCanonicalBlock(blockPtr); } //add hop count block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7HopCountCanonicalBlock>(); Bpv7HopCountCanonicalBlock & block = *(reinterpret_cast<Bpv7HopCountCanonicalBlock*>(blockPtr.get())); //block.SetZero(); block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 4; block.m_crcType = crcTypeToUse; block.m_hopLimit = HOP_LIMIT; block.m_hopCount = HOP_COUNT; bv.AppendMoveCanonicalBlock(blockPtr); } //add payload block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; //block.SetZero(); block.m_blockTypeCode = BPV7_BLOCK_TYPE_CODE::PAYLOAD; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 1; //must be 1 block.m_crcType = crcTypeToUse; block.m_dataLength = payloadString.size(); block.m_dataPtr = (uint8_t*)payloadString.data(); //payloadString must remain in scope until after render bv.AppendMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.Render(5000)); std::vector<uint8_t> bundleSerializedOriginal(bv.m_frontBuffer); //std::cout << "renderedsize: " << bv.m_frontBuffer.size() << "\n"; BOOST_REQUIRE_GT(bundleSerializedOriginal.size(), 0); std::vector<uint8_t> bundleSerializedCopy(bundleSerializedOriginal); //the copy can get modified by bundle view on first load BOOST_REQUIRE(bundleSerializedOriginal == bundleSerializedCopy); bv.Reset(); //std::cout << "sz " << bundleSerializedCopy.size() << std::endl; BOOST_REQUIRE(bv.LoadBundle(&bundleSerializedCopy[0], bundleSerializedCopy.size())); BOOST_REQUIRE(bv.m_backBuffer != bundleSerializedCopy); BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedCopy); BOOST_REQUIRE_EQUAL(primary.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(primary.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC)); BOOST_REQUIRE_EQUAL(primary.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primary.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bv.m_primaryBlockView.actualSerializedPrimaryBlockPtr.size(), primary.GetSerializationSize()); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), 4); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::UNUSED_4), 0); BOOST_REQUIRE_EQUAL(bv.GetNextFreeCanonicalBlockNumber(), 5); //get previous node { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7PreviousNodeCanonicalBlock* previousNodeBlockPtr = dynamic_cast<Bpv7PreviousNodeCanonicalBlock*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(previousNodeBlockPtr); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_blockNumber, 2); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_previousNode.nodeId, PREVIOUS_NODE); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_previousNode.serviceId, PREVIOUS_SVC); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), previousNodeBlockPtr->GetSerializationSize()); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } //get bundle age { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7BundleAgeCanonicalBlock* bundleAgeBlockPtr = dynamic_cast<Bpv7BundleAgeCanonicalBlock*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(bundleAgeBlockPtr); BOOST_REQUIRE_EQUAL(bundleAgeBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE); BOOST_REQUIRE_EQUAL(bundleAgeBlockPtr->m_blockNumber, 3); BOOST_REQUIRE_EQUAL(bundleAgeBlockPtr->m_bundleAgeMilliseconds, BUNDLE_AGE_MS); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), bundleAgeBlockPtr->GetSerializationSize()); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } //get hop count { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7HopCountCanonicalBlock* hopCountBlockPtr = dynamic_cast<Bpv7HopCountCanonicalBlock*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(hopCountBlockPtr); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::HOP_COUNT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_blockNumber, 4); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_hopLimit, HOP_LIMIT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_hopCount, HOP_COUNT); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), hopCountBlockPtr->GetSerializationSize()); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } //get payload { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const char * strPtr = (const char *)blocks[0]->headerPtr->m_dataPtr; std::string s(strPtr, strPtr + blocks[0]->headerPtr->m_dataLength); //std::cout << "s: " << s << "\n"; BOOST_REQUIRE_EQUAL(s, payloadString); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockNumber, 1); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), blocks[0]->headerPtr->GetSerializationSize()); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } //attempt to increase hop count without rerendering whole bundle { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7HopCountCanonicalBlock* hopCountBlockPtr = dynamic_cast<Bpv7HopCountCanonicalBlock*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(hopCountBlockPtr); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::HOP_COUNT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_blockNumber, 4); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_hopLimit, HOP_LIMIT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr->m_hopCount, HOP_COUNT); uint8_t * bundlePtrStart = (uint8_t*)(bv.m_renderedBundle.data()); std::size_t bundleSize = bv.m_renderedBundle.size(); uint8_t * blockPtrStart = (uint8_t*)(blocks[0]->actualSerializedBlockPtr.data()); std::size_t blockSize = blocks[0]->actualSerializedBlockPtr.size(); std::vector<uint8_t> bundleUnmodified(bundlePtrStart, bundlePtrStart + bundleSize); ++hopCountBlockPtr->m_hopCount; BOOST_REQUIRE(hopCountBlockPtr->TryReserializeExtensionBlockDataWithoutResizeBpv7()); blocks[0]->headerPtr->RecomputeCrcAfterDataModification(blockPtrStart, blockSize); std::vector<uint8_t> bundleModifiedButSameSize(bundlePtrStart, bundlePtrStart + bundleSize); BOOST_REQUIRE(bundleSerializedOriginal == bundleUnmodified); BOOST_REQUIRE(bundleSerializedOriginal != bundleModifiedButSameSize); BOOST_REQUIRE_EQUAL(bundleSerializedOriginal.size(), bundleModifiedButSameSize.size()); { BundleViewV7 bv2; BOOST_REQUIRE(bv2.LoadBundle(&bundleModifiedButSameSize[0], bundleModifiedButSameSize.size())); //get hop count { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks2; bv2.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT, blocks2); BOOST_REQUIRE_EQUAL(blocks2.size(), 1); Bpv7HopCountCanonicalBlock* hopCountBlockPtr2 = dynamic_cast<Bpv7HopCountCanonicalBlock*>(blocks2[0]->headerPtr.get()); BOOST_REQUIRE(hopCountBlockPtr2); BOOST_REQUIRE_EQUAL(hopCountBlockPtr2->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::HOP_COUNT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr2->m_blockNumber, 4); BOOST_REQUIRE_EQUAL(hopCountBlockPtr2->m_hopLimit, HOP_LIMIT); BOOST_REQUIRE_EQUAL(hopCountBlockPtr2->m_hopCount, HOP_COUNT + 1); //increased by 1 } } } } } BOOST_AUTO_TEST_CASE(Bpv7PrependExtensionBlockToPaddedBundleTestCase) { static const uint64_t PREVIOUS_NODE = 12345; static const uint64_t PREVIOUS_SVC = 678910; static const uint64_t BUNDLE_AGE_MS = 135791113; static const uint8_t HOP_LIMIT = 250; static const uint8_t HOP_COUNT = 200; const std::string payloadString = { "This is the data inside the bpv7 payload block!!!" }; const std::vector<BPV7_CRC_TYPE> crcTypesVec = { BPV7_CRC_TYPE::NONE, BPV7_CRC_TYPE::CRC16_X25, BPV7_CRC_TYPE::CRC32C }; for (std::size_t crcI = 0; crcI < crcTypesVec.size(); ++crcI) { const BPV7_CRC_TYPE crcTypeToUse = crcTypesVec[crcI]; BundleViewV7 bv; Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT; //All BP endpoints identified by ipn-scheme endpoint IDs are singleton endpoints. primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); primary.m_destinationEid.Set(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); //add only a payload block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; //block.SetZero(); block.m_blockTypeCode = BPV7_BLOCK_TYPE_CODE::PAYLOAD; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 1; //must be 1 block.m_crcType = crcTypeToUse; block.m_dataLength = payloadString.size(); block.m_dataPtr = (uint8_t*)payloadString.data(); //payloadString must remain in scope until after render bv.AppendMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.Render(5000)); std::vector<uint8_t> bundleSerializedOriginal(bv.m_frontBuffer); //std::cout << "renderedsize: " << bv.m_frontBuffer.size() << "\n"; BOOST_REQUIRE_GT(bundleSerializedOriginal.size(), 0); padded_vector_uint8_t bundleSerializedPadded(bundleSerializedOriginal.data(), bundleSerializedOriginal.data() + bundleSerializedOriginal.size()); //the copy can get modified by bundle view on first load BOOST_REQUIRE_EQUAL(bundleSerializedOriginal.size(), bundleSerializedPadded.size()); bv.Reset(); //std::cout << "sz " << bundleSerializedPadded.size() << std::endl; BOOST_REQUIRE(bv.LoadBundle(&bundleSerializedPadded[0], bundleSerializedPadded.size())); BOOST_REQUIRE_EQUAL(primary.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(primary.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC)); BOOST_REQUIRE_EQUAL(primary.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primary.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD), 1); //get payload { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const char * strPtr = (const char *)blocks[0]->headerPtr->m_dataPtr; std::string s(strPtr, strPtr + blocks[0]->headerPtr->m_dataLength); //std::cout << "s: " << s << "\n"; BOOST_REQUIRE_EQUAL(s, payloadString); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockNumber, 1); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } //prepend previous node block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7PreviousNodeCanonicalBlock>(); Bpv7PreviousNodeCanonicalBlock & block = *(reinterpret_cast<Bpv7PreviousNodeCanonicalBlock*>(blockPtr.get())); //block.SetZero(); block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 2; block.m_crcType = crcTypeToUse; block.m_previousNode.Set(PREVIOUS_NODE, PREVIOUS_SVC); bv.PrependMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.RenderInPlace(bundleSerializedPadded.get_allocator().PADDING_ELEMENTS_BEFORE)); //reload new bundle { uint8_t * newStartPtr = (uint8_t *)bv.m_renderedBundle.data(); std::size_t newSize = bv.m_renderedBundle.size(); std::vector<uint8_t> newBundleWithPrependedBlock(newStartPtr, newStartPtr + newSize); BOOST_REQUIRE(bundleSerializedOriginal != newBundleWithPrependedBlock); bv.Reset(); BOOST_REQUIRE(bv.LoadBundle(newStartPtr, newSize)); } //get previous node, mark for deletion { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7PreviousNodeCanonicalBlock* previousNodeBlockPtr = dynamic_cast<Bpv7PreviousNodeCanonicalBlock*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(previousNodeBlockPtr); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_blockNumber, 2); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_previousNode.nodeId, PREVIOUS_NODE); BOOST_REQUIRE_EQUAL(previousNodeBlockPtr->m_previousNode.serviceId, PREVIOUS_SVC); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), previousNodeBlockPtr->GetSerializationSize()); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted blocks[0]->markedForDeletion = true; } //get payload { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); const char * strPtr = (const char *)blocks[0]->headerPtr->m_dataPtr; std::string s(strPtr, strPtr + blocks[0]->headerPtr->m_dataLength); //std::cout << "s: " << s << "\n"; BOOST_REQUIRE_EQUAL(s, payloadString); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(blocks[0]->headerPtr->m_blockNumber, 1); BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted } BOOST_REQUIRE(bv.RenderInPlace(0)); //0 => expecting not to go into left padded space due to removal { uint8_t * newStartPtr = (uint8_t *)bv.m_renderedBundle.data(); std::size_t newSize = bv.m_renderedBundle.size(); std::vector<uint8_t> newOriginalBundle(newStartPtr, newStartPtr + newSize); BOOST_REQUIRE(bundleSerializedOriginal == newOriginalBundle); } } } BOOST_AUTO_TEST_CASE(Bpv7BundleStatusReportTestCase) { const std::vector<BPV7_CRC_TYPE> crcTypesVec = { BPV7_CRC_TYPE::NONE, BPV7_CRC_TYPE::CRC16_X25, BPV7_CRC_TYPE::CRC32C }; for (std::size_t crcI = 0; crcI < crcTypesVec.size(); ++crcI) { const BPV7_CRC_TYPE crcTypeToUse = crcTypesVec[crcI]; for (unsigned int useFragI = 0; useFragI < 2; ++useFragI) { const bool useFrag = (useFragI != 0); for (unsigned int timeFlagSetI = 0; timeFlagSetI < 2; ++timeFlagSetI) { const bool useReportStatusTime = (timeFlagSetI != 0); for (unsigned int assertionsMask = 1; assertionsMask < 16; ++assertionsMask) { //start at 1 because you must assert at least one of the four items const bool assert0 = ((assertionsMask & 1) != 0); const bool assert1 = ((assertionsMask & 2) != 0); const bool assert2 = ((assertionsMask & 4) != 0); const bool assert3 = ((assertionsMask & 8) != 0); //std::cout << assert3 << assert2 << assert1 << assert0 << "\n"; BundleViewV7 bv; Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT | BPV7_BUNDLEFLAG::ADMINRECORD; primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); primary.m_destinationEid.Set(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); uint64_t bsrSerializationSize = 0; //add bundle status report payload block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7AdministrativeRecord>(); Bpv7AdministrativeRecord & block = *(reinterpret_cast<Bpv7AdministrativeRecord*>(blockPtr.get())); //block.m_blockTypeCode = BPV7_BLOCK_TYPE_CODE::PAYLOAD; //not needed because handled by Bpv7AdministrativeRecord constructor block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against //block.m_blockNumber = 1; //must be 1 //not needed because handled by Bpv7AdministrativeRecord constructor block.m_crcType = crcTypeToUse; block.m_adminRecordTypeCode = BPV7_ADMINISTRATIVE_RECORD_TYPE_CODE::BUNDLE_STATUS_REPORT; block.m_adminRecordContentPtr = boost::make_unique<Bpv7AdministrativeRecordContentBundleStatusReport>(); Bpv7AdministrativeRecordContentBundleStatusReport & bsr = *(reinterpret_cast<Bpv7AdministrativeRecordContentBundleStatusReport*>(block.m_adminRecordContentPtr.get())); bsr.m_reportStatusTimeFlagWasSet = useReportStatusTime; //reporting-node-received-bundle bsr.m_bundleStatusInfo[0].first = assert0; bsr.m_bundleStatusInfo[0].second = (bsr.m_reportStatusTimeFlagWasSet) ? 10000 : 0; //time asserted, 0 if don't care //reporting-node-forwarded-bundle bsr.m_bundleStatusInfo[1].first = assert1; bsr.m_bundleStatusInfo[1].second = (bsr.m_reportStatusTimeFlagWasSet) ? 10001 : 0; //time asserted, all don't cares //reporting-node-delivered-bundle bsr.m_bundleStatusInfo[2].first = assert2; bsr.m_bundleStatusInfo[2].second = (bsr.m_reportStatusTimeFlagWasSet) ? 10002 : 0; //time asserted, 0 if don't care //reporting-node-deleted-bundle bsr.m_bundleStatusInfo[3].first = assert3; bsr.m_bundleStatusInfo[3].second = (bsr.m_reportStatusTimeFlagWasSet) ? 10003 : 0; //time asserted, all don't cares bsr.m_statusReportReasonCode = BPV7_STATUS_REPORT_REASON_CODE::DEPLETED_STORAGE; bsr.m_sourceNodeEid.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); bsr.m_creationTimestamp.millisecondsSinceStartOfYear2000 = 5000; bsr.m_creationTimestamp.sequenceNumber = 10; bsr.m_subjectBundleIsFragment = useFrag; bsr.m_optionalSubjectPayloadFragmentOffset = 200; bsr.m_optionalSubjectPayloadFragmentLength = 100; bsrSerializationSize = bsr.GetSerializationSize(); bv.AppendMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.Render(5000)); std::vector<uint8_t> bundleSerializedOriginal(bv.m_frontBuffer); //std::cout << "renderedsize: " << bv.m_frontBuffer.size() << "\n"; BOOST_REQUIRE_GT(bundleSerializedOriginal.size(), 0); std::vector<uint8_t> bundleSerializedCopy(bundleSerializedOriginal); //the copy can get modified by bundle view on first load BOOST_REQUIRE(bundleSerializedOriginal == bundleSerializedCopy); bv.Reset(); //std::cout << "sz " << bundleSerializedCopy.size() << std::endl; BOOST_REQUIRE(bv.LoadBundle(&bundleSerializedCopy[0], bundleSerializedCopy.size())); BOOST_REQUIRE(bv.m_backBuffer != bundleSerializedCopy); BOOST_REQUIRE(bv.m_frontBuffer != bundleSerializedCopy); BOOST_REQUIRE_EQUAL(primary.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(primary.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC)); BOOST_REQUIRE_EQUAL(primary.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primary.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bv.m_primaryBlockView.actualSerializedPrimaryBlockPtr.size(), primary.GetSerializationSize()); BOOST_REQUIRE_EQUAL(primary.m_bundleProcessingControlFlags, BPV7_BUNDLEFLAG::NOFRAGMENT | BPV7_BUNDLEFLAG::ADMINRECORD); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD), 1); //get bundle status report payload block { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7AdministrativeRecord* adminRecordBlockPtr = dynamic_cast<Bpv7AdministrativeRecord*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(adminRecordBlockPtr); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_blockNumber, 1); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_adminRecordTypeCode, BPV7_ADMINISTRATIVE_RECORD_TYPE_CODE::BUNDLE_STATUS_REPORT); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), adminRecordBlockPtr->GetSerializationSize()); //std::cout << "adminRecordBlockPtr->GetSerializationSize() " << adminRecordBlockPtr->GetSerializationSize() << "\n"; BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted Bpv7AdministrativeRecordContentBundleStatusReport * bsrPtr = dynamic_cast<Bpv7AdministrativeRecordContentBundleStatusReport*>(adminRecordBlockPtr->m_adminRecordContentPtr.get()); BOOST_REQUIRE(bsrPtr); Bpv7AdministrativeRecordContentBundleStatusReport & bsr = *(reinterpret_cast<Bpv7AdministrativeRecordContentBundleStatusReport*>(bsrPtr)); BOOST_REQUIRE_EQUAL(bsr.GetSerializationSize(), bsrSerializationSize); BOOST_REQUIRE_EQUAL(bsr.m_reportStatusTimeFlagWasSet, useReportStatusTime); //reporting-node-received-bundle BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[0].first, assert0); if (bsr.m_bundleStatusInfo[0].first && bsr.m_reportStatusTimeFlagWasSet) { BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[0].second, 10000); } //reporting-node-forwarded-bundle BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[1].first, assert1); if (bsr.m_bundleStatusInfo[1].first && bsr.m_reportStatusTimeFlagWasSet) { BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[1].second, 10001); } //reporting-node-delivered-bundle BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[2].first, assert2); if (bsr.m_bundleStatusInfo[2].first && bsr.m_reportStatusTimeFlagWasSet) { BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[2].second, 10002); } //reporting-node-deleted-bundle BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[3].first, assert3); if (bsr.m_bundleStatusInfo[3].first && bsr.m_reportStatusTimeFlagWasSet) { BOOST_REQUIRE_EQUAL(bsr.m_bundleStatusInfo[3].second, 10003); } BOOST_REQUIRE_EQUAL(bsr.m_statusReportReasonCode, BPV7_STATUS_REPORT_REASON_CODE::DEPLETED_STORAGE); BOOST_REQUIRE_EQUAL(bsr.m_sourceNodeEid, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(bsr.m_creationTimestamp.millisecondsSinceStartOfYear2000, 5000); BOOST_REQUIRE_EQUAL(bsr.m_creationTimestamp.sequenceNumber, 10); BOOST_REQUIRE_EQUAL(bsr.m_subjectBundleIsFragment, useFrag); if (bsr.m_subjectBundleIsFragment) { BOOST_REQUIRE_EQUAL(bsr.m_optionalSubjectPayloadFragmentOffset, 200); BOOST_REQUIRE_EQUAL(bsr.m_optionalSubjectPayloadFragmentLength, 100); } } } } } } } BOOST_AUTO_TEST_CASE(Bpv7BibeTestCase) { const std::string payloadString = { "This is the data inside the encapsulated bpv7 bundle!!!" }; const std::vector<BPV7_CRC_TYPE> crcTypesVec = { BPV7_CRC_TYPE::NONE, BPV7_CRC_TYPE::CRC16_X25, BPV7_CRC_TYPE::CRC32C }; for (std::size_t crcI = 0; crcI < crcTypesVec.size(); ++crcI) { const BPV7_CRC_TYPE crcTypeToUse = crcTypesVec[crcI]; //create the encapsulated (inner) bundle std::vector<uint8_t> encapsulatedBundleVersion7; { BundleViewV7 bv; Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT; //All BP endpoints identified by ipn-scheme endpoint IDs are singleton endpoints. primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE + 10, PRIMARY_SRC_SVC + 10); primary.m_destinationEid.Set(PRIMARY_DEST_NODE + 10, PRIMARY_DEST_SVC + 10); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); //add only a payload block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7CanonicalBlock>(); Bpv7CanonicalBlock & block = *blockPtr; //block.SetZero(); block.m_blockTypeCode = BPV7_BLOCK_TYPE_CODE::PAYLOAD; block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against block.m_blockNumber = 1; //must be 1 block.m_crcType = crcTypeToUse; block.m_dataLength = payloadString.size(); block.m_dataPtr = (uint8_t*)payloadString.data(); //payloadString must remain in scope until after render bv.AppendMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.Render(5000)); encapsulatedBundleVersion7.assign(bv.m_frontBuffer.begin(), bv.m_frontBuffer.end()); } //create the encapsulating (outer) bundle (admin record) std::vector<uint8_t> encapsulatingBundleVersion7; uint64_t bibePduMessageSerializationSize = 0; { BundleViewV7 bv; Bpv7CbhePrimaryBlock & primary = bv.m_primaryBlockView.header; primary.SetZero(); primary.m_bundleProcessingControlFlags = BPV7_BUNDLEFLAG::NOFRAGMENT | BPV7_BUNDLEFLAG::ADMINRECORD; primary.m_sourceNodeId.Set(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC); primary.m_destinationEid.Set(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC); primary.m_reportToEid.Set(0, 0); primary.m_creationTimestamp.millisecondsSinceStartOfYear2000 = PRIMARY_TIME; primary.m_lifetimeMilliseconds = PRIMARY_LIFETIME; primary.m_creationTimestamp.sequenceNumber = PRIMARY_SEQ; primary.m_crcType = crcTypeToUse; bv.m_primaryBlockView.SetManuallyModified(); //add bundle status report payload block { std::unique_ptr<Bpv7CanonicalBlock> blockPtr = boost::make_unique<Bpv7AdministrativeRecord>(); Bpv7AdministrativeRecord & block = *(reinterpret_cast<Bpv7AdministrativeRecord*>(blockPtr.get())); //block.m_blockTypeCode = BPV7_BLOCK_TYPE_CODE::PAYLOAD; //not needed because handled by Bpv7AdministrativeRecord constructor block.m_blockProcessingControlFlags = BPV7_BLOCKFLAG::REMOVE_BLOCK_IF_IT_CANT_BE_PROCESSED; //something for checking against //block.m_blockNumber = 1; //must be 1 //not needed because handled by Bpv7AdministrativeRecord constructor block.m_crcType = crcTypeToUse; block.m_adminRecordTypeCode = BPV7_ADMINISTRATIVE_RECORD_TYPE_CODE::BIBE_PDU; block.m_adminRecordContentPtr = boost::make_unique<Bpv7AdministrativeRecordContentBibePduMessage>(); Bpv7AdministrativeRecordContentBibePduMessage & bibe = *(reinterpret_cast<Bpv7AdministrativeRecordContentBibePduMessage*>(block.m_adminRecordContentPtr.get())); bibe.m_transmissionId = 49; bibe.m_custodyRetransmissionTime = 0; bibe.m_encapsulatedBundlePtr = encapsulatedBundleVersion7.data(); bibe.m_encapsulatedBundleLength = encapsulatedBundleVersion7.size(); bibePduMessageSerializationSize = bibe.GetSerializationSize(); bv.AppendMoveCanonicalBlock(blockPtr); } BOOST_REQUIRE(bv.Render(5000)); encapsulatingBundleVersion7.assign(bv.m_frontBuffer.begin(), bv.m_frontBuffer.end()); } //load the encapsulating (outer) bundle (admin record) std::vector<uint8_t> encapsulatingBundleVersion7ForLoad(encapsulatingBundleVersion7); { BundleViewV7 bv; BOOST_REQUIRE(bv.SwapInAndLoadBundle(encapsulatingBundleVersion7ForLoad)); const Bpv7CbhePrimaryBlock & primaryOuter = bv.m_primaryBlockView.header; BOOST_REQUIRE_EQUAL(primaryOuter.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE, PRIMARY_SRC_SVC)); BOOST_REQUIRE_EQUAL(primaryOuter.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE, PRIMARY_DEST_SVC)); BOOST_REQUIRE_EQUAL(primaryOuter.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primaryOuter.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bv.m_primaryBlockView.actualSerializedPrimaryBlockPtr.size(), primaryOuter.GetSerializationSize()); BOOST_REQUIRE_EQUAL(primaryOuter.m_bundleProcessingControlFlags, BPV7_BUNDLEFLAG::NOFRAGMENT | BPV7_BUNDLEFLAG::ADMINRECORD); BOOST_REQUIRE_EQUAL(primaryOuter.m_crcType, crcTypeToUse); BOOST_REQUIRE_EQUAL(bv.GetNumCanonicalBlocks(), 1); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 0); BOOST_REQUIRE_EQUAL(bv.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD), 1); //get BIBE payload block (inner bundle) { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocks; bv.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocks); BOOST_REQUIRE_EQUAL(blocks.size(), 1); Bpv7AdministrativeRecord* adminRecordBlockPtr = dynamic_cast<Bpv7AdministrativeRecord*>(blocks[0]->headerPtr.get()); BOOST_REQUIRE(adminRecordBlockPtr); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_blockNumber, 1); BOOST_REQUIRE_EQUAL(adminRecordBlockPtr->m_adminRecordTypeCode, BPV7_ADMINISTRATIVE_RECORD_TYPE_CODE::BIBE_PDU); BOOST_REQUIRE_EQUAL(blocks[0]->actualSerializedBlockPtr.size(), adminRecordBlockPtr->GetSerializationSize()); //std::cout << "adminRecordBlockPtr->GetSerializationSize() " << adminRecordBlockPtr->GetSerializationSize() << "\n"; BOOST_REQUIRE(!blocks[0]->isEncrypted); //not encrypted Bpv7AdministrativeRecordContentBibePduMessage * bibePduMessagePtr = dynamic_cast<Bpv7AdministrativeRecordContentBibePduMessage*>(adminRecordBlockPtr->m_adminRecordContentPtr.get()); BOOST_REQUIRE(bibePduMessagePtr); Bpv7AdministrativeRecordContentBibePduMessage & bibe = *(reinterpret_cast<Bpv7AdministrativeRecordContentBibePduMessage*>(bibePduMessagePtr)); BOOST_REQUIRE_EQUAL(bibe.GetSerializationSize(), bibePduMessageSerializationSize); BOOST_REQUIRE_EQUAL(bibe.m_transmissionId, 49); BOOST_REQUIRE_EQUAL(bibe.m_custodyRetransmissionTime, 0); BOOST_REQUIRE_EQUAL(bibe.m_encapsulatedBundleLength, encapsulatedBundleVersion7.size()); BOOST_REQUIRE_EQUAL(memcmp(bibe.m_encapsulatedBundlePtr, encapsulatedBundleVersion7.data(), bibe.m_encapsulatedBundleLength), 0); BundleViewV7 bvInner; BOOST_REQUIRE(bvInner.LoadBundle(bibe.m_encapsulatedBundlePtr, bibe.m_encapsulatedBundleLength)); const Bpv7CbhePrimaryBlock & primaryInner = bvInner.m_primaryBlockView.header; BOOST_REQUIRE_EQUAL(primaryInner.m_sourceNodeId, cbhe_eid_t(PRIMARY_SRC_NODE + 10, PRIMARY_SRC_SVC + 10)); BOOST_REQUIRE_EQUAL(primaryInner.m_destinationEid, cbhe_eid_t(PRIMARY_DEST_NODE + 10, PRIMARY_DEST_SVC + 10)); BOOST_REQUIRE_EQUAL(primaryInner.m_creationTimestamp, TimestampUtil::bpv7_creation_timestamp_t(PRIMARY_TIME, PRIMARY_SEQ)); BOOST_REQUIRE_EQUAL(primaryInner.m_lifetimeMilliseconds, PRIMARY_LIFETIME); BOOST_REQUIRE_EQUAL(bvInner.m_primaryBlockView.actualSerializedPrimaryBlockPtr.size(), primaryInner.GetSerializationSize()); BOOST_REQUIRE_EQUAL(primaryInner.m_bundleProcessingControlFlags, BPV7_BUNDLEFLAG::NOFRAGMENT); BOOST_REQUIRE_EQUAL(primaryInner.m_crcType, crcTypeToUse); BOOST_REQUIRE_EQUAL(bvInner.GetNumCanonicalBlocks(), 1); BOOST_REQUIRE_EQUAL(bvInner.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PREVIOUS_NODE), 0); BOOST_REQUIRE_EQUAL(bvInner.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::BUNDLE_AGE), 0); BOOST_REQUIRE_EQUAL(bvInner.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::HOP_COUNT), 0); BOOST_REQUIRE_EQUAL(bvInner.GetCanonicalBlockCountByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD), 1); //get inner bundle payload block { std::vector<BundleViewV7::Bpv7CanonicalBlockView*> blocksInner; bvInner.GetCanonicalBlocksByType(BPV7_BLOCK_TYPE_CODE::PAYLOAD, blocksInner); BOOST_REQUIRE_EQUAL(blocksInner.size(), 1); const char * strPtr = (const char *)blocksInner[0]->headerPtr->m_dataPtr; std::string s(strPtr, strPtr + blocksInner[0]->headerPtr->m_dataLength); //std::cout << "s: " << s << "\n"; BOOST_REQUIRE_EQUAL(s, payloadString); BOOST_REQUIRE_EQUAL(blocksInner[0]->headerPtr->m_blockTypeCode, BPV7_BLOCK_TYPE_CODE::PAYLOAD); BOOST_REQUIRE_EQUAL(blocksInner[0]->headerPtr->m_blockNumber, 1); BOOST_REQUIRE(!blocksInner[0]->isEncrypted); //not encrypted } } } } }
58.883459
210
0.684639
[ "render", "vector" ]
eae598cf717c05dc61abda4f5ee77e4e3d5f024b
1,096
hpp
C++
include/midipatcher/Port/VirtMidiIn.hpp
tschiemer/midipatcher
a0922df002fe8b99ed551f7092c94fecff600728
[ "MIT" ]
2
2020-09-29T06:51:48.000Z
2021-10-06T17:58:00.000Z
include/midipatcher/Port/VirtMidiIn.hpp
tschiemer/midipatcher
a0922df002fe8b99ed551f7092c94fecff600728
[ "MIT" ]
null
null
null
include/midipatcher/Port/VirtMidiIn.hpp
tschiemer/midipatcher
a0922df002fe8b99ed551f7092c94fecff600728
[ "MIT" ]
null
null
null
#ifndef MIDIPATCHER_PORT_VIRT_MIDI_IN_H #define MIDIPATCHER_PORT_VIRT_MIDI_IN_H #include "AbstractInputPort.hpp" #include <RtMidi.h> namespace MidiPatcher { namespace Port { class VirtMidiIn : AbstractInputPort { public: static const constexpr char * PortClass = "VirtMidiIn"; std::string getPortClass(){ return PortClass; } PortDescriptor * getPortDescriptor(){ return new PortDescriptor(PortClass, Name); } static PortClassRegistryInfo * getPortClassRegistryInfo() { return new PortClassRegistryInfo(PortClass, factory, nullptr); } static AbstractPort* factory(PortDescriptor &portDescriptor){ assert( portDescriptor.PortClass == PortClass ); return new VirtMidiIn(portDescriptor.Name); } VirtMidiIn(std::string portName); ~VirtMidiIn(); protected: RtMidiIn * MidiPort = NULL; static void rtMidiCallback( double timeStamp, std::vector<unsigned char> *message, void *midiInRef ); }; } } #endif /* MIDIPATCHER_PORT_VIRT_MIDI_IN_H */
21.490196
109
0.680657
[ "vector" ]
eae69fd70be8777a9baeb277ec872f14ffa94023
80,831
cpp
C++
pd/pe_header.cpp
elsisoft/Process-Dump
b5eb1fcfb14566cd279a0fb17ea79152d8a197db
[ "MIT" ]
1,196
2015-11-21T22:59:47.000Z
2022-03-22T09:16:46.000Z
pd/pe_header.cpp
hdbeefup/Process-Dump
b5eb1fcfb14566cd279a0fb17ea79152d8a197db
[ "MIT" ]
19
2016-09-19T15:51:14.000Z
2021-08-31T18:54:47.000Z
pd/pe_header.cpp
hdbeefup/Process-Dump
b5eb1fcfb14566cd279a0fb17ea79152d8a197db
[ "MIT" ]
235
2015-11-23T09:21:12.000Z
2022-03-25T20:28:50.000Z
#include "StdAfx.h" #include "pe_header.h" pe_header::pe_header( char* filename, PD_OPTIONS* options ) { this->_options = options; this->_image_size = 0; this->_raw_header_size = 0; this->_disk_image_size = 0; this->_stream = (stream_wrapper*) new file_stream( filename ); _original_base = 0; _unique_hash = 0; _unique_hash_ep = 0; _unique_hash_ep_short = 0; _name_filepath_long_size = 0; _name_filepath_long = NULL; _name_filepath_short_size = 0; _name_filepath_short = NULL; _name_original_exports_size = 0; _name_original_exports = NULL; _name_original_manifest_size = 0; _name_original_manifest = NULL; _name_symbols_path_size = 0; _name_symbols_path = NULL; _export_list = NULL; this->_parsed_dos = false; this->_parsed_pe_32 = false; this->_parsed_pe_64 = false; this->_parsed_sections = false; this->_image_size = 0; this->_disk_image_size = 0; this->_unique_hash = 0; if( _stream != NULL ) { // Assign the disk filename for this file _name_filepath_long = new char[FILEPATH_SIZE]; _name_filepath_long_size = _stream->get_long_name( _name_filepath_long, FILEPATH_SIZE ); _name_filepath_short = new char[FILEPATH_SIZE]; _name_filepath_short_size = _stream->get_short_name( _name_filepath_short, FILEPATH_SIZE ); } if( _options->Verbose ) fprintf( stdout, "INFO: Initialized header for module name %s.\n", this->get_name() ); } export_list* pe_header::get_exports() { if( (_parsed_pe_32 || _parsed_pe_64) && _export_list != NULL ) { return this->_export_list; } return NULL; } pe_header::pe_header( DWORD pid, void* base, module_list* modules, PD_OPTIONS* options ) { this->_options = options; this->_image_size = 0; this->_raw_header_size = 0; this->_disk_image_size = 0; _unique_hash = 0; _unique_hash_ep = 0; _unique_hash_ep_short = 0; _header_export_directory = NULL; _header_import_descriptors = NULL; _name_filepath_long_size = 0; _name_filepath_long = NULL; _name_filepath_short_size = 0; _name_filepath_short = NULL; _name_original_exports_size = 0; _name_original_exports = NULL; _name_original_manifest_size = 0; _name_original_manifest = NULL; _name_symbols_path_size = 0; _name_symbols_path = NULL; _export_list = NULL; this->_parsed_dos = false; this->_parsed_pe_32 = false; this->_parsed_pe_64 = false; this->_parsed_sections = false; this->_image_size = 0; this->_disk_image_size = 0; this->_unique_hash = 0; this->_stream = (stream_wrapper*) new process_stream( pid, base, modules ); _original_base = base; if( _stream != NULL ) { // Assign the disk filename for this file _name_filepath_long = new char[FILEPATH_SIZE]; _name_filepath_long_size = _stream->get_long_name( _name_filepath_long, FILEPATH_SIZE ); _name_filepath_short = new char[FILEPATH_SIZE]; _name_filepath_short_size = _stream->get_short_name( _name_filepath_short, FILEPATH_SIZE ); } if( _options->Verbose ) fprintf( stdout, "INFO: Initialized header for module name %s.\n", this->get_name() ); } pe_header::pe_header( DWORD pid, module_list* modules, PD_OPTIONS* options ) { this->_options = options; this->_image_size = 0; this->_raw_header_size = 0; this->_disk_image_size = 0; _unique_hash = 0; _unique_hash_ep = 0; _unique_hash_ep_short = 0; _header_export_directory = NULL; _header_import_descriptors = NULL; _name_filepath_long_size = 0; _name_filepath_long = NULL; _name_filepath_short_size = 0; _name_filepath_short = NULL; _name_original_exports_size = 0; _name_original_exports = NULL; _name_original_manifest_size = 0; _name_original_manifest = NULL; _name_symbols_path_size = 0; _name_symbols_path = NULL; _export_list = NULL; this->_parsed_dos = false; this->_parsed_pe_32 = false; this->_parsed_pe_64 = false; this->_parsed_sections = false; this->_image_size = 0; this->_disk_image_size = 0; this->_unique_hash = 0; this->_stream = (stream_wrapper*) new process_stream( pid, modules ); _original_base = ((process_stream*) _stream)->base; if( _options->Verbose ) fprintf( stdout, "INFO: Initialized header for module name %s.\n", this->get_name() ); } pe_header::pe_header( HANDLE ph, void* base, module_list* modules, PD_OPTIONS* options ) { this->_options = options; this->_image_size = 0; this->_raw_header_size = 0; this->_disk_image_size = 0; _unique_hash = 0; _unique_hash_ep = 0; _unique_hash_ep_short = 0; _name_filepath_long_size = 0; _name_filepath_long = NULL; _name_filepath_short_size = 0; _name_filepath_short = NULL; _name_original_exports_size = 0; _name_original_exports = NULL; _name_original_manifest_size = 0; _name_original_manifest = NULL; _name_symbols_path_size = 0; _name_symbols_path = NULL; _export_list = NULL; this->_parsed_dos = false; this->_parsed_pe_32 = false; this->_parsed_pe_64 = false; this->_parsed_sections = false; this->_image_size = 0; this->_disk_image_size = 0; this->_unique_hash = 0; this->_stream = (stream_wrapper*) new process_stream( ph, base ); _original_base = base; if( _options->Verbose ) fprintf( stdout, "INFO: Initialized header for module name %s.\n", this->get_name() ); } void pe_header::print_report(FILE* stream) { // Print the on-disk filepath if there is an associated file // Print the original filename specified by the exports table if it has one // Print the original filename specified by the manifest file if it has one // Print the symbols .pdb file path and name if found // Print the basic information } bool pe_header::somewhat_parsed() { return _parsed_pe_32 || _parsed_pe_64; } bool pe_header::is_dll() { if( this->_parsed_pe_32 ) return (this->_header_pe32->FileHeader.Characteristics & IMAGE_FILE_DLL); if( this->_parsed_pe_64 ) return (this->_header_pe64->FileHeader.Characteristics & IMAGE_FILE_DLL); return false; } bool pe_header::is_exe() { if( this->_parsed_pe_32 ) return !(this->_header_pe32->FileHeader.Characteristics & IMAGE_FILE_DLL) && !(this->_header_pe32->FileHeader.Characteristics & IMAGE_FILE_SYSTEM); if( this->_parsed_pe_64 ) return !(this->_header_pe64->FileHeader.Characteristics & IMAGE_FILE_DLL) && !(this->_header_pe64->FileHeader.Characteristics & IMAGE_FILE_SYSTEM); return false; } bool pe_header::is_sys() { if( this->_parsed_pe_32 ) return this->_header_pe32->FileHeader.Characteristics & IMAGE_FILE_SYSTEM; if( this->_parsed_pe_64 ) return this->_header_pe64->FileHeader.Characteristics & IMAGE_FILE_SYSTEM; return false; } bool pe_header::is_64() { return this->_parsed_pe_64; } void pe_header::set_name(char* new_name) { // Set name to sue for this module if( _name_filepath_short != NULL ) delete _name_filepath_short; // Localize _name_filepath_short = new char[strlen(new_name) + 1]; strcpy_s(_name_filepath_short, strlen(new_name) + 1, new_name); _name_filepath_short_size = strlen(_name_filepath_short); } char* pe_header::get_name() { // Return the name of this module if available. if( this->_name_filepath_short_size > 0 && _name_filepath_short != NULL ) return _name_filepath_short; return "hiddenmodule"; } unsigned __int64 pe_header::get_virtual_size() { if( this->_parsed_pe_32 || this->_parsed_pe_64 ) { return _image_size; } return 0; } bool pe_header::process_hash( ) { // Build the hash of this library if has been loaded this->_unique_hash = 0; if( this->_parsed_pe_32 || this->_parsed_pe_64 ) { // Hash the PE directory up until the end of the section definition, and hashes // this with the length of the import table, and number of modules in the import // table // First calculate begin hashing from the import table entries SIZE_T offset = 0; SIZE_T read_size = 0; if( _parsed_pe_32 ) { offset = _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress; read_size = 4; } else { offset = _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress; read_size = 8; } unsigned __int64 last_dw = -1; // Hash the IAT overview (not the exact values, just the structure). bool more; do { more = false; if( _test_read( _image, _image_size, _image + offset, read_size ) ) { unsigned __int64 new_dw; if( read_size == 4 ) new_dw = *((DWORD*) (_image + (long) offset)); if( read_size == 8 ) new_dw = *((unsigned __int64*) (_image + (long) offset)); if( new_dw == 0 && last_dw == 0 ) break; if( new_dw == 0 ) { // New module hash _unique_hash = _unique_hash ^ 0x8ADFA91F8ADFA91F; _unique_hash = _rotl64(_unique_hash, 0x13); } else { // New import in module hash _unique_hash = _unique_hash ^ 0x18F31A228FA9B17A; _unique_hash = _rotl64(_unique_hash, 0x17); } offset += read_size; last_dw = new_dw; more = true; } }while(more); /* // Hash this with the DOS header unsigned char* start = 0; SIZE_T length = 0; start = (unsigned char*) &_header_dos; length = sizeof(IMAGE_DOS_HEADER); for( unsigned char* i = start; i + 8 < start + length; i+= 4 ) { // Hash with this segment _unique_hash = _unique_hash ^ *((unsigned __int32*)(i)); _unique_hash = _rotl64(_unique_hash, 0x19); } */ // Hash this with some of the section information if( this->_parsed_sections ) { for( int i = 0; i < this->_num_sections; i++ ) { // Hash with this section description _unique_hash = _unique_hash ^ *((unsigned __int64*)(&_header_sections[i].Name)); _unique_hash = _rotl64(_unique_hash, 0x21); _unique_hash = _unique_hash ^ _header_sections[i].SizeOfRawData; _unique_hash = _rotl64(_unique_hash, 0x13); _unique_hash = _unique_hash ^ _header_sections[i].Characteristics; _unique_hash = _rotl64(_unique_hash, 0x17); } } return true; } return false; } unsigned __int64 pe_header::_hash_short_asm(SIZE_T offset) { unsigned __int64 result = 0; if (offset == 0 || !_options->EntryPointHash) { // Invalid entry point for hashing or code hashing is disabled return result; } // Load the 8 bytes at the offset as the short hash if (_test_read(_image, _image_size, _image + offset, 8)) { result = *((unsigned __int64*)(_image + offset)); // Require at least 2 different byte values to be valid if ( ((result ^ (result << 8)) & 0xffffffffffffff00) == 0) { // All the same bytes, so it isn't valid return 0; } } return result; } unsigned __int64 pe_header::_hash_asm(SIZE_T offset) { // Calculate the entry-point hash given the specified entry point unsigned __int64 result = 0; if (offset == 0 || !_options->EntryPointHash) { // Invalid entry point for hashing or code hashing is disabled return result; } if (this->_parsed_pe_32 || this->_parsed_pe_64) { // Partial hash of the code at the entry point. A database of these hashes for known modules can be // used to attempt to recover the original entry-point of dumped modules with tampered entry points. // First load the disassembly mode NMD_X86_MODE mode; if (_parsed_pe_32) { mode = NMD_X86_MODE_32; } else { mode = NMD_X86_MODE_64; } // Hashing logic: // Hash opcodes + prefix // Hash the first 100 instructions or until a ret is hit. If a ret is hit before 30 instructions are processed, // it will continue blindly processing until 30 instructions are processed. bool more; bool return_hit = false; NMD_X86Instruction inst; int inst_count = 0; do { more = false; if (_test_read(_image, _image_size, _image + offset, 20)) { // Disassemble more = true; if (nmd_x86_decode_buffer(_image + offset, 20, &inst, mode, NMD_X86_DECODER_FLAGS_MINIMAL)) { // Hash in this opcode result = (result + inst.opcode + (inst.opcode << 8) + (inst.opcode << 16) + (inst.opcode << 24)) ^ 0x8ADFA91F8ADFA91F; result = _rotl64(result, 0x13); // Hash in the opcode prefix result = (result + inst.prefixes + (inst.prefixes << 16)) ^ 0x18F31A228FA9B17A; result = _rotl64(result, 0x17); // Check if it was a function return if (inst.group == NMD_GROUP_RET) { return_hit = true; } offset += inst.length; } else { // Failed to disassemble. Hash this information and skip to the next byte. result = result ^ 0xCDA13B89DB31AF13; result = _rotl64(result, 0x18); offset++; } inst_count++; } if (more) { if (return_hit && inst_count >= EP_HASH_OPCODES_MIN) { // End if we've hit a return instruction and we've finished hashing at least 30 instructions more = false; } if (inst_count >= EP_HASH_OPCODES_MAX) { // We hash at most 100 instructions more = false; } } } while (more); if (inst_count >= EP_HASH_OPCODES_MIN) { return result; } } return 0; // Not a valid hash } bool pe_header::process_hash_ep() { // Build the hash the entry point code this->_unique_hash_ep = 0; this->_unique_hash_ep_short = 0; // Calculate the entry-point hash given the specified entry point unsigned __int64 result = 0; if (this->_parsed_pe_32 || this->_parsed_pe_64) { // Partial hash of the code at the entry point. A database of these hashes for known modules can be // used to attempt to recover the original entry-point of dumped modules with tampered entry points. // First load the entry point SIZE_T offset = 0; NMD_X86_MODE mode; if (_parsed_pe_32) { offset = _header_pe32->OptionalHeader.AddressOfEntryPoint; // rva } else { offset = _header_pe64->OptionalHeader.AddressOfEntryPoint; } // Load the 8 bytes at the entrypoint as the short hash unsigned __int64 hash = _hash_short_asm(offset); if (hash != 0) { _unique_hash_ep_short = hash; // Load the hash of the code at the entry point hash = _hash_asm(offset); if (hash != 0) { this->_unique_hash_ep = hash; return true; } } } // Failed to parse an entry point hash return false; } bool pe_header::write_image( char* filename ) { // Writes the loaded and reconstructed memory image to a file if( _disk_image_size > 0 ) { FILE* fh = fopen( filename, "wb" ); if( fh != NULL ) { // Write the image fwrite( _disk_image, 1, _disk_image_size, fh ); fclose(fh); } } return false; } IMPORT_SUMMARY pe_header::get_imports_information( export_list* exports ) { return get_imports_information( exports, _image_size ); } IMPORT_SUMMARY pe_header::get_imports_information( export_list* exports, __int64 size_limit ) { // Builds a structure of information about the imports declared by this PE object. This includes: // # of different import addresses // # of code locations that imported // Generic import hash // Specific import hash // Gets the number of distinct import addresses that are imported. unordered_set<unsigned __int64> import_addresses; if( _options->Verbose ) printf( "INFO: Building import information.\n" ); IMPORT_SUMMARY result; result.COUNT_UNIQUE_IMPORT_ADDRESSES = 0; result.COUNT_UNIQUE_IMPORT_LIBRARIES = 0; result.HASH_GENERIC = 0; result.HASH_SPECIFIC = 0; size_t hash_generic = 0x1a78ac10; size_t hash_specific = 0x1a78ac10; hash<string> hasher; if( this->_parsed_sections ) { // Add matches to exports in this process unsigned __int32 cand32_last = 0; unsigned __int64 cand64_last = 0; for(__int64 offset = 0; offset < _image_size - 8 && offset < size_limit - 8; offset+=4 ) { // Check if this 4-gram or 8-gram points to an export unsigned __int32 cand32 = *((__int32*)(_image + offset)); if (cand32 != cand32_last) { if (exports->contains(cand32)) { export_entry entry = exports->find(cand32); // Found an import reference unordered_set<unsigned __int64>::const_iterator gotImportAddress = import_addresses.find(cand32); if (gotImportAddress == import_addresses.end()) { // Add this new import import_addresses.insert(cand32); result.COUNT_UNIQUE_IMPORT_ADDRESSES++; // Add this imported function hash if (entry.name != NULL) { hash_generic = hash_generic ^ hasher(string(entry.name)); hash_specific = hash_specific ^ hasher(string(entry.name)); } if (entry.library_name != NULL) { hash_generic = hash_generic ^ (hasher(string(entry.library_name)) << 1); hash_specific = hash_specific ^ (hasher(string(entry.library_name)) << 1); } hash_generic = _rotl(hash_generic, 0x05); hash_specific = hash_specific ^ offset; hash_specific = _rotl(hash_specific, 0x05); } } } cand32_last = cand32; unsigned __int64 cand64 = *((unsigned __int64*)(_image + offset)); if (cand64 != cand64_last && cand64 > 0xffffffff) { if (exports->contains(cand64)) { export_entry entry = exports->find(cand64); // Found an import reference unordered_set<unsigned __int64>::const_iterator gotImportAddress = import_addresses.find(cand64); if (gotImportAddress == import_addresses.end()) { // Add this new import import_addresses.insert(cand64); result.COUNT_UNIQUE_IMPORT_ADDRESSES++; // Add this imported function hash if (entry.name != NULL) { hash_generic = hash_generic ^ hasher(string(entry.name)); hash_specific = hash_specific ^ hasher(string(entry.name)); } if (entry.library_name != NULL) { hash_generic = hash_generic ^ (hasher(string(entry.library_name)) << 1); hash_specific = hash_specific ^ (hasher(string(entry.library_name)) << 1); } hash_generic = _rotl(hash_generic, 0x05); hash_specific = hash_specific ^ offset; hash_specific = _rotl(hash_specific, 0x05); } } } cand64_last = cand64; } } result.HASH_GENERIC = hash_generic; result.HASH_SPECIFIC = hash_specific; if( _options->Verbose ) { printf( "INFO: Finished building import information:\n" ); printf( "INFO: Count Unique Import Addresses = %i\n", result.COUNT_UNIQUE_IMPORT_ADDRESSES ); printf( "INFO: Count Unique Import Libraries = %i\n", result.COUNT_UNIQUE_IMPORT_LIBRARIES ); printf( "INFO: Generic Hash = 0x%llX\n", result.HASH_GENERIC ); printf( "INFO: Specific Hash = 0x%llX\n", result.HASH_SPECIFIC ); } return result; } unsigned __int64 pe_header::get_hash() { if( _unique_hash == 0 ) process_hash(); return _unique_hash; } unsigned __int64 pe_header::get_hash_ep() { if (_unique_hash_ep == 0) process_hash_ep(); return _unique_hash_ep; } unsigned __int64 pe_header::get_hash_ep_short() { if (_unique_hash_ep_short == 0) process_hash_ep(); return _unique_hash_ep_short; } bool pe_header::build_pe_header( __int64 size, bool amd64 ) { return build_pe_header( size, amd64, 99 ); // Build it with as many sections as we can. } bool pe_header::build_pe_header( __int64 size, bool amd64, int num_sections_limit ) { if( _stream != NULL ) { _raw_header_size = 0x2000; _raw_header = new unsigned char[_raw_header_size]; memset( _raw_header, 0, _raw_header_size ); _original_base = (void*) ((__int64) _original_base - (__int64) _raw_header_size); _stream->update_base(-(__int64) _raw_header_size); // Build the old dos header _header_dos = (IMAGE_DOS_HEADER*) _raw_header; _header_dos->e_magic=0x5a4d; _header_dos->e_cblp=0x0090; _header_dos->e_cp=0x0003; _header_dos->e_crlc=0x0000; _header_dos->e_cparhdr=0x0004; _header_dos->e_minalloc=0x0000; _header_dos->e_maxalloc=0xffff; _header_dos->e_ss=0x0000; _header_dos->e_sp=0x00b8; _header_dos->e_csum=0x0000; _header_dos->e_ip=0x0000; _header_dos->e_cs=0x0000; _header_dos->e_lfarlc=0x0040; _header_dos->e_ovno=0x0000; memset( &_header_dos->e_res, 0, sizeof(WORD)*4 ); _header_dos->e_oemid=0x0000; _header_dos->e_oeminfo=0x0000; memset( &_header_dos->e_res2, 0, sizeof(WORD)*10 ); _header_dos->e_lfanew=0x000000e0; this->_parsed_dos = true; unsigned char* base_pe = _header_dos->e_lfanew + _raw_header; if( !amd64 ) { // Build intel 32 bit PE header _header_pe32 = (IMAGE_NT_HEADERS32*) base_pe; _header_pe32->Signature = 0x00004550; _header_pe32->FileHeader.Machine = IMAGE_FILE_MACHINE_I386; _header_pe32->FileHeader.NumberOfSections = 1; _header_pe32->FileHeader.NumberOfSymbols = 0; _header_pe32->FileHeader.PointerToSymbolTable = 0; _header_pe32->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32); if( _options->ReconstructHeaderAsDll ) _header_pe32->FileHeader.Characteristics = 0x0002; // Exe: 0x0002 else _header_pe32->FileHeader.Characteristics = 0x2000; // Dll: 0x2000 _header_pe32->OptionalHeader.Magic=0x10b; _header_pe32->OptionalHeader.MajorLinkerVersion=0x08; _header_pe32->OptionalHeader.MinorLinkerVersion=0x00; _header_pe32->OptionalHeader.SizeOfCode=0x00000000; _header_pe32->OptionalHeader.SizeOfInitializedData=0x00000000; _header_pe32->OptionalHeader.SizeOfUninitializedData=0x00000000; _header_pe32->OptionalHeader.AddressOfEntryPoint=0x2000; // Made up, start of first section _header_pe32->OptionalHeader.BaseOfCode=0x00002000; _header_pe32->OptionalHeader.ImageBase= (DWORD)_original_base; // Set to current address _header_pe32->OptionalHeader.SectionAlignment=0x00001000; _header_pe32->OptionalHeader.FileAlignment=0x000001000; _header_pe32->OptionalHeader.MajorOperatingSystemVersion=0x0004; _header_pe32->OptionalHeader.MinorOperatingSystemVersion=0x0000; _header_pe32->OptionalHeader.MajorImageVersion=0x0000; _header_pe32->OptionalHeader.MinorImageVersion=0x0000; _header_pe32->OptionalHeader.MajorSubsystemVersion=0x0005; _header_pe32->OptionalHeader.MinorSubsystemVersion=0x0002; _header_pe32->OptionalHeader.Win32VersionValue=0x00000000; _header_pe32->OptionalHeader.SizeOfImage=0x00006000; _header_pe32->OptionalHeader.SizeOfHeaders=0x00002000; _header_pe32->OptionalHeader.CheckSum=0x00000000; _header_pe32->OptionalHeader.Subsystem=0x0003; _header_pe32->OptionalHeader.DllCharacteristics=0x0000; // 0x2000 _header_pe32->OptionalHeader.SizeOfStackReserve=0x0000000000100000; _header_pe32->OptionalHeader.SizeOfStackCommit=0x0000000000001000; _header_pe32->OptionalHeader.SizeOfHeapReserve=0x0000000000100000; _header_pe32->OptionalHeader.SizeOfHeapCommit=0x0000000000001000; _header_pe32->OptionalHeader.LoaderFlags=0x00000000; _header_pe32->OptionalHeader.NumberOfRvaAndSizes=0x00000010; memset( &_header_pe32->OptionalHeader.DataDirectory, 0, sizeof(IMAGE_DATA_DIRECTORY)*IMAGE_NUMBEROF_DIRECTORY_ENTRIES ); _header_sections = (IMAGE_SECTION_HEADER*) (base_pe + sizeof(IMAGE_NT_HEADERS32)); this->_parsed_pe_32 = true; } else { // Build intel 64 bit PE header _header_pe64 = (IMAGE_NT_HEADERS64*) base_pe; _header_pe64->Signature = 0x00004550; _header_pe64->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; _header_pe64->FileHeader.NumberOfSections = 1; _header_pe64->FileHeader.NumberOfSymbols = 0; _header_pe64->FileHeader.PointerToSymbolTable = 0; _header_pe64->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); if( _options->ReconstructHeaderAsDll ) _header_pe64->FileHeader.Characteristics = 0x0002; // Exe: 0x0002 else _header_pe64->FileHeader.Characteristics = 0x2000; // Dll: 0x2000 _header_pe64->OptionalHeader.Magic=0x020b; _header_pe64->OptionalHeader.MajorLinkerVersion=0x08; _header_pe64->OptionalHeader.MinorLinkerVersion=0x00; _header_pe64->OptionalHeader.SizeOfCode=0x00000000; _header_pe64->OptionalHeader.SizeOfInitializedData=0x00000000; _header_pe64->OptionalHeader.SizeOfUninitializedData=0x00000000; // Select the entry point _header_pe64->OptionalHeader.AddressOfEntryPoint=0x2000; // Made up, start of first section _header_pe64->OptionalHeader.BaseOfCode=0x00002000; _header_pe64->OptionalHeader.ImageBase= (__int64)_original_base; // Set to current address _header_pe64->OptionalHeader.SectionAlignment=0x00001000; _header_pe64->OptionalHeader.FileAlignment=0x000001000; _header_pe64->OptionalHeader.MajorOperatingSystemVersion=0x0004; _header_pe64->OptionalHeader.MinorOperatingSystemVersion=0x0000; _header_pe64->OptionalHeader.MajorImageVersion=0x0000; _header_pe64->OptionalHeader.MinorImageVersion=0x0000; _header_pe64->OptionalHeader.MajorSubsystemVersion=0x0005; _header_pe64->OptionalHeader.MinorSubsystemVersion=0x0002; _header_pe64->OptionalHeader.Win32VersionValue=0x00000000; _header_pe64->OptionalHeader.SizeOfImage=0x00006000; _header_pe64->OptionalHeader.SizeOfHeaders=0x00002000; _header_pe64->OptionalHeader.CheckSum=0x00000000; _header_pe64->OptionalHeader.Subsystem=0x0003; _header_pe64->OptionalHeader.DllCharacteristics=0x0000; _header_pe64->OptionalHeader.SizeOfStackReserve=0x0000000000100000; _header_pe64->OptionalHeader.SizeOfStackCommit=0x0000000000001000; _header_pe64->OptionalHeader.SizeOfHeapReserve=0x0000000000100000; _header_pe64->OptionalHeader.SizeOfHeapCommit=0x0000000000001000; _header_pe64->OptionalHeader.LoaderFlags=0x00000000; _header_pe64->OptionalHeader.NumberOfRvaAndSizes=0x00000010; memset( &_header_pe64->OptionalHeader.DataDirectory, 0, sizeof(IMAGE_DATA_DIRECTORY)*IMAGE_NUMBEROF_DIRECTORY_ENTRIES ); _header_sections = (IMAGE_SECTION_HEADER*) (base_pe + sizeof(IMAGE_NT_HEADERS64)); this->_parsed_pe_64 = true; } // Create the sections _num_sections = 0; __int64 image_size = _raw_header_size; while( _stream->estimate_section_size(image_size) != 0 && image_size >= size && _num_sections < 99 && _num_sections < num_sections_limit ) { __int64 est_size = _stream->estimate_section_size(image_size); _header_sections[_num_sections].PointerToRawData = image_size; _header_sections[_num_sections].SizeOfRawData = est_size; _header_sections[_num_sections].VirtualAddress = image_size; _header_sections[_num_sections].Misc.PhysicalAddress = image_size; _header_sections[_num_sections].Misc.VirtualSize = est_size; _header_sections[_num_sections].Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; //_stream->get_region_characteristics(offset); char name[9]; sprintf_s( name, 9, "pd_rec%i", _num_sections); memcpy( &_header_sections[_num_sections].Name, name, 8 ); _header_sections[_num_sections].NumberOfLinenumbers = 0; _header_sections[_num_sections].NumberOfRelocations = 0; _header_sections[_num_sections].PointerToLinenumbers = 0; if( _options->Verbose ) printf("%s: size %x\n", name, image_size); _num_sections++; image_size += est_size; } // Update the number of sections and image size if( !amd64 ) { _header_pe32->FileHeader.NumberOfSections = _num_sections; _header_pe32->OptionalHeader.SizeOfImage = image_size; } else { _header_pe64->FileHeader.NumberOfSections = _num_sections; _header_pe64->OptionalHeader.SizeOfImage = image_size; } return true; } return false; } bool pe_header::process_pe_header( ) { if( _options->Verbose ) fprintf( stdout, "INFO: Loading PE header for %s.\n", this->get_name() ); if( _stream != NULL ) { // Request the block size of the first region _raw_header_size = _stream->block_size(0); _raw_header = new unsigned char[_raw_header_size]; if( _raw_header_size >= 0x500 ) { // Read in the PE header if( _stream->read(0, _raw_header_size, _raw_header, &_raw_header_size) && _raw_header_size >= 0x500 ) { // Parse the PE header if( _raw_header_size > sizeof(IMAGE_DOS_HEADER) ) { this->_header_dos = (IMAGE_DOS_HEADER*) _raw_header; if( _header_dos->e_magic == 0x5A4D ) { // Successfully parsed dos header this->_parsed_dos = true; // Parse the PE header unsigned char* base_pe = _header_dos->e_lfanew + _raw_header; if( _test_read( _raw_header, _raw_header_size, base_pe, sizeof(IMAGE_NT_HEADERS64) ) ) { // We are unsure if we need to process this as a 32bit or 64bit PE header, lets figure it out. // The first part is independent of the 32 or 64 bit definition. if ( ((IMAGE_NT_HEADERS32*)base_pe)->Signature == 0x4550 && ((IMAGE_NT_HEADERS32*)base_pe)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC ) { // 32bit module this->_header_pe32 = ((IMAGE_NT_HEADERS32*) base_pe); this->_parsed_pe_32 = true; if( _options->Verbose ) fprintf( stdout, "INFO: Loaded PE header for %s. Somewhat parsed: %d\n", this->get_name(), this->somewhat_parsed() ); return true; } else if( ((IMAGE_NT_HEADERS64*)base_pe)->Signature == 0x4550 && ((IMAGE_NT_HEADERS64*)base_pe)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC ) { // 64bit module this->_header_pe64 = ((IMAGE_NT_HEADERS64*) base_pe); this->_parsed_pe_64 = true; if( _options->Verbose ) fprintf( stdout, "INFO: Loaded PE header for %s. Somewhat parsed: %d\n", this->get_name(), this->somewhat_parsed() ); return true; } else { // error if (_options->Verbose) fprintf(stdout, "INFO: Invalid PE header for %s. Somewhat parsed: %d\n", this->get_name(), this->somewhat_parsed()); } } } } } } } else { if( _options->Verbose ) fprintf( stderr, "INFO: Invalid stream.\n" ); } if( _options->Verbose ) fprintf( stdout, "INFO: Loaded PE header for %s. Somewhat parsed: %d\n", this->get_name(), this->somewhat_parsed() ); return false; } bool pe_header::process_sections( ) { if( _options->Verbose ) fprintf( stdout, "INFO: Loading sections for %s.\n", this->get_name() ); if( this->_parsed_pe_32 ) { // Attempt to parse the sections unsigned char* base_pe = _header_dos->e_lfanew + _raw_header; unsigned char* base_sections = base_pe + sizeof(*_header_pe32); if( _header_pe32->FileHeader.NumberOfSections > 0x100 ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Extremely large number of sections of 0x%x changed to 0x100 as part of sanity check.\n", this->get_name(), location, _header_pe32->FileHeader.NumberOfSections ); _header_pe32->FileHeader.NumberOfSections = 0x100; delete[] location; } if( _test_read( _raw_header, _raw_header_size, base_sections, sizeof(IMAGE_SECTION_HEADER) ) ) { // Has room for at least 1 section. if( !_test_read( _raw_header, _raw_header_size, base_sections, _header_pe32->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER) ) ) { // Parse the maximum number of sections possible char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Number of sections being changed from 0x%x to 0x%x such that it will fit within the PE header buffer.\n", this->get_name(), location, _header_pe32->FileHeader.NumberOfSections, ( (_raw_header + _raw_header_size - base_sections - 1) / sizeof(IMAGE_SECTION_HEADER) ) ); delete[] location; _header_pe32->FileHeader.NumberOfSections = ( (_raw_header + _raw_header_size - base_sections - 1) / sizeof(IMAGE_SECTION_HEADER) ); } this->_parsed_sections = true; this->_num_sections = _header_pe32->FileHeader.NumberOfSections; this->_header_sections = (IMAGE_SECTION_HEADER*) base_sections; if( _options->Verbose ) { for( int i = 0; i < this->_num_sections; i++ ) { if( _test_read( _raw_header, _raw_header_size, this->_header_sections[i].Name, 0x40 ) ) fprintf( stdout, "INFO: %s\t#%i\t%s\t0x%x\t0x%x\n", this->get_name(), i, this->_header_sections[i].Name, this->_header_sections[i].VirtualAddress, this->_header_sections[i].SizeOfRawData ); else fprintf( stdout, "INFO: %s\t#%i\tINVALID ADDRESS\t0x%x\t0x%x\n", this->get_name(), i, this->_header_sections[i].VirtualAddress, this->_header_sections[i].SizeOfRawData ); } } // Calculate the total size of the virtual image by inspecting the last section DWORD image_size = 0; if( this->_num_sections > 0 ) { if( _header_sections[_num_sections - 1].Misc.VirtualSize > MAX_SECTION_SIZE ) { // Smartly choose _header_pe32->OptionalHeader.SizeOfImage or last section plus max section size if( _header_pe32->OptionalHeader.SizeOfImage > _header_sections[_num_sections - 1].VirtualAddress && _header_pe32->OptionalHeader.SizeOfImage < _header_sections[_num_sections - 1].VirtualAddress + MAX_SECTION_SIZE ) { // Use the _header_pe32->OptionalHeader.SizeOfImage, since it seems valid char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Image size of last section appears incorrect, using image size specified by optional header instead since it appears valid. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location); delete[] location; image_size = _header_pe32->OptionalHeader.SizeOfImage; } else { // Assume a really large last section since _header_pe32->OptionalHeader.SizeOfImage appears invalid. char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Image size of last section appears incorrect, using built-in max section size of 0x%x instead. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, MAX_SECTION_SIZE * (_num_sections+1)); delete[] location; image_size = _header_sections[_num_sections - 1].VirtualAddress + MAX_SECTION_SIZE; } } else image_size = _header_sections[_num_sections - 1].VirtualAddress + _header_sections[_num_sections - 1].Misc.VirtualSize; } if( _header_pe32->OptionalHeader.SizeOfImage > image_size ) image_size = _header_pe32->OptionalHeader.SizeOfImage; // Perform a sanity check on the resulting image size if( image_size > MAX_SECTION_SIZE * (_num_sections+1) ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large image size of 0x%x changed to 0x%x as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, image_size, MAX_SECTION_SIZE * (_num_sections+1) ); delete[] location; image_size = MAX_SECTION_SIZE * (_num_sections+1); } // Now lets build a proper image of this file with virtual alignment _image_size = image_size; _image = new unsigned char[_image_size]; memset(_image, 0, _image_size); // Read in this full image if( _stream->file_alignment ) { // Read in the full image from disk alignment // Read in the header SIZE_T num_read = 0; if( _test_read( _image, _image_size, _image, _header_pe32->OptionalHeader.SizeOfHeaders ) ) { if( !_stream->read(0, _header_pe32->OptionalHeader.SizeOfHeaders, _image, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in header of size 0x%x. Was only able to read 0x%x bytes from this region.\n",this->get_name(), location, _header_pe32->OptionalHeader.SizeOfHeaders, num_read); delete[] location; } } else { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in header.", this->get_name(), location); delete[] location; } // Loop through reading the sections into their respective virtual sections if( this->_parsed_sections ) { for( int i = 0; i < this->_num_sections; i++ ) { // Test the destination is valid if( _test_read( _image, _image_size, _image + (SIZE_T) this->_header_sections[i].VirtualAddress, this->_header_sections[i].SizeOfRawData ) ) { // Read in this section if( !_stream->read( this->_header_sections[i].PointerToRawData, this->_header_sections[i].SizeOfRawData, _image + (SIZE_T) this->_header_sections[i].VirtualAddress, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in section %i of size 0x%x. Was only able to read 0x%x bytes from this region.\n", this->get_name(), location, i, this->_header_sections[i].SizeOfRawData, num_read); delete[] location; } } } } } else { // Read in the full image from virtual alignment SIZE_T num_read = 0; if( !_stream->read( 0, _image_size, _image, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in image at 0x%llX of size 0x%x. Was only able to read 0x%x bytes from this region.\n",this->get_name(), location, this->_stream->get_address(), _image_size, num_read); delete[] location; } } if( _options->Verbose ) fprintf( stdout, "INFO: Loaded sections for %s with result: %d. %i sections found.\n", this->get_name(), this->_parsed_sections, ( this->_parsed_sections ? this->_num_sections : 0 ) ); return true; } } else if( this->_parsed_pe_64 ) { // Attempt to parse the sections unsigned char* base_pe = _header_dos->e_lfanew + _raw_header; unsigned char* base_sections = base_pe + sizeof(*_header_pe64); if( _header_pe64->FileHeader.NumberOfSections > 0x100 ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Extremely large number of sections of 0x%x changed to 0x100 as part of sanity check.\n", this->get_name(), location, _header_pe64->FileHeader.NumberOfSections ); _header_pe64->FileHeader.NumberOfSections = 0x100; delete[] location; } if( _test_read( _raw_header, _raw_header_size, base_sections, sizeof(IMAGE_SECTION_HEADER) ) ) { // Has room for at least 1 section. if( !_test_read( _raw_header, _raw_header_size, base_sections, _header_pe64->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER) ) ) { // Parse the maximum number of sections possible char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Number of sections being changed from 0x%x to 0x%x such that it will fit within the PE header buffer.\n", this->get_name(), location, _header_pe64->FileHeader.NumberOfSections, ( (_raw_header + _raw_header_size - base_sections - 1) / sizeof(IMAGE_SECTION_HEADER) ) ); delete[] location; _header_pe64->FileHeader.NumberOfSections = ( (_raw_header + _raw_header_size - base_sections - 1) / sizeof(IMAGE_SECTION_HEADER) ); } this->_parsed_sections = true; this->_num_sections = _header_pe64->FileHeader.NumberOfSections; this->_header_sections = (IMAGE_SECTION_HEADER*) base_sections; if( _options->Verbose ) { for( int i = 0; i < this->_num_sections; i++ ) { fprintf( stdout, "INFO: %s\t#%i\t%s\t0x%x\t0x%x\n", this->get_name(), i, this->_header_sections[i].Name, this->_header_sections[i].VirtualAddress, this->_header_sections[i].SizeOfRawData ); } } // Calculate the total size of the virtual image by inspecting the last section DWORD image_size = 0; if( this->_num_sections > 0 ) { if( _header_sections[_num_sections - 1].Misc.VirtualSize > MAX_SECTION_SIZE ) { // Smartly choose _header_pe64->OptionalHeader.SizeOfImage or last section plus max section size if( _header_pe64->OptionalHeader.SizeOfImage > _header_sections[_num_sections - 1].VirtualAddress && _header_pe64->OptionalHeader.SizeOfImage < _header_sections[_num_sections - 1].VirtualAddress + MAX_SECTION_SIZE ) { // Use the _header_pe64->OptionalHeader.SizeOfImage, since it seems valid char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Image size of last section appears incorrect, using image size specified by optional header instead since it appears valid. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location); delete[] location; image_size = _header_pe64->OptionalHeader.SizeOfImage; } else { // Assume a really large last section since _header_pe64->OptionalHeader.SizeOfImage appears invalid. char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Image size of last section appears incorrect, using built-in max section size of 0x%x instead. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, MAX_SECTION_SIZE * (_num_sections+1)); delete[] location; image_size = _header_sections[_num_sections - 1].VirtualAddress + MAX_SECTION_SIZE; } } else image_size = _header_sections[_num_sections - 1].VirtualAddress + _header_sections[_num_sections - 1].Misc.VirtualSize; } if( _header_pe64->OptionalHeader.SizeOfImage > image_size ) image_size = _header_pe64->OptionalHeader.SizeOfImage; // Perform a sanity check on the resulting image size if( image_size > MAX_SECTION_SIZE * (_num_sections+1) ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large image size of 0x%x changed to 0x%x as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, image_size, MAX_SECTION_SIZE * (_num_sections+1) ); delete[] location; image_size = MAX_SECTION_SIZE * (_num_sections+1); } // Now lets build a proper image of this file with virtual alignment _image_size = image_size; _image = new unsigned char[_image_size]; memset(_image, 0, _image_size); // Read in this full image if( _stream->file_alignment ) { // Read in the full image from disk alignment // Read in the header SIZE_T num_read = 0; if( _test_read( _image, _image_size, _image, _header_pe64->OptionalHeader.SizeOfHeaders ) ) { if( !_stream->read(0, _header_pe64->OptionalHeader.SizeOfHeaders, _image, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in header of size 0x%x. Was only able to read 0x%x bytes from this region.\n",this->get_name(), location, _header_pe64->OptionalHeader.SizeOfHeaders, num_read); delete[] location; } } else { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in header.", this->get_name(), location); delete[] location; } // Loop through reading the sections into their respective virtual sections if( this->_parsed_sections ) { for( int i = 0; i < this->_num_sections; i++ ) { // Test the destination is valid if( _test_read( _image, _image_size, _image + (SIZE_T) this->_header_sections[i].VirtualAddress, this->_header_sections[i].SizeOfRawData ) ) { // Read in this section if( !_stream->read( this->_header_sections[i].PointerToRawData, this->_header_sections[i].SizeOfRawData, _image + (SIZE_T) this->_header_sections[i].VirtualAddress, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in section %i of size 0x%x. Was only able to read 0x%x bytes from this region.\n", this->get_name(), location, i, this->_header_sections[i].SizeOfRawData, num_read); delete[] location; } } } } } else { // Read in the full image from virtual alignment SIZE_T num_read = 0; if( !_stream->read( 0, _image_size, _image, &num_read ) && _options->Verbose ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Failed to read in image at 0x%llX of size 0x%x. Was only able to read 0x%x bytes from this region.\n",this->get_name(), location, this->_stream->get_address(), _image_size, num_read); delete[] location; } } if( _options->Verbose ) fprintf( stdout, "INFO: Loaded sections for %s with result: %d. %i sections found.\n", this->get_name(), this->_parsed_sections, ( this->_parsed_sections ? this->_num_sections : 0 ) ); return true; } } if( _options->Verbose ) fprintf( stdout, "INFO: Failed to load sections for %s.\n", this->get_name() ); return false; } bool pe_header::process_disk_image( export_list* exports, pe_hash_database* hash_database) { if( this->_parsed_sections ) { if( this->_parsed_pe_32 ) { // Re-build the Original Entry Point OEP if it looks to be not valid if (_header_pe32->OptionalHeader.AddressOfEntryPoint == 0 || _header_pe32->OptionalHeader.AddressOfEntryPoint == 0x2000 || !_test_read(_image, _image_size, _image + _header_pe32->OptionalHeader.AddressOfEntryPoint, 20) || _options->ForceReconstructEntryPoint) { printf("INFO: Re-building entrypoint. Original entrypoint invalid: %x\n", _header_pe32->OptionalHeader.AddressOfEntryPoint); // The entry-point looks invalid, search for candidates to reconstruct it unsigned __int64 best_entrypoint = 0; for (__int64 offset = 0x1000; offset < _image_size - 8; offset += 1) { // Check if this is a possible entrypoint unsigned __int64 cand = *((__int64*)(_image + offset)); // Lookup the address if (hash_database->contains_epshort(cand)) { // This is a possible entrypoint, this is a weak correlation but we'll use it if it's all we have if (best_entrypoint == 0) { best_entrypoint = offset; } if( _options->Verbose ) printf("INFO: Possible entrypoint found (weak): %x\n", offset); // Validate that the full hash matches a known entrypoint cand = _hash_asm(offset); if (hash_database->contains_ep(cand)) { best_entrypoint = offset; printf("INFO: Possible entrypoint found (strong): %x\n", offset); if (!_options->Verbose) break; } } } // Update the entrypoint if (best_entrypoint != 0) { _header_pe32->OptionalHeader.AddressOfEntryPoint = best_entrypoint; printf("INFO: Updated entrypoint to: %x\n", best_entrypoint); } } // Reconstruct PE imports aggressively using our knowledge of all the exports addresses in this process // Technique: // 1. 'exports' defines all valid export addresses in this process // 2. Find any binary that points to a valid export in this rpocess // 3. Add a new section for the new HintName Array and Import Address Table // 4. For each binary patch found above, add a HintName and ImportAddress point so the loads // will recognize it correctly for analysis (IDA). unsigned char* larger_image; __int64 larger_image_size; if( _options->ImportRec ) { // Start the with the original import descriptor list pe_imports* peimp = new pe_imports( _image, _image_size, _header_import_descriptors, false ); // Add matches to exports in this process int count = 0; unsigned __int64 cand_last = 0; for(__int64 offset = 0; offset < _image_size - 8; offset+=4 ) { // Check if this 4-gram or 8-gram points to an export unsigned __int64 cand = *((__int32*)(_image + offset)); if ( cand_last != cand && exports->contains( cand ) ) { export_entry entry = exports->find(cand); // Add this to be reconstructed as an import if (entry.name != NULL) peimp->add_fixup(entry.library_name, entry.name, offset, this->_parsed_pe_64); else peimp->add_fixup(entry.library_name, entry.ord, offset, this->_parsed_pe_64); count++; } else { cand_last = cand; } } if( _options->Verbose ) printf( "INFO: Reconstructing %i imports.\n", count ); // Increase the image size for a new section __int64 descriptor_size = 0; __int64 data_size = 0; peimp->get_table_size( descriptor_size, data_size ); __int64 new_section_size = this->_section_align(data_size+descriptor_size, this->_header_pe32->OptionalHeader.SectionAlignment); // Increase the size of the last section _header_sections[_num_sections-1].Misc.VirtualSize = this->_section_align(_header_sections[_num_sections-1].Misc.VirtualSize, this->_header_pe32->OptionalHeader.SectionAlignment) + new_section_size; _header_sections[_num_sections-1].SizeOfRawData = _header_sections[_num_sections-1].Misc.VirtualSize; larger_image_size = this->_section_align((long long) this->_image_size, this->_header_pe32->OptionalHeader.SectionAlignment) + new_section_size; larger_image = new unsigned char[larger_image_size]; memset(larger_image, 0, larger_image_size); memcpy(larger_image, _image, _image_size); if( _options->Verbose ) printf( "INFO: Writing added import table.\n" ); // Write to the new section peimp->build_table( larger_image + this->_section_align((long long) _image_size, this->_header_pe32->OptionalHeader.SectionAlignment), new_section_size, (__int64) _image_size, (__int64) 0, descriptor_size ); if( _options->Verbose ) printf( "INFO: Updating import data directory.\n" ); // Update the PE header to refer to it _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = this->_section_align((long long) _image_size, this->_header_pe32->OptionalHeader.SectionAlignment); _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = descriptor_size; delete peimp; } else { larger_image_size = _image_size; larger_image = new unsigned char[larger_image_size]; memset(larger_image, 0, larger_image_size); memcpy(larger_image, _image, _image_size); } if( _original_base != 0 ) { // Adjust the preferred image base, this way the relocations doesn't have to be fixed _header_pe32->OptionalHeader.ImageBase = (DWORD) _original_base; } // Change the physical alignment to use the virtual alignment if( _options->Verbose ) printf( "INFO: Adjusting file alignment to %x.\n", _header_pe32->OptionalHeader.SectionAlignment); _header_pe32->OptionalHeader.FileAlignment = _header_pe32->OptionalHeader.SectionAlignment; // Adjust the physical size of each section to use the virtual size _header_pe32->OptionalHeader.SizeOfHeaders = _section_align(_header_pe32->OptionalHeader.SizeOfHeaders, _header_pe32->OptionalHeader.FileAlignment); DWORD required_space = _section_align( _header_pe32->OptionalHeader.SizeOfHeaders, _header_pe32->OptionalHeader.SectionAlignment); for( int i = 0; i < _num_sections; i++ ) { // Correct the VirtualSize of the section if it is too large if( this->_header_sections[i].Misc.VirtualSize > MAX_SECTION_SIZE ) { if( _options->Verbose ) printf( "INFO: Calculating required space for section %i.\n", i); if( i + 1 < _num_sections && this->_header_sections[i+1].VirtualAddress > this->_header_sections[i].VirtualAddress && this->_header_sections[i+1].VirtualAddress < this->_header_sections[i].VirtualAddress + MAX_SECTION_SIZE ) { // Calculate the virtual size manually char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x changed to 0x%x based on image size as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, this->_header_sections[i+1].VirtualAddress - this->_header_sections[i].VirtualAddress ); delete[] location; this->_header_sections[i].Misc.VirtualSize = this->_header_sections[i+1].VirtualAddress - this->_header_sections[i].VirtualAddress; } else { // Use MAX_SECTION_SIZE char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x changed to 0x%x based on maximum section size as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, MAX_SECTION_SIZE ); delete[] location; this->_header_sections[i].Misc.VirtualSize = MAX_SECTION_SIZE; } } // Truncate VirtualSize to fit inside image size if( this->_header_sections[i].Misc.VirtualSize + this->_header_sections[i].VirtualAddress > larger_image_size ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); DWORD new_size = larger_image_size - this->_header_sections[i].VirtualAddress; fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x being truncated to 0x%x to fit within the image size. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, new_size ); delete[] location; this->_header_sections[i].Misc.VirtualSize = new_size; } // Adjust the physical size to be at least the same size as the virtual size if( this->_header_sections[i].Misc.VirtualSize > _header_sections[i].SizeOfRawData ) { _header_sections[i].SizeOfRawData = this->_header_sections[i].Misc.VirtualSize; } // Update the pointer to raw data to be correct _header_sections[i].PointerToRawData = required_space; required_space = _section_align( required_space + _header_sections[i].SizeOfRawData, _header_pe32->OptionalHeader.FileAlignment ); } // Set the size of image _header_pe32->OptionalHeader.SizeOfImage = required_space; if( _options->Verbose ) printf( "INFO: Copying the corrected memory PE header into file PE header format.\n"); // Copy over the modified PE header into the imaged version if( _test_read( larger_image, larger_image_size, larger_image, _header_pe32->OptionalHeader.SizeOfHeaders ) && _test_read( _raw_header, _raw_header_size, _raw_header, _header_pe32->OptionalHeader.SizeOfHeaders ) ) { memcpy( larger_image, _raw_header, _header_pe32->OptionalHeader.SizeOfHeaders ); } else if( _test_read( larger_image, larger_image_size, larger_image, _raw_header_size ) && _test_read( _raw_header, _raw_header_size, _raw_header, _raw_header_size ) ) { memcpy( larger_image, _raw_header, _raw_header_size ); } if( _header_pe32->OptionalHeader.SectionAlignment >= _header_pe32->OptionalHeader.FileAlignment ) { // Pack it down into a disk image of the file if( _options->Verbose ) printf( "INFO: Packing down memory sections into the file.\n"); // Allocate the necessary space for the physical image and initialize it to zero _disk_image_size = required_space; _disk_image = new unsigned char[_disk_image_size]; memset(_disk_image, 0, _disk_image_size); // Copy the header if( _test_read( _disk_image, _disk_image_size, _disk_image, _section_align(_header_pe32->OptionalHeader.SizeOfHeaders, _header_pe32->OptionalHeader.FileAlignment) ) && _test_read( larger_image, larger_image_size, larger_image, _section_align(_header_pe32->OptionalHeader.SizeOfHeaders, _header_pe32->OptionalHeader.FileAlignment) ) ) { memcpy( _disk_image, larger_image, _header_pe32->OptionalHeader.SizeOfHeaders ); } if( _parsed_sections ) { // Copy the sections one-by-one for( int i = 0; i < _num_sections; i++ ) { if( _options->Verbose ) printf( "INFO: Packing down section %i.\n", i); // Copy this section if the source and destination are both within acceptable bounds if( _test_read( _disk_image, _disk_image_size, _disk_image + (SIZE_T) _header_sections[i].PointerToRawData, _header_sections[i].SizeOfRawData ) && _test_read( larger_image, larger_image_size, larger_image + (SIZE_T) _header_sections[i].VirtualAddress, _header_sections[i].SizeOfRawData )) { memcpy( _disk_image + _header_sections[i].PointerToRawData, larger_image + _header_sections[i].VirtualAddress, _header_sections[i].SizeOfRawData ); } } } delete [] larger_image; if( _options->Verbose ) printf( "INFO: Done processing disk image.\n"); return true; } delete [] larger_image; } else if( this->_parsed_pe_64 ) { // Re-build the Original Entry Point OEP if it looks to be not valid if (_header_pe64->OptionalHeader.AddressOfEntryPoint == 0 || _header_pe64->OptionalHeader.AddressOfEntryPoint == 0x2000 || !_test_read(_image, _image_size, _image + _header_pe64->OptionalHeader.AddressOfEntryPoint, 20) || _options->ForceReconstructEntryPoint) { printf("INFO: Re-building entrypoint. Original entrypoint invalid: %x\n", _header_pe64->OptionalHeader.AddressOfEntryPoint); // The entry-point looks invalid, search for candidates to reconstruct it unsigned __int64 best_entrypoint = 0; for (__int64 offset = 0x1000; offset < _image_size - 8; offset += 1) { // Check if this is a possible entrypoint unsigned __int64 cand = *((__int64*)(_image + offset)); // Lookup the address if (hash_database->contains_epshort(cand)) { // This is a possible entrypoint, this is a weak correlation but we'll use it if it's all we have if (best_entrypoint == 0) { best_entrypoint = offset; } if (_options->Verbose) printf("INFO: Possible entrypoint found (weak): %x\n", offset); // Validate that the full hash matches a known entrypoint cand = _hash_asm(offset); if (hash_database->contains_ep(cand)) { best_entrypoint = offset; printf("INFO: Possible entrypoint found (strong): %x\n", offset); if (!_options->Verbose) break; } } } // Update the entrypoint if (best_entrypoint != 0) { _header_pe64->OptionalHeader.AddressOfEntryPoint = best_entrypoint; printf("INFO: Updated entrypoint to: %x\n", best_entrypoint); } } // Reconstruct PE imports aggressively using our knowledge of all the exports addresses in this process // Technique: // 1. 'exports' defines all valid export addresses in this process // 2. Find any binary that points to a valid export in this rpocess // 3. Add a new section for the new HintName Array and Import Address Table // 4. For each binary patch found above, add a HintName and ImportAddress point so the loads // will recognize it correctly for analysis (IDA). unsigned char* larger_image; __int64 larger_image_size; if( _options->ImportRec ) { // Start the with the original import descriptor list pe_imports* peimp = new pe_imports( _image, _image_size, _header_import_descriptors, true ); // Add matches to exports in this process int count = 0; unsigned __int64 cand_last = 0; for(__int64 offset = 0; offset < _image_size - 8; offset+=4 ) { // Check if this 4-gram or 8-gram points to an export unsigned __int64 cand = *((unsigned __int64*)(_image + offset)); if (cand_last != cand && exports->contains(cand)) { export_entry entry = exports->find(cand); // Add this to be reconstructed as an import if (entry.name != NULL) peimp->add_fixup(entry.library_name, entry.name, offset, this->_parsed_pe_64); else peimp->add_fixup(entry.library_name, entry.ord, offset, this->_parsed_pe_64); count++; } else { cand_last = cand; } } if( _options->Verbose ) printf( "INFO: Reconstructing %i imports.\n", count ); // Increase the image size for a new section __int64 descriptor_size = 0; __int64 data_size = 0; peimp->get_table_size( descriptor_size, data_size ); __int64 new_section_size = this->_section_align(data_size+descriptor_size, this->_header_pe64->OptionalHeader.SectionAlignment); // Increase the size of the last section _header_sections[_num_sections-1].Misc.VirtualSize = this->_section_align(_header_sections[_num_sections-1].Misc.VirtualSize, this->_header_pe64->OptionalHeader.SectionAlignment) + new_section_size; _header_sections[_num_sections-1].SizeOfRawData = _header_sections[_num_sections-1].Misc.VirtualSize; larger_image_size = this->_section_align((long long) this->_image_size, this->_header_pe64->OptionalHeader.SectionAlignment) + new_section_size; larger_image = new unsigned char[larger_image_size]; memset(larger_image, 0, larger_image_size); memcpy(larger_image, _image, _image_size); if( _options->Verbose ) printf( "INFO: Writing added import table.\n" ); // Write to the new section peimp->build_table( larger_image + this->_section_align((long long) this->_image_size, this->_header_pe64->OptionalHeader.SectionAlignment), new_section_size, (__int64) _image_size, (__int64) 0, descriptor_size ); if( _options->Verbose ) printf( "INFO: Updating import data directory.\n" ); // Update the PE header to refer to it _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = this->_section_align((long long) this->_image_size, this->_header_pe64->OptionalHeader.SectionAlignment); _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = descriptor_size; delete peimp; } else { larger_image_size = _image_size; larger_image = new unsigned char[larger_image_size]; memset(larger_image, 0, larger_image_size); memcpy(larger_image, _image, _image_size); } if( _original_base != 0 ) { // Adjust the preferred image base, this way the relocations doesn't have to be fixed _header_pe64->OptionalHeader.ImageBase = reinterpret_cast<__int64> (_original_base); } // Change the physical alignment to use the virtual alignment if( _options->Verbose ) printf( "INFO: Adjusting file alignment to %x.\n", _header_pe64->OptionalHeader.SectionAlignment); _header_pe64->OptionalHeader.FileAlignment = _header_pe64->OptionalHeader.SectionAlignment; // Adjust the physical size of each section to use the virtual size _header_pe64->OptionalHeader.SizeOfHeaders = _section_align(_header_pe64->OptionalHeader.SizeOfHeaders, _header_pe64->OptionalHeader.FileAlignment); DWORD required_space = _section_align( _header_pe64->OptionalHeader.SizeOfHeaders, _header_pe64->OptionalHeader.SectionAlignment); for( int i = 0; i < _num_sections; i++ ) { // Correct the VirtualSize of the section if it is too large if( this->_header_sections[i].Misc.VirtualSize > MAX_SECTION_SIZE ) { if( _options->Verbose ) printf( "INFO: Calculating required space for section %i.\n", i); if( i + 1 < _num_sections && this->_header_sections[i+1].VirtualAddress > this->_header_sections[i].VirtualAddress && this->_header_sections[i+1].VirtualAddress < this->_header_sections[i].VirtualAddress + MAX_SECTION_SIZE ) { // Calculate the virtual size manually char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x changed to 0x%x based on image virtual size as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, this->_header_sections[i+1].VirtualAddress - this->_header_sections[i].VirtualAddress ); delete[] location; this->_header_sections[i].Misc.VirtualSize = this->_header_sections[i+1].VirtualAddress - this->_header_sections[i].VirtualAddress; } else { // Use MAX_SECTION_SIZE char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x changed to 0x%x based on maximum section size as part of sanity check. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, MAX_SECTION_SIZE ); delete[] location; this->_header_sections[i].Misc.VirtualSize = MAX_SECTION_SIZE; } } // Truncate VirtualSize to fit inside image size if( this->_header_sections[i].Misc.VirtualSize + this->_header_sections[i].VirtualAddress > larger_image_size ) { char* location = new char[FILEPATH_SIZE + 1]; _stream->get_location(location, FILEPATH_SIZE + 1); DWORD new_size = larger_image_size - this->_header_sections[i].VirtualAddress; fprintf( stderr, "WARNING: module '%s' at %s. Large section size for section %i of 0x%x being truncated to 0x%x to fit within the image size. This could be as a result of a custom code to load a library by means other than LoadLibrary().\n", this->get_name(), location, i, this->_header_sections[i].Misc.VirtualSize, new_size ); delete[] location; this->_header_sections[i].Misc.VirtualSize = new_size; } // Adjust the physical size to be at least the same size as the virtual size if( this->_header_sections[i].Misc.VirtualSize > _header_sections[i].SizeOfRawData ) { _header_sections[i].SizeOfRawData = this->_header_sections[i].Misc.VirtualSize; } // Update the pointer to raw data to be correct _header_sections[i].PointerToRawData = required_space; required_space = _section_align( required_space + _header_sections[i].SizeOfRawData, _header_pe64->OptionalHeader.FileAlignment ); } // Set the size of image _header_pe64->OptionalHeader.SizeOfImage = required_space; if( _options->Verbose ) printf( "INFO: Copying the corrected memory PE header into file PE header format.\n"); // Copy over the modified PE header into the imaged version if( _test_read( larger_image, larger_image_size, larger_image, _header_pe64->OptionalHeader.SizeOfHeaders ) && _test_read( _raw_header, _raw_header_size, _raw_header, _header_pe64->OptionalHeader.SizeOfHeaders ) ) { memcpy( larger_image, _raw_header, _header_pe64->OptionalHeader.SizeOfHeaders ); } else if( _test_read( larger_image, larger_image_size, larger_image, _raw_header_size ) && _test_read( _raw_header, _raw_header_size, _raw_header, _raw_header_size ) ) { memcpy( larger_image, _raw_header, _raw_header_size ); } if( _header_pe64->OptionalHeader.SectionAlignment >= _header_pe64->OptionalHeader.FileAlignment ) { // Pack it down into a disk image of the file if( _options->Verbose ) printf( "INFO: Packing down memory sections into the file.\n"); // Allocate the necessary space for the physical image and initialize it to zero _disk_image_size = required_space; _disk_image = new unsigned char[_disk_image_size]; memset(_disk_image, 0, _disk_image_size); // Copy the header if( _test_read( _disk_image, _disk_image_size, _disk_image, _section_align(_header_pe64->OptionalHeader.SizeOfHeaders, _header_pe64->OptionalHeader.FileAlignment) ) && _test_read( larger_image, larger_image_size, larger_image, _section_align(_header_pe64->OptionalHeader.SizeOfHeaders, _header_pe64->OptionalHeader.FileAlignment) ) ) { memcpy( _disk_image, larger_image, _header_pe64->OptionalHeader.SizeOfHeaders ); } if( _parsed_sections ) { // Copy the sections one-by-one for( int i = 0; i < _num_sections; i++ ) { if( _options->Verbose ) printf( "INFO: Packing down section %i.\n", i); // Copy this section if the source and destination are both within acceptable bounds if( _test_read( _disk_image, _disk_image_size, _disk_image + (SIZE_T) _header_sections[i].PointerToRawData, _header_sections[i].SizeOfRawData ) && _test_read( larger_image, larger_image_size, larger_image + (SIZE_T) _header_sections[i].VirtualAddress, _header_sections[i].SizeOfRawData )) { memcpy( _disk_image + _header_sections[i].PointerToRawData, larger_image + _header_sections[i].VirtualAddress, _header_sections[i].SizeOfRawData ); } } } delete [] larger_image; if( _options->Verbose ) printf( "INFO: Done processing disk image.\n"); return true; } delete [] larger_image; } } return false; } bool pe_header::process_import_directory( ) { if( this->_parsed_pe_32 ) { // Test case for import reconstruction - destroy it :) //_header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = 0; //_header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = 0; if( _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress != 0 ) { unsigned char* base_imports = _image + _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; // Count the number of IMAGE_IMPORT_DESCRIPTORs _header_import_descriptors_count = 0; bool more; do { more = false; if( _test_read( _image,_image_size, base_imports + _header_import_descriptors_count * sizeof(IMAGE_IMPORT_DESCRIPTOR ), sizeof(IMAGE_IMPORT_DESCRIPTOR ) ) ) { IMAGE_IMPORT_DESCRIPTOR* current = &((IMAGE_IMPORT_DESCRIPTOR*) base_imports)[_header_import_descriptors_count]; if( current->Characteristics != 0 || current->FirstThunk != 0 || current->ForwarderChain != 0 || current->Name != 0 ) { more = true; _header_import_descriptors_count++; } } }while(more); if( _options->Verbose ) printf("Found %i import descriptors.\n", _header_import_descriptors_count); if( _header_import_descriptors_count > 0 ) { // Load the IMAGE_IMPORT_DESCRIPTOR array _header_import_descriptors = (IMAGE_IMPORT_DESCRIPTOR*) base_imports; // Now process and fix the contents of each of these IMAGE_IMPORT_DESCRIPTORs. We assume the // OriginalFirstThunk HintName array is valid. // TODO: Upgrade this to assume OriginalFirstThunk array is invalid. for( int i = 0; i < _header_import_descriptors_count; i++ ) { int num_iat_entries = 0; bool more; do{ more = false; if( _test_read( _image, _image_size, _image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ) && _test_read( _image, _image_size, _image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ) && *((DWORD*)(_image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32))) != 0 && *((DWORD*)(_image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32))) != 0) { memcpy( _image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), _image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ); more = true; num_iat_entries++; } // TODO: Parse the import table information }while(more); if( _options->Verbose ) printf("Reconstructed %i thunk data entries.\n", num_iat_entries); } } } return true; } else if( this->_parsed_pe_64 ) { // Test case for import reconstruction - destroy it :) //_header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = 0; //_header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = 0; if( _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress != 0 ) { unsigned char* base_imports = _image + _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; // Count the number of IMAGE_IMPORT_DESCRIPTORs _header_import_descriptors_count = 0; bool more; do { more = false; if( _test_read( _image,_image_size, base_imports + _header_import_descriptors_count * sizeof(IMAGE_IMPORT_DESCRIPTOR ), sizeof(IMAGE_IMPORT_DESCRIPTOR ) ) ) { IMAGE_IMPORT_DESCRIPTOR* current = &((IMAGE_IMPORT_DESCRIPTOR*) base_imports)[_header_import_descriptors_count]; if( current->Characteristics != 0 || current->FirstThunk != 0 || current->ForwarderChain != 0 || current->Name != 0 ) { more = true; _header_import_descriptors_count++; } } }while(more); if( _options->Verbose ) printf("Found %i import descriptors.\n", _header_import_descriptors_count); if( _header_import_descriptors_count > 0 ) { // Load the IMAGE_IMPORT_DESCRIPTOR array _header_import_descriptors = (IMAGE_IMPORT_DESCRIPTOR*) base_imports; // Now process and fix the contents of each of these IMAGE_IMPORT_DESCRIPTORs. We assume the // OriginalFirstThunk HintName array is valid. // TODO: Upgrade this to assume OriginalFirstThunk array is invalid. for( int i = 0; i < _header_import_descriptors_count; i++ ) { int num_iat_entries = 0; bool more; do{ more = false; if( _test_read( _image, _image_size, _image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ) && _test_read( _image, _image_size, _image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ) && *((DWORD*)(_image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32))) != 0 && *((DWORD*)(_image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32))) != 0) { memcpy( _image + _header_import_descriptors[i].FirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), _image + _header_import_descriptors[i].OriginalFirstThunk + num_iat_entries*sizeof(_IMAGE_THUNK_DATA32), sizeof(_IMAGE_THUNK_DATA32) ); more = true; num_iat_entries++; } // TODO: Parse the import table information }while(more); if( _options->Verbose ) printf("Reconstructed %i thunk data entries.\n", num_iat_entries); } } } return true; } return false; } bool pe_header::process_export_directory( ) { _header_import_descriptors_count = 0; if( (this->_parsed_pe_32 || this->_parsed_pe_64) && _image != NULL ) { unsigned char* base_exports; if( _parsed_pe_32 ) base_exports = _image + _header_pe32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; else base_exports = _image + _header_pe64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; if( _test_read( _image,_image_size, base_exports, sizeof(IMAGE_EXPORT_DIRECTORY ) ) ) { _header_export_directory = ((IMAGE_EXPORT_DIRECTORY*) base_exports); // Parse this export directory _export_list = new export_list(); _export_list->add_exports( _image, _image_size, (__int64) _original_base, _header_export_directory, this->_parsed_pe_64); return true; } } return false; } bool pe_header::_test_read( unsigned char* buffer, SIZE_T length, unsigned char* read_ptr, SIZE_T read_length ) { return read_ptr >= buffer && read_ptr + read_length <= buffer + length; } pe_header::~pe_header(void) { if( this->_stream != NULL ) delete this->_stream; if( this->_image_size != 0 ) delete[] _image; if( this->_raw_header_size != 0 ) delete[] _raw_header; if( this->_disk_image_size != 0 ) delete[] _disk_image; if( this->_name_filepath_long != 0 ) delete[] _name_filepath_long; if( this->_name_filepath_short != 0 ) delete[] _name_filepath_short; if( this->_name_original_exports != 0 ) delete[] _name_original_exports; if( this->_name_original_manifest != 0 ) delete[] _name_original_manifest; if( this->_name_symbols_path != 0 ) delete[] _name_symbols_path; if( this->_export_list != NULL ) delete _export_list; } DWORD pe_header::_section_align( DWORD address, DWORD alignment) { // Round the address up to the nearest section alignment if( alignment > 0 && address % alignment > 0 ) return (address - (address % alignment)) + alignment; return address; } __int64 pe_header::_section_align( __int64 address, DWORD alignment) { // Round the address up to the nearest section alignment if( address % alignment > 0 ) return (address - (address % alignment)) + alignment; return address; }
39.23835
276
0.692606
[ "object" ]
eae78d4bd332954d892de441cde27b0fcdd7e279
72,736
cc
C++
virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/srsenb/src/upper/rrc.cc
Joanguitar/docker-nextepc
2b606487968fe63ce19a8acf58938a84d97ffb89
[ "MIT" ]
1
2020-10-02T00:20:22.000Z
2020-10-02T00:20:22.000Z
srsenb/src/upper/rrc.cc
rzrepo/U-CIMAN
292be030da3a2ec6fe8230630547e04837e2fa34
[ "MIT" ]
null
null
null
srsenb/src/upper/rrc.cc
rzrepo/U-CIMAN
292be030da3a2ec6fe8230630547e04837e2fa34
[ "MIT" ]
3
2020-04-04T18:26:04.000Z
2021-09-24T18:41:01.000Z
/** * * \section COPYRIGHT * * Copyright 2013-2017 Software Radio Systems Limited * * \section LICENSE * * This file is part of srsLTE. * * srsUE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * srsUE 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 Affero General Public License for more details. * * A copy of the GNU Affero General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * */ #include "srslte/interfaces/sched_interface.h" #include "srslte/asn1/liblte_rrc.h" #include "srsenb/hdr/upper/rrc.h" #include "srslte/srslte.h" #include "srslte/asn1/liblte_mme.h" #include "srslte/common/int_helpers.h" using srslte::byte_buffer_t; using srslte::bit_buffer_t; using srslte::uint32_to_uint8; using srslte::uint8_to_uint32; namespace srsenb { void rrc::init(rrc_cfg_t *cfg_, phy_interface_rrc* phy_, mac_interface_rrc* mac_, rlc_interface_rrc* rlc_, pdcp_interface_rrc* pdcp_, s1ap_interface_rrc *s1ap_, gtpu_interface_rrc* gtpu_, srslte::log* log_rrc) { phy = phy_; mac = mac_; rlc = rlc_; pdcp = pdcp_; gtpu = gtpu_; s1ap = s1ap_; rrc_log = log_rrc; cnotifier = NULL; running = false; pool = srslte::byte_buffer_pool::get_instance(); memcpy(&cfg, cfg_, sizeof(rrc_cfg_t)); if(cfg.sibs[12].sib_type == LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_13 && cfg_->enable_mbsfn) { configure_mbsfn_sibs(&cfg.sibs[1].sib.sib2,&cfg.sibs[12].sib.sib13); } nof_si_messages = generate_sibs(); config_mac(); pthread_mutex_init(&user_mutex, NULL); pthread_mutex_init(&paging_mutex, NULL); act_monitor.start(RRC_THREAD_PRIO); bzero(&sr_sched, sizeof(sr_sched_t)); start(RRC_THREAD_PRIO); } void rrc::set_connect_notifer(connect_notifier *cnotifier) { this->cnotifier = cnotifier; } void rrc::stop() { if(running) { running = false; rrc_pdu p = {0, LCID_EXIT, NULL}; rx_pdu_queue.push(p); wait_thread_finish(); } act_monitor.stop(); pthread_mutex_lock(&user_mutex); users.clear(); pthread_mutex_unlock(&user_mutex); pthread_mutex_destroy(&user_mutex); pthread_mutex_destroy(&paging_mutex); } /******************************************************************************* Public functions All public functions must be mutexed. *******************************************************************************/ void rrc::get_metrics(rrc_metrics_t &m) { if (running) { pthread_mutex_lock(&user_mutex); m.n_ues = 0; for(std::map<uint16_t, ue>::iterator iter=users.begin(); m.n_ues < ENB_METRICS_MAX_USERS &&iter!=users.end(); ++iter) { ue *u = (ue*) &iter->second; if(iter->first != SRSLTE_MRNTI){ m.ues[m.n_ues++].state = u->get_state(); } } pthread_mutex_unlock(&user_mutex); } } /******************************************************************************* MAC interface Those functions that shall be called from a phch_worker should push the command to the queue and process later *******************************************************************************/ void rrc::read_pdu_bcch_dlsch(uint32_t sib_index, uint8_t* payload) { if (sib_index < LIBLTE_RRC_MAX_SIB) { memcpy(payload, sib_buffer[sib_index].msg, sib_buffer[sib_index].N_bytes); } } void rrc::rl_failure(uint16_t rnti) { rrc_pdu p = {rnti, LCID_RLF_USER, NULL}; rx_pdu_queue.push(p); } void rrc::set_activity_user(uint16_t rnti) { rrc_pdu p = {rnti, LCID_ACT_USER, NULL}; rx_pdu_queue.push(p); } void rrc::rem_user_thread(uint16_t rnti) { rrc_pdu p = {rnti, LCID_REM_USER, NULL}; rx_pdu_queue.push(p); } uint32_t rrc::get_nof_users() { return users.size(); } void rrc::max_retx_attempted(uint16_t rnti) { } // This function is called from PRACH worker (can wait) void rrc::add_user(uint16_t rnti) { pthread_mutex_lock(&user_mutex); if (users.count(rnti) == 0) { users[rnti].parent = this; users[rnti].rnti = rnti; rlc->add_user(rnti); pdcp->add_user(rnti); rrc_log->info("Added new user rnti=0x%x\n", rnti); } else { rrc_log->error("Adding user rnti=0x%x (already exists)\n", rnti); } if(rnti == SRSLTE_MRNTI){ srslte::srslte_pdcp_config_t cfg; cfg.is_control = false; cfg.is_data = true; cfg.direction = SECURITY_DIRECTION_DOWNLINK; uint32_t teid_in = 1; for(uint32_t i = 0; i <mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9_size; i++) { uint32_t lcid = mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[i].logicalchannelid_r9; rlc->add_bearer_mrb(SRSLTE_MRNTI,lcid); pdcp->add_bearer(SRSLTE_MRNTI,lcid,cfg); gtpu->add_bearer(SRSLTE_MRNTI,lcid, 1, 1, &teid_in); } } pthread_mutex_unlock(&user_mutex); } /* Function called by MAC after the reception of a C-RNTI CE indicating that the UE still has a * valid RNTI. * Called by MAC reader thread (can wait to process) */ void rrc::upd_user(uint16_t new_rnti, uint16_t old_rnti) { // Remove new_rnti rem_user_thread(new_rnti); // Send Reconfiguration to old_rnti if is RRC_CONNECT or RRC Release if already released here pthread_mutex_lock(&user_mutex); if (users.count(old_rnti) == 1) { if (users[old_rnti].is_connected()) { users[old_rnti].send_connection_reconf_upd(pool_allocate); } else { users[old_rnti].send_connection_release(); } } pthread_mutex_unlock(&user_mutex); } /******************************************************************************* PDCP interface *******************************************************************************/ void rrc::write_pdu(uint16_t rnti, uint32_t lcid, byte_buffer_t* pdu) { rrc_pdu p = {rnti, lcid, pdu}; rx_pdu_queue.push(p); } /******************************************************************************* S1AP interface *******************************************************************************/ void rrc::write_dl_info(uint16_t rnti, byte_buffer_t* sdu) { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; bzero(&dl_dcch_msg, sizeof(LIBLTE_RRC_DL_DCCH_MSG_STRUCT)); pthread_mutex_lock(&user_mutex); if (users.count(rnti) == 1) { dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_DL_INFO_TRANSFER; memcpy(dl_dcch_msg.msg.dl_info_transfer.dedicated_info.msg, sdu->msg, sdu->N_bytes); dl_dcch_msg.msg.dl_info_transfer.dedicated_info.N_bytes = sdu->N_bytes; sdu->reset(); users[rnti].send_dl_dcch(&dl_dcch_msg, sdu); } else { rrc_log->error("Rx SDU for unknown rnti=0x%x\n", rnti); } pthread_mutex_unlock(&user_mutex); } void rrc::release_complete(uint16_t rnti) { rrc_pdu p = {rnti, LCID_REL_USER, NULL}; rx_pdu_queue.push(p); } bool rrc::setup_ue_ctxt(uint16_t rnti, LIBLTE_S1AP_MESSAGE_INITIALCONTEXTSETUPREQUEST_STRUCT *msg) { pthread_mutex_lock(&user_mutex); rrc_log->info("Adding initial context for 0x%x\n", rnti); if(users.count(rnti) == 0) { rrc_log->warning("Unrecognised rnti: 0x%x\n", rnti); pthread_mutex_unlock(&user_mutex); return false; } if(msg->CSFallbackIndicator_present) { rrc_log->warning("Not handling CSFallbackIndicator\n"); } if(msg->AdditionalCSFallbackIndicator_present) { rrc_log->warning("Not handling AdditionalCSFallbackIndicator\n"); } if(msg->CSGMembershipStatus_present) { rrc_log->warning("Not handling CSGMembershipStatus\n"); } if(msg->GUMMEI_ID_present) { rrc_log->warning("Not handling GUMMEI_ID\n"); } if(msg->HandoverRestrictionList_present) { rrc_log->warning("Not handling HandoverRestrictionList\n"); } if(msg->ManagementBasedMDTAllowed_present) { rrc_log->warning("Not handling ManagementBasedMDTAllowed\n"); } if(msg->ManagementBasedMDTPLMNList_present) { rrc_log->warning("Not handling ManagementBasedMDTPLMNList\n"); } if(msg->MME_UE_S1AP_ID_2_present) { rrc_log->warning("Not handling MME_UE_S1AP_ID_2\n"); } if(msg->RegisteredLAI_present) { rrc_log->warning("Not handling RegisteredLAI\n"); } if(msg->SRVCCOperationPossible_present) { rrc_log->warning("Not handling SRVCCOperationPossible\n"); } if(msg->SubscriberProfileIDforRFP_present) { rrc_log->warning("Not handling SubscriberProfileIDforRFP\n"); } if(msg->TraceActivation_present) { rrc_log->warning("Not handling TraceActivation\n"); } if(msg->UERadioCapability_present) { rrc_log->warning("Not handling UERadioCapability\n"); } // UEAggregateMaximumBitrate users[rnti].set_bitrates(&msg->uEaggregateMaximumBitrate); // UESecurityCapabilities users[rnti].set_security_capabilities(&msg->UESecurityCapabilities); // SecurityKey uint8_t key[32]; liblte_pack(msg->SecurityKey.buffer, LIBLTE_S1AP_SECURITYKEY_BIT_STRING_LEN, key); users[rnti].set_security_key(key, LIBLTE_S1AP_SECURITYKEY_BIT_STRING_LEN/8); // Send RRC security mode command users[rnti].send_security_mode_command(); // Setup E-RABs users[rnti].setup_erabs(&msg->E_RABToBeSetupListCtxtSUReq); pthread_mutex_unlock(&user_mutex); return true; } bool rrc::setup_ue_erabs(uint16_t rnti, LIBLTE_S1AP_MESSAGE_E_RABSETUPREQUEST_STRUCT *msg) { pthread_mutex_lock(&user_mutex); rrc_log->info("Setting up erab(s) for 0x%x\n", rnti); if(users.count(rnti) == 0) { rrc_log->warning("Unrecognised rnti: 0x%x\n", rnti); pthread_mutex_unlock(&user_mutex); return false; } if(msg->uEaggregateMaximumBitrate_present) { // UEAggregateMaximumBitrate users[rnti].set_bitrates(&msg->uEaggregateMaximumBitrate); } // Setup E-RABs users[rnti].setup_erabs(&msg->E_RABToBeSetupListBearerSUReq); pthread_mutex_unlock(&user_mutex); return true; } bool rrc::release_erabs(uint32_t rnti) { pthread_mutex_lock(&user_mutex); rrc_log->info("Releasing E-RABs for 0x%x\n", rnti); if(users.count(rnti) == 0) { rrc_log->warning("Unrecognised rnti: 0x%x\n", rnti); pthread_mutex_unlock(&user_mutex); return false; } bool ret = users[rnti].release_erabs(); pthread_mutex_unlock(&user_mutex); return ret; } /******************************************************************************* Paging functions These functions use a different mutex because access different shared variables than user map *******************************************************************************/ void rrc::add_paging_id(uint32_t ueid, LIBLTE_S1AP_UEPAGINGID_STRUCT UEPagingID) { pthread_mutex_lock(&paging_mutex); if (pending_paging.count(ueid) == 0) { pending_paging[ueid] = UEPagingID; } else { rrc_log->warning("Received Paging for UEID=%d but not yet transmitted\n", ueid); } pthread_mutex_unlock(&paging_mutex); } // Described in Section 7 of 36.304 bool rrc::is_paging_opportunity(uint32_t tti, uint32_t *payload_len) { int sf_pattern[4][4] = {{9, 4, -1, 0}, {-1, 9, -1, 4}, {-1, -1, -1, 5}, {-1, -1, -1, 9}}; if (pending_paging.empty()) { return false; } pthread_mutex_lock(&paging_mutex); LIBLTE_RRC_PCCH_MSG_STRUCT pcch_msg; bzero(&pcch_msg, sizeof(LIBLTE_RRC_PCCH_MSG_STRUCT)); // Default paging cycle, should get DRX from user uint32_t T = liblte_rrc_default_paging_cycle_num[cfg.sibs[1].sib.sib2.rr_config_common_sib.pcch_cnfg.default_paging_cycle]; uint32_t Nb = T*liblte_rrc_nb_num[cfg.sibs[1].sib.sib2.rr_config_common_sib.pcch_cnfg.nB]; uint32_t N = T<Nb?T:Nb; uint32_t Ns = Nb/T>1?Nb/T:1; uint32_t sfn = tti/10; std::vector<uint32_t> ue_to_remove; int n=0; for(std::map<uint32_t, LIBLTE_S1AP_UEPAGINGID_STRUCT>::iterator iter=pending_paging.begin(); n < LIBLTE_RRC_MAX_PAGE_REC && iter!=pending_paging.end(); ++iter) { LIBLTE_S1AP_UEPAGINGID_STRUCT u = (LIBLTE_S1AP_UEPAGINGID_STRUCT) iter->second; uint32_t ueid = ((uint32_t) iter->first)%1024; uint32_t i_s = (ueid/N) % Ns; if ((sfn % T) == (T/N) * (ueid % N)) { int sf_idx = sf_pattern[i_s%4][(Ns-1)%4]; if (sf_idx < 0) { rrc_log->error("SF pattern is N/A for Ns=%d, i_s=%d, imsi_decimal=%d\n", Ns, i_s, ueid); } else if ((uint32_t) sf_idx == (tti%10)) { if (u.choice_type == LIBLTE_S1AP_UEPAGINGID_CHOICE_IMSI) { pcch_msg.paging_record_list[n].ue_identity.ue_identity_type = LIBLTE_RRC_PAGING_UE_IDENTITY_TYPE_IMSI; memcpy(pcch_msg.paging_record_list[n].ue_identity.imsi, u.choice.iMSI.buffer, u.choice.iMSI.n_octets); pcch_msg.paging_record_list[n].ue_identity.imsi_size = u.choice.iMSI.n_octets; printf("Warning IMSI paging not tested\n"); } else { pcch_msg.paging_record_list[n].ue_identity.ue_identity_type = LIBLTE_RRC_PAGING_UE_IDENTITY_TYPE_S_TMSI; pcch_msg.paging_record_list[n].ue_identity.s_tmsi.mmec = u.choice.s_TMSI.mMEC.buffer[0]; uint32_t m_tmsi = 0; for (int i=0;i<LIBLTE_S1AP_M_TMSI_OCTET_STRING_LEN;i++) { m_tmsi |= u.choice.s_TMSI.m_TMSI.buffer[i]<<(8*(LIBLTE_S1AP_M_TMSI_OCTET_STRING_LEN-i-1)); } pcch_msg.paging_record_list[n].ue_identity.s_tmsi.m_tmsi = m_tmsi; } pcch_msg.paging_record_list[n].cn_domain = LIBLTE_RRC_CN_DOMAIN_PS; ue_to_remove.push_back(ueid); n++; rrc_log->info("Assembled paging for ue_id=%d, tti=%d\n", ueid, tti); } } } for (uint32_t i=0;i<ue_to_remove.size();i++) { pending_paging.erase(ue_to_remove[i]); } pthread_mutex_unlock(&paging_mutex); if (n > 0) { pcch_msg.paging_record_list_size = n; liblte_rrc_pack_pcch_msg(&pcch_msg, (LIBLTE_BIT_MSG_STRUCT*)&bit_buf_paging); uint32_t N_bytes = (bit_buf_paging.N_bits-1)/8+1; if (payload_len) { *payload_len = N_bytes; } rrc_log->info("Assembling PCCH payload with %d UE identities, payload_len=%d bytes, nbits=%d\n", pcch_msg.paging_record_list_size, N_bytes, bit_buf_paging.N_bits); return true; } return false; } void rrc::read_pdu_pcch(uint8_t *payload, uint32_t buffer_size) { pthread_mutex_lock(&paging_mutex); uint32_t N_bytes = (bit_buf_paging.N_bits-1)/8+1; if (N_bytes <= buffer_size) { srslte_bit_pack_vector(bit_buf_paging.msg, payload, bit_buf_paging.N_bits); } pthread_mutex_unlock(&paging_mutex); } /******************************************************************************* Private functions All private functions are not mutexed and must be called from a mutexed enviornment from either a public function or the internal thread *******************************************************************************/ void rrc::parse_ul_ccch(uint16_t rnti, byte_buffer_t *pdu) { uint16_t old_rnti = 0; if (pdu) { LIBLTE_RRC_UL_CCCH_MSG_STRUCT ul_ccch_msg; bzero(&ul_ccch_msg, sizeof(LIBLTE_RRC_UL_CCCH_MSG_STRUCT)); srslte_bit_unpack_vector(pdu->msg, bit_buf.msg, pdu->N_bytes * 8); bit_buf.N_bits = pdu->N_bytes * 8; liblte_rrc_unpack_ul_ccch_msg((LIBLTE_BIT_MSG_STRUCT *) &bit_buf, &ul_ccch_msg); rrc_log->info_hex(pdu->msg, pdu->N_bytes, "SRB0 - Rx: %s", liblte_rrc_ul_ccch_msg_type_text[ul_ccch_msg.msg_type]); switch (ul_ccch_msg.msg_type) { case LIBLTE_RRC_UL_CCCH_MSG_TYPE_RRC_CON_REQ: if (users.count(rnti)) { users[rnti].handle_rrc_con_req(&ul_ccch_msg.msg.rrc_con_req); } else { rrc_log->error("Received ConnectionSetup for rnti=0x%x without context\n", rnti); } break; case LIBLTE_RRC_UL_CCCH_MSG_TYPE_RRC_CON_REEST_REQ: rrc_log->debug("rnti=0x%x, phyid=0x%x, smac=0x%x, cause=%s\n", ul_ccch_msg.msg.rrc_con_reest_req.ue_id.c_rnti, ul_ccch_msg.msg.rrc_con_reest_req.ue_id.phys_cell_id, ul_ccch_msg.msg.rrc_con_reest_req.ue_id.short_mac_i, liblte_rrc_con_reest_req_cause_text[ul_ccch_msg.msg.rrc_con_reest_req.cause] ); if (users[rnti].is_idle()) { old_rnti = ul_ccch_msg.msg.rrc_con_reest_req.ue_id.c_rnti; if (users.count(old_rnti)) { rrc_log->error("Not supported: ConnectionReestablishment for rnti=0x%x. Sending Connection Reject\n", old_rnti); users[rnti].send_connection_reest_rej(); s1ap->user_release(old_rnti, LIBLTE_S1AP_CAUSERADIONETWORK_RELEASE_DUE_TO_EUTRAN_GENERATED_REASON); } else { rrc_log->error("Received ConnectionReestablishment for rnti=0x%x without context\n", old_rnti); users[rnti].send_connection_reest_rej(); } // remove temporal rnti rrc_log->warning("Received ConnectionReestablishment for rnti=0x%x. Removing temporal rnti=0x%x\n", old_rnti, rnti); rem_user_thread(rnti); } else { rrc_log->error("Received ReestablishmentRequest from an rnti=0x%x not in IDLE\n", rnti); } break; default: rrc_log->error("UL CCCH message not recognised\n"); break; } pool->deallocate(pdu); } } void rrc::parse_ul_dcch(uint16_t rnti, uint32_t lcid, byte_buffer_t *pdu) { if (pdu) { if (users.count(rnti)) { users[rnti].parse_ul_dcch(lcid, pdu); } else { rrc_log->error("Processing %s: Unkown rnti=0x%x\n", rb_id_text[lcid], rnti); } } } void rrc::process_rl_failure(uint16_t rnti) { if (users.count(rnti) == 1) { uint32_t n_rfl = users[rnti].rl_failure(); if (n_rfl == 1) { rrc_log->info("Radio-Link failure detected rnti=0x%x\n", rnti); if (s1ap->user_exists(rnti)) { if (!s1ap->user_release(rnti, LIBLTE_S1AP_CAUSERADIONETWORK_RADIO_CONNECTION_WITH_UE_LOST)) { rrc_log->info("Removing rnti=0x%x\n", rnti); } } else { rrc_log->warning("User rnti=0x%x context not existing in S1AP. Removing user\n", rnti); // Remove user from separate thread to wait to close all resources rem_user_thread(rnti); } } else { rrc_log->info("%d Radio-Link failure detected rnti=0x%x\n", n_rfl, rnti); } } else { rrc_log->error("Radio-Link failure detected for uknown rnti=0x%x\n", rnti); } } void rrc::process_release_complete(uint16_t rnti) { rrc_log->info("Received Release Complete rnti=0x%x\n", rnti); if (users.count(rnti) == 1) { if (!users[rnti].is_idle()) { rlc->clear_buffer(rnti); users[rnti].send_connection_release(); // There is no RRCReleaseComplete message from UE thus wait ~50 subframes for tx usleep(50000); } rem_user_thread(rnti); } else { rrc_log->error("Received ReleaseComplete for unknown rnti=0x%x\n", rnti); } } void rrc::rem_user(uint16_t rnti) { pthread_mutex_lock(&user_mutex); if (users.count(rnti) == 1) { rrc_log->console("Disconnecting rnti=0x%x.\n", rnti); rrc_log->info("Disconnecting rnti=0x%x.\n", rnti); /* First remove MAC and GTPU to stop processing DL/UL traffic for this user */ mac->ue_rem(rnti); // MAC handles PHY gtpu->rem_user(rnti); // Now remove RLC and PDCP rlc->rem_user(rnti); pdcp->rem_user(rnti); // And deallocate resources from RRC users[rnti].sr_free(); users[rnti].cqi_free(); users.erase(rnti); rrc_log->info("Removed user rnti=0x%x\n", rnti); } else { rrc_log->error("Removing user rnti=0x%x (does not exist)\n", rnti); } pthread_mutex_unlock(&user_mutex); } void rrc::config_mac() { // Fill MAC scheduler configuration for SIBs sched_interface::cell_cfg_t sched_cfg; bzero(&sched_cfg, sizeof(sched_interface::cell_cfg_t)); for (uint32_t i=0;i<nof_si_messages;i++) { sched_cfg.sibs[i].len = sib_buffer[i].N_bytes; if (i == 0) { sched_cfg.sibs[i].period_rf = 8; // SIB1 is always 8 rf } else { sched_cfg.sibs[i].period_rf = liblte_rrc_si_periodicity_num[cfg.sibs[0].sib.sib1.sched_info[i-1].si_periodicity]; } } sched_cfg.si_window_ms = liblte_rrc_si_window_length_num[cfg.sibs[0].sib.sib1.si_window_length]; sched_cfg.prach_rar_window = liblte_rrc_ra_response_window_size_num[cfg.sibs[1].sib.sib2.rr_config_common_sib.rach_cnfg.ra_resp_win_size]; sched_cfg.prach_freq_offset = cfg.sibs[1].sib.sib2.rr_config_common_sib.prach_cnfg.prach_cnfg_info.prach_freq_offset; sched_cfg.maxharq_msg3tx = cfg.sibs[1].sib.sib2.rr_config_common_sib.rach_cnfg.max_harq_msg3_tx; sched_cfg.nrb_pucch = SRSLTE_MAX(cfg.sr_cfg.nof_prb, cfg.cqi_cfg.nof_prb); rrc_log->info("Allocating %d PRBs for PUCCH\n", sched_cfg.nrb_pucch); // Copy Cell configuration memcpy(&sched_cfg.cell, &cfg.cell, sizeof(srslte_cell_t)); // Configure MAC scheduler mac->cell_cfg(&sched_cfg); } uint32_t rrc::generate_sibs() { // nof_messages includes SIB2 by default, plus all configured SIBs uint32_t nof_messages = 1+cfg.sibs[0].sib.sib1.N_sched_info; LIBLTE_RRC_SCHEDULING_INFO_STRUCT *sched_info = cfg.sibs[0].sib.sib1.sched_info; // msg is array of SI messages, each SI message msg[i] may contain multiple SIBs // all SIBs in a SI message msg[i] share the same periodicity LIBLTE_RRC_BCCH_DLSCH_MSG_STRUCT *msg = (LIBLTE_RRC_BCCH_DLSCH_MSG_STRUCT*)calloc(nof_messages+1, sizeof(LIBLTE_RRC_BCCH_DLSCH_MSG_STRUCT)); // Copy SIB1 to first SI message msg[0].N_sibs = 1; memcpy(&msg[0].sibs[0], &cfg.sibs[0], sizeof(LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_STRUCT)); // Copy rest of SIBs for (uint32_t sched_info_elem = 0; sched_info_elem < nof_messages; sched_info_elem++) { uint32_t msg_index = sched_info_elem + 1; // first msg is SIB1, therefore start with second uint32_t current_msg_element_offset = 0; msg[msg_index].N_sibs = 0; // SIB2 always in second SI message if (msg_index == 1) { msg[msg_index].N_sibs++; memcpy(&msg[msg_index].sibs[0], &cfg.sibs[1], sizeof(LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_STRUCT)); current_msg_element_offset = 1; // make sure "other SIBs" do not overwrite this SIB2 // Save SIB2 memcpy(&sib2, &cfg.sibs[1].sib.sib2, sizeof(LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_2_STRUCT)); } else { current_msg_element_offset = 0; // no SIB2, no offset } // Add other SIBs to this message, if any for (uint32_t mapping = 0; mapping < sched_info[sched_info_elem].N_sib_mapping_info; mapping++) { msg[msg_index].N_sibs++; // current_msg_element_offset skips SIB2 if necessary memcpy(&msg[msg_index].sibs[mapping + current_msg_element_offset], &cfg.sibs[(int) sched_info[sched_info_elem].sib_mapping_info[mapping].sib_type+2], sizeof(LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_STRUCT)); } } // Pack payload for all messages for (uint32_t msg_index = 0; msg_index < nof_messages; msg_index++) { LIBLTE_BIT_MSG_STRUCT bitbuffer; liblte_rrc_pack_bcch_dlsch_msg(&msg[msg_index], &bitbuffer); srslte_bit_pack_vector(bitbuffer.msg, sib_buffer[msg_index].msg, bitbuffer.N_bits); sib_buffer[msg_index].N_bytes = (bitbuffer.N_bits-1)/8+1; } free(msg); return nof_messages; } void rrc::configure_mbsfn_sibs(LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_2_STRUCT *sib2, LIBLTE_RRC_SYS_INFO_BLOCK_TYPE_13_STRUCT *sib13) { // Temp assignment of MCCH, this will eventually come from a cfg file mcch.pmch_infolist_r9_size = 1; mcch.commonsf_allocpatternlist_r9_size = 1; mcch.commonsf_allocperiod_r9 = LIBLTE_RRC_MBSFN_COMMON_SF_ALLOC_PERIOD_R9_RF64; mcch.commonsf_allocpatternlist_r9[0].radio_fr_alloc_offset = 0; mcch.commonsf_allocpatternlist_r9[0].radio_fr_alloc_period = LIBLTE_RRC_RADIO_FRAME_ALLOCATION_PERIOD_N1; mcch.commonsf_allocpatternlist_r9[0].subfr_alloc = 32+31; mcch.commonsf_allocpatternlist_r9[0].subfr_alloc_num_frames = LIBLTE_RRC_SUBFRAME_ALLOCATION_NUM_FRAMES_ONE; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9_size = 1; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].logicalchannelid_r9 = 1; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].sessionid_r9 = 0; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].sessionid_r9_present = true; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].tmgi_r9.plmn_id_explicit = true; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].tmgi_r9.plmn_id_r9.mcc = 0; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].tmgi_r9.plmn_id_r9.mnc = 3; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].tmgi_r9.plmn_index_r9 = 0; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[0].tmgi_r9.serviceid_r9 = 0; if(mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9_size > 1) { mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].logicalchannelid_r9 = 2; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].sessionid_r9 = 1; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].sessionid_r9_present = true; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].tmgi_r9.plmn_id_explicit = true; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].tmgi_r9.plmn_id_r9.mcc = 0; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].tmgi_r9.plmn_id_r9.mnc = 3; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].tmgi_r9.plmn_index_r9 = 0; mcch.pmch_infolist_r9[0].mbms_sessioninfolist_r9[1].tmgi_r9.serviceid_r9 = 1; } mcch.pmch_infolist_r9[0].pmch_config_r9.datamcs_r9 = 10; mcch.pmch_infolist_r9[0].pmch_config_r9.mch_schedulingperiod_r9 = LIBLTE_RRC_MCH_SCHEDULING_PERIOD_R9_RF64; mcch.pmch_infolist_r9[0].pmch_config_r9.sf_alloc_end_r9 = 64*6; phy->configure_mbsfn(sib2,sib13,mcch); mac->write_mcch(sib2,sib13,&mcch); } void rrc::configure_security(uint16_t rnti, uint32_t lcid, uint8_t *k_rrc_enc, uint8_t *k_rrc_int, uint8_t *k_up_enc, uint8_t *k_up_int, srslte::CIPHERING_ALGORITHM_ID_ENUM cipher_algo, srslte::INTEGRITY_ALGORITHM_ID_ENUM integ_algo) { // TODO: add k_up_enc, k_up_int support to PDCP pdcp->config_security(rnti, lcid, k_rrc_enc, k_rrc_int, cipher_algo, integ_algo); } /******************************************************************************* RRC thread *******************************************************************************/ void rrc::run_thread() { rrc_pdu p; running = true; while(running) { p = rx_pdu_queue.wait_pop(); if (p.pdu) { rrc_log->info_hex(p.pdu->msg, p.pdu->N_bytes, "Rx %s PDU", rb_id_text[p.lcid]); } // Mutex these calls even though it's a private function if (users.count(p.rnti) == 1) { switch(p.lcid) { case RB_ID_SRB0: parse_ul_ccch(p.rnti, p.pdu); break; case RB_ID_SRB1: case RB_ID_SRB2: parse_ul_dcch(p.rnti, p.lcid, p.pdu); break; case LCID_REM_USER: rem_user(p.rnti); break; case LCID_REL_USER: process_release_complete(p.rnti); break; case LCID_RLF_USER: process_rl_failure(p.rnti); break; case LCID_ACT_USER: if (users.count(p.rnti) == 1) { users[p.rnti].set_activity(); } break; case LCID_EXIT: rrc_log->info("Exiting thread\n"); break; default: rrc_log->error("Rx PDU with invalid bearer id: %d", p.lcid); break; } } else { rrc_log->warning("Discarding PDU for removed rnti=0x%x\n", p.rnti); } } } /******************************************************************************* Activity monitor class *******************************************************************************/ rrc::activity_monitor::activity_monitor(rrc* parent_) { running = true; parent = parent_; } void rrc::activity_monitor::stop() { if (running) { running = false; thread_cancel(); wait_thread_finish(); } } void rrc::activity_monitor::run_thread() { while(running) { usleep(10000); pthread_mutex_lock(&parent->user_mutex); uint16_t rem_rnti = 0; for(std::map<uint16_t, ue>::iterator iter=parent->users.begin(); rem_rnti == 0 && iter!=parent->users.end(); ++iter) { if(iter->first != SRSLTE_MRNTI){ ue *u = (ue*) &iter->second; uint16_t rnti = (uint16_t) iter->first; if (parent->cnotifier && u->is_connected() && !u->connect_notified) { parent->cnotifier->user_connected(rnti); u->connect_notified = true; } if (u->is_timeout()) { parent->rrc_log->info("User rnti=0x%x timed out. Exists in s1ap=%s\n", rnti, parent->s1ap->user_exists(rnti)?"yes":"no"); rem_rnti = rnti; } } } if (rem_rnti) { if (parent->s1ap->user_exists(rem_rnti)) { parent->s1ap->user_release(rem_rnti, LIBLTE_S1AP_CAUSERADIONETWORK_USER_INACTIVITY); } else { if(rem_rnti != SRSLTE_MRNTI) parent->rem_user_thread(rem_rnti); } } pthread_mutex_unlock(&parent->user_mutex); } } /******************************************************************************* UE class Every function in UE class is called from a mutex environment thus does not need extra protection. *******************************************************************************/ rrc::ue::ue() { parent = NULL; set_activity(); has_tmsi = false; connect_notified = false; transaction_id = 0; sr_allocated = false; sr_sched_sf_idx = 0; sr_sched_prb_idx = 0; sr_N_pucch = 0; sr_I = 0; cqi_allocated = false; cqi_pucch = 0; cqi_idx = 0; cqi_sched_sf_idx = 0; cqi_sched_prb_idx = 0; rlf_cnt = 0; nas_pending = false; state = RRC_STATE_IDLE; pool = srslte::byte_buffer_pool::get_instance(); } rrc_state_t rrc::ue::get_state() { return state; } uint32_t rrc::ue::rl_failure() { rlf_cnt++; return rlf_cnt; } void rrc::ue::set_activity() { gettimeofday(&t_last_activity, NULL); if (parent) { if (parent->rrc_log) { parent->rrc_log->debug("Activity registered rnti=0x%x\n", rnti); } } } bool rrc::ue::is_connected() { return state == RRC_STATE_REGISTERED; } bool rrc::ue::is_idle() { return state == RRC_STATE_IDLE; } bool rrc::ue::is_timeout() { if (!parent) { return false; } struct timeval t[3]; uint32_t deadline_s = 0; uint32_t deadline_us = 0; const char *deadline_str = NULL; memcpy(&t[1], &t_last_activity, sizeof(struct timeval)); gettimeofday(&t[2], NULL); get_time_interval(t); switch(state) { case RRC_STATE_IDLE: deadline_s = 0; deadline_us = (parent->sib2.rr_config_common_sib.rach_cnfg.max_harq_msg3_tx + 1)* 8 * 1000; deadline_str = "RRCConnectionSetup"; break; case RRC_STATE_WAIT_FOR_CON_SETUP_COMPLETE: deadline_s = 1; deadline_us = 0; deadline_str = "RRCConnectionSetupComplete"; break; case RRC_STATE_RELEASE_REQUEST: deadline_s = 4; deadline_us = 0; deadline_str = "RRCReleaseRequest"; break; default: deadline_s = parent->cfg.inactivity_timeout_ms/1000; deadline_us = (parent->cfg.inactivity_timeout_ms%1000)*1000; deadline_str = "Activity"; break; } if (deadline_str) { int64_t deadline = deadline_s*1e6 + deadline_us; int64_t elapsed = t[0].tv_sec*1e6 + t[0].tv_usec; if (elapsed > deadline && elapsed > 0) { parent->rrc_log->warning("User rnti=0x%x expired %s deadline: %ld:%ld>%d:%d us\n", rnti, deadline_str, t[0].tv_sec, t[0].tv_usec, deadline_s, deadline_us); memcpy(&t_last_activity, &t[2], sizeof(struct timeval)); state = RRC_STATE_RELEASE_REQUEST; return true; } } return false; } void rrc::ue::parse_ul_dcch(uint32_t lcid, byte_buffer_t *pdu) { set_activity(); LIBLTE_RRC_UL_DCCH_MSG_STRUCT ul_dcch_msg; bzero(&ul_dcch_msg, sizeof(LIBLTE_RRC_UL_DCCH_MSG_STRUCT)); srslte_bit_unpack_vector(pdu->msg, parent->bit_buf.msg, pdu->N_bytes*8); parent->bit_buf.N_bits = pdu->N_bytes*8; liblte_rrc_unpack_ul_dcch_msg((LIBLTE_BIT_MSG_STRUCT*)&parent->bit_buf, &ul_dcch_msg); parent->rrc_log->info_hex(pdu->msg, pdu->N_bytes, "%s - Rx %s\n", rb_id_text[lcid], liblte_rrc_ul_dcch_msg_type_text[ul_dcch_msg.msg_type]); transaction_id = 0; pdu->reset(); switch(ul_dcch_msg.msg_type) { case LIBLTE_RRC_UL_DCCH_MSG_TYPE_RRC_CON_SETUP_COMPLETE: handle_rrc_con_setup_complete(&ul_dcch_msg.msg.rrc_con_setup_complete, pdu); break; case LIBLTE_RRC_UL_DCCH_MSG_TYPE_UL_INFO_TRANSFER: memcpy(pdu->msg, ul_dcch_msg.msg.ul_info_transfer.dedicated_info.msg, ul_dcch_msg.msg.ul_info_transfer.dedicated_info.N_bytes); pdu->N_bytes = ul_dcch_msg.msg.ul_info_transfer.dedicated_info.N_bytes; parent->s1ap->write_pdu(rnti, pdu); break; case LIBLTE_RRC_UL_DCCH_MSG_TYPE_RRC_CON_RECONFIG_COMPLETE: handle_rrc_reconf_complete(&ul_dcch_msg.msg.rrc_con_reconfig_complete, pdu); parent->rrc_log->console("User 0x%x connected\n", rnti); state = RRC_STATE_REGISTERED; break; case LIBLTE_RRC_UL_DCCH_MSG_TYPE_SECURITY_MODE_COMPLETE: handle_security_mode_complete(&ul_dcch_msg.msg.security_mode_complete); // Skipping send_ue_cap_enquiry() procedure for now // state = RRC_STATE_WAIT_FOR_UE_CAP_INFO; notify_s1ap_ue_ctxt_setup_complete(); send_connection_reconf(pdu); state = RRC_STATE_WAIT_FOR_CON_RECONF_COMPLETE; break; case LIBLTE_RRC_UL_DCCH_MSG_TYPE_SECURITY_MODE_FAILURE: handle_security_mode_failure(&ul_dcch_msg.msg.security_mode_failure); break; case LIBLTE_RRC_UL_DCCH_MSG_TYPE_UE_CAPABILITY_INFO: handle_ue_cap_info(&ul_dcch_msg.msg.ue_capability_info); send_connection_reconf(pdu); state = RRC_STATE_WAIT_FOR_CON_RECONF_COMPLETE; break; default: parent->rrc_log->error("Msg: %s not supported\n", liblte_rrc_ul_dcch_msg_type_text[ul_dcch_msg.msg_type]); break; } } void rrc::ue::handle_rrc_con_req(LIBLTE_RRC_CONNECTION_REQUEST_STRUCT *msg) { set_activity(); if(msg->ue_id_type == LIBLTE_RRC_CON_REQ_UE_ID_TYPE_S_TMSI) { mmec = msg->ue_id.s_tmsi.mmec; m_tmsi = msg->ue_id.s_tmsi.m_tmsi; has_tmsi = true; } establishment_cause = msg->cause; send_connection_setup(); state = RRC_STATE_WAIT_FOR_CON_SETUP_COMPLETE; } void rrc::ue::handle_rrc_con_reest_req(LIBLTE_RRC_CONNECTION_REESTABLISHMENT_REQUEST_STRUCT *msg) { //TODO: Check Short-MAC-I value parent->rrc_log->error("Not Supported: ConnectionReestablishment. \n"); } void rrc::ue::handle_rrc_con_setup_complete(LIBLTE_RRC_CONNECTION_SETUP_COMPLETE_STRUCT *msg, srslte::byte_buffer_t *pdu) { parent->rrc_log->info("RRCConnectionSetupComplete transaction ID: %d\n", msg->rrc_transaction_id); // TODO: msg->selected_plmn_id - used to select PLMN from SIB1 list // TODO: if(msg->registered_mme_present) - the indicated MME should be used from a pool memcpy(pdu->msg, msg->dedicated_info_nas.msg, msg->dedicated_info_nas.N_bytes); pdu->N_bytes = msg->dedicated_info_nas.N_bytes; // Acknowledge Dedicated Configuration parent->phy->set_conf_dedicated_ack(rnti, true); parent->mac->phy_config_enabled(rnti, true); if(has_tmsi) { parent->s1ap->initial_ue(rnti, (LIBLTE_S1AP_RRC_ESTABLISHMENT_CAUSE_ENUM)establishment_cause, pdu, m_tmsi, mmec); } else { parent->s1ap->initial_ue(rnti, (LIBLTE_S1AP_RRC_ESTABLISHMENT_CAUSE_ENUM)establishment_cause, pdu); } state = RRC_STATE_WAIT_FOR_CON_RECONF_COMPLETE; } void rrc::ue::handle_rrc_reconf_complete(LIBLTE_RRC_CONNECTION_RECONFIGURATION_COMPLETE_STRUCT *msg, srslte::byte_buffer_t *pdu) { parent->rrc_log->info("RRCReconfigurationComplete transaction ID: %d\n", msg->rrc_transaction_id); // Acknowledge Dedicated Configuration parent->phy->set_conf_dedicated_ack(rnti, true); parent->mac->phy_config_enabled(rnti, true); } void rrc::ue::handle_security_mode_complete(LIBLTE_RRC_SECURITY_MODE_COMPLETE_STRUCT *msg) { parent->rrc_log->info("SecurityModeComplete transaction ID: %d\n", msg->rrc_transaction_id); } void rrc::ue::handle_security_mode_failure(LIBLTE_RRC_SECURITY_MODE_FAILURE_STRUCT *msg) { parent->rrc_log->info("SecurityModeFailure transaction ID: %d\n", msg->rrc_transaction_id); } void rrc::ue::handle_ue_cap_info(LIBLTE_RRC_UE_CAPABILITY_INFORMATION_STRUCT *msg) { parent->rrc_log->info("UECapabilityInformation transaction ID: %d\n", msg->rrc_transaction_id); for(uint32_t i=0; i<msg->N_ue_caps; i++) { if(msg->ue_capability_rat[i].rat_type != LIBLTE_RRC_RAT_TYPE_EUTRA) { parent->rrc_log->warning("Not handling UE capability information for RAT type %s\n", liblte_rrc_rat_type_text[msg->ue_capability_rat[i].rat_type]); } else { memcpy(&eutra_capabilities, &msg->ue_capability_rat[0], sizeof(LIBLTE_RRC_UE_EUTRA_CAPABILITY_STRUCT)); parent->rrc_log->info("UE rnti: 0x%x category: %d\n", rnti, msg->ue_capability_rat[0].eutra_capability.ue_category); } } // TODO: Add liblte_rrc support for unpacking UE cap info and repacking into // inter-node UERadioAccessCapabilityInformation (36.331 v10.0.0 Section 10.2.2). // This is then passed to S1AP for transfer to EPC. // parent->s1ap->ue_capabilities(rnti, &eutra_capabilities); } void rrc::ue::set_bitrates(LIBLTE_S1AP_UEAGGREGATEMAXIMUMBITRATE_STRUCT *rates) { memcpy(&bitrates, rates, sizeof(LIBLTE_S1AP_UEAGGREGATEMAXIMUMBITRATE_STRUCT)); } void rrc::ue::set_security_capabilities(LIBLTE_S1AP_UESECURITYCAPABILITIES_STRUCT *caps) { memcpy(&security_capabilities, caps, sizeof(LIBLTE_S1AP_UESECURITYCAPABILITIES_STRUCT)); } void rrc::ue::set_security_key(uint8_t* key, uint32_t length) { memcpy(k_enb, key, length); parent->rrc_log->info_hex(k_enb, 32, "Key eNodeB (k_enb)"); // Select algos (TODO: use security capabilities and config preferences) cipher_algo = srslte::CIPHERING_ALGORITHM_ID_EEA0; integ_algo = srslte::INTEGRITY_ALGORITHM_ID_128_EIA1; // Generate K_rrc_enc and K_rrc_int security_generate_k_rrc( k_enb, cipher_algo, integ_algo, k_rrc_enc, k_rrc_int); // Generate K_up_enc and K_up_int security_generate_k_up( k_enb, cipher_algo, integ_algo, k_up_enc, k_up_int); parent->configure_security(rnti, RB_ID_SRB1, k_rrc_enc, k_rrc_int, k_up_enc, k_up_int, cipher_algo, integ_algo); } bool rrc::ue::setup_erabs(LIBLTE_S1AP_E_RABTOBESETUPLISTCTXTSUREQ_STRUCT *e) { for(uint32_t i=0; i<e->len; i++) { LIBLTE_S1AP_E_RABTOBESETUPITEMCTXTSUREQ_STRUCT *erab = &e->buffer[i]; if(erab->ext) { parent->rrc_log->warning("Not handling LIBLTE_S1AP_E_RABTOBESETUPITEMCTXTSUREQ_STRUCT extensions\n"); } if(erab->iE_Extensions_present) { parent->rrc_log->warning("Not handling LIBLTE_S1AP_E_RABTOBESETUPITEMCTXTSUREQ_STRUCT extensions\n"); } if(erab->transportLayerAddress.n_bits > 32) { parent->rrc_log->error("IPv6 addresses not currently supported\n"); return false; } uint32_t teid_out; uint8_to_uint32(erab->gTP_TEID.buffer, &teid_out); LIBLTE_S1AP_NAS_PDU_STRUCT *nas_pdu = erab->nAS_PDU_present ? &erab->nAS_PDU : NULL; setup_erab(erab->e_RAB_ID.E_RAB_ID, &erab->e_RABlevelQoSParameters, &erab->transportLayerAddress, teid_out, nas_pdu); } return true; } bool rrc::ue::setup_erabs(LIBLTE_S1AP_E_RABTOBESETUPLISTBEARERSUREQ_STRUCT *e) { for(uint32_t i=0; i<e->len; i++) { LIBLTE_S1AP_E_RABTOBESETUPITEMBEARERSUREQ_STRUCT *erab = &e->buffer[i]; if(erab->ext) { parent->rrc_log->warning("Not handling LIBLTE_S1AP_E_RABTOBESETUPITEMCTXTSUREQ_STRUCT extensions\n"); } if(erab->iE_Extensions_present) { parent->rrc_log->warning("Not handling LIBLTE_S1AP_E_RABTOBESETUPITEMCTXTSUREQ_STRUCT extensions\n"); } if(erab->transportLayerAddress.n_bits > 32) { parent->rrc_log->error("IPv6 addresses not currently supported\n"); return false; } uint32_t teid_out; uint8_to_uint32(erab->gTP_TEID.buffer, &teid_out); setup_erab(erab->e_RAB_ID.E_RAB_ID, &erab->e_RABlevelQoSParameters, &erab->transportLayerAddress, teid_out, &erab->nAS_PDU); } // Work in progress notify_s1ap_ue_erab_setup_response(e); send_connection_reconf_new_bearer(e); return true; } void rrc::ue::setup_erab(uint8_t id, LIBLTE_S1AP_E_RABLEVELQOSPARAMETERS_STRUCT *qos, LIBLTE_S1AP_TRANSPORTLAYERADDRESS_STRUCT *addr, uint32_t teid_out, LIBLTE_S1AP_NAS_PDU_STRUCT *nas_pdu) { erabs[id].id = id; memcpy(&erabs[id].qos_params, qos, sizeof(LIBLTE_S1AP_E_RABLEVELQOSPARAMETERS_STRUCT)); memcpy(&erabs[id].address, addr, sizeof(LIBLTE_S1AP_TRANSPORTLAYERADDRESS_STRUCT)); erabs[id].teid_out = teid_out; uint8_t* bit_ptr = addr->buffer; uint32_t addr_ = liblte_bits_2_value(&bit_ptr, addr->n_bits); uint8_t lcid = id - 2; // Map e.g. E-RAB 5 to LCID 3 (==DRB1) parent->gtpu->add_bearer(rnti, lcid, addr_, erabs[id].teid_out, &(erabs[id].teid_in)); if(nas_pdu) { nas_pending = true; memcpy(erab_info.buffer, nas_pdu->buffer, nas_pdu->n_octets); erab_info.N_bytes = nas_pdu->n_octets; parent->rrc_log->info_hex(erab_info.buffer, erab_info.N_bytes, "setup_erab nas_pdu -> erab_info rnti 0x%x", rnti); } else { nas_pending = false; } } bool rrc::ue::release_erabs() { typedef std::map<uint8_t, erab_t>::iterator it_t; for(it_t it=erabs.begin(); it!=erabs.end(); ++it) { // TODO: notify GTPU layer } erabs.clear(); return true; } void rrc::ue::notify_s1ap_ue_ctxt_setup_complete() { LIBLTE_S1AP_MESSAGE_INITIALCONTEXTSETUPRESPONSE_STRUCT res; res.ext = false; res.E_RABFailedToSetupListCtxtSURes_present = false; res.CriticalityDiagnostics_present = false; res.E_RABSetupListCtxtSURes.len = 0; res.E_RABFailedToSetupListCtxtSURes.len = 0; typedef std::map<uint8_t, erab_t>::iterator it_t; for(it_t it=erabs.begin(); it!=erabs.end(); ++it) { uint32_t j = res.E_RABSetupListCtxtSURes.len++; res.E_RABSetupListCtxtSURes.buffer[j].ext = false; res.E_RABSetupListCtxtSURes.buffer[j].iE_Extensions_present = false; res.E_RABSetupListCtxtSURes.buffer[j].e_RAB_ID.ext = false; res.E_RABSetupListCtxtSURes.buffer[j].e_RAB_ID.E_RAB_ID = it->second.id; uint32_to_uint8(it->second.teid_in, res.E_RABSetupListCtxtSURes.buffer[j].gTP_TEID.buffer); } parent->s1ap->ue_ctxt_setup_complete(rnti, &res); } void rrc::ue::notify_s1ap_ue_erab_setup_response(LIBLTE_S1AP_E_RABTOBESETUPLISTBEARERSUREQ_STRUCT *e) { LIBLTE_S1AP_MESSAGE_E_RABSETUPRESPONSE_STRUCT res; res.ext=false; res.E_RABSetupListBearerSURes.len = 0; res.E_RABFailedToSetupListBearerSURes.len = 0; res.CriticalityDiagnostics_present = false; res.E_RABFailedToSetupListBearerSURes_present = false; for(uint32_t i=0; i<e->len; i++) { res.E_RABSetupListBearerSURes_present = true; LIBLTE_S1AP_E_RABTOBESETUPITEMBEARERSUREQ_STRUCT *erab = &e->buffer[i]; uint8_t id = erab->e_RAB_ID.E_RAB_ID; uint32_t j = res.E_RABSetupListBearerSURes.len++; res.E_RABSetupListBearerSURes.buffer[j].ext = false; res.E_RABSetupListBearerSURes.buffer[j].iE_Extensions_present = false; res.E_RABSetupListBearerSURes.buffer[j].e_RAB_ID.ext = false; res.E_RABSetupListBearerSURes.buffer[j].e_RAB_ID.E_RAB_ID = id; uint32_to_uint8(erabs[id].teid_in, res.E_RABSetupListBearerSURes.buffer[j].gTP_TEID.buffer); } parent->s1ap->ue_erab_setup_complete(rnti, &res); } void rrc::ue::send_connection_reest_rej() { LIBLTE_RRC_DL_CCCH_MSG_STRUCT dl_ccch_msg; bzero(&dl_ccch_msg, sizeof(LIBLTE_RRC_DL_CCCH_MSG_STRUCT)); dl_ccch_msg.msg_type = LIBLTE_RRC_DL_CCCH_MSG_TYPE_RRC_CON_REEST_REJ; send_dl_ccch(&dl_ccch_msg); } void rrc::ue::send_connection_setup(bool is_setup) { LIBLTE_RRC_DL_CCCH_MSG_STRUCT dl_ccch_msg; bzero(&dl_ccch_msg, sizeof(LIBLTE_RRC_DL_CCCH_MSG_STRUCT)); LIBLTE_RRC_RR_CONFIG_DEDICATED_STRUCT* rr_cfg = NULL; if (is_setup) { dl_ccch_msg.msg_type = LIBLTE_RRC_DL_CCCH_MSG_TYPE_RRC_CON_SETUP; dl_ccch_msg.msg.rrc_con_setup.rrc_transaction_id = (transaction_id++)%4; rr_cfg = &dl_ccch_msg.msg.rrc_con_setup.rr_cnfg; } else { dl_ccch_msg.msg_type = LIBLTE_RRC_DL_CCCH_MSG_TYPE_RRC_CON_REEST; dl_ccch_msg.msg.rrc_con_reest.rrc_transaction_id = (transaction_id++)%4; rr_cfg = &dl_ccch_msg.msg.rrc_con_reest.rr_cnfg; } // Add SRB1 to cfg rr_cfg->srb_to_add_mod_list_size = 1; rr_cfg->srb_to_add_mod_list[0].srb_id = 1; rr_cfg->srb_to_add_mod_list[0].lc_cnfg_present = true; rr_cfg->srb_to_add_mod_list[0].lc_default_cnfg_present = true; rr_cfg->srb_to_add_mod_list[0].rlc_cnfg_present = true; rr_cfg->srb_to_add_mod_list[0].rlc_default_cnfg_present = true; // mac-MainConfig rr_cfg->mac_main_cnfg_present = true; LIBLTE_RRC_MAC_MAIN_CONFIG_STRUCT *mac_cfg = &rr_cfg->mac_main_cnfg.explicit_value; mac_cfg->ulsch_cnfg_present = true; memcpy(&mac_cfg->ulsch_cnfg, &parent->cfg.mac_cnfg.ulsch_cnfg, sizeof(LIBLTE_RRC_ULSCH_CONFIG_STRUCT)); mac_cfg->drx_cnfg_present = false; mac_cfg->phr_cnfg_present = true; memcpy(&mac_cfg->phr_cnfg, &parent->cfg.mac_cnfg.phr_cnfg, sizeof(LIBLTE_RRC_PHR_CONFIG_STRUCT)); mac_cfg->time_alignment_timer = parent->cfg.mac_cnfg.time_alignment_timer; // physicalConfigDedicated rr_cfg->phy_cnfg_ded_present = true; LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT *phy_cfg = &rr_cfg->phy_cnfg_ded; bzero(phy_cfg, sizeof(LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT)); phy_cfg->pusch_cnfg_ded_present = true; memcpy(&phy_cfg->pusch_cnfg_ded, &parent->cfg.pusch_cfg, sizeof(LIBLTE_RRC_PUSCH_CONFIG_DEDICATED_STRUCT)); phy_cfg->sched_request_cnfg_present = true; phy_cfg->sched_request_cnfg.setup_present = true; phy_cfg->sched_request_cnfg.dsr_trans_max = parent->cfg.sr_cfg.dsr_max; phy_cfg->antenna_info_default_value = true; phy_cfg->antenna_info_present = false; if (is_setup) { if (sr_allocate(parent->cfg.sr_cfg.period, &phy_cfg->sched_request_cnfg.sr_cnfg_idx, &phy_cfg->sched_request_cnfg.sr_pucch_resource_idx)) { parent->rrc_log->error("Allocating SR resources for rnti=%d\n", rnti); return; } } else { phy_cfg->sched_request_cnfg.sr_cnfg_idx = sr_I; phy_cfg->sched_request_cnfg.sr_pucch_resource_idx = sr_N_pucch; } // Power control phy_cfg->ul_pwr_ctrl_ded_present = true; phy_cfg->ul_pwr_ctrl_ded.p0_ue_pusch = 0; phy_cfg->ul_pwr_ctrl_ded.delta_mcs_en = LIBLTE_RRC_DELTA_MCS_ENABLED_EN0; phy_cfg->ul_pwr_ctrl_ded.accumulation_en = true; phy_cfg->ul_pwr_ctrl_ded.p0_ue_pucch = 0, phy_cfg->ul_pwr_ctrl_ded.p_srs_offset = 3; // PDSCH phy_cfg->pdsch_cnfg_ded_present = true; phy_cfg->pdsch_cnfg_ded = parent->cfg.pdsch_cfg; // PUCCH phy_cfg->pucch_cnfg_ded_present = true; phy_cfg->pucch_cnfg_ded.ack_nack_repetition_n1_pucch_an = 0; phy_cfg->cqi_report_cnfg_present = true; if(parent->cfg.cqi_cfg.mode == RRC_CFG_CQI_MODE_APERIODIC) { phy_cfg->cqi_report_cnfg.report_mode_aperiodic_present = true; phy_cfg->cqi_report_cnfg.report_mode_aperiodic = LIBLTE_RRC_CQI_REPORT_MODE_APERIODIC_RM30; } else { phy_cfg->cqi_report_cnfg.report_periodic_present = true; phy_cfg->cqi_report_cnfg.report_periodic_setup_present = true; phy_cfg->cqi_report_cnfg.report_periodic.format_ind_periodic = LIBLTE_RRC_CQI_FORMAT_INDICATOR_PERIODIC_WIDEBAND_CQI; phy_cfg->cqi_report_cnfg.report_periodic.simult_ack_nack_and_cqi = false; if (is_setup) { if (cqi_allocate(parent->cfg.cqi_cfg.period, &phy_cfg->cqi_report_cnfg.report_periodic.pmi_cnfg_idx, &phy_cfg->cqi_report_cnfg.report_periodic.pucch_resource_idx)) { parent->rrc_log->error("Allocating CQI resources for rnti=%d\n", rnti); return; } } else { phy_cfg->cqi_report_cnfg.report_periodic.pucch_resource_idx = cqi_pucch; phy_cfg->cqi_report_cnfg.report_periodic.pmi_cnfg_idx = cqi_idx; } } phy_cfg->cqi_report_cnfg.nom_pdsch_rs_epre_offset = 0; // Add SRB1 to Scheduler srsenb::sched_interface::ue_cfg_t sched_cfg; bzero(&sched_cfg, sizeof(srsenb::sched_interface::ue_cfg_t)); sched_cfg.maxharq_tx = liblte_rrc_max_harq_tx_num[parent->cfg.mac_cnfg.ulsch_cnfg.max_harq_tx]; sched_cfg.continuous_pusch = false; sched_cfg.aperiodic_cqi_period = parent->cfg.cqi_cfg.mode == RRC_CFG_CQI_MODE_APERIODIC?parent->cfg.cqi_cfg.period:0; sched_cfg.ue_bearers[0].direction = srsenb::sched_interface::ue_bearer_cfg_t::BOTH; sched_cfg.ue_bearers[1].direction = srsenb::sched_interface::ue_bearer_cfg_t::BOTH; sched_cfg.sr_I = sr_I; sched_cfg.sr_N_pucch = sr_N_pucch; sched_cfg.sr_enabled = true; sched_cfg.cqi_pucch = cqi_pucch; sched_cfg.cqi_idx = cqi_idx; sched_cfg.cqi_enabled = parent->cfg.cqi_cfg.mode == RRC_CFG_CQI_MODE_PERIODIC; sched_cfg.pucch_cfg.delta_pucch_shift = liblte_rrc_delta_pucch_shift_num[parent->sib2.rr_config_common_sib.pucch_cnfg.delta_pucch_shift%LIBLTE_RRC_DELTA_PUCCH_SHIFT_N_ITEMS]; sched_cfg.pucch_cfg.N_cs = parent->sib2.rr_config_common_sib.pucch_cnfg.n_cs_an; sched_cfg.pucch_cfg.n_rb_2 = parent->sib2.rr_config_common_sib.pucch_cnfg.n_rb_cqi; sched_cfg.pucch_cfg.n1_pucch_an = parent->sib2.rr_config_common_sib.pucch_cnfg.n1_pucch_an; // Configure MAC parent->mac->ue_cfg(rnti, &sched_cfg); // Configure SRB1 in RLC parent->rlc->add_bearer(rnti, 1); // Configure SRB1 in PDCP srslte::srslte_pdcp_config_t pdcp_cnfg; pdcp_cnfg.is_control = true; pdcp_cnfg.direction = SECURITY_DIRECTION_DOWNLINK; parent->pdcp->add_bearer(rnti, 1, pdcp_cnfg); // Configure PHY layer parent->phy->set_config_dedicated(rnti, phy_cfg); parent->phy->set_conf_dedicated_ack(rnti, false); parent->mac->set_dl_ant_info(rnti, &phy_cfg->antenna_info_explicit_value); parent->mac->phy_config_enabled(rnti, false); rr_cfg->drb_to_add_mod_list_size = 0; rr_cfg->drb_to_release_list_size = 0; rr_cfg->rlf_timers_and_constants_present = false; rr_cfg->sps_cnfg_present = false; send_dl_ccch(&dl_ccch_msg); } void rrc::ue::send_connection_reest() { send_connection_setup(false); } void rrc::ue::send_connection_release() { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_RRC_CON_RELEASE; dl_dcch_msg.msg.rrc_con_release.rrc_transaction_id = (transaction_id++)%4; dl_dcch_msg.msg.rrc_con_release.release_cause = LIBLTE_RRC_RELEASE_CAUSE_OTHER; send_dl_dcch(&dl_dcch_msg); } int rrc::ue::get_drbid_config(LIBLTE_RRC_DRB_TO_ADD_MOD_STRUCT *drb, int drb_id) { uint32_t lc_id = drb_id + 2; uint32_t erab_id = lc_id + 2; uint32_t qci = erabs[erab_id].qos_params.qCI.QCI; if (qci >= MAX_NOF_QCI) { parent->rrc_log->error("Invalid QCI=%d for ERAB_id=%d, DRB_id=%d\n", qci, erab_id, drb_id); return -1; } if (!parent->cfg.qci_cfg[qci].configured) { parent->rrc_log->error("QCI=%d not configured\n", qci); return -1; } // Add DRB1 to the message drb->drb_id = drb_id; drb->lc_id = lc_id; drb->lc_id_present = true; drb->eps_bearer_id = erab_id; drb->eps_bearer_id_present = true; drb->lc_cnfg_present = true; drb->lc_cnfg.ul_specific_params_present = true; drb->lc_cnfg.log_chan_sr_mask_present = false; drb->lc_cnfg.ul_specific_params.log_chan_group_present = true; memcpy(&drb->lc_cnfg.ul_specific_params, &parent->cfg.qci_cfg[qci].lc_cfg, sizeof(LIBLTE_RRC_UL_SPECIFIC_PARAMETERS_STRUCT)); drb->pdcp_cnfg_present = true; memcpy(&drb->pdcp_cnfg, &parent->cfg.qci_cfg[qci].pdcp_cfg, sizeof(LIBLTE_RRC_PDCP_CONFIG_STRUCT)); drb->rlc_cnfg_present = true; memcpy(&drb->rlc_cnfg, &parent->cfg.qci_cfg[qci].rlc_cfg, sizeof(LIBLTE_RRC_RLC_CONFIG_STRUCT)); return 0; } void rrc::ue::send_connection_reconf_upd(srslte::byte_buffer_t *pdu) { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; bzero(&dl_dcch_msg, sizeof(LIBLTE_RRC_DL_DCCH_MSG_STRUCT)); dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_RRC_CON_RECONFIG; dl_dcch_msg.msg.rrc_con_reconfig.rrc_transaction_id = (transaction_id++)%4; LIBLTE_RRC_RR_CONFIG_DEDICATED_STRUCT* rr_cfg = &dl_dcch_msg.msg.rrc_con_reconfig.rr_cnfg_ded; dl_dcch_msg.msg.rrc_con_reconfig.rr_cnfg_ded_present = true; rr_cfg->phy_cnfg_ded_present = true; LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT *phy_cfg = &rr_cfg->phy_cnfg_ded; bzero(phy_cfg, sizeof(LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT)); phy_cfg->sched_request_cnfg_present = true; phy_cfg->sched_request_cnfg.setup_present = true; phy_cfg->sched_request_cnfg.dsr_trans_max = parent->cfg.sr_cfg.dsr_max; phy_cfg->cqi_report_cnfg_present = true; if (cqi_allocated) { cqi_get(&phy_cfg->cqi_report_cnfg.report_periodic.pmi_cnfg_idx, &phy_cfg->cqi_report_cnfg.report_periodic.pucch_resource_idx); phy_cfg->cqi_report_cnfg.report_periodic_present = true; phy_cfg->cqi_report_cnfg.report_periodic_setup_present = true; phy_cfg->cqi_report_cnfg.report_periodic.format_ind_periodic = LIBLTE_RRC_CQI_FORMAT_INDICATOR_PERIODIC_WIDEBAND_CQI; phy_cfg->cqi_report_cnfg.report_periodic.simult_ack_nack_and_cqi = parent->cfg.cqi_cfg.simultaneousAckCQI; if (parent->cfg.antenna_info.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_3 || parent->cfg.antenna_info.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_4) { phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx_present = true; phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx = 483; /* TODO: HARDCODED! Add to UL scheduler */ } else { phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx_present = false; } } else { phy_cfg->cqi_report_cnfg.report_mode_aperiodic_present = true; if (phy_cfg->antenna_info_present && parent->cfg.antenna_info.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_4) { phy_cfg->cqi_report_cnfg.report_mode_aperiodic = LIBLTE_RRC_CQI_REPORT_MODE_APERIODIC_RM31; } else { phy_cfg->cqi_report_cnfg.report_mode_aperiodic = LIBLTE_RRC_CQI_REPORT_MODE_APERIODIC_RM30; } } parent->phy->set_config_dedicated(rnti, phy_cfg); sr_get(&phy_cfg->sched_request_cnfg.sr_cnfg_idx, &phy_cfg->sched_request_cnfg.sr_pucch_resource_idx); pdu->reset(); send_dl_dcch(&dl_dcch_msg, pdu); state = RRC_STATE_WAIT_FOR_CON_RECONF_COMPLETE; } void rrc::ue::send_connection_reconf(srslte::byte_buffer_t *pdu) { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_RRC_CON_RECONFIG; dl_dcch_msg.msg.rrc_con_reconfig.rrc_transaction_id = (transaction_id++)%4; LIBLTE_RRC_CONNECTION_RECONFIGURATION_STRUCT* conn_reconf = &dl_dcch_msg.msg.rrc_con_reconfig; conn_reconf->rr_cnfg_ded_present = true; conn_reconf->rr_cnfg_ded.mac_main_cnfg_present = false; conn_reconf->rr_cnfg_ded.phy_cnfg_ded_present = false; conn_reconf->rr_cnfg_ded.rlf_timers_and_constants_present = false; conn_reconf->rr_cnfg_ded.sps_cnfg_present = false; conn_reconf->rr_cnfg_ded.drb_to_release_list_size = 0; conn_reconf->meas_cnfg_present = false; conn_reconf->mob_ctrl_info_present = false; conn_reconf->sec_cnfg_ho_present = false; LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT *phy_cfg = &conn_reconf->rr_cnfg_ded.phy_cnfg_ded; bzero(phy_cfg, sizeof(LIBLTE_RRC_PHYSICAL_CONFIG_DEDICATED_STRUCT)); conn_reconf->rr_cnfg_ded.phy_cnfg_ded_present = true; if (parent->cfg.antenna_info.tx_mode > LIBLTE_RRC_TRANSMISSION_MODE_1) { memcpy(&phy_cfg->antenna_info_explicit_value, &parent->cfg.antenna_info, sizeof(LIBLTE_RRC_ANTENNA_INFO_DEDICATED_STRUCT)); phy_cfg->antenna_info_present = true; phy_cfg->antenna_info_default_value = false; } // Configure PHY layer phy_cfg->cqi_report_cnfg_present = true; if(parent->cfg.cqi_cfg.mode == RRC_CFG_CQI_MODE_APERIODIC) { phy_cfg->cqi_report_cnfg.report_mode_aperiodic_present = true; if (phy_cfg->antenna_info_present && phy_cfg->antenna_info_explicit_value.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_4) { phy_cfg->cqi_report_cnfg.report_mode_aperiodic = LIBLTE_RRC_CQI_REPORT_MODE_APERIODIC_RM31; } else { phy_cfg->cqi_report_cnfg.report_mode_aperiodic = LIBLTE_RRC_CQI_REPORT_MODE_APERIODIC_RM30; } } else { cqi_get(&phy_cfg->cqi_report_cnfg.report_periodic.pmi_cnfg_idx, &phy_cfg->cqi_report_cnfg.report_periodic.pucch_resource_idx); phy_cfg->cqi_report_cnfg.report_periodic_present = true; phy_cfg->cqi_report_cnfg.report_periodic_setup_present = true; phy_cfg->cqi_report_cnfg.report_periodic.format_ind_periodic = LIBLTE_RRC_CQI_FORMAT_INDICATOR_PERIODIC_WIDEBAND_CQI; phy_cfg->cqi_report_cnfg.report_periodic.simult_ack_nack_and_cqi = parent->cfg.cqi_cfg.simultaneousAckCQI; if (phy_cfg->antenna_info_present && (phy_cfg->antenna_info_explicit_value.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_3 || phy_cfg->antenna_info_explicit_value.tx_mode == LIBLTE_RRC_TRANSMISSION_MODE_4)) { phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx_present = true; phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx = 483; } else { phy_cfg->cqi_report_cnfg.report_periodic.ri_cnfg_idx_present = false; } } phy_cfg->cqi_report_cnfg.nom_pdsch_rs_epre_offset = 0; parent->phy->set_config_dedicated(rnti, phy_cfg); parent->phy->set_conf_dedicated_ack(rnti, false); parent->mac->set_dl_ant_info(rnti, &phy_cfg->antenna_info_explicit_value); parent->mac->phy_config_enabled(rnti, false); // Add SRB2 to the message conn_reconf->rr_cnfg_ded.srb_to_add_mod_list_size = 1; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list[0].srb_id = 2; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list[0].lc_cnfg_present = true; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list[0].lc_default_cnfg_present = true; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list[0].rlc_cnfg_present = true; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list[0].rlc_default_cnfg_present = true; // Get DRB1 configuration if (get_drbid_config(&conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[0], 1)) { parent->rrc_log->error("Getting DRB1 configuration\n"); printf("The QCI %d for DRB1 is invalid or not configured.\n", erabs[5].qos_params.qCI.QCI); return; } else { conn_reconf->rr_cnfg_ded.drb_to_add_mod_list_size = 1; } // Add SRB2 and DRB1 to the scheduler srsenb::sched_interface::ue_bearer_cfg_t bearer_cfg; bearer_cfg.direction = srsenb::sched_interface::ue_bearer_cfg_t::BOTH; bearer_cfg.group = 0; parent->mac->bearer_ue_cfg(rnti, 2, &bearer_cfg); bearer_cfg.group = conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[0].lc_cnfg.ul_specific_params.log_chan_group; parent->mac->bearer_ue_cfg(rnti, 3, &bearer_cfg); // Configure SRB2 in RLC and PDCP parent->rlc->add_bearer(rnti, 2); // Configure SRB2 in PDCP srslte::srslte_pdcp_config_t pdcp_cnfg; pdcp_cnfg.direction = SECURITY_DIRECTION_DOWNLINK; pdcp_cnfg.is_control = true; pdcp_cnfg.is_data = false; parent->pdcp->add_bearer(rnti, 2, pdcp_cnfg); // Configure DRB1 in RLC parent->rlc->add_bearer(rnti, 3, &conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[0].rlc_cnfg); // Configure DRB1 in PDCP pdcp_cnfg.is_control = false; pdcp_cnfg.is_data = true; if (conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[0].pdcp_cnfg.rlc_um_pdcp_sn_size_present) { if(LIBLTE_RRC_PDCP_SN_SIZE_7_BITS == conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[0].pdcp_cnfg.rlc_um_pdcp_sn_size) { pdcp_cnfg.sn_len = 7; } } parent->pdcp->add_bearer(rnti, 3, pdcp_cnfg); // DRB1 has already been configured in GTPU through bearer setup // Add NAS Attach accept if(nas_pending){ parent->rrc_log->debug("Adding NAS message to connection reconfiguration\n"); conn_reconf->N_ded_info_nas = 1; parent->rrc_log->info_hex(erab_info.buffer, erab_info.N_bytes, "connection_reconf erab_info -> nas_info rnti 0x%x\n", rnti); conn_reconf->ded_info_nas_list[0].N_bytes = erab_info.N_bytes; memcpy(conn_reconf->ded_info_nas_list[0].msg, erab_info.buffer, erab_info.N_bytes); } else { parent->rrc_log->debug("Not adding NAS message to connection reconfiguration\n"); conn_reconf->N_ded_info_nas = 0; } // Reuse same PDU pdu->reset(); send_dl_dcch(&dl_dcch_msg, pdu); state = RRC_STATE_WAIT_FOR_CON_RECONF_COMPLETE; } void rrc::ue::send_connection_reconf_new_bearer(LIBLTE_S1AP_E_RABTOBESETUPLISTBEARERSUREQ_STRUCT *e) { srslte::byte_buffer_t *pdu = pool_allocate; LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_RRC_CON_RECONFIG; dl_dcch_msg.msg.rrc_con_reconfig.rrc_transaction_id = (transaction_id++)%4; LIBLTE_RRC_CONNECTION_RECONFIGURATION_STRUCT* conn_reconf = &dl_dcch_msg.msg.rrc_con_reconfig; conn_reconf->rr_cnfg_ded_present = true; conn_reconf->rr_cnfg_ded.mac_main_cnfg_present = false; conn_reconf->rr_cnfg_ded.phy_cnfg_ded_present = false; conn_reconf->rr_cnfg_ded.rlf_timers_and_constants_present = false; conn_reconf->rr_cnfg_ded.sps_cnfg_present = false; conn_reconf->rr_cnfg_ded.drb_to_release_list_size = 0; conn_reconf->rr_cnfg_ded.srb_to_add_mod_list_size = 0; conn_reconf->rr_cnfg_ded.drb_to_add_mod_list_size = 0; conn_reconf->meas_cnfg_present = false; conn_reconf->mob_ctrl_info_present = false; conn_reconf->sec_cnfg_ho_present = false; for(uint32_t i=0; i<e->len; i++) { LIBLTE_S1AP_E_RABTOBESETUPITEMBEARERSUREQ_STRUCT *erab = &e->buffer[i]; uint8_t id = erab->e_RAB_ID.E_RAB_ID; uint8_t lcid = id - 2; // Map e.g. E-RAB 5 to LCID 3 (==DRB1) // Get DRB configuration if (get_drbid_config(&conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[i], lcid-2)) { parent->rrc_log->error("Getting DRB configuration\n"); printf("ERROR: The QCI %d is invalid or not configured.\n", erabs[lcid+4].qos_params.qCI.QCI); return; } else { conn_reconf->rr_cnfg_ded.drb_to_add_mod_list_size++; } // Add DRB to the scheduler srsenb::sched_interface::ue_bearer_cfg_t bearer_cfg; bearer_cfg.direction = srsenb::sched_interface::ue_bearer_cfg_t::BOTH; parent->mac->bearer_ue_cfg(rnti, lcid, &bearer_cfg); // Configure DRB in RLC parent->rlc->add_bearer(rnti, lcid, &conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[i].rlc_cnfg); // Configure DRB in PDCP parent->pdcp->add_bearer(rnti, lcid, &conn_reconf->rr_cnfg_ded.drb_to_add_mod_list[i].pdcp_cnfg); // DRB has already been configured in GTPU through bearer setup // Add NAS message parent->rrc_log->info_hex(erab_info.buffer, erab_info.N_bytes, "reconf_new_bearer erab_info -> nas_info rnti 0x%x\n", rnti); conn_reconf->ded_info_nas_list[conn_reconf->N_ded_info_nas].N_bytes = erab_info.N_bytes; memcpy(conn_reconf->ded_info_nas_list[conn_reconf->N_ded_info_nas].msg, erab_info.buffer, erab_info.N_bytes); conn_reconf->N_ded_info_nas++; } send_dl_dcch(&dl_dcch_msg, pdu); } void rrc::ue::send_security_mode_command() { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_SECURITY_MODE_COMMAND; LIBLTE_RRC_SECURITY_MODE_COMMAND_STRUCT* comm = &dl_dcch_msg.msg.security_mode_cmd; comm->rrc_transaction_id = (transaction_id++)%4; // TODO: select these based on UE capabilities and preference order comm->sec_algs.cipher_alg = (LIBLTE_RRC_CIPHERING_ALGORITHM_ENUM)cipher_algo; comm->sec_algs.int_alg = (LIBLTE_RRC_INTEGRITY_PROT_ALGORITHM_ENUM)integ_algo; send_dl_dcch(&dl_dcch_msg); } void rrc::ue::send_ue_cap_enquiry() { LIBLTE_RRC_DL_DCCH_MSG_STRUCT dl_dcch_msg; dl_dcch_msg.msg_type = LIBLTE_RRC_DL_DCCH_MSG_TYPE_UE_CAPABILITY_ENQUIRY; LIBLTE_RRC_UE_CAPABILITY_ENQUIRY_STRUCT* enq = &dl_dcch_msg.msg.ue_cap_enquiry; enq->rrc_transaction_id = (transaction_id++)%4; enq->N_ue_cap_reqs = 1; enq->ue_capability_request[0] = LIBLTE_RRC_RAT_TYPE_EUTRA; send_dl_dcch(&dl_dcch_msg); } /********************** HELPERS ***************************/ void rrc::ue::send_dl_ccch(LIBLTE_RRC_DL_CCCH_MSG_STRUCT *dl_ccch_msg) { // Allocate a new PDU buffer, pack the message and send to PDCP byte_buffer_t *pdu = pool_allocate; if (pdu) { liblte_rrc_pack_dl_ccch_msg(dl_ccch_msg, (LIBLTE_BIT_MSG_STRUCT*) &parent->bit_buf); srslte_bit_pack_vector(parent->bit_buf.msg, pdu->msg, parent->bit_buf.N_bits); pdu->N_bytes = 1+(parent->bit_buf.N_bits-1)/8; parent->rrc_log->info_hex(pdu->msg, pdu->N_bytes, "SRB0 - rnti=0x%x, Sending: %s\n", rnti, liblte_rrc_dl_ccch_msg_type_text[dl_ccch_msg->msg_type]); parent->pdcp->write_sdu(rnti, RB_ID_SRB0, pdu); } else { parent->rrc_log->error("Allocating pdu\n"); } } void rrc::ue::send_dl_dcch(LIBLTE_RRC_DL_DCCH_MSG_STRUCT *dl_dcch_msg, byte_buffer_t *pdu) { if (!pdu) { pdu = pool_allocate; } if (pdu) { liblte_rrc_pack_dl_dcch_msg(dl_dcch_msg, (LIBLTE_BIT_MSG_STRUCT*) &parent->bit_buf); srslte_bit_pack_vector(parent->bit_buf.msg, pdu->msg, parent->bit_buf.N_bits); pdu->N_bytes = 1+(parent->bit_buf.N_bits-1)/8; parent->rrc_log->info_hex(pdu->msg, pdu->N_bytes, "SRB1 - rnti=0x%x, Sending: %s\n", rnti, liblte_rrc_dl_dcch_msg_type_text[dl_dcch_msg->msg_type]); parent->pdcp->write_sdu(rnti, RB_ID_SRB1, pdu); } else { parent->rrc_log->error("Allocating pdu\n"); } } int rrc::ue::sr_free() { if (sr_allocated) { if (parent->sr_sched.nof_users[sr_sched_prb_idx][sr_sched_sf_idx] > 0) { parent->sr_sched.nof_users[sr_sched_prb_idx][sr_sched_sf_idx]--; } else { parent->rrc_log->warning("Removing SR resources: no users in time-frequency slot (%d, %d)\n", sr_sched_prb_idx, sr_sched_sf_idx); } parent->rrc_log->info("Deallocated SR resources for time-frequency slot (%d, %d)\n", sr_sched_prb_idx, sr_sched_sf_idx); } return 0; } void rrc::ue::sr_get(uint32_t *I_sr, uint32_t *N_pucch_sr) { *I_sr = sr_I; *N_pucch_sr = sr_N_pucch; } int rrc::ue::sr_allocate(uint32_t period, uint32_t *I_sr, uint32_t *N_pucch_sr) { uint32_t c = SRSLTE_CP_ISNORM(parent->cfg.cell.cp)?3:2; uint32_t delta_pucch_shift = liblte_rrc_delta_pucch_shift_num[parent->sib2.rr_config_common_sib.pucch_cnfg.delta_pucch_shift]; uint32_t max_users = 12*c/delta_pucch_shift; // Find freq-time resources with least number of users int i_min=0, j_min=0; uint32_t min_users = 1e6; for (uint32_t i=0;i<parent->cfg.sr_cfg.nof_prb;i++) { for (uint32_t j=0;j<parent->cfg.sr_cfg.nof_subframes;j++) { if (parent->sr_sched.nof_users[i][j] < min_users) { i_min = i; j_min = j; min_users = parent->sr_sched.nof_users[i][j]; } } } if (parent->sr_sched.nof_users[i_min][j_min] > max_users) { parent->rrc_log->error("Not enough PUCCH resources to allocate Scheduling Request\n"); return -1; } // Compute I_sr if (period != 5 && period != 10 && period != 20 && period != 40 && period != 80) { parent->rrc_log->error("Invalid SchedulingRequest period %d ms\n", period); return -1; } if (parent->cfg.sr_cfg.sf_mapping[j_min] < period) { *I_sr = period - 5 + parent->cfg.sr_cfg.sf_mapping[j_min]; } else { parent->rrc_log->error("Allocating SR: invalid sf_idx=%d for period=%d\n", parent->cfg.sr_cfg.sf_mapping[j_min], period); return -1; } // Compute N_pucch_sr *N_pucch_sr = i_min*max_users + parent->sr_sched.nof_users[i_min][j_min]; if (parent->sib2.rr_config_common_sib.pucch_cnfg.n_cs_an) { *N_pucch_sr += parent->sib2.rr_config_common_sib.pucch_cnfg.n_cs_an; } // Allocate user parent->sr_sched.nof_users[i_min][j_min]++; sr_sched_prb_idx = i_min; sr_sched_sf_idx = j_min; sr_allocated = true; sr_I = *I_sr; sr_N_pucch = *N_pucch_sr; parent->rrc_log->info("Allocated SR resources for time-frequency slot (%d, %d), N_pucch_sr=%d, I_sr=%d\n", sr_sched_prb_idx, sr_sched_sf_idx, *N_pucch_sr, *I_sr); return 0; } int rrc::ue::cqi_free() { if (cqi_allocated) { if (parent->cqi_sched.nof_users[cqi_sched_prb_idx][cqi_sched_sf_idx] > 0) { parent->cqi_sched.nof_users[cqi_sched_prb_idx][cqi_sched_sf_idx]--; } else { parent->rrc_log->warning("Removing CQI resources: no users in time-frequency slot (%d, %d)\n", cqi_sched_prb_idx, cqi_sched_sf_idx); } parent->rrc_log->info("Deallocated CQI resources for time-frequency slot (%d, %d)\n", cqi_sched_prb_idx, cqi_sched_sf_idx); } return 0; } void rrc::ue::cqi_get(uint32_t *pmi_idx, uint32_t *n_pucch) { *pmi_idx = cqi_idx; *n_pucch = cqi_pucch; } int rrc::ue::cqi_allocate(uint32_t period, uint32_t *pmi_idx, uint32_t *n_pucch) { uint32_t c = SRSLTE_CP_ISNORM(parent->cfg.cell.cp)?3:2; uint32_t delta_pucch_shift = liblte_rrc_delta_pucch_shift_num[parent->sib2.rr_config_common_sib.pucch_cnfg.delta_pucch_shift]; uint32_t max_users = 12*c/delta_pucch_shift; // Find freq-time resources with least number of users int i_min=0, j_min=0; uint32_t min_users = 1e6; for (uint32_t i=0;i<parent->cfg.cqi_cfg.nof_prb;i++) { for (uint32_t j=0;j<parent->cfg.cqi_cfg.nof_subframes;j++) { if (parent->cqi_sched.nof_users[i][j] < min_users) { i_min = i; j_min = j; min_users = parent->cqi_sched.nof_users[i][j]; } } } if (parent->cqi_sched.nof_users[i_min][j_min] > max_users) { parent->rrc_log->error("Not enough PUCCH resources to allocate Scheduling Request\n"); return -1; } // Compute I_sr if (period != 2 && period != 5 && period != 10 && period != 20 && period != 40 && period != 80 && period != 160 && period != 32 && period != 64 && period != 128) { parent->rrc_log->error("Invalid CQI Report period %d ms\n", period); return -1; } if (parent->cfg.cqi_cfg.sf_mapping[j_min] < period) { if (period != 32 && period != 64 && period != 128) { if (period > 2) { *pmi_idx = period - 3 + parent->cfg.cqi_cfg.sf_mapping[j_min]; } else { *pmi_idx = parent->cfg.cqi_cfg.sf_mapping[j_min]; } } else { if (period == 32) { *pmi_idx = 318 + parent->cfg.cqi_cfg.sf_mapping[j_min]; } else if (period == 64) { *pmi_idx = 350 + parent->cfg.cqi_cfg.sf_mapping[j_min]; } else if (period == 128) { *pmi_idx = 414 + parent->cfg.cqi_cfg.sf_mapping[j_min]; } } } else { parent->rrc_log->error("Allocating SR: invalid sf_idx=%d for period=%d\n", parent->cfg.cqi_cfg.sf_mapping[j_min], period); return -1; } // Compute n_pucch_2 *n_pucch = i_min*max_users + parent->cqi_sched.nof_users[i_min][j_min]; if (parent->sib2.rr_config_common_sib.pucch_cnfg.n_cs_an) { *n_pucch += parent->sib2.rr_config_common_sib.pucch_cnfg.n_cs_an; } // Allocate user parent->cqi_sched.nof_users[i_min][j_min]++; cqi_sched_prb_idx = i_min; cqi_sched_sf_idx = j_min; cqi_allocated = true; cqi_idx = *pmi_idx; cqi_pucch = *n_pucch; parent->rrc_log->info("Allocated CQI resources for time-frequency slot (%d, %d), n_pucch_2=%d, pmi_cfg_idx=%d\n", cqi_sched_prb_idx, cqi_sched_sf_idx, *n_pucch, *pmi_idx); return 0; } }
36.56913
177
0.696711
[ "vector" ]
eaf48a0a00a2f84fa62e46b7a19618087cd030cd
6,708
cc
C++
core/scene_element.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2017-07-27T15:08:19.000Z
2017-07-27T15:08:19.000Z
core/scene_element.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
null
null
null
core/scene_element.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2020-10-01T08:46:10.000Z
2020-10-01T08:46:10.000Z
// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. /// @author Glazachev Vladimir <glazachev.vladimir@gmail.com> /// @author Mlodik Mikhail <mlodik_m@mail.ru> #include "core/scene_element.h" #include <cmath> #include <cstddef> #include <vector> #include "core/rotation_matrix.h" #include "core/mesh_merge_utils.h" namespace core { SceneElement::SceneElement() { SetStandardTransform(); } SceneElement::SceneElement(Mesh *mesh) { SetStandardTransform(); mesh_ = mesh; } void SceneElement::SetMesh(Mesh *mesh) { mesh_ = mesh; } void SceneElement::AddVertex(const cv::Point3d &point) { mesh_->AddVertex(point); } void SceneElement::AddFace(const Triangle &face) { mesh_->AddFace(face); } void SceneElement::SetPos(double x, double y, double z) { pos_x_ = x; pos_y_ = y; pos_z_ = z; } void SceneElement::SetScale(double scale_x, double scale_y, double scale_z) { scale_x_ = scale_x; scale_y_ = scale_y; scale_z_ = scale_z; } std::vector<cv::Point3d> SceneElement::Vertexes() const { return mesh_->vertexes(); } std::vector<Triangle> SceneElement::Faces() const { return mesh_->faces(); } cv::Point3d SceneElement::FindMin() const { double min_x = mesh_->vertexes()[0].x; double min_y = mesh_->vertexes()[0].y; double min_z = mesh_->vertexes()[0].z; for (int i = 0; i < mesh_->vertexes().size(); i++) { if (mesh_->vertexes()[i].x < min_x) min_x = mesh_->vertexes()[i].x; if (mesh_->vertexes()[i].y < min_y) min_y = mesh_->vertexes()[i].y; if (mesh_->vertexes()[i].z < min_z) min_z = mesh_->vertexes()[i].z; } cv::Point3d min_point(min_x, min_y, min_z); return min_point; } cv::Point3d SceneElement::FindMax() const { double max_x = mesh_->vertexes()[0].x; double max_y = mesh_->vertexes()[0].y; double max_z = mesh_->vertexes()[0].z; for (int i = 0; i < mesh_->vertexes().size(); i++) { if (mesh_->vertexes()[i].x > max_x) max_x = mesh_->vertexes()[i].x; if (mesh_->vertexes()[i].y > max_y) max_y = mesh_->vertexes()[i].y; if (mesh_->vertexes()[i].z > max_z) max_z = mesh_->vertexes()[i].z; } cv::Point3d max_point(max_x, max_y, max_z); return max_point; } cv::Point3d SceneElement::FindMeanPoint() const { cv::Point3d new_point( (this->FindMin().x + this->FindMax().x) / 2, (this->FindMin().y + this->FindMax().y) / 2, (this->FindMin().z + this->FindMax().z) / 2); return new_point; } void SceneElement::Transform( cv::Point3d* point, const cv::Point3d& mean_point) const { cv::Point3d new_point(point->x + pos_x_, point->y + pos_y_, point->z + pos_z_); new_point.x = (new_point.x - mean_point.x) * scale_x_ + mean_point.x; new_point.y = (new_point.y - mean_point.y) * scale_y_ + mean_point.y; new_point.z = (new_point.z - mean_point.z) * scale_z_ + mean_point.z; cv::Point3d rotated_point; rotated_point.x = new_point.x - rotation_center_x_; rotated_point.y = new_point.y - rotation_center_y_; rotated_point.z = new_point.z - rotation_center_z_; RotationMatrix rot_(angle_, axis_x_, axis_y_, axis_z_); rotated_point = rot_.Rotate(rotated_point); new_point.x = rotated_point.x + rotation_center_x_; new_point.y = rotated_point.y + rotation_center_y_; new_point.z = rotated_point.z + rotation_center_z_; *point = new_point; } void SceneElement::Transform(SceneElement* scene) const { cv::Point3d tmp; cv::Point3d mean_point = this->FindMeanPoint(); for (int i = 0; i < scene->Vertexes().size(); i++) { tmp = scene->Vertexes().at(i); scene->Transform(&tmp, mean_point); scene->ChangeVertex(tmp, i); } } void SceneElement::SetStandardTransform() { pos_x_ = 0; pos_y_ = 0; pos_z_ = 0; scale_x_ = 1; scale_y_ = 1; scale_z_ = 1; axis_x_ = 1; axis_y_ = 0; axis_z_ = 0; angle_ = 0; rotation_center_x_ = 0; rotation_center_y_ = 0; rotation_center_z_ = 0; } Mesh SceneElement::Merge(const Mesh& mesh, const SceneElement& scene) { Mesh sorted_mesh = MergeSortByX(mesh); SceneElement new_scene = scene; new_scene.Transform(&new_scene); const int shift = scene.Vertexes().size(); for (int i = 0; i < sorted_mesh.vertexes().size(); i++) { new_scene.AddVertex(sorted_mesh.vertexes()[i]); } for (int i = 0; i < sorted_mesh.faces().size(); i++) { Triangle TmpFace( mesh.faces()[i].Point1() + shift, mesh.faces()[i].Point2() + shift, mesh.faces()[i].Point3() + shift); new_scene.AddFace(TmpFace); } std::vector<int> point_to_merge; for (int i = 0; i < new_scene.Vertexes().size(); i++) point_to_merge.push_back(i); int vert_counter = new_scene.Vertexes().size(); for (int i = 0; (i < shift) && (vert_counter > shift); i++) { cv::Point3d curr_point = new_scene.Vertexes().at(i); int begin = shift; int end = new_scene.Vertexes().size(); int left_border = BinarySearchByX(new_scene.Vertexes(), begin, end, curr_point.x - merge_error, LESS); int right_border = BinarySearchByX(new_scene.Vertexes(), begin, end, curr_point.x + merge_error, MORE); for (int j = left_border; j <= right_border; j++) if ((fabs(curr_point.x - new_scene.Vertexes().at(j).x) < merge_error) && (fabs(curr_point.y - new_scene.Vertexes().at(j).y) < merge_error) && (fabs(curr_point.z - new_scene.Vertexes().at(j).z) < merge_error)) { vert_counter--; point_to_merge.at(j) = i; } } Mesh GluedMesh; std::vector<int> old_number; std::vector<int> new_number; for (int i = 0; i < new_scene.Vertexes().size(); i++) { if (point_to_merge.at(i) == i) { GluedMesh.AddVertex(new_scene.Vertexes()[i]); old_number.push_back(i); new_number.push_back(old_number.size() - 1); } else { new_number.push_back(-1); } } for (int i = 0; i < new_scene.Faces().size(); i++) { Triangle TmpFace(new_number[point_to_merge[new_scene.Faces()[i].Point1()]], new_number[point_to_merge[new_scene.Faces()[i].Point2()]], new_number[point_to_merge[new_scene.Faces()[i].Point3()]]); GluedMesh.AddFace(TmpFace); } return GluedMesh; } } // namespace core
28.066946
80
0.607782
[ "mesh", "vector", "transform" ]
46ad2d849875d4cdfd9aa8b71a35669b22a9c59e
2,356
cpp
C++
chap5/chap5-1.4.cpp
liangzai90/Amazing-Algorithm-With-C
d1e992517eafd9197075d85591ed5270d945b5e3
[ "Apache-2.0" ]
null
null
null
chap5/chap5-1.4.cpp
liangzai90/Amazing-Algorithm-With-C
d1e992517eafd9197075d85591ed5270d945b5e3
[ "Apache-2.0" ]
null
null
null
chap5/chap5-1.4.cpp
liangzai90/Amazing-Algorithm-With-C
d1e992517eafd9197075d85591ed5270d945b5e3
[ "Apache-2.0" ]
null
null
null
/* 数学趣题 三色球问题 有红、黄、绿三种颜色的球,其中红球3个,黄球3个,绿球6个。 现将这12个球混放在一个盒子中,从中任意摸出8个球,编程计算摸出球的各种颜色搭配。 */ #include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <vector> using namespace std; /**************************方法1,穷举实现****************************************/ void Qiongju() { printf("red yellow green \r\n"); for (int red=0; red <= 3; red++) { for (int yellow = 0; yellow <= 3; yellow++) { for (int green = 0; green <= 6; green++) { if (red + yellow + green == 8) { printf("%3d %3d %3d\r\n", red, yellow, green); } } } } } /**************************方法2,递归实现**************************************/ //记录球色,过滤重复的情况 typedef struct tagRYG { int red; int yellow; int green; }RYGDef; static vector<tagRYG> Result; void InputResult(int red, int yellow, int green) { int isRepeat = 1; for (vector<tagRYG>::iterator it1 = Result.begin(); it1 != Result.end(); ++it1) { if (it1->red == red && it1->yellow == yellow && it1->green == green) { //repeat result. isRepeat = 0; break; } } if (1 == isRepeat) { tagRYG temp; temp.red = red; temp.yellow = yellow; temp.green = green; Result.push_back(temp); } } void OutputResult() { cout << "OutputResult:" << endl; for (vector<tagRYG>::iterator it1 = Result.begin(); it1 != Result.end(); ++it1) { printf("oneResult:r(%d),y(%d),g(%d)\r\n", it1->red,it1->yellow, it1->green); } cout << "Count is " << Result.size() << endl; } //递归查找 void Dfs(int red, int yellow, int green) { if (red > 3 || yellow > 3 || green > 6) { return;//边界判断 } if (red + yellow + green == 8) { InputResult(red, yellow, green); // printf("oneResult:r(%d),y(%d),g(%d)\r\n", red, yellow, green); return; } for (int k = 0; k < 3; k++) { if (0 == k) { red++; Dfs(red, yellow, green); red--; } else if (1 == k) { yellow++; Dfs(red, yellow, green); yellow--; } else { green++; Dfs(red, yellow, green); green--; } } return; } int main() { //穷举实现 Qiongju(); //递归实现 Dfs(0,0,0); OutputResult(); cout << endl; cout << "Hello World C Algorithm." << endl; system("pause"); return 0; } /* red yellow green 0 2 6 0 3 5 1 1 6 1 2 5 1 3 4 2 0 6 2 1 5 2 2 4 2 3 3 3 0 5 3 1 4 3 2 3 3 3 2 */
14.02381
80
0.5191
[ "vector", "3d" ]
46b574f892e2a71d5db7a11e26371aba6ef357ce
82,904
cpp
C++
GCG_Source.build/module.urllib3.packages.backports.makefile.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.urllib3.packages.backports.makefile.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.urllib3.packages.backports.makefile.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
/* Generated code for Python source for module 'urllib3.packages.backports.makefile' * created by Nuitka version 0.5.28.2 * * This code is in part copyright 2017 Kay Hayen. * * 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 "nuitka/prelude.h" #include "__helpers.h" /* The _module_urllib3$packages$backports$makefile is a Python object pointer of module type. */ /* Note: For full compatibility with CPython, every module variable access * needs to go through it except for cases where the module cannot possibly * have changed in the mean time. */ PyObject *module_urllib3$packages$backports$makefile; PyDictObject *moduledict_urllib3$packages$backports$makefile; /* The module constants used, if any. */ extern PyObject *const_str_plain_b; static PyObject *const_str_plain_BufferedRWPair; extern PyObject *const_str_plain_ModuleSpec; extern PyObject *const_str_plain___spec__; extern PyObject *const_str_plain___package__; extern PyObject *const_str_plain_io; extern PyObject *const_str_plain_buffer; extern PyObject *const_str_plain__makefile_refs; extern PyObject *const_str_plain_socket; extern PyObject *const_dict_empty; extern PyObject *const_int_pos_1; static PyObject *const_str_digest_397bad4f1f82195a3ed46c76f3f81db2; extern PyObject *const_str_plain___file__; extern PyObject *const_str_plain_encoding; extern PyObject *const_str_digest_650f585b546df29797de13514560918c; static PyObject *const_str_plain_writing; static PyObject *const_str_plain_BufferedReader; static PyObject *const_str_digest_ad2722dd707a6545f6ac36b0edd5f307; extern PyObject *const_str_plain_w; extern PyObject *const_int_0; static PyObject *const_set_401163d21cde59e9d84000b61cf44847; static PyObject *const_str_digest_46ba7ada41bfc9e1958ff44bcc27a137; static PyObject *const_str_digest_ffa90462ed056cbd39f2ebcac7b85df9; extern PyObject *const_str_plain_rawmode; extern PyObject *const_int_neg_1; static PyObject *const_tuple_str_plain_SocketIO_tuple; extern PyObject *const_str_plain_self; extern PyObject *const_str_plain_buffering; extern PyObject *const_str_plain_text; static PyObject *const_str_plain_DEFAULT_BUFFER_SIZE; extern PyObject *const_str_plain_mode; static PyObject *const_str_plain_SocketIO; static PyObject *const_str_plain_TextIOWrapper; extern PyObject *const_str_plain_backport_makefile; extern PyObject *const_str_plain_binary; static PyObject *const_str_plain_BufferedWriter; extern PyObject *const_str_plain_newline; static PyObject *const_tuple_cbca45272716ffce2b2760b545c987c0_tuple; extern PyObject *const_tuple_empty; static PyObject *const_str_digest_782a3f0e2f8a7742fb10a727995e1a91; static PyObject *const_str_digest_cf4af7845cfa9f5a0e15afd29386c674; static PyObject *const_tuple_str_plain_r_none_none_none_none_tuple; extern PyObject *const_str_plain___loader__; static PyObject *const_str_plain_reading; extern PyObject *const_str_plain_r; extern PyObject *const_str_empty; extern PyObject *const_str_plain_errors; extern PyObject *const_str_plain_raw; extern PyObject *const_str_plain___doc__; extern PyObject *const_str_plain___cached__; static PyObject *const_str_digest_7b499d847d0db721a985dc262ff53888; static PyObject *module_filename_obj; static bool constants_created = false; static void createModuleConstants( void ) { const_str_plain_BufferedRWPair = UNSTREAM_STRING( &constant_bin[ 1950143 ], 14, 1 ); const_str_digest_397bad4f1f82195a3ed46c76f3f81db2 = UNSTREAM_STRING( &constant_bin[ 1950157 ], 33, 0 ); const_str_plain_writing = UNSTREAM_STRING( &constant_bin[ 761406 ], 7, 1 ); const_str_plain_BufferedReader = UNSTREAM_STRING( &constant_bin[ 1950190 ], 14, 1 ); const_str_digest_ad2722dd707a6545f6ac36b0edd5f307 = UNSTREAM_STRING( &constant_bin[ 1950204 ], 38, 0 ); const_set_401163d21cde59e9d84000b61cf44847 = PySet_New( NULL ); PySet_Add( const_set_401163d21cde59e9d84000b61cf44847, const_str_plain_r ); PySet_Add( const_set_401163d21cde59e9d84000b61cf44847, const_str_plain_b ); PySet_Add( const_set_401163d21cde59e9d84000b61cf44847, const_str_plain_w ); assert( PySet_Size( const_set_401163d21cde59e9d84000b61cf44847 ) == 3 ); const_str_digest_46ba7ada41bfc9e1958ff44bcc27a137 = UNSTREAM_STRING( &constant_bin[ 1950242 ], 44, 0 ); const_str_digest_ffa90462ed056cbd39f2ebcac7b85df9 = UNSTREAM_STRING( &constant_bin[ 1950286 ], 38, 0 ); const_tuple_str_plain_SocketIO_tuple = PyTuple_New( 1 ); const_str_plain_SocketIO = UNSTREAM_STRING( &constant_bin[ 1950324 ], 8, 1 ); PyTuple_SET_ITEM( const_tuple_str_plain_SocketIO_tuple, 0, const_str_plain_SocketIO ); Py_INCREF( const_str_plain_SocketIO ); const_str_plain_DEFAULT_BUFFER_SIZE = UNSTREAM_STRING( &constant_bin[ 1950332 ], 19, 1 ); const_str_plain_TextIOWrapper = UNSTREAM_STRING( &constant_bin[ 1950351 ], 13, 1 ); const_str_plain_BufferedWriter = UNSTREAM_STRING( &constant_bin[ 1950364 ], 14, 1 ); const_tuple_cbca45272716ffce2b2760b545c987c0_tuple = PyTuple_New( 13 ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 0, const_str_plain_self ); Py_INCREF( const_str_plain_self ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 1, const_str_plain_mode ); Py_INCREF( const_str_plain_mode ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 2, const_str_plain_buffering ); Py_INCREF( const_str_plain_buffering ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 3, const_str_plain_encoding ); Py_INCREF( const_str_plain_encoding ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 4, const_str_plain_errors ); Py_INCREF( const_str_plain_errors ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 5, const_str_plain_newline ); Py_INCREF( const_str_plain_newline ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 6, const_str_plain_writing ); Py_INCREF( const_str_plain_writing ); const_str_plain_reading = UNSTREAM_STRING( &constant_bin[ 58206 ], 7, 1 ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 7, const_str_plain_reading ); Py_INCREF( const_str_plain_reading ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 8, const_str_plain_binary ); Py_INCREF( const_str_plain_binary ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 9, const_str_plain_rawmode ); Py_INCREF( const_str_plain_rawmode ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 10, const_str_plain_raw ); Py_INCREF( const_str_plain_raw ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 11, const_str_plain_buffer ); Py_INCREF( const_str_plain_buffer ); PyTuple_SET_ITEM( const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 12, const_str_plain_text ); Py_INCREF( const_str_plain_text ); const_str_digest_782a3f0e2f8a7742fb10a727995e1a91 = UNSTREAM_STRING( &constant_bin[ 1950378 ], 157, 0 ); const_str_digest_cf4af7845cfa9f5a0e15afd29386c674 = UNSTREAM_STRING( &constant_bin[ 1950535 ], 58, 0 ); const_tuple_str_plain_r_none_none_none_none_tuple = PyTuple_New( 5 ); PyTuple_SET_ITEM( const_tuple_str_plain_r_none_none_none_none_tuple, 0, const_str_plain_r ); Py_INCREF( const_str_plain_r ); PyTuple_SET_ITEM( const_tuple_str_plain_r_none_none_none_none_tuple, 1, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_str_plain_r_none_none_none_none_tuple, 2, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_str_plain_r_none_none_none_none_tuple, 3, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_str_plain_r_none_none_none_none_tuple, 4, Py_None ); Py_INCREF( Py_None ); const_str_digest_7b499d847d0db721a985dc262ff53888 = UNSTREAM_STRING( &constant_bin[ 1950250 ], 35, 0 ); constants_created = true; } #ifndef __NUITKA_NO_ASSERT__ void checkModuleConstants_urllib3$packages$backports$makefile( void ) { // The module may not have been used at all. if (constants_created == false) return; } #endif // The module code objects. static PyCodeObject *codeobj_4db582d7654cc977b8043ac15883f816; static PyCodeObject *codeobj_d831567be1d26889517493ab75a0d0eb; static void createModuleCodeObjects(void) { module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_ad2722dd707a6545f6ac36b0edd5f307 ); codeobj_4db582d7654cc977b8043ac15883f816 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_46ba7ada41bfc9e1958ff44bcc27a137, 1, const_tuple_empty, 0, 0, CO_NOFREE ); codeobj_d831567be1d26889517493ab75a0d0eb = MAKE_CODEOBJ( module_filename_obj, const_str_plain_backport_makefile, 14, const_tuple_cbca45272716ffce2b2760b545c987c0_tuple, 6, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE ); } // The module function declarations. static PyObject *MAKE_FUNCTION_urllib3$packages$backports$makefile$$$function_1_backport_makefile( PyObject *defaults ); // The module function definitions. static PyObject *impl_urllib3$packages$backports$makefile$$$function_1_backport_makefile( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_self = python_pars[ 0 ]; PyObject *par_mode = python_pars[ 1 ]; PyObject *par_buffering = python_pars[ 2 ]; PyObject *par_encoding = python_pars[ 3 ]; PyObject *par_errors = python_pars[ 4 ]; PyObject *par_newline = python_pars[ 5 ]; PyObject *var_writing = NULL; PyObject *var_reading = NULL; PyObject *var_binary = NULL; PyObject *var_rawmode = NULL; PyObject *var_raw = NULL; PyObject *var_buffer = NULL; PyObject *var_text = NULL; PyObject *tmp_inplace_assign_attr_1__end = NULL; PyObject *tmp_inplace_assign_attr_1__start = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; int tmp_and_left_truth_1; PyObject *tmp_and_left_value_1; PyObject *tmp_and_right_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_element_name_3; PyObject *tmp_args_element_name_4; PyObject *tmp_args_element_name_5; PyObject *tmp_args_element_name_6; PyObject *tmp_args_element_name_7; PyObject *tmp_args_element_name_8; PyObject *tmp_args_element_name_9; PyObject *tmp_args_element_name_10; PyObject *tmp_args_element_name_11; PyObject *tmp_args_element_name_12; PyObject *tmp_args_element_name_13; PyObject *tmp_assattr_name_1; PyObject *tmp_assattr_name_2; PyObject *tmp_assattr_target_1; PyObject *tmp_assattr_target_2; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_called_name_4; PyObject *tmp_called_name_5; int tmp_cmp_Eq_1; int tmp_cmp_Lt_1; int tmp_cmp_LtE_1; PyObject *tmp_compare_left_1; PyObject *tmp_compare_left_2; PyObject *tmp_compare_left_3; PyObject *tmp_compare_left_4; PyObject *tmp_compare_left_5; PyObject *tmp_compare_right_1; PyObject *tmp_compare_right_2; PyObject *tmp_compare_right_3; PyObject *tmp_compare_right_4; PyObject *tmp_compare_right_5; PyObject *tmp_compexpr_left_1; PyObject *tmp_compexpr_left_2; PyObject *tmp_compexpr_left_3; PyObject *tmp_compexpr_right_1; PyObject *tmp_compexpr_right_2; PyObject *tmp_compexpr_right_3; int tmp_cond_truth_1; int tmp_cond_truth_2; int tmp_cond_truth_3; int tmp_cond_truth_4; int tmp_cond_truth_5; int tmp_cond_truth_6; int tmp_cond_truth_7; int tmp_cond_truth_8; PyObject *tmp_cond_value_1; PyObject *tmp_cond_value_2; PyObject *tmp_cond_value_3; PyObject *tmp_cond_value_4; PyObject *tmp_cond_value_5; PyObject *tmp_cond_value_6; PyObject *tmp_cond_value_7; PyObject *tmp_cond_value_8; bool tmp_is_1; bool tmp_isnot_1; PyObject *tmp_left_name_1; PyObject *tmp_left_name_2; PyObject *tmp_left_name_3; PyObject *tmp_make_exception_arg_1; PyObject *tmp_make_exception_arg_2; PyObject *tmp_operand_name_1; int tmp_or_left_truth_1; int tmp_or_left_truth_2; PyObject *tmp_or_left_value_1; PyObject *tmp_or_left_value_2; PyObject *tmp_or_right_value_1; PyObject *tmp_or_right_value_2; PyObject *tmp_raise_type_1; PyObject *tmp_raise_type_2; PyObject *tmp_raise_type_3; PyObject *tmp_raise_type_4; bool tmp_result; PyObject *tmp_return_value; PyObject *tmp_right_name_1; PyObject *tmp_right_name_2; PyObject *tmp_right_name_3; PyObject *tmp_set_arg_1; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; PyObject *tmp_source_name_4; PyObject *tmp_source_name_5; PyObject *tmp_source_name_6; PyObject *tmp_tuple_element_1; static struct Nuitka_FrameObject *cache_frame_d831567be1d26889517493ab75a0d0eb = NULL; struct Nuitka_FrameObject *frame_d831567be1d26889517493ab75a0d0eb; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_d831567be1d26889517493ab75a0d0eb, codeobj_d831567be1d26889517493ab75a0d0eb, module_urllib3$packages$backports$makefile, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_d831567be1d26889517493ab75a0d0eb = cache_frame_d831567be1d26889517493ab75a0d0eb; // Push the new frame as the currently active one. pushFrameStack( frame_d831567be1d26889517493ab75a0d0eb ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_d831567be1d26889517493ab75a0d0eb ) == 2 ); // Frame stack // Framed code: tmp_set_arg_1 = par_mode; CHECK_OBJECT( tmp_set_arg_1 ); tmp_compare_left_1 = PySet_New( tmp_set_arg_1 ); if ( tmp_compare_left_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 19; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_compare_right_1 = PySet_New( const_set_401163d21cde59e9d84000b61cf44847 ); tmp_cmp_LtE_1 = RICH_COMPARE_BOOL_LE( tmp_compare_left_1, tmp_compare_right_1 ); if ( tmp_cmp_LtE_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_compare_left_1 ); Py_DECREF( tmp_compare_right_1 ); exception_lineno = 19; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_compare_left_1 ); Py_DECREF( tmp_compare_right_1 ); if ( tmp_cmp_LtE_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_left_name_1 = const_str_digest_ffa90462ed056cbd39f2ebcac7b85df9; tmp_right_name_1 = PyTuple_New( 1 ); tmp_tuple_element_1 = par_mode; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_right_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 21; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_right_name_1, 0, tmp_tuple_element_1 ); tmp_make_exception_arg_1 = BINARY_OPERATION_REMAINDER( tmp_left_name_1, tmp_right_name_1 ); Py_DECREF( tmp_right_name_1 ); if ( tmp_make_exception_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 21; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 20; { PyObject *call_args[] = { tmp_make_exception_arg_1 }; tmp_raise_type_1 = CALL_FUNCTION_WITH_ARGS1( PyExc_ValueError, call_args ); } Py_DECREF( tmp_make_exception_arg_1 ); assert( tmp_raise_type_1 != NULL ); exception_type = tmp_raise_type_1; exception_lineno = 20; RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb ); type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; branch_no_1:; tmp_compexpr_left_1 = const_str_plain_w; tmp_compexpr_right_1 = par_mode; if ( tmp_compexpr_right_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 23; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_1 = SEQUENCE_CONTAINS( tmp_compexpr_left_1, tmp_compexpr_right_1 ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 23; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_writing == NULL ); Py_INCREF( tmp_assign_source_1 ); var_writing = tmp_assign_source_1; tmp_compexpr_left_2 = const_str_plain_r; tmp_compexpr_right_2 = par_mode; if ( tmp_compexpr_right_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 24; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_or_left_value_1 = SEQUENCE_CONTAINS( tmp_compexpr_left_2, tmp_compexpr_right_2 ); if ( tmp_or_left_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 24; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 ); assert( !(tmp_or_left_truth_1 == -1) ); if ( tmp_or_left_truth_1 == 1 ) { goto or_left_1; } else { goto or_right_1; } or_right_1:; tmp_operand_name_1 = var_writing; if ( tmp_operand_name_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "writing" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 24; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_or_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 ); if ( tmp_or_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 24; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_2 = tmp_or_right_value_1; goto or_end_1; or_left_1:; tmp_assign_source_2 = tmp_or_left_value_1; or_end_1:; assert( var_reading == NULL ); Py_INCREF( tmp_assign_source_2 ); var_reading = tmp_assign_source_2; tmp_or_left_value_2 = var_reading; CHECK_OBJECT( tmp_or_left_value_2 ); tmp_or_left_truth_2 = CHECK_IF_TRUE( tmp_or_left_value_2 ); if ( tmp_or_left_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 25; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_or_left_truth_2 == 1 ) { goto or_left_2; } else { goto or_right_2; } or_right_2:; tmp_or_right_value_2 = var_writing; if ( tmp_or_right_value_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "writing" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 25; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_value_1 = tmp_or_right_value_2; goto or_end_2; or_left_2:; tmp_cond_value_1 = tmp_or_left_value_2; or_end_2:; tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 25; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_1 == 1 ) { goto branch_no_2; } else { goto branch_yes_2; } branch_yes_2:; tmp_raise_type_2 = PyExc_AssertionError; exception_type = tmp_raise_type_2; Py_INCREF( tmp_raise_type_2 ); exception_lineno = 25; RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb ); type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; branch_no_2:; tmp_compexpr_left_3 = const_str_plain_b; tmp_compexpr_right_3 = par_mode; if ( tmp_compexpr_right_3 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 26; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_3 = SEQUENCE_CONTAINS( tmp_compexpr_left_3, tmp_compexpr_right_3 ); if ( tmp_assign_source_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 26; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_binary == NULL ); Py_INCREF( tmp_assign_source_3 ); var_binary = tmp_assign_source_3; tmp_assign_source_4 = const_str_empty; assert( var_rawmode == NULL ); Py_INCREF( tmp_assign_source_4 ); var_rawmode = tmp_assign_source_4; tmp_cond_value_2 = var_reading; if ( tmp_cond_value_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "reading" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 28; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 ); if ( tmp_cond_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 28; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_2 == 1 ) { goto branch_yes_3; } else { goto branch_no_3; } branch_yes_3:; tmp_assign_source_5 = const_str_plain_r; { PyObject *old = var_rawmode; assert( old != NULL ); var_rawmode = tmp_assign_source_5; Py_INCREF( var_rawmode ); Py_DECREF( old ); } branch_no_3:; tmp_cond_value_3 = var_writing; if ( tmp_cond_value_3 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "writing" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 30; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_3 = CHECK_IF_TRUE( tmp_cond_value_3 ); if ( tmp_cond_truth_3 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 30; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_3 == 1 ) { goto branch_yes_4; } else { goto branch_no_4; } branch_yes_4:; tmp_left_name_2 = var_rawmode; CHECK_OBJECT( tmp_left_name_2 ); tmp_right_name_2 = const_str_plain_w; tmp_result = BINARY_OPERATION_ADD_INPLACE( &tmp_left_name_2, tmp_right_name_2 ); tmp_assign_source_6 = tmp_left_name_2; if ( tmp_result == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 31; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } var_rawmode = tmp_assign_source_6; branch_no_4:; tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_SocketIO ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_SocketIO ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "SocketIO" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 32; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_self; if ( tmp_args_element_name_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 32; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_2 = var_rawmode; if ( tmp_args_element_name_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "rawmode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 32; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 32; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 32; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_raw == NULL ); var_raw = tmp_assign_source_7; tmp_source_name_1 = par_self; if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 33; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_8 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain__makefile_refs ); if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 33; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( tmp_inplace_assign_attr_1__start == NULL ); tmp_inplace_assign_attr_1__start = tmp_assign_source_8; // Tried code: tmp_left_name_3 = tmp_inplace_assign_attr_1__start; CHECK_OBJECT( tmp_left_name_3 ); tmp_right_name_3 = const_int_pos_1; tmp_assign_source_9 = BINARY_OPERATION( PyNumber_InPlaceAdd, tmp_left_name_3, tmp_right_name_3 ); if ( tmp_assign_source_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 33; type_description_1 = "ooooooooooooo"; goto try_except_handler_2; } assert( tmp_inplace_assign_attr_1__end == NULL ); tmp_inplace_assign_attr_1__end = tmp_assign_source_9; // Tried code: tmp_compare_left_2 = tmp_inplace_assign_attr_1__start; CHECK_OBJECT( tmp_compare_left_2 ); tmp_compare_right_2 = tmp_inplace_assign_attr_1__end; CHECK_OBJECT( tmp_compare_right_2 ); tmp_isnot_1 = ( tmp_compare_left_2 != tmp_compare_right_2 ); if ( tmp_isnot_1 ) { goto branch_yes_5; } else { goto branch_no_5; } branch_yes_5:; tmp_assattr_name_1 = tmp_inplace_assign_attr_1__end; CHECK_OBJECT( tmp_assattr_name_1 ); tmp_assattr_target_1 = par_self; if ( tmp_assattr_target_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 33; type_description_1 = "ooooooooooooo"; goto try_except_handler_3; } tmp_result = SET_ATTRIBUTE( tmp_assattr_target_1, const_str_plain__makefile_refs, tmp_assattr_name_1 ); if ( tmp_result == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 33; type_description_1 = "ooooooooooooo"; goto try_except_handler_3; } branch_no_5:; goto try_end_1; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_inplace_assign_attr_1__end ); tmp_inplace_assign_attr_1__end = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto try_except_handler_2; // End of try: try_end_1:; goto try_end_2; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_inplace_assign_attr_1__start ); tmp_inplace_assign_attr_1__start = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto frame_exception_exit_1; // End of try: try_end_2:; Py_XDECREF( tmp_inplace_assign_attr_1__end ); tmp_inplace_assign_attr_1__end = NULL; Py_XDECREF( tmp_inplace_assign_attr_1__start ); tmp_inplace_assign_attr_1__start = NULL; tmp_compare_left_3 = par_buffering; if ( tmp_compare_left_3 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 34; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_compare_right_3 = Py_None; tmp_is_1 = ( tmp_compare_left_3 == tmp_compare_right_3 ); if ( tmp_is_1 ) { goto branch_yes_6; } else { goto branch_no_6; } branch_yes_6:; tmp_assign_source_10 = const_int_neg_1; { PyObject *old = par_buffering; par_buffering = tmp_assign_source_10; Py_INCREF( par_buffering ); Py_XDECREF( old ); } branch_no_6:; tmp_compare_left_4 = par_buffering; if ( tmp_compare_left_4 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 36; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_compare_right_4 = const_int_0; tmp_cmp_Lt_1 = RICH_COMPARE_BOOL_LT( tmp_compare_left_4, tmp_compare_right_4 ); if ( tmp_cmp_Lt_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 36; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cmp_Lt_1 == 1 ) { goto branch_yes_7; } else { goto branch_no_7; } branch_yes_7:; tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_io ); } if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "io" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 37; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_11 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_DEFAULT_BUFFER_SIZE ); if ( tmp_assign_source_11 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 37; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } { PyObject *old = par_buffering; par_buffering = tmp_assign_source_11; Py_XDECREF( old ); } branch_no_7:; tmp_compare_left_5 = par_buffering; if ( tmp_compare_left_5 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 38; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_compare_right_5 = const_int_0; tmp_cmp_Eq_1 = RICH_COMPARE_BOOL_EQ( tmp_compare_left_5, tmp_compare_right_5 ); if ( tmp_cmp_Eq_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 38; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cmp_Eq_1 == 1 ) { goto branch_yes_8; } else { goto branch_no_8; } branch_yes_8:; tmp_cond_value_4 = var_binary; if ( tmp_cond_value_4 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "binary" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 39; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_4 = CHECK_IF_TRUE( tmp_cond_value_4 ); if ( tmp_cond_truth_4 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 39; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_4 == 1 ) { goto branch_no_9; } else { goto branch_yes_9; } branch_yes_9:; tmp_make_exception_arg_2 = const_str_digest_397bad4f1f82195a3ed46c76f3f81db2; frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 40; { PyObject *call_args[] = { tmp_make_exception_arg_2 }; tmp_raise_type_3 = CALL_FUNCTION_WITH_ARGS1( PyExc_ValueError, call_args ); } assert( tmp_raise_type_3 != NULL ); exception_type = tmp_raise_type_3; exception_lineno = 40; RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb ); type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; branch_no_9:; tmp_return_value = var_raw; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "raw" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 41; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; branch_no_8:; tmp_and_left_value_1 = var_reading; if ( tmp_and_left_value_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "reading" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 42; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 ); if ( tmp_and_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 42; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_and_left_truth_1 == 1 ) { goto and_right_1; } else { goto and_left_1; } and_right_1:; tmp_and_right_value_1 = var_writing; if ( tmp_and_right_value_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "writing" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 42; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_value_5 = tmp_and_right_value_1; goto and_end_1; and_left_1:; tmp_cond_value_5 = tmp_and_left_value_1; and_end_1:; tmp_cond_truth_5 = CHECK_IF_TRUE( tmp_cond_value_5 ); if ( tmp_cond_truth_5 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 42; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_5 == 1 ) { goto branch_yes_10; } else { goto branch_no_10; } branch_yes_10:; tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io ); if (unlikely( tmp_source_name_3 == NULL )) { tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_io ); } if ( tmp_source_name_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "io" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_BufferedRWPair ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_3 = var_raw; if ( tmp_args_element_name_3 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "raw" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_4 = var_raw; if ( tmp_args_element_name_4 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "raw" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_5 = par_buffering; if ( tmp_args_element_name_5 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 43; { PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4, tmp_args_element_name_5 }; tmp_assign_source_12 = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_2, call_args ); } Py_DECREF( tmp_called_name_2 ); if ( tmp_assign_source_12 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 43; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_buffer == NULL ); var_buffer = tmp_assign_source_12; goto branch_end_10; branch_no_10:; tmp_cond_value_6 = var_reading; if ( tmp_cond_value_6 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "reading" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 44; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_6 = CHECK_IF_TRUE( tmp_cond_value_6 ); if ( tmp_cond_truth_6 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 44; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_6 == 1 ) { goto branch_yes_11; } else { goto branch_no_11; } branch_yes_11:; tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io ); if (unlikely( tmp_source_name_4 == NULL )) { tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_io ); } if ( tmp_source_name_4 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "io" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 45; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_BufferedReader ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 45; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_6 = var_raw; if ( tmp_args_element_name_6 == NULL ) { Py_DECREF( tmp_called_name_3 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "raw" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 45; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_7 = par_buffering; if ( tmp_args_element_name_7 == NULL ) { Py_DECREF( tmp_called_name_3 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 45; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 45; { PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 }; tmp_assign_source_13 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_3, call_args ); } Py_DECREF( tmp_called_name_3 ); if ( tmp_assign_source_13 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 45; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_buffer == NULL ); var_buffer = tmp_assign_source_13; goto branch_end_11; branch_no_11:; tmp_cond_value_7 = var_writing; if ( tmp_cond_value_7 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "writing" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 47; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_7 = CHECK_IF_TRUE( tmp_cond_value_7 ); if ( tmp_cond_truth_7 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 47; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_7 == 1 ) { goto branch_no_12; } else { goto branch_yes_12; } branch_yes_12:; tmp_raise_type_4 = PyExc_AssertionError; exception_type = tmp_raise_type_4; Py_INCREF( tmp_raise_type_4 ); exception_lineno = 47; RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb ); type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; branch_no_12:; tmp_source_name_5 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io ); if (unlikely( tmp_source_name_5 == NULL )) { tmp_source_name_5 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_io ); } if ( tmp_source_name_5 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "io" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 48; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_BufferedWriter ); if ( tmp_called_name_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 48; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_8 = var_raw; if ( tmp_args_element_name_8 == NULL ) { Py_DECREF( tmp_called_name_4 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "raw" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 48; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_9 = par_buffering; if ( tmp_args_element_name_9 == NULL ) { Py_DECREF( tmp_called_name_4 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffering" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 48; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 48; { PyObject *call_args[] = { tmp_args_element_name_8, tmp_args_element_name_9 }; tmp_assign_source_14 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args ); } Py_DECREF( tmp_called_name_4 ); if ( tmp_assign_source_14 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 48; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_buffer == NULL ); var_buffer = tmp_assign_source_14; branch_end_11:; branch_end_10:; tmp_cond_value_8 = var_binary; if ( tmp_cond_value_8 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "binary" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 49; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_8 = CHECK_IF_TRUE( tmp_cond_value_8 ); if ( tmp_cond_truth_8 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 49; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_8 == 1 ) { goto branch_yes_13; } else { goto branch_no_13; } branch_yes_13:; tmp_return_value = var_buffer; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffer" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 50; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; branch_no_13:; tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io ); if (unlikely( tmp_source_name_6 == NULL )) { tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_io ); } if ( tmp_source_name_6 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "io" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_TextIOWrapper ); if ( tmp_called_name_5 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_10 = var_buffer; if ( tmp_args_element_name_10 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "buffer" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_11 = par_encoding; if ( tmp_args_element_name_11 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "encoding" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_12 = par_errors; if ( tmp_args_element_name_12 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "errors" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_13 = par_newline; if ( tmp_args_element_name_13 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "newline" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } frame_d831567be1d26889517493ab75a0d0eb->m_frame.f_lineno = 51; { PyObject *call_args[] = { tmp_args_element_name_10, tmp_args_element_name_11, tmp_args_element_name_12, tmp_args_element_name_13 }; tmp_assign_source_15 = CALL_FUNCTION_WITH_ARGS4( tmp_called_name_5, call_args ); } Py_DECREF( tmp_called_name_5 ); if ( tmp_assign_source_15 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 51; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } assert( var_text == NULL ); var_text = tmp_assign_source_15; tmp_assattr_name_2 = par_mode; if ( tmp_assattr_name_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mode" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 52; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_assattr_target_2 = var_text; CHECK_OBJECT( tmp_assattr_target_2 ); tmp_result = SET_ATTRIBUTE( tmp_assattr_target_2, const_str_plain_mode, tmp_assattr_name_2 ); if ( tmp_result == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 52; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } tmp_return_value = var_text; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "text" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 53; type_description_1 = "ooooooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_d831567be1d26889517493ab75a0d0eb ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_d831567be1d26889517493ab75a0d0eb ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_d831567be1d26889517493ab75a0d0eb ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_d831567be1d26889517493ab75a0d0eb, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_d831567be1d26889517493ab75a0d0eb->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_d831567be1d26889517493ab75a0d0eb, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_d831567be1d26889517493ab75a0d0eb, type_description_1, par_self, par_mode, par_buffering, par_encoding, par_errors, par_newline, var_writing, var_reading, var_binary, var_rawmode, var_raw, var_buffer, var_text ); // Release cached frame. if ( frame_d831567be1d26889517493ab75a0d0eb == cache_frame_d831567be1d26889517493ab75a0d0eb ) { Py_DECREF( frame_d831567be1d26889517493ab75a0d0eb ); } cache_frame_d831567be1d26889517493ab75a0d0eb = NULL; assertFrameObject( frame_d831567be1d26889517493ab75a0d0eb ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( urllib3$packages$backports$makefile$$$function_1_backport_makefile ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_self ); par_self = NULL; Py_XDECREF( par_mode ); par_mode = NULL; Py_XDECREF( par_buffering ); par_buffering = NULL; Py_XDECREF( par_encoding ); par_encoding = NULL; Py_XDECREF( par_errors ); par_errors = NULL; Py_XDECREF( par_newline ); par_newline = NULL; Py_XDECREF( var_writing ); var_writing = NULL; Py_XDECREF( var_reading ); var_reading = NULL; Py_XDECREF( var_binary ); var_binary = NULL; Py_XDECREF( var_rawmode ); var_rawmode = NULL; Py_XDECREF( var_raw ); var_raw = NULL; Py_XDECREF( var_buffer ); var_buffer = NULL; Py_XDECREF( var_text ); var_text = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_self ); par_self = NULL; Py_XDECREF( par_mode ); par_mode = NULL; Py_XDECREF( par_buffering ); par_buffering = NULL; Py_XDECREF( par_encoding ); par_encoding = NULL; Py_XDECREF( par_errors ); par_errors = NULL; Py_XDECREF( par_newline ); par_newline = NULL; Py_XDECREF( var_writing ); var_writing = NULL; Py_XDECREF( var_reading ); var_reading = NULL; Py_XDECREF( var_binary ); var_binary = NULL; Py_XDECREF( var_rawmode ); var_rawmode = NULL; Py_XDECREF( var_raw ); var_raw = NULL; Py_XDECREF( var_buffer ); var_buffer = NULL; Py_XDECREF( var_text ); var_text = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( urllib3$packages$backports$makefile$$$function_1_backport_makefile ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *MAKE_FUNCTION_urllib3$packages$backports$makefile$$$function_1_backport_makefile( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_urllib3$packages$backports$makefile$$$function_1_backport_makefile, const_str_plain_backport_makefile, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_d831567be1d26889517493ab75a0d0eb, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_urllib3$packages$backports$makefile, const_str_digest_cf4af7845cfa9f5a0e15afd29386c674, 0 ); return (PyObject *)result; } #if PYTHON_VERSION >= 300 static struct PyModuleDef mdef_urllib3$packages$backports$makefile = { PyModuleDef_HEAD_INIT, "urllib3.packages.backports.makefile", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PYTHON_VERSION >= 300 extern PyObject *metapath_based_loader; #endif #if PYTHON_VERSION >= 330 extern PyObject *const_str_plain___loader__; #endif extern void _initCompiledCellType(); extern void _initCompiledGeneratorType(); extern void _initCompiledFunctionType(); extern void _initCompiledMethodType(); extern void _initCompiledFrameType(); #if PYTHON_VERSION >= 350 extern void _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 extern void _initCompiledAsyncgenTypes(); #endif // The exported interface to CPython. On import of the module, this function // gets called. It has to have an exact function name, in cases it's a shared // library export. This is hidden behind the MOD_INIT_DECL. MOD_INIT_DECL( urllib3$packages$backports$makefile ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_urllib3$packages$backports$makefile ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); /* Initialize the compiled types of Nuitka. */ _initCompiledCellType(); _initCompiledGeneratorType(); _initCompiledFunctionType(); _initCompiledMethodType(); _initCompiledFrameType(); #if PYTHON_VERSION >= 350 _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 _initCompiledAsyncgenTypes(); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif /* The constants only used by this module are created now. */ #ifdef _NUITKA_TRACE puts("urllib3.packages.backports.makefile: Calling createModuleConstants()."); #endif createModuleConstants(); /* The code objects used by this module are created now. */ #ifdef _NUITKA_TRACE puts("urllib3.packages.backports.makefile: Calling createModuleCodeObjects()."); #endif createModuleCodeObjects(); // puts( "in initurllib3$packages$backports$makefile" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_urllib3$packages$backports$makefile = Py_InitModule4( "urllib3.packages.backports.makefile", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_urllib3$packages$backports$makefile = PyModule_Create( &mdef_urllib3$packages$backports$makefile ); #endif moduledict_urllib3$packages$backports$makefile = MODULE_DICT( module_urllib3$packages$backports$makefile ); CHECK_OBJECT( module_urllib3$packages$backports$makefile ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_7b499d847d0db721a985dc262ff53888, module_urllib3$packages$backports$makefile ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. if ( GET_STRING_DICT_VALUE( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then but the module itself. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___builtins__, value ); } #if PYTHON_VERSION >= 330 UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_called_name_1; PyObject *tmp_defaults_1; PyObject *tmp_fromlist_name_1; PyObject *tmp_fromlist_name_2; PyObject *tmp_globals_name_1; PyObject *tmp_globals_name_2; PyObject *tmp_import_name_from_1; PyObject *tmp_level_name_1; PyObject *tmp_level_name_2; PyObject *tmp_locals_name_1; PyObject *tmp_locals_name_2; PyObject *tmp_name_name_1; PyObject *tmp_name_name_2; struct Nuitka_FrameObject *frame_4db582d7654cc977b8043ac15883f816; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; // Module code. tmp_assign_source_1 = const_str_digest_782a3f0e2f8a7742fb10a727995e1a91; UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = module_filename_obj; UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); tmp_assign_source_3 = metapath_based_loader; UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 ); // Frame without reuse. frame_4db582d7654cc977b8043ac15883f816 = MAKE_MODULE_FRAME( codeobj_4db582d7654cc977b8043ac15883f816, module_urllib3$packages$backports$makefile ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_4db582d7654cc977b8043ac15883f816 ); assert( Py_REFCNT( frame_4db582d7654cc977b8043ac15883f816 ) == 2 ); // Framed code: frame_4db582d7654cc977b8043ac15883f816->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("importlib._bootstrap"); if (likely( module != NULL )) { tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec ); } else { tmp_called_name_1 = NULL; } } if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_1 = const_str_digest_7b499d847d0db721a985dc262ff53888; tmp_args_element_name_2 = metapath_based_loader; frame_4db582d7654cc977b8043ac15883f816->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } if ( tmp_assign_source_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 ); tmp_assign_source_5 = Py_None; UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 ); tmp_assign_source_6 = const_str_digest_650f585b546df29797de13514560918c; UPDATE_STRING_DICT0( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 ); tmp_name_name_1 = const_str_plain_io; tmp_globals_name_1 = (PyObject *)moduledict_urllib3$packages$backports$makefile; tmp_locals_name_1 = Py_None; tmp_fromlist_name_1 = Py_None; tmp_level_name_1 = const_int_0; frame_4db582d7654cc977b8043ac15883f816->m_frame.f_lineno = 9; tmp_assign_source_7 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 9; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_io, tmp_assign_source_7 ); tmp_name_name_2 = const_str_plain_socket; tmp_globals_name_2 = (PyObject *)moduledict_urllib3$packages$backports$makefile; tmp_locals_name_2 = Py_None; tmp_fromlist_name_2 = const_tuple_str_plain_SocketIO_tuple; tmp_level_name_2 = const_int_0; frame_4db582d7654cc977b8043ac15883f816->m_frame.f_lineno = 11; tmp_import_name_from_1 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 ); if ( tmp_import_name_from_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto frame_exception_exit_1; } tmp_assign_source_8 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_SocketIO ); Py_DECREF( tmp_import_name_from_1 ); if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_SocketIO, tmp_assign_source_8 ); // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_4db582d7654cc977b8043ac15883f816 ); #endif popFrameStack(); assertFrameObject( frame_4db582d7654cc977b8043ac15883f816 ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_4db582d7654cc977b8043ac15883f816 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_4db582d7654cc977b8043ac15883f816, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_4db582d7654cc977b8043ac15883f816->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_4db582d7654cc977b8043ac15883f816, exception_lineno ); } // Put the previous frame back on top. popFrameStack(); // Return the error. goto module_exception_exit; frame_no_exception_1:; tmp_defaults_1 = const_tuple_str_plain_r_none_none_none_none_tuple; Py_INCREF( tmp_defaults_1 ); tmp_assign_source_9 = MAKE_FUNCTION_urllib3$packages$backports$makefile$$$function_1_backport_makefile( tmp_defaults_1 ); UPDATE_STRING_DICT1( moduledict_urllib3$packages$backports$makefile, (Nuitka_StringObject *)const_str_plain_backport_makefile, tmp_assign_source_9 ); return MOD_RETURN_VALUE( module_urllib3$packages$backports$makefile ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
33.618816
354
0.708928
[ "object" ]
46bca4abeb930bd7d348a8e6c1fd938ac6eec0a6
489
cpp
C++
_includes/leet255/leet2551.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet255/leet2551.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet255/leet2551.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: bool verifyPreorder(vector<int>& preorder) { if(preorder.size() < 1) { return true; } stack<int> s; int bound = INT_MIN; for(auto num : preorder) { if(num < bound) { return false; } while(!s.empty() && num > s.top()) { bound = s.top(); s.pop(); } s.push(num); } return true; } };
22.227273
48
0.390593
[ "vector" ]
46bdcb9ef4533f6e7d4984edd5585c10fe8d7ec7
5,571
hpp
C++
include/dds/core/BuiltinTopicTypes.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
575
2015-01-22T20:05:04.000Z
2020-06-01T10:06:12.000Z
include/dds/core/BuiltinTopicTypes.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
1,110
2015-04-20T19:30:34.000Z
2020-06-01T08:13:52.000Z
include/dds/core/BuiltinTopicTypes.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
273
2015-08-10T23:34:42.000Z
2020-05-28T13:03:32.000Z
/* * Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Corp. * Copyright 2010, Real-Time Innovations, Inc. * Copyright 2019, Proyectos y Sistemas de Mantenimiento SL (eProsima). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef OMG_DDS_CORE_BUILTIN_TOPIC_TYPES_HPP_ #define OMG_DDS_CORE_BUILTIN_TOPIC_TYPES_HPP_ #include <dds/core/detail/conformance.hpp> #include <dds/core/detail/BuiltinTopicTypes.hpp> #if defined (OMG_DDS_X_TYPES_BUILTIN_TOPIC_TYPES_SUPPORT) namespace dds { namespace core { /** * @brief * Class that is a built-in topic type that can be used to readily create Topics, * DataReaders and DataWriters for this type without the need for code generation. * * This built-in type allows for easy transfer of vectors of bytes. */ template<typename DELEGATE> class TBytesTopicType : public Value<DELEGATE> { public: /** * Creates topic type with an empty byte vector. */ TBytesTopicType(); /** * Creates topic type with the given byte vector. */ TBytesTopicType( const std::vector<uint8_t>& data); /** * Conversion operator to a vector of bytes. */ operator std::vector<uint8_t>&() const; /** * Getter function for the internal vector of bytes. */ const std::vector<uint8_t>& data() const; /** * Setter function for the internal vector of bytes. */ void data( const std::vector<uint8_t>& data); }; /** * @brief * Class that is a built-in topic type that can be used to readily create Topics, * DataReaders and DataWriters for this type without the need for code generation. * * This built-in type allows for easy transfer of strings. */ template<typename DELEGATE> class TStringTopicType : public Value<DELEGATE> { public: /** * Creates topic type with an empty data string. */ TStringTopicType(); /** * Creates topic type with the given string. */ TStringTopicType( const std::string& data); /** * Conversion operator to a string. */ operator std::string& () const; /** * Getter function for the internal data string. */ const std::string& data() const; /** * Setter function for the internal data string. */ void data( const std::string& data); }; /** * @brief * Class that is a built-in topic type that can be used to readily create Topics, * DataReaders and DataWriters for this type without the need for code generation. * * This built-in type allows for easy transfer of keyed strings. */ template<typename DELEGATE> class TKeyedStringTopicType : public Value<DELEGATE> { public: /** * Creates topic type with an empty key and data strings. */ TKeyedStringTopicType(); /** * Creates topic type with the given key and data strings. */ TKeyedStringTopicType( const std::string& key, const std::string& value); /** * Getter function for the key string. */ const std::string& key() const; /** * Setter function for the key string. */ void key( const std::string& key); /** * Getter function for the internal data string. */ const std::string& value() const; /** * Setter function for the internal data string. */ void value( const std::string& value); }; /** * @brief * Class that is a built-in topic type that can be used to readily create Topics, * DataReaders and DataWriters for this type without the need for code generation. * * This built-in type allows for easy transfer of keyed vectors of bytes. */ template<typename DELEGATE> class TKeyedBytesTopicType : public Value<DELEGATE> { public: /** * Creates topic type with an empty key string and data vector. */ TKeyedBytesTopicType(); /** * Creates topic type with given key string and data vector. */ TKeyedBytesTopicType( const std::string& key, const std::vector<uint8_t>& value); /** * Getter function for the key string. */ const std::string& key() const; /** * Setter function for the key string. */ void key( const std::string& key); /** * Getter function for the internal vector of bytes. */ const std::vector<uint8_t>& value() const; /** * Setter function for the internal vector of bytes. */ void value( const std::vector<uint8_t>& value); }; /** * @file * This file contains the type definitions for BuiltinTopicTypes */ typedef dds::core::detail::BytesTopicType BytesTopicType; typedef dds::core::detail::StringTopicType StringTopicType; typedef dds::core::detail::KeyedBytesTopicType KeyedBytesTopicType; typedef dds::core::detail::KeyedStringTopicType KeyedStringTopicType; } //namespace core } //namespace dds #endif //OMG_DDS_X_TYPES_BUILTIN_TOPIC_TYPES_SUPPORT #endif //OMG_DDS_CORE_BUILTIN_TOPIC_TYPES_HPP_
25.208145
82
0.664872
[ "object", "vector" ]
46c96aa14d90f143f93735890bc2fe5780707afc
3,047
cpp
C++
OpenGL Backend/scene.cpp
gm-archive/pineapple-ide
215044b2ccbf3bf30ab2dc03247c75a7de80a505
[ "MIT" ]
null
null
null
OpenGL Backend/scene.cpp
gm-archive/pineapple-ide
215044b2ccbf3bf30ab2dc03247c75a7de80a505
[ "MIT" ]
null
null
null
OpenGL Backend/scene.cpp
gm-archive/pineapple-ide
215044b2ccbf3bf30ab2dc03247c75a7de80a505
[ "MIT" ]
null
null
null
#include "SDL/SDL.h" #include "SDL/SDL_opengl.h" #include <vector> #include <list> #include "application.h" #include "actor.h" #include "scene.h" #include "window.h" using namespace Pineapple; using namespace std; // //Scene base constructor // Scene::Scene(int width, int height) { glClearColor(0, 0, 0, 1); this->width = width; this->height = height; Window::setSize(width, height); bgColor = Color::BLACK; } // //Scene base destructor, frees the actors and views used // Scene::~Scene() { list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { delete *i; i++; } for (unsigned int i = 0; i < views.size(); i++) { delete views[i]; } } // //Update the scene //For each actor, update and then move // void Scene::update() { list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { (*i)->verifyCollisions(); (*i)->update(); (*i)->move(); i++; } } // //Clear the screen, set the view(s) and draw the actors // void Scene::draw() { if(bgColor!=NULL) { glClearColor(bgColor->getRed(), bgColor->getGreen(), bgColor->getBlue(), bgColor->getAlpha()); glClear(GL_COLOR_BUFFER_BIT); } if (views.size() == 0) { View* v = new View(); addView(v); } for (unsigned int i = 0; i < views.size(); i++) { Drawing* d = new Drawing(); View* v = views[i]; v->set(bgColor); draw(d); } } void Scene::draw(Drawing* d){ drawBackgrounds(); drawActors(d); } bool compareActors(Actor*& a, Actor*& b) { return a->getDepth() > b->getDepth(); } // //Draw this scene's actors // void Scene::drawActors(Drawing* d) { actors.sort(compareActors); list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { if((*i)->isVisible()){ glPushMatrix(); (*i)->draw(d); glPopMatrix(); d->drawColor(Color::WHITE); } i++; } } // //Draw this scene's backgrounds // void Scene::drawBackgrounds() { for (unsigned int i = 0; i < backgrounds.size(); i++) { if (backgrounds[i]->visible) backgrounds[i]->draw(this); } } void Scene::addActor(Actor* actor) { actors.push_back(actor); } void Scene::addView(View* view) { views.push_back(view); } void Scene::addBackground(Background* bg) { backgrounds.push_back(bg); } void Scene::onKeyDown(int key) { if (key == Key::Escape) Application::exit(); list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { (*i)->onKeyDown(key); i++; } } void Scene::onKeyUp(int key) { list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { (*i)->onKeyUp(key); i++; } } void Scene::onKeyPressed(int key) { list<Actor*>::iterator i = actors.begin(); while (i != actors.end()) { (*i)->onKeyPressed(key); i++; } }
17.923529
102
0.543814
[ "vector" ]
46cd0bd013d661b73ce12fde0e2117c0ded3acca
1,195
cpp
C++
785.is_graph_bipartite.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
5
2019-09-12T05:23:44.000Z
2021-11-15T11:19:39.000Z
785.is_graph_bipartite.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
18
2019-09-23T13:11:06.000Z
2019-11-09T11:20:17.000Z
785.is_graph_bipartite.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
null
null
null
#include <vector> #define WHITE 0 #define RED 1 #define GREEN -1 using namespace std; class Solution { public: bool isBipartite(vector<vector<int>> &graph) { // 0 - no-color // 1 - red color // -1 - green color vector<int> colored(graph.size(), WHITE); for (int i = 0; i < graph.size(); i++) { if (colored[i] == WHITE && !dfs(graph, colored, i, RED)) { return false; } } return true; } bool dfs(vector<vector<int>> &graph, vector<int> &colored, int i, int color) { if (colored[i] != WHITE) { return colored[i] == color; } colored[i] = color; for (int j = 0; j < graph[i].size(); j++) { if (!dfs(graph, colored, graph[i][j], -color)) { return false; } } return true; } }; int main() { Solution s; vector<vector<int>> n1 = {{1, 3}, {0, 2}, {1, 3}, {0, 2}}; assert(s.isBipartite(n1) == true); vector<vector<int>> n2 = {{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}}; assert(s.isBipartite(n2) == false); }
19.590164
80
0.451046
[ "vector" ]
46e8db1f9e8db9de7c042af159cdfd58907c8d7a
1,025
cpp
C++
0900/80/985b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0900/80/985b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0900/80/985b.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <string> #include <vector> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(bool v) { constexpr const char* s[2] = { "NO", "YES" }; std::cout << s[v] << '\n'; } void solve(const std::vector<std::string>& s) { const size_t n = s.size(), m = s[0].length(); std::vector<unsigned> f(m); for (const std::string& x : s) { for (size_t i = 0; i < m; ++i) f[i] += x[i] - '0'; } const auto check = [&](const std::string& x) { for (size_t i = 0; i < m; ++i) { if (x[i] == '1' && f[i] < 2) return false; } return true; }; for (const std::string& x : s) { if (check(x)) return answer(true); } answer(false); } int main() { size_t n, m; std::cin >> n >> m; std::vector<std::string> s(n); std::cin >> s; solve(s); return 0; }
17.372881
65
0.468293
[ "vector" ]
46ee6362d5e8d0111117fb3983e1ff6a937b8bfa
437
cpp
C++
Medium/Sort Colors.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
Medium/Sort Colors.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
Medium/Sort Colors.cpp
TheCodeAlpha26/Lets-LeetCode
00110044763a683d262fed196f7b0742d2e8505f
[ "Apache-2.0" ]
null
null
null
class Solution { public: void sortColors(vector<int>& nums) { int r=0,w=0,b=0,i=0; for(int i=0;i<nums.size();i++) if(nums[i]==0) r++; else if(nums[i]==1) w++; else b++; for(i=0;i<r;i++) nums[i]=0; for(;i<r+w;i++) nums[i]=1; for(;i<nums.size();i++) nums[i]=2; } };
20.809524
39
0.338673
[ "vector" ]
2001b5760ce29221a3f3c58192d4479505f7806c
72,952
cpp
C++
flowstar-release/Polynomial.cpp
souradeep-111/sherlock
bf34fb4713e5140b893c98382055fb963230d69d
[ "MIT" ]
34
2018-02-17T14:18:57.000Z
2022-03-08T19:21:00.000Z
flowstar-release/Polynomial.cpp
souradeep-111/sherlock_2
763e5817cca2b69f0e96560835a442434980b3a8
[ "MIT" ]
4
2018-02-09T07:58:44.000Z
2021-01-15T14:32:02.000Z
flowstar-release/Polynomial.cpp
souradeep-111/sherlock_2
763e5817cca2b69f0e96560835a442434980b3a8
[ "MIT" ]
12
2018-02-05T15:13:05.000Z
2021-10-05T04:16:44.000Z
/*--- Flow*: A Verification Tool for Cyber-Physical Systems. Authors: Xin Chen, Sriram Sankaranarayanan, and Erika Abraham. Email: Xin Chen <chenxin415@gmail.com> if you have questions or comments. The code is released as is under the GNU General Public License (GPL). ---*/ #include "Polynomial.h" #include "TaylorModel.h" using namespace flowstar; namespace flowstar { std::vector<Interval> factorial_rec; std::vector<Interval> power_4; std::vector<Interval> double_factorial; UnivariatePolynomial up_parseresult; ParsePolynomial parsePolynomial; } Variables::Variables() { } Variables::~Variables() { varTab.clear(); varNames.clear(); } Variables::Variables(const Variables & variables) { varTab = variables.varTab; varNames = variables.varNames; } Variables & Variables::operator = (const Variables & variables) { if(this == &variables) return *this; varTab = variables.varTab; varNames = variables.varNames; return *this; } bool Variables::declareVar(const std::string & vName) { std::map<std::string,int>::const_iterator iter; if((iter = varTab.find(vName)) == varTab.end()) { varTab[vName] = varNames.size(); varNames.push_back(vName); return true; } else { return false; } } int Variables::getIDForVar(const std::string & vName) const { std::map<std::string,int>::const_iterator iter; if((iter = varTab.find(vName)) == varTab.end()) { return -1; } return iter->second; } bool Variables::getVarName(std::string & vName, const int id) const { if(id >= 0 && id < varNames.size()) { vName = varNames[id]; return true; } else { return false; } } int Variables::size() const { return varNames.size(); } void Variables::clear() { varTab.clear(); varNames.clear(); } RangeTree::RangeTree() { } RangeTree::RangeTree(const std::list<Interval> & ranges_input, const std::list<RangeTree *> & children_input) { ranges = ranges_input; children = children_input; } RangeTree::RangeTree(const RangeTree & tree) { ranges = tree.ranges; children = tree.children; } RangeTree::~RangeTree() { std::list<RangeTree *>::iterator iter = children.begin(); for(; iter!=children.end(); ++iter) { delete *iter; } ranges.clear(); children.clear(); } RangeTree & RangeTree::operator = (const RangeTree & tree) { if(this == &tree) return *this; ranges = tree.ranges; children = tree.children; return *this; } // class HornerForm HornerForm::HornerForm() { } HornerForm::HornerForm(const Interval & I):constant(I) { } HornerForm::HornerForm(const Interval & I, const std::vector<HornerForm> & hfs):constant(I), hornerForms(hfs) { } HornerForm::HornerForm(const HornerForm & hf):constant(hf.constant), hornerForms(hf.hornerForms) { } HornerForm::~HornerForm() { hornerForms.clear(); } void HornerForm::clear() { constant.set(0,0); hornerForms.clear(); } void HornerForm::intEval(Interval & result, const std::vector<Interval> & domain) const { result = constant; for(int i=0; i<hornerForms.size(); ++i) { Interval intHF; hornerForms[i].intEval(intHF, domain); intHF *= domain[i]; result += intHF; } } void HornerForm::insert(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & domain, const Interval & cutoff_threshold) const { Interval intZero; int numVars = domain.size(); result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert(tmTemp, vars, varsPolyRange, domain, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= domain[0]; result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert(tmTemp, vars, varsPolyRange, domain, cutoff_threshold); // recursive call tmTemp.mul_insert_assign(vars.tms[i-1], varsPolyRange[i-1], domain, cutoff_threshold); result.add_assign(tmTemp); } } } void HornerForm::insert_normal(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const Interval & cutoff_threshold) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_normal(tmTemp, vars, varsPolyRange, step_exp_table, numVars, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= step_exp_table[1]; result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_normal(tmTemp, vars, varsPolyRange, step_exp_table, numVars, cutoff_threshold); // recursive call tmTemp.mul_insert_normal_assign(vars.tms[i-1], varsPolyRange[i-1], step_exp_table, cutoff_threshold); result.add_assign(tmTemp); } } } void HornerForm::insert_ctrunc(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & domain, const int order, const Interval & cutoff_threshold) const { Interval intZero; int numVars = domain.size(); result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_ctrunc(tmTemp, vars, varsPolyRange, domain, order, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= domain[0]; tmTemp.ctrunc(domain, order); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_ctrunc(tmTemp, vars, varsPolyRange, domain, order, cutoff_threshold); // recursive call tmTemp.mul_insert_ctrunc_assign(vars.tms[i-1], varsPolyRange[i-1], domain, order, cutoff_threshold); result.add_assign(tmTemp); } } } void HornerForm::insert_no_remainder(TaylorModel & result, const TaylorModelVec & vars, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_no_remainder(tmTemp, vars, numVars, order, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.nctrunc(order); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_no_remainder(tmTemp, vars, numVars, order, cutoff_threshold); // recursive call tmTemp.mul_no_remainder_assign(vars.tms[i-1], order, cutoff_threshold); result.add_assign(tmTemp); } } } void HornerForm::insert_no_remainder_no_cutoff(TaylorModel & result, const TaylorModelVec & vars, const int numVars, const int order) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_no_remainder_no_cutoff(tmTemp, vars, numVars, order); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.nctrunc(order); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_no_remainder_no_cutoff(tmTemp, vars, numVars, order); // recursive call tmTemp.mul_no_remainder_no_cutoff_assign(vars.tms[i-1], order); result.add_assign(tmTemp); } } } void HornerForm::insert_no_remainder_no_cutoff(Polynomial & result, const TaylorModelVec & vars, const int numVars) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { Polynomial polyConstant(constant, numVars); result = polyConstant; } if(hornerForms.size() > 0) // the first variable is t { Polynomial polyTemp; hornerForms[0].insert_no_remainder_no_cutoff(polyTemp, vars, numVars); polyTemp.mul_assign(0,1); // multiplied by t result += polyTemp; for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_no_remainder_no_cutoff(polyTemp, vars, numVars); // recursive call polyTemp *= vars.tms[i-1].expansion; result += polyTemp; } } } void HornerForm::insert_no_remainder_no_cutoff(Polynomial & result, const std::vector<Polynomial> & vars, const int numVars) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { Polynomial polyConstant(constant, numVars); result = polyConstant; } if(hornerForms.size() > 0) // the first variable is t { Polynomial polyTemp; hornerForms[0].insert_no_remainder_no_cutoff(polyTemp, vars, numVars); polyTemp.mul_assign(0,1); // multiplied by t result += polyTemp; for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_no_remainder_no_cutoff(polyTemp, vars, numVars); // recursive call polyTemp *= vars[i-1]; result += polyTemp; } } } void HornerForm::insert_ctrunc_normal(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_ctrunc_normal(tmTemp, vars, varsPolyRange, step_exp_table, numVars, order, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= step_exp_table[1]; tmTemp.ctrunc_normal(step_exp_table, order); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_ctrunc_normal(tmTemp, vars, varsPolyRange, step_exp_table, numVars, order, cutoff_threshold); // recursive call tmTemp.mul_insert_ctrunc_normal_assign(vars.tms[i-1], varsPolyRange[i-1], step_exp_table, order, cutoff_threshold); result.add_assign(tmTemp); } } } void HornerForm::insert_ctrunc_normal_no_cutoff(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const int order) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; hornerForms[0].insert_ctrunc_normal_no_cutoff(tmTemp, vars, varsPolyRange, step_exp_table, numVars, order); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= step_exp_table[1]; tmTemp.ctrunc_normal(step_exp_table, order); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { hornerForms[i].insert_ctrunc_normal_no_cutoff(tmTemp, vars, varsPolyRange, step_exp_table, numVars, order); // recursive call tmTemp.mul_insert_ctrunc_normal_no_cutoff_assign(vars.tms[i-1], varsPolyRange[i-1], step_exp_table, order); result.add_assign(tmTemp); } } } void HornerForm::insert_ctrunc_normal(TaylorModel & result, RangeTree * & tree, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } RangeTree *pnode = new RangeTree; if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; RangeTree *child; hornerForms[0].insert_ctrunc_normal(tmTemp, child, vars, varsPolyRange, step_exp_table, numVars, order, cutoff_threshold); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= step_exp_table[1]; Interval intTrunc; tmTemp.expansion.ctrunc_normal(intTrunc, step_exp_table, order); tmTemp.remainder += intTrunc; pnode->ranges.push_back(intTrunc); pnode->children.push_back(child); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { TaylorModel tmTemp; RangeTree *child; hornerForms[i].insert_ctrunc_normal(tmTemp, child, vars, varsPolyRange, step_exp_table, numVars, order, cutoff_threshold); // recursive call Interval tm1, intTrunc2; tmTemp.mul_insert_ctrunc_normal_assign(tm1, intTrunc2, vars.tms[i-1], varsPolyRange[i-1], step_exp_table, order, cutoff_threshold); // here coefficient_range = tm1 pnode->ranges.push_back(tm1); pnode->ranges.push_back(varsPolyRange[i-1]); pnode->ranges.push_back(intTrunc2); pnode->children.push_back(child); result.add_assign(tmTemp); } } tree = pnode; } void HornerForm::insert_ctrunc_normal_no_cutoff(TaylorModel & result, RangeTree * & tree, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const int order) const { Interval intZero; result.clear(); if(!constant.subseteq(intZero)) { TaylorModel tmConstant(constant, numVars); result = tmConstant; } RangeTree *pnode = new RangeTree; if(hornerForms.size() > 0) // the first variable is t { TaylorModel tmTemp; RangeTree *child; hornerForms[0].insert_ctrunc_normal_no_cutoff(tmTemp, child, vars, varsPolyRange, step_exp_table, numVars, order); tmTemp.expansion.mul_assign(0,1); // multiplied by t tmTemp.remainder *= step_exp_table[1]; Interval intTrunc; tmTemp.expansion.ctrunc_normal(intTrunc, step_exp_table, order); tmTemp.remainder += intTrunc; pnode->ranges.push_back(intTrunc); pnode->children.push_back(child); result.add_assign(tmTemp); for(int i=1; i<hornerForms.size(); ++i) { TaylorModel tmTemp; RangeTree *child; hornerForms[i].insert_ctrunc_normal_no_cutoff(tmTemp, child, vars, varsPolyRange, step_exp_table, numVars, order); // recursive call Interval tm1, intTrunc2; tmTemp.mul_insert_ctrunc_normal_no_cutoff_assign(tm1, intTrunc2, vars.tms[i-1], varsPolyRange[i-1], step_exp_table, order); // here coefficient_range = tm1 pnode->ranges.push_back(tm1); pnode->ranges.push_back(varsPolyRange[i-1]); pnode->ranges.push_back(intTrunc2); pnode->children.push_back(child); result.add_assign(tmTemp); } } tree = pnode; } void HornerForm::insert_only_remainder(Interval & result, RangeTree *tree, const TaylorModelVec & vars, const Interval & timeStep) const { Interval intZero; result = intZero; std::list<Interval>::const_iterator iter = tree->ranges.begin(); std::list<RangeTree *>::const_iterator child = tree->children.begin(); if(hornerForms.size() > 0) // the first variable is t { Interval intTemp; hornerForms[0].insert_only_remainder(intTemp, *child, vars, timeStep); intTemp *= timeStep; intTemp += (*iter); result += intTemp; ++iter; ++child; for(int i=1; i<hornerForms.size(); ++i,++child) { Interval intTemp2; hornerForms[i].insert_only_remainder(intTemp2, *child, vars, timeStep); Interval newRemainder = (*iter) * vars.tms[i-1].remainder; ++iter; newRemainder += (*iter) * intTemp2; newRemainder += vars.tms[i-1].remainder * intTemp2; ++iter; newRemainder += (*iter); result += newRemainder; ++iter; } } } void HornerForm::dump(FILE *fp, const std::vector<std::string> & varNames) const { int numVars = hornerForms.size(); Interval intZero; bool bPlus = false; fprintf(fp, " ( "); if(!constant.subseteq(intZero)) { bPlus = true; constant.dump(fp); } if(numVars == 0) { fprintf(fp, " ) "); return; } for(int i=0; i<numVars; ++i) { if(hornerForms[i].hornerForms.size() != 0 || !hornerForms[i].constant.subseteq(intZero)) { if(bPlus) // only used to print the "+" symbol fprintf(fp, " + "); else bPlus = true; hornerForms[i].dump(fp, varNames); fprintf(fp, "* %s", varNames[i].c_str()); } } fprintf(fp, " ) "); } HornerForm & HornerForm::operator = (const HornerForm & hf) { if(this == &hf) return *this; constant = hf.constant; hornerForms = hf.hornerForms; return *this; } // class Polynomial Polynomial::Polynomial() { } Polynomial::Polynomial(const Interval & constant, const int numVars) { Interval intZero; if(!constant.subseteq(intZero)) { Monomial monomial(constant, numVars); monomials.push_back(monomial); } } Polynomial::Polynomial(const RowVector & coefficients) { int numVars = coefficients.size(); for(int i=0; i<numVars; ++i) { double dTemp = coefficients.get(i); if(dTemp <= THRESHOLD_LOW && dTemp >= -THRESHOLD_LOW) // dTemp is zero continue; Interval intTemp(dTemp); Monomial monoTemp(intTemp, numVars); monoTemp.degrees[i] = 1; monoTemp.d = 1; monomials.push_back(monoTemp); } reorder(); } Polynomial::Polynomial(const std::vector<Interval> & coefficients) { int numVars = coefficients.size(); Interval intZero; for(int i=0; i<numVars; ++i) { if(coefficients[i].subseteq(intZero)) // the coefficient is zero continue; Monomial monoTemp(coefficients[i], numVars); monoTemp.degrees[i] = 1; monoTemp.d = 1; monomials.push_back(monoTemp); } reorder(); } Polynomial::Polynomial(const Interval *pcoefficients, const int numVars) { Interval intZero; for(int i=0; i<numVars; ++i) { if((pcoefficients + i)->subseteq(intZero)) // the coefficient is zero { continue; } Monomial monoTemp(*(pcoefficients + i), numVars); monoTemp.degrees[i] = 1; monoTemp.d = 1; monomials.push_back(monoTemp); } reorder(); } Polynomial::Polynomial(const Monomial & monomial) { monomials.push_back(monomial); } Polynomial::Polynomial(const std::list<Monomial> & monos):monomials(monos) { reorder(); } Polynomial::Polynomial(const int varID, const int degree, const int numVars) { Interval intOne(1); Monomial monomial(intOne, numVars); monomial.degrees[varID] = degree; monomial.d = degree; monomials.push_back(monomial); } Polynomial::Polynomial(const UnivariatePolynomial & up, const int numVars) { Interval intZero; std::vector<int> degrees; for(int i=0; i<numVars; ++i) { degrees.push_back(0); } for(int i=0; i<up.coefficients.size(); ++i) { if(!up.coefficients[i].subseteq(intZero)) { Monomial monomial(up.coefficients[i], degrees); monomial.degrees[0] = i; monomial.d = i; monomials.push_back(monomial); } } } Polynomial::Polynomial(const Polynomial & polynomial):monomials(polynomial.monomials) { } Polynomial::~Polynomial() { monomials.clear(); } Polynomial::Polynomial(const std::string & strPolynomial, const Variables & vars) { parsePolynomial.clear(); std::string prefix(str_prefix_multivariate_polynomial); std::string suffix(str_suffix); parsePolynomial.strPolynomial = prefix + strPolynomial + suffix; parsePolynomial.variables = vars; parseMultivariatePolynomial(); *this = parsePolynomial.result; } void Polynomial::reorder() { monomials.sort(); } void Polynomial::clear() { monomials.clear(); } void Polynomial::dump_interval(FILE *fp, const std::vector<std::string> & varNames) const { if(monomials.size() == 0) { fprintf(fp, "[0,0]"); return; } std::list<Monomial>::const_iterator iter, iter_last; iter_last = monomials.end(); --iter_last; for(iter = monomials.begin(); iter != iter_last; ++iter) { iter->dump_interval(fp, varNames); fprintf(fp, " + "); } monomials.back().dump_interval(fp, varNames); } void Polynomial::dump_constant(FILE *fp, const std::vector<std::string> & varNames) const { if(monomials.size() == 0) { fprintf(fp, "[0,0]"); return; } std::list<Monomial>::const_iterator iter, iter_last; iter_last = monomials.end(); --iter_last; for(iter = monomials.begin(); iter != iter_last; ++iter) { iter->dump_constant(fp, varNames); fprintf(fp, " + "); } monomials.back().dump_constant(fp, varNames); } void Polynomial::constant(Interval & result) const { Interval intZero; if(monomials.size() > 0 && (monomials.begin())->d == 0) { result = (monomials.begin())->coefficient; } else { result = intZero; } } void Polynomial::constant(Real & result) const { Real zero; if(monomials.size() > 0 && (monomials.begin())->d == 0) { (monomials.begin())->coefficient.midpoint(result); } else { result = zero; } } void Polynomial::intEval(Interval & result, const std::vector<Interval> & domain) const { HornerForm hf; toHornerForm(hf); hf.intEval(result, domain); } void Polynomial::intEvalNormal(Interval & result, const std::vector<Interval> & step_exp_table) const { Interval intZero; result = intZero; std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { Interval intTemp; iter->intEvalNormal(intTemp, step_exp_table); result += intTemp; } } void Polynomial::inv(Polynomial & result) const { result = *this; result.inv_assign(); } void Polynomial::inv_assign() { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { iter->coefficient.inv_assign(); } } void Polynomial::pow(Polynomial & result, const int degree) const { Polynomial temp = *this; result = *this; for(int d = degree - 1; d > 0;) { if(d & 1) { result *= temp; } d >>= 1; if(d > 0) { temp *= temp; } } } void Polynomial::pow_assign(const int degree) { Polynomial temp = *this; Polynomial result = *this; for(int d = degree - 1; d > 0;) { if(d & 1) { result *= temp; } d >>= 1; if(d > 0) { temp *= temp; } } *this = result; } void Polynomial::pow(Polynomial & result, const int degree, const int order) const { Polynomial p = *this; p.nctrunc(order); Polynomial temp = p; result = p; for(int d = degree - 1; d > 0;) { if(d & 1) { result *= temp; result.nctrunc(order); } d >>= 1; if(d > 0) { temp *= temp; temp.nctrunc(order); } } } void Polynomial::pow_assign(const int degree, const int order) { Polynomial p = *this; p.nctrunc(order); Polynomial temp = p; Polynomial result = p; for(int d = degree - 1; d > 0;) { if(d & 1) { result *= temp; result.nctrunc(order); } d >>= 1; if(d > 0) { temp *= temp; temp.nctrunc(order); } } *this = result; } void Polynomial::center() { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { bool bvalid = iter->center(); if(!bvalid) { iter = monomials.erase(iter); } else { ++iter; } } } void Polynomial::add_assign(const Monomial & monomial) { bool bAdded = false; std::list<Monomial>::iterator iter; Interval intZero; if(monomial.coefficient.subseteq(intZero)) { return; } for(iter = monomials.begin(); iter != monomials.end(); ++iter) { if(monomial < *iter) { monomials.insert(iter, monomial); bAdded = true; break; } else if(monomial == *iter) { (*iter) += monomial; bAdded = true; break; } } if(!bAdded) { monomials.push_back(monomial); } } void Polynomial::sub_assign(const Monomial & monomial) { Monomial monoTemp; monomial.inv(monoTemp); add_assign(monoTemp); } void Polynomial::mul_assign(const Monomial & monomial) { Interval intZero; if(monomial.coefficient.subseteq(intZero)) // the monomial is zero { clear(); } else { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { (*iter) *= monomial; ++iter; } } } void Polynomial::mul_assign(const Interval & I) { Interval intZero; if(I.subseteq(intZero)) // the interval is zero { clear(); } else { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { iter->coefficient *= I; if(iter->coefficient.subseteq(intZero)) { iter = monomials.erase(iter); } else { ++iter; } } } } void Polynomial::div_assign(const Interval & I) { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { iter->coefficient /= I; ++iter; } } void Polynomial::mul(Polynomial & result, const Interval & I) const { result = *this; result.mul_assign(I); } void Polynomial::div(Polynomial & result, const Interval & I) const { result = *this; result.div_assign(I); } void Polynomial::mul_assign(const int varIndex, const int degree) { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { iter->degrees[varIndex] += degree; iter->d += degree; } } void Polynomial::mul(Polynomial result, const int varIndex, const int degree) const { result = *this; result.mul_assign(varIndex, degree); } Polynomial & Polynomial::operator = (const Polynomial & polynomial) { if(this == &polynomial) return *this; monomials = polynomial.monomials; return *this; } Polynomial & Polynomial::operator += (const Polynomial & polynomial) { Polynomial result; std::list<Monomial>::const_iterator iterA; // polynomial A std::list<Monomial>::const_iterator iterB; // polynomial B for(iterA = monomials.begin(), iterB = polynomial.monomials.begin(); ; ) { if(iterA == monomials.end() || iterB == polynomial.monomials.end()) break; if((*iterA) < (*iterB)) { result.monomials.push_back(*iterA); ++iterA; } else if((*iterB) < (*iterA)) { result.monomials.push_back(*iterB); ++iterB; } else { Interval intTemp; intTemp = iterA->coefficient + iterB->coefficient; Monomial monoTemp(*iterA); monoTemp.coefficient = intTemp; result.monomials.push_back(monoTemp); ++iterA; ++iterB; } } if(iterA == monomials.end() && iterB != polynomial.monomials.end()) { for(; iterB != polynomial.monomials.end(); ++iterB) result.monomials.push_back(*iterB); } else if(iterA != monomials.end() && iterB == polynomial.monomials.end()) { for(; iterA != monomials.end(); ++iterA) result.monomials.push_back(*iterA); } *this = result; return *this; } Polynomial & Polynomial::operator -= (const Polynomial & polynomial) { Polynomial polyTemp = polynomial; polyTemp.inv_assign(); *this += polyTemp; return *this; } Polynomial & Polynomial::operator *= (const Polynomial & polynomial) { Polynomial result; if((monomials.size() == 0) || (polynomial.monomials.size() == 0)) { this->clear(); return *this; } std::list<Monomial>::const_iterator iterB; // polynomial B for(iterB = polynomial.monomials.begin(); iterB != polynomial.monomials.end(); ++iterB) { Polynomial polyTemp = *this; polyTemp.mul_assign(*iterB); result += polyTemp; } *this = result; return *this; } Polynomial & Polynomial::operator *= (const Interval & I) { Interval intZero; if(I.subseteq(intZero)) // the interval is zero { clear(); } else { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { iter->coefficient *= I; if(iter->coefficient.subseteq(intZero)) { iter = monomials.erase(iter); } else { ++iter; } } } return *this; } Polynomial Polynomial::operator + (const Polynomial & polynomial) const { Polynomial result = *this; result += polynomial; return result; } Polynomial Polynomial::operator - (const Polynomial & polynomial) const { Polynomial result = *this; result -= polynomial; return result; } Polynomial Polynomial::operator * (const Polynomial & polynomial) const { Polynomial result = *this; result *= polynomial; return result; } Polynomial Polynomial::operator * (const Interval & I) const { Polynomial result = *this; result *= I; return result; } void Polynomial::ctrunc(Interval & remainder, const std::vector<Interval> & domain, const int order) { Polynomial polyTemp; Monomial monoTemp; for(; monomials.size() > 0;) { monoTemp = monomials.back(); if(monoTemp.d > order) { polyTemp.monomials.insert(polyTemp.monomials.begin(), monoTemp); monomials.pop_back(); } else { break; } } polyTemp.intEval(remainder, domain); } void Polynomial::nctrunc(const int order) { Monomial monoTemp; for(; monomials.size() > 0;) { monoTemp = monomials.back(); if(monoTemp.d > order) { monomials.pop_back(); } else { break; } } } void Polynomial::ctrunc_normal(Interval & remainder, const std::vector<Interval> & step_exp_table, const int order) { Polynomial polyTemp; Monomial monoTemp; for(; monomials.size() > 0;) { monoTemp = monomials.back(); if(monoTemp.d > order) { polyTemp.monomials.insert(polyTemp.monomials.begin(), monoTemp); monomials.pop_back(); } else { break; } } polyTemp.intEvalNormal(remainder, step_exp_table); } void Polynomial::linearCoefficients(std::vector<Interval> & result) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { result[i] = iter->coefficient; } } } void Polynomial::linearCoefficients(RowVector & result) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { result.set(iter->coefficient.sup(), i); } } } void Polynomial::linearCoefficients(iMatrix & coefficients, const int row) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { if(i != 0) // variable t is not considered { coefficients[row][i-1] = iter->coefficient; } } } } void Polynomial::linearCoefficients(iMatrix2 & coefficients, const int row) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { if(i != 0) // variable t is not considered { Real c, r; iter->coefficient.toCenterForm(c, r); coefficients.center[row][i-1] = c; coefficients.radius[row][i-1] = r; } } } } void Polynomial::constraintCoefficients(RowVector & result) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { if(i > 0) { result.set(iter->coefficient.sup(), i-1); } } } } void Polynomial::constraintCoefficients(std::vector<Interval> & result) const { // initially, the result should be filled with 0 std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { int i; if(iter->d > 1) break; if(iter->isLinear(i)) { if(i > 0) { result[i-1] = iter->coefficient; } } } } void Polynomial::toHornerForm(HornerForm & result) const { result.clear(); if(monomials.size() == 0) return; int numVars = (monomials.begin())->degrees.size(); std::list<Monomial> lstMono = monomials; std::list<Monomial>::iterator iter = lstMono.begin(); if(iter->d == 0) { result.constant = iter->coefficient; iter = lstMono.erase(iter); if(lstMono.size() == 0) return; } std::vector<std::list<Monomial> > vlMono; for(int i=0; i<numVars; ++i) { std::list<Monomial> lst_ith; for(iter = lstMono.begin(); iter != lstMono.end();) { if(iter->degrees[i] > 0) { iter->degrees[i] -= 1; iter->d -= 1; lst_ith.push_back(*iter); iter = lstMono.erase(iter); } else { ++iter; } } vlMono.push_back(lst_ith); } for(int i=0; i<numVars; ++i) { Polynomial polyTemp(vlMono[i]); HornerForm hf; polyTemp.toHornerForm(hf); result.hornerForms.push_back(hf); } } void Polynomial::rmConstant() { if(monomials.size() > 0 && (monomials.begin())->d == 0) { monomials.erase( monomials.begin() ); } } void Polynomial::decompose(Polynomial & linear, Polynomial & other) const { std::list<Monomial>::const_iterator iter; linear.monomials.clear(); other.monomials.clear(); for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { if(iter->d != 1) { other.monomials.push_back(*iter); } else { linear.monomials.push_back(*iter); } } } int Polynomial::degree() const { if(monomials.size() > 0) { std::list<Monomial>::const_iterator iter = monomials.end(); --iter; return iter->d; } else { return 0; } } int Polynomial::degree_wo_t() const { std::list<Monomial>::const_iterator iter = monomials.begin(); int degree = 0; for(; iter!=monomials.end(); ++iter) { int tmp = iter->d - iter->degrees[0]; if(degree < tmp) { degree = tmp; } } return degree; } bool Polynomial::isLinear_wo_t() const { std::list<Monomial>::const_iterator iter = monomials.begin(); for(; iter!=monomials.end(); ++iter) { if(iter->d - iter->degrees[0] > 1) { return false; } } return true; } bool Polynomial::isZero() const { if(monomials.size() == 0) { return true; } else { return false; } } void Polynomial::rmZeroTerms(const std::vector<int> & indices) { if(indices.size() == 0) { return; } std::list<Monomial>::iterator iter = monomials.begin(); for(; iter != monomials.end();) { bool bDeleted = false; for(int i=0; i<indices.size(); ++i) { if(iter->degrees[indices[i]] > 0) { iter = monomials.erase(iter); bDeleted = true; break; } } if(bDeleted == false) { ++iter; } } } void Polynomial::integral_t() { std::list<Monomial>::iterator iter = monomials.begin(); for(; iter != monomials.end(); ++iter) { if(iter->degrees[0] > 0) { iter->degrees[0] += 1; iter->d += 1; double tmp = iter->degrees[0]; iter->coefficient.div_assign(tmp); } else { iter->degrees[0] += 1; iter->d += 1; } } } /* void Polynomial::cutoff_normal(Interval & intRem, const std::vector<Interval> & step_exp_table, const Interval & cutoff_threshold) { Polynomial polyTemp; std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { double width = iter->coefficient.width(); if(iter->d == 0) { if(width >= CUTOFF_WIDTH) { Interval M; iter->coefficient.remove_midpoint(M); polyTemp.monomials.push_back(*iter); iter->coefficient = M; } else { ++iter; } } else { if(iter->coefficient.subseteq(cutoff_threshold) || width >= CUTOFF_WIDTH) { polyTemp.monomials.push_back(*iter); iter = monomials.erase(iter); } else { ++iter; } } } polyTemp.intEvalNormal(intRem, step_exp_table); } void Polynomial::cutoff(Interval & intRem, const std::vector<Interval> & domain, const Interval & cutoff_threshold) { Polynomial polyTemp; std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { double width = iter->coefficient.width(); if(iter->d == 0) { if(width >= CUTOFF_WIDTH) { Interval M; iter->coefficient.remove_midpoint(M); polyTemp.monomials.push_back(*iter); iter->coefficient = M; } else { ++iter; } } else { if(iter->coefficient.subseteq(cutoff_threshold) || width >= CUTOFF_WIDTH) { polyTemp.monomials.push_back(*iter); iter = monomials.erase(iter); } else { ++iter; } } } polyTemp.intEval(intRem, domain); } void Polynomial::cutoff(const Interval & cutoff_threshold) { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { double width = iter->coefficient.width(); if(iter->d == 0) { if(width >= CUTOFF_WIDTH) { Interval M; iter->coefficient.midpoint(M); iter->coefficient = M; } else { ++iter; } } else { if(iter->coefficient.subseteq(cutoff_threshold) || width >= CUTOFF_WIDTH) { iter = monomials.erase(iter); } else { ++iter; } } } } */ void Polynomial::cutoff_normal(Interval & intRem, const std::vector<Interval> & step_exp_table, const Interval & cutoff_threshold) { Polynomial polyTemp; std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { Monomial monoTemp; int res = iter->cutoff(monoTemp, cutoff_threshold); switch(res) { case 0: ++iter; break; case 1: polyTemp.monomials.push_back(monoTemp); ++iter; break; case 2: polyTemp.monomials.push_back(*iter); iter = monomials.erase(iter); break; } } polyTemp.intEvalNormal(intRem, step_exp_table); } void Polynomial::cutoff(Interval & intRem, const std::vector<Interval> & domain, const Interval & cutoff_threshold) { Polynomial polyTemp; std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { Monomial monoTemp; int res = iter->cutoff(monoTemp, cutoff_threshold); switch(res) { case 0: ++iter; break; case 1: polyTemp.monomials.push_back(monoTemp); ++iter; break; case 2: polyTemp.monomials.push_back(*iter); iter = monomials.erase(iter); break; } } polyTemp.intEval(intRem, domain); } void Polynomial::cutoff(const Interval & cutoff_threshold) { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ) { int res = iter->cutoff(cutoff_threshold); switch(res) { case 0: ++iter; break; case 1: ++iter; break; case 2: iter = monomials.erase(iter); break; } } } void Polynomial::derivative(Polynomial & result, const int varIndex) const { result = *this; std::list<Monomial>::iterator iter; for(iter = result.monomials.begin(); iter != result.monomials.end(); ) { if(iter->degrees[varIndex] > 0) { double tmp = iter->degrees[varIndex]; iter->degrees[varIndex] -= 1; iter->d -= 1; iter->coefficient.mul_assign(tmp); ++iter; } else { iter = result.monomials.erase(iter); } } } void Polynomial::LieDerivative(Polynomial & result, const std::vector<Polynomial> & f) const { derivative(result, 0); int rangeDim = f.size(); for(int i=0; i<rangeDim; ++i) { Polynomial P; derivative(P, i+1); P *= f[i]; result += P; } } void Polynomial::sub(Polynomial & result, const Polynomial & P, const int order) const { std::list<Monomial> monomials1, monomials2; std::list<Monomial>::const_iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { if(iter->d == order) { monomials1.push_back(*iter); } } for(iter = P.monomials.begin(); iter != P.monomials.end(); ++iter) { if(iter->d == order) { monomials2.push_back(*iter); } } Polynomial P1(monomials1), P2(monomials2); result = P1 - P2; } void Polynomial::exp_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c const_part.exp_assign(); // exp(c) if(F.isZero()) // tm = c { Polynomial polyExp(const_part, numVars); result = polyExp; return; } Interval I(1); Polynomial polyOne(I, numVars); // to compute the expression 1 + F + (1/2!)F^2 + ... + (1/k!)F^k, // we evaluate its Horner form (...((1/(k-1))((1/k)*F+1)*F + 1) ... + 1) result = polyOne; for(int i=order; i>0; --i) { Interval intFactor(1); intFactor.div_assign((double)i); result.mul_assign(intFactor); result *= F; result.nctrunc(order); result.cutoff(cutoff_threshold); result += polyOne; } result.mul_assign(const_part); } void Polynomial::rec_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c const_part.rec_assign(); // 1/c if(F.isZero()) // tm = c { Polynomial polyExp(const_part, numVars); result = polyExp; return; } Interval I(1); Polynomial polyOne(I, numVars); Polynomial F_c; F.mul(F_c, const_part); // to compute the expression 1 - F/c + (F/c)^2 - ... + (-1)^k (F/c)^k, // we evaluate its Horner form (-1)*(...((-1)*(-F/c + 1)*F/c + 1)...) + 1 result = polyOne; for(int i=order; i>0; --i) { result.inv_assign(); result *= F_c; result.nctrunc(order); result.cutoff(cutoff_threshold); result += polyOne; } result.mul_assign(const_part); } void Polynomial::sin_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c if(F.isZero()) // tm = c { const_part.sin_assign(); Polynomial polyExp(const_part, numVars); result = polyExp; return; } Interval sinc, cosc, msinc, mcosc; sinc = const_part.sin(); cosc = const_part.cos(); sinc.inv(msinc); cosc.inv(mcosc); Polynomial polyTemp(sinc, numVars); result = polyTemp; int k=1; Interval I(1); Polynomial polyPowerF(I, numVars); for(int i=1; i<=order; ++i, ++k) { k %= 4; I.div_assign((double)i); switch(k) { case 0: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * sinc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 1: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * cosc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 2: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * msinc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 3: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * mcosc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } } } result.cutoff(cutoff_threshold); } void Polynomial::cos_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c if(F.isZero()) // tm = c { const_part.cos_assign(); Polynomial polyExp(const_part, numVars); result = polyExp; return; } Interval sinc, cosc, msinc, mcosc; sinc = const_part.sin(); cosc = const_part.cos(); sinc.inv(msinc); cosc.inv(mcosc); Polynomial polyTemp(cosc, numVars); result = polyTemp; int k=1; Interval I(1); Polynomial polyPowerF(I, numVars); for(int i=1; i<=order; ++i, ++k) { k %= 4; I.div_assign((double)i); switch(k) { case 0: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * cosc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 1: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * msinc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 2: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * mcosc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } case 3: { polyPowerF *= F; polyPowerF.nctrunc(order); polyPowerF.cutoff(cutoff_threshold); polyTemp = polyPowerF; Interval intTemp = I * sinc; polyTemp.mul_assign(intTemp); result += polyTemp; break; } } } result.cutoff(cutoff_threshold); } void Polynomial::log_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c Interval C = const_part; const_part.log_assign(); // log(c) if(F.isZero()) // tm = c { Polynomial polyLog(const_part, numVars); result = polyLog; return; } Polynomial F_c; F.div(F_c, C); result = F_c; Interval I((double)order); result.div_assign(I); // F/c * (1/order) for(int i=order; i>=2; --i) { Interval J(1); J.div_assign((double)(i-1)); Polynomial polyJ(J, numVars); result -= polyJ; result.inv_assign(); result *= F_c; result.nctrunc(order); result.cutoff(cutoff_threshold); } Polynomial const_part_poly(const_part, numVars); result += const_part_poly; } void Polynomial::sqrt_taylor(Polynomial & result, const int numVars, const int order, const Interval & cutoff_threshold) const { Interval const_part; Polynomial F = *this; // remove the center point of tm F.constant(const_part); F.rmConstant(); // F = tm - c Interval C = const_part; const_part.sqrt_assign(); // sqrt(c) if(F.isZero()) // tm = c { Polynomial polySqrt(const_part, numVars); result = polySqrt; return; } Polynomial F_2c; F.div(F_2c, C); Interval intTwo(2); F_2c.div_assign(intTwo); // F/2c Interval intOne(1); Polynomial polyOne(intOne, numVars); result = F_2c; Interval K(1), J(1); for(int i=order, j=2*order-3; i>=2; --i, j-=2) { // i Interval K((double)i); // j = 2*i-3 Interval J((double)j); result.inv_assign(); result.mul_assign( J / K ); result += polyOne; result *= F_2c; result.nctrunc(order); result.cutoff(cutoff_threshold); } result += polyOne; result.mul_assign(const_part); } void Polynomial::toString(std::string & result, const std::vector<std::string> & varNames) const { std::string strPoly; if(monomials.size() == 0) { strPoly = "(0)"; return; } std::list<Monomial>::const_iterator iter, iter_last; iter_last = monomials.end(); --iter_last; strPoly += '('; for(iter = monomials.begin(); iter != iter_last; ++iter) { std::string strTemp; iter->toString(strTemp, varNames); strPoly += strTemp; strPoly += ' '; strPoly += '+'; strPoly += ' '; } std::string strTemp2; monomials.back().toString(strTemp2, varNames); strPoly += strTemp2; strPoly += ')'; result = strPoly; } void Polynomial::substitute(const int varID, const Interval & intVal) { Polynomial result; std::list<Monomial>::iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { iter->substitute(varID, intVal); result.add_assign(*iter); } monomials = result.monomials; } void Polynomial::substitute(const std::vector<int> & varIDs, const std::vector<Interval> & intVals) { Polynomial result; std::list<Monomial>::iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { iter->substitute(varIDs, intVals); result.add_assign(*iter); } monomials = result.monomials; } void Polynomial::substitute_with_precond(Interval & intRem, const std::vector<bool> & substitution, const std::vector<Interval> & step_exp_table) { Polynomial polyRem; std::list<Monomial>::iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ) { if(iter->substitute_with_precond(substitution)) { polyRem.monomials.push_back(*iter); iter = monomials.erase(iter); } else { ++iter; } } polyRem.intEvalNormal(intRem, step_exp_table); } void Polynomial::substitute_with_precond_no_remainder(const std::vector<bool> & substitution) { Polynomial result; std::list<Monomial>::iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ) { if(iter->substitute_with_precond(substitution)) { iter = monomials.erase(iter); } else { ++iter; } } } void Polynomial::simplification_in_decomposition(const std::vector<bool> & substitution) { Interval even(0,1), odd(-1,1); Polynomial result; std::list<Monomial>::iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { for(int i=1; i<substitution.size(); ++i) { if(substitution[i]) { iter->d -= iter->degrees[i]; if(iter->degrees[i]%2 == 0) { iter->coefficient *= even; } else { iter->coefficient *= odd; } iter->degrees[i] = 0; } } result.add_assign(*iter); } monomials = result.monomials; } void Polynomial::substitute(Polynomial & result, const int varID, const Interval & intVal) const { result.clear(); std::list<Monomial>::const_iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { Monomial monomial = *iter; monomial.substitute(varID, intVal); result.add_assign(monomial); } } void Polynomial::substitute(Polynomial & result, const std::vector<int> & varIDs, const std::vector<Interval> & intVals) const { result.clear(); std::list<Monomial>::const_iterator iter; for(iter=monomials.begin(); iter!=monomials.end(); ++iter) { Monomial monomial = *iter; monomial.substitute(varIDs, intVals); result.add_assign(monomial); } } void Polynomial::evaluate_t(Polynomial & result, const std::vector<Interval> & step_exp_table) const { result.clear(); if(monomials.size() == 0) return; std::list<Monomial>::const_iterator iter; Interval intZero; if(step_exp_table[1].subseteq(intZero)) // t = 0 { for(iter = monomials.begin(); iter != monomials.end(); ++iter) { if(iter->degrees[0] == 0) { result.add_assign(*iter); } } } else { for(iter = monomials.begin(); iter != monomials.end(); ++iter) { Monomial monoTemp = *iter; int tmp = monoTemp.degrees[0]; if(tmp > 0) { monoTemp.coefficient *= step_exp_table[tmp]; monoTemp.d -= tmp; monoTemp.degrees[0] = 0; } result.add_assign(monoTemp); } } } void Polynomial::extend(const int num) { std::list<Monomial>::iterator iter; for(iter = monomials.begin(); iter != monomials.end(); ++iter) { iter->extend(num); } } void Polynomial::insert(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & domain, const Interval & cutoff_threshold) const { if(vars.tms.size() == 0) { result = *this; std::list<Monomial>::iterator iter; for(iter = result.expansion.monomials.begin(); iter != result.expansion.monomials.end(); ) { if( ((iter->d) - (iter->degrees[0])) > 0 ) { iter = result.expansion.monomials.erase(iter); } else { ++iter; } } } else { HornerForm hf; toHornerForm(hf); hf.insert(result, vars, varsPolyRange, domain, cutoff_threshold); } } void Polynomial::insert_normal(TaylorModel & result, const TaylorModelVec & vars, const std::vector<Interval> & varsPolyRange, const std::vector<Interval> & step_exp_table, const int numVars, const Interval & cutoff_threshold) const { if(vars.tms.size() == 0) { result = *this; std::list<Monomial>::iterator iter; for(iter = result.expansion.monomials.begin(); iter != result.expansion.monomials.end(); ) { if( ((iter->d) - (iter->degrees[0])) > 0 ) { iter = result.expansion.monomials.erase(iter); } else { ++iter; } } } else { HornerForm hf; toHornerForm(hf); hf.insert_normal(result, vars, varsPolyRange, step_exp_table, numVars, cutoff_threshold); } } // class for univariate polynomials UnivariatePolynomial::UnivariatePolynomial() { Interval intZero; coefficients.push_back(intZero); } UnivariatePolynomial::UnivariatePolynomial(const std::vector<Interval> & coeffs) { coefficients = coeffs; } UnivariatePolynomial::UnivariatePolynomial(const UnivariatePolynomial & polynomial) { coefficients = polynomial.coefficients; } UnivariatePolynomial::UnivariatePolynomial(const Interval & I) { coefficients.push_back(I); } UnivariatePolynomial::UnivariatePolynomial(const double c) { Interval I(c); coefficients.push_back(I); } UnivariatePolynomial::UnivariatePolynomial(const double c, const int d) { Interval I(c), intZero; for(int i=0; i<d; ++i) { coefficients.push_back(intZero); } coefficients.push_back(I); } UnivariatePolynomial::UnivariatePolynomial(const Interval & I, const int d) { Interval intZero; for(int i=0; i<d; ++i) { coefficients.push_back(intZero); } coefficients.push_back(I); } UnivariatePolynomial::UnivariatePolynomial(const std::string & strPolynomial) { std::string prefix(str_prefix_univariate_polynomial); std::string suffix(str_suffix); std::string input = prefix + strPolynomial + suffix; parseUnivariatePolynomial(input); // call the parser *this = up_parseresult; } UnivariatePolynomial::~UnivariatePolynomial() { coefficients.clear(); } void UnivariatePolynomial::set2zero() { coefficients.clear(); Interval intZero; coefficients.push_back(intZero); } int UnivariatePolynomial::degree() const { return (int)(coefficients.size() - 1); } bool UnivariatePolynomial::isZero() const { Interval intZero; int n = coefficients.size(); if(n == 0) { return true; } else { bool bzero = true; for(int i=0; i<n; ++i) { if(!coefficients[i].isZero()) { bzero = false; break; } } return bzero; } } Interval UnivariatePolynomial::intEval(const std::vector<Interval> & val_exp_table) const { Interval result = coefficients[0]; for(int i=1; i<coefficients.size(); ++i) { result += coefficients[i] * val_exp_table[i]; } return result; } Interval UnivariatePolynomial::intEval(const Interval & val) const { Interval result = coefficients[coefficients.size()-1]; for(int i=coefficients.size()-2; i>=0; --i) { result = result * val + coefficients[i]; } return result; } void UnivariatePolynomial::intEval(Real & c, Real & r, const std::vector<Interval> & val_exp_table) const { Interval result = coefficients[0]; for(int i=1; i<coefficients.size(); ++i) { result += coefficients[i] * val_exp_table[i]; } result.toCenterForm(c, r); } void UnivariatePolynomial::intEval(Real & c, Real & r, const Interval & val) const { Interval I = coefficients[coefficients.size()-1]; for(int i=coefficients.size()-2; i>=0; --i) { I = I * val + coefficients[i]; } I.toCenterForm(c, r); } void UnivariatePolynomial::integral() { Interval intZero; coefficients.push_back(intZero); for(int i=coefficients.size()-2; i>=0; --i) { Interval factor(i+1); coefficients[i+1] = coefficients[i] / factor; } coefficients[0] = intZero; } void UnivariatePolynomial::times_x(const int order) { Interval intZero; if(order == 0 || coefficients.size() == 0) { return; } if(coefficients.size() == 1) { if(coefficients[0].subseteq(intZero)) return; } for(int i=0; i<order; ++i) { coefficients.push_back(intZero); } for(int i=coefficients.size()-order-1; i>=0; --i) { coefficients[i+order] = coefficients[i]; } for(int i=0; i<order; ++i) { coefficients[i] = intZero; } } void UnivariatePolynomial::pow(UnivariatePolynomial & result, const int degree) const { UnivariatePolynomial temp = *this; result = *this; for(int d = degree - 1; d > 0;) { if(d & 1) { result *= temp; } d >>= 1; if(d > 0) { temp *= temp; } } } void UnivariatePolynomial::decompose(UnivariatePolynomial & pos, UnivariatePolynomial & neg, Interval & rem) const { pos.set2zero(); neg.set2zero(); Interval I = coefficients[0], M, intZero; I.remove_midpoint(M); rem = I; if(M > intZero) { pos.coefficients[0] = M; } else { neg.coefficients[0] = M; } for(int i=1; i<coefficients.size(); ++i) { if(coefficients[i] > intZero) { pos.coefficients.push_back(coefficients[i]); neg.coefficients.push_back(intZero); } else { neg.coefficients.push_back(coefficients[i]); pos.coefficients.push_back(intZero); } } /* printf("=====================================\n"); this->output(stdout);printf("\n\n"); pos.output(stdout);printf("\n\n"); neg.output(stdout);printf("\n\n"); rem.dump(stdout);printf("\n"); printf("=====================================\n"); */ } void UnivariatePolynomial::ctrunc(Interval & rem, const int order, const std::vector<Interval> & val_exp_table) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>order; --i) { coefficients.pop_back(); } rem = trunc_part.intEval(val_exp_table); rem *= val_exp_table[order+1]; } void UnivariatePolynomial::ctrunc(Interval & rem, const int order, const Interval & val) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>order; --i) { coefficients.pop_back(); } rem = trunc_part.intEval(val); for(int i=0; i<=order; ++i) { rem *= val; } } void UnivariatePolynomial::ctrunc(Interval & rem1, Interval & rem2, const int order, const std::vector<Interval> & val1_exp_table, const std::vector<Interval> & val2_exp_table) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>order; --i) { coefficients.pop_back(); } rem1 = trunc_part.intEval(val1_exp_table); rem2 = trunc_part.intEval(val2_exp_table); rem1 *= val1_exp_table[order+1]; rem2 *= val2_exp_table[order+1]; } void UnivariatePolynomial::ctrunc(Interval & rem1, Interval & rem2, const int order, const Interval & val1, const Interval & val2) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>order; --i) { coefficients.pop_back(); } rem1 = trunc_part.intEval(val1); rem2 = trunc_part.intEval(val2); for(int i=0; i<=order; ++i) { rem1 *= val1; rem2 *= val2; } } void UnivariatePolynomial::ctrunc(const int order, const std::vector<Interval> & val_exp_table) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>order; --i) { coefficients.pop_back(); } Interval rem = trunc_part.intEval(val_exp_table); rem *= val_exp_table[order+1]; coefficients[0] += rem; } void UnivariatePolynomial::ctrunc(const int order, const Interval & val) { UnivariatePolynomial trunc_part; for(int i=order+1; i<coefficients.size(); ++i) { trunc_part.coefficients.push_back(coefficients[i]); } for(int i=coefficients.size()-1; i>=order; --i) { coefficients.pop_back(); } Interval rem = trunc_part.intEval(val); for(int i=0; i<=order; ++i) { rem *= val; } coefficients[0] += rem; } void UnivariatePolynomial::nctrunc(const int order) { for(int i=coefficients.size()-1; i>=order; --i) { coefficients.pop_back(); } } void UnivariatePolynomial::substitute(UnivariatePolynomial & result, const std::vector<UnivariatePolynomial> & t_exp_table) const { result.set2zero(); result += coefficients[0]; for(int i=1; i<coefficients.size(); ++i) { result += t_exp_table[i] * coefficients[i]; } } void UnivariatePolynomial::substitute(UnivariatePolynomial & result, const UnivariatePolynomial & t) const { result.coefficients.clear(); result.coefficients.push_back(coefficients[coefficients.size()-1]); for(int i=coefficients.size()-2; i>=0; --i) { result = result * t + coefficients[i]; } } void UnivariatePolynomial::output(FILE *fp) const { Interval intZero; bool bfirst = true; if(!coefficients[0].subseteq(intZero)) { coefficients[0].dump(stdout); bfirst = false; } for(int i=1; i<coefficients.size(); ++i) { if(!coefficients[i].subseteq(intZero)) { if(!bfirst) { fprintf(fp, " + "); } else { bfirst = false; } coefficients[i].dump(stdout); fprintf(fp, "*t^%d", i); } } if(bfirst) { fprintf(fp, "0"); } } UnivariatePolynomial & UnivariatePolynomial::operator = (const UnivariatePolynomial & polynomial) { if(this == &polynomial) return *this; coefficients = polynomial.coefficients; return *this; } UnivariatePolynomial & UnivariatePolynomial::operator = (const Interval & I) { coefficients.clear(); coefficients.push_back(I); return *this; } UnivariatePolynomial & UnivariatePolynomial::operator += (const UnivariatePolynomial & polynomial) { int n = coefficients.size(); int m = polynomial.coefficients.size(); if(n <= m) { for(int i=0; i<n; ++i) { coefficients[i] += polynomial.coefficients[i]; } for(int i=n; i<m; ++i) { coefficients.push_back(polynomial.coefficients[i]); } } else { for(int i=0; i<m; ++i) { coefficients[i] += polynomial.coefficients[i]; } } return *this; } UnivariatePolynomial & UnivariatePolynomial::operator -= (const UnivariatePolynomial & polynomial) { int n = coefficients.size(); int m = polynomial.coefficients.size(); if(n <= m) { for(int i=0; i<n; ++i) { coefficients[i] -= polynomial.coefficients[i]; } for(int i=n; i<m; ++i) { coefficients.push_back(polynomial.coefficients[i]); coefficients[i].inv_assign(); } } else { for(int i=0; i<m; ++i) { coefficients[i] -= polynomial.coefficients[i]; } } return *this; } UnivariatePolynomial & UnivariatePolynomial::operator *= (const UnivariatePolynomial & polynomial) { if(this->isZero()) { return *this; } if(polynomial.isZero()) { this->set2zero(); return *this; } int n = coefficients.size(); int m = polynomial.coefficients.size(); std::vector<Interval> result; for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { int degree = i + j; if(result.size() <= degree) { result.push_back(coefficients[i] * polynomial.coefficients[j]); } else { result[degree] += coefficients[i] * polynomial.coefficients[j]; } } } coefficients = result; return *this; } UnivariatePolynomial & UnivariatePolynomial::operator += (const Interval & I) { coefficients[0] += I; return *this; } UnivariatePolynomial & UnivariatePolynomial::operator -= (const Interval & I) { coefficients[0] -= I; return *this; } UnivariatePolynomial & UnivariatePolynomial::operator *= (const Interval & I) { if(this->isZero()) { return *this; } if(I.isZero()) { this->set2zero(); return *this; } for(int i=0; i<coefficients.size(); ++i) { coefficients[i] *= I; } return *this; } UnivariatePolynomial & UnivariatePolynomial::operator /= (const Interval & I) { for(int i=0; i<coefficients.size(); ++i) { coefficients[i] /= I; } return *this; } UnivariatePolynomial UnivariatePolynomial::operator + (const UnivariatePolynomial & polynomial) const { int n = coefficients.size(); int m = polynomial.coefficients.size(); UnivariatePolynomial result; result.coefficients.clear(); if(n <= m) { for(int i=0; i<n; ++i) { result.coefficients.push_back(coefficients[i] + polynomial.coefficients[i]); } for(int i=n; i<m; ++i) { result.coefficients.push_back(polynomial.coefficients[i]); } } else { for(int i=0; i<m; ++i) { result.coefficients.push_back(coefficients[i] + polynomial.coefficients[i]); } for(int i=m; i<n; ++i) { result.coefficients.push_back(coefficients[i]); } } return result; } UnivariatePolynomial UnivariatePolynomial::operator - (const UnivariatePolynomial & polynomial) const { int n = coefficients.size(); int m = polynomial.coefficients.size(); UnivariatePolynomial result; result.coefficients.clear(); if(n <= m) { for(int i=0; i<n; ++i) { result.coefficients.push_back(coefficients[i] - polynomial.coefficients[i]); } for(int i=n; i<m; ++i) { result.coefficients.push_back(polynomial.coefficients[i]); result.coefficients[i].inv_assign(); } } else { for(int i=0; i<m; ++i) { result.coefficients.push_back(coefficients[i] - polynomial.coefficients[i]); } for(int i=m; i<n; ++i) { result.coefficients.push_back(coefficients[i]); } } return result; } UnivariatePolynomial UnivariatePolynomial::operator * (const UnivariatePolynomial & polynomial) const { UnivariatePolynomial result; if(this->isZero() || polynomial.isZero()) { return result; } int n = coefficients.size(); int m = polynomial.coefficients.size(); for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { int degree = i + j; if(result.coefficients.size() <= degree) { result.coefficients.push_back(coefficients[i] * polynomial.coefficients[j]); } else { result.coefficients[degree] += coefficients[i] * polynomial.coefficients[j]; } } } return result; } Polynomial UnivariatePolynomial::operator * (const Polynomial & polynomial) const { Polynomial result; for(int i=0; i<coefficients.size(); ++i) { std::list<Monomial>::const_iterator iter = polynomial.monomials.begin(); Polynomial tmp; for(; iter != polynomial.monomials.end(); ++iter) { Monomial monomial = *iter; monomial.coefficient *= coefficients[i]; monomial.degrees[0] += i; monomial.d += i; tmp.add_assign(monomial); } result += tmp; } return result; } UnivariatePolynomial UnivariatePolynomial::operator + (const Interval & I) const { UnivariatePolynomial result = *this; result.coefficients[0] += I; return result; } UnivariatePolynomial UnivariatePolynomial::operator - (const Interval & I) const { UnivariatePolynomial result = *this; result.coefficients[0] -= I; return result; } UnivariatePolynomial UnivariatePolynomial::operator * (const Interval & I) const { UnivariatePolynomial result; if(this->isZero() || I.isZero()) { return result; } result.coefficients[0] = coefficients[0] * I; for(int i=1; i<coefficients.size(); ++i) { result.coefficients.push_back(coefficients[i] * I); } return result; } UnivariatePolynomial UnivariatePolynomial::operator / (const Interval & I) const { UnivariatePolynomial result; result.coefficients[0] = coefficients[0] / I; for(int i=1; i<coefficients.size(); ++i) { result.coefficients.push_back(coefficients[i] / I); } return result; } ParsePolynomial::ParsePolynomial() { } ParsePolynomial::ParsePolynomial(const ParsePolynomial & setting) { strPolynomial = setting.strPolynomial; variables = setting.variables; result = setting.result; } ParsePolynomial::~ParsePolynomial() { variables.clear(); } ParsePolynomial & ParsePolynomial::operator = (const ParsePolynomial & setting) { if(this == &setting) return *this; strPolynomial = setting.strPolynomial; variables = setting.variables; result = setting.result; return *this; } void ParsePolynomial::clear() { variables.clear(); } namespace flowstar { void compute_factorial_rec(const int order) { Interval I(1); factorial_rec.push_back(I); for(int i=1; i<=order; ++i) { I.div_assign((double)i); factorial_rec.push_back(I); } } void compute_power_4(const int order) { Interval I(1); power_4.push_back(I); for(int i=1; i<=order; ++i) { I.mul_assign(4.0); power_4.push_back(I); } } void compute_double_factorial(const int order) { Interval odd(1), even(1); double_factorial.push_back(even); double_factorial.push_back(odd); for(int i=2; i<=order; ++i) { if(i%2 == 0) { even.mul_assign((double)i); double_factorial.push_back(even); } else { odd.mul_assign((double)i); double_factorial.push_back(odd); } } } void computeTaylorExpansion(std::vector<HornerForm> & result, const std::vector<Polynomial> & ode, const int order) { int rangeDim = ode.size(); std::vector<Polynomial> taylorExpansion; std::vector<Polynomial> LieDeriv_n; for(int i=0; i<rangeDim; ++i) { RowVector row(rangeDim+1); row.set(1,i+1); Polynomial P(row); taylorExpansion.push_back(P); LieDeriv_n.push_back(P); } for(int i=0; i<rangeDim; ++i) { for(int j=1; j<=order; ++j) { Polynomial P1; LieDeriv_n[i].LieDerivative(P1, ode); LieDeriv_n[i] = P1; P1.mul_assign(factorial_rec[j]); P1.mul_assign(0,j); taylorExpansion[i] += P1; } } result.clear(); for(int i=0; i<taylorExpansion.size(); ++i) { HornerForm hf; taylorExpansion[i].toHornerForm(hf); result.push_back(hf); } } void computeTaylorExpansion(std::vector<HornerForm> & result, const std::vector<Polynomial> & ode, const std::vector<int> & orders) { int rangeDim = ode.size(); std::vector<Polynomial> taylorExpansion; std::vector<Polynomial> LieDeriv_n; for(int i=0; i<rangeDim; ++i) { RowVector row(rangeDim+1); row.set(1,i+1); Polynomial P(row); taylorExpansion.push_back(P); LieDeriv_n.push_back(P); } for(int i=0; i<rangeDim; ++i) { for(int j=1; j<=orders[i]; ++j) { Polynomial P1; LieDeriv_n[i].LieDerivative(P1, ode); LieDeriv_n[i] = P1; P1.mul_assign(factorial_rec[j]); P1.mul_assign(0,j); taylorExpansion[i] += P1; } } result.clear(); for(int i=0; i<taylorExpansion.size(); ++i) { HornerForm hf; taylorExpansion[i].toHornerForm(hf); result.push_back(hf); } } void computeTaylorExpansion(std::vector<HornerForm> & resultHF, std::vector<Polynomial> & resultMF, std::vector<Polynomial> & highest, const std::vector<Polynomial> & ode, const int order) { int rangeDim = ode.size(); std::vector<Polynomial> taylorExpansion; std::vector<Polynomial> LieDeriv_n; for(int i=0; i<rangeDim; ++i) { RowVector row(rangeDim+1); row.set(1,i+1); Polynomial P(row); taylorExpansion.push_back(P); LieDeriv_n.push_back(P); } highest.clear(); for(int i=0; i<rangeDim; ++i) { for(int j=1; j<=order; ++j) { Polynomial P; LieDeriv_n[i].LieDerivative(P, ode); LieDeriv_n[i] = P; if(j == order) { highest.push_back(P); } P.mul_assign(factorial_rec[j]); P.mul_assign(0,j); taylorExpansion[i] += P; } } resultMF = taylorExpansion; resultHF.clear(); for(int i=0; i<taylorExpansion.size(); ++i) { HornerForm hf; taylorExpansion[i].toHornerForm(hf); resultHF.push_back(hf); } } void computeTaylorExpansion(std::vector<HornerForm> & resultHF, std::vector<Polynomial> & resultMF, std::vector<Polynomial> & highest, const std::vector<Polynomial> & ode, const std::vector<int> & orders) { int rangeDim = ode.size(); std::vector<Polynomial> taylorExpansion; std::vector<Polynomial> LieDeriv_n; for(int i=0; i<rangeDim; ++i) { RowVector row(rangeDim+1); row.set(1,i+1); Polynomial P(row); taylorExpansion.push_back(P); LieDeriv_n.push_back(P); } highest.clear(); for(int i=0; i<rangeDim; ++i) { for(int j=1; j<=orders[i]; ++j) { Polynomial P; LieDeriv_n[i].LieDerivative(P, ode); LieDeriv_n[i] = P; if(j == orders[i]) { highest.push_back(P); } P.mul_assign(factorial_rec[j]); P.mul_assign(0,j); taylorExpansion[i] += P; } } resultMF = taylorExpansion; resultHF.clear(); for(int i=0; i<taylorExpansion.size(); ++i) { HornerForm hf; taylorExpansion[i].toHornerForm(hf); resultHF.push_back(hf); } } void increaseExpansionOrder(std::vector<HornerForm> & resultHF, std::vector<Polynomial> & resultMF, std::vector<Polynomial> & highest, const std::vector<Polynomial> & taylorExpansion, const std::vector<Polynomial> & ode, const int order) { int rangeDim = ode.size(); std::vector<Polynomial> expansion = taylorExpansion; std::vector<Polynomial> LieDeriv_n = highest; for(int i=0; i<rangeDim; ++i) { Polynomial P1; LieDeriv_n[i].LieDerivative(P1, ode); highest[i] = P1; P1.mul_assign(factorial_rec[order+1]); P1.mul_assign(0, order+1); expansion[i] += P1; } resultMF = expansion; resultHF.clear(); for(int i=0; i<expansion.size(); ++i) { HornerForm hf; expansion[i].toHornerForm(hf); resultHF.push_back(hf); } } void increaseExpansionOrder(HornerForm & resultHF, Polynomial & resultMF, Polynomial & highest, const Polynomial & taylorExpansion, const std::vector<Polynomial> & ode, const int order) { int rangeDim = ode.size(); Polynomial expansion = taylorExpansion; Polynomial LieDeriv_n = highest; Polynomial P1; LieDeriv_n.LieDerivative(P1, ode); highest = P1; P1.mul_assign(factorial_rec[order+1]); P1.mul_assign(0, order+1); expansion += P1; resultMF = expansion; expansion.toHornerForm(resultHF); } }
19.027647
276
0.671113
[ "vector" ]
2016b058d51257d664573b06c672140fe77b6caa
3,203
cpp
C++
src/components/fm.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
17
2021-03-22T14:17:16.000Z
2022-02-22T20:58:27.000Z
src/components/fm.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
null
null
null
src/components/fm.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
1
2021-11-17T18:00:55.000Z
2021-11-17T18:00:55.000Z
#include "fm.h" #include "synth/synth.h" void FMComponent::update(Synth const & synth) { auto steps_per_second = 4.0f / 60.0f * float(synth.settings.tempo); update_voices(steps_per_second); for (int v = 0; v < voices.size(); v++) { auto & voice = voices[v]; auto carrier_freq = util::note_freq(voice.note); for (int i = voice.get_first_sample(synth.time); i < BLOCK_SIZE; i++) { auto time_in_seconds = voice.sample * SAMPLE_RATE_INV; auto time_in_steps = time_in_seconds * steps_per_second; float amplitude; auto done = voice.apply_envelope(time_in_steps, 0.0f, INFINITY, 0.0f, 1.0f, release, amplitude); if (done) { voices.erase(voices.begin() + v); v--; break; } Sample sample = { }; float next_operator_values[FM_NUM_OPERATORS] = { }; auto phase = TWO_PI * time_in_seconds * carrier_freq; for (int o = 0; o < FM_NUM_OPERATORS; o++) { auto phs = ratios[o] * phase; // Modulate phase of operator o using the values of other operators p for (int p = 0; p < FM_NUM_OPERATORS; p++) { phs += weights[p][o] * voice.operator_values[p]; } auto value = util::envelope(time_in_steps, attacks[o], holds[o], decays[o], sustains[o]) * std::sin(phs); next_operator_values[o] = value; sample += outs[o] * value; } std::memcpy(voice.operator_values, next_operator_values, sizeof(voice.operator_values)); outputs[0].get_sample(i) += amplitude * sample; voice.sample += 1.0f; } } } void FMComponent::render(Synth const & synth) { char label[128] = { }; ImVec2 cur = { }; for (int op_to = 0; op_to < FM_NUM_OPERATORS; op_to++) { for (int op_from = 0; op_from < FM_NUM_OPERATORS; op_from++) { sprintf_s(label, "Operator %i to %i", op_from, op_to); ImGui::Knob(label, "", label, &weights[op_from][op_to], 0.0f, 2.0f, false, "", 12.0f); auto spacing = op_from < FM_NUM_OPERATORS - 1 ? -1.0f : 12.0f; ImGui::SameLine(0.0f, spacing); } sprintf_s(label, "Out %i", op_to); ImGui::Knob(label, "", label, &outs[op_to], 0.0f, 1.0f, false, "", 12.0f); if (op_to == 0) { // Save cursor position to allow drawing on the same line later on ImGui::SameLine(); cur = ImGui::GetCursorPos(); ImGui::NewLine(); } } auto prev = ImGui::GetCursorPos(); ImGui::SetCursorPos(cur); release.render(); ImGui::SetCursorPos(prev); if (ImGui::BeginTabBar("Operators")) { for (int i = 0; i < FM_NUM_OPERATORS; i++) { sprintf_s(label, "Op %i", i); if (ImGui::BeginTabItem(label)) { ratios[i].render(); ImGui::SameLine(); attacks [i].render(); ImGui::SameLine(); holds [i].render(); ImGui::SameLine(); decays [i].render(); ImGui::SameLine(); sustains[i].render(); ImGui::EndTabItem(); } } ImGui::EndTabBar(); } } void FMComponent::serialize_custom(json::Writer & writer) const { writer.write("weights", FM_NUM_OPERATORS * FM_NUM_OPERATORS, &weights[0][0]); writer.write("outs", FM_NUM_OPERATORS, outs); } void FMComponent::deserialize_custom(json::Object const & object) { object.find_array("weights", FM_NUM_OPERATORS * FM_NUM_OPERATORS, &weights[0][0]); object.find_array("outs", FM_NUM_OPERATORS, outs); }
26.915966
109
0.644708
[ "render", "object" ]
2018b7cbfc5f42809644390a1af9680a72a912d6
23,193
cpp
C++
Codes/qstarstar.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
null
null
null
Codes/qstarstar.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
null
null
null
Codes/qstarstar.cpp
CasperLumby/Bottleneck_Size_Estimation
9f9d81e35c1ac9dc74541401e8da70d428be1ad1
[ "MIT" ]
1
2019-06-12T13:25:36.000Z
2019-06-12T13:25:36.000Z
#include <algorithm> #include <iostream> #include <list> #include <string> #include <array> #include <fstream> #include <math.h> #include <math.h> #include <vector> #include <sstream> #include <gsl/gsl_rng.h> #include <gsl/gsl_sf_gamma.h> #include <numeric> #include <gsl/gsl_blas.h> #include <gsl/gsl_sf_pow_int.h> #include <time.h> #include <stdio.h> #include <unistd.h> #include <sys/stat.h> using namespace std; //Normalise the frequency of haplotypes to 1 void NormaliseFreqs(vector<double> &init_freqs) { double tot = 0; for (unsigned int i = 0; i<init_freqs.size(); i++) { tot = tot + init_freqs[i]; } for (unsigned int i = 0; i<init_freqs.size(); i++) { init_freqs[i] = init_freqs[i] / tot; } } //Calculate the log Dirichlet Multinomial given c=noise parameter, n=reads, x=frequencies of haplotypes double Likelihood(int c, vector<double> n, vector<double> x) { double sum_1 = 0; for (unsigned int i = 0; i < n.size(); i++) { sum_1 += n[i]; } double sum_2 = 0; for (unsigned int i = 0; i < n.size(); i++) { sum_2 += gsl_sf_lngamma(n[i] + 1); } double sum_3 = 0; for (unsigned int i = 0; i < x.size(); i++) { sum_3 += (c*x[i]); } double sum_4 = 0; for (unsigned int i = 0; i < x.size(); i++) { sum_4 += (n[i] + c * x[i]); } double sum_5 = 0; for (unsigned int i = 0; i < n.size(); i++) { sum_5 += gsl_sf_lngamma(n[i] + c * x[i]); } double sum_6 = 0; for (unsigned int i = 0; i < n.size(); i++) { sum_6 += gsl_sf_lngamma(c*x[i]); } return gsl_sf_lngamma(sum_1 + 1) - sum_2 + gsl_sf_lngamma(sum_3) - gsl_sf_lngamma(sum_4) + sum_5 - sum_6; } /*Given a timepoint (0 for the donor and 1 for the recipient), this function finds the likelihood of a set of haplotypes with their frequencies (freq) and their contribution to the reads of a given partial haplotype set (CONTRIBS) with full partitioning of the partial sets (partitions) and inferred noise parameter c*/ double Dirichlet_m(double timepoint, vector<string> haplotypes, vector<double> freq, vector<vector<vector<int>>> &CONTRIBS, vector<vector<vector<string>>> &partitions, double c) { //In Multi_locus_trajectories.out, go two columns back from the last column on the right --> first timepoint if (timepoint == 0) { timepoint = 3; } //In Multi_locus_trajectories.out, go zero columns back from the last column on the right --> last timepoint else if (timepoint == 1) { timepoint = 1; } vector<string> candidates = haplotypes; vector<double> q = freq; double ULTIMA_THULE = 0; //For a candidate haplotype set, this parameter calculates the sum of the likelihoods for each of the i partial haplotype sets int candidates_size = candidates.size(); for (unsigned int i = 0; i<CONTRIBS.size(); i++) { vector<double> inf; //contains the sum of the frequencies of all contributing candidate haplotypes for each of the j members of the ith partial haplotype set vector<double> nn; //contains the corresponding total number of reads for each member of inf vector vector<double> qCopy = q; //copy of the input frequencies, freq qCopy.erase(remove(qCopy.begin(), qCopy.end() - 1, q[candidates_size]));//erase the unkknown haplotype qx out of the copy of the frequency list, qCopy. unsigned int count_no_contrib = 0; //counts the number of haplotypes with no contribution to a partial haplotype read double no_contrib_reads = 0; //partial haplotype reads with no matching haplotype that contributes vector<double> no_contrib_haps; //list of all haplotype frequencies that do not contribute vector<double> contrib_haps; //list of all haplotype frequencies that contribute double contrib_reads = 0; //partial haplotype reads with, at least, one matching haplotype that contributes unsigned int count_contrib = 0; //counts the number of haplotypes contributing to a partial haplotype read double sum_nn = 0; //adds the number of reads //the following loop goes over all the haplotypes that contribute to the reads of a given partial haplotype set for (unsigned int j = 0; j<(CONTRIBS[i]).size(); j++) { double sum = 0; int count_if_any_contrib = 0; //checks, for each partial haplotype, if any haplotype contributes for (unsigned int k = 0; k<(CONTRIBS[i][j]).size(); k++)//this loop adds the frequency of all the haplotypes that share the same partial haplotype of interest { //the if clause below insures that we add the frequency of all haplotypes that contribute to the ith partial haplotype set (CONTRIBS[i][j][k] = ith partial haplotype set, jth element, kth contributing haplotype) sum += q[(CONTRIBS[i][j][k])]; count_if_any_contrib++; count_contrib++; contrib_haps.push_back(q[(CONTRIBS[i][j][k])]); } //if none of the candidate haplotypes match with the partial haplotype of interest (i.e. do not 'contribute' to that partial haplotype set), the corresponding reads for that partial haplotype goes to the unknown haplotype qx) if ((CONTRIBS[i][j]).empty()) { count_no_contrib++; double SIZE1_1 = (partitions[i][j]).size(); no_contrib_reads = atoi((partitions[i][j]).at(SIZE1_1 - timepoint).c_str()); sum_nn += no_contrib_reads; no_contrib_haps.push_back(no_contrib_reads); } //if, at least, there were one candidate haplotype that contributed to the ith partial haplotype set, uptade nn and inf if (count_if_any_contrib != 0) { inf.push_back(sum); double SIZE = (partitions[i][j]).size(); contrib_reads = atoi((partitions[i][j]).at(SIZE - timepoint).c_str()); nn.push_back(contrib_reads); } } //if the candidate haplotypes covered all the partial haplotypes in the ith set, then there are zero reads left to be attributed to qx if (count_no_contrib == 0 && count_contrib == qCopy.size()) { inf.push_back(q[candidates_size]); nn.push_back(0.0); } unsigned int check2 = 0; //if some (but not all) of the candidate haplotypes covered the entire partial haplotype set i, the remaining candidates would correspond to zero reads (so as the qx haplotype) if (count_no_contrib == 0 && count_contrib != qCopy.size()) { for (unsigned int m = 0; m < contrib_haps.size(); m++)//this loop finds all the haplotypes that do not contribute and removes their frequencies from qCopy { qCopy.erase(remove(qCopy.begin(), qCopy.end() - 1, contrib_haps[m])); } double temp_sum = 0; for (unsigned int g = 0; g < qCopy.size(); g++) { temp_sum += qCopy[g]; } inf.push_back(temp_sum); nn.push_back(0.0); inf.push_back(q[candidates_size]); nn.push_back(0.0); check2++; } //if some (but not all) of the candidate haplotypes did not contribute to the ith set, then they correspond to zero reads and the remaining unidentified partial haplotypes go to qx unsigned int check3 = 0; if (count_no_contrib != 0 && count_contrib != qCopy.size() && count_contrib != 0 && check2 == 0) { for (unsigned int m = 0; m < contrib_haps.size(); m++) { qCopy.erase(remove(qCopy.begin(), qCopy.end() - 1, contrib_haps[m])); } double temp_sum = 0; for (unsigned int g = 0; g < qCopy.size(); g++) { temp_sum += qCopy[g]; } double total = accumulate(no_contrib_haps.begin(), no_contrib_haps.end(), 0); inf.push_back(temp_sum); nn.push_back(0.0); inf.push_back(q[candidates_size]); nn.push_back(total); check3++; } //if non of the candidate haplotypes contributed to ith set, then they all correspond to zero reads and everything else would be classified as qx if (count_no_contrib != 0 && count_contrib != qCopy.size() && count_contrib == 0 && check2 == 0 && check3 == 0) { double temp_sum = 0; for (unsigned int g = 0; g < qCopy.size(); g++) { temp_sum += qCopy[g]; } double total = accumulate(no_contrib_haps.begin(), no_contrib_haps.end(), 0); inf.push_back(q[candidates_size]); nn.push_back(total); inf.push_back(temp_sum); nn.push_back(0.0); } //if all the candidate haplotypes covered some of the partial haplotypes, then all the remaining reads correspond to qx. if (count_no_contrib != 0 && count_contrib == qCopy.size() && check2 == 0 && check3 == 0) { inf.push_back(q[candidates_size]); nn.push_back(sum_nn); } ULTIMA_THULE += Likelihood(c, nn, inf); qCopy = q; //resetting the copy of the original frequencies } return ULTIMA_THULE; } //For a candidate haplotype set, this function finds an optimal frequency given the short-read data collected from Multi_locus_trajectories.out file and returns the log-likelihood value for that set double OptimumFreqs(double timepoint, vector<string> &candidates, vector<double> &init_freqs, vector<vector<vector<int>>> &CONTRIBS, vector<vector<vector<string>>> &partitions, double c) { gsl_rng_env_setup(); gsl_rng *rgen = gsl_rng_alloc(gsl_rng_taus); int seed = (int)time(NULL); gsl_rng_set(rgen, seed); double init_size = init_freqs.size(); vector<double> init_freqs_store = init_freqs; double L = -1e7; //initial (extremely low) value for the likelihood unsigned int check = 1; unsigned int max_it = 8e3; //maximum number of attempts for optimising the frequencies double changex = 1e-2; //magnitude of the incremental (random) change in frequency double L_store1 = -1e7; //improved likelihood after frequency optimisation for (unsigned int it = 0; it < max_it; it++) { double r = 2 * (gsl_rng_uniform(rgen) - 0.5);//random direction between -1 to +1 int j = floor(init_freqs.size()*gsl_rng_uniform(rgen)); init_freqs[j] = init_freqs[j] + (r*changex); for (unsigned int i = 0; i < init_size; i++) { if (init_freqs[i] < 1e-11) { //Warning: if you change this threshold below from 1e-11 to 0, there will be a problem with calculating the gamma function //we assume that the lowest possible frequency is 10^-11 init_freqs[i] = 1e-11; } } NormaliseFreqs(init_freqs); //frequencies should add up to one after being randomly changed if (init_freqs[init_size - 1] > 1e-2) { init_freqs[init_size - 1] = 1e-2; //the frequency of the 'X' haplotype, qx, could only go up to 1% double TOTAL = 0; for (unsigned int i = 0; i < init_size-1; i++) { TOTAL += init_freqs[i]; } for (unsigned int i = 0; i < init_size-1; i++) { init_freqs[i] = init_freqs[i]*(0.99/TOTAL);//in this case, the frequency of the rest of the haplotypes should add up to 99% } } L = Dirichlet_m(timepoint, candidates, init_freqs, CONTRIBS, partitions, c);//calculate the Dirichlet likelihood after frequency optimisation step if (L > L_store1)//if the likelihood improved, store it and go from there in the next step { L_store1 = L; init_freqs_store = init_freqs; check = 1; } if (L <= L_store1)//if there was no improvement for over 50 consecutive attempts, then we have reached a maximum likelihood peak { init_freqs = init_freqs_store; check++; } if (check >= 50)//50 is found heuristically from testing multiple simulations { break; } } return L_store1; } bool fileExists (string& fileName) { ifstream f(fileName.c_str()); if (f.good()) { f.close(); return true; } else { f.close(); return false; } } int main(int argc, char* argv[]) { if(argc < 6 || argc > 6) { cout << "Error in the input format: " << endl << "Please use the following input order:" << endl; cout << "(1) Directory to simulated reads, i.e. x*" << endl; cout << "(2) Directory to reconstructed haplotypes, i.e. q*" << endl; cout << "(3) Directory to store re-inferred haplotype frequencies q**" << endl; cout << "(4) File name for the re-inferred haplotypes for a particular segment $t" << endl; cout << "(5) Inferred noise parameter C" << endl; return false; } else { cout << "qstarstar is now initiated..." << endl; } string xStar = argv[1]; string reconstructed_haplotypes = argv[2]; double c = atoi(argv[5]); gsl_rng_env_setup(); gsl_rng *rgen = gsl_rng_alloc(gsl_rng_taus); int seed = (int)time(NULL); gsl_rng_set(rgen, seed); if (fileExists(xStar) == true) { if (fileExists(reconstructed_haplotypes) == true) { vector<string> table; ifstream test; test.open(reconstructed_haplotypes); while (!test.eof()) { string line; getline(test, line); table.push_back(line); } test.close(); vector < vector<string> > rows; for (unsigned int i = 0; i < table.size(); i++) { vector<string> row; istringstream iss(table[i]); string term; while (iss >> term) { row.push_back(term); } if (!row.empty()) { rows.push_back(row); } } vector<double> f_before; vector<double> f_after; vector<string> candidates; //the list of all haplotypes (already constructed from q*) for (unsigned int i = 0; i < rows.size(); i++) { unsigned int sz = (rows[i]).size(); candidates.push_back(rows[i][sz-3]); //string temp_1 = rows[i][sz-2]; double num_1 = atof((rows[i][sz-2]).c_str()); f_before.push_back(num_1); //string temp_2 = rows[i][sz-1]; double num_2 = atof((rows[i][sz-1]).c_str()); f_after.push_back(num_2); } vector<string> table_2; ifstream reads; reads.open(xStar); while (!reads.eof())//read the content of Multi_locus_trajectories.out and store it in table { string line_2; getline(reads, line_2); table_2.push_back(line_2); } reads.close(); vector < vector<string> > rows_2; //save each row of Multi_locus_trajectories.out for (unsigned int i = 0; i < table_2.size(); i++) { vector<string> row_2; istringstream iss(table_2[i]); string term_2; while (iss >> term_2) { row_2.push_back(term_2); } if (!row_2.empty()) { rows_2.push_back(row_2); } } int reads_total = 0; //calculating the total number of reads for all the partial haplotypes -- this quantity is required for BIC calculations for (unsigned int i=0; i<rows_2.size(); i++) { unsigned int sz = (rows_2[i]).size(); string reads_before_s = rows_2[i][sz-1]; string reads_after_s = rows_2[i][sz-3]; int reads_before = atoi(reads_before_s.c_str()); int reads_after = atoi(reads_after_s.c_str()); reads_total += reads_before + reads_after; } vector<int> positions; //collect the loci numbers from Multi_locus_trajectories.out for (unsigned int i = 0; i < rows_2.size(); i++) { unsigned int numLoci = atoi(rows_2[i][0].c_str()); //get the number of loci for the ith row for (unsigned int j = 1; j < 1 + numLoci; j++) //loop over the loci in the file { positions.push_back(atoi((rows_2[i][j]).c_str())); } } //The following ~30 lines of code sorts the order of loci from 0 to the last variant locus and store them in positions_string sort(positions.begin(), positions.end()); positions.erase(unique(positions.begin(), positions.end()), positions.end()); //up to this point, positions contain a list of all unique loci numbers sorted from smallest to largest, e.g. 121 322 1123 5694 vector<string> positions_string; //convert positions to a vector of strings to do comparison on characters for (int i : positions) { positions_string.push_back(to_string(i)); } vector<vector<string>> temprows = rows_2;//we want temprows to include all the information about Multi_locus_trajectories.out BUT with loci numbers that are sorted from 0 to n-1 for each partial haplotype of size n for (unsigned int i = 0; i < rows_2.size(); i++)//loop over all the rows in Multi_locus_trajectories.out { unsigned int numLoci = atoi(rows_2[i][0].c_str()); //get the number of loci for the ith row for (unsigned int j = 1; j < 1 + numLoci; j++)//loop over the loci for each partial haplotype (i.e. each row in Multi_locus_trajectories.out) { int count = -1; for (string k : positions_string) { count++; if (rows_2[i][j] == k) { temprows[i][j] = " "; temprows[i][j] = to_string(count); //what this does is that it would swap the actual loci number from SAMFIRE and re-label it as a sorted integer between [0,n-1] break; } } } } //the updated rows of temprows are identical to original SAMFIRE Multi_locus_trajectories.out except that the loci are numbered from 0 to n-1 vector<vector<vector<string>>> partitions; //partitions the partial haplotypes from Multi_locus_trajectories.out into groups with matching loci numbers for (unsigned int k = 1; k <= positions_string.size(); k++)//loop from 1 to n-1 { for (unsigned int i = 0; i < positions_string.size(); i++)//loop over from 0 to n-1 { vector<string> pick_row; vector<vector<string>> partialPar; for (unsigned int j = 0; j < temprows.size(); j++)//loop over all the rows in Multi_locus_trajectories.out { pick_row = temprows[j]; string pos_num = to_string(k); unsigned int check_match = 0; if (pick_row[0] == pos_num)//if partial haplotype j has k number of loci { for (unsigned int m = 0; m < k; m++)//go over all of loci in partial haplotype j and see if it contains a unique sequence of loci { if (pick_row[m + 1] == to_string(i + m)) { check_match++; } } if (check_match == k)//if there is a perfect match, then it is an element of a given partition set { partialPar.push_back(pick_row); } } } if (!partialPar.empty()) { partitions.push_back(partialPar); } } } bool changeOccurred = true; while(changeOccurred == true) { changeOccurred = false; vector<string> sort_by_recipeint; //Here we sort each element of a partition set from largest to smallest with respect to the total number of reads in the recipient // -- the pattern of sorting should not change if you do it with the donor reads (because it is always the case that a partial haplotype that has the // highest number of reads in the donor would have the highest number of reads in the recipient) for (unsigned int i = 0; i < (partitions).size(); i++) //go over every element of the partition (defined above) { double SIZE0 = (partitions[i]).size(); for (unsigned int j = 0; j < SIZE0 - 1; j++)// loop over the elements and sort partial haplotypes based on reads in the recipient { double SIZE1 = (partitions[i][j]).size();//select the jth partial haplotype double NUM1 = atoi((partitions[i][j]).at(SIZE1 - 1).c_str());//SIZE1 - 1 corresponds to the the number of reads in the recipient of every partial haplotype in Multi_locus_trajectories.out double SIZE2 = (partitions[i][j + 1]).size();//select the (j+1)th partial haplotype double NUM2 = atoi((partitions[i][j + 1]).at(SIZE2 - 1).c_str()); if (NUM2 > NUM1) { sort_by_recipeint = partitions[i][j]; partitions[i][j] = partitions[i][j + 1]; partitions[i][j + 1] = sort_by_recipeint; changeOccurred = true; } } } } //Uncomment the following lines if you want to see how the jth element of the ith partial haplotype set looks like for (unsigned int i = 0; i<partitions.size(); i++) { for (unsigned int j = 0; j<(partitions[i]).size(); j++) { for (unsigned int k = 0; k<(partitions[i][j]).size(); k++) { //cout << partitions[i][j][k] << " "; } //cout << endl << "--------------------------------------" << endl; } //cout << "**************************************" << endl; } vector<vector<vector<int>>> CONTRIBS; //find the contribution of the candidate set given this change at a randomly selected locus (or loci) of one haplotype for (unsigned int i = 0; i < partitions.size(); i++) { vector<vector<int>> contribs; for (unsigned int j = 0; j < (partitions[i]).size(); j++) { vector<int> Contribs; vector<string> tempa; tempa = partitions[i][j]; unsigned int sz = tempa.size(); int num = sz - 6; for (unsigned int s = 0; s < candidates.size(); s++) { int counter = 0; for (int k = 1; k < num; k++) { int tem = atoi((tempa[k]).c_str()); if ((candidates[s])[tem] == (tempa[num])[k - 1]) { counter++; } } int dum = atoi((tempa[0]).c_str()); if (counter == dum) { Contribs.push_back(s); } } contribs.push_back(Contribs); } CONTRIBS.push_back(contribs); } vector<double> init_freqs1;//set the initial frequency of candidate haplotypes for the first timepoint to be a randomly distributed number between 0 and 1 for (unsigned int i = 0; i < candidates.size() + 1; i++) { init_freqs1.push_back(gsl_rng_uniform(rgen)); } NormaliseFreqs(init_freqs1); vector<double> init_freqs1_store = init_freqs1; vector<double> init_freqs2;//set the initial frequency of candidate haplotypes for the second timepoint to be a randomly distributed number between 0 and 1 for (unsigned int i = 0; i < candidates.size() + 1; i++) { init_freqs2.push_back(gsl_rng_uniform(rgen)); } NormaliseFreqs(init_freqs2); OptimumFreqs(0, candidates, init_freqs1, CONTRIBS, partitions, c); OptimumFreqs(1, candidates, init_freqs2, CONTRIBS, partitions, c); //L_store = L_store1 + L_store2; //cout << endl << L_store1 << " + " << L_store2 << " = " << L_store << endl; //cout << L_store << endl; /*for (unsigned int i = 0; i < f_after.size(); i++) { cout << init_freqs2[i] << "\t" << f_after[i] << endl << init_freqs1[i] << "\t" << f_before[i] << endl; } cout << endl << "****************************************" << endl;*/ for (unsigned int i = 0; i < candidates.size(); i++) { if (init_freqs1[i] < 1e-7) { init_freqs1[i] = 0; } if (init_freqs2[i] < 1e-7) { init_freqs2[i] = 0; } } chdir(argv[3]); //directory to store re-inferred haplotype frequencies q** ofstream myfile; myfile.open(argv[4]); //file name for the re-inferred haplotypes for a particular segment $t for (unsigned int i = 0; i < f_after.size(); i++) { myfile << i << "\t" << init_freqs1[i] << "\t" << init_freqs2[i] << endl; } myfile.close(); return 0; } else { //cout << "No outcome_1.txt file found in " << reconstructed_haplotypes << endl; return false; } } else { //cout << "No SimulatedData_Mahan_Gene.txt file found in " << xStar << endl; return false; } }
37.589951
229
0.636226
[ "vector" ]
20190c95b613076e7e97d984e0f31fba881d1d47
24,295
cpp
C++
shell/shdocvw/winlist.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/shdocvw/winlist.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/shdocvw/winlist.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//-------------------------------------------------------------------------- // Manage the windows list, such that we can get the IDispatch for each of // the shell windows to be marshalled to different processes //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Includes... #include "priv.h" #include "sccls.h" #include <varutil.h> #include "winlist.h" #include "iedde.h" #define DM_WINLIST 0 void IEInitializeClassFactoryObject(IUnknown* punkAuto); void IERevokeClassFactoryObject(void); class CShellWindowListCF : public IClassFactory { public: // IUnKnown STDMETHODIMP QueryInterface(REFIID, void **); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); // IClassFactory STDMETHODIMP CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject); STDMETHODIMP LockServer(BOOL fLock); // constructor CShellWindowListCF(); BOOL Init(void); protected: ~CShellWindowListCF(); // locals LONG _cRef; IShellWindows *_pswWinList; }; DWORD g_dwWinListCFRegister = 0; DWORD g_fWinListRegistered = FALSE; // Only used in browser only mode... IShellWindows *g_pswWinList = NULL; // Function to get called by the tray to create the global window list and register // it with the system //=================================== Class Factory implemention ======================== CShellWindowListCF::CShellWindowListCF() { _cRef = 1; DllAddRef(); } BOOL CShellWindowListCF::Init() { HRESULT hr = CSDWindows_CreateInstance(&_pswWinList); g_pswWinList = _pswWinList; // First see if there already is one defined... if (FAILED(hr)) { TraceMsg(DM_WINLIST, "WinList_Init CoCreateInstance Failed: %x", hr); return FALSE; } // And register our class factory with the system... hr = CoRegisterClassObject(CLSID_ShellWindows, this, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &g_dwWinListCFRegister); // this call governs when we will call CoRevoke on the CF if (SUCCEEDED(hr) && g_pswWinList) { g_pswWinList->ProcessAttachDetach(TRUE); } // Create an instance of the underlying window list class... TraceMsg(DM_WINLIST, "WinList_Init CoRegisterClass: %x", hr); return SUCCEEDED(hr); } CShellWindowListCF::~CShellWindowListCF() { if (_pswWinList) { g_pswWinList = NULL; _pswWinList->Release(); } DllRelease(); } STDMETHODIMP CShellWindowListCF::QueryInterface(REFIID riid, void **ppvObj) { static const QITAB qit[] = { QITABENT(CShellWindowListCF, IClassFactory), // IID_IClassFactory { 0 }, }; return QISearch(this, qit, riid, ppvObj); } STDMETHODIMP_(ULONG) CShellWindowListCF::AddRef() { return InterlockedIncrement(&_cRef); } STDMETHODIMP_(ULONG) CShellWindowListCF::Release() { ASSERT( 0 != _cRef ); ULONG cRef = InterlockedDecrement(&_cRef); if ( 0 == cRef ) { delete this; } return cRef; } STDMETHODIMP CShellWindowListCF::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObj) { // aggregation checking is done in class factory // For now simply use our QueryService to get the dispatch. // this will do all of the things to create it and the like. if (!_pswWinList) { ASSERT(0); return E_FAIL; } return _pswWinList->QueryInterface(riid, ppvObj); } STDMETHODIMP CShellWindowListCF::LockServer(BOOL fLock) { return S_OK; // we don't do anything with this... } // As this is marshalled over to the main shell process hopefully this will take care of // most of the serialization problems. Probably still need a way to handle the case better // where a window is coming up at the same time the last one is going down... STDAPI CWinListShellProc_CreateInstance(IUnknown* pUnkOuter, IUnknown** ppunk, LPCOBJECTINFO poi) { *ppunk = NULL; if (g_dwWinListCFRegister) { return CO_E_OBJISREG; } CShellWindowListCF *pswWinList = new CShellWindowListCF; if (pswWinList) { pswWinList->Init(); // tell it to initialize // // TODO: gpease 20-MAR-2002 // Shouldn't we fail if the Init() return FALSE? // *ppunk = SAFECAST(pswWinList, IUnknown *); return S_OK; } return E_OUTOFMEMORY; } BOOL WinList_Init(void) { // Create our clas factory to register out there... TraceMsg(DM_WINLIST, "WinList_Init called"); // // If this is not a browser-only install. Register the class factory // object now with no instance. Otherwise, do it when the first instance // is created (see shbrowse.cpp). // if (!g_fBrowserOnlyProcess) { // // First, register the class factory object for CLSID_InternetExplorer. // Note that we pass NULL indicating that subsequent CreateInstance // should simply create a new instance. // IEInitializeClassFactoryObject(NULL); CShellWindowListCF *pswWinList = new CShellWindowListCF; if (pswWinList) { BOOL fRetVal = pswWinList->Init(); // tell it to initialize pswWinList->Release(); // Release our handle hopefully init registered // // Initialize IEDDE. // if (!IsBrowseNewProcessAndExplorer()) { IEDDE_Initialize(); } return fRetVal; } } else { // // Initialize IEDDE. - Done before cocreate below for timing issues // IEDDE_Initialize(); // All of the main processing moved to first call to WinList_GetShellWindows // as the creating of OLE object across processes messed up DDE timing. return TRUE; } return FALSE; } // Helper function to get the ShellWindows Object IShellWindows* WinList_GetShellWindows(BOOL fForceMarshalled) { IShellWindows *psw; if (fForceMarshalled) { psw = NULL; } else { psw = g_pswWinList; } if (psw) { // Optimize the inter-thread case by using the global WinList, // this makes opening folders much faster. psw->AddRef(); } else { SHCheckRegistry(); HRESULT hr = CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER, IID_PPV_ARG(IShellWindows, &psw)); if ( (g_fBrowserOnlyProcess || !IsInternetExplorerApp()) && !g_fWinListRegistered) { // If it failed and we are not funning in integrated mode, and this is the // first time for this process, we should then register the Window List with // the shell process. We moved that from WinList_Init as that caused us to // do interprocess send/post messages to early which caused DDE to break... g_fWinListRegistered = TRUE; // only call once if (FAILED(hr)) { SHLoadInProc(CLSID_WinListShellProc); hr = CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER, IID_PPV_ARG(IShellWindows, &psw)); } if (psw) { psw->ProcessAttachDetach(TRUE); } } // hr == REGDB_E_CLASSNOTREG when the shell process isn't running. // hr == RPC_E_CANTCALLOUT_ININPUTSYNCCALL happens durring DDE launch of IE. // should investigate, but removing assert for IE5 ship. if (!(SUCCEEDED(hr) || hr == REGDB_E_CLASSNOTREG || hr == RPC_E_CANTCALLOUT_ININPUTSYNCCALL)) { TraceMsg(TF_WARNING, "WinList_GetShellWindows CoCreateInst(CLSID_ShellWindows) failed %x", hr); } } return psw; } // Function to terminate our use of the window list. void WinList_Terminate(void) { // Lets release everything in a thread safe way... TraceMsg(DM_WINLIST, "WinList_Terminate called"); IEDDE_Uninitialize(); // Release our usage of the object to allow the system to clean it up if (!g_fBrowserOnlyProcess) { // this is the explorer process, and we control the vertical if (g_dwWinListCFRegister) { IShellWindows* psw = WinList_GetShellWindows(FALSE); if (psw) { #ifdef DEBUG long cwindow = -1; psw->get_Count(&cwindow); if (cwindow != 0) { TraceMsg(DM_ERROR, "wl_t: cwindow=%d (!=0)", cwindow); } #endif psw->ProcessAttachDetach(FALSE); psw->Release(); } // the processattachdetach() should kill the CF in our process if (g_dwWinListCFRegister != 0) { TraceMsg(DM_ERROR, "wl_t: g_dwWinListCFRegister=%d (!=0)", g_dwWinListCFRegister); } } IERevokeClassFactoryObject(); CUrlHistory_CleanUp(); } else { if (g_fWinListRegistered) { // only do this if we actually registered... IShellWindows* psw = WinList_GetShellWindows(TRUE); if (psw) { psw->ProcessAttachDetach(FALSE); // Tell it we are going away... psw->Release(); } } } } STDAPI WinList_Revoke(long dwRegister) { IShellWindows* psw = WinList_GetShellWindows(TRUE); HRESULT hr = E_FAIL; TraceMsg(DM_WINLIST, "WinList_Reevoke called on %x", dwRegister); if (psw) { hr = psw->Revoke((long)dwRegister); if (FAILED(hr)) { TraceMsg(TF_WARNING, "WinList_Revoke(%x) failed. hresult = %x", dwRegister, hr); } psw->Release(); } return hr; } STDAPI WinList_NotifyNewLocation(IShellWindows* psw, long dwRegister, LPCITEMIDLIST pidl) { HRESULT hr = E_UNEXPECTED; if (pidl) { VARIANT var; hr = InitVariantFromIDList(&var, pidl); if (SUCCEEDED(hr)) { hr = psw->OnNavigate(dwRegister, &var); VariantClearLazy(&var); } } return hr; } // Register with the window list that we have a pidl that we are starting up. STDAPI WinList_RegisterPending(DWORD dwThread, LPCITEMIDLIST pidl, LPCITEMIDLIST pidlRoot, long *pdwRegister) { HRESULT hr = E_UNEXPECTED; ASSERT(!pidlRoot); if (pidl) { IShellWindows* psw = WinList_GetShellWindows(FALSE); if (psw) { VARIANT var; hr = InitVariantFromIDList(&var, pidl); if (SUCCEEDED(hr)) { hr = psw->RegisterPending(dwThread, &var, PVAREMPTY, SWC_BROWSER, pdwRegister); VariantClearLazy(&var); } } } return hr; } /* * PERFORMANCE note - getting back the automation object (ppauto) is really * expensive due to the marshalling overhead. Don't query for it unless you * absolutely need it! */ STDAPI WinList_FindFolderWindow(LPCITEMIDLIST pidl, LPCITEMIDLIST pidlRoot, HWND *phwnd, IWebBrowserApp **ppauto) { HRESULT hr = E_UNEXPECTED; ASSERT(!pidlRoot); if (ppauto) { *ppauto = NULL; } if (phwnd) { *phwnd = NULL; } if (pidl) { // Try a cached psw if we don't need ppauto IShellWindows* psw = WinList_GetShellWindows(ppauto != NULL); if (psw) { VARIANT var; hr = InitVariantFromIDList(&var, pidl); if (SUCCEEDED(hr)) { IDispatch* pdisp = NULL; hr = psw->FindWindowSW(&var, PVAREMPTY, SWC_BROWSER, (long *)phwnd, ppauto ? (SWFO_NEEDDISPATCH | SWFO_INCLUDEPENDING) : SWFO_INCLUDEPENDING, &pdisp); if (pdisp) { // if this fails it's because we are inside SendMessage loop and ole doesn't like it if (ppauto) { hr = pdisp->QueryInterface(IID_PPV_ARG(IWebBrowserApp, ppauto)); } pdisp->Release(); } VariantClearLazy(&var); } psw->Release(); } } return hr; } // Support for Being able to open a folder and get it's idispatch... // class CWaitForWindow { public: ULONG AddRef(void); ULONG Release(void); BOOL Init(IShellWindows *psw, LPCITEMIDLIST pidl, DWORD dwPending); void CleanUp(void); HRESULT WaitForWindowToOpen(DWORD dwTimeout); CWaitForWindow(void); private: ~CWaitForWindow(void); // internal class to watch for events... class CWindowEvents : public DShellWindowsEvents { public: // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void ** ppvObj); STDMETHODIMP_(ULONG) AddRef(void) ; STDMETHODIMP_(ULONG) Release(void); // IDispatch STDMETHOD(GetTypeInfoCount)(THIS_ UINT * pctinfo); STDMETHOD(GetTypeInfo)(THIS_ UINT itinfo, LCID lcid, ITypeInfo * * pptinfo); STDMETHOD(GetIDsOfNames)(THIS_ REFIID riid, OLECHAR * * rgszNames, UINT cNames, LCID lcid, DISPID * rgdispid); STDMETHOD(Invoke)(THIS_ DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pdispparams, VARIANT * pvarResult, EXCEPINFO * pexcepinfo, UINT * puArgErr); } m_EventHandler; friend class CWindowEvents; LONG m_cRef; DWORD m_dwCookie; IShellWindows *m_psw; IConnectionPoint *m_picp; DWORD m_dwPending; LPITEMIDLIST m_pidl; HANDLE m_hevent; BOOL m_fAdvised; }; ULONG CWaitForWindow::AddRef(void) { return InterlockedIncrement(&m_cRef); } ULONG CWaitForWindow::Release(void) { ASSERT( 0 != m_cRef ); ULONG cRef = InterlockedDecrement(&m_cRef); if ( 0 == cRef ) { delete this; } return cRef; } CWaitForWindow::CWaitForWindow(void) : m_cRef(1) { ASSERT(m_psw == NULL); ASSERT(m_picp == NULL); ASSERT(m_hevent == NULL); ASSERT(m_dwCookie == 0); ASSERT(m_fAdvised == FALSE); } CWaitForWindow::~CWaitForWindow(void) { ATOMICRELEASE(m_psw); CleanUp(); if (m_hevent) { CloseHandle(m_hevent); } if (m_pidl) { ILFree(m_pidl); } } BOOL CWaitForWindow::Init(IShellWindows *psw, LPCITEMIDLIST pidl, DWORD dwPending) { // First try to create an event object m_hevent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!m_hevent) return FALSE; // We do not have a window or it is pending... // first lets setup that we want to be notified of new windows. if (FAILED(ConnectToConnectionPoint(SAFECAST(&m_EventHandler, IDispatch*), DIID_DShellWindowsEvents, TRUE, psw, &m_dwCookie, &m_picp))) return FALSE; // Save away passed in stuff that we care about. m_psw = psw; psw->AddRef(); m_pidl = ILClone(pidl); m_dwPending = dwPending; return TRUE; } void CWaitForWindow::CleanUp(void) { // Don't need to listen anmore. if (m_dwCookie) { m_picp->Unadvise(m_dwCookie); m_dwCookie = 0; } ATOMICRELEASE(m_picp); } HRESULT CWaitForWindow::WaitForWindowToOpen(DWORD dwTimeOut) { if (!m_hevent || !m_dwCookie) return E_FAIL; ENTERCRITICAL; if (!m_fAdvised) { ResetEvent(m_hevent); } LEAVECRITICAL; DWORD dwStart = GetTickCount(); DWORD dwWait = dwTimeOut; DWORD dwWaitResult; do { dwWaitResult = MsgWaitForMultipleObjects(1, &m_hevent, FALSE, // fWaitAll, wait for any one dwWait, QS_ALLINPUT); // Check if we are signaled for a send message. if (dwWaitResult != WAIT_OBJECT_0 + 1) { break; // No. Break out of the loop. } // We may need to dispatch stuff here. MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // than MSEC_MAXWAIT if we wait more than that. dwWait = dwStart+dwTimeOut - GetTickCount(); } while (dwWait <= dwTimeOut); BOOL fAdvised; { ENTERCRITICAL; fAdvised = m_fAdvised; m_fAdvised = FALSE; LEAVECRITICAL; } return fAdvised ? S_OK : E_FAIL; } STDMETHODIMP CWaitForWindow::CWindowEvents::QueryInterface(REFIID riid, void **ppv) { static const QITAB qit[] = { QITABENTMULTI2(CWaitForWindow::CWindowEvents, DIID_DShellWindowsEvents, DShellWindowsEvents), QITABENTMULTI(CWaitForWindow::CWindowEvents, IDispatch, DShellWindowsEvents), { 0 }, }; return QISearch(this, qit, riid, ppv); } ULONG CWaitForWindow::CWindowEvents::AddRef(void) { CWaitForWindow* pdfwait = IToClass(CWaitForWindow, m_EventHandler, this); return pdfwait->AddRef(); } ULONG CWaitForWindow::CWindowEvents::Release(void) { CWaitForWindow* pdfwait = IToClass(CWaitForWindow, m_EventHandler, this); return pdfwait->Release(); } HRESULT CWaitForWindow::CWindowEvents::GetTypeInfoCount(UINT *pctinfo) { return E_NOTIMPL; } HRESULT CWaitForWindow::CWindowEvents::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo **pptinfo) { return E_NOTIMPL; } HRESULT CWaitForWindow::CWindowEvents::GetIDsOfNames(REFIID riid, OLECHAR **rgszNames, UINT cNames, LCID lcid, DISPID *rgdispid) { return E_NOTIMPL; } HRESULT CWaitForWindow::CWindowEvents::Invoke(DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pdispparams, VARIANT * pvarResult, EXCEPINFO * pexcepinfo, UINT * puArgErr) { CWaitForWindow* pdfwait = IToClass(CWaitForWindow, m_EventHandler, this); if (dispid == DISPID_WINDOWREGISTERED) { ENTERCRITICAL; // Signal the event pdfwait->m_fAdvised = TRUE; ::SetEvent(pdfwait->m_hevent); LEAVECRITICAL; } return S_OK; } // WARNING:: this assumes not rooted STDAPI SHGetIDispatchForFolder(LPCITEMIDLIST pidl, IWebBrowserApp **ppauto) { HRESULT hr = E_UNEXPECTED; if (ppauto) { *ppauto = NULL; } if (!pidl) return E_POINTER; // Try a cached psw if we don't need ppauto IShellWindows* psw = WinList_GetShellWindows(ppauto != NULL); if (psw) { VARIANT var; hr = InitVariantFromIDList(&var, pidl); if (SUCCEEDED(hr)) { LONG lhwnd; IDispatch* pdisp; hr = psw->FindWindowSW(&var, PVAREMPTY, SWC_BROWSER, &lhwnd, ppauto ? (SWFO_NEEDDISPATCH | SWFO_INCLUDEPENDING) : SWFO_INCLUDEPENDING, &pdisp); if ((hr == E_PENDING) || (hr == S_FALSE)) { HRESULT hrOld = hr; hr = E_FAIL; CWaitForWindow *pdfwait = new CWaitForWindow(); // Setup a wait object... if (pdfwait) { if (pdfwait->Init(psw, pidl, 0)) { if (hrOld == S_FALSE) { // Startup opening a new window SHELLEXECUTEINFO sei = {sizeof(sei)}; sei.lpIDList = (void *)pidl; // // WARNING - old versions of ShellExec() didnt pay attention - ZekeL - 30-DEC-98 // to whether the hwnd is in the same process or not, // and so could fault in TryDDEShortcut(). // only pass the hwnd if the shell window shares // the same process. // sei.hwnd = GetShellWindow(); DWORD idProcess; GetWindowThreadProcessId(sei.hwnd, &idProcess); if (idProcess != GetCurrentProcessId()) { sei.hwnd = NULL; } // Everything should have been initialize to NULL(0) sei.fMask = SEE_MASK_IDLIST | SEE_MASK_FLAG_DDEWAIT; sei.nShow = SW_SHOWNORMAL; hr = ShellExecuteEx(&sei) ? S_OK : S_FALSE; } while ((hr = psw->FindWindowSW(&var, PVAREMPTY, SWC_BROWSER, &lhwnd, ppauto ? (SWFO_NEEDDISPATCH | SWFO_INCLUDEPENDING) : SWFO_INCLUDEPENDING, &pdisp)) != S_OK) { if (FAILED(pdfwait->WaitForWindowToOpen(20 * 1000))) { hr = E_ABORT; break; } } } pdfwait->CleanUp(); // No need to watch things any more... pdfwait->Release(); // release our use of this object... } } if (hr == S_OK && ppauto) { // if this fails this is because we are inside SendMessage loop hr = pdisp->QueryInterface(IID_PPV_ARG(IWebBrowserApp, ppauto)); } if (pdisp) { pdisp->Release(); } VariantClear(&var); } psw->Release(); } return hr; } #undef VariantCopy WINOLEAUTAPI VariantCopyLazy(VARIANTARG * pvargDest, VARIANTARG * pvargSrc) { VariantClearLazy(pvargDest); switch(pvargSrc->vt) { case VT_I4: case VT_UI4: case VT_BOOL: // we can add more *pvargDest = *pvargSrc; return S_OK; case VT_UNKNOWN: if (pvargDest) { *pvargDest = *pvargSrc; if (pvargDest->punkVal) pvargDest->punkVal->AddRef(); return S_OK; } ASSERT(0); return E_INVALIDARG; } return VariantCopy(pvargDest, pvargSrc); } // // WARNING: This function must be placed at the end because we #undef // VariantClear // #undef VariantClear HRESULT VariantClearLazy(VARIANTARG *pvarg) { switch(pvarg->vt) { case VT_I4: case VT_UI4: case VT_EMPTY: case VT_BOOL: // No operation break; case VT_UNKNOWN: if(V_UNKNOWN(pvarg) != NULL) V_UNKNOWN(pvarg)->Release(); break; case VT_DISPATCH: if(V_DISPATCH(pvarg) != NULL) V_DISPATCH(pvarg)->Release(); break; case VT_SAFEARRAY: THR(SafeArrayDestroy(V_ARRAY(pvarg))); break; default: return VariantClear(pvarg); } V_VT(pvarg) = VT_EMPTY; return S_OK; }
28.515258
140
0.550278
[ "object" ]
201d531c6a3816d47aa9658bef53e6a73736cb13
50,828
cc
C++
src/bgp/test/bgp_mvpn_integration_test.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
37
2020-09-21T10:42:26.000Z
2022-01-09T10:16:40.000Z
src/bgp/test/bgp_mvpn_integration_test.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
null
null
null
src/bgp/test/bgp_mvpn_integration_test.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
21
2020-08-25T12:48:42.000Z
2022-03-22T04:32:18.000Z
/* * Copyright (c) 2017 Juniper Networks, Inc. All rights reserved. */ #include <boost/foreach.hpp> #include <boost/format.hpp> #include "bgp/bgp_config.h" #include "bgp/bgp_config_parser.h" #include "bgp/bgp_factory.h" #include "bgp/bgp_multicast.h" #include "bgp/bgp_mvpn.h" #include "bgp/bgp_sandesh.h" #include "bgp/bgp_session_manager.h" #include "bgp/bgp_xmpp_channel.h" #include "bgp/inet/inet_table.h" #include "bgp/ermvpn/ermvpn_table.h" #include "bgp/mvpn/mvpn_table.h" #include "bgp/test/bgp_server_test_util.h" #include "bgp/xmpp_message_builder.h" #include "io/test/event_manager_test.h" #include "control-node/control_node.h" #include "control-node/test/network_agent_mock.h" #include "sandesh/sandesh.h" #include "sandesh/sandesh_server.h" #include "schema/xmpp_multicast_types.h" #include "schema/xmpp_mvpn_types.h" #include "xmpp/xmpp_factory.h" #include "xmpp/test/xmpp_test_util.h" using namespace autogen; using namespace std; using namespace test; using boost::format; #define kFabricInstance BgpConfigManager::kFabricInstance // enable it for introspect of 2nd controller #define SANDESH_Y false class SandeshServerTest : public SandeshServer { public: SandeshServerTest(EventManager *evm) : SandeshServer(evm, SandeshConfig()) { } virtual ~SandeshServerTest() { } virtual bool ReceiveSandeshMsg(SandeshSession *session, const SandeshMessage *msg, bool rsc) { return true; } private: }; class BgpMvpnIntegrationTest { public: BgpMvpnIntegrationTest() : thread_(&evm_), xs_x_(NULL), red_(NULL), blue_(NULL), green_(NULL), red_inet_(NULL), green_inet_(NULL) { } virtual void SetUp() { bs_x_.reset(new BgpServerTest(&evm_, "X")); bs_x_->set_mvpn_ipv4_enable(true); xs_x_ = new XmppServer(&evm_, XmppDocumentMock::kControlNodeJID); bs_x_->session_manager()->Initialize(0); xs_x_->Initialize(0, false); bcm_x_.reset(new BgpXmppChannelManager(xs_x_, bs_x_.get())); #if !SANDESH_Y SandeshStartup(); sandesh_context_->bgp_server = bs_x_.get(); sandesh_context_->xmpp_peer_manager = bcm_x_.get(); #endif thread_.Start(); } virtual void TearDown() { xs_x_->Shutdown(); task_util::WaitForIdle(); bs_x_->Shutdown(); task_util::WaitForIdle(); bcm_x_.reset(); TcpServerManager::DeleteServer(xs_x_); xs_x_ = NULL; agent_xa_->Delete(); agent_xb_->Delete(); agent_xc_->Delete(); if (red_) delete[] red_; if (blue_) delete[] blue_; if (green_) delete[] green_; if (red_inet_) delete[] red_inet_; if (green_inet_) delete[] green_inet_; #if !SANDESH_Y SandeshShutdown(); task_util::WaitForIdle(); sandesh_context_.reset(); #endif evm_.Shutdown(); thread_.Join(); task_util::WaitForIdle(); } virtual void SessionUp() { agent_xa_.reset(new NetworkAgentMock( &evm_, "agent-xa", xs_x_->GetPort(), "127.0.0.1", "127.0.0.101")); TASK_UTIL_EXPECT_TRUE(agent_xa_->IsEstablished()); agent_xb_.reset(new NetworkAgentMock( &evm_, "agent-xb", xs_x_->GetPort(), "127.0.0.2", "127.0.0.101")); TASK_UTIL_EXPECT_TRUE(agent_xb_->IsEstablished()); agent_xc_.reset(new NetworkAgentMock( &evm_, "agent-xc", xs_x_->GetPort(), "127.0.0.3", "127.0.0.101")); TASK_UTIL_EXPECT_TRUE(agent_xc_->IsEstablished()); } virtual void SessionDown() { agent_xa_->SessionDown(); agent_xb_->SessionDown(); agent_xc_->SessionDown(); task_util::WaitForIdle(); } virtual void Subscribe(const string net, int id) { if (net == kFabricInstance) { agent_xa_->SubscribeAll(net, id); agent_xb_->SubscribeAll(net, id); agent_xc_->SubscribeAll(net, id); task_util::WaitForIdle(); return; } for (size_t i = 1; i <= instance_count_; i++) { ostringstream r; r << net << i; agent_xa_->SubscribeAll(r.str(), id); agent_xb_->SubscribeAll(r.str(), id); agent_xc_->SubscribeAll(r.str(), id); task_util::WaitForIdle(); } } string getRouteTarget (int i, string suffix) const { ostringstream os; os << "target:127.0.0.1:1" << format("%|03|")%i << suffix; return os.str(); } const string GetConfig() const { ostringstream os; os << "<?xml version='1.0' encoding='utf-8'?>" "<config>" " <bgp-router name=\"X\">" " <identifier>192.168.0.101</identifier>" " <address>127.0.0.101</address>" " </bgp-router>" ""; os << " <virtual-network name='default-domain:default-project:ip-fabric:ip-fabric'>" " <network-id>101</network-id>" " </virtual-network>" " <routing-instance name='default-domain:default-project:ip-fabric:ip-fabric'>" " <virtual-network>default-domain:default-project:ip-fabric:ip-fabric" "</virtual-network>" " <vrf-target>target:127.0.0.1:60000</vrf-target>" " </routing-instance>"; for (size_t i = 1; i <= instance_count_; i++) { os << " <virtual-network name='red" << i << "'>" " <network-id>" << 200+i << "</network-id>" " </virtual-network>" " <routing-instance name='red" << i << "'>" " <virtual-network>red" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "1") << "</vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "3") << " </vrf-target>" " </routing-instance>" " <virtual-network name='blue" << i << "'>" " <network-id>" << 300+i << "</network-id>" " </virtual-network>" " <routing-instance name='blue" << i << "'>" " <virtual-network>blue" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "2") << "</vrf-target>" " </routing-instance>" " <virtual-network name='green" << i << "'>" " <network-id>" << 400+i << "</network-id>" " </virtual-network>" " <routing-instance name='green" << i << "'>" " <virtual-network>green" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "3") << "</vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "1") << " </vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "2") << " </vrf-target>" " </routing-instance>" ; } os << "</config>"; return os.str(); } virtual void Configure(const char *config_tmpl) { char config[8192]; snprintf(config, sizeof(config), config_tmpl, bs_x_->session_manager()->GetPort()); bs_x_->Configure(config); } int GetLabel(const NetworkAgentMock *agent, const string &net, const string &prefix) { const NetworkAgentMock::McastRouteEntry *rt = agent->McastRouteLookup(net, prefix); return (rt ? rt->entry.nlri.source_label : 0); } int CheckErmvpnOListSize( boost::shared_ptr<const NetworkAgentMock> agent, const string &prefix) { const NetworkAgentMock::McastRouteEntry *ermvpn_rt = agent->McastRouteLookup(kFabricInstance, prefix); if (ermvpn_rt == NULL) return false; const OlistType &olist = ermvpn_rt->entry.olist; return olist.next_hop.size(); } bool CheckOListElem(boost::shared_ptr<const NetworkAgentMock> agent, const string &net, const string &prefix, size_t olist_size, const string &address, const string &encap, const string &source_address, const NetworkAgentMock *other_agent) { const NetworkAgentMock::MvpnRouteEntry *mvpn_rt = agent->MvpnRouteLookup(net, prefix); if (mvpn_rt == NULL) return false; const NetworkAgentMock::McastRouteEntry *ermvpn_rt = other_agent->McastRouteLookup(kFabricInstance, prefix); if (ermvpn_rt == NULL) return false; if (!(ermvpn_rt->entry.nlri.source_address == source_address)) return false; int label = GetLabel(other_agent, kFabricInstance, prefix); if (label == 0) return false; vector<string> tunnel_encapsulation; if (encap == "all") { tunnel_encapsulation.push_back("gre"); tunnel_encapsulation.push_back("udp"); } else if (!encap.empty()) { tunnel_encapsulation.push_back(encap); } sort(tunnel_encapsulation.begin(), tunnel_encapsulation.end()); const MvpnOlistType &olist = mvpn_rt->entry.olist; if (olist.next_hop.size() != olist_size) return false; for (MvpnOlistType::const_iterator it = olist.begin(); it != olist.end(); ++it) { if (it->address == address) { if (it->tunnel_encapsulation_list.tunnel_encapsulation != tunnel_encapsulation) return false; if (it->label != label) return false; return true; } } return false; } void VerifyOListAndSource(boost::shared_ptr<const NetworkAgentMock> agent, const string &net, const string &prefix, size_t olist_size, const string &address, const string source_address, boost::shared_ptr<NetworkAgentMock> other_agent, const string &encap = "") { TASK_UTIL_EXPECT_TRUE( CheckOListElem(agent, net, prefix, olist_size, address, encap, source_address, other_agent.get())); } bool VerifyMvpnRouteType(boost::shared_ptr<const NetworkAgentMock> agent, const string &net, const string &prefix, int route_type = MvpnPrefix::SourceTreeJoinRoute) { const NetworkAgentMock::MvpnRouteEntry *mvpn_rt = agent->MvpnRouteLookup(net, prefix); if (mvpn_rt == NULL) return false; if (mvpn_rt->entry.nlri.route_type == route_type) return true; return false; } void SandeshStartup(); void SandeshShutdown(); void TableInit() { master_ = static_cast<BgpTable *>( bs_x_->database()->FindTable("bgp.mvpn.0")); ostringstream os; os << "default-domain:default-project:ip-fabric:ip-fabric"; os << ".ermvpn.0"; ostringstream os2; os2 << "default-domain:default-project:ip-fabric:ip-fabric"; os2 << ".mvpn.0"; fabric_ermvpn_ = dynamic_cast<ErmVpnTable *>( bs_x_->database()->FindTable(os.str())); fabric_mvpn_ = dynamic_cast<MvpnTable *>( bs_x_->database()->FindTable(os2.str())); for (size_t i = 1; i <= instance_count_; i++) { ostringstream r, b, g, ri, gi; r << "red" << i << ".mvpn.0"; b << "blue" << i << ".mvpn.0"; g << "green" << i << ".mvpn.0"; ri << "red" << i << ".inet.0"; gi << "green" << i << ".inet.0"; TASK_UTIL_EXPECT_NE(static_cast<BgpTable *>(NULL), bs_x_->database()->FindTable(r.str())); TASK_UTIL_EXPECT_NE(static_cast<BgpTable *>(NULL), bs_x_->database()->FindTable(b.str())); TASK_UTIL_EXPECT_NE(static_cast<BgpTable *>(NULL), bs_x_->database()->FindTable(g.str())); red_[i-1] = static_cast<MvpnTable *>( bs_x_->database()->FindTable(r.str())); blue_[i-1] = static_cast<MvpnTable *>( bs_x_->database()->FindTable(b.str())); green_[i-1] = static_cast<MvpnTable *>( bs_x_->database()->FindTable(g.str())); red_inet_[i-1] = static_cast<InetTable *>( bs_x_->database()->FindTable(ri.str())); green_inet_[i-1] = static_cast<InetTable *>( bs_x_->database()->FindTable(gi.str())); } } EventManager evm_; ServerThread thread_; BgpServerTestPtr bs_x_; XmppServer *xs_x_; boost::scoped_ptr<BgpXmppChannelManager> bcm_x_; boost::shared_ptr<NetworkAgentMock> agent_xa_; boost::shared_ptr<NetworkAgentMock> agent_xb_; boost::shared_ptr<NetworkAgentMock> agent_xc_; BgpTable *master_; ErmVpnTable *fabric_ermvpn_; MvpnTable **red_; MvpnTable **blue_; MvpnTable **green_; MvpnTable *fabric_mvpn_; InetTable **red_inet_; InetTable **green_inet_; SandeshServerTest *sandesh_bs_x_; boost::scoped_ptr<BgpSandeshContext> sandesh_context_; size_t instance_count_; }; void BgpMvpnIntegrationTest::SandeshStartup() { sandesh_context_.reset(new BgpSandeshContext()); // Initialize SandeshServer. sandesh_bs_x_ = new SandeshServerTest(&evm_); sandesh_bs_x_->Initialize(0); boost::system::error_code error; string hostname(boost::asio::ip::host_name(error)); Sandesh::InitGenerator("BgpUnitTestSandeshClient", hostname, "BgpTest", "Test", &evm_, 0, sandesh_context_.get()); Sandesh::ConnectToCollector("127.0.0.1", sandesh_bs_x_->GetPort()); task_util::WaitForIdle(); cout << "Introspect at http://localhost:" << Sandesh::http_port() << endl; } void BgpMvpnIntegrationTest::SandeshShutdown() { Sandesh::Uninit(); task_util::WaitForIdle(); sandesh_bs_x_->Shutdown(); task_util::WaitForIdle(); TcpServerManager::DeleteServer(sandesh_bs_x_); sandesh_bs_x_ = NULL; task_util::WaitForIdle(); } class BgpMvpnOneControllerTest : public BgpMvpnIntegrationTest, public ::testing::TestWithParam<int> { public: static const int kTimeoutSeconds = 15; virtual void SetUp() { BgpMvpnIntegrationTest::SetUp(); instance_count_ = GetParam(); red_ = new MvpnTable *[instance_count_]; blue_ = new MvpnTable *[instance_count_]; green_ = new MvpnTable *[instance_count_]; red_inet_ = new InetTable *[instance_count_]; green_inet_ = new InetTable *[instance_count_]; string config = GetConfig(); Configure(config.c_str()); task_util::WaitForIdle(); BgpMvpnIntegrationTest::TableInit(); BgpMvpnIntegrationTest::SessionUp(); } virtual void TearDown() { BgpMvpnIntegrationTest::SessionDown(); BgpMvpnIntegrationTest::TearDown(); } }; TEST_P(BgpMvpnOneControllerTest, Basic) { for (size_t i = 1; i <= instance_count_; i++) { // 1 type1 from red and 1 from green TASK_UTIL_EXPECT_EQ(2, red_[i-1]->Size()); TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), red_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_EQ(1, blue_[i-1]->Size()); TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), blue_[i-1]->FindType1ADRoute()); // 1 type1 from red, blue and green TASK_UTIL_EXPECT_EQ(3, green_[i-1]->Size()); TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), green_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_EQ(1, fabric_mvpn_->Size()); TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), fabric_mvpn_->FindType1ADRoute()); } // red, blue, green, kFabricInstance TASK_UTIL_EXPECT_EQ(1 + 3 * instance_count_, master_->Size()); // Register agents and add source active mvpn routes Subscribe("red", 1); Subscribe("green", 2); Subscribe(kFabricInstance, 1000); for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; NextHop nexthop_red("10.1.1.2", 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.0/24", nexthop_red, attr); task_util::WaitForIdle(); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), "10.1.1.2"); task_util::WaitForIdle(); // Verify that Type5 route gets added TASK_UTIL_EXPECT_EQ(3, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(1, blue_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(4, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(1, red_inet_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(1, green_inet_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(2 + 3*instance_count_ + 4*(i-1), master_->Size()); ostringstream grn; grn << "green" << i; agent_xb_->AddType7MvpnRoute(grn.str(), sg.str(), "10.1.1.3", "30-40"); // Type7, Type3, Type4 routes should have generated TASK_UTIL_EXPECT_EQ(3*i, fabric_ermvpn_->Size()); TASK_UTIL_EXPECT_EQ(7, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(1, blue_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(6, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(1 + 3 * instance_count_ + 4 * i, master_->Size()); // Verify that sender should have received a route TASK_UTIL_EXPECT_EQ(0, agent_xa_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_xb_->McastRouteCount()); // Receiver TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); // Sender TASK_UTIL_EXPECT_EQ((int)i, agent_xb_->MvpnRouteCount()); TASK_UTIL_EXPECT_TRUE(VerifyMvpnRouteType( agent_xb_, grn.str(), sg.str())); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.1.3", "192.168.0.101", agent_xb_); TASK_UTIL_EXPECT_EQ(0, CheckErmvpnOListSize(agent_xb_, sg.str())); // Add a receiver in red agent_xa_->AddMcastRoute(kFabricInstance, sg.str(), "10.1.1.3", "50-60"); // ermvpn route olist size will increase TASK_UTIL_EXPECT_EQ(1, CheckErmvpnOListSize(agent_xb_, sg.str())); // No change in mvpn route olist VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.1.3", "192.168.0.101", agent_xb_); agent_xa_->DeleteMcastRoute(kFabricInstance, sg.str()); } } class BgpMvpnTwoControllerTest : public BgpMvpnIntegrationTest, public ::testing::TestWithParam<int> { protected: BgpMvpnTwoControllerTest() : BgpMvpnIntegrationTest(), red_y_(NULL), blue_y_(NULL), green_y_(NULL) { } virtual void Configure(const char *config_tmpl) { char config[8192]; snprintf(config, sizeof(config), config_tmpl, bs_x_->session_manager()->GetPort(), bs_y_->session_manager()->GetPort()); bs_x_->Configure(config); bs_y_->Configure(config); task_util::WaitForIdle(); } virtual void ReConfigure(const char *config_tmpl) { bs_x_->Configure(config_tmpl); bs_y_->Configure(config_tmpl); task_util::WaitForIdle(); } virtual void SessionUp() { BgpMvpnIntegrationTest::SessionUp(); agent_ya_.reset(new NetworkAgentMock( &evm_, "agent-ya", xs_y_->GetPort(), "127.0.0.4", "127.0.0.102")); TASK_UTIL_EXPECT_TRUE(agent_ya_->IsEstablished()); agent_yb_.reset(new NetworkAgentMock( &evm_, "agent-yb", xs_y_->GetPort(), "127.0.0.5", "127.0.0.102")); TASK_UTIL_EXPECT_TRUE(agent_yb_->IsEstablished()); agent_yc_.reset(new NetworkAgentMock( &evm_, "agent-yc", xs_y_->GetPort(), "127.0.0.6", "127.0.0.102")); TASK_UTIL_EXPECT_TRUE(agent_yc_->IsEstablished()); } const string GetDeleteGreenConfig(size_t i) const { ostringstream os; os << "<?xml version='1.0' encoding='utf-8'?>" "<delete>" " <routing-instance name='green" << i << "'>" " <vrf-target>" << getRouteTarget(i, "3") << "</vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "1") << " </vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "2") << " </vrf-target>" " </routing-instance>" ; os << "</delete>"; return os.str(); } const string GetIdentifierChangeConfig() const { ostringstream os; os << "<?xml version='1.0' encoding='utf-8'?>" "<config>" " <bgp-router name=\"X\">" " <identifier>192.168.0.201</identifier>" " <port>%d</port>" " </bgp-router>" " <bgp-router name=\"Y\">" " <identifier>192.168.0.202</identifier>" " <port>%d</port>" " </bgp-router>" ; os << "</config>"; return os.str(); } const string GetConfig() const { ostringstream os; os << "<?xml version='1.0' encoding='utf-8'?>" "<config>" " <bgp-router name=\"X\">" " <identifier>192.168.0.101</identifier>" " <address>127.0.0.101</address>" " <port>%d</port>" " <session to=\'Y\'>" " <address-families>" " <family>inet</family>" " <family>inet-vpn</family>" " <family>inet-mvpn</family>" " <family>erm-vpn</family>" " <family>route-target</family>" " </address-families>" " </session>" " </bgp-router>" " <bgp-router name=\"Y\">" " <identifier>192.168.0.102</identifier>" " <address>127.0.0.102</address>" " <port>%d</port>" " <session to=\'X\'>" " <address-families>" " <family>inet</family>" " <family>inet-vpn</family>" " <family>inet-mvpn</family>" " <family>erm-vpn</family>" " <family>route-target</family>" " </address-families>" " </session>" " </bgp-router>" ""; os << " <virtual-network name='default-domain:default-project:ip-fabric:ip-fabric'>" " <network-id>101</network-id>" " </virtual-network>" " <routing-instance name='default-domain:default-project:ip-fabric:ip-fabric'>" " <virtual-network>default-domain:default-project:ip-fabric:ip-fabric" "</virtual-network>" " <vrf-target>target:127.0.0.1:60000</vrf-target>" " </routing-instance>"; for (size_t i = 1; i <= instance_count_; i++) { os << " <virtual-network name='red" << i << "'>" " <network-id>" << 200+i << "</network-id>" " </virtual-network>" " <routing-instance name='red" << i << "'>" " <virtual-network>red" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "1") << "</vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "3") << " </vrf-target>" " </routing-instance>" " <virtual-network name='blue" << i << "'>" " <network-id>" << 300+i << "</network-id>" " </virtual-network>" " <routing-instance name='blue" << i << "'>" " <virtual-network>blue" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "2") << "</vrf-target>" " </routing-instance>" " <virtual-network name='green" << i << "'>" " <network-id>" << 400+i << "</network-id>" " </virtual-network>" " <routing-instance name='green" << i << "'>" " <virtual-network>green" << i << "</virtual-network>" " <vrf-target>" << getRouteTarget(i, "3") << "</vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "1") << " </vrf-target>" " <vrf-target>" " <import-export>import</import-export>" << getRouteTarget(i, "2") << " </vrf-target>" " </routing-instance>" ; } os << "</config>"; return os.str(); } void TableInit() { BgpMvpnIntegrationTest::TableInit(); master_y_ = static_cast<BgpTable *>( bs_y_->database()->FindTable("bgp.mvpn.0")); ostringstream os; os << "default-domain:default-project:ip-fabric:ip-fabric"; os << ".ermvpn.0"; fabric_ermvpn_ = dynamic_cast<ErmVpnTable *>( bs_y_->database()->FindTable(os.str())); for (size_t i = 1; i <= instance_count_; i++) { ostringstream r, b, g, ri, gi; r << "red" << i << ".mvpn.0"; b << "blue" << i << ".mvpn.0"; g << "green" << i << ".mvpn.0"; red_y_[i-1] = static_cast<MvpnTable *>( bs_y_->database()->FindTable(r.str())); blue_y_[i-1] = static_cast<MvpnTable *>( bs_y_->database()->FindTable(b.str())); green_y_[i-1] = static_cast<MvpnTable *>( bs_y_->database()->FindTable(g.str())); } } void SandeshYStartup() { sandesh_context_y_.reset(new BgpSandeshContext()); // Initialize SandeshServer. sandesh_bs_y_ = new SandeshServerTest(&evm_); sandesh_bs_y_->Initialize(0); boost::system::error_code error; string hostname(boost::asio::ip::host_name(error)); Sandesh::InitGenerator("BgpUnitTestSandeshClient", hostname, "BgpTest", "Test", &evm_, 0, sandesh_context_y_.get()); Sandesh::ConnectToCollector("127.0.0.1", sandesh_bs_y_->GetPort()); task_util::WaitForIdle(); cout << "Introspect for Y at http://localhost:" << Sandesh::http_port() << endl; } void SandeshYShutdown() { Sandesh::Uninit(); task_util::WaitForIdle(); sandesh_bs_y_->Shutdown(); task_util::WaitForIdle(); TcpServerManager::DeleteServer(sandesh_bs_y_); sandesh_bs_y_ = NULL; task_util::WaitForIdle(); } virtual void SetUp() { bs_y_.reset(new BgpServerTest(&evm_, "Y")); bs_y_->set_mvpn_ipv4_enable(true); xs_y_ = new XmppServer(&evm_, XmppDocumentMock::kControlNodeJID); bs_y_->session_manager()->Initialize(0); xs_y_->Initialize(0, false); bcm_y_.reset(new BgpXmppChannelManager(xs_y_, bs_y_.get())); BgpMvpnIntegrationTest::SetUp(); #if SANDESH_Y SandeshYStartup(); sandesh_context_y_->bgp_server = bs_y_.get(); sandesh_context_y_->xmpp_peer_manager = bcm_y_.get(); #endif instance_count_ = GetParam(); type1_routes_ = 2 + 6 * instance_count_; red_ = new MvpnTable *[instance_count_]; blue_ = new MvpnTable *[instance_count_]; green_ = new MvpnTable *[instance_count_]; red_inet_ = new InetTable *[instance_count_]; green_inet_ = new InetTable *[instance_count_]; red_y_ = new MvpnTable *[instance_count_]; blue_y_ = new MvpnTable *[instance_count_]; green_y_ = new MvpnTable *[instance_count_]; string config = GetConfig(); Configure(config.c_str()); task_util::WaitForIdle(); SessionUp(); TableInit(); string uuid = BgpConfigParser::session_uuid("X", "Y", 1); TASK_UTIL_EXPECT_NE(static_cast<BgpPeerTest *>(NULL), bs_x_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid)); peer_x_ = bs_x_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid); TASK_UTIL_EXPECT_NE(static_cast<BgpPeerTest *>(NULL), bs_y_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid)); peer_y_ = bs_y_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid); TASK_UTIL_EXPECT_TRUE(peer_x_->IsReady()); TASK_UTIL_EXPECT_TRUE(peer_y_->IsReady()); // Register agents and add a source active mvpn route Subscribe("red", 1); Subscribe("green", 2); Subscribe("blue", 3); Subscribe(kFabricInstance, 1000); task_util::WaitForIdle(); } virtual void SessionDown() { BgpMvpnIntegrationTest::SessionDown(); agent_ya_->SessionDown(); agent_yb_->SessionDown(); agent_yc_->SessionDown(); task_util::WaitForIdle(); } virtual void TearDown() { SessionDown(); xs_y_->Shutdown(); task_util::WaitForIdle(); bs_y_->Shutdown(); task_util::WaitForIdle(); bcm_y_.reset(); TcpServerManager::DeleteServer(xs_y_); xs_y_ = NULL; agent_ya_->Delete(); agent_yb_->Delete(); agent_yc_->Delete(); #if SANDESH_Y SandeshYShutdown(); task_util::WaitForIdle(); sandesh_context_y_.reset(); #endif BgpMvpnIntegrationTest::TearDown(); if (red_y_) delete[] red_y_; if (blue_y_) delete[] blue_y_; if (green_y_) delete[] green_y_; } virtual void Subscribe(const string net, int id) { BgpMvpnIntegrationTest::Subscribe(net, id); if (net == kFabricInstance) { agent_ya_->SubscribeAll(net, id); agent_yb_->SubscribeAll(net, id); agent_yc_->SubscribeAll(net, id); task_util::WaitForIdle(); return; } for (size_t i = 1; i <= instance_count_; i++) { ostringstream r; r << net << i; agent_ya_->SubscribeAll(r.str(), id); agent_yb_->SubscribeAll(r.str(), id); agent_yc_->SubscribeAll(r.str(), id); task_util::WaitForIdle(); } } int type1_routes_; BgpServerTestPtr bs_y_; XmppServer *xs_y_; boost::scoped_ptr<BgpXmppChannelManager> bcm_y_; boost::shared_ptr<NetworkAgentMock> agent_ya_; boost::shared_ptr<NetworkAgentMock> agent_yb_; boost::shared_ptr<NetworkAgentMock> agent_yc_; BgpTable *master_y_; MvpnTable **red_y_; MvpnTable **blue_y_; MvpnTable **green_y_; BgpPeerTest *peer_x_; BgpPeerTest *peer_y_; SandeshServerTest *sandesh_bs_y_; boost::scoped_ptr<BgpSandeshContext> sandesh_context_y_; }; TEST_P(BgpMvpnTwoControllerTest, RedSenderGreenReceiver) { for (size_t i = 1; i <= instance_count_; i++) { TASK_UTIL_EXPECT_EQ(4, red_[i-1]->Size()); // 1 type1 each from A, B TASK_UTIL_EXPECT_EQ(4, red_y_[i-1]->Size()); // 1 type1 each from A, B TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), red_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), red_y_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); // 1 type1 each from A, B TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), blue_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_EQ(6, green_[i-1]->Size()); // 1 type1 each from A, B TASK_UTIL_EXPECT_NE(static_cast<MvpnRoute *>(NULL), green_[i-1]->FindType1ADRoute()); TASK_UTIL_EXPECT_TRUE(peer_x_->IsReady()); TASK_UTIL_EXPECT_TRUE(peer_y_->IsReady()); } // red, blue, green, kFabricInstance from A, B TASK_UTIL_EXPECT_EQ(2 + 6 * instance_count_, master_->Size()); TASK_UTIL_EXPECT_EQ(2 + 6 * instance_count_, master_y_->Size()); for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); task_util::WaitForIdle(); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); // Verify that the type5 route gets added to red and master only TASK_UTIL_EXPECT_EQ(5, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); // For every i, 4 routes get added TASK_UTIL_EXPECT_EQ(3 + 6*instance_count_ + 4*(i-1), master_->Size()); TASK_UTIL_EXPECT_EQ(7, green_[i-1]->Size()); ostringstream grn; grn << "green" << i; agent_yb_->AddType7MvpnRoute(grn.str(), sg.str(), "10.1.2.3", "30-40"); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(3*i, fabric_ermvpn_->Size()); // verify that t7, t3, t4 primary routes get added to red, master TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); // total 3 more routes got added TASK_UTIL_EXPECT_EQ(3 + 6*instance_count_ + 4*i -1, master_y_->Size()); TASK_UTIL_EXPECT_EQ(3 + 6*instance_count_ + 4*i -1, master_->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); // Verify that sender agent should have received a mvpn route TASK_UTIL_EXPECT_EQ(0, agent_xa_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->MvpnRouteCount()); TASK_UTIL_EXPECT_TRUE(VerifyMvpnRouteType( agent_yb_, grn.str(), sg.str())); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.3", "192.168.0.101", agent_yb_); TASK_UTIL_EXPECT_EQ(0, CheckErmvpnOListSize(agent_yb_, sg.str())); } } TEST_P(BgpMvpnTwoControllerTest, RedSenderRedGreenReceiver) { for (size_t i = 1; i <= instance_count_; i++) { string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); task_util::WaitForIdle(); ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); ostringstream grn; grn << "green" << i; agent_ya_->AddType7MvpnRoute(grn.str(), sg.str(), "10.1.1.3", "50-60"); agent_yb_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.3", "30-40"); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(4*i, fabric_ermvpn_->Size()); TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); // 2 + 6*instance_count_ // For every i, 4 routes get added TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i, master_->Size()); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.3", "192.168.0.101", agent_yb_); // Add receivers on X and make sure that it also receives type7 route TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); agent_xa_->AddType7MvpnRoute(grn.str(), sg.str(), "10.1.3.3", "70-80"); TASK_UTIL_EXPECT_EQ((int)i+1, agent_xa_->MvpnRouteCount()); TASK_UTIL_EXPECT_TRUE(VerifyMvpnRouteType( agent_xa_, grn.str(), sg.str())); TASK_UTIL_EXPECT_EQ(9, green_[i-1]->Size()); agent_xa_->DeleteMvpnRoute(grn.str(), sg.str(), 7); agent_xa_->DeleteMcastRoute(kFabricInstance, sg.str()); TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); } } TEST_P(BgpMvpnTwoControllerTest, MultipleReceivers) { for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); task_util::WaitForIdle(); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); // Verify that the type5 route gets added to red, green and master only TASK_UTIL_EXPECT_EQ(5, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(7, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*(i-1) + 1, master_->Size()); agent_ya_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.2", "30-40"); agent_yb_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.3", "50-60"); agent_yc_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.4", "70-80"); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(5*i, fabric_ermvpn_->Size()); // verify that t7, t3, t4 primary routes get added to red, master TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i, master_->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); // Verify that sender agent should have received a mvpn route TASK_UTIL_EXPECT_EQ(0, agent_xa_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_ya_->MvpnRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->MvpnRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yc_->MvpnRouteCount()); TASK_UTIL_EXPECT_TRUE(VerifyMvpnRouteType( agent_ya_, red.str(), sg.str())); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.4", "192.168.0.101", agent_yc_); TASK_UTIL_EXPECT_EQ(2, CheckErmvpnOListSize(agent_ya_, sg.str())); } } TEST_P(BgpMvpnTwoControllerTest, RedSenderRedGreenReceiverGreenDown) { for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); task_util::WaitForIdle(); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); agent_yb_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.2", "30-40"); task_util::WaitForIdle(); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); ostringstream green; green << "green" << i; agent_ya_->AddType7MvpnRoute(green.str(), sg.str(), "10.1.1.3", "50-60"); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_->Size()); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); TASK_UTIL_EXPECT_EQ(1, CheckErmvpnOListSize(agent_yb_, sg.str())); } for (size_t i = 1; i <= instance_count_; i++) { string delete_green = GetDeleteGreenConfig(i); Configure(delete_green.c_str()); agent_ya_->McastUnsubscribe(kFabricInstance, 1000); task_util::WaitForIdle(); TASK_UTIL_EXPECT_EQ(6, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * instance_count_ - 2 * i, master_->Size()); ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; TASK_UTIL_EXPECT_EQ(0, CheckErmvpnOListSize(agent_yb_, sg.str())); } } TEST_P(BgpMvpnTwoControllerTest, Type5AfterType7) { for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; ostringstream grn; grn << "green" << i; agent_yb_->AddType7MvpnRoute(grn.str(), sg.str(), "10.1.2.2", "30-40"); TASK_UTIL_EXPECT_EQ(3*i, fabric_ermvpn_->Size()); // verify that nothing changes since source is not resolvable // Only type7 route should get added to green_y_ TASK_UTIL_EXPECT_EQ(6, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(7, green_y_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * (i - 1), master_y_->Size()); ostringstream red; red << "red" << i; string tunnel; RouteAttributes attr; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); // Verify that type7 route gets resolved and copied to red_ of sender // Howver, type3 route does not get generated since no type5 route TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*(i-1) + 1, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*(i-1) + 1, master_->Size()); TASK_UTIL_EXPECT_EQ(5, red_[i-1]->Size()); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); // verify that t5, t3, t4 primary routes get added to red, master TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_->Size()); TASK_UTIL_EXPECT_EQ(2, blue_[i-1]->Size()); // Verify that sender agent should have received a mvpn route TASK_UTIL_EXPECT_EQ(0, agent_xa_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->McastRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_xa_->MvpnRouteCount()); TASK_UTIL_EXPECT_EQ((int)i, agent_yb_->MvpnRouteCount()); TASK_UTIL_EXPECT_TRUE(VerifyMvpnRouteType( agent_yb_, grn.str(), sg.str())); VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); TASK_UTIL_EXPECT_EQ(0, CheckErmvpnOListSize(agent_yb_, sg.str())); } } TEST_P(BgpMvpnTwoControllerTest, MvpnWithoutErmvpnRoute) { for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); agent_yb_->AddType7MvpnRoute(red.str(), sg.str(), "10.1.2.2", "30-40"); // Verify that tables get all mvpn routes TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_y_->Size()); TASK_UTIL_EXPECT_EQ(3 * i, fabric_ermvpn_->Size()); // Delete the ermvpn route agent_yb_->DeleteMcastRoute(kFabricInstance, sg.str()); // Verify that type4 route gets deleted TASK_UTIL_EXPECT_EQ(3*(i-1), fabric_ermvpn_->Size()); TASK_UTIL_EXPECT_EQ(7, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i - 1, master_y_->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*i - 1, master_->Size()); // Verify that type5 route is withdrawn since there are no receivers TASK_UTIL_EXPECT_EQ(static_cast<NetworkAgentMock::MvpnRouteEntry *>(NULL), agent_xa_->MvpnRouteLookup(red.str(), sg.str())); // Add the ermvpn receiver back agent_yb_->AddMcastRoute(kFabricInstance, sg.str(), "10.1.2.2", "30-40", ""); TASK_UTIL_EXPECT_EQ(3*i, fabric_ermvpn_->Size()); // Verify that type4 route gets added back TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_y_->Size()); // Verify that mvpn and ermvpn routes are ok VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); } } TEST_P(BgpMvpnTwoControllerTest, ReceiverSenderLeave) { for (size_t i = 1; i <= instance_count_; i++) { ostringstream sg; sg << "224." << i << "." << instance_count_ << ".3,192.168.1.1"; string tunnel; RouteAttributes attr; ostringstream red; red << "red" << i; ostringstream nh; nh << "10." << i << "." << instance_count_ << ".2"; NextHop nexthop_red(nh.str(), 11, tunnel, red.str()); agent_xa_->AddRoute(red.str(), "192.168.1.1/32", nexthop_red, attr); agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); ostringstream green; green << "green" << i; agent_yb_->AddType7MvpnRoute(green.str(), sg.str(), "10.1.2.2", "30-40"); // Verify that tables get all mvpn routes TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(8, green_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_y_->Size()); // Delete the type7 join route agent_yb_->DeleteMvpnRoute(green.str(), sg.str(), 7); // Verify that type7, type3 and type4 routes get deleted TASK_UTIL_EXPECT_EQ(5, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*(i-1) + 1, master_->Size()); // Verify that type5 route is withdrawn since there are no receivers TASK_UTIL_EXPECT_EQ(static_cast<NetworkAgentMock::MvpnRouteEntry *>(NULL), agent_xa_->MvpnRouteLookup(red.str(), sg.str())); // Add the receiver back agent_yb_->AddType7MvpnRoute(green.str(), sg.str(), "10.1.2.2", "30-40"); // Verify that type7, type3 and type4 routes get added back TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(3+ 6*instance_count_ + 4*i -1, master_->Size()); // Verify that mvpn and ermvpn routes are ok VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); // Delete the type5 source active route agent_xa_->DeleteMvpnRoute(red.str(), sg.str(), 5); // Verify that type5, type3 and type4 routes get deleted TASK_UTIL_EXPECT_EQ(5, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4*(i -1) + 1, master_->Size()); // Verify that type5 route is withdrawn since there are no receivers TASK_UTIL_EXPECT_EQ(static_cast<NetworkAgentMock::MvpnRouteEntry *> (NULL), agent_xa_->MvpnRouteLookup(red.str(), sg.str())); // Add the sender back agent_xa_->AddType5MvpnRoute(red.str(), sg.str(), nh.str()); // Verify that type5, type3 and type4 routes get added back TASK_UTIL_EXPECT_EQ(8, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(type1_routes_ + 4 * i, master_->Size()); // Verify that mvpn and ermvpn routes are ok VerifyOListAndSource(agent_xa_, red.str(), sg.str(), 1, "10.1.2.2", "192.168.0.101", agent_yb_); } }; TEST_P(BgpMvpnTwoControllerTest, ChangeIdentifier) { for (size_t i = 1; i <= instance_count_; i++) { // Verify that tables get all mvpn routes TASK_UTIL_EXPECT_EQ(4, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(6, green_[i-1]->Size()); } TASK_UTIL_EXPECT_EQ(8 + 6*(instance_count_-1), master_y_->Size()); // Change the identifiers of routers string config = GetIdentifierChangeConfig(); Configure(config.c_str()); Subscribe("blue", 3); Subscribe("red", 1); Subscribe("green", 2); Subscribe(kFabricInstance, 1000); task_util::WaitForIdle(); string uuid = BgpConfigParser::session_uuid("X", "Y", 1); TASK_UTIL_EXPECT_NE(static_cast<BgpPeerTest *>(NULL), bs_x_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid)); peer_x_ = bs_x_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid); TASK_UTIL_EXPECT_NE(static_cast<BgpPeerTest *>(NULL), bs_y_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid)); peer_y_ = bs_y_->FindPeerByUuid(BgpConfigManager::kMasterInstance, uuid); TASK_UTIL_EXPECT_TRUE(peer_x_->IsReady()); TASK_UTIL_EXPECT_TRUE(peer_y_->IsReady()); for (size_t i = 1; i <= instance_count_; i++) { // Verify that tables get all mvpn routes TASK_UTIL_EXPECT_EQ(4, red_[i-1]->Size()); TASK_UTIL_EXPECT_EQ(6, green_[i-1]->Size()); } TASK_UTIL_EXPECT_EQ(8 + 6*(instance_count_-1), master_y_->Size()); } static int GetInstanceCount() { char *env = getenv("BGP_MVPN_TEST_INSTANCE_COUNT"); int count = 4; if (!env) return count; stringToInteger(string(env), count); return count; } INSTANTIATE_TEST_CASE_P(BgpMvpnTestWithParams, BgpMvpnOneControllerTest, ::testing::Range(1, GetInstanceCount())); INSTANTIATE_TEST_CASE_P(BgpMvpnTestWithParams, BgpMvpnTwoControllerTest, ::testing::Values(1, 3, GetInstanceCount())); static void SetUp() { BgpServer::Initialize(); ControlNode::SetDefaultSchedulingPolicy(); BgpServerTest::GlobalSetUp(); BgpObjectFactory::Register<StateMachine>( boost::factory<StateMachineTest *>()); BgpObjectFactory::Register<BgpXmppMessageBuilder>( boost::factory<BgpXmppMessageBuilder *>()); XmppObjectFactory::Register<XmppStateMachine>( boost::factory<XmppStateMachineTest *>()); } static void TearDown() { BgpServer::Terminate(); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Terminate(); } int main(int argc, char **argv) { bgp_log_test::init(); ::testing::InitGoogleTest(&argc, argv); SetUp(); int result = RUN_ALL_TESTS(); TearDown(); return result; }
39.008442
82
0.59359
[ "vector" ]
20220866e1681e32484a2589009d372f5c2b1e9b
702
cpp
C++
dynamic-programming/C++/0121-best-time-to-buy-and-sell-stock/main.cpp
ljyljy/LeetCode-Solution-in-Good-Style
0998211d21796868061eb22e2cbb9bcd112cedce
[ "Apache-2.0" ]
1
2020-03-09T00:45:32.000Z
2020-03-09T00:45:32.000Z
dynamic-programming/C++/0121-best-time-to-buy-and-sell-stock/main.cpp
lemonnader/LeetCode-Solution-Well-Formed
baabdb1990fd49ab82a712e121f49c4f68b29459
[ "Apache-2.0" ]
null
null
null
dynamic-programming/C++/0121-best-time-to-buy-and-sell-stock/main.cpp
lemonnader/LeetCode-Solution-Well-Formed
baabdb1990fd49ab82a712e121f49c4f68b29459
[ "Apache-2.0" ]
1
2021-06-17T09:21:54.000Z
2021-06-17T09:21:54.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int size = prices.size(); if (size <= 1) { return 0; } // 差分数组 vector<int> diff(size - 1, 0); for (int i = 0; i < size - 1; ++i) { diff[i] = prices[i + 1] - prices[i]; } // 下面转化成求解差分数组的最大子段和 vector<int> dp(size - 1, 0); dp[0] = max(0, diff[0]); int res = dp[0]; for (int i = 1; i < size - 1; ++i) { // 最大子段和的状态转移方程 dp[i] = max(0, dp[i - 1]) + diff[i]; res = max(res, dp[i]); } return res; } };
20.057143
48
0.425926
[ "vector" ]
45d8c0853d0cb66d9c50b3866910af44bb09ccfa
7,542
hpp
C++
src/SkillSet.hpp
GeorgeWeb/Heroes_Journey
2f1ee746fe6834a1c49a148539dd5a618e363972
[ "MIT" ]
1
2020-05-19T06:47:10.000Z
2020-05-19T06:47:10.000Z
src/SkillSet.hpp
GeorgeWeb/HeroesJourney
2f1ee746fe6834a1c49a148539dd5a618e363972
[ "MIT" ]
null
null
null
src/SkillSet.hpp
GeorgeWeb/HeroesJourney
2f1ee746fe6834a1c49a148539dd5a618e363972
[ "MIT" ]
null
null
null
#ifndef SKILL_SET_H #define SKILL_SET_H #include "Components/StatusComponent.hpp" #include "DEFINITIONS.hpp" namespace HJ { using namespace Components; enum class SKILL_TARGET : int { SELF = 0, ALLY = 1, ENEMY = 2, ENEMY_TEAM = 3 }; enum class DAMAGE_BASE : int { MELEE = 0, RANGED = 1, DEFENCE = 2 }; enum class DAMAGE_TYPE : int { BASIC = 0, FROST = 1, FIRE = 2, MAGIC = 3 }; class Skill { public: Skill() = default; DAMAGE_BASE dmgBase; DAMAGE_TYPE dmgType; SKILL_TARGET target; // power and mana modificators unsigned int damageMod; unsigned int manaNeed = 0; // assets std::string textureRefName = ""; std::string soundRefName = ""; // skill description std::string effectDesc = ""; std::vector<EFFECT_TYPE> applicableEffects = {}; }; // [BASIC/GENERAL SKILL SET] class BasicAttack final : public Skill { public: BasicAttack() : Skill() { textureRefName = "Tex_BasicAttackBtn"; soundRefName = SKILL_BASIC_ATTACK_SOUND; dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 100; } }; class BasicMagicAttack final : public Skill { public: BasicMagicAttack() : Skill() { textureRefName = "Tex_BasicAttackBtn"; soundRefName = SKILL_BASIC_ATTACK_SOUND; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::MAGIC; target = SKILL_TARGET::ENEMY; damageMod = 100; } }; class BasicDefence final : public Skill { public: BasicDefence() : Skill() { textureRefName = "Tex_DefendBtn"; soundRefName = SKILL_BASIC_DEFENCE_SOUND; dmgBase = DAMAGE_BASE::DEFENCE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::SELF; damageMod = 0; applicableEffects = { EFFECT_TYPE::DEFEND }; } }; /*** SPECIALIZED SKILL SETS ***/ // [KNIGHT SKILL SET] class HeroicStrike final : public Skill { public: HeroicStrike() : Skill() { textureRefName = "Tex_HeroicStrikeSkill"; soundRefName = SKILL_HEROIC_STRIKE_SOUND; effectDesc = "Heroic Strike"; dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; manaNeed = 50; damageMod = 200; } }; class ShieldThrow final : public Skill { public: ShieldThrow() : Skill() { textureRefName = "Tex_ShieldBashSkill"; soundRefName = SKILL_SHIELD_BASH_SOUND; effectDesc = "Shield Bash"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; manaNeed = 50; damageMod = 50; applicableEffects = { EFFECT_TYPE::STUN }; } }; // [BARD SKILL SET] class OffenseAura final : public Skill { public: OffenseAura() : Skill() { textureRefName = "Tex_OffAuraSkill"; soundRefName = SKILL_OFF_AURA_SOUND; effectDesc = "DMG Aura"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ALLY; manaNeed = 25; damageMod = 0; applicableEffects = { EFFECT_TYPE::DAMAGE_AURA }; } }; class DeffenseAura final : public Skill { public: DeffenseAura() : Skill() { textureRefName = "Tex_DefAuraSkill"; soundRefName = SKILL_DEF_AURA_SOUND; effectDesc = "DEF Aura"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ALLY; manaNeed = 25; damageMod = 0; applicableEffects = { EFFECT_TYPE::ARMOUR_AURA }; } }; // [ROGUE SKILL SET] class RavenBow final : public Skill { public: RavenBow() : Skill() { textureRefName = "Tex_ArcherySkill"; soundRefName = SKILL_BOW_SOUND; effectDesc = "Raven Bow"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 75; } }; class RainOfArrows final : public Skill { public: RainOfArrows() : Skill() { textureRefName = "Tex_RoASkill"; soundRefName = SKILL_ROA_SOUND; effectDesc = "Rain Of Arrows"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; manaNeed = 50; damageMod = 3 * 75; } }; // [SORCERESS SKILL SET] class FireBolt final : public Skill { public: FireBolt() : Skill() { textureRefName = "Tex_FireBoltSkill"; soundRefName = SKILL_FIRE_BOLT_SOUND; effectDesc = "Fire Bolt"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::FIRE; target = SKILL_TARGET::ENEMY; manaNeed = 50; damageMod = 200; } }; class FrostAura final : public Skill { public: FrostAura() : Skill() { textureRefName = "Tex_FireAuraSkill"; soundRefName = SKILL_FIRE_AURA_SOUND; effectDesc = "Fire Aura"; dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::FROST; target = SKILL_TARGET::ALLY; manaNeed = 50; damageMod = 0; applicableEffects = { EFFECT_TYPE::FROST_AURA }; } }; // [TROLL SKILL SET] class Stomp final : public Skill { public: Stomp() : Skill() { dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 50; applicableEffects = { EFFECT_TYPE::STUN }; } }; class Smack final : public Skill { public: Smack() : Skill() { dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 133; } }; class RageRawr final : public Skill { public: RageRawr() : Skill() { dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY_TEAM; damageMod = 100; applicableEffects = { EFFECT_TYPE::STUN, EFFECT_TYPE::ENRAGE }; } }; // [CYCLOP SKILL SET] class HeavyBoulder final : public Skill { public: HeavyBoulder() : Skill() { dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 100; } }; class VeryHeavyBoulder final : public Skill { public: VeryHeavyBoulder() : Skill() { dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 90; applicableEffects = { EFFECT_TYPE::STUN }; } }; class Devour final : public Skill { public: Devour() : Skill() { dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::BASIC; target = SKILL_TARGET::ENEMY; damageMod = 200; } }; // [HARPY SKILL SET] class IcyClaw : public Skill { public: IcyClaw() : Skill() { dmgBase = DAMAGE_BASE::MELEE; dmgType = DAMAGE_TYPE::FROST; target = SKILL_TARGET::ENEMY; damageMod = 100; } }; // For rage state, the harpy will use Devour, the on that the Cyclop uses. // [EVIL FROST MAGE (LAST BOSS) SKILL SET] class FrostBolt : public Skill { public: FrostBolt() : Skill() { dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::FROST; target = SKILL_TARGET::ENEMY; damageMod = 300; } }; class FrostRing : public Skill { public: FrostRing() : Skill() { dmgBase = DAMAGE_BASE::RANGED; dmgType = DAMAGE_TYPE::FROST; target = SKILL_TARGET::ENEMY; damageMod = 50; applicableEffects = { EFFECT_TYPE::STUN }; } }; class FrostArmor : public Skill { public: FrostArmor() : Skill() { dmgBase = DAMAGE_BASE::DEFENCE; dmgType = DAMAGE_TYPE::FROST; target = SKILL_TARGET::SELF; damageMod = 0; applicableEffects = { EFFECT_TYPE::FROST_ARMOR }; } }; } #endif // !SKILL_SET_H
20.383784
75
0.640546
[ "vector" ]
45f292395f8b722b9c1317128583e0d28176245b
565
cpp
C++
TAO/TAO_IDL/be/be_init.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/TAO_IDL/be/be_init.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/TAO_IDL/be/be_init.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: be_init.cpp 85771 2009-06-23 20:11:39Z mitza $ #include "global_extern.h" #include "be_extern.h" #include "../../tao/Version.h" TAO_IDL_BE_Export void BE_version (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("TAO_IDL_BE, version ") ACE_TEXT (TAO_VERSION) ACE_TEXT ("\n"))); } TAO_IDL_BE_Export int BE_init (int &, ACE_TCHAR *[]) { // Initialize BE global data object. ACE_NEW_RETURN (be_global, BE_GlobalData, -1); return 0; } TAO_IDL_BE_Export void BE_post_init (char *[], long) { }
18.225806
70
0.619469
[ "object" ]
45f37e350f093d0bd33f593a7d9b4ae011b8682a
20,506
cpp
C++
DKPlugins/DKRml/DKRml.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
29
2015-05-03T06:23:22.000Z
2022-02-10T15:16:26.000Z
DKPlugins/DKRml/DKRml.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
125
2016-02-28T06:13:49.000Z
2022-01-04T11:50:08.000Z
DKPlugins/DKRml/DKRml.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
8
2016-12-04T02:29:34.000Z
2022-01-04T01:11:25.000Z
#include "DK/stdafx.h" #ifdef USE_rmlui_debugger #include <RmlUi/Debugger.h> #endif #include "DKRml/DKRml.h" #include "DKWindow/DKWindow.h" #include "DKCurl/DKCurl.h" #include "DKDuktape/DKDuktape.h" #include "DKXml/DKXml.h" #include "DKRml/DKRmlHeadInstancer.h" #include <RmlUi/Core/StreamMemory.h> #include "../../3rdParty/RmlUi-master/Source/Core/PluginRegistry.h" #include "../../3rdParty/RmlUi-master/Source/Core/XMLNodeHandlerDefault.h" #include "../../3rdParty/RmlUi-master/Source/Core/XMLNodeHandlerBody.h" #define DRAG_FIX 1 DKRmlFile* DKRml::dkRmlFile = NULL; bool DKRml::Init(){ DKDEBUGFUNC(); DKClass::DKCreate("DKRmlJS"); DKClass::DKCreate("DKRmlV8"); document = NULL; if(!dkRmlFile){ dkRmlFile = new DKRmlFile(); Rml::SetFileInterface(dkRmlFile); } //Create DKSDLRml or DKOSGRml if(DKClass::DKAvailable("DKSDLRml")){ DKClass::DKCreate("DKSDLRml"); if(!Rml::Initialise()) return DKERROR("Rml::Initialise(): failed\n"); int w; if(!DKWindow::GetWidth(w)){ return false; } int h; if(!DKWindow::GetHeight(h)){ return false; } context = Rml::CreateContext("default", Rml::Vector2i(w, h)); } else if(DKClass::DKAvailable("DKOSGRml")){ DKClass::DKCreate("DKOSGRml"); } else{ DKERROR("No registered window found\n"); return false; } #ifdef USE_rmlui_debugger if (!Rml::Debugger::Initialise(context)) return DKERROR("Rml::Debugger::Initialise(): failed\n"); #endif //Add missing stylesheet properties //TODO - https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat Rml::PropertyId background_repeat = Rml::StyleSheetSpecification::RegisterProperty("background-repeat", "repeat", false) .AddParser("keyword", "repeat, space, round, no-repeat") .AddParser("string") .GetId(); //this supresses background-repeat warnings temporarily //TODO - https://developer.mozilla.org/en-US/docs/Web/CSS/border-style Rml::PropertyId border_style = Rml::StyleSheetSpecification::RegisterProperty("border-style", "none", false) .AddParser("keyword", "none, hidden") .AddParser("string") .GetId(); //this supresses border-style warnings temporarily context->SetDocumentsBaseTag("html"); DKString rmlFonts = DKFile::local_assets+"DKRml"; LoadFonts(rmlFonts); LoadFonts(DKFile::local_assets); DKEvents::AddRegisterEventFunc(&DKRml::RegisterEvent, this); //DKEvents::AddUnegisterEventFunc(&DKRml::UnregisterEvent, this); //DKEvents::AddSendEventFunc(&DKRml::SendEvent, this); //DKClass::DKCreate("DKRmlJS"); //NOTE: already call above. around line 23 Rml::Factory::RegisterElementInstancer("html", new Rml::ElementInstancerGeneric<Rml::ElementDocument>); Rml::XMLParser::RegisterNodeHandler("html", std::make_shared<Rml::XMLNodeHandlerBody>()); Rml::XMLParser::RegisterNodeHandler("head", std::make_shared<HeadInstancer>()); Rml::Factory::RegisterElementInstancer("body", new Rml::ElementInstancerElement); Rml::XMLParser::RegisterNodeHandler("body", std::make_shared<Rml::XMLNodeHandlerDefault>()); DKClass::DKCreate("DKDom"); DKString html; DKString workingPath = DKFile::local_assets; DKFile::FileToString(workingPath +"DKRml/blank.html", html); DKFile::ChDir(workingPath); LoadHtml(html); return true; } bool DKRml::End(){ DKDEBUGFUNC(); if(context){ Rml::ReleaseTextures(); Rml::Shutdown(); delete Rml::GetRenderInterface(); delete Rml::GetSystemInterface(); delete Rml::GetFileInterface(); } DKClass::DKClose("DKRmlJS"); DKClass::DKClose("DKRmlV8"); DKEvents::RemoveRegisterEventFunc(&DKRml::RegisterEvent, this); DKEvents::RemoveUnegisterEventFunc(&DKRml::UnregisterEvent, this); DKEvents::RemoveSendEventFunc(&DKRml::SendEvent, this); return true; } bool DKRml::GetSourceCode(DKString& source_code) { source_code = document->GetContext()->GetRootElement()->GetInnerRML(); DKINFO("######################## CODE FROM RmlUi #########################\n"); DKINFO(source_code+"\n"); DKINFO("##################################################################\n"); // Actually, we only want the last html node int n = source_code.rfind("<html"); if(n < 0) return DKWARN("html tag not found\n"); source_code = source_code.substr(n); replace(source_code, "<", "\n<"); //put all tags on a new line DKINFO("################## Last <html> node from RmlUi ##################\n"); DKINFO(source_code+"\n"); DKINFO("#################################################################\n"); return true; } bool DKRml::LoadFont(const DKString& file){ DKDEBUGFUNC(file); if(!Rml::LoadFontFace(file.c_str())) return DKERROR("Could not load "+file+"\n"); return true; } bool DKRml::LoadFonts(DKString& directory){ DKDEBUGFUNC(); char ch = directory.back(); if(ch != '/') directory += '/'; //make sure directory has a trailing / DKStringArray files; DKFile::GetDirectoryContents(directory, files); for(unsigned int i=0; i<files.size(); ++i){ if(DKFile::IsDirectory(directory+files[i])) continue; DKString extension; DKFile::GetExtention(files[i],extension); if(same(extension,".otf") || same(extension,".ttf")){ //DKString file; //DKFile::GetFileName(files[i],file); LoadFont(directory+files[i]); } } return true; } bool DKRml::LoadHtml(const DKString& html){ //// Prepair the html document for RmlUi DKString rml; dkRmlConverter.HtmlToRml(html, rml); //// Clear any document and load the rml into the document if (document) { Rml::Factory::ClearStyleSheetCache(); document->Close(); } auto stream = std::make_unique<Rml::StreamMemory>((Rml::byte*)rml.c_str(), rml.size()); stream->SetSourceURL("[document from memory]"); Rml::PluginRegistry::NotifyDocumentOpen(context, stream->GetSourceURL().GetURL()); document = context->CreateDocument("html"); //Create DOM javascript instance of the document using the documents element address DKString rval; DKString document_address = elementToAddress(document); DKDuktape::RunDuktape("var document = new Document(\"" + document_address + "\");", rval); Rml::Element* ele = document; Rml::XMLParser parser(ele); parser.Parse(stream.get()); //Make sure we have <head> and <body> tags Rml::ElementList heads; Rml::ElementList bodys; Rml::Element* head = NULL; Rml::Element* body = NULL; Rml::ElementDocument* elementDocument = document->GetOwnerDocument(); document->GetOwnerDocument()->GetElementsByTagName(heads, "head"); if (!heads.empty()) head = heads[0]; document->GetOwnerDocument()->GetElementsByTagName(bodys, "body"); if (!bodys.empty()) body = bodys[0]; if (!head && !body) { document->GetOwnerDocument()->AppendChild(document->CreateElement("head"), true); document->GetOwnerDocument()->AppendChild(document->CreateElement("body"), true); } else if (head && !body) document->GetOwnerDocument()->AppendChild(document->CreateElement("body"), true); else if (!head && body) document->GetOwnerDocument()->InsertBefore(document->CreateElement("head"), body); //Load user agent style sheet DKString file = DKFile::local_assets + "DKRml/DKRml.css"; const Rml::StyleSheetContainer* doc_sheet = document->GetOwnerDocument()->GetStyleSheetContainer(); Rml::SharedPtr<Rml::StyleSheetContainer> file_sheet = Rml::Factory::InstanceStyleSheetFile(file.c_str()); if(doc_sheet) { //Combine the file_sheet and the doc_sheet into a new_sheet and load it back to the document Rml::SharedPtr<Rml::StyleSheetContainer> new_sheet = doc_sheet->CombineStyleSheetContainer(*file_sheet); document->GetOwnerDocument()->SetStyleSheetContainer(std::move(new_sheet)); } else //no current sheet, just load the file sheet document->GetOwnerDocument()->SetStyleSheetContainer(std::move(file_sheet)); //Finish loading the document //Rml::ElementUtilities::BindEventAttributes(document); Rml::PluginRegistry::NotifyDocumentLoad(document); document->DispatchEvent(Rml::EventId::Load, Rml::Dictionary()); document->UpdateDocument(); if(!document){ document = context->LoadDocumentFromMemory(""); return DKERROR("DKRml::LoadHtml(): document invalid\n"); } Rml::ElementList elements; DKRml::Get()->document->GetElementsByTagName(elements, "body"); if(!elements[0]) return DKERROR("body element invalid\n"); //dkRmlConverter.PostProcess(document); dkRmlConverter.PostProcess(elements[0]); document->Show(); #ifdef ANDROID //We have to make sure the fonts are loaded on ANDROID LoadFonts(); #endif return true; } bool DKRml::LoadUrl(const DKString& url){ DKDEBUGFUNC(url); DKString _url = url; if(has(_url,":/")) //could be http:// , https://, file:/// or C:/ href = _url; //absolute path including protocol else if(has(_url,"//")){ //could be //www.site.com/style.css or //site.com/style.css return DKERROR("DKRml::LoadUrl(): no protocol specified\n"); //absolute path without protocol } else _url = workingPath + _url; //Get the working path; std::size_t found = _url.find_last_of("/"); workingPath = _url.substr(0, found + 1); DKINFO("DKRml::LoadUrl(): workingPath: " + workingPath + "\n"); DKINFO("DKRml::LoadUrl(): href: " + href + "\n"); //get the protocol int n = _url.find(":"); protocol = _url.substr(0,n); DKINFO("DKRml::LoadUrl(): protocol: "+protocol+"\n"); found = _url.rfind("/"); _path = _url.substr(0,found+1); //DKWARN("DKRml::LoadUrl(): last / at "+toString(found)+"\n"); DKINFO("DKRml::LoadUrl(): _path = "+_path+"\n"); DKString html; if(has(_url, "http://") || has(_url, "https://")){ DKClass::DKCreate("DKCurl"); if(!DKCurl::Get()->HttpFileExists(_url)) return DKERROR("Could not locate "+_url+"\n"); if(!DKCurl::Get()->HttpToString(_url, html)) return DKERROR("Could not get html from url "+_url+"\n"); } else{ if(!DKFile::FileToString(_url, html)) return DKERROR("DKFile::FileToString failed on "+_url+"\n"); } LoadHtml(html); return true; } void DKRml::ProcessEvent(Rml::Event& rmlEvent){ //TODO - make rmlEvent accessable through javascript //1. Create Javascript Event object that references the rmlEvent DKString rmlEventAddress = eventToAddress(&rmlEvent); //DKString code = "new Event("+rmlEventAddress+")"; //DKString rval; //DKDuktape::Get()->RunDuktape(code, rval); //DKINFO("DKRml::ProcessEvent(): "+code+": rval="+rval+"\n"); //DKDEBUGFUNC(event); if (!rmlEvent.GetCurrentElement()) return; if (!rmlEvent.GetTargetElement()) return; Rml::Element* currentElement = rmlEvent.GetCurrentElement(); DKString currentElementAddress = elementToAddress(currentElement); Rml::Element* targetElement = rmlEvent.GetTargetElement(); DKString targetElementAddress = elementToAddress(targetElement); DKString type = rmlEvent.GetType(); int phase = (int)rmlEvent.GetPhase(); //{ None, Capture = 1, Target = 2, Bubble = 4 }; /* // Send this event back to duktape to be processed in javascript DKString evnt = "{type:'"+type+"', eventPhase:"+toString(phase)+"}"; DKString code = "EventFromCPP('"+ currentElementAddress +"',"+evnt+");"; DKString rval; DKDuktape::Get()->RunDuktape(code, rval); if(!rval.empty()){ DKINFO("DKRml::ProcessEvent(): rval = "+rval+"\n"); } */ // If the event bubbles up, ignore elements underneith Rml::Context* context = document->GetContext(); Rml::Element* hoverElement = NULL; if (context) hoverElement = context->GetHoverElement(); Rml::Element* hoverParent = NULL; if (hoverElement) hoverParent = hoverElement->GetParentNode(); if (hoverParent) hover = hoverParent; //if(rmlEvent.GetPhase() == 1 && currentElement != hover){ return; } /* //Event Monitor DKString tag = currentElement->GetTagName(); DKString id = currentElement->GetId(); DKString target_id = targetElement->GetId(); DKString target_tag = targetElement->GetTagName(); DKString hover_id = hover->GetId(); DKString string = "EVENT: " + type + " (current) " + tag + "> " + id + " (target) " + target_tag + "> " + target_id + "(hover)" + hover_id + "\n"; DKINFO(string + "\n"); */ #ifdef ANDROID //Toggle Keyboard on text element click if (type == "mousedown") { if (same(currentElement->GetTagName(), "textarea") || same(currentElement->GetTagName(), "input")) { CallJavaFunction("toggleKeyboard", ""); return; } } //Hide Keyboard on input Enter if (type == "keydown" && currentElement->GetTagName() == "input") { int key = rmlEvent.GetParameter<int>("key_identifier", 0); if (key == Rml::Input::KI_RETURN) { //Enter CallJavaFunction("toggleKeyboard", ""); return; } } #endif if (same(type, "mouseup") && rmlEvent.GetParameter<int>("button", 0) == 1) type = "contextmenu"; for(unsigned int i = 0; i < DKEvents::events.size(); ++i){ DKEvents* ev = DKEvents::events[i]; //certain stored events are altered before comparison DKString _type = ev->GetType(); if (same(_type, "input")) _type = "change"; //// PROCESS ELEMENT EVENTS ////// if (same(ev->GetId(), currentElementAddress) && same(_type, type)) { ev->data.clear(); ev->data.push_back(rmlEventAddress); //ev->rEvent = &rmlEvent; /* //pass the value if (same(type, "keydown") || same(type, "keyup")) { ev->data.clear(); ev->data.push_back(toString(rmlEvent.GetParameter<int>("key_identifier", 0))); } if (same(type, "mousedown") || same(type, "mouseup")) { ev->data.clear(); ev->data.push_back(toString(rmlEvent.GetParameter<int>("button", 0))); } */ //FIXME - we run the risk of having event function pointers that point to nowhere if (!ev->event_func(ev)){ DKERROR("DKRml::ProcessEvent failed \n"); return; } //call the function linked to the event //DKINFO("Event: "+ev->type+", "+ev->id+"\n"); //FIXME - StopPropagation() on a mousedown even will bock the elements ability to drag // we need to find a way to stop propagation of the event, while allowing drag events. /* #ifdef DRAG_FIX if (!same(type, "mousedown")) { #endif if (!same(type, "keydown")) rmlEvent.StopPropagation(); #ifdef DRAG_FIX } #endif */ //ev->rEvent = NULL; return; } } } bool DKRml::RegisterEvent(const DKString& elementAddress, const DKString& type){ DKDEBUGFUNC(elementAddress, type); if(elementAddress.empty()) return DKERROR("DKRml::RegisterEvent(): elementAddress empty\n"); if(type.empty()) return DKERROR("DKRml::RegisterEvent("+elementAddress+"): type empty\n"); Rml::Element* element = addressToElement(elementAddress.c_str()); if(!element) return DKERROR("DKRml::RegisterEvent("+elementAddress+","+type+"): element invalid\n"); DKString _type = type; if(same(type, "contextmenu")) _type = "mouseup"; if(same(type, "input")) _type = "change"; //NOTE: This was an old libRocket issue and has not been tested for a long time //FIXME - StopPropagation() on a mousedown event will bock the elements ability to drag // we need to find a way to stop propagation of the event, while allowing drag events. // If we bubble our event upward and allow mousedown events to propagate, it works, // but it's a very nasty fix as every mousedown listener under the element will process // first and then finally process the element clicked, allowing drag. // WE don't want to process mousedown on other events! We want a one-shot mousedown event // processed for that element and stopped. And it must allow drag to bleed thru. #ifdef DRAG_FIX if(same(type, "mousedown")) element->AddEventListener(_type.c_str(), this, true); //bubble up else{ #endif element->AddEventListener(_type.c_str(), this, false); #ifdef DRAG_FIX } #endif return true; } bool DKRml::SendEvent(const DKString& elementAddress, const DKString& type, const DKString& value){ //DKDEBUGFUNC(id, type, value); if(elementAddress.empty()) return DKERROR("elementAddress invalid"); if(type.empty()) return DKERROR("type invalid"); if(!document) return DKERROR("document invalid"); //if(same(addressToElement(elementAddress)->GetId(),"window")) //DKWARN("DKRml::SendEvent(): recieved global window event\n"); Rml::Element* element = addressToElement(elementAddress); if(!element) return DKERROR("element invalid"); Rml::Dictionary parameters; //parameters.Set("msg0", value.c_str()); element->DispatchEvent(type.c_str(), parameters, false); return true; } bool DKRml::DebuggerOff(){ #ifdef USE_rmlui_debugger Rml::Debugger::SetVisible(false); DKINFO("Rml Debugger OFF\n"); #else return DKERROR("RML Debugger not available \n"); #endif return true; } bool DKRml::DebuggerOn(){ #ifdef USE_rmlui_debugger Rml::Debugger::SetVisible(true); DKINFO("Rml Debugger ON\n"); #else return DKERROR("RML Debugger not available \n"); #endif return true; } bool DKRml::DebuggerToggle(){ DKDEBUGFUNC(); #ifdef USE_rmlui_debugger if(Rml::Debugger::IsVisible()) //FIXME: always returns false DKRml::DebuggerOff(); else DKRml::DebuggerOn(); #else return DKERROR("RML Debugger not available \n"); #endif return true; } bool DKRml::UnregisterEvent(const DKString& elementAddress, const DKString& type){ DKDEBUGFUNC(elementAddress, type); if(elementAddress.empty()) return DKERROR("elementAddress invalid"); if(type.empty()) return DKERROR("type invalid"); if (same(addressToElement(elementAddress)->GetId(), "window")) return DKERROR("can not Unregister window event"); //if(!DKValid("DKRml0")){ return false; } Rml::Element* element = addressToElement(elementAddress); if(!element) return DKERROR("element invalid"); DKString _type = type; if(same(type, "contextmenu")) _type = "mouseup"; if(same(type, "input")) _type = "change"; element->RemoveEventListener(_type.c_str(), this, false); return true; } Rml::Event* DKRml::addressToEvent(const DKString& address){ //DKDEBUGFUNC(address); Rml::Event* event; if (address.compare(0, 2, "0x") != 0 || address.size() <= 2 || address.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos) { DKERROR("the address ("+address+") is not a valid hex notation\n"); return NULL; } //Convert a string of an address back into a pointer std::stringstream ss; ss << address.substr(2, address.size() - 2); //int tmp(0); std::uint64_t tmp; if (!(ss >> std::hex >> tmp)) { DKERROR("DKRml::addressToEvent(" + address + "): invalid address\n"); return NULL; } event = reinterpret_cast<Rml::Event*>(tmp); if (!event->GetCurrentElement()) { DKERROR("DKRml::addressToEvent(" + address + "): currentElement invalid\n"); return NULL; } return event; } DKString DKRml::eventToAddress(Rml::Event* event){ if (!event) { DKERROR("DKRml::eventToAddress(): invalid event\n"); return ""; } std::stringstream ss; const void* address = static_cast<const void*>(event); #ifdef WIN32 ss << "0x" << address; #else ss << address; #endif return ss.str(); } Rml::Element* DKRml::addressToElement(const DKString& address) { //DKDEBUGFUNC(address); Rml::Element* element = nullptr; if (address == "window") { element = DKRml::Get()->document->GetContext()->GetRootElement(); //Root element that holds all the documents. } else if (address == "document") { element = DKRml::Get()->document->GetOwnerDocument(); } //else if (address == "document") { // element = DKRml::Get()->document; //} else { if (address.compare(0, 2, "0x") != 0 || address.size() <= 2 || address.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos) { DKERROR("NOTE: DKRml::addressToElement(): the address is not a valid hex notation"); return NULL; } //Convert a string of an address back into a pointer std::stringstream ss; ss << address.substr(2, address.size() - 2); std::uint64_t tmp; if (!(ss >> std::hex >> tmp)) { DKERROR("invalid address\n"); return NULL; } element = reinterpret_cast<Rml::Element*>(tmp); } if (!element) { DKERROR("invalid element\n"); return NULL; } if (element->GetTagName().empty()) return NULL; return element; } DKString DKRml::elementToAddress(Rml::Element* element){ if (!element) { DKERROR("DKRml::elementToAddress(): invalid element\n"); return ""; } std::stringstream ss; if (element == DKRml::Get()->document->GetContext()->GetRootElement()) ss << "window"; else if (element == DKRml::Get()->document->GetOwnerDocument()) ss << "document"; else if (element == DKRml::Get()->document) { //TEST: Let's just test if we ever hear anything from this one throw DKERROR("!!!! element = DKRml::Get()->document !!!!"); ss << "document"; } else { const void* address = static_cast<const void*>(element); #ifdef WIN32 ss << "0x" << address; #else ss << address; #endif } if (same("0xDDDDDDDD", ss.str())) return ""; return ss.str(); }
34.233723
147
0.691164
[ "object" ]
45fdaed525c24edb0dc3bc6fb62c162b12da1d4b
503
cpp
C++
CodeForces/Complete/600-699/618B-GuessThePermutation.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/600-699/618B-GuessThePermutation.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/600-699/618B-GuessThePermutation.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> #include <vector> #include <algorithm> int main(){ int n; std::cin >> n; std::vector<int> perm(n, 0); for(int row = 0; row < n; row++){ int current(0); for(int col = 0; col < n; col++){int x; std::cin >> x; current = std::max(current, x);} perm[row] = current; } for(int p = 0; p < n; p++){if(perm[p] == n - 1){perm[p] = n; break;}} for(int p = 0; p < n; p++){std::cout << perm[p] << " ";}; std::cout << std::endl; return 0; }
25.15
95
0.489066
[ "vector" ]
45fff1dcb706c7fe3e6232be8dd115be07044a00
2,003
hpp
C++
src/ELL_OPT.hpp
efocht/hpcg-ve-open
73dfcef70ad3dea32329264e035a602523ca1cf7
[ "BSD-3-Clause" ]
1
2022-02-12T03:22:50.000Z
2022-02-12T03:22:50.000Z
src/ELL_OPT.hpp
efocht/hpcg-ve-open
73dfcef70ad3dea32329264e035a602523ca1cf7
[ "BSD-3-Clause" ]
null
null
null
src/ELL_OPT.hpp
efocht/hpcg-ve-open
73dfcef70ad3dea32329264e035a602523ca1cf7
[ "BSD-3-Clause" ]
null
null
null
#ifndef ELL_OPT_HPP #define ELL_OPT_HPP #include "Geometry.hpp" // // +--------+--------+ // | | | // | | | // | L | U | n // | | | rows // | | | // | | | // +--------+--------+ // |<- mL ->|<- mU ->| // // matrix stored column wise, therefore both, L and U are contiguous in memory struct ELL_STRUCT{ double *a; local_int_t *ja; local_int_t lda; local_int_t n; local_int_t m; local_int_t mL; // width of lower matrix in MATRIX_LU format local_int_t mU; // width of upper matrix in MATRIX_LU format }; typedef struct ELL_STRUCT ELL; // // +--------+ // | | // | | // | | nah // | | rows // | | // | | // +--------+ // |<- mh ->| // // matrix stored column wise, therefore both, L and U are contiguous in memory struct HALO_STRUCT{ double *ah; local_int_t *jah; local_int_t *rows; // rows corresponding to each halo matrix row local_int_t *hcptr; // color pointer in halo matrix, for all colors local_int_t ldah; // leading dimension of halo matrix, usually nah local_int_t nh; // length of incoming/outgoing X values local_int_t nah; // length of AH matrix! local_int_t mh; // width of halo matrix double *v; // a vector for SPMV that should save alloc/free time }; typedef struct HALO_STRUCT HALO; struct OPT_STRUCT{ ELL *ell; HALO *halo; double *diag; double *idiag; local_int_t *perm0; // 0 origin local_int_t *iperm0; // 0 origin local_int_t *icptr; // pointer to start row of each color local_int_t *icolor; // color of each row. freed when not needed any more local_int_t maxcolor; // maximum color local_int_t *color_mL; // width of lower matrix in LU format for each color local_int_t *color_mU; // width of upper matrix in LU format for each color double * work1; double *work2; }; typedef struct OPT_STRUCT OPT; #endif
27.067568
78
0.581628
[ "geometry", "vector" ]
3411dee90fef5f34a6c612dd53c07af8c87a1a98
3,304
hpp
C++
include/topology/flag.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
5
2020-04-24T17:34:54.000Z
2021-04-07T15:56:00.000Z
include/topology/flag.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
5
2021-05-13T14:16:35.000Z
2021-08-15T15:11:55.000Z
include/topology/flag.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
1
2021-05-09T12:17:30.000Z
2021-05-09T12:17:30.000Z
#pragma once namespace bats { // template over filtration type // CpxT should be a template <typename CpxT, typename NT> void add_dimension_recursive_flag( CpxT &X, const NT &nbrs, // lists of neighbors const size_t d, // dimension const size_t maxd, // max dimension const std::vector<size_t> &iter_idxs, std::vector<size_t> &spx_idxs ) { // sorted simplices will end up here std::vector<size_t> spx_idxs2(spx_idxs.size() + 1); if (d == maxd) { // no recursion - we're adding maximal dimension cells for (auto k : iter_idxs) { // append k to spx_idxs, sort spx_idxs.push_back(k); bats::util::sort_into(spx_idxs, spx_idxs2); // add to X X.add(spx_idxs2); // pop k off spx_idxs spx_idxs.pop_back(); } } else if (d < maxd) { // d < maxd // recursion std::vector<size_t> iter_idxs2; // indices for recursing on iter_idxs2.reserve(iter_idxs.size()); for (auto k : iter_idxs) { // append k to spx_idxs, sort spx_idxs.push_back(k); bats::util::sort_into(spx_idxs, spx_idxs2); // add to X X.add(spx_idxs2); // recurse bats::util::intersect_sorted_lt(iter_idxs, nbrs[k], k, iter_idxs2); add_dimension_recursive_flag(X, nbrs, d+1, maxd, iter_idxs2, spx_idxs2); // pop k off spx_idxs spx_idxs.pop_back(); } } // else do nothing } // Flag complex using list of edges // (edges[2*k], edges[2*k+1]) = (i, j) is an edge // n - number of vertices // maxdim - maximum dimension of simplices template <typename CpxT> CpxT FlagComplex( const std::vector<size_t> &edges, const size_t n, // number of 0-cells const size_t maxdim ) { // check that dimensions agree size_t m = edges.size() / 2; if (!(edges.size() == 2 * m)) { throw std::logic_error("edge vector must have length multiple of 2!"); } // X = SimplicialComplex(maxdim); // F = Filtration<T, SimplicialComplex>(X); // reset simplicial complex CpxT X(n, maxdim); // sets 0-cells std::vector<size_t> spx_idxs(1); for (size_t k = 0; k < n; k++) { spx_idxs[0] = k; X.add(spx_idxs); } std::vector<std::vector<size_t>> nbrs(n); spx_idxs.resize(2); // now time to add edges std::vector<size_t> iter_idxs; iter_idxs.reserve(n); // maximum size for (size_t k = 0; k < m; k++) { size_t i = edges[2*k]; size_t j = edges[2*k + 1]; spx_idxs[0] = i; spx_idxs[1] = j; X.add(spx_idxs); // std::cout << ret.second << std::endl; bats::util::intersect_sorted(nbrs[i], nbrs[j], iter_idxs); if (!iter_idxs.empty()) { add_dimension_recursive_flag(X, nbrs, 2, maxdim, iter_idxs, spx_idxs); } // TODO: use std::set for neighbors - insertion is log(n) // nbrs[i].emplace(j); // nbrs[j].emplace(i); // TODO: insertion sort nbrs[i].emplace_back(j); std::sort(nbrs[i].begin(), nbrs[i].end()); nbrs[j].emplace_back(i); std::sort(nbrs[j].begin(), nbrs[j].end()); } return X; } } // namespace bats
28
84
0.565375
[ "vector" ]
3417d155aa0b94bb76c06c5473f92fe89f819ee9
703
hpp
C++
src/input/action_factory.hpp
DonRomanos/Terms_of_Enrampagement
7c825e1d6f460809df97af645736b69c27acadf8
[ "MIT" ]
null
null
null
src/input/action_factory.hpp
DonRomanos/Terms_of_Enrampagement
7c825e1d6f460809df97af645736b69c27acadf8
[ "MIT" ]
null
null
null
src/input/action_factory.hpp
DonRomanos/Terms_of_Enrampagement
7c825e1d6f460809df97af645736b69c27acadf8
[ "MIT" ]
null
null
null
#pragma once #include "actions.hpp" #include "input_provider.hpp" #include "action_table.hpp" #include <vector> #include <memory> struct GLFWwindow; namespace input { class ActionFactory { public: [[nodiscard]] virtual std::vector<core::Actions> produce_actions() = 0; virtual ~ActionFactory() = 0 {}; }; class DefaultActionFactory : public ActionFactory { public: explicit DefaultActionFactory(GLFWwindow* window); DefaultActionFactory(std::unique_ptr<InputProvider>&& input_source, InputActionTable action_table); [[nodiscard]] virtual std::vector<core::Actions> produce_actions(); private: std::unique_ptr<InputProvider> input_source; InputActionTable action_table; }; }
21.30303
101
0.753912
[ "vector" ]
34242ce5b6dc3cbbcc8b41c79ad80dbc9134a1ff
11,803
cpp
C++
cpp/extras/benchmarks/bench.cpp
tenzir/libfilter
d0d23243f841cc625588afc16f2cacdfeb1cae56
[ "Apache-2.0" ]
22
2020-08-04T15:13:52.000Z
2022-02-08T18:51:09.000Z
cpp/extras/benchmarks/bench.cpp
tenzir/libfilter
d0d23243f841cc625588afc16f2cacdfeb1cae56
[ "Apache-2.0" ]
3
2021-10-09T00:38:05.000Z
2022-01-24T02:27:16.000Z
cpp/extras/benchmarks/bench.cpp
tenzir/libfilter
d0d23243f841cc625588afc16f2cacdfeb1cae56
[ "Apache-2.0" ]
2
2021-03-31T04:34:54.000Z
2021-06-22T19:30:34.000Z
// This is a benchmark of insert time, find time, (both in nanoseconds) and false positive // probability. The results are printed to stdout. // // The output is CSV. Each line has the form // // filter_name, ndv, bytes, sample_type, payload // // The sample_type can be "insert_nanos", "find_nanos", or "fpp". #include <algorithm> #include <chrono> // for nanoseconds, duration, duration_cast #include <cstdint> // for uint64_t #include <iostream> // for operator<<, basic_ostream, endl, istr... #include <sstream> // for basic_istringstream #include <string> // for string, operator<<, operator== #include <tuple> // for tuple #include <utility> #include <vector> // for vector, allocator #include "cuckoo32.hpp" #include "cuckoofilter.h" #include "filter/block.hpp" // for BlockFilter, ScalarBlockFilter (ptr o... #include "filter/minimal-taffy-cuckoo.hpp" #include "filter/taffy-block.hpp" #include "filter/taffy-cuckoo.hpp" #include "filter/taffy-vector-quotient.hpp" #include "util.hpp" // for Rand using namespace filter; using namespace std; // TODO: since we're printing out stats directly, there is no reason to return any values // from the benchmarking functions. // A single statistic. sample_type must be "insert_nanos", "find_missing_nanos", // "find_present_nanos", "to_fin_base", "to_ins_base", or "fpp". // // "to_fin_base" is how long it takes just to iterate over the absent elements being // found. This can be subtracted from find_missing_nanos to remove the baseline cost and // focus on the find cost only. // // "to_ins_base" is the same, but for the present elements. struct Sample { string filter_name = "", sample_type = ""; uint64_t ndv_start = 0; uint64_t ndv_finish = 0; uint64_t bytes = 0; double payload = 0.0; static const char* kHeader() { static const char result[] = "filter_name,ndv_start,ndv_finish,bytes,sample_type,payload"; return result; }; // Escape quotation marks in strings static string EscapedName(const string& x) { string result = "\""; for (char c : x) { result += c; if (c == '"') result += "\""; } result += "\""; return result; } string CSV() const { ostringstream o; o << EscapedName(filter_name) << ","; o << ndv_start << "," << ndv_finish << "," << bytes << ","; o << EscapedName(sample_type) << ","; o << payload; return o.str(); } }; template <size_t bits_per_item> struct CuckooShim { cuckoofilter::CuckooFilter<uint64_t, bits_per_item> payload; static string Name() { thread_local static const string result = "Cuckoo"; return result; } bool InsertHash(uint64_t h) { return cuckoofilter::Ok == payload.Add(h); } uint64_t SizeInBytes() const { return payload.SizeInBytes(); } bool FindHash(uint64_t h) const { return payload.Contain(h) == 0; } explicit CuckooShim(uint64_t n) : payload(n) {} static CuckooShim CreateWithBytes(uint64_t bytes) { uint64_t last = bytes; CuckooShim result(last); while (result.SizeInBytes() > bytes) { result.~CuckooShim(); last = last / 2; new (&result) CuckooShim(last); } return result; } static CuckooShim CreateWithNdvFpp(uint64_t ndv, double) { return CuckooShim(ndv); } }; struct Cuckoo32Shim { Cuckoo32 payload; static string Name() { thread_local static const string result = "Cuckoo32"; return result; } bool InsertHash(uint64_t h) { payload.Insert((h * 0xc7ea1a71f80b4b0b) >> 32); return true; } uint64_t SizeInBytes() const { return payload.Capacity() * 4; } bool FindHash(uint64_t h) const { return payload.Find((h * 0xc7ea1a71f80b4b0b) >> 32); } explicit Cuckoo32Shim(uint64_t ) : payload() {} static Cuckoo32Shim CreateWithBytes(uint64_t) { return Cuckoo32Shim(0); } static Cuckoo32Shim CreateWithNdvFpp(uint64_t, double) { return Cuckoo32Shim(0); } }; // Does the actual benchmarking work. Repeasts `reps` times, samples grow by // `growth_factor`. // // TODO: does all the printing. Why bother returning a value at all? template <typename FILTER_TYPE> vector<Sample> BenchHelp(uint64_t reps, double growth_factor, vector<uint64_t>& to_insert, const vector<uint64_t>& to_find, FILTER_TYPE& filter) { Sample base; base.filter_name = FILTER_TYPE::Name(); vector<Sample> result; chrono::steady_clock s; // insert_nanos: double last = 0, next = 1; Rand r; while (last < to_insert.size()) { const auto start = s.now(); for (uint64_t i = last; i < min(to_insert.size(), static_cast<size_t>(next)); ++i) { if (not filter.InsertHash(to_insert[i])) { next = i; to_insert.resize(i); break; } } const auto finish = s.now(); base.ndv_start = last; base.ndv_finish = next; if (base.ndv_finish > base.ndv_start) { base.bytes = filter.SizeInBytes(); const auto insert_time = static_cast<std::chrono::duration<double>>(finish - start); base.sample_type = "insert_nanos"; // TODO: shouldn't the denominator be min(to_insert.size(), // static_cast<uint64_t>(next)) - last? base.payload = 1.0 * chrono::duration_cast<chrono::nanoseconds>(insert_time).count() / min(to_insert.size(), static_cast<size_t>(next - last)); result.push_back(base); cout << base.CSV() << endl; uint64_t found = 0; // Just something to force computation so the optimizer doesn't fully elide a loop uint64_t dummy = 0; uint64_t found_monotonic = 0; for (unsigned j = 0; j < reps; ++j) { const auto start = s.now(); for (unsigned i = 0; i < 1000 * 1000; ++i) { found += filter.FindHash(to_find[r() % static_cast<uint64_t>(next)]); } const auto finish = s.now(); for (unsigned i = 0; i < 1000 * 1000; ++i) { dummy += to_find[r() % static_cast<uint64_t>(next)]; } const auto finality = s.now(); auto find_time = static_cast<std::chrono::duration<double>>(finish - start); base.sample_type = "find_missing_nanos"; base.payload = 1.0 * chrono::duration_cast<chrono::nanoseconds>(find_time).count() / 1000 / 1000; result.push_back(base); cout << base.CSV() << endl; find_time = static_cast<std::chrono::duration<double>>(finality - finish); base.sample_type = "to_fin_base"; base.payload = 1.0 * chrono::duration_cast<chrono::nanoseconds>(find_time).count() / 1000 / 1000; result.push_back(base); cout << base.CSV() << endl; for (unsigned i = 0; i < 1000 * 1000; ++i) { found_monotonic += filter.FindHash(to_find[i]); } } base.sample_type = "fpp"; base.payload = 1.0 * found_monotonic / 1000 / 1000 / reps; result.push_back(base); cout << base.CSV() << endl; for (unsigned j = 0; j < reps; ++j) { const auto start = s.now(); for (uint64_t i = 0; i < 1000 * 1000; ++i) { found += filter.FindHash(to_insert[r() % static_cast<uint64_t>(next)]); } const auto finish = s.now(); for (uint64_t i = 0; i < 1000 * 1000; ++i) { found += to_insert[r() % static_cast<uint64_t>(next)]; } const auto finality = s.now(); auto find_time = static_cast<std::chrono::duration<double>>(finish - start); base.sample_type = "find_present_nanos"; base.payload = 1.0 * chrono::duration_cast<chrono::nanoseconds>(find_time).count() / 1000 / 1000; result.push_back(base); cout << base.CSV() << endl; find_time = static_cast<std::chrono::duration<double>>(finality - finish); base.sample_type = "to_ins_base"; base.payload = 1.0 * chrono::duration_cast<chrono::nanoseconds>(find_time).count() / 1000 / 1000; result.push_back(base); cout << base.CSV() << endl; } // Force the FindHash value to be calculated: if (found & dummy & found_monotonic) { // do something nearly nilpotent that the compiler can't figure out is a no-op result.push_back(base); result.pop_back(); } } double tmp = last; last = next; next = (tmp * growth_factor) + 1; } return result; } template <typename FILTER_TYPE> vector<Sample> BenchWithBytes(uint64_t reps, uint64_t bytes, double growth_factor, vector<uint64_t>& to_insert, const vector<uint64_t>& to_find) { auto filter = FILTER_TYPE::CreateWithBytes(bytes); return BenchHelp(reps, growth_factor, to_insert, to_find, filter); } template <typename FILTER_TYPE> vector<Sample> BenchWithNdvFpp(uint64_t reps, double growth_factor, vector<uint64_t>& to_insert, const vector<uint64_t>& to_find, uint64_t ndv, double fpp) { auto filter = FILTER_TYPE::CreateWithNdvFpp(ndv, fpp); return BenchHelp(reps, growth_factor, to_insert, to_find, filter); } template <typename FILTER_TYPE> vector<Sample> BenchGrowWithNdvFpp(uint64_t reps, double growth_factor, vector<uint64_t>& to_insert, const vector<uint64_t>& to_find, uint64_t, double fpp) { auto filter = FILTER_TYPE::CreateWithNdvFpp(32, fpp); return BenchHelp(reps, growth_factor, to_insert, to_find, filter); } void Samples(uint64_t ndv, vector<uint64_t>& to_insert, vector<uint64_t>& to_find) { Rand r; for (unsigned i = 0; i < ndv; ++i) { to_insert.push_back(r()); } for (unsigned i = 0; i < std::max(ndv, static_cast<uint64_t>(1000 * 1000)); ++i) { to_find.push_back(r()); } } int main(int argc, char** argv) { if (argc < 7) { err: cerr << "one optional flag (--print_header) and four required flags: --ndv, --reps, " "--bytes, --fpp\n"; return 1; } uint64_t ndv = 0, reps = 0, bytes = 0; double fpp = 0.0; bool print_header = false; for (int i = 1; i < argc; ++i) { if (argv[i] == string("--ndv")) { ++i; auto s = istringstream(argv[i]); if (not(s >> ndv)) goto err; if (not s.eof()) goto err; } else if (argv[i] == string("--reps")) { ++i; auto s = istringstream(argv[i]); if (not(s >> reps)) goto err; if (not s.eof()) goto err; } else if (argv[i] == string("--bytes")) { ++i; auto s = istringstream(argv[i]); if (not(s >> bytes)) goto err; if (not s.eof()) goto err; } else if (argv[i] == string("--fpp")) { ++i; auto s = istringstream(argv[i]); if (not(s >> fpp)) goto err; if (not s.eof()) goto err; } else if (argv[i] == string("--print_header")) { print_header = true; } else { goto err; } } if (reps == 0 or ndv == 0 or reps == 0 or fpp == 0 or bytes == 0) goto err; vector<uint64_t> to_insert; vector<uint64_t> to_find; Samples(ndv, to_insert, to_find); if (print_header) cout << Sample::kHeader() << endl; for (unsigned i = 0; i < reps; ++i) { BenchWithBytes<Cuckoo32Shim>(reps, bytes, 1.05, to_insert, to_find); BenchWithNdvFpp<CuckooShim<12>>(reps, 1.05, to_insert, to_find, ndv, fpp); BenchWithBytes<MinimalTaffyCuckooFilter>(reps, bytes, 1.05, to_insert, to_find); BenchWithBytes<TaffyCuckooFilter>(reps, bytes, 1.05, to_insert, to_find); BenchGrowWithNdvFpp<TaffyBlockFilter>(reps, 1.05, to_insert, to_find, ndv, fpp); BenchWithNdvFpp<BlockFilter>(reps, 1.05, to_insert, to_find, ndv, fpp); } }
35.87538
94
0.613912
[ "vector" ]
342b0f358818e789e33e65b82f9ffbcca9aed66d
29,565
cpp
C++
test/qcan/test_qcan_frame.cpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
36
2016-08-23T13:05:02.000Z
2022-02-13T07:11:05.000Z
test/qcan/test_qcan_frame.cpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
19
2017-01-30T08:59:40.000Z
2018-10-30T07:55:33.000Z
test/qcan/test_qcan_frame.cpp
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
16
2016-06-02T11:15:02.000Z
2020-07-10T11:49:12.000Z
//====================================================================================================================// // File: test_qcan_frame.cpp // // Description: QCAN classes - Test QCan frame // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //--------------------------------------------------------------------------------------------------------------------// // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions, the following // // disclaimer and the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products // // derived from this software without specific prior written permission. // // // // 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 files ** ** ** \*--------------------------------------------------------------------------------------------------------------------*/ #include <iostream> using namespace std; #include "test_qcan_frame.hpp" #include "cp_msg.h" /*--------------------------------------------------------------------------------------------------------------------*\ ** Definitions ** ** ** \*--------------------------------------------------------------------------------------------------------------------*/ #define TEST_VALUE_DATA ((uint8_t) 0xA5) #define TEST_VALUE_DLC ((uint8_t) 0x05) #define TEST_VALUE_ID_STD ((uint32_t) 0x00000405) #define TEST_VALUE_ID_EXT ((uint32_t) 0x01B2F405) #define TEST_VALUE_MARKER ((uint32_t) 0x98765432) #define TEST_VALUE_TIME_STAMP ((uint32_t) 10245) #define TEST_VALUE_USER ((uint32_t) 0xAB64281F) //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::TestQCanFrame() // // frame type and frame format stay the same through all test cases // //--------------------------------------------------------------------------------------------------------------------// TestQCanFrame::TestQCanFrame() { pclCanStdP = (QCanFrame *) 0L; pclCanExtP = (QCanFrame *) 0L; pclFdStdP = (QCanFrame *) 0L; pclFdExtP = (QCanFrame *) 0L; pclErrorP = (QCanFrame *) 0L; pclFrameP = (QCanFrame *) 0L; } TestQCanFrame::~TestQCanFrame() { } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkByteArray() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkByteArray() { QByteArray clByteArrayT; for (uint8_t ubCntT = 0; ubCntT < 9; ubCntT++) { pclCanStdP->setIdentifier(0x301 + ubCntT); pclCanStdP->setDlc(ubCntT); pclCanStdP->setData(0, ubCntT); pclCanStdP->setData(1, 0x10 + ubCntT); pclCanStdP->setData(2, 0x20 + ubCntT); pclCanStdP->setData(3, 0x30 + ubCntT); pclCanStdP->setData(4, 0x40 + ubCntT); pclCanStdP->setData(5, 0x50 + ubCntT); pclCanStdP->setData(6, 0x60 + ubCntT); pclCanStdP->setData(7, 0x70 + ubCntT); pclCanStdP->setMarker(0x223344); pclCanStdP->setUser(0xAB1023); clByteArrayT = pclCanStdP->toByteArray(); QVERIFY(pclFrameP->fromByteArray(clByteArrayT) == true); QVERIFY(pclFrameP->identifier() == (0x301 + ubCntT)); QVERIFY(pclFrameP->dlc() == (ubCntT)); if(ubCntT == 4) { QVERIFY(pclFrameP->data(0) == (ubCntT)); QVERIFY(pclFrameP->data(1) == (0x10 + ubCntT)); QVERIFY(pclFrameP->data(2) == (0x20 + ubCntT)); QVERIFY(pclFrameP->data(3) == (0x30 + ubCntT)); QVERIFY(pclFrameP->data(4) == 0); } } //--------------------------------------------------------------------------------------------------- // test conversion of time-stamp and injection into existing byte array // QCanTimeStamp clTimeStampT; clTimeStampT.setSeconds(4); clTimeStampT.setNanoSeconds(120340560); QByteArray clTimeArrayT = clTimeStampT.toByteArray(); clByteArrayT.replace(QCAN_FRAME_TIME_STAMP_POS, 8, clTimeArrayT); QCanFrame clFrameT; QVERIFY(clFrameT.fromByteArray(clByteArrayT) == true); QCanTimeStamp clTimeStampResultT = clFrameT.timeStamp(); QVERIFY(clTimeStampResultT.seconds() == 4); QVERIFY(clTimeStampResultT.nanoSeconds() == 120340560); clTimeStampT.setSeconds(477890321); clTimeStampT.setNanoSeconds(987501234); clTimeArrayT = clTimeStampT.toByteArray(); clByteArrayT.replace(QCAN_FRAME_TIME_STAMP_POS, 8, clTimeArrayT); QVERIFY(clFrameT.fromByteArray(clByteArrayT) == true); clTimeStampResultT = clFrameT.timeStamp(); QVERIFY(clTimeStampResultT.seconds() == 477890321); QVERIFY(clTimeStampResultT.nanoSeconds() == 987501234); } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkConversion() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkConversion() { uint8_t ubCntT = 0; uint8_t ubDataCntT = 0; CpCanMsg_ts tsCanMsgT; //--------------------------------------------------------------------------------------------------- // test conversion of standard frame // QCanFrame -> CpCanMsg structure // for (ubCntT = 8; ubCntT <= 64; ubCntT ++) { pclCanStdP->setIdentifier(0x100 + ubCntT); pclCanStdP->setDlc(ubCntT); pclCanStdP->setData(0, ubCntT); pclCanStdP->setData(1, 0x10 + ubCntT); pclCanStdP->setData(2, 0x20 + ubCntT); pclCanStdP->setData(3, 0x30 + ubCntT); pclCanStdP->setData(4, 0x40 + ubCntT); pclCanStdP->setData(5, 0x50 + ubCntT); pclCanStdP->setData(6, 0x60 + ubCntT); pclCanStdP->setData(7, 0x70 + ubCntT); //------------------------------------------------------------------------------------------- // Convert to CpCanMsg_s structure // QVERIFY(pclCanStdP->toCpCanMsg(&tsCanMsgT) == true); QVERIFY(CpMsgIsFdFrame(&tsCanMsgT) == false); QVERIFY(CpMsgIsExtended(&tsCanMsgT) == false); QVERIFY(CpMsgGetIdentifier(&tsCanMsgT) == pclCanStdP->identifier()); QVERIFY(CpMsgGetDlc(&tsCanMsgT) == pclCanStdP->dlc()); for (ubDataCntT = 0; ubDataCntT < pclCanStdP->dataSize(); ubDataCntT++) { QVERIFY(CpMsgGetData(&tsCanMsgT, ubDataCntT) == pclCanStdP->data(ubDataCntT)); } //------------------------------------------------------------------------------------------- // Convert CpCanMsg_s structure to QCanFrame // QVERIFY(pclFrameP->fromCpCanMsg(&tsCanMsgT) == true); QVERIFY(pclCanStdP->frameFormat() == pclFrameP->frameFormat()); QVERIFY(pclCanStdP->identifier() == pclFrameP->identifier()); QVERIFY(pclCanStdP->dlc() == pclFrameP->dlc()); for (ubDataCntT = 0; ubDataCntT < pclCanStdP->dataSize(); ubDataCntT++) { QVERIFY(pclCanStdP->data(ubDataCntT) == pclFrameP->data(ubDataCntT)); } } } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkErrorFrame() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkErrorFrame() { } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameBitrateSwitch() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameBitrateSwitch() { //--------------------------------------------------------------------------------------------------- // bit-rate switch is disabled by default // QVERIFY(pclCanStdP->bitrateSwitch() == false); QVERIFY(pclCanExtP->bitrateSwitch() == false); QVERIFY(pclFdStdP->bitrateSwitch() == false); QVERIFY(pclFdExtP->bitrateSwitch() == false); //--------------------------------------------------------------------------------------------------- // enable bit-rate switch and test it // pclCanStdP->setBitrateSwitch(true); pclCanExtP->setBitrateSwitch(true); pclFdStdP->setBitrateSwitch(true); pclFdExtP->setBitrateSwitch(true); QVERIFY(pclCanStdP->bitrateSwitch() == false); QVERIFY(pclCanExtP->bitrateSwitch() == false); QVERIFY(pclFdStdP->bitrateSwitch() == true); QVERIFY(pclFdExtP->bitrateSwitch() == true); //--------------------------------------------------------------------------------------------------- // copy FD frame contents and convert type to classic CAN // *pclFrameP = *pclFdStdP; QVERIFY(pclFrameP->bitrateSwitch() == true); pclFrameP->setFrameFormat(QCanFrame::eFORMAT_CAN_STD); QVERIFY(pclFrameP->bitrateSwitch() == false); //--------------------------------------------------------------------------------------------------- // disable bit-rate switch and test it // pclCanStdP->setBitrateSwitch(false); pclCanExtP->setBitrateSwitch(false); pclFdStdP->setBitrateSwitch(false); pclFdExtP->setBitrateSwitch(false); QVERIFY(pclCanStdP->bitrateSwitch() == false); QVERIFY(pclCanExtP->bitrateSwitch() == false); QVERIFY(pclFdStdP->bitrateSwitch() == false); QVERIFY(pclFdExtP->bitrateSwitch() == false); } //--------------------------------------------------------------------------------------------------------------------// // checkFrameData() // // check frame data // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameData() { pclCanStdP->setDlc(4); pclCanStdP->setData(0, 0x12); pclCanStdP->setData(1, 0x34); pclCanStdP->setData(2, 0x56); pclCanStdP->setData(3, 0x78); bool btMsbFirstT = true; QVERIFY(pclCanStdP->dataUInt16(0, btMsbFirstT) == 0x1234); QVERIFY(pclCanStdP->dataUInt16(1, btMsbFirstT) == 0x3456); QVERIFY(pclCanStdP->dataUInt16(2, btMsbFirstT) == 0x5678); QVERIFY(pclCanStdP->dataUInt16(3, btMsbFirstT) == 0x0000); QVERIFY(pclCanStdP->dataUInt32(0, btMsbFirstT) == 0x12345678); btMsbFirstT = false; QVERIFY(pclCanStdP->dataUInt16(0, btMsbFirstT) == 0x3412); QVERIFY(pclCanStdP->dataUInt16(1, btMsbFirstT) == 0x5634); QVERIFY(pclCanStdP->dataUInt16(2, btMsbFirstT) == 0x7856); QVERIFY(pclCanStdP->dataUInt16(3, btMsbFirstT) == 0x0000); QVERIFY(pclCanStdP->dataUInt32(0, btMsbFirstT) == 0x78563412); pclCanStdP->setDataUInt16(0, 0xAABB); QVERIFY(pclCanStdP->data(0) == 0xBB); QVERIFY(pclCanStdP->data(1) == 0xAA); QVERIFY(pclCanStdP->dataUInt16(0, 0) == 0xAABB); } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameDataSize() // // test invalid data size combinations // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameDataSize() { uint8_t ubSizeT; //--------------------------------------------------------------------------------------------------- // Test 1: set the data size value for classic CAN and CAN FD and check the result for the // dlc() return value // for (ubSizeT = 0; ubSizeT < 9; ubSizeT++) { pclCanStdP->setDataSize(ubSizeT); pclFdStdP->setDataSize(ubSizeT); QVERIFY(pclCanStdP->dlc() == ubSizeT); QVERIFY(pclFdStdP->dlc() == ubSizeT); } for (ubSizeT = 9; ubSizeT <= 12; ubSizeT++) { pclCanStdP->setDataSize(ubSizeT); pclFdStdP->setDataSize(ubSizeT); QVERIFY(pclCanStdP->dlc() == 8); QVERIFY(pclFdStdP->dlc() == 9); } for (ubSizeT = 13; ubSizeT <= 16; ubSizeT++) { pclCanStdP->setDataSize(ubSizeT); pclFdStdP->setDataSize(ubSizeT); QVERIFY(pclCanStdP->dlc() == 8); QVERIFY(pclFdStdP->dlc() == 10); } for (ubSizeT = 17; ubSizeT <= 20; ubSizeT++) { pclCanStdP->setDataSize(ubSizeT); pclFdStdP->setDataSize(ubSizeT); QVERIFY(pclCanStdP->dlc() == 8); QVERIFY(pclFdStdP->dlc() == 11); } } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameDlc() // // test invalid DLC combinations // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameDlc() { uint8_t ubSizeT; //--------------------------------------------------------------------------------------------------- // Test 1: set the DLC value for classic CAN and CAN FD and check the result for the dataSize() // return value // for (ubSizeT = 0; ubSizeT < 16; ubSizeT++) { pclCanStdP->setDlc(ubSizeT); pclFdStdP->setDlc(ubSizeT); //------------------------------------------------------------------------------------------- // check data size // if(ubSizeT < 9) { QVERIFY(pclCanStdP->dataSize() == ubSizeT); QVERIFY(pclFdStdP->dataSize() == ubSizeT); } else { //----------------------------------------------------------------------------------- // copy FD frame contents and convert type to classic CAN // *pclFrameP = *pclFdStdP; pclFrameP->setFrameFormat(QCanFrame::eFORMAT_CAN_STD); //----------------------------------------------------------------------------------- // make sure maximum dataSize of classic CAN is 8 // QVERIFY(pclFrameP->dataSize() == 8); QVERIFY(pclCanStdP->dataSize() == 8); //----------------------------------------------------------------------------------- // check data size of CAN FD // switch (ubSizeT) { case 9: QVERIFY(pclFdStdP->dataSize() == 12); break; case 10: QVERIFY(pclFdStdP->dataSize() == 16); break; case 11: QVERIFY(pclFdStdP->dataSize() == 20); break; case 12: QVERIFY(pclFdStdP->dataSize() == 24); break; case 13: QVERIFY(pclFdStdP->dataSize() == 32); break; case 14: QVERIFY(pclFdStdP->dataSize() == 48); break; case 15: QVERIFY(pclFdStdP->dataSize() == 64); break; default: break; } } //------------------------------------------------------------------------------------------- // check DLC // if(ubSizeT < 9) { QVERIFY(pclCanStdP->dlc() == ubSizeT); QVERIFY(pclFdStdP->dlc() == ubSizeT); } else { QVERIFY(pclCanStdP->dlc() == 8); QVERIFY(pclFdStdP->dlc() == ubSizeT); } } //--------------------------------------------------------------------------------------------------- // Test 2: set DLC value out of range // pclCanStdP->setDlc(TEST_VALUE_DLC); pclFdStdP->setDlc(TEST_VALUE_DLC); for (ubSizeT = 255; ubSizeT > 15; ubSizeT--) { pclCanStdP->setDlc(ubSizeT); pclFdStdP->setDlc(ubSizeT); QVERIFY(pclCanStdP->dlc() == TEST_VALUE_DLC); QVERIFY(pclFdStdP->dlc() == TEST_VALUE_DLC); } } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameErrorIndicator() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameErrorIndicator() { } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameFormat() // // test the initial frame format // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameFormat() { QVERIFY(pclCanStdP->frameFormat() == QCanFrame::eFORMAT_CAN_STD); QVERIFY(pclCanExtP->frameFormat() == QCanFrame::eFORMAT_CAN_EXT); QVERIFY(pclFdStdP->frameFormat() == QCanFrame::eFORMAT_FD_STD); QVERIFY(pclFdExtP->frameFormat() == QCanFrame::eFORMAT_FD_EXT); } //--------------------------------------------------------------------------------------------------------------------// // checkFrameId() // // check frame identifier // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameId() { uint32_t ulIdValueT; for (ulIdValueT = 0; ulIdValueT <= 0x0000FFFF; ulIdValueT++) { pclCanStdP->setIdentifier(ulIdValueT); pclCanExtP->setIdentifier(ulIdValueT); *pclFrameP = *pclCanStdP; if (ulIdValueT <= 0x07FF) { QVERIFY(pclCanStdP->identifier() == ulIdValueT); QVERIFY(pclFrameP->identifier() == ulIdValueT); } else { QVERIFY(pclCanStdP->identifier() == (ulIdValueT & 0x07FF)); QVERIFY(pclFrameP->identifier() == (ulIdValueT & 0x07FF)); } QVERIFY(pclCanExtP->identifier() == ulIdValueT); QVERIFY(pclCanStdP->isExtended() == 0); QVERIFY(pclFrameP->isExtended() == 0); } } //--------------------------------------------------------------------------------------------------------------------// // checkFrameRemote() // // check remote frame // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameRemote() { // classic CAN,set remote, change frame type to FD, check remote } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkFrameType() // // test the initial frame type // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkFrameType() { QVERIFY(pclCanStdP->frameType() == QCanFrame::eFRAME_TYPE_DATA); *pclFrameP = *pclCanStdP; QVERIFY(pclFrameP->frameType() == QCanFrame::eFRAME_TYPE_DATA); QVERIFY(pclCanExtP->frameType() == QCanFrame::eFRAME_TYPE_DATA); *pclFrameP = *pclCanExtP; QVERIFY(pclFrameP->frameType() == QCanFrame::eFRAME_TYPE_DATA); QVERIFY(pclErrorP->frameType() == QCanFrame::eFRAME_TYPE_ERROR); *pclFrameP = *pclErrorP; QVERIFY(pclFrameP->frameType() == QCanFrame::eFRAME_TYPE_ERROR); QVERIFY(pclFdStdP->frameType() == QCanFrame::eFRAME_TYPE_DATA); QVERIFY(pclFdExtP->frameType() == QCanFrame::eFRAME_TYPE_DATA); } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::checkOutput() // // test toString() functionality // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::checkOutput() { QString clStringT; bool btMsbFirstT = true; //--------------------------------------------------------------------------------------------------- // set default values for classic CAN frames // pclCanStdP->setIdentifier(TEST_VALUE_ID_STD); pclCanStdP->setDlc(7); pclCanStdP->setDataUInt32(0, 0xA1B2C3D4, btMsbFirstT); fprintf(stdout, "%s\n", qPrintable(pclCanStdP->toString())); clStringT = pclCanStdP->toString(); QVERIFY(clStringT.contains("CBFF" , Qt::CaseSensitive) == true); QVERIFY(clStringT.contains("7" , Qt::CaseSensitive) == true); QVERIFY(clStringT.contains("405" , Qt::CaseSensitive) == true); QVERIFY(clStringT.contains("A1 B2 C3 D4" , Qt::CaseSensitive) == true); pclCanExtP->setIdentifier(TEST_VALUE_ID_EXT); pclCanExtP->setDlc(7); pclCanExtP->setDataUInt32(0, 0x0123); fprintf(stdout, "%s\n", qPrintable(pclCanExtP->toString())); clStringT = pclCanExtP->toString(); QVERIFY(clStringT.contains("CEFF", Qt::CaseSensitive) == true); QVERIFY(clStringT.contains("405" , Qt::CaseSensitive) == true); //--------------------------------------------------------------------------------------------------- // set default values for CAN FD frames // pclFdStdP->setIdentifier(TEST_VALUE_ID_STD); pclFdStdP->setDlc(9); pclFdStdP->setDataUInt32(0, 0xA1B2C3D4); fprintf(stdout, "%s\n", qPrintable(pclFdStdP->toString())); pclFdStdP->setBitrateSwitch(true); fprintf(stdout, "%s\n", qPrintable(pclFdStdP->toString())); pclFdStdP->setErrorStateIndicator(true); fprintf(stdout, "%s\n", qPrintable(pclFdStdP->toString())); pclFdExtP->setIdentifier(TEST_VALUE_ID_EXT); pclCanStdP->setDlc(12); pclCanStdP->setDataUInt32(0, 0x0123); fprintf(stdout, "%s\n", qPrintable(pclFdExtP->toString())); //--------------------------------------------------------------------------------------------------- // set Remote frame // pclCanStdP->setRemote(true); fprintf(stdout, "%s\n", qPrintable(pclCanStdP->toString())); //--------------------------------------------------------------------------------------------------- // Check error frame // fprintf(stdout, "%s\n", qPrintable(pclErrorP->toString())); } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::cleanupTestCase() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::cleanupTestCase() { delete (pclCanStdP); delete (pclCanExtP); delete (pclFdStdP); delete (pclFdExtP); delete (pclErrorP); delete (pclFrameP); } //--------------------------------------------------------------------------------------------------------------------// // TestQCanFrame::initTestCase() // // // //--------------------------------------------------------------------------------------------------------------------// void TestQCanFrame::initTestCase() { pclCanStdP = new QCanFrame(QCanFrame::eFORMAT_CAN_STD); pclCanStdP->setIdentifier(TEST_VALUE_ID_STD); pclCanExtP = new QCanFrame(QCanFrame::eFORMAT_CAN_EXT); pclCanExtP->setIdentifier(TEST_VALUE_ID_EXT); pclFdStdP = new QCanFrame(QCanFrame::eFORMAT_FD_STD); pclFdStdP->setIdentifier(TEST_VALUE_ID_STD); pclFdExtP = new QCanFrame(QCanFrame::eFORMAT_FD_EXT); pclFdExtP->setIdentifier(TEST_VALUE_ID_EXT); pclErrorP = new QCanFrame(QCanFrame::eFRAME_TYPE_ERROR); //--------------------------------------------------------------------------------------------------- // testing is done after assignment with the pclFrameP object // pclFrameP = new QCanFrame(); }
43.541973
120
0.390631
[ "object" ]
3431a3d8af447f9db9c165cd881c2ea9f3f4a69c
16,030
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/hdmi/HdmiTimerRecordSources.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/hdmi/HdmiTimerRecordSources.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/hdmi/HdmiTimerRecordSources.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 "elastos/droid/hardware/hdmi/HdmiTimerRecordSources.h" #include <elastos/utility/logging/Logger.h> using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Hardware { namespace Hdmi { CAR_INTERFACE_IMPL(HdmiTimerRecordSources::TimeUnit, Object, IHdmiTimerRecordSourcesTimeUnit) HdmiTimerRecordSources::TimeUnit::TimeUnit( /* [in] */ Int32 hour, /* [in] */ Int32 minute) : mHour(hour) , mMinute(minute) { } ECode HdmiTimerRecordSources::TimeUnit::ToByteArray( /* [in] */ ArrayOf<Byte>* data, /* [in] */ Int32 index, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); (*data)[index] = ToBcdByte(mHour); (*data)[index + 1] = ToBcdByte(mMinute); *result = 2; return NOERROR; } Byte HdmiTimerRecordSources::TimeUnit::ToBcdByte( /* [in] */ Int32 value) { Int32 digitOfTen = (value / 10) % 10; Int32 digitOfOne = value % 10; return (Byte)((digitOfTen << 4) | digitOfOne); } CAR_INTERFACE_IMPL(HdmiTimerRecordSources::Time, TimeUnit, IHdmiTimerRecordSourcesTime) HdmiTimerRecordSources::Time::Time( /* [in] */ Int32 hour, /* [in] */ Int32 minute) : TimeUnit(hour, minute) { } CAR_INTERFACE_IMPL(HdmiTimerRecordSources::Duration, TimeUnit, IHdmiTimerRecordSourcesDuration) HdmiTimerRecordSources::Duration::Duration( /* [in] */ Int32 hour, /* [in] */ Int32 minute) : TimeUnit(hour, minute) { } const Int32 HdmiTimerRecordSources::TimerInfo::DAY_OF_MONTH_SIZE = 1; const Int32 HdmiTimerRecordSources::TimerInfo::MONTH_OF_YEAR_SIZE = 1; const Int32 HdmiTimerRecordSources::TimerInfo::START_TIME_SIZE = 2; const Int32 HdmiTimerRecordSources::TimerInfo::DURATION_SIZE = 2; const Int32 HdmiTimerRecordSources::TimerInfo::RECORDING_SEQUENCE_SIZE = 1; const Int32 HdmiTimerRecordSources::TimerInfo::BASIC_INFO_SIZE = DAY_OF_MONTH_SIZE + MONTH_OF_YEAR_SIZE + START_TIME_SIZE + DURATION_SIZE + RECORDING_SEQUENCE_SIZE; CAR_INTERFACE_IMPL(HdmiTimerRecordSources::TimerInfo, Object, IHdmiTimerRecordSourcesTimerInfo) HdmiTimerRecordSources::TimerInfo::TimerInfo( /* [in] */ Int32 dayOfMonth, /* [in] */ Int32 monthOfYear, /* [in] */ IHdmiTimerRecordSourcesTime* startTime, /* [in] */ IHdmiTimerRecordSourcesDuration* duration, /* [in] */ Int32 recordingSequence) : mDayOfMonth(dayOfMonth) , mMonthOfYear(monthOfYear) , mStartTime(startTime) , mDuration(duration) , mRecordingSequence(recordingSequence) { } ECode HdmiTimerRecordSources::TimerInfo::ToByteArray( /* [in] */ ArrayOf<Byte>* data, /* [in] */ Int32 index, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); // [Day of Month] (*data)[index] = (Byte)mDayOfMonth; index += DAY_OF_MONTH_SIZE; // [Month of Year] (*data)[index] = (Byte)mMonthOfYear; index += MONTH_OF_YEAR_SIZE; // [Start Time] Int32 res; IHdmiTimerRecordSourcesTimeUnit::Probe(mStartTime)->ToByteArray(data, index, &res); index += res; IHdmiTimerRecordSourcesTimeUnit::Probe(mDuration)->ToByteArray(data, index, &res); index += res; // [Duration] // [Recording Sequence] (*data)[index] = (Byte)mRecordingSequence; return GetDataSize(result); } ECode HdmiTimerRecordSources::TimerInfo::GetDataSize( /* [out] */ Int32* size) { VALIDATE_NOT_NULL(size); *size = BASIC_INFO_SIZE; return NOERROR; } CAR_INTERFACE_IMPL(HdmiTimerRecordSources::TimerRecordSource, Object, ITimerRecordSource) HdmiTimerRecordSources::TimerRecordSource::TimerRecordSource( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IRecordSource* recordSource) : mRecordSource(recordSource) , mTimerInfo(timerInfo) { } CARAPI HdmiTimerRecordSources::TimerRecordSource::GetDataSize( /* [out] */ Int32* size) { VALIDATE_NOT_NULL(size); Int32 res1; mTimerInfo->GetDataSize(&res1); Int32 res2; mRecordSource->GetDataSize(FALSE, &res2); *size = res1 + res2; return NOERROR; } CARAPI HdmiTimerRecordSources::TimerRecordSource::ToByteArray( /* [in] */ ArrayOf<Byte>* data, /* [in] */ Int32 index, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); // Basic infos including [Day of Month] [Month of Year] [Start Time] [Duration] // [Recording Sequence] Int32 res; mTimerInfo->ToByteArray(data, index, &res); index += res; // [Record Source] mRecordSource->ToByteArray(FALSE, data, index, &res); return GetDataSize(result); } HdmiTimerRecordSources::ExternalSourceDecorator::ExternalSourceDecorator( /* [in] */ IRecordSource* recordSource, /* [in] */ Int32 externalSourceSpecifier) : mRecordSource(recordSource) , mExternalSourceSpecifier(externalSourceSpecifier) { // External source has one byte field for [External Source Specifier]. Int32 size; recordSource->GetDataSize(FALSE, &size); HdmiRecordSources::RecordSource* _recordSource = (HdmiRecordSources::RecordSource*)recordSource; HdmiRecordSources::RecordSource::constructor(_recordSource->mSourceType, size + 1); } ECode HdmiTimerRecordSources::ExternalSourceDecorator::ExtraParamToByteArray( /* [in] */ ArrayOf<Byte>* data, /* [in] */ Int32 index, /* [out] */ Int32* array) { VALIDATE_NOT_NULL(array); (*data)[index] = (Byte)mExternalSourceSpecifier; Int32 tmp; mRecordSource->ToByteArray(FALSE, data, index + 1, &tmp); return GetDataSize(FALSE, array); } const String HdmiTimerRecordSources::TAG("HdmiTimerRecordSources"); const Int32 HdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_MASK = (IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_SUNDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_MONDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_TUESDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_WEDNESDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_THURSDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_FRIDAY | IHdmiTimerRecordSources::RECORDING_SEQUENCE_REPEAT_SATUREDAY); const Int32 HdmiTimerRecordSources::EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PLUG = 4; const Int32 HdmiTimerRecordSources::EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PHYSICAL_ADDRESS = 5; CAR_INTERFACE_IMPL(HdmiTimerRecordSources, Object, IHdmiTimerRecordSources) ECode HdmiTimerRecordSources::OfDigitalSource( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IHdmiRecordSourcesDigitalServiceSource* source, /* [out] */ ITimerRecordSource** result) { VALIDATE_NOT_NULL(result); *result = NULL; FAIL_RETURN(CheckTimerRecordSourceInputs(timerInfo, IRecordSource::Probe(source))) AutoPtr<ITimerRecordSource> tmp = new TimerRecordSource(timerInfo, IRecordSource::Probe(source)); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::OfAnalogueSource( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IHdmiRecordSourcesAnalogueServiceSource* source, /* [out] */ ITimerRecordSource** result) { VALIDATE_NOT_NULL(result); *result = NULL; FAIL_RETURN(CheckTimerRecordSourceInputs(timerInfo, IRecordSource::Probe(source))) AutoPtr<ITimerRecordSource> tmp = new TimerRecordSource(timerInfo, IRecordSource::Probe(source)); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::OfExternalPlug( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IHdmiRecordSourcesExternalPlugData* source, /* [out] */ ITimerRecordSource** result) { VALIDATE_NOT_NULL(result); *result = NULL; FAIL_RETURN(CheckTimerRecordSourceInputs(timerInfo, IRecordSource::Probe(source))) AutoPtr<IRecordSource> decorator = new ExternalSourceDecorator(IRecordSource::Probe(source), EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PLUG); AutoPtr<ITimerRecordSource> tmp = new TimerRecordSource(timerInfo, decorator); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::OfExternalPhysicalAddress( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IHdmiRecordSourcesExternalPhysicalAddress* source, /* [out] */ ITimerRecordSource** result) { VALIDATE_NOT_NULL(result); *result = NULL; FAIL_RETURN(CheckTimerRecordSourceInputs(timerInfo, IRecordSource::Probe(source))) AutoPtr<IRecordSource> decorator = new ExternalSourceDecorator(IRecordSource::Probe(source), EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PHYSICAL_ADDRESS); AutoPtr<ITimerRecordSource> tmp = new TimerRecordSource(timerInfo, decorator); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::CheckTimerRecordSourceInputs( /* [in] */ IHdmiTimerRecordSourcesTimerInfo* timerInfo, /* [in] */ IRecordSource* source) { if (timerInfo == NULL) { Logger::W(TAG, "TimerInfo should not be null."); //throw new IllegalArgumentException("TimerInfo should not be null."); Logger::E(TAG, "TimerInfo should not be null."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (source == NULL) { Logger::W(TAG, "source should not be null."); //throw new IllegalArgumentException("source should not be null."); Logger::E(TAG, "TimerInfo should not be null."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return NOERROR; } ECode HdmiTimerRecordSources::TimeOf( /* [in] */ Int32 hour, /* [in] */ Int32 minute, /* [out] */ IHdmiTimerRecordSourcesTime** _time) { VALIDATE_NOT_NULL(_time); *_time = NULL; FAIL_RETURN(CheckTimeValue(hour, minute)) AutoPtr<IHdmiTimerRecordSourcesTime> tmp = new Time(hour, minute); *_time = tmp; REFCOUNT_ADD(*_time); return NOERROR; } ECode HdmiTimerRecordSources::CheckTimeValue( /* [in] */ Int32 hour, /* [in] */ Int32 minute) { if (hour < 0 || hour > 23) { //throw new IllegalArgumentException("Hour should be in rage of [0, 23]:" + hour); Logger::E(TAG, "Hour should be in rage of [0, 23]:%d", hour); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (minute < 0 || minute > 59) { //throw new IllegalArgumentException("Minute should be in rage of [0, 59]:" + minute); Logger::E(TAG, "Minute should be in rage of [0, 59]:%d", minute); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return NOERROR; } ECode HdmiTimerRecordSources::DurationOf( /* [in] */ Int32 hour, /* [in] */ Int32 minute, /* [out] */ IHdmiTimerRecordSourcesDuration** result) { VALIDATE_NOT_NULL(result); *result = NULL; FAIL_RETURN(CheckDurationValue(hour, minute)) AutoPtr<IHdmiTimerRecordSourcesDuration> tmp = new Duration(hour, minute); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::CheckDurationValue( /* [in] */ Int32 hour, /* [in] */ Int32 minute) { if (hour < 0 || hour > 99) { //throw new IllegalArgumentException("Hour should be in rage of [0, 99]:" + hour); Logger::E(TAG, "Hour should be in rage of [0, 23]:%d", hour); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (minute < 0 || minute > 59) { //throw new IllegalArgumentException("minute should be in rage of [0, 59]:" + minute); Logger::E(TAG, "minute should be in rage of [0, 59]:%d", minute); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return NOERROR; } ECode HdmiTimerRecordSources::TimerInfoOf( /* [in] */ Int32 dayOfMonth, /* [in] */ Int32 monthOfYear, /* [in] */ IHdmiTimerRecordSourcesTime* startTime, /* [in] */ IHdmiTimerRecordSourcesDuration* duration, /* [in] */ Int32 recordingSequence, /* [out] */ IHdmiTimerRecordSourcesTimerInfo** result) { VALIDATE_NOT_NULL(result); *result = NULL; if (dayOfMonth < 0 || dayOfMonth > 31) { // throw new IllegalArgumentException( // "Day of month should be in range of [0, 31]:" + dayOfMonth); Logger::E(TAG, "Day of month should be in range of [0, 31]:%d", dayOfMonth); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (monthOfYear < 1 || monthOfYear > 12) { // throw new IllegalArgumentException( // "Month of year should be in range of [1, 12]:" + monthOfYear); Logger::E(TAG, "Month of year should be in range of [1, 12]:%d", monthOfYear); return E_ILLEGAL_ARGUMENT_EXCEPTION; } HdmiTimerRecordSources::Time* _startTime = (HdmiTimerRecordSources::Time*)startTime; FAIL_RETURN(CheckTimeValue(_startTime->mHour, _startTime->mMinute)) HdmiTimerRecordSources::Duration* _duration = (HdmiTimerRecordSources::Duration*)duration; FAIL_RETURN(CheckDurationValue(_duration->mHour, _duration->mMinute)) // Recording sequence should use least 7 bits or no bits. if ((recordingSequence != 0) && ((recordingSequence & ~RECORDING_SEQUENCE_REPEAT_MASK) != 0)) { // throw new IllegalArgumentException( // "Invalid reecording sequence value:" + recordingSequence); Logger::E(TAG, "Invalid reecording sequence value:%d", recordingSequence); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<IHdmiTimerRecordSourcesTimerInfo> tmp = new TimerInfo(dayOfMonth, monthOfYear, startTime, duration, recordingSequence); *result = tmp; REFCOUNT_ADD(*result); return NOERROR; } ECode HdmiTimerRecordSources::CheckTimerRecordSource( /* [in] */ Int32 sourcetype, /* [in] */ ArrayOf<Byte>* recordSource, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; Int32 recordSourceSize = recordSource->GetLength() - TimerInfo::BASIC_INFO_SIZE; switch (sourcetype) { case IHdmiControlManager::TIMER_RECORDING_TYPE_DIGITAL: *result = IHdmiRecordSourcesDigitalServiceSource::EXTRA_DATA_SIZE == recordSourceSize; return NOERROR; case IHdmiControlManager::TIMER_RECORDING_TYPE_ANALOGUE: *result = IHdmiRecordSourcesAnalogueServiceSource::EXTRA_DATA_SIZE == recordSourceSize; return NOERROR; case IHdmiControlManager::TIMER_RECORDING_TYPE_EXTERNAL: { Int32 specifier = (*recordSource)[TimerInfo::BASIC_INFO_SIZE]; if (specifier == EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PLUG) { // One byte for specifier. *result = IHdmiRecordSourcesExternalPlugData::EXTRA_DATA_SIZE + 1 == recordSourceSize; return NOERROR; } else if (specifier == EXTERNAL_SOURCE_SPECIFIER_EXTERNAL_PHYSICAL_ADDRESS) { // One byte for specifier. *result = IHdmiRecordSourcesExternalPhysicalAddress::EXTRA_DATA_SIZE + 1 == recordSourceSize; return NOERROR; } else { // Invalid specifier. *result = FALSE; return NOERROR; } } default: *result = FALSE; return NOERROR; } return NOERROR; } } // namespace Hdmi } // namespace Hardware } // namepsace Droid } // namespace Elastos
35.30837
109
0.683593
[ "object" ]
343705d99fc925c00d8f062b6a7808e143bc3dcd
3,571
cpp
C++
snippets/utilities/regex.cpp
raakasf/moderncpp
2f8495c90e717e73303191e6f6aef37212448a46
[ "MIT" ]
334
2020-08-29T16:41:02.000Z
2022-03-28T06:26:28.000Z
snippets/utilities/regex.cpp
raakasf/moderncpp
2f8495c90e717e73303191e6f6aef37212448a46
[ "MIT" ]
4
2021-02-06T21:18:20.000Z
2022-03-16T17:10:44.000Z
snippets/utilities/regex.cpp
raakasf/moderncpp
2f8495c90e717e73303191e6f6aef37212448a46
[ "MIT" ]
33
2020-08-31T11:36:44.000Z
2022-03-31T07:07:20.000Z
#include <iostream> #include <regex> #include <sstream> #include <string> int main() { using namespace std; // Test single expression if (regex_match("subject", regex("(sub)(.*)"))) { cout << "subject matches expression (sub)(.*)" << endl; } // Test string const char cstr[] = "subject"; string s("subject"); regex e("(sub)(.*)"); if (regex_match(s, e)) { cout << "subject matches expression (sub)(.*)" << endl; } // Test range if (regex_match(s.begin(), s.end(), e)) { cout << "subject matches expression (sub)(.*)" << endl; } // Get match results for char* // cmatch is the same as match_results<const char*> cm; cmatch cm; regex_match(cstr, cm, e); cout << "literal string with " << cm.size() << " matches" << endl; cout << "The literal string matches were: "; for (const auto &i : cm) { cout << "[" << i << "] "; } cout << endl; // Get match results for string // same as match_results<string::const_iterator> sm; smatch sm; regex_match(s, sm, e); cout << "string object with " << sm.size() << " matches" << endl; cout << "The string matches were: "; for (const auto &i : sm) { cout << "[" << i << "] "; } cout << endl; // Get match results for string range regex_match(s.cbegin(), s.cend(), sm, e); cout << sm.size() << " matches" << endl; // Using flags to determine behavior regex_match(cstr, cm, e, regex_constants::match_default); // Iterate substrings with matches std::string ss = "foo bar 123"; std::regex r("([a-zA-Z]+)|(d+)"); std::sregex_iterator first_str_match = std::sregex_iterator(ss.begin(), ss.end(), r); for (auto i = first_str_match; i != std::sregex_iterator(); ++i) { std::smatch m = *i; std::cout << "Match value: " << m.str() << " at Position " << m.position() << '\n'; for (size_t index = 1; index < m.size(); ++index) { if (!m[index].str().empty()) { std::cout << "Capture group ID: " << index - 1 << std::endl; break; } } } // Concatenate regexes: conjunction string var = "first second third forth"; if (regex_match(var, sm, regex("(.*) (.*) (.*) (.*)"))) { for (size_t i = 1; i < sm.size(); i++) { cout << "Match " << i << ": " << sm[i] << " at position " << sm.position(i) << endl; } } // Concatenate regexes: disjunction // This strategy does not work when there are internal capture groups var = "user/32"; smatch sm2; auto implode = [](const std::vector<std::string> &strs, const std::string &delim) { std::stringstream s; copy(strs.begin(), strs.end(), ostream_iterator<string>(s, delim.c_str())); return s.str(); }; std::vector<std::string> routes = {"welcome", "user/\\d+", "post/[a-zA-Z]+", "about"}; regex disjunction("(" + implode(routes, ")|(") + ")"); if (regex_match(var, sm2, disjunction, regex_constants::match_not_null)) { for (size_t index = 1; index < sm2.size(); ++index) { if (sm2[index].length() > 0) { std::cout << "Capture group index: " << index - 1 << std::endl; std::cout << var << " matched route " << routes[index - 1] << std::endl; break; } } } return 0; }
32.463636
80
0.505741
[ "object", "vector" ]
3437bea02a47a1a02c7438cb1c135b7bfe5206cc
5,597
cpp
C++
copyhandler.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
3
2015-05-06T16:56:14.000Z
2017-03-22T05:25:21.000Z
copyhandler.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
null
null
null
copyhandler.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Jonathan R. Guthrie * * 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 "copyhandler.hpp" ImapHandler *copyHandler(ImapSession *session, INPUT_DATA_STRUCT &input) { (void) input; return new CopyHandler(session, session->parseBuffer(), false); } ImapHandler *uidCopyHandler(ImapSession *session, INPUT_DATA_STRUCT &input) { (void) input; return new CopyHandler(session, session->parseBuffer(), true); } IMAP_RESULTS CopyHandler::execute() { IMAP_RESULTS result = IMAP_OK; size_t execute_pointer = 0; // Skip the first two tokens that are the tag and the command execute_pointer += strlen(m_parseBuffer->tag()) + 1; execute_pointer += strlen(m_parseBuffer->parsingAt()) + 1; // I do this once again if m_usingUid is set because the command in that case is UID if (m_usingUid) { execute_pointer += strlen(m_parseBuffer->parsingAt()) + 1; } SEARCH_RESULT vector; bool sequenceOk; if (m_usingUid) { sequenceOk = m_session->uidSequenceSet(vector, execute_pointer); } else { sequenceOk = m_session->msnSequenceSet(vector, execute_pointer); } if (sequenceOk) { NUMBER_LIST messageUidsAdded; MailStore::MAIL_STORE_RESULT lock1Result = MailStore::SUCCESS; MailStore::MAIL_STORE_RESULT lock2Result = MailStore::SUCCESS; execute_pointer += strlen(m_parseBuffer->parsingAt()) + 1; std::string mailboxName(m_parseBuffer->parsingAt()); if ((MailStore::SUCCESS == (lock1Result = m_session->store()->lock())) && (MailStore::SUCCESS == (lock2Result = m_session->store()->lock(mailboxName)))) { for (SEARCH_RESULT::iterator i=vector.begin(); (i!=vector.end()) && (IMAP_OK==result); ++i) { MailMessage *message; MailMessage::MAIL_MESSAGE_RESULT messageReadResult = m_session->store()->messageData(&message, *i); if (MailMessage::SUCCESS == messageReadResult) { size_t newUid; DateTime when = m_session->store()->messageInternalDate(*i); uint32_t flags = message->messageFlags(); char buffer[m_session->store()->bufferLength(*i)+1]; switch (m_session->mboxErrorCode(m_session->store()->openMessageFile(*i))) { case MailStore::SUCCESS: { size_t size = m_session->store()->readMessage(buffer, 0, m_session->store()->bufferLength(*i)); switch (m_session->mboxErrorCode(m_session->store()->addMessageToMailbox(mailboxName, (uint8_t *)buffer, size, when, flags, &newUid))) { case MailStore::SUCCESS: m_session->store()->doneAppendingDataToMessage(mailboxName, newUid); messageUidsAdded.push_back(newUid); result = IMAP_OK; break; case MailStore::CANNOT_COMPLETE_ACTION: result = IMAP_TRY_AGAIN; break; default: result = IMAP_MBOX_ERROR; break; } } break; case MailStore::CANNOT_COMPLETE_ACTION: result = IMAP_TRY_AGAIN; break; default: result = IMAP_MBOX_ERROR; break; } } } if (IMAP_OK != result) { for (NUMBER_LIST::iterator i=messageUidsAdded.begin(); i!=messageUidsAdded.end(); ++i) { m_session->store()->deleteMessage(mailboxName, *i); } } } else { if (((MailStore::CANNOT_COMPLETE_ACTION == lock1Result) || (MailStore::SUCCESS == lock1Result)) && ((MailStore::CANNOT_COMPLETE_ACTION == lock2Result) || (MailStore::SUCCESS == lock2Result))) { result = IMAP_TRY_AGAIN; } else { result = IMAP_MBOX_ERROR; } } m_session->store()->unlock(); m_session->store()->unlock(mailboxName); } else { m_session->responseText("Malformed Command"); result = IMAP_BAD; } return result; } IMAP_RESULTS CopyHandler::receiveData(INPUT_DATA_STRUCT &input) { IMAP_RESULTS result = IMAP_OK; if (0 == m_parseStage) { while((input.parsingAt < input.dataLen) && (' ' != input.data[input.parsingAt])) { m_parseBuffer->addToParseBuffer(input, 1, false); } m_parseBuffer->addToParseBuffer(input, 0); if ((input.parsingAt < input.dataLen) && (' ' == input.data[input.parsingAt])) { ++input.parsingAt; } else { m_session->responseText("Malformed Command"); result = IMAP_BAD; } if (IMAP_OK == result) { switch (m_parseBuffer->astring(input, false, NULL)) { case ImapStringGood: m_parseStage = 2; break; case ImapStringBad: m_session->responseText("Malformed Command"); result = IMAP_BAD; break; case ImapStringPending: result = IMAP_NOTDONE; m_session->responseText("Ready for Literal"); break; default: m_session->responseText("Failed"); break; } } } else { result = IMAP_OK; if (1 == m_parseStage) { size_t dataUsed = m_parseBuffer->addLiteralToParseBuffer(input); if (dataUsed <= input.dataLen) { if (2 < (input.dataLen - dataUsed)) { // Get rid of the CRLF if I have it input.dataLen -= 2; input.data[input.dataLen] = '\0'; // Make sure it's terminated so strchr et al work } } else { result = IMAP_IN_LITERAL; } } } if (IMAP_OK == result) { result = execute(); } return result; }
29.613757
139
0.67286
[ "vector" ]
343e61c5d0a8a1674d2ed4346f73c5c9f062cc9f
10,823
cpp
C++
DSP/extensions/FilterLib/tests/TTHilbertLinear33.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
31
2015-02-28T23:51:10.000Z
2021-12-25T04:16:01.000Z
DSP/extensions/FilterLib/tests/TTHilbertLinear33.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
126
2015-01-01T13:42:05.000Z
2021-07-13T14:11:42.000Z
DSP/extensions/FilterLib/tests/TTHilbertLinear33.test.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
14
2015-02-10T15:08:32.000Z
2019-09-17T01:21:25.000Z
/** @file * * @ingroup dspFilterLib * * @brief Unit test for the FilterLib #TTHilbertLinear33 class. * * @details Currently this test is just a stub * * @authors Trond Lossius, Tim Place * * @copyright Copyright © 2012 by Trond Lossius & Timothy Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTHilbertLinear33.h" TTErr TTHilbertLinear33::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; int badSampleCount = 0; TTAudioSignalPtr input = NULL; TTAudioSignalPtr outputReal = NULL; TTAudioSignalPtr outputImaginary = NULL; // create audio signal objects - hilbert returns real and imaginary signal so we need two channels for output TTObjectBaseInstantiate(kTTSym_audiosignal, &input, 1); TTObjectBaseInstantiate(kTTSym_audiosignal, &outputReal, 1); TTObjectBaseInstantiate(kTTSym_audiosignal, &outputImaginary, 1); input->allocWithVectorSize(128); outputReal->allocWithVectorSize(128); outputImaginary->allocWithVectorSize(128); // create an impulse input->clear(); // set all samples to zero input->mSampleVectors[0][0] = 1.0; // set the first sample to 1 // setup the filter //this->setAttributeValue(TT("linearGain"), 0.5); //this->setAttributeValue(TT("delayInSamples"), 1); TTObject inputArray(kTTSym_audiosignalarray, 1); TTObject outputArray(kTTSym_audiosignalarray, 2); // TODO: switch these to use the new TTBASE macro: ((TTAudioSignalArrayPtr)inputArray.instance())->setSignal(0, input); ((TTAudioSignalArrayPtr)outputArray.instance())->setSignal(0, outputReal); ((TTAudioSignalArrayPtr)outputArray.instance())->setSignal(1, outputImaginary); this->process(TTAudioSignalArrayPtr(inputArray.instance()), TTAudioSignalArrayPtr(outputArray.instance())); /// The following values are not necsessarily to be trusted. They were calculated from this filter unit itself at a time when the filter was assumed to work. As such, if this test fails in the future, it should be considered an indication that something has changed in the code or compiler that causes the calculated impulse response to differ from earlier results, but this test is not able to say anything meaningful about whether the old or new behaviour is to be trusted (or eventually none of them). TTFloat64 expectedImpulseResponseCh1[128] = { 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 1.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, 0.0000000000000000e+00, }; TTFloat64 expectedImpulseResponseCh2[128] = { 0.0000000000000000e+00, -2.8092457249341120e-03, 0.0000000000000000e+00, -5.7437236386599748e-03, 0.0000000000000000e+00, -1.1602174238849574e-02, 0.0000000000000000e+00, -2.1812001394733507e-02, 0.0000000000000000e+00, -3.9950693784204676e-02, 0.0000000000000000e+00, -7.4975660919201770e-02, 0.0000000000000000e+00, -1.5941021199354771e-01, 0.0000000000000000e+00, -5.8434596240466408e-01, 0.0000000000000000e+00, 6.8737371572856165e-01, 0.0000000000000000e+00, 2.6047219272586097e-01, 0.0000000000000000e+00, 1.7220504166668985e-01, 0.0000000000000000e+00, 1.3165880751558845e-01, 0.0000000000000000e+00, 1.0672637484521202e-01, 0.0000000000000000e+00, 8.8763042682027796e-02, 0.0000000000000000e+00, 7.4590817559364642e-02, 0.0000000000000000e+00, 6.2491816141289638e-02, 0.0000000000000000e+00, 5.3601005804006424e-02, 0.0000000000000000e+00, 4.4268254704726902e-02, 0.0000000000000000e+00, 3.6698916574512824e-02, 0.0000000000000000e+00, 3.0491527642942159e-02, 0.0000000000000000e+00, 2.5364772306844932e-02, 0.0000000000000000e+00, 2.1112011554879444e-02, 0.0000000000000000e+00, 1.7575632461599877e-02, 0.0000000000000000e+00, 1.4631136058800433e-02, 0.0000000000000000e+00, 1.2180032897411687e-02, 0.0000000000000000e+00, 1.0137024036000260e-02, 0.0000000000000000e+00, 8.4366607684061290e-03, 0.0000000000000000e+00, 7.0216702898170313e-03, 0.0000000000000000e+00, 5.8441053213995897e-03, 0.0000000000000000e+00, 4.8640673178878824e-03, 0.0000000000000000e+00, 4.0483891530415182e-03, 0.0000000000000000e+00, 3.3694930991639144e-03, 0.0000000000000000e+00, 2.8044411084449080e-03, 0.0000000000000000e+00, 2.3341416117147440e-03, 0.0000000000000000e+00, 1.9427099863831426e-03, 0.0000000000000000e+00, 1.6169211725708889e-03, 0.0000000000000000e+00, 1.3457668541494491e-03, 0.0000000000000000e+00, 1.1200846929263178e-03, 0.0000000000000000e+00, 9.3224896671763400e-04, 0.0000000000000000e+00, 7.7591286433524435e-04, 0.0000000000000000e+00, 6.4579396750947084e-04, 0.0000000000000000e+00, 5.3749571564408851e-04, 0.0000000000000000e+00, 4.4735884490682882e-04, 0.0000000000000000e+00, 3.7233773378069054e-04, 0.0000000000000000e+00, 3.0989750176924926e-04, 0.0000000000000000e+00, 2.5792836193805926e-04, 0.0000000000000000e+00, 2.1467433437323476e-04, 0.0000000000000000e+00, 1.7867391348799137e-04, 0.0000000000000000e+00, 1.4871068515793736e-04, 0.0000000000000000e+00, 1.2377222529964514e-04, 0.0000000000000000e+00, 1.0301589114967565e-04, 0.0000000000000000e+00, 8.5740349291217426e-05, 0.0000000000000000e+00, 7.1361878394029805e-05, 0.0000000000000000e+00, 5.9394645929584248e-05, 0.0000000000000000e+00, 4.9434292433224237e-05, 0.0000000000000000e+00, 4.1144268647743772e-05, 0.0000000000000000e+00, 3.4244463897949263e-05, 0.0000000000000000e+00, 2.8501741462339606e-05, 0.0000000000000000e+00, 2.3722061142687539e-05, 0.0000000000000000e+00, 1.9743922861739448e-05, 0.0000000000000000e+00, 1.6432909755427518e-05, 0.0000000000000000e+00, 1.3677146376690416e-05, 0.0000000000000000e+00, 1.1383518548663555e-05, 0.0000000000000000e+00, 9.4745271402964313e-06, }; // TEST 1: IMPULSE RESPONSE - REAL VECTOR //TTTestLog("\nRESULTING VALUES - CHANNEL 1"); for (int i=0; i<128; i++) { TTBoolean result = !TTTestFloatEquivalence(outputReal->mSampleVectors[0][i], expectedImpulseResponseCh1[i]); //TTTestLog("%.16e,", outputReal->mSampleVectors[0][i]); badSampleCount += result; if (result) TTTestLog("BAD SAMPLE @ i=%i ( value=%.10f expected=%.10f )", i, outputReal->mSampleVectors[0][i], expectedImpulseResponseCh1[i]); } TTTestAssertion("Produces correct impulse response for real signal", badSampleCount == 0, testAssertionCount, errorCount); if (badSampleCount) TTTestLog("badSampleCount is %i", badSampleCount); // TEST 2: IMPULSE RESPONSE - IMAGINARY VECTOR //TTTestLog("\nRESULTING VALUES - CHANNEL 2"); badSampleCount = 0; for (int i=0; i<128; i++) { TTBoolean result = !TTTestFloatEquivalence(outputImaginary->mSampleVectors[0][i], expectedImpulseResponseCh2[i]); //TTTestLog("%.16e,", outputImaginary->mSampleVectors[0][i]); badSampleCount += result; if (result) TTTestLog("BAD SAMPLE @ i=%i ( value=%.10f expected=%.10f )", i, outputImaginary->mSampleVectors[0][i], expectedImpulseResponseCh2[i]); } TTTestAssertion("Produces correct impulse response for imaginary signal", badSampleCount == 0, testAssertionCount, errorCount); if (badSampleCount) TTTestLog("badSampleCount is %i", badSampleCount); TTObjectBaseRelease(&input); TTObjectBaseRelease(&outputReal); TTObjectBaseRelease(&outputImaginary); // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
29.251351
505
0.757369
[ "vector" ]
3441636bd56d41db50bcf2184402fe1639129496
4,811
hpp
C++
ThirdParty/logog/include/unittest.hpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2021-06-25T13:43:06.000Z
2021-06-25T13:43:06.000Z
ThirdParty/logog/include/unittest.hpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
25
2015-02-04T20:34:21.000Z
2018-12-10T20:19:57.000Z
ThirdParty/logog/include/unittest.hpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
2
2018-03-01T13:07:12.000Z
2018-03-01T13:16:22.000Z
/** * \file unittest.hpp Unit testing interface; may be used for other programs as well. */ #ifndef __LOGOG_UNITTEST_HPP #define __LOGOG_UNITTEST_HPP #include <iostream> #include <string> namespace logog { /** * \page unittesting Unit test framework * * A unit test framework is included with logog. This framework was intended specifically to exercise logog functionality, but it may also * be used as a general purpose test framework. * * A typical test program will look like this: * \code * int main( int argc, char *argv[] ) * { * int nResult; * nResult = RunAllTests(); * ShutdownTests(); * return nResult; * } * \endcode * * To define a unit test, create a function of the following form: * * \code * UNITTEST( AdditionTest ) * { * logog::Initialize(); * * int nResult = 0; * * if ( 2 + 2 == 4 ) * { * LOGOG_COUT << _LG("Sane.") << endl; * } * else * { * LOGOG_COUT << _LG("Insane!") << endl; * nResult = 1; * } * * logog::Shutdown(); * * return nResult; * * }; * \endcode * * The UNITTEST() macro defines a unique UnitTest object that encompasses your function. * Your function should take no parameters and return an integer value. It should return * zero if the test was successful, and non-zero if the test was unsuccesful. If any * of your tests fail, the stub main() program will propagate that error to the operating * system, which in turn can be used to halt an automated build system. * * The unit testing framework is known to leak memory. However, the underlying logog macros are not known to leak memory (let us know * if you find any leaks). */ /** A standard string type, used for labelling a test. We don't use LOGOG_STRING here because that class is mutable ** and it allocates memory. **/ typedef const char * TestNameType; class UnitTest; /** A registry for all tests. All tests are instanced using the UNITTEST() macro and stored in the LogogTestRegistry. ** \ref UNITTEST **/ typedef LOGOG_LIST< UnitTest * > TestRegistryType; /** All unit tests are registered in here at program initialization time. */ extern TestRegistryType &LogogTestRegistry(); /** A TestSignup is responsible for recording each instanced UnitTest in the test registry. */ class TestSignup { public: /** Creates a new TestSignup. Only called from constructor for UnitTest. */ TestSignup( UnitTest *pTest ); protected: /** A pointer back to the UnitTest that created this TestSignup */ UnitTest *m_pTest; private: TestSignup(); }; /** The base class for unit testing. Children of UnitTest are instanced by the UNITTEST() macro. */ class UnitTest { public: /** Instances a test. An instanced test is automatically executed when the RunAllTests() function is called. * \param sTestName A string representing the name of this test. */ UnitTest( const TestNameType &sTestName ); virtual ~UnitTest(); /** Returns the name of this UnitTest provided at construction time. */ virtual TestNameType &GetName(); /** Child classes of UnitTest() must provide a RunTest() function. A RunTest() function must initialize logog, conduct its ** tests, and return 0 if the test was successful, a non-0 value otherwise. If any RunTest() function returns any value other than ** zero, then the main RunAllTests() function will return non zero as well. */ virtual int RunTest() = 0; /** This function is called during ShutdownTests(). Its purpose is to free ** the internal structures allocated by the UnitTest without freeing ** the UnitTest itself. Microsoft's leak detector will flag the internals ** of a UnitTest as a leak unless these internals are explicitly destroyed ** prior to exit(). **/ virtual void FreeInternals(); protected: /** The name of this particular test. */ TestNameType m_sTestName; /** A pointer to the TestSignup constructed by this UnitTest. */ TestSignup *m_pTestSignup; private: UnitTest(); }; /** Executes all currently registered tests and prints a report of success or failure. */ extern int RunAllTests(); /** Should remove all memory allocated during unit testing. */ extern void ShutdownTests(); /** This should be the function prefix for a unit test. It defines a new class for the test inherited from UnitTest. It instances ** a member of the class at run-time (before main() starts). Lastly it provides the function definition for the actual test class. */ #define UNITTEST( x ) class x : public UnitTest { \ public: \ x( TestNameType name ) : \ UnitTest( name ) \ {} \ virtual ~x() {}; \ virtual int RunTest(); \ }; \ x __LogogTestInstance_ ## x ( #x ); \ int x::RunTest() } #endif // __LOGOG_UNITTEST_HPP
31.651316
139
0.690085
[ "object" ]
451ab4bf35ac291615ccb19daa280446d21d17c2
13,375
cpp
C++
Sky.cpp
koladonia/Natural-Phenomena
9598c17ae6ff93d53bd1b0e557c706d169630916
[ "MIT" ]
null
null
null
Sky.cpp
koladonia/Natural-Phenomena
9598c17ae6ff93d53bd1b0e557c706d169630916
[ "MIT" ]
null
null
null
Sky.cpp
koladonia/Natural-Phenomena
9598c17ae6ff93d53bd1b0e557c706d169630916
[ "MIT" ]
null
null
null
#include "QuadRenderer.h" #ifdef _WIN32 #define NOMINMAX #include <windows.h> #endif #include <cstring> #include <GL/gl.h> #include <GL/glu.h> #include <QImage> #include <QGLWidget> #include <QtWidgets> #include <QDebug> #include <iostream> #include <algorithm> #include <cmath> QuadRenderer::QuadRenderer(int width, int height) { //Define sky texture this->width = width; this->height = height; skyData = new GLubyte[width * height * 3]; memset(skyData, 255, width * height * 3); //Each row must be aligned to 1-4 bytes, 1 means no alignment! glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &skyQuadTextureId); glBindTexture(GL_TEXTURE_2D, skyQuadTextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)skyData); glBindTexture(GL_TEXTURE_2D, 0); //Define sky mesh vertices.push_back(QVector3D(-1, -1, 0.9999999)); vertices.push_back(QVector3D(1, -1, 0.9999999)); vertices.push_back(QVector3D(1, 1, 0.9999999)); vertices.push_back(QVector3D(-1, 1, 0.9999999)); texVertices.push_back(QVector2D(0.0f, 0.0f)); texVertices.push_back(QVector2D(1.0f, 0.0f)); texVertices.push_back(QVector2D(1.0f, 1.0f)); texVertices.push_back(QVector2D(0.0f, 1.0f)); indices.push_back(0); indices.push_back(1); indices.push_back(2); indices.push_back(0); indices.push_back(2); indices.push_back(3); //Define sky properties sunDir = new QVector3D(0.0f, -0.05f, -1.0f); sunDir->normalize(); earthRadius = 6360e3f; atmosphereRadius = 6420e3f; //Scale heights rH = 7994.0f; mH = 1200.0f; //Scattering coefficients rBeta = new QVector3D(5.8e-6f, 13.5e-6f, 33.1e-6f); mBeta = new QVector3D(21e-6f, 21e-6f, 21e-6f); //Transmittance sample amount viewTSamples = 16; lightTSamples = 2; //Mean cosine, describes that light is mainly scattered along the light forward direction g = 0.76f; //Intensity of the sunlight sunIntensity = 20.0f; } QuadRenderer::~QuadRenderer() { clearTexture(); glDeleteTextures(1, &skyQuadTextureId); } void QuadRenderer::render() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBindTexture(GL_TEXTURE_2D, skyQuadTextureId); glTexCoordPointer(2, GL_FLOAT, 0, &(texVertices[0])); glVertexPointer(3, GL_FLOAT, 0, &(vertices[0])); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, &(indices[0])); glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindTexture(GL_TEXTURE_2D, 0); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void QuadRenderer::clearTexture() { delete[] skyData; skyData = 0; } void QuadRenderer::updateTexture(int width, int height, float angleX, float angleY, float fovX) { bool sizeChanged = false; //std::cout << "Here it comes\n"; glBindTexture(GL_TEXTURE_2D, skyQuadTextureId); //If new dimensions, allocate new texture, otherwise update if (this->width != width || this->height != height) { //Deallocate bitmap data clearTexture(); //Allocate new array of colours with correct new width and height skyData = new GLubyte[width * height * 3]; //Set it to white memset(skyData, 255, width * height * 3); //Save new height and width this->height = height; this->width = width; //Update sizeChanged bool sizeChanged = true; } //Rotate sun direction by 2 degrees around x axis *sunDir = QQuaternion::fromAxisAndAngle(1.0f, 0.0f, 0.0f, 2).rotatedVector(*sunDir); //View Rotation quaternion //Camera rotation angle is inverted since quaternion rotation of view vector is ccw, but angle increase turns camera look vector right and up(cw around X and Y axis) QQuaternion viewRot = QQuaternion::fromAxisAndAngle(0.0f, 1.0f, 0.0f, -angleY) * QQuaternion::fromAxisAndAngle(1.0f, 0.0f, 0.0f, -angleX); //Actual update for each pixel for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { //Calculate ray direction // x E (tan(-fovX/2); tan(fovX/2)) //i / width // turns into [0;1] range //2 * i / width // turns into [0;2] range //2 * i / width - 1 // turns into [-1;1] range //tanf(fovX / 180.0f * M_PI / 2.0f) = 1 if fovX = 90 float x = (2.0f * i / static_cast<float>(width) - 1.0f); // * tanf(fovX / 180.0f * M_PI / 2.0f) // y E (-tan(fovY/2); tan(fovY/2)) float y = (2.0f * j / static_cast<float>(height) - 1.0f) / //Divide by aspect ratio to convert x fov resulting values to y fov (static_cast<float>(width) / static_cast<float>(height)); // * tanf(fovX / 180.0f * M_PI / 2.0f) //By default camera looks in the direction of +z, hence x is inverted (as it increases to the left relative from camera look direction) QVector3D rayDir(-x, y, 1.0); //Rotate by quaternion rayDir = viewRot.rotatedVector(rayDir); rayDir.normalize(); //Compute light one meter from earth QVector3D lightColour = computeIncidentLight(QVector3D(0.0f, earthRadius + 1.0f, 0.0f), rayDir); //qDebug() << lightColour; //Tone mapping by scratchpixel.com float r = lightColour.x() < 1.413f ? pow(lightColour.x() * 0.38317f, 1.0f / 2.2f) : 1.0f - exp(-lightColour.x()); float g = lightColour.y() < 1.413f ? pow(lightColour.y() * 0.38317f, 1.0f / 2.2f) : 1.0f - exp(-lightColour.y()); float b = lightColour.z() < 1.413f ? pow(lightColour.z() * 0.38317f, 1.0f / 2.2f) : 1.0f - exp(-lightColour.z()); //skyData[i * 3 + j * width * 3] = static_cast<int>(std::clamp(r, 0.0f, 1.0f) * 255); //skyData[i * 3 + j * width * 3 + 1] = static_cast<int>(std::clamp(g, 0.0f, 1.0f) * 255); //skyData[i * 3 + j * width * 3 + 2] = static_cast<int>(std::clamp(b, 0.0f, 1.0f) * 255); skyData[i * 3 + j * width * 3] = static_cast<int>(std::max(0.0f, std::min(1.0f, r)) * 255); skyData[i * 3 + j * width * 3 + 1] = static_cast<int>(std::max(0.0f, std::min(1.0f, g)) * 255); skyData[i * 3 + j * width * 3 + 2] = static_cast<int>(std::max(0.0f, std::min(1.0f, b)) * 255); //std::cout << lightColour.x() << ", " //<< lightColour.y() << ", " //<< lightColour.z() << std::endl; /* // Set colour skyData[i * 3 + j * width * 3] = static_cast<int>(std::clamp(lightColour.x(), 0.0f, 1.0f) * 255); skyData[i * 3 + j * width * 3 + 1] = static_cast<int>(std::clamp(lightColour.y(), 0.0f, 1.0f) * 255); skyData[i * 3 + j * width * 3 + 2] = static_cast<int>(std::clamp(lightColour.z(), 0.0f, 1.0f) * 255); */ } } //Texture test /*float normalizedAngleX = (angleX + 90) / 180.0f; for (int i = 0; i < width*height * 3 ; i += 3) { skyData[i] = normalizedAngleX * 81 + (1.0f - normalizedAngleX) * 109; skyData[i + 1] = normalizedAngleX * 198 + (1.0f - normalizedAngleX) * 31; skyData[i + 2] = normalizedAngleX * 31 + (1.0f - normalizedAngleX) * 198; }*/ // if (sizeChanged) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)skyData); else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)skyData); glBindTexture(GL_TEXTURE_2D, 0); } bool QuadRenderer::solveQuadratic(float a, float b, float c, float& x1, float& x2) { //Handle special case where the two vector ray.dir and V are perpendicular, // with V = ray.orig - sphere.centre if (b == 0) { //No roots if (a == 0) return false; x1 = 0; x2 = sqrtf(-c / a); return true; } float discr = b * b - 4 * a * c; //No roots. if (discr < 0) return false; //More stable version proposed by scratchapixel.com // root of discriminant will never cancel out b or produce big round off error due to close values float q = (b < 0.f) ? -0.5f * (b - sqrtf(discr)) : -0.5f * (b + sqrtf(discr)); //Standard quadratic solution x1 = q / a; //Muller's method x2 = c / q; return true; } bool QuadRenderer::raySphereIntersect(QVector3D orig, QVector3D dir, float radius, float &t0, float &t1) { //They ray dir is normalized so A = 1 float A = QVector3D::dotProduct(dir, dir); float B = 2 * QVector3D::dotProduct(dir, orig); float C = QVector3D::dotProduct(orig, orig) - radius * radius; if (!solveQuadratic(A, B, C, t0, t1)) return false; if (t0 > t1) std::swap(t0, t1); return true; } QVector3D QuadRenderer::computeIncidentLight(QVector3D orig, QVector3D dir) { //First and second intersection distances float dist0 = -1.0f, dist1 = -1.0f; //If ray doesn't intersect with the atmosphere or the only intersection is behind the camera return black light if (!raySphereIntersect(orig, dir, atmosphereRadius, dist0, dist1) || dist1 < 0) return QVector3D(0.0f, 0.0f, 0.0f); //First intersection can't be behind, should be at least at eye position dist0 = std::max(dist0, 0.0f); //Length of the segment on the view ray to integrate view ray Transmittance float segmentLength = (dist1 - dist0) / viewTSamples; //Start from either first intersection if outside of atmosphere or camera position float distCurrent = dist0; //Rayleigh light contribution QVector3D rSum(0.0f, 0.0f, 0.0f); //Mie light contribution QVector3D mSum(0.0f, 0.0f, 0.0f); //Accumulated exponent function of negative height by height scale division for transmittance integral //Rayleigh float rOpticalDepthAcc = 0.0f; //Mie float mOpticalDepthAcc = 0.0f; //Greek letter mu, cosine between view direction and sun light direction, required for phase function float mu = QVector3D::dotProduct(dir, *sunDir) / (dir.length() * sunDir->length()); //Describes how much light is scattered towards camera //Rayleigh float rPhase = 3.0f / (16.0f * M_PI) * (1 + mu * mu); //Mie float mPhase = 3.0f / (8.0f * M_PI) * ((1.0f - g * g) * (1.0f + mu * mu)) / ((2.0f + g * g) * pow(1.0f + g * g - 2.0f * g * mu, 1.5f)); //Integrate Transmittance over view vector for (int i = 0; i < viewTSamples; i++) { //Sample positions are taken in the middle between sample points QVector3D samplePos = orig + (distCurrent + segmentLength * 0.5f) * dir; //Altitude of the sample point in relation to the ground float height = samplePos.length() - earthRadius; if (height < 0) break; //Exponent function of negative height by height scale division for view ray transmittance integral //Rayleigh float rOpticalDepth = exp(-height / rH) * segmentLength; rOpticalDepthAcc += rOpticalDepth; //Mie float mOpticalDepth = exp(-height / mH) * segmentLength; mOpticalDepthAcc += mOpticalDepth; //Distance to atmosphere from sample point position by the light vector float dist0Light, dist1Light; //Get intersection of light ray with atmosphere. Since sample position is always inside of the atmosphere //there is only one intersection of the ray and atmosphere, the second one raySphereIntersect(samplePos, *sunDir, atmosphereRadius, dist0Light, dist1Light); //Length of the segment on the light ray to integrate light ray Transmittance float segmentLengthLight = dist1Light / lightTSamples; //Start from sample point position float distCurrentLight = 0; //Exponent function of negative height by height scale division for light ray transmittance integral //Rayleigh double rOpticalDepthLightAcc = 0; //Mie double mOpticalDepthLightAcc = 0; int j; for (j = 0; j < lightTSamples; ++j) { //Sample positions are taken in the middle between sample points QVector3D samplePosLight = samplePos + (distCurrentLight + segmentLengthLight * 0.5f) * (*sunDir); //Altitude of the sample point in relation to the ground float heightLight = samplePosLight.length() - earthRadius; //If altitude of a sample point is less than 0 if (heightLight < 0) break; //Exponent function accumulation //Rayleigh rOpticalDepthLightAcc += exp(-heightLight / rH) * segmentLengthLight; //Mie mOpticalDepthLightAcc += exp(-heightLight / mH) * segmentLengthLight; //Advance forward light vector distCurrentLight += segmentLengthLight; } if (j == lightTSamples) { //Transmittance of both types of scattering of both light and view rays first without exponential function, //which is calculated later so that there would not be four exponential calls QVector3D transmittanceWithoutExp = (*rBeta) * (rOpticalDepthAcc + rOpticalDepthLightAcc) + (*mBeta) * 1.1f * (mOpticalDepth + mOpticalDepthLightAcc); QVector3D transmittanceWithExp(exp(-transmittanceWithoutExp.x()), exp(-transmittanceWithoutExp.y()), exp(-transmittanceWithoutExp.z())); //Transmittance part by what is left of the integral part of the sky colour equation except of scattering coefficient beta, because it is a constant in this case //Rayleigh rSum += transmittanceWithExp * rOpticalDepth; //Mie mSum += transmittanceWithExp * mOpticalDepth; } //Advance forward view vector distCurrent += segmentLength; } //Beta by sum are integral part of sky colour equation return (rSum * (*rBeta) * rPhase + mSum * (*mBeta) * mPhase) * sunIntensity; }
37.464986
166
0.694505
[ "mesh", "render", "vector" ]
451e4954773b05f520ef6d9de97a19d0380551bb
3,579
cpp
C++
test/boost_test/eagine/msgbus_serialized_storage.cpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
103
2015-10-15T07:09:22.000Z
2022-03-20T03:39:32.000Z
test/boost_test/eagine/msgbus_serialized_storage.cpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
11
2015-11-25T11:39:49.000Z
2021-06-18T08:06:06.000Z
test/boost_test/eagine/msgbus_serialized_storage.cpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
10
2016-02-28T00:13:20.000Z
2021-09-06T05:21:38.000Z
/* * Copyright Matus Chochlik. * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt */ #include "../../main_ctx.hpp" #include <eagine/message_bus/message.hpp> #define BOOST_TEST_MODULE EAGINE_msgbus_serialized_storage #include "../unit_test_begin.inl" #include <map> #include <vector> BOOST_AUTO_TEST_SUITE(msgbus_serialized_storage_tests) static eagine::test_random_generator rg; //------------------------------------------------------------------------------ BOOST_AUTO_TEST_CASE(msgbus_serialized_storage_1) { using namespace eagine; test_main_ctx tmc; main_ctx_object mco{EAGINE_ID(TestObj), tmc}; std::array<byte, 4 * 1024> temp_buffer{}; std::array<byte, 4 * 1024> pack_buffer{}; memory::buffer test_data{}; msgbus::connection_outgoing_messages com; msgbus::connection_incoming_messages cim; const std::array<message_id, 10> msgids{ {EAGINE_MSG_ID(eagiTest1, message1), EAGINE_MSG_ID(eagiTest1, message2), EAGINE_MSG_ID(eagiTest1, message3), EAGINE_MSG_ID(eagiTest1, message4), EAGINE_MSG_ID(eagiTest1, message5), EAGINE_MSG_ID(eagiTest2, message6), EAGINE_MSG_ID(eagiTest2, message7), EAGINE_MSG_ID(eagiTest2, message8), EAGINE_MSG_ID(eagiTest2, message9), EAGINE_MSG_ID(eagiTest2, message0)}}; std::map<msgbus::message_sequence_t, std::tuple<message_id, span_size_t>> msg_infos; msgbus::message_sequence_t total_sent = 0; msgbus::message_sequence_t total_rcvd = 0; auto test_handler = [&msg_infos, &total_rcvd]( auto msgid, auto, auto msg) -> bool { BOOST_ASSERT(!msg_infos.empty()); auto& [cmpid, cmpsz] = msg_infos[msg.sequence_no]; BOOST_CHECK(msgid == cmpid); BOOST_CHECK_EQUAL(msg.data.size(), cmpsz); msg_infos.erase(msg.sequence_no); ++total_rcvd; return true; }; for(int i = 0; i < test_repeats(100, 1000); ++i) { for(int s = 0, n = rg.get_int(20, 100); s < n; ++s) { const auto size = rg.get_span_size(1, 3 * 1024); test_data.resize(size); const message_id msgid = rg.pick_one_of(msgids); msgbus::message_view msg{memory::const_block{test_data}}; msg.set_sequence_no(total_sent); const auto enqueued = com.enqueue(mco, msgid, msg, cover(temp_buffer)); BOOST_ASSERT(enqueued); msg_infos[total_sent++] = {msgid, size}; } BOOST_CHECK(!com.empty()); for(int p = 0, n = rg.get_int(1, 100); p < n; ++p) { const auto packed = com.pack_into(cover(pack_buffer)); if(!com.empty()) { BOOST_ASSERT(packed); cim.push(view(pack_buffer)); com.cleanup(packed); } } while(!cim.empty()) { cim.fetch_messages(mco, {construct_from, test_handler}); } } while(!com.empty()) { const auto packed = com.pack_into(cover(pack_buffer)); BOOST_ASSERT(packed); cim.push(view(pack_buffer)); com.cleanup(packed); cim.fetch_messages(mco, {construct_from, test_handler}); } BOOST_CHECK_EQUAL(total_sent, total_rcvd); BOOST_CHECK(cim.empty()); BOOST_CHECK_EQUAL(msg_infos.size(), 0); } //------------------------------------------------------------------------------ BOOST_AUTO_TEST_SUITE_END() #include "../unit_test_end.inl"
33.448598
80
0.607712
[ "vector" ]
45314cee5a14ccc3f8753370a0d1009b9fda0150
12,017
cc
C++
lib/build_packet_1_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
1
2021-06-16T14:35:29.000Z
2021-06-16T14:35:29.000Z
lib/build_packet_1_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
null
null
null
lib/build_packet_1_impl.cc
pavelfpl/gr-gsSDR
141f5cd1f53b9691c7c7e084f32343bddc0d2d97
[ "MIT" ]
1
2021-03-03T14:51:02.000Z
2021-03-03T14:51:02.000Z
/* -*- c++ -*- */ /* MIT License * * Copyright (c) 2021 Pavel Fiala * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "build_packet_1_impl.h" // --------------------- // GNURADIO specific ... // --------------------- #include <gnuradio/io_signature.h> #include <gnuradio/blocks/pdu.h> #include <gnuradio/thread/thread.h> #include <gnuradio/digital/crc32.h> // ------------------- // System standard ... // ------------------- #include <sys/types.h> #include <sys/stat.h> #include <stdexcept> #include <cstdlib> #include <limits> #include <time.h> #include <stdio.h> // -------------- // My DEFINES ... // -------------- #define CONST_DATA_FROM_RANDOM_GENERATOR 0 #define CONST_DATA_FROM_FILE 1 #define CONST_DATA_CMD_LINE 2 #define CONST_DATA_PACKED 0 #define CONST_DATA_UNPACKED 1 #define CONST_HEADER_PRELOAD_BYTES 2 #define CONST_HEADER_PACKET_SIZE 2 #define CONST_HEADER_CRC32 4 #define CONST_PAYLOAD_CRC32 4 #define CONST_TRANSFER_IN_PROGRESS 0 #define CONST_TRANSFER_READY 1 #define CONST_FILE_READ_OK 0 #define CONST_FILE_READ_FAILED 1 // ------------------------------------------------------------------------------------------------------ // !!! ADD DIGITAL component to ROOT CMakeList.txt - set(GR_REQUIRED_COMPONENTS RUNTIME FFT DIGITAL) !!! // ------------------------------------------------------------------------------------------------------ namespace gr { namespace gsSDR { using namespace std; build_packet_1::sptr build_packet_1::make(bool appendHeader, int packetLength, int dataType, int dataFrom, const char *filename, std::vector<unsigned char> packet_bytes_h) { return gnuradio::get_initial_sptr (new build_packet_1_impl(appendHeader, packetLength, dataType, dataFrom, filename, packet_bytes_h)); } /* * The private constructor ... * --------------------------- */ build_packet_1_impl::build_packet_1_impl(bool appendHeader, int packetLength, int dataType, int dataFrom, const char *filename, std::vector<unsigned char> packet_bytes_h) : gr::block("build_packet_1", gr::io_signature::make(0, 0, 0), // gr::io_signature::make(<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)), gr::io_signature::make(0, 0, 0)), // gr::io_signature::make(<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>))) m_appendHeader(appendHeader), // appendHeader - append header to beginning of the packet m_packetLength(packetLength), // burst packet length / including header m_dataType(dataType), // output data type - packed or unpacked m_dataFrom(dataFrom) // dataFrom - fromFile or random / for testing { if(packetLength == 0) packetLength = 64; // Set default vector [ packet size ]... if(m_dataFrom == CONST_DATA_FROM_FILE){ fileOpen(filename); } // Set packet bytes uchar ... // -------------------------- packet_bytes = packet_bytes_h; // Initialize random seed ... // -------------------------- srand(time(NULL)); out_port_0 = pmt::mp("stat_pdus"); out_port_1 = pmt::mp("out_pdus"); message_port_register_in(pmt::mp("pdus")); message_port_register_out(out_port_0); // pdu - status ... message_port_register_out(out_port_1); // pud - vectors ... set_msg_handler(pmt::mp("pdus"), boost::bind(&build_packet_1_impl::packet_handler, this, _1)); } // fileOpen - private function ... // ------------------------------- void build_packet_1_impl::fileOpen(const char *filename){ // obtain exclusive access for duration of this function ... // --------------------------------------------------------- gr::thread::scoped_lock lock(fp_mutex); struct stat results; // The size of the file in bytes is in results.st_size ... // ------------------------------------------------------- if(stat(filename, &results) != 0){ perror(filename); throw std::runtime_error("File status failed"); } // Set file size ... // ----------------- m_fileSize = results.st_size; m_fileIncrement = 0; fileToTransfer.open(filename, ios::in | ios::binary); } // fileClose - private function ... // -------------------------------- void build_packet_1_impl::fileClose(){ // Close file [if opened] ... // -------------------------- if(fileToTransfer.is_open()) fileToTransfer.close(); } /* * Our virtual destructor. * ----------------------- */ build_packet_1_impl::~build_packet_1_impl(){ fileClose(); } void build_packet_1_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) { /* <+forecast+> e.g. ninput_items_required[0] = noutput_items */ } int build_packet_1_impl::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { /* const <+ITYPE*> *in = (const <+ITYPE*> *) input_items[0]; <+OTYPE*> *out = (<+OTYPE*> *) output_items[0]; */ // Do <+signal processing+> // Tell runtime system how many input items we consumed on // each input stream. consume_each (noutput_items); // Tell runtime system how many output items we produced. return noutput_items; } // packet_handler - public function / callback ... // ----------------------------------------------- void build_packet_1_impl::packet_handler(pmt::pmt_t msg){ int offset = 0; int extraOffset = 0; // Valid only for file read transfer ... int payload_length = m_packetLength; // Get parameters from the pdu / or make dict ... // ---------------------------------------------- // pmt::pmt_t meta = pmt::car(msg); pmt::pmt_t meta = pmt::make_dict(); // Create vector of given length - m_packetLength / packed ... // ----------------------------------------------------------- vector<unsigned char> data_packet(m_packetLength,0x00); // Set default values ... // Generate header of the packet / PRE ... // ---------------------------------------- if(m_appendHeader && m_dataFrom != CONST_DATA_CMD_LINE){ *(uint16_t*)&data_packet[0] = 0x1337; // Header == 0x1337 [2 bytes] *(uint16_t*)&data_packet[2] = m_packetLength - CONST_HEADER_PRELOAD_BYTES - CONST_HEADER_PACKET_SIZE - CONST_HEADER_CRC32 - CONST_PAYLOAD_CRC32; // [2 bytes] *(uint32_t*)&data_packet[4] = gr::digital::crc32(&data_packet[0],4); // [4 bytes] // Add header offset ... // --------------------- offset+=8; payload_length-= CONST_PAYLOAD_CRC32; } // Append payload bytes / option 0 - RANDOM PAYLOAD ... // ---------------------------------------------------- if(m_dataFrom == CONST_DATA_FROM_RANDOM_GENERATOR){ for(int i = offset;i < payload_length;i++){ data_packet[i] = rand() % 256; // Bytes - 0 ... 255 } } // Append payload bytes / option 1 - DATA_FROM_FILE PAYLOAD ... // ------------------------------------------------------------ if(m_dataFrom == CONST_DATA_FROM_FILE){ if(m_fileIncrement < m_fileSize){ // Check for opened file ... // ------------------------- if(fileToTransfer.is_open()){ char read2file[payload_length - offset]; // seekg ... // --------- fileToTransfer.seekg(m_fileIncrement); // read ... // -------- fileToTransfer.read(read2file, (payload_length - offset)); // EOF or error states ... // ----------------------- if(!fileToTransfer){ extraOffset = (payload_length - offset) - fileToTransfer.gcount(); fileToTransfer.clear(); // Clear errors ... } // m_fileIncrement ... // ------------------- m_fileIncrement+=(payload_length - offset) - extraOffset; // copy data to data_packet ... // ---------------------------- for(int i = offset;i < (payload_length - extraOffset);i++){ data_packet[i] = (unsigned char)read2file[i-offset]; } // pmt ... // ------- meta = pmt::dict_add(meta, pmt::string_to_symbol("f_errors"), pmt::from_long(CONST_FILE_READ_OK)); meta = pmt::dict_add(meta, pmt::string_to_symbol("f_transfer"), pmt::from_long(CONST_TRANSFER_IN_PROGRESS)); message_port_pub(out_port_0,meta); }else{ // Handle errors + pmt ... // ----------------------- meta = pmt::dict_add(meta, pmt::string_to_symbol("f_errors"), pmt::from_long(CONST_FILE_READ_OK)); meta = pmt::dict_add(meta, pmt::string_to_symbol("f_transfer"), pmt::from_long(CONST_TRANSFER_READY)); message_port_pub(out_port_0,meta); return; } }else{ // pmt - transfer ready ... // ------------------------ meta = pmt::dict_add(meta, pmt::string_to_symbol("f_errors"), pmt::from_long(CONST_FILE_READ_OK)); meta = pmt::dict_add(meta, pmt::string_to_symbol("f_transfer"), pmt::from_long(CONST_TRANSFER_READY)); message_port_pub(out_port_0,meta); return; } } // Append payload bytes / option 2 - RANDOM FROM CMD LINE ... // ---------------------------------------------------------- if(m_dataFrom == CONST_DATA_CMD_LINE){ data_packet.resize(packet_bytes.size()); m_packetLength = packet_bytes.size(); for(int i = 0;i < packet_bytes.size();i++){ data_packet[i] = packet_bytes[i]; } } // Generate header of the packet / POST ... // ----------------------------------------- if(m_appendHeader && m_dataFrom != CONST_DATA_CMD_LINE){ if(extraOffset!=0){ *(uint16_t*)&data_packet[2]-= extraOffset; *(uint32_t*)&data_packet[4] = gr::digital::crc32(&data_packet[0],4);} *(uint32_t*)&data_packet[payload_length - extraOffset] = gr::digital::crc32(&data_packet[8],(payload_length - offset) - extraOffset); // extraOffset - valid only for file read ... } // Data packed ... // --------------- if(m_dataType == CONST_DATA_PACKED){ pmt::pmt_t packed_vec = pmt::init_u8vector(m_packetLength, data_packet); message_port_pub(out_port_1, pmt::cons(meta, packed_vec)); } // Data unpacked ... // ----------------- /* in 0b11110000 out 0b00000001 0b00000001 0b00000001 0b00000001 0b00000000 0b00000000 0b00000000 0b00000000 * https://stackoverflow.com/questions/50977399/what-do-packed-to-unpacked-blocks-do-in-gnu-radio * */ if(m_dataType == CONST_DATA_UNPACKED){ int unpackedLength = m_packetLength*8; vector<unsigned char> data_unpacked(unpackedLength,0x00); // unpacked bytes ... for (int i=0; i<unpackedLength; i++){ data_unpacked[i] = (unsigned char)((data_packet.at(i/8) & (1 << (7 - (i % 8)))) != 0); } pmt::pmt_t unpacked_vec = pmt::init_u8vector(unpackedLength, data_unpacked); message_port_pub(out_port_1, pmt::cons(meta, unpacked_vec)); } } } /* namespace gsSDR */ } /* namespace gr */
36.087087
183
0.589498
[ "vector" ]
4535e376557c13b69e41310e07573968aa51d845
1,751
cc
C++
idrsservice/src/model/DeleteUserDepartmentsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
idrsservice/src/model/DeleteUserDepartmentsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
idrsservice/src/model/DeleteUserDepartmentsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/idrsservice/model/DeleteUserDepartmentsRequest.h> using AlibabaCloud::Idrsservice::Model::DeleteUserDepartmentsRequest; DeleteUserDepartmentsRequest::DeleteUserDepartmentsRequest() : RpcServiceRequest("idrsservice", "2020-06-30", "DeleteUserDepartments") { setMethod(HttpRequest::Method::Post); } DeleteUserDepartmentsRequest::~DeleteUserDepartmentsRequest() {} std::vector<std::string> DeleteUserDepartmentsRequest::getDepartmentId()const { return departmentId_; } void DeleteUserDepartmentsRequest::setDepartmentId(const std::vector<std::string>& departmentId) { departmentId_ = departmentId; for(int dep1 = 0; dep1!= departmentId.size(); dep1++) { setParameter("DepartmentId."+ std::to_string(dep1), departmentId.at(dep1)); } } std::vector<std::string> DeleteUserDepartmentsRequest::getUserId()const { return userId_; } void DeleteUserDepartmentsRequest::setUserId(const std::vector<std::string>& userId) { userId_ = userId; for(int dep1 = 0; dep1!= userId.size(); dep1++) { setBodyParameter("UserId."+ std::to_string(dep1), userId.at(dep1)); } }
31.267857
97
0.74586
[ "vector", "model" ]
453a760dd3643670593db021b223488a10b13dbb
429
cc
C++
Thinking_in_Cpp/I/C04/vector_init.cc
honeytavis/cpp
232cb0add3f5b481b62a9a23d086514e2c425279
[ "MIT" ]
null
null
null
Thinking_in_Cpp/I/C04/vector_init.cc
honeytavis/cpp
232cb0add3f5b481b62a9a23d086514e2c425279
[ "MIT" ]
null
null
null
Thinking_in_Cpp/I/C04/vector_init.cc
honeytavis/cpp
232cb0add3f5b481b62a9a23d086514e2c425279
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> svec(10, "hello"); for (auto i : svec) { std::cout << i << " "; } std::cout << std::endl; std::vector<int> nvec1(10, 666); for (auto i : nvec1) { std::cout << i << " "; } std::cout << std::endl; std::vector<int> nvec2{10, 666}; for (auto i : nvec2) { std::cout << i << " "; } std::cout << std::endl; }
16.5
45
0.524476
[ "vector" ]
45466f1e8f720c9cd2fcd87588efa3374fefbc76
1,619
cpp
C++
CGameEngine/src/Engine/Texture.cpp
3DExtended/C-GameEngine
557b5894d4a574772c17efe729a872f3d192ee7e
[ "MIT" ]
2
2017-09-05T12:35:16.000Z
2019-10-26T09:56:35.000Z
CGameEngine/src/Engine/Texture.cpp
3DExtended/C-GameEngine
557b5894d4a574772c17efe729a872f3d192ee7e
[ "MIT" ]
null
null
null
CGameEngine/src/Engine/Texture.cpp
3DExtended/C-GameEngine
557b5894d4a574772c17efe729a872f3d192ee7e
[ "MIT" ]
null
null
null
#include "Texture.h" ENGINE::Texture::Texture(const std::string path) { // Load file and decode image. std::vector<unsigned char> image; unsigned int width, height; unsigned int error = lodepng::decode(image, width, height, path.c_str()); // If there's an error, display it. if (error != 0) { std::cout << "error " << error << ": " << lodepng_error_text(error) << std::endl; assert(false); } // Texture size must be power of two for the primitive OpenGL version this is written for. Find next power of two. size_t u2 = 1; while (u2 < width) u2 *= 2; size_t v2 = 1; while (v2 < height) v2 *= 2; // Make power of two version of the image. std::vector<unsigned char> image2(u2 * v2 * 4); for (size_t y = 0; y < height; y++) { for (size_t x = 0; x < width; x++) { for (size_t c = 0; c < 4; c++) { image2[4 * u2 * y + 4 * x + c] = image[4 * width * y + 4 * x + c]; } } } //Generate opengl needed things glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, u2, //width v2, //height 0, GL_RGBA, GL_UNSIGNED_BYTE, &image2[0]); glBindTexture(GL_TEXTURE_2D, 0); } void ENGINE::Texture::_bind() { glActiveTexture(numberOfTexture); glBindTexture(GL_TEXTURE_2D, textureID); } void ENGINE::Texture::_unbind() { glBindTexture(GL_TEXTURE_2D, 0); }
25.698413
115
0.678814
[ "vector" ]
454e929235f8e72d1dd1fe2d6e76d12fe9fb97e0
27,276
cxx
C++
model_server/subsystem/src/Entity.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
model_server/subsystem/src/Entity.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
model_server/subsystem/src/Entity.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY 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. * *************************************************************************/ /* * Entity.h.C * * Definitions for high-level Entity object * */ #include <cLibraryFunctions.h> #include <Entity.h> #include <autosubsys.h> #include <proj.h> #include <autosubsys-weights.h> #include <linkType_selector.h> #include <XrefTable.h> /* Class statics */ objSet Entity::projects_to_search; allentity* Entity::allentities; static Entity no_class; // used as dummy target for basetype and parent_class // if is a builtin type, not a member of the projects // being analyzed, or whatever /* simple constructor */ Entity::Entity(): isundead(false), preve(NULL), nexte(NULL), parent_class(NULL), basetype(NULL) { } /* copy constructor */ Entity::Entity(const Entity& o): Obj(o), isundead(o.isundead), preve(o.preve), nexte(o.nexte), parent_class(o.parent_class), basetype(o.basetype) { } //------------------------------------------ // Debugging print() function //------------------------------------------ void Entity::print(ostream& ostr, int) const { ostr << get_name(); } // // Add Entity to allentities' xref mapping; alreadyused refers to whether the // entity should consider itself already in a subsystem or not. // add() and add1() are long gone. int Entity::add2(const symbolPtr& sym, int) { Initialize(Entity::add2); allentities->add(this, sym); my_sym = sym; return 1; } // // Given a particular relation and a symbolPtr, we find the symbol's // entity and then create the reference. (For historical reasons, the // rels are "backwards" -- e.g., if entity A calls entity B, this // routine will be called with A as "this", B as "sym", and // AUS_FCALL_INV as the rel; the proper way to read this is // "sym rel this", or "B is called by this". This made more sense // with the "relation" implementation; now that we use refs_and_weights, // we use the inverse rel with "this" and the passed rel with "sym.") void Entity::relate_to_symbol(size_t rel, const symbolPtr& sym) { Initialize(Entity::relate_to_symbol); Entity *ffar = allentities->item(sym); if (ffar && this!=ffar) { size_t inv_rel; bool outgoing = false; if (rel >= NWEIGHTS / 2) { inv_rel = rel - NWEIGHTS / 2; outgoing = true; } else inv_rel = rel + NWEIGHTS / 2; rw.add_ref(ffar->index(), inv_rel); ffar->rw.add_ref(index(), rel); if (outgoing) { // Take care of model aliases -- if this calls foo(), for instance, // and there is more than one foo() in the model, we can't tell which // foo() is involved, so we'd better add relations with all of them. // (Aliased Entities were linked together in decomposer::additems().) EntityPtr e; for (e = ffar->get_preve(); e; e = e->get_preve()) { rw.add_ref(e->index(), inv_rel); e->rw.add_ref(index(), rel); } for (e = ffar->get_nexte(); e; e = e->get_nexte()) { rw.add_ref(e->index(), inv_rel); e->rw.add_ref(index(), rel); } if (rel == AUS_FCALL_INV || rel == AUS_DATAREF_INV) { // apply usage of member so that class is used, too if (!ffar->parent_class && strstr(ffar->my_sym.get_name(), "::")) { symbolPtr parent_sym = ffar->my_sym.get_parent_of(projects_to_search); if (parent_sym.xrisnotnull()) { ffar->parent_class = allentities->item(parent_sym); } } if (ffar->parent_class) { rw.add_ref(ffar->parent_class->index(), AUS_DATAREF); ffar->parent_class->rw.add_ref(index(), AUS_DATAREF_INV); } if (ffar->my_sym.get_kind() == DD_TYPEDEF) { if (!ffar->basetype) { ffar->set_basetype(); } if (ffar->basetype != &no_class) { rw.add_ref(ffar->basetype->index(), inv_rel); ffar->basetype->rw.add_ref(index(), rel); } } } } } } //============================================= // collect_classes_from_type: takes the type ("has_type" link) of the // supplied symbol and filters the result for a class or enum that is // used in the type. It handles indirecting through typedefs. If the // result array is non-empty, it returns "true." //============================================= bool collect_classes_from_type(const symbolPtr& type, symbolArr& classes, const objSet& projects_to_search) { Initialize(collect_classes_from_type); symbolArr targs; if (type->get_link(is_using, targs, projects_to_search, type.get_xref()->get_lxref())) { symbolPtr targ; ForEachS(targ, targs) { ddKind k = targ.get_kind(); if (k == DD_CLASS || k == DD_ENUM) { classes.insert_last(targ); } else if (k == DD_TYPEDEF) { symbolArr targs2; if (targ.get_link(have_arg_type, targs2, projects_to_search)) { symbolPtr targ2; ForEachS(targ2, targs2) { ddKind k2 = targ2.get_kind(); if (k2 == DD_CLASS || k2 == DD_ENUM) { classes.insert_last(targ2); } } } } } } return (classes.size() > 0); } // relate_to_type caches the result of collect_classes_from_type, which is // horrendously expensive, in the allentities xref mapper, as well as // establishing the relationship between this entity and the class used in // its type/return type. symbolPtr Entity::relate_to_type(const symbolPtr& type, size_t rel) { Initialize(Entity::relate_to_type); Entity* type_class = allentities->item(type); if (!type_class) { symbolArr classes; if (collect_classes_from_type(type, classes, projects_to_search)) { symbolPtr cl; ForEachS(cl, classes) { if (type_class = allentities->item(cl)) { break; } } } if (!type_class) { type_class = &no_class; } allentities->add_sym_alias(type_class, type); } if (type_class != &no_class) { relate_to_symbol(rel, type_class->my_sym); return type_class->my_sym; } return NULL_symbolPtr; } // // newrelate sets up the relations between entities. All of them. It replaces // an enormous hodge-podge of ad-hockery which ultimately collapsed under its // own weight (and the lack of support underneath from a changed data // dictionary...) int Entity::newrelate() { Initialize(Entity::newrelate); symbolPtr used; symbolPtr user; symbolPtr type; symbolArr targs; symbolPtr targ; linkType_selector sel; int i; if (my_sym.xrisnotnull()) { switch(my_sym.get_kind()) { case DD_FUNC_DECL: { symbolPtr class_of_func = NULL_symbolPtr; size_t qual_len = 0; sel.add_link_type(is_using); sel.add_link_type(has_type); sel.add_link_type(have_arg_type); const char* my_name = my_sym.get_name(); const char* q = strstr(my_name, "::"); if (q) { qual_len = q - my_name + 2; } my_sym.get_links(sel, projects_to_search, false); // Because "is_using" is very general, subsuming many kinds of relationships, // we process more-specific link types first and remove entities related in // those ways from the "useds" array. This means that certain relationships // will be ignored -- e.g., if a function takes class A as an argument and // also uses it in the body of the function, only the former relationship // will be honored. It's not perfect, but it's the best we can do with the // kind of information maintained in the PMOD. // The first step is to find classes used in the function declaration, i.e., // as arguments or the return type. These are lumped together in the PMOD // under the "have_arg_type" link. We can then find the return type using // the "has_type" link and process its target separately, playing the same // game as for "useds" with the combined list of types. if (sel[has_type].size()) { targ = relate_to_type(sel[has_type][0], AUS_RETTYPE_INV); if (targ.isnotnull()) { sel[have_arg_type].remove(targ); sel[is_using].remove(targ); } } ForEachS(type, sel[have_arg_type]) { ddKind k = type.get_kind(); if (k == DD_CLASS || k == DD_ENUM) { relate_to_symbol(AUS_ARGTYPE_INV, type); sel[is_using].remove(type); } } // Now go through remaining items used by this func and add appropriate // relationships. ForEachS(used, sel[is_using]) { switch (used.get_kind()) { case DD_FUNC_DECL: relate_to_symbol(AUS_FCALL_INV, used); break; case DD_VAR_DECL: case DD_CLASS: case DD_ENUM: case DD_TYPEDEF: relate_to_symbol(AUS_DATAREF_INV, used); break; case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; case DD_FIELD: { if (!(qual_len && memcmp(my_name, used.get_name(), qual_len) == 0)) { /* not a reference to another member of the same class */ targ = used.get_parent_of(projects_to_search); if (targ.xrisnotnull()) { relate_to_symbol(AUS_DATAREF_INV, targ); } } if (used.get_link(has_type, targs, projects_to_search)) { relate_to_type(targs[0], AUS_DATAREF_INV); } break; } case DD_ENUM_VAL: { targ = used.get_parent_of(projects_to_search); if (targ.xrisnotnull()) relate_to_symbol(AUS_DATAREF_INV, targ); break; } default: break; } } break; } /*************************************************************************** * Many of the same considerations apply to DD_CLASS symbols; of course, * the inverse relationships with DD_FUNC_DECLs are the same (used_by * instead of is_using), but there are also is_using, which may indicate * use of a class as the type of a member or, possibly, friendship. * * Finding the functions in whose arguments this class participates is more * involved, however; we have to find all the functions using the class and * scan through their argument lists to find references to the class. */ case DD_CLASS: sel.add_link_type(is_using); sel.add_link_type(have_friends); sel.add_link_type(has_superclass); my_sym.get_links(sel, projects_to_search, false); // Handle friend relationships for (i = 0; i < sel[have_friends].size(); i++) { targ = sel[have_friends][i]; relate_to_symbol(AUS_FRIEND_INV, targ); sel[is_using].remove(targ); } // Handle superclass/subclass relationships for (i = 0; i < sel[has_superclass].size(); i++) { targ = sel[has_superclass][i]; relate_to_symbol(AUS_SUBCLASS_INV, targ); sel[is_using].remove(targ); } // Handle remaining cases of useds: members, nested classes, and macros { ForEachS(used, sel[is_using]) { switch (used.get_kind()) { case DD_FUNC_DECL: case DD_VAR_DECL: relate_to_symbol(AUS_MEMBER, used); break; case DD_TYPEDEF: case DD_ENUM: case DD_CLASS: { // check for nested typedef: name must begin with // "my_name::" const char* my_name = my_sym.get_name(); size_t my_name_len = strlen(my_name); const char* used_name = used.get_name(); size_t used_name_len = strlen(used_name); const char* qual = used_name + my_name_len; if (used_name_len > my_name_len && qual[0] == ':' && qual[1] == ':' && memcmp(my_name, used_name, my_name_len) == 0) { relate_to_symbol(AUS_ELEMENT_INV, used); } break; } case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; default: break; } } } break; /*************************************************************************** * DD_VAR_DECLs only participate in a few relationships: * used_by indicates a reference to the variable from a function or a * membership relationship in a class. "is_using" reflects either the * type of the variable or an initializer. */ case DD_VAR_DECL: { symbolPtr class_of_var = NULL_symbolPtr; size_t qual_len = 0; sel.add_link_type(is_using); sel.add_link_type(has_type); const char* my_name = my_sym.get_name(); const char* q = strstr(my_name, "::"); if (q) { qual_len = q - my_name; } my_sym.get_links(sel, projects_to_search, false); if (sel[has_type].size()) { targ = relate_to_type(sel[has_type][0], AUS_INSTANCE_INV); if (targ.isnotnull()) { sel[is_using].remove(targ); } } ForEachS(used, sel[is_using]) { switch(used.get_kind()) { case DD_VAR_DECL: case DD_CLASS: case DD_ENUM: case DD_TYPEDEF: relate_to_symbol(AUS_DATAREF_INV, used); break; case DD_FUNC_DECL: case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; case DD_FIELD: if (used.get_link(has_type, targs, projects_to_search)) { relate_to_type(targs[0], AUS_DATAREF_INV); } /* FALLTHROUGH */ case DD_ENUM_VAL: targ = used.get_parent_of(projects_to_search); if (targ.xrisnotnull()) { relate_to_symbol(AUS_DATAREF_INV, targ); } break; default: break; } } break; } case DD_MACRO: { symbolArr useds; my_sym.get_link_chase_typedefs(is_using, useds, projects_to_search); ForEachS(used, useds) { switch(used.get_kind()) { case DD_FUNC_DECL: case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; case DD_VAR_DECL: case DD_CLASS: case DD_ENUM: case DD_TYPEDEF: relate_to_symbol(AUS_DATAREF_INV, used); break; case DD_FIELD: if (used.get_link(has_type, targs, projects_to_search)) { relate_to_type(targs[0], AUS_DATAREF_INV); } /* FALLTHROUGH */ case DD_ENUM_VAL: targ = used.get_parent_of(projects_to_search); if (targ.xrisnotnull()) relate_to_symbol(AUS_DATAREF_INV, targ); break; default: break; } } break; } case DD_TYPEDEF: { symbolArr useds; my_sym.get_link_chase_typedefs(have_arg_type, useds, projects_to_search); ForEachS(used, useds) { switch(used.get_kind()) { case DD_CLASS: case DD_ENUM: case DD_TYPEDEF: relate_to_symbol(AUS_DATAREF_INV, used); break; case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; default: break; } } break; } case DD_ENUM: { symbolArr members; my_sym.get_link(is_using, members, projects_to_search); symbolPtr member; ForEachS(member, members) { symbolArr targs; symbolPtr targ; member->get_link(is_using, targs); ForEachS(targ, targs) { switch(targ.get_kind()) { case DD_VAR_DECL: relate_to_symbol(AUS_DATAREF_INV, used); break; case DD_MACRO: relate_to_symbol(AUS_FCALL_INV, used); break; case DD_ENUM_VAL: { symbolPtr targ_enum = targ.get_parent_of(projects_to_search); if (targ_enum.xrisnotnull()) relate_to_symbol(AUS_DATAREF_INV, targ_enum); break; } default: break; } } } break; } default: break; } } return 1; } // // The original relate function called half a dozen other things. // int Entity::relate() { Initialize(Entity::relate); newrelate(); return 1; } // // Returns the name of the associated xrefSymbol. char *Entity::get_name() const { Initialize(Entity::get_name); return my_sym.get_name(); } // // Return dormant/live status: int Entity::isdead() { return !isundead; } // // Goes down from this entity to mark all code that is actually referenced. // We stop going down and go sideways when we find something already marked // as live, both to protect against infinite recursion and to improve speed // if this is done several times with different top-level functions. void Entity::find_live_code(struct weight *w, int nw, int depth, FILE* dump_file) { Initialize(Entity::find_live_code); if (dump_file) { OSapi_fprintf(dump_file, "%2d:%.*s ", depth, depth, "=============================="); dump_refs_and_weights(dump_file, *allentities); } ddKind my_kind = my_sym.get_kind(); refs_and_weights_iter it(rw); ref_and_weight* ref; while (ref = it.next()) { if (w[ref->weight].outgoing) { EntityPtr ent = EntityPtr((*allentities)[ref->targ_ref]); symbolPtr ent_sym = ent->my_sym; // The condition following the "||" handles the case where there // is a direct reference to a virtual destructor that was earlier // processed only by virtue of being a member of a base class of // a destroyed object. if (!ent->isundead || (ref->weight == AUS_FCALL && strstr(ent_sym.get_name(), "::~") && ent_sym->get_attribute(VIRT_ATT, 1))) { // The condition following the "||" handles the case of a ptr-to-mbr // variable that is initialized with "ent"; dereferencing this variable // does a virtual dispatch, so the code below must be executed in this // case. if (ref->weight == AUS_FCALL || (my_kind == DD_VAR_DECL && ent_sym.get_kind() == DD_FUNC_DECL)) { symbolArr relateds; ent_sym.get_overrides(relateds, false); ent->add_operator_delete(relateds); ent_sym.get_base_dtors(relateds); ent->find_member_dtors(relateds); if (relateds.size() == 0) { relateds.insert_last(ent_sym); } symbolPtr related; ForEachS(related, relateds) { EntityPtr rel_ent = allentities->item(related); if (rel_ent && !rel_ent->isundead) { rel_ent->isundead = 1; if (dump_file) { OSapi_fprintf(dump_file, "+"); } rel_ent->find_live_code(w, nw, depth + 1, dump_file); } } } else { ent->isundead = 1; if (dump_file) { OSapi_fprintf(dump_file, " "); } ent->find_live_code(w, nw, depth+1, dump_file); } } } } } //------------------------------------------ // Entity::find_member_dtors: if this Entity is a destructor, examines // all sibling members for destructors that will be implicitly invoked by // this destructor and adds any such member destructors to the argument // symbolArr. THIS IS A CROCK AND A KLUDGE AND SHOULD BE REMOVED AS SOON // AS THE MODEL HAS THESE RELATIONSHIPS IN IT. //------------------------------------------ void Entity::find_member_dtors(symbolArr& dtors) { Initialize(Entity::find_member_dtors); // Am I a destructor? if (strstr(my_sym.get_name(), "::~")) { // Find my class and its members (my siblings) symbolArr users; symbolPtr my_class = my_sym.get_parent_of(projects_to_search); if (my_class.xrisnotnull()) { symbolArr siblings; my_class.get_link(is_using, siblings, projects_to_search); // For each data member sibling, check its class for a dtor symbolPtr sibling; ForEachS(sibling, siblings) { if (sibling.get_kind() == DD_FIELD) { symbolArr sib_classes; symbolArr types; if (sibling.get_link(has_type, types, projects_to_search)) { if (collect_classes_from_type(types[0], sib_classes, projects_to_search)) { symbolPtr sib_class; ForEachS(sib_class, sib_classes) { symbolArr members; sib_class.get_link(is_using, members, projects_to_search); symbolPtr member; ForEachS(member, members) { if (member.get_kind() == DD_FUNC_DECL && strstr(member.get_name(), "::~")) { member.get_base_dtors(dtors); // member's and member's bases' break; } } } } } } } } } } //------------------------------------------ // Entity::add_operator_delete: another crock to write around missing model // information. Every destructor that is (or might be because of virtual // overriding) should be listed as calling that class's operator delete() // (if any) so that the operator deletes are not listed as dormant. This // should be called immediately after doing a "get_overrides", because it // assumes the input array is filled (only) with virtual overrides of this // symbol. //------------------------------------------ void Entity::add_operator_delete(symbolArr& overrides) { Initialize(Entity::add_operator_delete); if (strstr(my_sym.get_name(), "::~")) { // I'm a destructor symbolArr op_dels; if (overrides.size() == 0) { overrides.insert_last(my_sym); // at least work on myself } symbolPtr override; ForEachS(override, overrides) { symbolPtr the_class = override.get_parent_of(projects_to_search); if (the_class.xrisnotnull()) { symbolArr members; the_class->get_link(is_using, members); symbolPtr member; ForEachS(member, members) { if (strstr(member.get_name(), "operator delete")) { op_dels.insert_last(member); break; // only one per class } } } } overrides.insert_last(op_dels); } } //------------------------------------------ // Entity::dump_refs_and_weights //------------------------------------------ void Entity::dump_refs_and_weights(FILE* f, const objArr& entities) { Initialize(Entity::dump_refs_and_weights); OSapi_fprintf(f, "%s:\n", get_name()); rw.dump(f, entities); } //------------------------------------------ // Entity::set_allentities [static] //------------------------------------------ void Entity::set_allentities(allentity* ae) { Initialize(Entity::set_allentities); allentities = ae; } //------------------------------------------ // Entity:: set_preve //------------------------------------------ void Entity::set_preve(Entity* e) { Initialize(Entity::set_preve); preve = e; } //------------------------------------------ // Entity::set_nexte //------------------------------------------ void Entity::set_nexte(Entity* e) { Initialize(Entity::set_nexte); nexte = e; } //------------------------------------------ // Entity::set_basetype() //------------------------------------------ void Entity::set_basetype() { Initialize(Entity::set_basetype); if (!basetype) { symbolArr targs; if (my_sym.get_link(have_arg_type, targs, projects_to_search)) { symbolPtr targ; ForEachS(targ, targs) { ddKind k = targ.get_kind(); if (k == DD_CLASS || k == DD_ENUM) { basetype = allentities->item(targ); break; } } } if (!basetype) { basetype = &no_class; } } } /* START-LOG------------------------------------------- $Log: Entity.cxx $ Revision 1.21 2002/01/23 09:58:06EST ktrans Merge from branch: mainly dormant code removal Revision 1.2.1.23 1994/03/29 01:23:29 builder {P``Port Revision 1.2.1.22 1994/03/22 20:15:42 mg Bug track: 1 validation for dormant code Revision 1.2.1.21 1994/02/16 18:11:45 kws Port Revision 1.2.1.20 1993/12/08 21:37:38 wmm Bug track: 5043 Fix bug 5043. Revision 1.2.1.19 1993/09/14 16:50:09 bella testing Revision 1.2.1.18 1993/09/14 16:36:15 bella testing Revision 1.2.1.17 1993/08/25 17:02:36 wmm Fix bug 4531. Revision 1.2.1.16 1993/08/23 18:32:54 wmm Fix bug 4151. Revision 1.2.1.15 1993/05/24 01:00:41 wmm Fix bugs 3244, 3243, 3252, and 3152. Revision 1.2.1.14 1993/05/20 11:52:08 wmm Tweak automatic subsystem extraction algorithm (use only processed objects for intra-subsystem binding calculation). Revision 1.2.1.13 1993/05/17 17:33:06 wmm Performance tuning, etc., for subsystem extraction. Revision 1.2.1.12 1993/05/11 11:09:40 wmm Performance enhancement for subsystem extraction (forgot to remove Initialize() macro from inlined function, so it wasn't really inlined). Revision 1.2.1.11 1993/05/10 11:40:36 wmm Performance improvements for automatic subsystem extraction. Revision 1.2.1.10 1993/03/27 02:56:51 davea changes between xrefSymbol* and fsymbolPtr Revision 1.2.1.9 1993/03/26 22:19:28 wmm Fix bug 2827 (adjust to new Xref, etc.). Revision 1.2.1.8 1993/01/28 02:45:15 efreed patch to account for dd class/member connection mods. Revision 1.2.1.7 1992/12/28 19:28:11 wmm Support new subsystem implementation Revision 1.2.1.6 1992/11/23 19:34:37 wmm typesafe casts. Revision 1.2.1.5 1992/11/18 14:37:00 trung change dd_of_xref to function Revision 1.2.1.4 1992/11/17 23:11:48 trung change using to used_of_user Revision 1.2.1.3 1992/10/20 09:53:17 wmm Add copy constructor to allow importation into alphaSET. Revision 1.2.1.2 92/10/09 20:20:58 swu *** empty log message *** */
30.475978
138
0.600528
[ "object", "model" ]
45561ba79d7d9a31190147ba3f24ae6c65ad3e03
15,241
cpp
C++
sources/game.cpp
bourgeoisor/chess3d
bc34fc47381b701167f6d881fe44e7e45ccdee79
[ "MIT" ]
3
2021-01-28T22:46:36.000Z
2021-06-17T05:32:53.000Z
sources/game.cpp
bourgeoisor/chess3d
bc34fc47381b701167f6d881fe44e7e45ccdee79
[ "MIT" ]
null
null
null
sources/game.cpp
bourgeoisor/chess3d
bc34fc47381b701167f6d881fe44e7e45ccdee79
[ "MIT" ]
null
null
null
#include "game.h" GLuint Game::boardObj; GLuint Game::kingObj; GLuint Game::queenObj; GLuint Game::bishopObj; GLuint Game::knightObj; GLuint Game::rookObj; GLuint Game::pawnObj; float Game::cameraAlpha; float Game::cameraBeta; float Game::cameraRadius; bool Game::mouseRightClick; int Game::motionLastX; int Game::motionLastY; char Game::turn; char Game::board[8][8] = { {'r', 'n', 'b', 'k', 'q', 'b', 'n', 'r'}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'} }; int Game::selectionI; int Game::selectionJ; std::string Game::msgWhite; std::string Game::msgBlack; std::vector<std::vector<int>> Game::stars; const std::string MSG_YOUR_TURN = "Your turn!"; const std::string MSG_INVALID = "Invalid.."; const std::string MSG_CHECK = "Check.."; const std::string MSG_WIN = "YOU WIN!"; const std::string MSG_LOSE = "Sorry.."; const int WINDOW_WIDTH = 1024; const int WINDOW_HEIGHT = 768; const float MIN_CAMERA_BETA = 0; const float MAX_CAMERA_BETA = 1.4; const int TILE_SIZE = 75; // Main point of entry of the game. Resets the instance variables and sets // the glut callback functions. void Game::start(int *argc, char *argv[]) { cameraAlpha = 0; cameraBeta = 0.5; cameraRadius = 800; selectionI = -1; selectionJ = -1; turn = 'A'; msgWhite = MSG_YOUR_TURN; msgBlack = ""; mouseRightClick = false; glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-WINDOW_WIDTH)/2, (glutGet(GLUT_SCREEN_HEIGHT)-WINDOW_HEIGHT)/2); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow("Chess3D"); init(); glutDisplayFunc(display); glutMouseFunc(mouseInput); glutMotionFunc(mouseMotion); glutReshapeFunc(reshape); glutMainLoop(); } // Initializes the OpenGL environment (lights, tests, and model loading). void Game::init() { glEnable(GL_MULTISAMPLE); glClearColor(0.01, 0.01, 0.06, 0.0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_LIGHT2); glEnable(GL_LIGHT3); glEnable(GL_LIGHT4); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.80, 0.80, -0.60, 0.60, 1, 2000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Load the object models. boardObj = Vao::loadObj("models/board.obj"); kingObj = Vao::loadObj("models/king.obj"); queenObj = Vao::loadObj("models/queen.obj"); bishopObj = Vao::loadObj("models/bishop.obj"); knightObj = Vao::loadObj("models/knight.obj"); rookObj = Vao::loadObj("models/rook.obj"); pawnObj = Vao::loadObj("models/pawn.obj"); // Generate the stars. for (int i = 0; i < 200; i++) { for (int j = 0; j < 200; j++) { for (int k = 0; k < 200; k++) { if ((i < 30 || i > 170) || (j < 30 || j > 170) || (k < 30 || k > 170)) { if (rand() % 1000 == 0) { std::vector<int> star = {i*10-1000, j*10-1000, k*10-1000}; stars.push_back(star); } } } } } } // Handles displaying a single frame of the game. void Game::display() { // Resets the camera position values. float cameraZ = cameraRadius * std::cos(cameraBeta) * std::sin(cameraAlpha); float cameraX = cameraRadius * std::cos(cameraBeta) * std::cos(cameraAlpha); float cameraY = cameraRadius * std::sin(cameraBeta); // Sets the camera position accordingly. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(cameraX, cameraY, cameraZ, 0, 0, 0, 0, 1, 0); // Define light positions. GLfloat light_position0[] = {0.0, 600.0, 0.0, 1.0}; GLfloat light_position1[] = {400.0, 100.0, 0.0, 1.0}; GLfloat light_position2[] = {-400.0, 100.0, 0.0, 1.0}; GLfloat light_position3[] = {0.0, 100.0, 400.0, 1.0}; GLfloat light_position4[] = {0.0, 100.0, -400.0, 1.0}; glutSolidSphere(300, 10, 10); // Sets light positions. glLightfv(GL_LIGHT0, GL_POSITION, light_position0); glLightfv(GL_LIGHT1, GL_POSITION, light_position1); glLightfv(GL_LIGHT2, GL_POSITION, light_position2); glLightfv(GL_LIGHT3, GL_POSITION, light_position3); glLightfv(GL_LIGHT4, GL_POSITION, light_position4); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draws the stars. glPushMatrix(); { glDisable(GL_LIGHTING); glColor3f(1, 1, 1); glBegin(GL_POINTS); { for (int i = 0; i < stars.size(); i++) { glVertex3f(stars.at(i).at(0), stars.at(i).at(1), stars.at(i).at(2)); } } glEnd(); glEnable(GL_LIGHTING); } glPopMatrix(); // Draws the game board. glPushMatrix(); { GLfloat mat_diffuse[] = {0.426, 0.258, 0.129, 1.0}; GLfloat mat_specular[] = {0.426, 0.258, 0.129, 1.0}; GLfloat mat_shininess[] = {50.0}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glCallList(boardObj); } glPopMatrix(); // For each tile on the board... for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Draws the white or black tile. glPushMatrix(); { if ((i+j)%2 == 0) { GLfloat mat_diffuse[] = {0.929, 0.929, 0.820, 1.0}; GLfloat mat_specular[] = {0.929, 0.929, 0.820, 1.0}; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); } else { GLfloat mat_diffuse[] = {0.090, 0.090, 0.090, 1.0}; GLfloat mat_specular[] = {0.090, 0.090, 0.090, 1.0}; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); } GLfloat mat_shininess[] = {1000.0}; glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glBegin(GL_TRIANGLE_STRIP); glNormal3f(0, 1, 0); glVertex3f(i*TILE_SIZE-299, 1, j*TILE_SIZE-299); glNormal3f(0, 1, 0); glVertex3f(i*TILE_SIZE-224, 1, j*TILE_SIZE-299); glNormal3f(0, 1, 0); glVertex3f(i*TILE_SIZE-299, 1, j*TILE_SIZE-224); glNormal3f(0, 1, 0); glVertex3f(i*TILE_SIZE-224, 1, j*TILE_SIZE-224); glEnd(); } glPopMatrix(); // Draws a game piece. char piece = board[i][j]; if (piece != ' ') { glPushMatrix(); { glTranslatef(i*75-263, 0, (7-j)*75-263); // White piece. if (piece < 96) { GLfloat mat_diffuse[] = {0.929, 0.929, 0.820, 1.0}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glRotatef(90, 0, 1, 0); if (selectionI == i && selectionJ == j) { GLfloat mat_diffuse[] = {0.500, 0.929, 0.820, 1.0}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); } } // Black piece. else { GLfloat mat_diffuse[] = {0.090, 0.090, 0.090, 1.0}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glRotatef(270, 0, 1, 0); if (selectionI == i && selectionJ == j) { GLfloat mat_diffuse[] = {0.590, 0.090, 0.090, 1.0}; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); } } GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat mat_shininess[] = {50.0}; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); // Draws the correct piece. if (piece == 'k' || piece == 'K') glCallList(kingObj); else if (piece == 'q' || piece == 'Q') glCallList(queenObj); else if (piece == 'b' || piece == 'B') glCallList(bishopObj); else if (piece == 'n' || piece == 'N') glCallList(knightObj); else if (piece == 'r' || piece == 'R') glCallList(rookObj); else if (piece == 'p' || piece == 'P') glCallList(pawnObj); } glPopMatrix(); } } } glDisable(GL_LIGHTING); // Draws the message to white player. glPushMatrix(); { glColor3f(1, 1, 1); int z = glutStrokeWidth(GLUT_STROKE_MONO_ROMAN, '?')*(msgWhite.size()/2); glTranslatef(-500, 150, z); glRotatef(90, 0, 1, 0); for (int i = 0; i < msgWhite.size(); i++) { glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, msgWhite[i]); } } glPopMatrix(); // Draws the message to black player. glPushMatrix(); { glColor3f(1, 1, 1); int z = glutStrokeWidth(GLUT_STROKE_MONO_ROMAN, '?')*(-msgBlack.size()/2); glTranslatef(500, 150, z); glRotatef(270, 0, 1, 0); for (int i = 0; i < msgBlack.size(); i++) { glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, msgBlack[i]); } } glPopMatrix(); glEnable(GL_LIGHTING); glutSwapBuffers(); } // Gets called when a player clicks on a new tile or piece. void Game::handleNewSelection(int i, int j) { char piece = board[i][j]; // Selecting own turn's piece. if (piece != ' ' && ((piece < 96 && turn == 'A') || (piece >= 96 && turn == 'a'))) { selectionI = i; selectionJ = j; } // Trying to move a selected piece. else if (selectionI >= 0 && selectionJ >= 0) { if (Rules::validMove(board, selectionI, selectionJ, i, j, turn)) { board[i][j] = board[selectionI][selectionJ]; board[selectionI][selectionJ] = ' '; selectionI = -1; selectionJ = -1; if (turn == 'A') { if (Rules::isCheckMate(board, 'a')) { msgWhite = MSG_WIN; msgBlack = MSG_LOSE; } else { turn = 'a'; msgWhite = ""; msgBlack = MSG_YOUR_TURN; } } else { if (Rules::isCheckMate(board, 'A')) { msgWhite = MSG_LOSE; msgBlack = MSG_WIN; } else { turn = 'A'; msgWhite = MSG_YOUR_TURN; msgBlack = ""; } } } else { if (Rules::isCheck(board, turn)) { if (turn == 'A') { msgWhite = MSG_CHECK; } else { msgBlack = MSG_CHECK; } } else { if (turn == 'A') { msgWhite = MSG_INVALID; } else { msgBlack = MSG_INVALID; } } glutTimerFunc(500, resetMessageTimer, 0); selectionI = -1; selectionJ = -1; } } } // Handles mouse click inputs. void Game::mouseInput(int button, int state, int x, int y) { // Scroll wheel down. if (button == 3) { cameraRadius -= 20; } // Scroll wheel up. else if (button == 4) { cameraRadius += 20; } // Left click down. Figures out which tile the mouse clicked and handles // potential game movemnets accordingly. else if (button == 0 && state == GLUT_DOWN) { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; // Get the current matrices. glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); // Convert display coordinates to model-view coordinates. winX = (float)x; winY = (float)viewport[3] - (float)y; glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); // Figure out which tile based on x and z values. int i = (posX + 4*TILE_SIZE) / TILE_SIZE; int j = 8 - ((posZ + 4*TILE_SIZE) / TILE_SIZE); // Inside of the board. if (i >= 0 && i < 8 && j >= 0 && j < 8) { handleNewSelection(i, j); } // Outside of the board. else { selectionI = -1; selectionJ = -1; } } // Right click down event. Changes the delta motion for rotations. else if (button == 2 && state == GLUT_DOWN) { mouseRightClick = true; motionLastX = x; motionLastY = y; glutTimerFunc(0, motionTimer, 0); } // Right click up event. else if (button == 2 && state == GLUT_UP) { mouseRightClick = false; } display(); } // Handles mouse movement changes. void Game::mouseMotion(int x, int y) { if (mouseRightClick) { cameraAlpha += (float) (x-motionLastX) / 100; cameraBeta += (float) (y-motionLastY) / 100; if (cameraBeta < MIN_CAMERA_BETA) cameraBeta = MIN_CAMERA_BETA; if (cameraBeta > MAX_CAMERA_BETA) cameraBeta = MAX_CAMERA_BETA; motionLastX = x; motionLastY = y; } } // GL timer function to handle right click movements. void Game::motionTimer(int value) { if (mouseRightClick) { display(); glutTimerFunc(10, motionTimer, 0); } } // GL timer function to reset a message. void Game::resetMessageTimer(int value) { if (turn == 'A') { msgWhite = MSG_YOUR_TURN; } else { msgBlack = MSG_YOUR_TURN; } display(); } // Handles window size changes. void Game::reshape(int newWidth, int newHeight) { double aspect = (double) newWidth / (double) newHeight; glViewport(0, 0, newWidth, newHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60, aspect, 1, 4000); }
31.554865
119
0.515583
[ "object", "vector", "model" ]
455836d4b0ba3ffb400ff38a3a917eb7d63431db
7,206
cpp
C++
sfml-porting/Shader.cpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
1
2020-02-11T05:37:54.000Z
2020-02-11T05:37:54.000Z
sfml-porting/Shader.cpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
null
null
null
sfml-porting/Shader.cpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
1
2022-03-01T00:47:19.000Z
2022-03-01T00:47:19.000Z
/** * @file Shader.cpp * @brief Shader class implementation. * @author zer0 * @date 2019-02-19 */ #include <libtbag/gui/Shader.hpp> #include <libtbag/gui/Texture.hpp> #include <libtbag/log/Log.hpp> #include <libtbag/Type.hpp> #if defined(USE_GUI) #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> STATIC_ASSERT_INTEGER_EQUAL(sf::Shader::Vertex, libtbag::gui::Shader::Type::T_VERTEX); STATIC_ASSERT_INTEGER_EQUAL(sf::Shader::Geometry, libtbag::gui::Shader::Type::T_GEOMETRY); STATIC_ASSERT_INTEGER_EQUAL(sf::Shader::Fragment, libtbag::gui::Shader::Type::T_FRAGMENT); #else #include <libtbag/dummy/Sfml.hpp> using namespace libtbag::dummy; #endif #include <cassert> #include <algorithm> #include <utility> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace gui { #ifndef _self_sf #define _self_sf() Pointer::cast<sf::Shader>() #endif Shader::Shader() : SfNative(SfType::ST_SHADER) { // EMPTY. } Shader::Shader(void * handle, no_init_no_ref_t) : SfNative(SfType::ST_SHADER, no_init_no_ref) { assert(ptr == nullptr); ptr = handle; assert(ptr != nullptr); } Shader::Shader(Shader && obj) TBAG_NOEXCEPT : SfNative(SfType::ST_SHADER, no_init) { *this = std::move(obj); } Shader::~Shader() { // EMPTY. } Shader & Shader::operator =(Shader && obj) TBAG_NOEXCEPT { swap(obj); return *this; } void Shader::swap(Shader & obj) TBAG_NOEXCEPT { if (this != &obj) { SfNative::swap(obj); } } bool Shader::loadFromFile(std::string const & filename, Type type) { return _self_sf()->loadFromFile(filename, (sf::Shader::Type)type); } bool Shader::loadFromFile(std::string const & vertex, std::string const & fragment) { return _self_sf()->loadFromFile(vertex, fragment); } bool Shader::loadFromFile(std::string const & vertex, std::string const & geometry, std::string const & fragment) { return _self_sf()->loadFromFile(vertex, geometry, fragment); } bool Shader::loadFromMemory(std::string const & shader, Type type) { return _self_sf()->loadFromMemory(shader, (sf::Shader::Type)type); } bool Shader::loadFromMemory(std::string const & vertex, std::string const & fragment) { return _self_sf()->loadFromMemory(vertex, fragment); } bool Shader::loadFromMemory(std::string const & vertex, std::string const & geometry, std::string const & fragment) { return _self_sf()->loadFromMemory(vertex, geometry, fragment); } void Shader::setUniform(std::string const & name, float x) { _self_sf()->setUniform(name, x); } void Shader::setUniform(std::string const & name, Vec2 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Vec2(vector.x, vector.y)); } void Shader::setUniform(std::string const & name, Vec3 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Vec3(vector.x, vector.y, vector.z)); } void Shader::setUniform(std::string const & name, Vec4 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Vec4(vector.x, vector.y, vector.z, vector.w)); } void Shader::setUniform(std::string const & name, int x) { _self_sf()->setUniform(name, x); } void Shader::setUniform(std::string const & name, Ivec2 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Ivec2(vector.x, vector.y)); } void Shader::setUniform(std::string const & name, Ivec3 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Ivec3(vector.x, vector.y, vector.z)); } void Shader::setUniform(std::string const & name, Ivec4 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Ivec4(vector.x, vector.y, vector.z, vector.w)); } void Shader::setUniform(std::string const & name, bool x) { _self_sf()->setUniform(name, x); } void Shader::setUniform(std::string const & name, Bvec2 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Bvec2(vector.x, vector.y)); } void Shader::setUniform(std::string const & name, Bvec3 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Bvec3(vector.x, vector.y, vector.z)); } void Shader::setUniform(std::string const & name, Bvec4 const & vector) { _self_sf()->setUniform(name, sf::Glsl::Bvec4(vector.x, vector.y, vector.z, vector.w)); } void Shader::setUniform(std::string const & name, Mat3 const & matrix) { _self_sf()->setUniform(name, sf::Glsl::Mat3(matrix.array)); } void Shader::setUniform(std::string const & name, Mat4 const & matrix) { _self_sf()->setUniform(name, sf::Glsl::Mat4(matrix.array)); } void Shader::setUniform(std::string const & name, Texture const & texture) { _self_sf()->setUniform(name, *texture.cast<sf::Texture>()); } void Shader::setUniform(std::string const & name, current_texture_t) { _self_sf()->setUniform(name, sf::Shader::CurrentTextureType{}); } void Shader::setUniformArray(std::string const & name, float const * scalar_arr, std::size_t length) { _self_sf()->setUniformArray(name, scalar_arr, length); } void Shader::setUniformArray(std::string const & name, Vec2 const * vector_arr, std::size_t length) { auto vector = std::make_unique<sf::Glsl::Vec2[]>(length); for (std::size_t i = 0; i < length; ++i) { vector[i].x = vector_arr[i].x; vector[i].y = vector_arr[i].y; } _self_sf()->setUniformArray(name, vector.get(), length); } void Shader::setUniformArray(std::string const & name, Vec3 const * vector_arr, std::size_t length) { auto vector = std::make_unique<sf::Glsl::Vec3[]>(length); for (std::size_t i = 0; i < length; ++i) { vector[i].x = vector_arr[i].x; vector[i].y = vector_arr[i].y; vector[i].z = vector_arr[i].z; } _self_sf()->setUniformArray(name, vector.get(), length); } void Shader::setUniformArray(std::string const & name, Vec4 const * vector_arr, std::size_t length) { auto vector = std::make_unique<sf::Glsl::Vec4[]>(length); for (std::size_t i = 0; i < length; ++i) { vector[i].x = vector_arr[i].x; vector[i].y = vector_arr[i].y; vector[i].z = vector_arr[i].z; vector[i].w = vector_arr[i].w; } _self_sf()->setUniformArray(name, vector.get(), length); } void Shader::setUniformArray(std::string const & name, Mat3 const * matrix_arr, std::size_t length) { std::vector<sf::Glsl::Mat3> matrix; matrix.reserve(length); for (std::size_t i = 0; i < length; ++i) { matrix.emplace_back(matrix_arr[i].array); } _self_sf()->setUniformArray(name, &(matrix[0]), length); } void Shader::setUniformArray(std::string const & name, Mat4 const * matrix_arr, std::size_t length) { std::vector<sf::Glsl::Mat4> matrix; matrix.reserve(length); for (std::size_t i = 0; i < length; ++i) { matrix.emplace_back(matrix_arr[i].array); } _self_sf()->setUniformArray(name, &(matrix[0]), length); } unsigned int Shader::getNativeHandle() const { return _self_sf()->getNativeHandle(); } void Shader::bind(Shader const & shader) { return sf::Shader::bind(shader.cast<sf::Shader>()); } bool Shader::isAvailable() { return sf::Shader::isAvailable(); } bool Shader::isGeometryAvailable() { return sf::Shader::isGeometryAvailable(); } } // namespace gui // -------------------- NAMESPACE_LIBTBAG_CLOSE // --------------------
26.788104
115
0.665556
[ "geometry", "vector" ]
45598f03b55d0c8898089b3f24f1cd42039e648e
11,449
cpp
C++
CGALWrapper/Utility/CGALGlobal_EIK_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
CGALWrapper/Utility/CGALGlobal_EIK_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
CGALWrapper/Utility/CGALGlobal_EIK_EEK.cpp
unitycoder/CGALDotNet
90682724a55aec2818847500047d4785aa7e1d67
[ "MIT" ]
null
null
null
#include "../pch.h" #include "CGALGlobal_EIK_EEK.h" #include "CGALGlobal.h" #include "../Geometry/Geometry2.h" #include "../Geometry/Geometry3.h" //---------------------------------------------------------------------------// // Angle // //---------------------------------------------------------------------------// CGAL::Angle CGALGlobal_EIK_Angle_Vector2d(Vector2d u, Vector2d v) { return CGALGlobal<EIK>::Angle_Vector2(u, v); } CGAL::Angle CGALGlobal_EIK_Angle_Vector2(void* u, void* v) { return CGALGlobal<EIK>::Angle_EIK_Vector2(u, v); } CGAL::Angle CGALGlobal_EEK_Angle_Vector2(void* u, void* v) { return CGALGlobal<EEK>::Angle_EEK_Vector2(u, v); } CGAL::Angle CGALGlobal_EIK_Angle_Vector3d(Vector3d u, Vector3d v) { return CGALGlobal<EIK>::Angle_Vector3(u, v); } //---------------------------------------------------------------------------// // ApproxAngle // //---------------------------------------------------------------------------// double CGALGlobal_EIK_ApproxAngle_Vector3d(Vector3d u, Vector3d v) { return CGALGlobal<EIK>::ApproxAngle_Vector3d(u, v); } //---------------------------------------------------------------------------// // ApproxDihedralAngle // //---------------------------------------------------------------------------// double CGALGlobal_EIK_ApproxDihedralAngle_Point3(Point3d p, Point3d q, Point3d r, Point3d s) { return CGALGlobal<EIK>::ApproxDihedralAngle(p, q, r, s); } //---------------------------------------------------------------------------// // AreOrderedAlongLine // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_AreOrderedAlongLine_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::AreOrderedAlongLine_Point2d(p, q, r); } BOOL CGALGlobal_EIK_AreOrderedAlongLine_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::AreOrderedAlongLine_EIK_Point2(p, q, r); } BOOL CGALGlobal_EEK_AreOrderedAlongLine_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::AreOrderedAlongLine_EEK_Point2(p, q, r); } BOOL CGALGlobal_EIK_AreOrderedAlongLine_Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::AreOrderedAlongLine_Point3d(p, q, r); } //---------------------------------------------------------------------------// // AreStrictlyOrderedAlongLine // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_AreStrictlyOrderedAlongLine_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::AreStrictlyOrderedAlongLine_Point2d(p, q, r); } BOOL CGALGlobal_EIK_AreStrictlyOrderedAlongLine_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::AreStrictlyOrderedAlongLine_EIK_Point2(p, q, r); } BOOL CGALGlobal_EEK_AreStrictlyOrderedAlongLine_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::AreStrictlyOrderedAlongLine_EEK_Point2(p, q, r); } BOOL CGALGlobal_EIK_AreStrictlyOrderedAlongLine_Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::AreStrictlyOrderedAlongLine_Point3d(p, q, r); } //---------------------------------------------------------------------------// // Collinear // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_Collinear_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::Collinear_Point2d(p, q, r); } BOOL CGALGlobal_EIK_Collinear_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::Collinear_EIK_Point2(p, q, r); } BOOL CGALGlobal_EEK_Collinear_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::Collinear_EEK_Point2(p, q, r); } BOOL CGALGlobal_EIK_Collinear_Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::Collinear_Point3d(p, q, r); } //---------------------------------------------------------------------------// // Barycenter // //---------------------------------------------------------------------------// Point2d CGALGlobal_EIK_Barycenter_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::Barycenter_Point2d(p, q, r); } void* CGALGlobal_EIK_Barycenter_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::Barycenter_EIK_Point2(p, q, r); } void* CGALGlobal_EEK_Barycenter_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::Barycenter_EEK_Point2(p, q, r); } Point3d CGALGlobal_EIK_Barycenter_Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::Barycenter_Point3d(p, q, r); } //---------------------------------------------------------------------------// // Bisector // //---------------------------------------------------------------------------// Line2d CGALGlobal_EIK_Bisector_Point3d(Point3d p, Point3d q) { return CGALGlobal<EIK>::Bisector_Point3d(p, q); } Line2d CGALGlobal_EIK_Bisector_Line2d(Line2d p, Line2d q) { return CGALGlobal<EIK>::Bisector_Line2d(p, q); } void* CGALGlobal_EIK_Bisector_Line2(void* p, void* q) { return CGALGlobal<EIK>::Bisector_EIK_Line2(p, q); } void* CGALGlobal_EEK_Bisector_Line2(void* p, void* q) { return CGALGlobal<EEK>::Bisector_EEK_Line2(p, q); } //---------------------------------------------------------------------------// // Coplanar // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_Coplanar_Point3d(Point3d p, Point3d q, Point3d r, Point3d s) { return CGALGlobal<EIK>::Coplanar_Point3d(p, q, r, s); } //---------------------------------------------------------------------------// // CoplanarOrientation // //---------------------------------------------------------------------------// CGAL::Orientation CGALGlobal_EIK_CoplanarOrientation_3Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::CoplanarOrientation_Point3d(p, q, r); } CGAL::Orientation CGALGlobal_EIK_CoplanarOrientation_4Point3d(Point3d p, Point3d q, Point3d r, Point3d s) { return CGALGlobal<EIK>::CoplanarOrientation_Point3d(p, q, r, s); } //---------------------------------------------------------------------------// // EquidistantLine // //---------------------------------------------------------------------------// Line3d CGALGlobal_EIK_EquidistantLine_Line3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::EquidistantLine_Point3d(p, q, r); } //---------------------------------------------------------------------------// // LeftTurn // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_LeftTurn_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::LeftTurn_Point2d(p, q, r); } BOOL CGALGlobal_EIK_LeftTurn_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::LeftTurn_EIK_Point2(p, q, r); } BOOL CGALGlobal_EEK_LeftTurn_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::LeftTurn_EEK_Point2(p, q, r); } //---------------------------------------------------------------------------// // RightTurn // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_RightTurn_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::RightTurn_Point2d(p, q, r); } BOOL CGALGlobal_EIK_RightTurn_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::RightTurn_EIK_Point2(p, q, r); } BOOL CGALGlobal_EEK_RightTurn_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::RightTurn_EEK_Point2(p, q, r); } //---------------------------------------------------------------------------// // Orientation // //---------------------------------------------------------------------------// CGAL::Orientation CGALGlobal_EIK_Orientation_Point2d(Point2d p, Point2d q, Point2d r) { return CGALGlobal<EIK>::Orientation_Point2d(p, q, r); } CGAL::Orientation CGALGlobal_EIK_Orientation_Point2(void* p, void* q, void* r) { return CGALGlobal<EIK>::Orientation_EIK_Point2(p, q, r); } CGAL::Orientation CGALGlobal_EEK_Orientation_Point2(void* p, void* q, void* r) { return CGALGlobal<EEK>::Orientation_EEK_Point2(p, q, r); } CGAL::Orientation CGALGlobal_EIK_Orientation_Vector2d(Vector2d u, Vector2d v) { return CGALGlobal<EIK>::Orientation_Vector2d(u, v); } CGAL::Orientation CGALGlobal_EIK_Orientation_Vector2(void* p, void* q) { return CGALGlobal<EIK>::Orientation_EIK_Vector2(p, q); } CGAL::Orientation CGALGlobal_EEK_Orientation_Vector2(void* p, void* q) { return CGALGlobal<EEK>::Orientation_EEK_Vector2(p, q); } CGAL::Orientation CGALGlobal_EIK_Orientation_Point3d(Point3d p, Point3d q, Point3d r, Point3d s) { return CGALGlobal<EIK>::Orientation_Point3d(p, q, r, s); } CGAL::Orientation CGALGlobal_EIK_Orientation_Vector3d(Vector3d u, Vector3d v, Vector3d w) { return CGALGlobal<EIK>::Orientation_Vector3d(u, v, w); } //---------------------------------------------------------------------------// // OrthogonalVector // //---------------------------------------------------------------------------// Vector3d CGALGlobal_EIK_OrthogonalVector_Point3d(Point3d p, Point3d q, Point3d r) { return CGALGlobal<EIK>::OrthogonalVector_Point3d(p, q, r); } void* CGALGlobal_EIK_OrthogonalVector_Point3(void* p, void* q, void* r) { return CGALGlobal<EIK>::OrthogonalVector_EIK_Point3(p, q, r); } void* CGALGlobal_EEK_OrthogonalVector_Point3(void* p, void* q, void* r) { return CGALGlobal<EEK>::OrthogonalVector_EEK_Point3(p, q, r); } //---------------------------------------------------------------------------// // Parallel // //---------------------------------------------------------------------------// BOOL CGALGlobal_EIK_Parallel_Line2d(Line2d l1, Line2d l2) { return CGALGlobal<EIK>::Parallel_Line2d(l1, l2); } BOOL CGALGlobal_EIK_Parallel_Line2(void* l1, void* l2) { return CGALGlobal<EIK>::Parallel_EIK_Line2d(l1, l2); } BOOL CGALGlobal_EEK_Parallel_Line2(void* l1, void* l2) { return CGALGlobal<EEK>::Parallel_EEK_Line2d(l1, l2); } BOOL CGALGlobal_EIK_Parallel_Ray2d(Ray2d r1, Ray2d r2) { return CGALGlobal<EIK>::Parallel_Ray2d(r1, r2); } BOOL CGALGlobal_EIK_Parallel_Ray2(void* r1, void* r2) { return CGALGlobal<EIK>::Parallel_EIK_Ray2d(r1, r2); } BOOL CGALGlobal_EEK_Parallel_Ray2(void* r1, void* r2) { return CGALGlobal<EEK>::Parallel_EEK_Ray2d(r1, r2); } BOOL CGALGlobal_EIK_Parallel_Segment2d(Segment2d s1, Segment2d s2) { return CGALGlobal<EIK>::Parallel_Segment2d(s1, s2); } BOOL CGALGlobal_EIK_Parallel_Segment2(void* s1, void* s2) { return CGALGlobal<EIK>::Parallel_EIK_Segment2d(s1, s2); } BOOL CGALGlobal_EEK_Parallel_Segment2(void* s1, void* s2) { return CGALGlobal<EEK>::Parallel_EEK_Segment2d(s1, s2); }
32.341808
105
0.528343
[ "geometry" ]
4570aa858117c61edf39b91eaa5e7863f8d3d474
1,244
hpp
C++
triangler/mesh.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
2
2020-01-14T11:22:23.000Z
2022-02-24T13:13:47.000Z
triangler/mesh.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
null
null
null
triangler/mesh.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include <vector> #include <string> #define PI 3.1415927f struct Mesh { // Index std::vector<int> t; // Vertices std::vector<glm::vec3> v; // Normals std::vector<glm::vec3> n; // Colors std::vector<glm::vec4> c; // Texture coordinates std::vector <glm::vec2> tx; // Mid point glm::vec3 mid = { 0, 0 , 0 }; float radius; void AddVert(glm::vec3 vert) { v.emplace_back(vert); } void AddColor(glm::vec4 vert) { c.emplace_back(vert); } void AddTri(int a, int b, int c) { t.emplace_back(a); t.emplace_back(b); t.emplace_back(c); } void Clear() { v.clear(); t.clear(); } void Normalize() { for (auto& vert : v) vert = glm::normalize(vert); } }; void genNormals(Mesh& mesh); void genRandomColors(Mesh& mesh); Mesh genIcosahedron(); Mesh genIcosphere(const int subdivisions); Mesh genRing(const int points, const glm::vec4 color); Mesh genGrid(const float dim, const int segments, const int subgrids, const glm::vec4 color); Mesh genVector(const glm::vec3 start, const glm::vec3 end, const glm::vec4 color); Mesh LoadOBJ(const std::string path, const glm::vec3 offsaet = glm::vec3(0)); Mesh LoadOBJFast(const std::string path, const std::string filename);
18.028986
93
0.67283
[ "mesh", "vector" ]
4575c1fb689389231e7fa9992005e5eb4d800973
332
cpp
C++
practicas/2122/practicaI/solucion/ejercicio1.cpp
Nebrija-Programacion/Programacion-I
15a3d02f3c78969b5da6c9aceb64eae0a0bf8ca8
[ "MIT" ]
19
2019-09-08T06:46:30.000Z
2022-03-19T02:28:14.000Z
practicas/2122/practicaI/solucion/ejercicio1.cpp
Nebrija-Programacion/Programacion-I
15a3d02f3c78969b5da6c9aceb64eae0a0bf8ca8
[ "MIT" ]
65
2018-09-10T11:46:18.000Z
2018-11-12T10:12:51.000Z
practicas/2122/practicaI/solucion/ejercicio1.cpp
Nebrija-Programacion-I-II/Programacion-I
73bf34d6268b26ca3068c23a8d5d70579ebca25e
[ "MIT" ]
93
2018-09-10T11:35:46.000Z
2019-01-11T14:07:25.000Z
#include <iostream> #include <string> int main(){ std::sring cad; std::cout << "Introduce una cadena de texto: "; std::getline(std::cin, cad); int cont{0}; for(int i; i < cad.size(); i++){ if(cad.at(i) == 'a') cont++; } std::cout << "La letra a aparece " << cont << " veces\n"; return 0; }
20.75
61
0.521084
[ "cad" ]
457852a23fe53dc94731361f6916bed247af6ce9
2,596
cpp
C++
src/customwidgets/qgsdatetimeeditplugin.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/customwidgets/qgsdatetimeeditplugin.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/customwidgets/qgsdatetimeeditplugin.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsdatetimeeditplugin.cpp -------------------------------------- Date : 01.09.2014 Copyright : (C) 2014 Denis Rouzaud Email : denis.rouzaud@gmail.com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgiscustomwidgets.h" #include "qgsdatetimeeditplugin.h" #include "qgsdatetimeedit.h" QgsDateTimeEditPlugin::QgsDateTimeEditPlugin( QObject *parent ) : QObject( parent ) , mInitialized( false ) { } QString QgsDateTimeEditPlugin::name() const { return "QgsDateTimeEdit"; } QString QgsDateTimeEditPlugin::group() const { return QgisCustomWidgets::groupName(); } QString QgsDateTimeEditPlugin::includeFile() const { return "qgsdatetimeedit.h"; } QIcon QgsDateTimeEditPlugin::icon() const { return QIcon( ":/images/icons/qgis-icon-60x60.png" ); } bool QgsDateTimeEditPlugin::isContainer() const { return false; } QWidget *QgsDateTimeEditPlugin::createWidget( QWidget *parent ) { return new QgsDateTimeEdit( parent ); } bool QgsDateTimeEditPlugin::isInitialized() const { return mInitialized; } void QgsDateTimeEditPlugin::initialize( QDesignerFormEditorInterface *core ) { Q_UNUSED( core ); if ( mInitialized ) return; mInitialized = true; } QString QgsDateTimeEditPlugin::toolTip() const { return tr( "Define date" ); } QString QgsDateTimeEditPlugin::whatsThis() const { return ""; } QString QgsDateTimeEditPlugin::domXml() const { return QString( "<ui language=\"c++\">\n" " <widget class=\"%1\" name=\"mDateTimeEdit\">\n" " <property name=\"geometry\">\n" " <rect>\n" " <x>0</x>\n" " <y>0</y>\n" " <width>90</width>\n" " <height>27</height>\n" " </rect>\n" " </property>\n" " </widget>\n" "</ui>\n" ) .arg( name() ); }
26.489796
76
0.505393
[ "geometry" ]
457bb30cdf9952a8896a52f87aa79485a97f2c7e
2,014
cc
C++
linux/r_crypto_plugin.cc
TinoGuo/r_crypto
c5e8640b1dfd683a6cd948c3830160ebc1c9d9aa
[ "MIT" ]
22
2020-11-19T05:35:08.000Z
2022-03-20T14:46:06.000Z
linux/r_crypto_plugin.cc
TinoGuo/r_crypto
c5e8640b1dfd683a6cd948c3830160ebc1c9d9aa
[ "MIT" ]
6
2020-11-30T02:15:41.000Z
2021-10-17T14:00:25.000Z
linux/r_crypto_plugin.cc
TinoGuo/r_crypto
c5e8640b1dfd683a6cd948c3830160ebc1c9d9aa
[ "MIT" ]
1
2021-09-19T13:43:43.000Z
2021-09-19T13:43:43.000Z
#include "include/r_crypto/r_crypto_plugin.h" #include <flutter_linux/flutter_linux.h> #include <gtk/gtk.h> #include <sys/utsname.h> #include <cstring> #define R_CRYPTO_PLUGIN(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), r_crypto_plugin_get_type(), \ RCryptoPlugin)) struct _RCryptoPlugin { GObject parent_instance; }; G_DEFINE_TYPE(RCryptoPlugin, r_crypto_plugin, g_object_get_type()) // Called when a method call is received from Flutter. static void r_crypto_plugin_handle_method_call( RCryptoPlugin* self, FlMethodCall* method_call) { g_autoptr(FlMethodResponse) response = nullptr; response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); fl_method_call_respond(method_call, response, nullptr); } static void r_crypto_plugin_dispose(GObject* object) { G_OBJECT_CLASS(r_crypto_plugin_parent_class)->dispose(object); } static void r_crypto_plugin_class_init(RCryptoPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = r_crypto_plugin_dispose; } static void r_crypto_plugin_init(RCryptoPlugin* self) {} static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { RCryptoPlugin* plugin = R_CRYPTO_PLUGIN(user_data); r_crypto_plugin_handle_method_call(plugin, method_call); } void r_crypto_plugin_register_with_registrar(FlPluginRegistrar* registrar) { RCryptoPlugin* plugin = R_CRYPTO_PLUGIN( g_object_new(r_crypto_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), "r_crypto", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), g_object_unref); g_object_unref(plugin); }
33.016393
79
0.728401
[ "object" ]
4580413f8be981231d805446bdb941342c31396a
865
cpp
C++
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_StreamOutputStage.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_StreamOutputStage.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_StreamOutputStage.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
#include "SR_PCH.h" #include "SR_StreamOutputStage.h" #include "SR_App.h" namespace SunrinEngine { SR_StreamOutputStage::SR_StreamOutputStage() noexcept : m_streamBufferCount { 0 }, m_streamBuffers { nullptr }, m_streamBufferOffsets { 0 } { } void SR_StreamOutputStage::Apply(bool isBindSB) { if (isBindSB) { SR_App::GetInstance()->GetGraphic().GetD3DDeferredContext(GetThreadID())->SOSetTargets( m_streamBufferCount, m_streamBuffers, m_streamBufferOffsets); } } void SR_StreamOutputStage::SetStreamBuffers(unsigned count, const std::vector<ID3D11Buffer*> & streamBuffers, const std::vector<unsigned> & streamBufferOffsets) { m_streamBufferCount = count; for (unsigned i{ 0 }; i < m_streamBufferCount; ++i) { m_streamBuffers[i] = streamBuffers[i]; m_streamBufferOffsets[i] = streamBufferOffsets[i]; } } }
22.179487
161
0.727168
[ "vector" ]
45833a4f323b814990c89f0f983797064fa94a56
549
cpp
C++
codes/TC_2020/FALL/1.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
codes/TC_2020/FALL/1.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
codes/TC_2020/FALL/1.cpp
pikaninja/collection-of-chessbot-codes
a56e5e4e38c293ecddd2ce4b0b922723ca833089
[ "MIT" ]
null
null
null
//daniel //#include <iostream> //#include <vector> //#include <queue> //#include <stack> //#include <set> //#include <algorithm> //#include <cstring> // //using namespace std; // //int main(){ // int n, m; cin >> n >> m; // int arr[n][m]; // for(int i = 0; i < n; i++){ // for(int j = 0; j < m; j++){ // cin >> arr[i][j]; // } // } // // for(int i = 0; i < m; i++){ // for(int j = 0; j < n; j++){ // cout << arr[j][i] << " "; // } // cout << endl; // } // return 0; //}
18.3
39
0.393443
[ "vector" ]
4586c38aef3d330583179647466f28cb3dbb29f2
24,878
hpp
C++
worker/ReaderWriter.hpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
7
2021-06-19T08:32:49.000Z
2022-03-31T15:46:48.000Z
worker/ReaderWriter.hpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
null
null
null
worker/ReaderWriter.hpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
2
2021-06-19T08:32:50.000Z
2022-01-04T12:11:32.000Z
/** * CoRM: Compactable Remote Memory over RDMA * * The function for reading and writing objects to the memory. * * Copyright (c) 2020-2021 ETH-Zurich. All rights reserved. * * Author(s): Konstantin Taranov <konstantin.taranov@inf.ethz.ch> * */ #pragma once #include <stdio.h> #include <string.h> #include "../common/common.hpp" #include <algorithm> typedef void (*read_cb)(uint16_t size, addr_t newaddr,uint8_t version, void *owner); typedef void (*write_cb)( addr_t newaddr, uint8_t success, uint8_t version, void *owner); static const int OBJECT_IS_INCONSISTENT = -4; static const int NOT_FOUND = -3; static const int UNDER_COMPACTION = -2; static const int LOCK_FAILED = -1; class ReaderWriter{ public: /*The call copies data to reply_buffer from slot at address pointer*/ static void ReadObjectToBuf(char* reply_buffer, addr_t pointer, uint16_t obj_id, uint16_t slot_size, read_cb cb , void* owner ); // ReadObjectToBuf internally calls read_object_to_buffer, which is lock-free. // read_object_to_buffer knows how to read object splitted with cacheline versions static int read_object_to_buffer(uint64_t to, uint64_t from, uint16_t obj_id, uint16_t slot_size, uint16_t *return_size, uint8_t *version ); // read_object_to_buffer_lim is similar to read_object_to_buffer, but also takes into acccount that destination buffer can be small static int client_read_object_to_buffer_lim(uint64_t to, uint64_t from, uint64_t actual_remote_address, uint16_t slot_size, uint16_t obj_id, uint32_t *lim_size ); // as above but no objid check static int client_read_object_farm(uint64_t to, uint64_t from, uint64_t actual_remote_address, uint16_t slot_size, uint32_t *lim_size ); static int client_read_fast(uint64_t to, uint64_t from,uint16_t slot_size, uint32_t *lim_size ); // WriteBufToObject will write data to slot. It will try to lock object first and then write static void WriteBufToObject(addr_t pointer, uint16_t obj_id, uint16_t slot_size, void *buf, uint32_t size, write_cb cb , void* owner ); // WriteBufToObjectAtomic is similar to previous one, but it will also check the expected version before locking. static void WriteBufToObjectAtomic(addr_t pointer, uint16_t obj_id, uint16_t slot_size, uint8_t version, void *buf, uint32_t size, write_cb cb , void* owner ); static void write_locally(addr_t localbuf, uint8_t new_version, uint16_t slot_size, void* buf, uint32_t bufsize); // the call fixes object addresses static void FixSlots(addr_t old_client_addr, addr_t newaddr, uint16_t slot_size); static addr_t FixOneSlot(addr_t addr,uint16_t obj_id, addr_t new_base_addr); static bool HasOldBaseSlot(addr_t old_base_addr, addr_t new_base_addr,uint16_t slot_size); // different calls for locking and unlocking objects static int try_lock_slot_and_increment_version(addr_t localbuf, uint16_t obj_id); static int try_lock_slot_and_increment_version_if_version(addr_t localbuf, uint16_t obj_id, uint8_t version); static bool try_lock_slot_for_compaction(addr_t localbuf); static void unlock_slot(addr_t localbuf); static bool unlock_slot_from_compaction(addr_t localbuf); // write block header for new blocks static void WriteBlockHeader(addr_t addr, uint8_t type, uint32_t rkey); // scan memory block to find an object with object_id. it is linear static addr_t ScanMemory(addr_t addr, uint16_t slot_size, uint16_t object_id ); // set object version for new objects. static bool SetNewObject(addr_t addr, uint16_t object_id, uint8_t *version); // clear object header at address static addr_t FreeSlot(addr_t addr); }; void ReaderWriter::WriteBlockHeader(addr_t addr, uint8_t type, uint32_t rkey) { memset((char*)addr,0,BLOCK_SIZE); block_header_t* h = (block_header_t*)(addr + BLOCK_USEFUL_SIZE); h->comp.rkey = rkey; h->comp.type = type; h->comp.base = addr; //(addr >> BLOCK_BIT_SIZE); } // TODO. is not safe, if user is freeing an ibject in use. addr_t ReaderWriter::FreeSlot(addr_t addr){ text(log_fp, "\t\t[ReaderWriter] zero slot at %" PRIx64 "\n",addr); std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)addr; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.lock){ return 0; } addr_t old_base = header_copy.oldbase; slot_header_t deallocated_header_copy = header_copy; deallocated_header_copy.allocated = 0; deallocated_header_copy.obj_id = 0; deallocated_header_copy.oldbase = 0; bool suc = head->compare_exchange_strong(header_copy,deallocated_header_copy); if(suc) return (old_base << BLOCK_BIT_SIZE); else return 0; } bool ReaderWriter::SetNewObject(addr_t addr, uint16_t object_id, uint8_t *version){ text(log_fp, "\t\t[ReaderWriter] SetNewObject at %" PRIx64 "\n",addr); std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)addr; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.lock){ return false; } slot_header_t allocated_header_copy = header_copy; allocated_header_copy.allocated = 1; allocated_header_copy.obj_id = object_id; allocated_header_copy.oldbase = (addr >> BLOCK_BIT_SIZE); *version = allocated_header_copy.version; return head->compare_exchange_strong(header_copy,allocated_header_copy); } void ReaderWriter::write_locally(addr_t localbuf, uint8_t new_version, uint16_t slot_size, void* buf, uint32_t bufsize){ text(log_fp, "\t\t[ReaderWriter] object at 0x%" PRIx64 " \n", localbuf); uint64_t next_cache_line = (localbuf & CACHELINE_MASK) + CACHELINE; // text(log_fp, "\t\t[ReaderWriter] next cache line at 0x%" PRIx64 " \n", next_cache_line); uint64_t src = (uint64_t)buf; uint64_t dst = localbuf + sizeof(slot_header_t); text(log_fp, "\t\t[ReaderWriter] data at 0x%" PRIx64 " \n", dst); uint64_t tocopy = bufsize; assert(next_cache_line >= dst && "cacheline overlapped header! "); uint64_t copy_size = std::min(next_cache_line-dst, tocopy); text(log_fp, "\t\t[ReaderWriter] can copy before first cacheversion %" PRIu64 " \n", copy_size); memcpy((char*)dst, (char*)src, copy_size); src += copy_size; dst += copy_size; tocopy -= copy_size; while(tocopy > 0){ text(log_fp, "\t\t[ReaderWriter] write version to cache at 0x%" PRIx64 " \n", dst); *(uint8_t*)dst = new_version; dst++; copy_size = std::min(CACHELINE -1, tocopy); text(log_fp, "\t\t[ReaderWriter] can copy before next cacheversion %" PRIu64 " \n", copy_size); memcpy((char*)dst, (char*)src, copy_size); src += copy_size; dst += copy_size; tocopy -= copy_size; } assert(dst <= localbuf+slot_size && "Overflow write"); // jump to next cacheline dst = (dst + CACHELINE -1) & CACHELINE_MASK; text(log_fp, "\t\t[ReaderWriter] jumped to %" PRIx64 " \n", dst); // while( dst < localbuf+slot_size ){ text(log_fp, "\t\t[ReaderWriter] write cache version to %" PRIx64 " \n", dst); *(uint8_t*)dst = new_version; dst+=CACHELINE; } text(log_fp, "\t\t[ReaderWriter] write_locally finished \n"); } void ReaderWriter::ReadObjectToBuf(char* reply_buffer, addr_t newaddr, uint16_t obj_id, uint16_t slot_size, read_cb cb , void* owner ){ text(log_fp, "\t\t[ReaderWriter] Read Object To Buffer from %" PRIx64 "\n ", newaddr ); uint16_t size = 0; uint8_t version = 0; uint8_t try_count = 0; int ret = read_object_to_buffer((uint64_t)reply_buffer, newaddr, obj_id, slot_size, &size,&version); while(ret < 0){ try_count++; text(log_fp, "\t\t[ReaderWriter] retry read %u \n",try_count ); if(ret==NOT_FOUND || ret == UNDER_COMPACTION){ // object is invalid. need to find address again info(log_fp, "\t\t[ReadObjectToBuf] failed to read since compaction\n" ); cb(0, 0, 0, owner ); return; } if(try_count > 4 ){ // lock failed info(log_fp, "\t\t[ReadObjectToBuf] failed to read \n" ); cb(0, newaddr, 0, owner ); return; } ret = read_object_to_buffer((uint64_t)reply_buffer, newaddr, obj_id, slot_size, &size,&version); } text(log_fp, "\t\t[ReaderWriter] We read %" PRIu64 "\n", (*reinterpret_cast<uint64_t*>(reply_buffer)) ); text(log_fp, "\t\t[ReaderWriter] read from %p \n", reply_buffer); cb(size, newaddr, version, owner ); return ; } void ReaderWriter::WriteBufToObjectAtomic(addr_t newaddr, uint16_t obj_id, uint16_t slot_size, uint8_t version, void *buf, uint32_t size, write_cb cb , void* owner ){ text(log_fp, "\t\t[ReaderWriter] Write Object From Buffer to %" PRIx64 "\n", newaddr ); uint8_t try_count = 0; int ret = try_lock_slot_and_increment_version_if_version(newaddr, obj_id, version); while(ret < 0){ try_count++; text(log_fp, "\t\t[WriteBufToObjectAtomic] retry lock %u \n",try_count ); if(ret==NOT_FOUND || ret == UNDER_COMPACTION){ // object is invalid. need to find address again cb( 0, 0, 0,owner ); return; } if(ret==OBJECT_IS_INCONSISTENT){ cb( newaddr, 2, 0, owner ); } if(try_count > 4 ){ // lock failed cb( newaddr, 0, 0, owner ); return; } ret = try_lock_slot_and_increment_version_if_version(newaddr, obj_id, version); } uint8_t newversion = (uint8_t)ret; write_locally(newaddr, newversion, slot_size, buf, size); unlock_slot(newaddr); text(log_fp, "\t\t[ReaderWriter] We wrote %" PRIu64 "\n", (*static_cast<uint64_t*>(buf)) ); cb(newaddr, 1 , newversion ,owner ); return; } void ReaderWriter::WriteBufToObject(addr_t newaddr, uint16_t obj_id, uint16_t slot_size, void *buf, uint32_t size, write_cb cb , void* owner ){ text(log_fp, "\t\t[ReaderWriter] Write Object From Buffer to %" PRIx64 "\n", newaddr ); uint8_t try_count = 0; int ret = try_lock_slot_and_increment_version(newaddr, obj_id); while(ret < 0){ try_count++; text(log_fp, "\t\t[WriteBufToObject] retry lock %u \n",try_count ); if(ret==NOT_FOUND || ret == UNDER_COMPACTION){ // object is invalid. need to find address again if (cb) cb( 0, 0, 0,owner ); info(log_fp, "\t\t[WriteBufToObject] failed because of compaction \n"); return; } if(try_count > 4 ){ // lock failed info(log_fp, "\t\t[WriteBufToObject] failed because of lock \n"); if (cb) cb( newaddr, 0, 0, owner ); return; } ret = try_lock_slot_and_increment_version(newaddr, obj_id); } uint8_t newversion = (uint8_t)ret; write_locally(newaddr, newversion, slot_size, buf, size); unlock_slot(newaddr); text(log_fp, "\t\t[ReaderWriter] We wrote %" PRIu64 "\n", (*static_cast<uint64_t*>(buf)) ); if(cb) cb(newaddr, 1 , newversion, owner ); return; } addr_t ReaderWriter::FixOneSlot(addr_t current_addr,uint16_t obj_id, addr_t new_base_addr){ text(log_fp, "\t\t[FixOneSlot] FixOneSlot at addr %" PRIx64 ". We set this base %" PRIx64 " \n",current_addr, new_base_addr ); uint64_t shifted_newaddr = (new_base_addr >> BLOCK_BIT_SIZE); bool exhanged = true; std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)current_addr; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.compaction || (header_copy.obj_id != obj_id)){ text(log_fp, "\t\t[FixOneSlot] fix address under compaction at %" PRIx64 " \n", current_addr); return 0; } if(header_copy.oldbase == shifted_newaddr){ // nothing to fix text(log_fp, "\t\t[FixOneSlot] address has been already fixed at %" PRIx64 " \n", current_addr); return 0; } addr_t oldbase = header_copy.oldbase; slot_header_t fixed_header_copy = header_copy; fixed_header_copy.oldbase = shifted_newaddr; exhanged = head->compare_exchange_strong(header_copy,fixed_header_copy); if(exhanged) return (oldbase << BLOCK_BIT_SIZE ) ; else return 0; } bool ReaderWriter::HasOldBaseSlot(addr_t old_base_addr, addr_t new_base_addr,uint16_t slot_size){ text(log_fp, "\t\t[ReaderWriter] FixOneSlot in block %" PRIx64 ". We remove this address %" PRIx64 " \n",new_base_addr, old_base_addr ); uint64_t shifted_oldaddr = (old_base_addr >> BLOCK_BIT_SIZE); uint32_t total_objects = (BLOCK_USEFUL_SIZE) / slot_size; addr_t current_addr = new_base_addr; for(uint32_t i=0; i < total_objects; i++ ){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)current_addr; slot_header_t header_copy = head->load(std::memory_order_relaxed); bool equal = (header_copy.oldbase == shifted_oldaddr) ; if(equal){ return true; } current_addr+=slot_size; } return false; } void ReaderWriter::FixSlots(addr_t oldaddr, addr_t newaddr,uint16_t slot_size){ uint64_t shifted_oldaddr = (oldaddr >> BLOCK_BIT_SIZE); uint64_t shifted_newaddr = (newaddr >> BLOCK_BIT_SIZE); uint32_t total_objects = (BLOCK_USEFUL_SIZE) / slot_size; addr_t current_addr = newaddr; for(uint32_t i=0; i < total_objects; i++ ){ bool equal = false; bool exhanged = true; do{ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)current_addr; slot_header_t header_copy = head->load(std::memory_order_relaxed); equal = (header_copy.oldbase == shifted_oldaddr); if(equal){ text(log_fp, "\t\t[ReaderWriter] Old base found for obj %u at %" PRIx64 " \n", i, current_addr); slot_header_t fixed_header_copy = header_copy; fixed_header_copy.oldbase = shifted_newaddr; exhanged = head->compare_exchange_strong(header_copy,fixed_header_copy); } } while( equal && !exhanged); current_addr+=slot_size; } } addr_t ReaderWriter::ScanMemory(addr_t addr, uint16_t slot_size, uint16_t object_id ){ text(log_fp,"\t\t[ScanMemory] Scan Block at %" PRIx64 " of slot size %" PRIu16 " for object %" PRIu16 " \n ", addr, slot_size,object_id ); uint32_t total_objects = (BLOCK_USEFUL_SIZE) / slot_size; addr_t current_addr = addr ; for(uint32_t i=0; i < total_objects; i++ ){ if( ((slot_header_t*)current_addr)->obj_id == object_id ){ text(log_fp,"\t\t[ScanMemory] Object found at %" PRIx64 " \n", current_addr); return current_addr; } current_addr+=slot_size; } text(log_fp,"\t\t[ScanMemory] Object has not been found block at %" PRIx64 " \n", addr); return 0; } int ReaderWriter::read_object_to_buffer(uint64_t to, uint64_t from, uint16_t obj_id, uint16_t slot_size, uint16_t *return_size, uint8_t *version ) { std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)from; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.obj_id != obj_id){ return NOT_FOUND; } if(header_copy.compaction){ return UNDER_COMPACTION; } if(header_copy.lock){ return LOCK_FAILED; } uint8_t current_version = header_copy.version; *version = current_version; text(log_fp, "\t\t[ReaderWriter] read current %" PRIx64 " \n", from); uint64_t next_cache_line = (from & CACHELINE_MASK) + CACHELINE; // text(log_fp, "\t\t[ReaderWriter] next_cache_line %" PRIx64 " \n", next_cache_line); uint64_t src = (uint64_t)from + sizeof(slot_header_t); uint64_t dst = (uint64_t)to; uint64_t size = slot_size - sizeof(slot_header_t) ; assert(next_cache_line >= src && "Alignment is not correct! "); uint64_t copy_size = std::min(next_cache_line-src, size); text(log_fp, "\t\t[ReaderWriter] can read copy %" PRIu64 " \n", copy_size); memcpy((char*)dst, (char*)src, copy_size); uint64_t total_size = copy_size; src += copy_size; dst += copy_size; size -= copy_size; // read over cachelines while(size > 0 ){ text(log_fp, "\t\t[ReaderWriter] read version from %" PRIx64 " \n", src); if(current_version != *(uint8_t*)src){ text(log_fp,"Error version, \n"); return false; } src++; size--; copy_size = std::min((uint64_t)CACHELINE - 1, size); // 1 - is cache line version size text(log_fp, "\t\t[ReaderWriter] can read copy %" PRIu64 " \n", copy_size); memcpy((char*)dst, (char*)src, copy_size); src += copy_size; dst += copy_size; size -= copy_size; total_size += copy_size; } assert(src == from+slot_size && "Did you copy all bytes?"); text(log_fp, "\t\t[ReaderWriter] read_locally finished \n"); *return_size = (uint16_t) total_size; return 0; } int ReaderWriter::client_read_object_to_buffer_lim(uint64_t to, uint64_t from, uint64_t actual_remote_address, uint16_t slot_size, uint16_t obj_id, uint32_t *lim_size ) { slot_header_t* h = (slot_header_t*)from; if(h->obj_id != obj_id){ return NOT_FOUND; } if(h->lock){ return LOCK_FAILED; } uint64_t actual_offset = actual_remote_address & mask_of_bits(BLOCK_BIT_SIZE); uint64_t upper_size = (*lim_size == 0) ? UINT64_MAX : *lim_size; uint8_t current_version = h->version; text(log_fp, "\t\t[ReaderWriter] read current %" PRIx64 " \n", from); uint64_t next_cache_line = ((actual_offset + CACHELINE) & CACHELINE_MASK) - actual_offset + from; // text(log_fp, "\t\t[ReaderWriter] next_cache_line %" PRIx64 " \n", next_cache_line); uint64_t src = (uint64_t)from + sizeof(slot_header_t); uint64_t dst = (uint64_t)to; uint64_t size = slot_size - sizeof(slot_header_t); assert(next_cache_line >= src && "Alignment is not correct! "); uint64_t hop_size = std::min(next_cache_line-src, size); uint64_t total_size = 0; uint64_t copy_size = std::min(hop_size, upper_size - total_size); memcpy((char*)dst, (char*)src, copy_size); total_size += copy_size; src += hop_size; dst += copy_size; size -= hop_size; while(size > 0 ){ text(log_fp, "\t\t[ReaderWriter] read version from %" PRIx64 " \n", src); if(current_version != *(uint8_t*)src){ text(log_fp,"Error version, \n"); return OBJECT_IS_INCONSISTENT; } src++; size--; hop_size = std::min((uint64_t)CACHELINE - 1, size); copy_size = std::min(hop_size, upper_size-total_size); memcpy((char*)dst, (char*)src, copy_size); total_size += copy_size; src += hop_size; dst += copy_size; size -= hop_size; } assert(src == from+slot_size && "Did you copy all bytes?"); text(log_fp, "\t\t[ReaderWriter] read_locally finished \n"); *lim_size = (uint32_t) total_size; return 0; } // for debugging int ReaderWriter::client_read_object_farm(uint64_t to, uint64_t from, uint64_t actual_remote_address, uint16_t slot_size, uint32_t *lim_size ) { slot_header_t* h = (slot_header_t*)from; if(h->lock){ return LOCK_FAILED; } uint64_t actual_offset = actual_remote_address & mask_of_bits(BLOCK_BIT_SIZE); uint64_t upper_size = (*lim_size == 0) ? UINT64_MAX : *lim_size; uint8_t current_version = h->version; text(log_fp, "\t\t[ReaderWriter] read current %" PRIx64 " \n", from); uint64_t next_cache_line = ((actual_offset + CACHELINE) & CACHELINE_MASK) - actual_offset + from; // text(log_fp, "\t\t[ReaderWriter] next_cache_line %" PRIx64 " \n", next_cache_line); uint64_t src = (uint64_t)from + sizeof(slot_header_t); uint64_t dst = (uint64_t)to; uint64_t size = slot_size - sizeof(slot_header_t); assert(next_cache_line >= src && "Alignment is not correct! "); uint64_t hop_size = std::min(next_cache_line-src, size); uint64_t total_size = 0; uint64_t copy_size = std::min(hop_size, upper_size - total_size); memcpy((char*)dst, (char*)src, copy_size); total_size += copy_size; src += hop_size; dst += copy_size; size -= hop_size; while(size > 0 ){ text(log_fp, "\t\t[ReaderWriter] read version from %" PRIx64 " \n", src); if(current_version != *(uint8_t*)src){ text(log_fp,"Error version, \n"); return OBJECT_IS_INCONSISTENT; } src++; size--; hop_size = std::min((uint64_t)CACHELINE - 1, size); copy_size = std::min(hop_size, upper_size-total_size); memcpy((char*)dst, (char*)src, copy_size); total_size += copy_size; src += hop_size; dst += copy_size; size -= hop_size; } assert(src == from+slot_size && "Did you copy all bytes?"); text(log_fp, "\t\t[ReaderWriter] read_locally finished \n"); *lim_size = (uint32_t) total_size; return 0; } int ReaderWriter::client_read_fast(uint64_t to, uint64_t from, uint16_t slot_size, uint32_t *lim_size ){ uint32_t copy_size = std::min((uint32_t)slot_size, *lim_size ); memcpy((char*)to, (char*)from, copy_size); return 0; } int ReaderWriter::try_lock_slot_and_increment_version(addr_t localbuf, uint16_t obj_id){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)localbuf; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.obj_id != obj_id){ return NOT_FOUND; } if(header_copy.compaction){ return UNDER_COMPACTION; } if(header_copy.lock){ return LOCK_FAILED; } slot_header_t locked_header_copy = header_copy; locked_header_copy.lock = 1; locked_header_copy.version++; int version = (int)locked_header_copy.version; bool success = head->compare_exchange_strong(header_copy,locked_header_copy); if(success){ return version; } return LOCK_FAILED; } int ReaderWriter::try_lock_slot_and_increment_version_if_version(addr_t localbuf, uint16_t obj_id, uint8_t requested_version){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)localbuf; slot_header_t header_copy = head->load(std::memory_order_relaxed); text(log_fp, "\t\t[ReaderWriter] %u == %u \n",(uint32_t)(header_copy.version), (uint32_t)requested_version); if(header_copy.obj_id != obj_id){ return NOT_FOUND; } if(header_copy.compaction){ return UNDER_COMPACTION; } if(header_copy.version != requested_version){ return OBJECT_IS_INCONSISTENT; } if(header_copy.lock){ return LOCK_FAILED; } slot_header_t locked_header_copy = header_copy; locked_header_copy.lock = 1; locked_header_copy.version++; int version = (int)locked_header_copy.version; bool success = head->compare_exchange_strong(header_copy,locked_header_copy); if(success){ return version; } return -1; } bool ReaderWriter::try_lock_slot_for_compaction(addr_t localbuf){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)localbuf; slot_header_t header_copy = head->load(std::memory_order_relaxed); if(header_copy.lock){ return false; } slot_header_t locked_header_copy = header_copy; locked_header_copy.lock = 1; locked_header_copy.compaction = 1; return head->compare_exchange_strong(header_copy,locked_header_copy); } void ReaderWriter::unlock_slot(addr_t localbuf){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)localbuf; slot_header_t header_copy = head->load(std::memory_order_relaxed); assert(header_copy.lock); slot_header_t unlocked_header_copy = header_copy; unlocked_header_copy.lock = 0; bool ret = head->compare_exchange_strong(header_copy,unlocked_header_copy); assert(ret); } bool ReaderWriter::unlock_slot_from_compaction(addr_t localbuf){ std::atomic<slot_header_t> * head = (std::atomic<slot_header_t> *)localbuf; slot_header_t header_copy = head->load(std::memory_order_relaxed); assert(header_copy.lock); slot_header_t unlocked_header_copy = header_copy; unlocked_header_copy.lock = 0; unlocked_header_copy.compaction = 0; return head->compare_exchange_strong(header_copy,unlocked_header_copy);; }
36.910979
167
0.666452
[ "object" ]
4588dd0bbdd77f4d753f713d6180f2a957ed75b5
7,530
cc
C++
Testcase4-Application-breakdown/online-compiling/src/models/generate-deps.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
129
2020-08-09T12:02:30.000Z
2022-03-31T15:26:03.000Z
Testcase4-Application-breakdown/online-compiling/src/models/generate-deps.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
11
2020-09-17T09:42:07.000Z
2022-03-30T19:05:38.000Z
Testcase4-Application-breakdown/online-compiling/src/models/generate-deps.cc
hunhoffe/ServerlessBench
529eb835638cad0edb5be3343166c7ade375ece2
[ "MulanPSL-1.0" ]
22
2020-08-20T06:59:24.000Z
2022-03-18T21:00:05.000Z
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #include <iostream> #include <algorithm> #include "gcc.hh" #include "timeouts.hh" #include "thunk/thunk.hh" #include "thunk/thunk_reader.hh" #include "thunk/thunk_writer.hh" #include "thunk/ggutils.hh" #include "util/exception.hh" #include "util/system_runner.hh" #include "util/tokenize.hh" #include "util/util.hh" using namespace std; using namespace gg::thunk; void usage( const char * argv0 ) { cerr << argv0 << " PREPROCESSOR-THUNK" << endl; } vector<string> canonicalize_args( vector<string> & args ) { const int argc = args.size(); vector<char *> argv; transform( args.begin(), args.end(), back_inserter( argv ), []( string & s ) { return &s[ 0 ]; } ); GCCArguments gcc_arguments { argc, &argv[ 0 ], false, true }; vector<string> new_args = gcc_arguments.all(); return new_args; } void prepare_include_path( const roost::path & sysroot, const vector<string> & tarballs ) { roost::create_directories( sysroot ); /* (1) extract the tarballs */ for ( const string & tarball_hash : tarballs ) { vector<string> extract_args { "/bin/tar", "xf", gg::paths::blob( tarball_hash ).string(), "-C", sysroot.string(), "-I", "/bin/gzip" }; cerr << "Extracting " << tarball_hash << "..."; run( extract_args[ 0 ], extract_args, {}, true, true ); cerr << "done." << endl; } } string get_hash( const string & file ) { constexpr char PREFIX[] = "// GGHASH:"; constexpr size_t PREFIX_LEN = sizeof( PREFIX ) - 1; constexpr size_t LEN = PREFIX_LEN + gg::hash::length; char read_buffer[ LEN ]; ifstream fin { file }; fin.read( read_buffer, LEN ); if ( strncmp( PREFIX, read_buffer, PREFIX_LEN ) == 0 ) { return { read_buffer + PREFIX_LEN, gg::hash::length }; } else { return gg::hash::file_force( file ); } } int main( int argc, char * argv[] ) { try { if ( argc <= 0 ) { abort(); } if ( argc < 2 ) { usage( argv[ 0 ] ); return EXIT_FAILURE; } /* setting the GG_DIR, so we can find the blobs directory */ setenv( "GG_DIR", roost::dirname( safe_getenv( "__GG_DIR__" ) ).string().c_str(), true ); Thunk thunk = ThunkReader::read( safe_getenv( "__GG_THUNK_PATH__" ) ); const roost::path execution_root { roost::current_working_directory() }; /* read all the necessary environment variables *****************/ roost::path working_directory = safe_getenv( DEPGEN_WORKING_DIRECTORY ); const string include_tarballs = safe_getenv( DEPGEN_INCLUDE_TARBALLS ); const string input_name = safe_getenv( DEPGEN_INPUT_NAME ); const string target_name = safe_getenv( DEPGEN_TARGET_NAME ); const string gcc_function_hash = safe_getenv( DEPGEN_GCC_HASH ); const string cc1_function_name = safe_getenv( DEPGEN_CC1_NAME ); const string cc1_function_hash = safe_getenv( DEPGEN_CC1_HASH ); /* create the sysroot directory *********************************/ roost::create_directories( GG_SYSROOT_PREFIX ); const roost::path sysroot = roost::canonical( GG_SYSROOT_PREFIX ); /* parse the arguments ******************************************/ vector<string> thunk_args = thunk.function().args(); const OperationMode op_mode = ( thunk_args[ 0 ] == program_data.at( GCC ).filename() ) ? OperationMode::GCC : OperationMode::GXX; thunk_args.erase( thunk_args.begin() + 1 ); thunk_args = canonicalize_args( thunk_args ); /* prepare the working directory ********************************/ working_directory = sysroot / working_directory; roost::create_directories( working_directory ); /* put gcc binaries in place ************************************/ const roost::path gcc_dir = sysroot / "gccbin"; roost::create_directories( gcc_dir ); const string path_envar = "PATH=" + gcc_dir.string(); const roost::path gcc_path = gcc_dir / ( ( op_mode == OperationMode::GCC ) ? "gcc" : "g++" ); const roost::path cc1_path = gcc_dir / cc1_function_name; roost::symlink( gg::paths::blob( gcc_function_hash ), gcc_path ); roost::symlink( gg::paths::blob( cc1_function_hash ), cc1_path ); /* extract the tarballs containig stripped header files *********/ const vector<string> tarballs = split( include_tarballs, ":" ); prepare_include_path( sysroot, tarballs ); roost::chdir( working_directory ); /* put all the extra files in the sysroot ***********************/ for ( const auto & value : thunk.values() ) { if ( value.second.length() == 0 or value.second.compare( 0, sizeof( "/__gg" ) - 1, "/__gg" ) == 0 ) { continue; } roost::path filepath { value.second }; if ( roost::is_absolute( filepath ) ) { filepath = sysroot / filepath; } cerr << "Putting file " << value.second << "..."; roost::create_directories( roost::dirname( filepath ) ); if ( roost::exists( filepath ) ) { roost::remove( filepath ); } roost::symlink( gg::paths::blob( value.first ), filepath ); cerr << "done." << endl; } /* time to run gcc -M *******************************************/ const vector<string> dependencies = GCCModelGenerator::generate_dependencies_file( op_mode, input_name, thunk_args, ( execution_root / "dependencies" ).string(), target_name, false, gcc_path.string(), vector<string> { { path_envar } } ); /* (1) create a new function ###################################*/ const Function & function = thunk.function(); vector<string> new_envars; for ( const string & envar : function.envars() ) { if ( envar.compare( 0, sizeof( "_GG" ) - 1, "_GG" ) != 0 ) { new_envars.push_back( envar ); } } Function new_function { gcc_function_hash, function.args(), new_envars }; /* (2) create new data lists ###################################*/ Thunk::DataList values = thunk.values(); Thunk::DataList executables = thunk.executables(); executables.erase( function.hash() ); for ( const auto & tarball_hash : tarballs ) { values.erase( tarball_hash ); } for ( auto it = values.begin(); it != values.end(); ) { if ( it->second.length() == 0 or it->second == "/__gg__/gcc-specs" ) { it++; continue; } it = values.erase( it ); } for ( const auto & dep : dependencies ) { const string dep_hash = get_hash( dep ); string dep_path; if ( dep.compare( 0, sysroot.string().length(), sysroot.string() ) == 0 ) { dep_path = dep.substr( sysroot.string().length() ); } else { dep_path = dep; } dep_path = roost::path( dep_path ).lexically_normal().string(); values.emplace( make_pair( dep_hash, dep_path ) ); } /* (3) create a new thunk ######################################*/ Thunk new_thunk { move( new_function ), move( values ), {}, move( executables ), { "output" } }; new_thunk.set_timeout( PREPROCESS_TIMEOUT ); /* (4) clean up and write output ###############################*/ roost::remove_directory( sysroot ); ThunkWriter::write( new_thunk, execution_root / "output" ); } catch ( const exception & e ) { print_exception( argv[ 0 ], e ); return EXIT_FAILURE; } return EXIT_SUCCESS; }
33.318584
97
0.58672
[ "vector", "transform" ]
45897193f484af38efb90375bc1daaf53b8d7989
35,006
cpp
C++
export/windows/obj/src/flixel/system/debug/console/Console.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/flixel/system/debug/console/Console.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/flixel/system/debug/console/Console.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxGame #include <flixel/FlxGame.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_input_FlxKeyManager #include <flixel/input/FlxKeyManager.h> #endif #ifndef INCLUDED_flixel_input_IFlxInputManager #include <flixel/input/IFlxInputManager.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyboard #include <flixel/input/keyboard/FlxKeyboard.h> #endif #ifndef INCLUDED_flixel_system_FlxAssets #include <flixel/system/FlxAssets.h> #endif #ifndef INCLUDED_flixel_system_debug_FlxDebugger #include <flixel/system/debug/FlxDebugger.h> #endif #ifndef INCLUDED_flixel_system_debug_GraphicConsole #include <flixel/system/debug/GraphicConsole.h> #endif #ifndef INCLUDED_flixel_system_debug_VCR #include <flixel/system/debug/VCR.h> #endif #ifndef INCLUDED_flixel_system_debug_Window #include <flixel/system/debug/Window.h> #endif #ifndef INCLUDED_flixel_system_debug_completion_CompletionHandler #include <flixel/system/debug/completion/CompletionHandler.h> #endif #ifndef INCLUDED_flixel_system_debug_completion_CompletionList #include <flixel/system/debug/completion/CompletionList.h> #endif #ifndef INCLUDED_flixel_system_debug_console_Console #include <flixel/system/debug/console/Console.h> #endif #ifndef INCLUDED_flixel_system_debug_console_ConsoleCommands #include <flixel/system/debug/console/ConsoleCommands.h> #endif #ifndef INCLUDED_flixel_system_debug_console_ConsoleHistory #include <flixel/system/debug/console/ConsoleHistory.h> #endif #ifndef INCLUDED_flixel_system_debug_console_ConsoleUtil #include <flixel/system/debug/console/ConsoleUtil.h> #endif #ifndef INCLUDED_flixel_system_debug_log_LogStyle #include <flixel/system/debug/log/LogStyle.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_ConsoleFrontEnd #include <flixel/system/frontEnds/ConsoleFrontEnd.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_DebuggerFrontEnd #include <flixel/system/frontEnds/DebuggerFrontEnd.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_LogFrontEnd #include <flixel/system/frontEnds/LogFrontEnd.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_VCRFrontEnd #include <flixel/system/frontEnds/VCRFrontEnd.h> #endif #ifndef INCLUDED_flixel_util_FlxStringUtil #include <flixel/util/FlxStringUtil.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_lime_app_IModule #include <lime/app/IModule.h> #endif #ifndef INCLUDED_lime_text__UTF8String_UTF8String_Impl_ #include <lime/text/_UTF8String/UTF8String_Impl_.h> #endif #ifndef INCLUDED_openfl_Lib #include <openfl/Lib.h> #endif #ifndef INCLUDED_openfl_display_BitmapData #include <openfl/display/BitmapData.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectContainer #include <openfl/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_MovieClip #include <openfl/display/MovieClip.h> #endif #ifndef INCLUDED_openfl_display_Sprite #include <openfl/display/Sprite.h> #endif #ifndef INCLUDED_openfl_display_Stage #include <openfl/display/Stage.h> #endif #ifndef INCLUDED_openfl_events_Event #include <openfl/events/Event.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_FocusEvent #include <openfl/events/FocusEvent.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_KeyboardEvent #include <openfl/events/KeyboardEvent.h> #endif #ifndef INCLUDED_openfl_events_MouseEvent #include <openfl/events/MouseEvent.h> #endif #ifndef INCLUDED_openfl_geom_Rectangle #include <openfl/geom/Rectangle.h> #endif #ifndef INCLUDED_openfl_text_TextField #include <openfl/text/TextField.h> #endif #ifndef INCLUDED_openfl_text_TextFormat #include <openfl/text/TextFormat.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_c69022abc8c5c26b_30_new,"flixel.system.debug.console.Console","new",0x900a6c8a,"flixel.system.debug.console.Console.new","flixel/system/debug/console/Console.hx",30,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_96_createInputTextField,"flixel.system.debug.console.Console","createInputTextField",0x91c24015,"flixel.system.debug.console.Console.createInputTextField","flixel/system/debug/console/Console.hx",96,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_122_registerEventListeners,"flixel.system.debug.console.Console","registerEventListeners",0x714c11de,"flixel.system.debug.console.Console.registerEventListeners","flixel/system/debug/console/Console.hx",122,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_131_registerEventListeners,"flixel.system.debug.console.Console","registerEventListeners",0x714c11de,"flixel.system.debug.console.Console.registerEventListeners","flixel/system/debug/console/Console.hx",131,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_135_registerEventListeners,"flixel.system.debug.console.Console","registerEventListeners",0x714c11de,"flixel.system.debug.console.Console.registerEventListeners","flixel/system/debug/console/Console.hx",135,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_111_registerEventListeners,"flixel.system.debug.console.Console","registerEventListeners",0x714c11de,"flixel.system.debug.console.Console.registerEventListeners","flixel/system/debug/console/Console.hx",111,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_143_update,"flixel.system.debug.console.Console","update",0x661b601f,"flixel.system.debug.console.Console.update","flixel/system/debug/console/Console.hx",143,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_160_onFocus,"flixel.system.debug.console.Console","onFocus",0xeecff763,"flixel.system.debug.console.Console.onFocus","flixel/system/debug/console/Console.hx",160,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_178_onFocusLost,"flixel.system.debug.console.Console","onFocusLost",0x2ed3bae7,"flixel.system.debug.console.Console.onFocusLost","flixel/system/debug/console/Console.hx",178,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_199_onKeyDown,"flixel.system.debug.console.Console","onKeyDown",0x970b39ec,"flixel.system.debug.console.Console.onKeyDown","flixel/system/debug/console/Console.hx",199,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_226_setText,"flixel.system.debug.console.Console","setText",0x66870699,"flixel.system.debug.console.Console.setText","flixel/system/debug/console/Console.hx",226,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_234_processCommand,"flixel.system.debug.console.Console","processCommand",0x640a92b2,"flixel.system.debug.console.Console.processCommand","flixel/system/debug/console/Console.hx",234,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_266_reposition,"flixel.system.debug.console.Console","reposition",0x383e0c72,"flixel.system.debug.console.Console.reposition","flixel/system/debug/console/Console.hx",266,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_281_registerFunction,"flixel.system.debug.console.Console","registerFunction",0xf8dd3a31,"flixel.system.debug.console.Console.registerFunction","flixel/system/debug/console/Console.hx",281,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_298_registerObject,"flixel.system.debug.console.Console","registerObject",0x0bbfe598,"flixel.system.debug.console.Console.registerObject","flixel/system/debug/console/Console.hx",298,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_312_registerClass,"flixel.system.debug.console.Console","registerClass",0x7ad06f7f,"flixel.system.debug.console.Console.registerClass","flixel/system/debug/console/Console.hx",312,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_323_registerEnum,"flixel.system.debug.console.Console","registerEnum",0x75d3399a,"flixel.system.debug.console.Console.registerEnum","flixel/system/debug/console/Console.hx",323,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_327_destroy,"flixel.system.debug.console.Console","destroy",0x788f2624,"flixel.system.debug.console.Console.destroy","flixel/system/debug/console/Console.hx",327,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_353_updateSize,"flixel.system.debug.console.Console","updateSize",0x97e42880,"flixel.system.debug.console.Console.updateSize","flixel/system/debug/console/Console.hx",353,0x367943c8) HX_LOCAL_STACK_FRAME(_hx_pos_c69022abc8c5c26b_36_boot,"flixel.system.debug.console.Console","boot",0x712d8cc8,"flixel.system.debug.console.Console.boot","flixel/system/debug/console/Console.hx",36,0x367943c8) namespace flixel{ namespace _hx_system{ namespace debug{ namespace console{ void Console_obj::__construct( ::flixel::_hx_system::debug::completion::CompletionList completionList){ HX_GC_STACKFRAME(&_hx_pos_c69022abc8c5c26b_30_new) HXLINE( 64) this->stageMouseDown = false; HXLINE( 63) this->inputMouseDown = false; HXLINE( 55) this->objectStack = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 50) this->registeredHelp = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 46) this->registeredFunctions = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 42) this->registeredObjects = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 76) super::__construct(HX_("Console",37,13,27,e6), ::flixel::_hx_system::debug::GraphicConsole_obj::__alloc( HX_CTX ,0,0,null(),null()),0,0,false,null(),null(),null()); HXLINE( 77) this->completionList = completionList; HXLINE( 78) completionList->setY((this->get_y() + 15)); HXLINE( 81) ::flixel::_hx_system::debug::console::ConsoleUtil_obj::init(); HXLINE( 84) this->history = ::flixel::_hx_system::debug::console::ConsoleHistory_obj::__alloc( HX_CTX ); HXLINE( 85) this->createInputTextField(); HXLINE( 86) ::flixel::_hx_system::debug::completion::CompletionHandler_obj::__alloc( HX_CTX ,completionList,this->input); HXLINE( 87) this->registerEventListeners(); HXLINE( 91) ::flixel::_hx_system::debug::console::ConsoleCommands_obj::__alloc( HX_CTX ,hx::ObjectPtr<OBJ_>(this)); } Dynamic Console_obj::__CreateEmpty() { return new Console_obj; } void *Console_obj::_hx_vtable = 0; Dynamic Console_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Console_obj > _hx_result = new Console_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool Console_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x1b123bf8) { if (inClassId<=(int)0x17120186) { if (inClassId<=(int)0x0ddfced7) { return inClassId==(int)0x00000001 || inClassId==(int)0x0ddfced7; } else { return inClassId==(int)0x17120186; } } else { return inClassId==(int)0x19c29573 || inClassId==(int)0x1b123bf8; } } else { if (inClassId<=(int)0x55cf6de8) { return inClassId==(int)0x3f2b00af || inClassId==(int)0x55cf6de8; } else { return inClassId==(int)0x619ca9b8; } } } void Console_obj::createInputTextField(){ HX_GC_STACKFRAME(&_hx_pos_c69022abc8c5c26b_96_createInputTextField) HXLINE( 98) this->input = ::openfl::text::TextField_obj::__alloc( HX_CTX ); HXLINE( 99) this->input->set_embedFonts(true); HXLINE( 100) ::openfl::text::TextField _hx_tmp = this->input; HXDLIN( 100) _hx_tmp->set_defaultTextFormat( ::openfl::text::TextFormat_obj::__alloc( HX_CTX ,::flixel::_hx_system::FlxAssets_obj::FONT_DEBUGGER,12,16777215,false,false,false,null(),null(),null(),null(),null(),null(),null())); HXLINE( 102) this->input->set_text(HX_("(Click here / press [Tab] to enter command. Type 'help' for help.)",f9,4e,c0,26)); HXLINE( 103) this->input->set_width(( (Float)((this->_width - 4)) )); HXLINE( 104) this->input->set_height(( (Float)((this->_height - 15)) )); HXLINE( 105) this->input->set_x(( (Float)(2) )); HXLINE( 106) this->input->set_y(( (Float)(15) )); HXLINE( 107) this->addChild(this->input); } HX_DEFINE_DYNAMIC_FUNC0(Console_obj,createInputTextField,(void)) void Console_obj::registerEventListeners(){ HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_0, ::flixel::_hx_system::debug::console::Console,_gthis) HXARGC(1) void _hx_run( ::openfl::events::KeyboardEvent e){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_122_registerEventListeners) HXLINE( 122) bool _hx_tmp; HXDLIN( 122) bool _hx_tmp1; HXDLIN( 122) if (::flixel::FlxG_obj::debugger->visible) { HXLINE( 122) _hx_tmp1 = ::flixel::FlxG_obj::game->debugger->console->get_visible(); } else { HXLINE( 122) _hx_tmp1 = false; } HXDLIN( 122) if (_hx_tmp1) { HXLINE( 122) _hx_tmp = (e->keyCode == 9); } else { HXLINE( 122) _hx_tmp = false; } HXDLIN( 122) if (_hx_tmp) { HXLINE( 123) ::openfl::Lib_obj::get_current()->stage->set_focus(_gthis->input); } } HX_END_LOCAL_FUNC1((void)) HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_1, ::flixel::_hx_system::debug::console::Console,_gthis) HXARGC(1) void _hx_run( ::openfl::events::MouseEvent _){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_131_registerEventListeners) HXLINE( 131) _gthis->inputMouseDown = true; } HX_END_LOCAL_FUNC1((void)) HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_2, ::flixel::_hx_system::debug::console::Console,_gthis) HXARGC(1) void _hx_run( ::openfl::events::MouseEvent _1){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_135_registerEventListeners) HXLINE( 135) _gthis->stageMouseDown = true; } HX_END_LOCAL_FUNC1((void)) HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_111_registerEventListeners) HXLINE( 110) ::flixel::_hx_system::debug::console::Console _gthis = hx::ObjectPtr<OBJ_>(this); HXLINE( 113) this->input->set_type(1); HXLINE( 114) this->input->addEventListener(HX_("focusIn",dd,45,83,41),this->onFocus_dyn(),null(),null(),null()); HXLINE( 115) this->input->addEventListener(HX_("focusOut",96,6f,5e,11),this->onFocusLost_dyn(),null(),null(),null()); HXLINE( 116) this->input->addEventListener(HX_("keyDown",a1,69,47,9c),this->onKeyDown_dyn(),null(),null(),null()); HXLINE( 120) ::openfl::Lib_obj::get_current()->stage->addEventListener(HX_("keyDown",a1,69,47,9c), ::Dynamic(new _hx_Closure_0(_gthis)),null(),null(),null()); HXLINE( 129) this->input->addEventListener(HX_("mouseDown",27,b1,c2,ee), ::Dynamic(new _hx_Closure_1(_gthis)),null(),null(),null()); HXLINE( 133) ::openfl::Lib_obj::get_current()->stage->addEventListener(HX_("mouseDown",27,b1,c2,ee), ::Dynamic(new _hx_Closure_2(_gthis)),null(),null(),null()); } HX_DEFINE_DYNAMIC_FUNC0(Console_obj,registerEventListeners,(void)) void Console_obj::update(){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_143_update) HXLINE( 144) this->super::update(); HXLINE( 146) bool _hx_tmp; HXDLIN( 146) bool _hx_tmp1; HXDLIN( 146) ::openfl::display::InteractiveObject _hx_tmp2 = ::openfl::Lib_obj::get_current()->stage->get_focus(); HXDLIN( 146) if (hx::IsEq( _hx_tmp2,this->input )) { HXLINE( 146) _hx_tmp1 = this->stageMouseDown; } else { HXLINE( 146) _hx_tmp1 = false; } HXDLIN( 146) if (_hx_tmp1) { HXLINE( 146) _hx_tmp = !(this->inputMouseDown); } else { HXLINE( 146) _hx_tmp = false; } HXDLIN( 146) if (_hx_tmp) { HXLINE( 148) ::openfl::Lib_obj::get_current()->stage->set_focus(null()); HXLINE( 150) ::flixel::FlxG_obj::game->onFocus(null()); } HXLINE( 153) this->stageMouseDown = false; HXLINE( 154) this->inputMouseDown = false; } void Console_obj::onFocus( ::openfl::events::FocusEvent _){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_160_onFocus) HXLINE( 163) if (::flixel::FlxG_obj::console->autoPause) { HXLINE( 164) ::flixel::FlxG_obj::vcr->pause(); } HXLINE( 168) ::flixel::FlxG_obj::keys->enabled = false; HXLINE( 171) if (::lime::text::_UTF8String::UTF8String_Impl__obj::equals(this->input->get_text(),HX_("(Click here / press [Tab] to enter command. Type 'help' for help.)",f9,4e,c0,26))) { HXLINE( 172) this->input->set_text(HX_("",00,00,00,00)); } } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,onFocus,(void)) void Console_obj::onFocusLost( ::openfl::events::FocusEvent _){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_178_onFocusLost) HXLINE( 181) bool _hx_tmp; HXDLIN( 181) if (::flixel::FlxG_obj::console->autoPause) { HXLINE( 181) _hx_tmp = !(::flixel::FlxG_obj::game->debugger->vcr->manualPause); } else { HXLINE( 181) _hx_tmp = false; } HXDLIN( 181) if (_hx_tmp) { HXLINE( 182) ::flixel::FlxG_obj::vcr->resume(); } HXLINE( 186) ::flixel::FlxG_obj::keys->enabled = true; HXLINE( 189) if (::lime::text::_UTF8String::UTF8String_Impl__obj::equals(this->input->get_text(),HX_("",00,00,00,00))) { HXLINE( 190) this->input->set_text(HX_("(Click here / press [Tab] to enter command. Type 'help' for help.)",f9,4e,c0,26)); } HXLINE( 193) this->completionList->close(); HXLINE( 194) ::flixel::FlxG_obj::game->debugger->onMouseFocusLost(); } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,onFocusLost,(void)) void Console_obj::onKeyDown( ::openfl::events::KeyboardEvent e){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_199_onKeyDown) HXLINE( 200) if (this->completionList->get_visible()) { HXLINE( 201) return; } HXLINE( 203) switch((int)(e->keyCode)){ case (int)13: { HXLINE( 206) if ((this->input->get_text() != HX_("",00,00,00,00))) { HXLINE( 207) this->processCommand(); } } break; case (int)27: { HXLINE( 210) ::openfl::Lib_obj::get_current()->stage->set_focus(null()); } break; case (int)38: { HXLINE( 216) if (!(this->history->get_isEmpty())) { HXLINE( 217) this->setText(this->history->getPreviousCommand()); } } break; case (int)40: { HXLINE( 220) if (!(this->history->get_isEmpty())) { HXLINE( 221) this->setText(this->history->getNextCommand()); } } break; case (int)46: { HXLINE( 213) this->input->set_text(HX_("",00,00,00,00)); } break; } } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,onKeyDown,(void)) void Console_obj::setText(::String text){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_226_setText) HXLINE( 227) this->input->set_text(text); HXLINE( 229) this->input->setSelection(text.length,text.length); } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,setText,(void)) void Console_obj::processCommand(){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_234_processCommand) HXDLIN( 234) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 236) ::String text = ::StringTools_obj::trim(this->input->get_text()); HXLINE( 240) if (hx::IsNotNull( this->registeredFunctions->get(text) )) { HXLINE( 241) text = (text + HX_("()",01,23,00,00)); } HXLINE( 244) ::Dynamic output = ::flixel::_hx_system::debug::console::ConsoleUtil_obj::runCommand(text); HXLINE( 245) if (hx::IsNotNull( output )) { HXLINE( 246) ::flixel::FlxG_obj::log->advanced(::cpp::VirtualArray_obj::__new(1)->init(0,output),::flixel::_hx_system::debug::log::LogStyle_obj::CONSOLE,null()); } HXLINE( 248) ::flixel::_hx_system::debug::console::ConsoleHistory _hx_tmp = this->history; HXDLIN( 248) _hx_tmp->addCommand(this->input->get_text()); HXLINE( 252) bool _hx_tmp1; HXDLIN( 252) if (::flixel::FlxG_obj::vcr->paused) { HXLINE( 252) _hx_tmp1 = ::flixel::FlxG_obj::console->stepAfterCommand; } else { HXLINE( 252) _hx_tmp1 = false; } HXDLIN( 252) if (_hx_tmp1) { HXLINE( 253) ::flixel::FlxG_obj::game->debugger->vcr->onStep(); } HXLINE( 256) this->input->set_text(HX_("",00,00,00,00)); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic e = _hx_e; HXLINE( 261) ::flixel::_hx_system::frontEnds::LogFrontEnd _this = ::flixel::FlxG_obj::log; HXDLIN( 261) ::Dynamic Data = ((HX_("Console: Invalid syntax: '",78,2b,94,2e) + ::Std_obj::string(e)) + HX_("'",27,00,00,00)); HXDLIN( 261) _this->advanced(Data,::flixel::_hx_system::debug::log::LogStyle_obj::ERROR,true); } else { HX_STACK_DO_THROW(_hx_e); } } } HX_DEFINE_DYNAMIC_FUNC0(Console_obj,processCommand,(void)) void Console_obj::reposition(Float X,Float Y){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_266_reposition) HXLINE( 267) this->super::reposition(X,Y); HXLINE( 268) ::flixel::_hx_system::debug::completion::CompletionList _hx_tmp = this->completionList; HXDLIN( 268) _hx_tmp->setY((this->get_y() + 15)); HXLINE( 269) this->completionList->close(); } void Console_obj::registerFunction(::String functionAlias, ::Dynamic func,::String helpText){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_281_registerFunction) HXLINE( 282) this->registeredFunctions->set(functionAlias,func); HXLINE( 284) ::flixel::_hx_system::debug::console::ConsoleUtil_obj::registerFunction(functionAlias,func); HXLINE( 287) if (hx::IsNotNull( helpText )) { HXLINE( 288) this->registeredHelp->set(functionAlias,helpText); } } HX_DEFINE_DYNAMIC_FUNC3(Console_obj,registerFunction,(void)) void Console_obj::registerObject(::String objectAlias, ::Dynamic anyObject){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_298_registerObject) HXLINE( 299) this->registeredObjects->set(objectAlias,anyObject); HXLINE( 301) ::flixel::_hx_system::debug::console::ConsoleUtil_obj::registerObject(objectAlias,anyObject); } HX_DEFINE_DYNAMIC_FUNC2(Console_obj,registerObject,(void)) void Console_obj::registerClass(hx::Class cl){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_312_registerClass) HXDLIN( 312) this->registerObject(::flixel::util::FlxStringUtil_obj::getClassName(cl,true),cl); } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,registerClass,(void)) void Console_obj::registerEnum(hx::Class e){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_323_registerEnum) HXDLIN( 323) this->registerObject(::flixel::util::FlxStringUtil_obj::getEnumName(e,true),e); } HX_DEFINE_DYNAMIC_FUNC1(Console_obj,registerEnum,(void)) void Console_obj::destroy(){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_327_destroy) HXLINE( 328) this->super::destroy(); HXLINE( 331) this->input->removeEventListener(HX_("focusIn",dd,45,83,41),this->onFocus_dyn(),null()); HXLINE( 332) this->input->removeEventListener(HX_("focusOut",96,6f,5e,11),this->onFocusLost_dyn(),null()); HXLINE( 333) this->input->removeEventListener(HX_("keyDown",a1,69,47,9c),this->onKeyDown_dyn(),null()); HXLINE( 336) if (hx::IsNotNull( this->input )) { HXLINE( 338) this->removeChild(this->input); HXLINE( 339) this->input = null(); } HXLINE( 342) this->registeredObjects = null(); HXLINE( 343) this->registeredFunctions = null(); HXLINE( 344) this->registeredHelp = null(); HXLINE( 346) this->objectStack = null(); } void Console_obj::updateSize(){ HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_353_updateSize) HXLINE( 354) this->super::updateSize(); HXLINE( 356) this->input->set_width(( (Float)((this->_width - 4)) )); HXLINE( 357) this->input->set_height(( (Float)((this->_height - 15)) )); } ::String Console_obj::DEFAULT_TEXT; hx::ObjectPtr< Console_obj > Console_obj::__new( ::flixel::_hx_system::debug::completion::CompletionList completionList) { hx::ObjectPtr< Console_obj > __this = new Console_obj(); __this->__construct(completionList); return __this; } hx::ObjectPtr< Console_obj > Console_obj::__alloc(hx::Ctx *_hx_ctx, ::flixel::_hx_system::debug::completion::CompletionList completionList) { Console_obj *__this = (Console_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Console_obj), true, "flixel.system.debug.console.Console")); *(void **)__this = Console_obj::_hx_vtable; __this->__construct(completionList); return __this; } Console_obj::Console_obj() { } void Console_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Console); HX_MARK_MEMBER_NAME(registeredObjects,"registeredObjects"); HX_MARK_MEMBER_NAME(registeredFunctions,"registeredFunctions"); HX_MARK_MEMBER_NAME(registeredHelp,"registeredHelp"); HX_MARK_MEMBER_NAME(objectStack,"objectStack"); HX_MARK_MEMBER_NAME(input,"input"); HX_MARK_MEMBER_NAME(inputMouseDown,"inputMouseDown"); HX_MARK_MEMBER_NAME(stageMouseDown,"stageMouseDown"); HX_MARK_MEMBER_NAME(history,"history"); HX_MARK_MEMBER_NAME(completionList,"completionList"); ::flixel::_hx_system::debug::Window_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void Console_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(registeredObjects,"registeredObjects"); HX_VISIT_MEMBER_NAME(registeredFunctions,"registeredFunctions"); HX_VISIT_MEMBER_NAME(registeredHelp,"registeredHelp"); HX_VISIT_MEMBER_NAME(objectStack,"objectStack"); HX_VISIT_MEMBER_NAME(input,"input"); HX_VISIT_MEMBER_NAME(inputMouseDown,"inputMouseDown"); HX_VISIT_MEMBER_NAME(stageMouseDown,"stageMouseDown"); HX_VISIT_MEMBER_NAME(history,"history"); HX_VISIT_MEMBER_NAME(completionList,"completionList"); ::flixel::_hx_system::debug::Window_obj::__Visit(HX_VISIT_ARG); } hx::Val Console_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"input") ) { return hx::Val( input ); } break; case 6: if (HX_FIELD_EQ(inName,"update") ) { return hx::Val( update_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"history") ) { return hx::Val( history ); } if (HX_FIELD_EQ(inName,"onFocus") ) { return hx::Val( onFocus_dyn() ); } if (HX_FIELD_EQ(inName,"setText") ) { return hx::Val( setText_dyn() ); } if (HX_FIELD_EQ(inName,"destroy") ) { return hx::Val( destroy_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"onKeyDown") ) { return hx::Val( onKeyDown_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"reposition") ) { return hx::Val( reposition_dyn() ); } if (HX_FIELD_EQ(inName,"updateSize") ) { return hx::Val( updateSize_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"objectStack") ) { return hx::Val( objectStack ); } if (HX_FIELD_EQ(inName,"onFocusLost") ) { return hx::Val( onFocusLost_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"registerEnum") ) { return hx::Val( registerEnum_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"registerClass") ) { return hx::Val( registerClass_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"registeredHelp") ) { return hx::Val( registeredHelp ); } if (HX_FIELD_EQ(inName,"inputMouseDown") ) { return hx::Val( inputMouseDown ); } if (HX_FIELD_EQ(inName,"stageMouseDown") ) { return hx::Val( stageMouseDown ); } if (HX_FIELD_EQ(inName,"completionList") ) { return hx::Val( completionList ); } if (HX_FIELD_EQ(inName,"processCommand") ) { return hx::Val( processCommand_dyn() ); } if (HX_FIELD_EQ(inName,"registerObject") ) { return hx::Val( registerObject_dyn() ); } break; case 16: if (HX_FIELD_EQ(inName,"registerFunction") ) { return hx::Val( registerFunction_dyn() ); } break; case 17: if (HX_FIELD_EQ(inName,"registeredObjects") ) { return hx::Val( registeredObjects ); } break; case 19: if (HX_FIELD_EQ(inName,"registeredFunctions") ) { return hx::Val( registeredFunctions ); } break; case 20: if (HX_FIELD_EQ(inName,"createInputTextField") ) { return hx::Val( createInputTextField_dyn() ); } break; case 22: if (HX_FIELD_EQ(inName,"registerEventListeners") ) { return hx::Val( registerEventListeners_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val Console_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"input") ) { input=inValue.Cast< ::openfl::text::TextField >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"history") ) { history=inValue.Cast< ::flixel::_hx_system::debug::console::ConsoleHistory >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"objectStack") ) { objectStack=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"registeredHelp") ) { registeredHelp=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } if (HX_FIELD_EQ(inName,"inputMouseDown") ) { inputMouseDown=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"stageMouseDown") ) { stageMouseDown=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"completionList") ) { completionList=inValue.Cast< ::flixel::_hx_system::debug::completion::CompletionList >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"registeredObjects") ) { registeredObjects=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 19: if (HX_FIELD_EQ(inName,"registeredFunctions") ) { registeredFunctions=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Console_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("registeredObjects",72,87,9b,2a)); outFields->push(HX_("registeredFunctions",79,8c,8a,1e)); outFields->push(HX_("registeredHelp",63,e5,ae,b7)); outFields->push(HX_("objectStack",09,84,3a,f3)); outFields->push(HX_("input",0a,c4,1d,be)); outFields->push(HX_("inputMouseDown",bd,fb,87,2d)); outFields->push(HX_("stageMouseDown",89,de,11,40)); outFields->push(HX_("history",54,35,47,64)); outFields->push(HX_("completionList",9a,d1,5d,23)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo Console_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Console_obj,registeredObjects),HX_("registeredObjects",72,87,9b,2a)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Console_obj,registeredFunctions),HX_("registeredFunctions",79,8c,8a,1e)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Console_obj,registeredHelp),HX_("registeredHelp",63,e5,ae,b7)}, {hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(Console_obj,objectStack),HX_("objectStack",09,84,3a,f3)}, {hx::fsObject /* ::openfl::text::TextField */ ,(int)offsetof(Console_obj,input),HX_("input",0a,c4,1d,be)}, {hx::fsBool,(int)offsetof(Console_obj,inputMouseDown),HX_("inputMouseDown",bd,fb,87,2d)}, {hx::fsBool,(int)offsetof(Console_obj,stageMouseDown),HX_("stageMouseDown",89,de,11,40)}, {hx::fsObject /* ::flixel::_hx_system::debug::console::ConsoleHistory */ ,(int)offsetof(Console_obj,history),HX_("history",54,35,47,64)}, {hx::fsObject /* ::flixel::_hx_system::debug::completion::CompletionList */ ,(int)offsetof(Console_obj,completionList),HX_("completionList",9a,d1,5d,23)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo Console_obj_sStaticStorageInfo[] = { {hx::fsString,(void *) &Console_obj::DEFAULT_TEXT,HX_("DEFAULT_TEXT",4b,9c,59,2d)}, { hx::fsUnknown, 0, null()} }; #endif static ::String Console_obj_sMemberFields[] = { HX_("registeredObjects",72,87,9b,2a), HX_("registeredFunctions",79,8c,8a,1e), HX_("registeredHelp",63,e5,ae,b7), HX_("objectStack",09,84,3a,f3), HX_("input",0a,c4,1d,be), HX_("inputMouseDown",bd,fb,87,2d), HX_("stageMouseDown",89,de,11,40), HX_("history",54,35,47,64), HX_("completionList",9a,d1,5d,23), HX_("createInputTextField",7f,2b,43,44), HX_("registerEventListeners",c8,2b,6e,76), HX_("update",09,86,05,87), HX_("onFocus",39,fe,c6,9a), HX_("onFocusLost",bd,e4,85,41), HX_("onKeyDown",42,22,f2,73), HX_("setText",6f,0d,7e,12), HX_("processCommand",9c,b2,cb,33), HX_("reposition",5c,6f,62,a5), HX_("registerFunction",9b,a8,15,13), HX_("registerObject",82,05,81,db), HX_("registerClass",d5,3a,c1,3d), HX_("registerEnum",04,ab,05,bf), HX_("destroy",fa,2c,86,24), HX_("updateSize",6a,8b,08,05), ::String(null()) }; static void Console_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Console_obj::DEFAULT_TEXT,"DEFAULT_TEXT"); }; #ifdef HXCPP_VISIT_ALLOCS static void Console_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Console_obj::DEFAULT_TEXT,"DEFAULT_TEXT"); }; #endif hx::Class Console_obj::__mClass; static ::String Console_obj_sStaticFields[] = { HX_("DEFAULT_TEXT",4b,9c,59,2d), ::String(null()) }; void Console_obj::__register() { Console_obj _hx_dummy; Console_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("flixel.system.debug.console.Console",98,1f,eb,2e); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = Console_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Console_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Console_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Console_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Console_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Console_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Console_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Console_obj::__boot() { { HX_STACKFRAME(&_hx_pos_c69022abc8c5c26b_36_boot) HXDLIN( 36) DEFAULT_TEXT = HX_("(Click here / press [Tab] to enter command. Type 'help' for help.)",f9,4e,c0,26); } } } // end namespace flixel } // end namespace system } // end namespace debug } // end namespace console
45.34456
264
0.728818
[ "3d" ]
458c2642c7efb81cfe709b1b06a1a8b2ba8ae21a
20,495
cpp
C++
coolkey/coolkey/src/coolkey/coolkey.cpp
OneIdentity/rc-legacy
6e247f55b7df6b1022819810ba3363a2db401f08
[ "Apache-2.0" ]
null
null
null
coolkey/coolkey/src/coolkey/coolkey.cpp
OneIdentity/rc-legacy
6e247f55b7df6b1022819810ba3363a2db401f08
[ "Apache-2.0" ]
null
null
null
coolkey/coolkey/src/coolkey/coolkey.cpp
OneIdentity/rc-legacy
6e247f55b7df6b1022819810ba3363a2db401f08
[ "Apache-2.0" ]
null
null
null
/* ***** BEGIN COPYRIGHT BLOCK ***** * Copyright (C) 2005 Red Hat, Inc. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version * 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***** END COPYRIGHT BLOCK *****/ #include "mypkcs11.h" #include <assert.h> #include <string> #include <map> #include <set> #include <memory> #include "log.h" #include "PKCS11Exception.h" #ifdef _WIN32 #include <windows.h> #endif #include <winscard.h> #include "slot.h" #include "cky_base.h" #include "params.h" #define NULL 0 /* static module data -------------------------------- */ static Log *log = NULL; static SlotList *slotList = NULL; static OSLock finalizeLock(false); static CK_BBOOL initialized = FALSE; static CK_BBOOL finalizing = FALSE; static CK_BBOOL waitEvent = FALSE; char *Params::params = NULL; // manufacturerID and libraryDescription should not be NULL-terminated, // so the last character is overwritten with a blank in C_GetInfo(). static CK_INFO ckInfo = { {2, 11}, "Mozilla Foundation ", 0, "CoolKey PKCS #11 Module ", {1, 0} }; typedef struct { CK_MECHANISM_TYPE mech; CK_MECHANISM_INFO info; } MechInfo; /********************************************************************** ************************** MECHANISM TABLE *************************** **********************************************************************/ static MechInfo mechanismList[] = { {CKM_RSA_PKCS, { 1024, 4096, CKF_HW | CKF_SIGN | CKF_DECRYPT } } }; static unsigned int numMechanisms = sizeof(mechanismList)/sizeof(MechInfo); /* ------------------------------------------------------------ */ void dumpTemplates(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { // no try here, let caller catch it. try { unsigned long i; if (!pTemplate) return; for (i = 0; i < ulCount; ++i) { CK_ATTRIBUTE_PTR pT = pTemplate + i; if (pT->pValue && pT->ulValueLen == 4) { log->log( "template [%02lu] type: %04lx, pValue: %08lx, ulValueLen: %08lx, value: %lu\n", i, pT->type, pT->pValue, pT->ulValueLen, *(CK_ULONG_PTR)pT->pValue); } else log->log("template [%02lu] type: %04lx, pValue: %08lx, ulValueLen: %08lx\n", i, pT->type, pT->pValue, pT->ulValueLen); } } /* PKCS11 defined functions ----------------------------------- */ #define NOTSUPPORTED(name, args) \ CK_RV name args \ { \ log->log(#name " called (notSupported)\n"); \ return CKR_FUNCTION_NOT_SUPPORTED; \ } #define SUPPORTED(name, name2, dec_args, use_args) \ CK_RV name dec_args \ { \ if( ! initialized ) { \ return CKR_CRYPTOKI_NOT_INITIALIZED; \ } \ try { \ log->log(#name " called\n"); \ slotList->name2 use_args ; \ return CKR_OK; \ } catch(PKCS11Exception& e) { \ e.log(log); \ return e.getCRV(); \ } \ } extern "C" { NOTSUPPORTED(C_InitToken,(CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR)) NOTSUPPORTED(C_InitPIN, (CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG)) NOTSUPPORTED(C_SetPIN, (CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG)) NOTSUPPORTED(C_GetOperationState, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR)) NOTSUPPORTED(C_SetOperationState, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE)) NOTSUPPORTED(C_CreateObject, (CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_CopyObject, (CK_SESSION_HANDLE,CK_OBJECT_HANDLE,CK_ATTRIBUTE_PTR,CK_ULONG,CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_DestroyObject, (CK_SESSION_HANDLE, CK_OBJECT_HANDLE)) NOTSUPPORTED(C_GetObjectSize, (CK_SESSION_HANDLE,CK_OBJECT_HANDLE,CK_ULONG_PTR)) NOTSUPPORTED(C_SetAttributeValue, (CK_SESSION_HANDLE,CK_OBJECT_HANDLE,CK_ATTRIBUTE_PTR,CK_ULONG)) NOTSUPPORTED(C_EncryptInit, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE)) NOTSUPPORTED(C_Encrypt, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR)) NOTSUPPORTED(C_EncryptUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_EncryptFinal, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DecryptUpdate,(CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DecryptFinal, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DigestInit, (CK_SESSION_HANDLE,CK_MECHANISM_PTR)) NOTSUPPORTED(C_Digest, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DigestUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG)) NOTSUPPORTED(C_DigestKey, (CK_SESSION_HANDLE,CK_OBJECT_HANDLE)) NOTSUPPORTED(C_DigestFinal, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR)) NOTSUPPORTED(C_SignUpdate, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG)) NOTSUPPORTED(C_SignFinal, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_SignRecoverInit, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE)) NOTSUPPORTED(C_SignRecover, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_VerifyInit, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE)) NOTSUPPORTED(C_Verify, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG)) NOTSUPPORTED(C_VerifyUpdate, (CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG)) NOTSUPPORTED(C_VerifyFinal, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG)) NOTSUPPORTED(C_VerifyRecoverInit, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE)) NOTSUPPORTED(C_VerifyRecover, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DigestEncryptUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DecryptDigestUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_SignEncryptUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_DecryptVerifyUpdate, (CK_SESSION_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_GenerateKey, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_ATTRIBUTE_PTR,CK_ULONG,CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_GenerateKeyPair, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_ATTRIBUTE_PTR,CK_ULONG,CK_ATTRIBUTE_PTR,CK_ULONG,CK_OBJECT_HANDLE_PTR,CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_WrapKey, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE,CK_OBJECT_HANDLE,CK_BYTE_PTR,CK_ULONG_PTR)) NOTSUPPORTED(C_UnwrapKey, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE,CK_BYTE_PTR,CK_ULONG,CK_ATTRIBUTE_PTR,CK_ULONG,CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_DeriveKey, (CK_SESSION_HANDLE,CK_MECHANISM_PTR,CK_OBJECT_HANDLE,CK_ATTRIBUTE_PTR,CK_ULONG,CK_OBJECT_HANDLE_PTR)) NOTSUPPORTED(C_GetFunctionStatus, (CK_SESSION_HANDLE)) NOTSUPPORTED(C_CancelFunction, (CK_SESSION_HANDLE)) /* non-specialized functions supported with the slotList object */ SUPPORTED(C_GetSlotList, getSlotList, (CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount), (tokenPresent, pSlotList, pulCount)) SUPPORTED(C_GetSessionInfo, getSessionInfo, (CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo), (hSession, pInfo) ) SUPPORTED(C_Logout, logout, (CK_SESSION_HANDLE hSession), (hSession)) SUPPORTED(C_Decrypt, decrypt, (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDecryptedData, CK_ULONG_PTR pulDecryptedDataLen), (hSession, pData, ulDataLen, pDecryptedData, pulDecryptedDataLen)) SUPPORTED(C_DecryptInit, decryptInit, (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey), (hSession, pMechanism, hKey)) SUPPORTED(C_SignInit, signInit, (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey), (hSession, pMechanism, hKey)) SUPPORTED(C_Sign, sign, (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen), (hSession, pData, ulDataLen, pSignature, pulSignatureLen)) SUPPORTED(C_SeedRandom, seedRandom, (CK_SESSION_HANDLE hSession ,CK_BYTE_PTR data,CK_ULONG dataLen), (hSession, data, dataLen)) SUPPORTED(C_GenerateRandom, generateRandom, (CK_SESSION_HANDLE hSession ,CK_BYTE_PTR data,CK_ULONG dataLen), (hSession, data, dataLen)) /* non-specialized functions supported with the slot directly */ CK_RV C_Initialize(CK_VOID_PTR pInitArgs) { try { if( initialized ) { return CKR_CRYPTOKI_ALREADY_INITIALIZED; } if (!finalizeLock.isValid()) { return CKR_CANT_LOCK; } CK_C_INITIALIZE_ARGS* initArgs = (CK_C_INITIALIZE_ARGS*) pInitArgs; if( initArgs != NULL ) { /* work around a bug in NSS where the library parameters are only * send if locking is requested */ if (initArgs->LibraryParameters) { Params::SetParams(strdup((char *)initArgs->LibraryParameters)); } else { Params::ClearParams(); } if( (initArgs->flags & CKF_OS_LOCKING_OK) || initArgs->LockMutex ){ throw PKCS11Exception(CKR_CANT_LOCK); } } char * logFileName = getenv("COOL_KEY_LOG_FILE"); if (logFileName) { if (strcmp(logFileName,"SYSLOG") == 0) { log = new SysLog(); } else { log = new FileLog(logFileName); } } else { log = new DummyLog(); } log->log("Initialize called, hello %d\n", 5); CKY_SetName("coolkey"); slotList = new SlotList(log); initialized = TRUE; return CKR_OK; } catch(PKCS11Exception &e) { if( log ) e.log(log); return e.getReturnValue(); } } CK_RV C_Finalize(CK_VOID_PTR pReserved) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } // XXX cleanup all data structures !!! //delete sessionManager; log->log("Finalizing...\n"); // don't race the setting of finalizing. If C_WaitEvent gets passed // the finalizing call first, we know it will set waitEvent before // we can get the lock, so we only need to protect setting finalizing // to true. finalizeLock.getLock(); finalizing = TRUE; finalizeLock.releaseLock(); if (waitEvent) { /* we're waiting on a slot event, shutdown first to allow * the wait function to complete before we pull the rug out. */ slotList->shutdown(); while (waitEvent) { OSSleep(500); } } delete slotList; delete log; finalizeLock.getLock(); finalizing = FALSE; initialized = FALSE; finalizeLock.releaseLock(); return CKR_OK; } CK_RV C_GetInfo(CK_INFO_PTR p) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } log->log("C_GetInfo called\n"); ckInfo.manufacturerID[31] = ' '; ckInfo.libraryDescription[31] = ' '; *p = ckInfo; return CKR_OK; } CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pSlotInfo) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("Called C_GetSlotInfo\n"); slotList->validateSlotID(slotID); return slotList->getSlot( slotIDToIndex(slotID))->getSlotInfo(pSlotInfo); } catch( PKCS11Exception &excep ) { excep.log(log); return excep.getCRV(); } } CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pTokenInfo) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_GetTokenInfo called\n"); slotList->validateSlotID(slotID); return slotList->getSlot( slotIDToIndex(slotID))->getTokenInfo(pTokenInfo); } catch( PKCS11Exception &excep ) { excep.log(log); return excep.getCRV(); } } CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { CK_RV rv = CKR_OK; log->log("C_GetMechanismList called\n"); if( pulCount == NULL ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->validateSlotID(slotID); if( ! slotList->getSlot( slotIDToIndex(slotID))->isTokenPresent() ) { return CKR_TOKEN_NOT_PRESENT; } if( pMechanismList != NULL ) { if( *pulCount < numMechanisms ) { rv = CKR_BUFFER_TOO_SMALL; } else { for(unsigned int i=0; i < numMechanisms; ++i ) { pMechanismList[i] = mechanismList[i].mech; } } } *pulCount = numMechanisms; log->log("C_GetMechanismList returning %d\n", rv); return rv; } catch(PKCS11Exception &excep ) { excep.log(log); return excep.getCRV(); } } CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_GetMechanismInfo called\n"); if( pInfo == NULL ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->validateSlotID(slotID); if( ! slotList->getSlot(slotIDToIndex(slotID))->isTokenPresent() ) { return CKR_TOKEN_NOT_PRESENT; } for(unsigned int i=0; i < numMechanisms; ++i ) { if( mechanismList[i].mech == type ) { *pInfo = mechanismList[i].info; log->log("C_GetMechanismInfo got info about %d\n", type); return CKR_OK; } } log->log("C_GetMechanismInfo failed to find info about %d\n", type); return CKR_MECHANISM_INVALID; // mechanism not in the list } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR phSession) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_OpenSession called\n"); slotList->validateSlotID(slotID); #ifdef LATER // the CSP isn't setting this bit right now. if( ! (flags & CKF_SERIAL_SESSION) ) { throw PKCS11Exception(CKR_SESSION_PARALLEL_NOT_SUPPORTED); } #endif if( phSession == NULL ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } Session::Type sessionType = (flags & CKF_RW_SESSION) ? Session::RW : Session::RO; slotList->openSession(sessionType, slotID, phSession); return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_CloseSession(CK_SESSION_HANDLE hSession) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_CloseSession(0x%x) called\n", hSession); // !!!XXX Hack // If nothing else, we need to logout the token when all // its sessions are closed. return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_CloseAllSessions(CK_SLOT_ID slotID) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_CloseAllSessions(0x%x) called\n", slotID); slotList->validateSlotID(slotID); // !!!XXX Hack // If nothing else, we need to logout the token when all // its sessions are closed. return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_FindObjectsInit called, %lu templates\n", ulCount); dumpTemplates(pTemplate, ulCount); if( pTemplate == NULL && ulCount != 0 ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->findObjectsInit(hSession, pTemplate, ulCount); return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount) { CK_ULONG count = 0; if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_FindObjects called, max objects = %lu\n", ulMaxObjectCount ); if( phObject == NULL && ulMaxObjectCount != 0 ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->findObjects(hSession, phObject, ulMaxObjectCount, pulObjectCount); count = *pulObjectCount; log->log("returned %lu objects:", count ); CK_ULONG i; for (i = 0; i < count; ++i) { log->log(" 0x%08lx", phObject[i]); } log->log("\n" ); return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } // we don't need to do any cleaup. We could check the session handle. return CKR_OK; } CK_RV C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_Login called\n"); if( userType != CKU_USER ) { throw PKCS11Exception(CKR_USER_TYPE_INVALID); } if( pPin == NULL ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->login(hSession, pPin, ulPinLen); return CKR_OK; } catch(PKCS11Exception &e) { e.log(log); return e.getCRV(); } } CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { if( ! initialized ) { return CKR_CRYPTOKI_NOT_INITIALIZED; } try { log->log("C_GetAttributeValue called, %lu templates for object 0x%08lx\n", ulCount, hObject); dumpTemplates(pTemplate, ulCount); if( pTemplate == NULL && ulCount != 0 ) { throw PKCS11Exception(CKR_ARGUMENTS_BAD); } slotList->getAttributeValue(hSession, hObject, pTemplate, ulCount); dumpTemplates(pTemplate, ulCount); return CKR_OK; } catch(PKCS11Exception& e) { CK_RV rv = e.getCRV(); e.log(log); if (rv == CKR_ATTRIBUTE_TYPE_INVALID || rv == CKR_BUFFER_TOO_SMALL) { dumpTemplates(pTemplate, ulCount); } return rv; } } /* * While the rest of the C_ calls are protected by the callers lock, * C_WaitForSlotEvent is guaranteed to be on a separate thread. * Make sure we are locking with C_Finalize, which is likely to be racing * with this function */ CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, CK_VOID_PTR pReserved) { finalizeLock.getLock(); if( ! initialized ) { finalizeLock.releaseLock(); return CKR_CRYPTOKI_NOT_INITIALIZED; } if (finalizing) { finalizeLock.releaseLock(); return CKR_CRYPTOKI_NOT_INITIALIZED; } waitEvent = TRUE; finalizeLock.releaseLock(); try { log->log("C_WaitForSlotEvent called\n"); slotList->waitForSlotEvent(flags, pSlot, pReserved); waitEvent = FALSE; return CKR_OK; } catch(PKCS11Exception& e) { e.log(log); waitEvent = FALSE; return e.getCRV(); } } CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR pPtr); #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO #define CK_PKCS11_FUNCTION_INFO(func) (CK_##func) func, static CK_FUNCTION_LIST functionList = { {2, 20}, // PKCS #11 spec version we support #include "pkcs11f.h" }; CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR pPtr) { if( pPtr == NULL ) { return CKR_ARGUMENTS_BAD; } *pPtr = &functionList; return CKR_OK; } } // end extern C
31.676971
163
0.678214
[ "object" ]
4592017ef97bb78362398713090af15eba916647
3,055
hpp
C++
Libs/MaterialSystem/Common/DepRelMatrix.hpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Libs/MaterialSystem/Common/DepRelMatrix.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Libs/MaterialSystem/Common/DepRelMatrix.hpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ /****************************************/ /*** Dependency Relationship Matrices ***/ /****************************************/ #ifndef CAFU_DEP_REL_MATRIX_HPP_INCLUDED #define CAFU_DEP_REL_MATRIX_HPP_INCLUDED #include "Math3D/Matrix.hpp" /// A matrix class with which dependencies among matrices can be handled. /// In order to model a specific dependency relationship, child classes should be derived from this class, /// see InverseMatrixT and ProductMatrixT for examples. /// Note that also the roots/parents/sources of the dep. relationships should (or at least: can) be matrix objects /// of the DepRelMatrixT class, because that helps to avoid unecessary updates of the dependents. class DepRelMatrixT { public: DepRelMatrixT(); DepRelMatrixT(const DepRelMatrixT& Other); virtual ~DepRelMatrixT() { } /// This method updates this matrix from the matrices it depends on (the source matrices). /// Derived classes are expected to overwrite this method in order to provide the desired behaviour. /// Their code should make good use of the Age member in order to minimize update efforts. /// User code should call this method before accessing the Matrix (or Age) member whenever /// there is a chance that the source matrices changed since the last call to Update(). virtual void Update() { } MatrixT Matrix; ///< The matrix. unsigned long Age; ///< The "age" or change-count of this matrix. How old the source matrix was when we were last updated. const unsigned long ID; ///< The unique ID of this matrix. Useful for unambiguous identification. private: static unsigned long GlobalIDCount; }; /// This class models the relationship with which a inverse matrix depends on its original matrix. class InverseMatrixT : public DepRelMatrixT { public: InverseMatrixT(DepRelMatrixT* Source=NULL); /// Sets the source matrix. Useful if InverseMatrixTs are stored in an array. void SetSourceMatrix(DepRelMatrixT* Source); /// Overwrite the base class method. virtual void Update(); private: DepRelMatrixT* m_Source; }; /// This class models the relationship with which a product matrix A*B depends on its components A and B /// (e.g.\ how a model-to-view matrix depends on the model-to-world and world-to-view matrices). /// /// Note that \code ProductMatrixT ModelView(WorldToView, ModelToWorld); \endcode would be the correct statement /// for a model-to-view matrix, whereas the opposite component order /// \code ProductMatrixT ModelView(ModelToWorld, WorldToView); \endcode is wrong. class ProductMatrixT : public DepRelMatrixT { public: ProductMatrixT(DepRelMatrixT& A, DepRelMatrixT& B); /// Overwrite the base class method. virtual void Update(); private: DepRelMatrixT& m_A; DepRelMatrixT& m_B; }; #endif
32.849462
139
0.705074
[ "model" ]
4592e19c59eb95f49d0d7f0d9ff8adcd4a3f3ad9
975
hpp
C++
code_examples/tensorflow/block_sparse/custom_ops/bsutils.hpp
payoto/graphcore_examples
46d2b7687b829778369fc6328170a7b14761e5c6
[ "MIT" ]
260
2019-11-18T01:50:00.000Z
2022-03-28T23:08:53.000Z
code_examples/tensorflow/block_sparse/custom_ops/bsutils.hpp
payoto/graphcore_examples
46d2b7687b829778369fc6328170a7b14761e5c6
[ "MIT" ]
27
2020-01-28T23:07:50.000Z
2022-02-14T15:37:06.000Z
code_examples/tensorflow/block_sparse/custom_ops/bsutils.hpp
payoto/graphcore_examples
46d2b7687b829778369fc6328170a7b14761e5c6
[ "MIT" ]
56
2019-11-18T02:13:12.000Z
2022-02-28T14:36:09.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #pragma once #include <poplar/Type.hpp> #include <popsparse/experimental/BlockSparse.hpp> #include <spdlog/spdlog.h> #include <array> #include <vector> #include <string> struct BsMatMulArgs { std::array<int, 3> dim; std::array<int, 3> blockSize; std::vector<unsigned char> sparsityMask; bool transposedRhs = false; poplar::Type dataType = poplar::FLOAT; poplar::Type partialDataType = poplar::FLOAT; int innerGroupSize = 0; std::string partitionMethod = "strip"; float memoryCycleRatio = 1.0f; }; BsMatMulArgs parseBsMatMulJsonArgs(const std::string& attributes); struct BsSoftmaxArgs { std::vector<int> dimDense; std::array<int, 2> blockSize; std::vector<unsigned char> sparsityMask; std::vector<popsparse::experimental::SubBlockMask> subBlockMaskType; int innerGroupSize = 0; }; BsSoftmaxArgs parseBsSoftmaxJsonArgs(const std::string& attributes); spdlog::logger* createLogger();
26.351351
70
0.745641
[ "vector" ]
45975f596e62ea7fa0bfa28f634ac7a6c8bfb687
5,724
cpp
C++
ALIZE_3.0/src/Distrib.cpp
ibillxia/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
83
2015-01-18T01:20:37.000Z
2022-03-02T20:15:27.000Z
ALIZE_3.0/src/Distrib.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
4
2016-03-03T08:43:00.000Z
2019-03-08T06:20:56.000Z
ALIZE_3.0/src/Distrib.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
59
2015-02-02T03:07:37.000Z
2021-11-22T12:05:42.000Z
/* This file is part of ALIZE which is an open-source tool for speaker recognition. ALIZE is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. ALIZE 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ALIZE. If not, see <http://www.gnu.org/licenses/>. ALIZE is a development project initiated by the ELISA consortium [alize.univ-avignon.fr/] and funded by the French Research Ministry in the framework of the TECHNOLANGUE program [www.technolangue.net] The ALIZE project team wants to highlight the limits of voice authentication in a forensic context. The "Person Authentification by Voice: A Need of Caution" paper proposes a good overview of this point (cf. "Person Authentification by Voice: A Need of Caution", Bonastre J.F., Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin- chagnolleau I., Eurospeech 2003, Genova]. The conclusion of the paper of the paper is proposed bellow: [Currently, it is not possible to completely determine whether the similarity between two recordings is due to the speaker or to other factors, especially when: (a) the speaker does not cooperate, (b) there is no control over recording equipment, (c) recording conditions are not known, (d) one does not know whether the voice was disguised and, to a lesser extent, (e) the linguistic content of the message is not controlled. Caution and judgment must be exercised when applying speaker recognition techniques, whether human or automatic, to account for these uncontrolled factors. Under more constrained or calibrated situations, or as an aid for investigative purposes, judicious application of these techniques may be suitable, provided they are not considered as infallible. At the present time, there is no scientific process that enables one to uniquely characterize a person=92s voice or to identify with absolute certainty an individual from his or her voice.] Contact Jean-Francois Bonastre for more information about the licence or the use of ALIZE Copyright (C) 2003-2010 Laboratoire d'informatique d'Avignon [lia.univ-avignon.fr] ALIZE admin [alize@univ-avignon.fr] Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr] */ #if !defined(ALIZE_Distrib_cpp) #define ALIZE_Distrib_cpp #include "Distrib.h" #include "DistribGD.h" #include "DistribGF.h" #include "Exception.h" using namespace alize; typedef Distrib D; //------------------------------------------------------------------------- D::Distrib(unsigned long vectSize) :Object(), _vectSize(vectSize), _det(0.0), _cst(0.0), _meanVect(vectSize, vectSize), _refCounter(0), _dictIndex(0) {} //------------------------------------------------------------------------- bool D::operator!=(const Distrib& d) const { return !(*this == d); } //------------------------------------------------------------------------- Distrib& D::duplicate(const K&) const { return clone(); } //------------------------------------------------------------------------- unsigned long D::getVectSize() const { return _vectSize; } //------------------------------------------------------------------------- real_t D::getMean(unsigned long i) const { return _meanVect[i]; } //------------------------------------------------------------------------- DoubleVector& D::getMeanVect() { return _meanVect; } //------------------------------------------------------------------------- const DoubleVector& D::getMeanVect() const { return _meanVect; } //------------------------------------------------------------------------- void D::setMean(const real_t v, const unsigned long i){ _meanVect[i] = v; } //------------------------------------------------------------------------- void D::setMeanVect(const DoubleVector& v) { _meanVect.setValues(v); } //------------------------------------------------------------------------- real_t D::getDet() const { return _det; } //------------------------------------------------------------------------- real_t D::getCst() const { return _cst; } //------------------------------------------------------------------------- void D::setDet(const K&, real_t v) { _det = v; } //------------------------------------------------------------------------- void D::setCst(const K&, real_t v) { _cst = v; } //------------------------------------------------------------------------- unsigned long& D::refCounter(const K&) { return _refCounter; } //------------------------------------------------------------------------- unsigned long& D::dictIndex(const K&) { return _dictIndex; } //------------------------------------------------------------------------- D::~Distrib() {} //------------------------------------------------------------------------- Distrib& D::create(const K&, const DistribType type, unsigned long vectSize) { if (type == DistribType_GD) return DistribGD::create(K::k, vectSize); if (type == DistribType_GF) return DistribGF::create(K::k, vectSize); throw Exception("Don't know how to create a distribution" + getDistribTypeName(type) + "'", __FILE__, __LINE__); return DistribGD::create(K::k, vectSize); // never called } //------------------------------------------------------------------------- #endif // !defined(ALIZE_Distrib_cpp)
49.344828
76
0.560797
[ "object" ]