hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
dcc228844073de0aa75390a5ac731493b40ee6f3
8,072
cc
C++
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
null
null
null
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2020 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/Application> #include <cc/TimeMaster> #include <cc/PlatformPlugin> #include <cc/PosGuard> #include <cc/InputControl> #include <cc/Process> #include <cc/Bmp> #include <cc/stdio> namespace cc { void Application::State::notifyTimer(const Timer &timer) { if (!timer) return; if (timer.interval() > 0) { TimeMaster{}.ack(); } timer.me().timeout_.emit(); } Application::State::State() { textInputArea.onChanged([this]{ if (focusControl()) setTextInputArea(textInputArea()); }); focusControl.onChanged([this]{ if (focusControlSaved_) stopTextInput(); focusControlSaved_ = focusControl(); if (focusControl()) { startTextInput(focusControl().window()); textInputArea([this]{ if (!focusControl()) return Rect{}; Rect a = focusControl().me().textInputArea(); return Rect{focusControl().mapToGlobal(a.pos()), a.size()}; }); setTextInputArea(textInputArea()); } else textInputArea = Rect{}; }); cursorControl.onChanged([this]{ if (cursorControl()) { cursor([this]{ return cursorControl() ? cursorControl().cursor() : Cursor{}; }); } else { cursor = Cursor{}; } }); cursor.onChanged([this]{ if (cursor()) setCursor(cursor()); else unsetCursor(); }); } bool Application::State::feedFingerEvent(const Window &window, FingerEvent &event) { if (cursorControl()) cursorControl = Control{}; if (hoverControl()) hoverControl = Control{}; showCursor(false); Point eventPos = window.size() * event.pos(); Control topControl = window.findControl(eventPos); if (topControl) { topControl->pointerPos = topControl.mapToLocal(eventPos); } if (event.action() == PointerAction::Moved) ; else if (event.action() == PointerAction::Pressed) { if (!pressedControl()) { pressedControl = topControl; } } else if (event.action() == PointerAction::Released) { if (focusControl() != pressedControl()) { focusControl = Control{}; } } bool eaten = false; if (pressedControl()) { eaten = pressedControl()->feedFingerEvent(event); if (event.action() == PointerAction::Released) { PosGuard guard{event, pressedControl().mapToLocal(eventPos)}; if ( pressedControl()->onPointerClicked(event) || pressedControl()->onFingerClicked(event) ) { eaten = true; } pressedControl = Control{}; } } if (!eaten) { eaten = window.view()->feedFingerEvent(event); } return eaten; } bool Application::State::feedMouseEvent(const Window &window, MouseEvent &event) { Control topControl = window.findControl(event.pos()); if (topControl) { topControl->pointerPos = topControl.mapToLocal(event.pos()); } if (event.action() == PointerAction::Moved) { hoverControl = topControl; } else if (event.action() == PointerAction::Pressed) { if (!pressedControl()) { pressedControl = topControl; if (topControl) captureMouse(true); } hoverControl = Control{}; } else if (event.action() == PointerAction::Released) { if (focusControl() != pressedControl()) { focusControl = Control{}; } hoverControl = topControl; } bool eaten = false; if (pressedControl()) { eaten = pressedControl()->feedMouseEvent(event); if (event.action() == PointerAction::Released) { PosGuard guard{event, pressedControl().mapToLocal(event.pos())}; if ( pressedControl()->onPointerClicked(event) || pressedControl()->onMouseClicked(event) ) { eaten = true; } pressedControl = Control{}; captureMouse(false); } } if (!eaten) { eaten = window.view()->feedMouseEvent(event); } cursorControl = topControl; showCursor(true); return eaten; } bool Application::State::feedWheelEvent(const Window &window, WheelEvent &event) { bool eaten = false; if (hoverControl()) eaten = hoverControl().me().feedWheelEvent(event); if (!eaten) eaten = window.view().me().feedWheelEvent(event); return eaten; } bool Application::State::feedKeyEvent(const Window &window, KeyEvent &event) { if ( event.scanCode() == ScanCode::Key_ScrollLock && event.action() == KeyAction::Pressed ) { takeScreenshot(window); return true; } if (focusControl()) { return focusControl().me().feedKeyEvent(event); } if ( event.scanCode() == ScanCode::Key_Tab && event.action() == KeyAction::Pressed && !(event.modifiers() & KeyModifier::Shift) && !(event.modifiers() & KeyModifier::Alt) && !(event.modifiers() & KeyModifier::Control) ) { List<InputControl> inputControls; window.view().collectVisible<InputControl>(&inputControls); if (inputControls.count() > 0) { inputControls.mutableAt(0).focus(true); } } return true; } bool Application::State::feedExposedEvent(const Window &window) { return window.view().me().feedExposedEvent(); } bool Application::State::feedEnterEvent(const Window &window) { return window.view().me().feedEnterEvent(); } bool Application::State::feedLeaveEvent(const Window &window) { hoverControl = Control{}; return window.view().me().feedLeaveEvent(); } bool Application::State::feedTextEditingEvent(const String &text, int start, int length) { if (focusControl()) { focusControl().me().onTextEdited(text, start, length); return true; } return false; } bool Application::State::feedTextInputEvent(const String &text) { if (focusControl()) { focusControl().me().onTextInput(text); return true; } return false; } void Application::State::takeScreenshot(const Window &window) { View view = window.view(); Image image{view.size()}; String path = Format{"%%.bmp"}.arg(fixed(System::now(), 0)); view.renderTo(image); Bmp::save(path, image); ferr() << "Written screenshot to file://" << Process::cwd() << "/" << path << nl; } void Application::State::disengage(const View &view) { if (view.isParentOf(hoverControl())) { hoverControl(Control{}); } if (view.isParentOf(pressedControl())) { pressedControl(Control{}); } if (view.isParentOf(focusControl())) { focusControl(Control{}); } if (view.isParentOf(cursorControl())) { cursorControl(Control{}); } if (view.isParentOf(focusControlSaved_)) { focusControlSaved_ = Control{}; } } Application::Application() { *this = platform().application(); } Application::Application(int argc, char *argv[]) { *this = platform().application(); me().init(argc, argv); } FontSmoothing Application::fontSmoothing() const { if (me().fontSmoothing_ == FontSmoothing::Default) return DisplayManager{}.defaultFontSmoothing(); return me().fontSmoothing_; } bool Application::pointerIsDragged(const PointerEvent &event, Point dragStart) const { double minDragDistance = event.is<MouseEvent>() ? minMouseDragDistance() : minFingerDragDistance(); return (event.pos() - dragStart).absPow2() >= minDragDistance * minDragDistance; } void Application::postEvent(Fun<void()> &&doNext) { me().postEvent(move(doNext)); } Application app() { return platform().application(); } } // namespace cc
24.24024
103
0.594896
frankencode
dcc40eb7eb4ca5a842c1d7db4b9ed4e93b1dc0a1
4,395
cc
C++
biod/ec_command_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
biod/ec_command_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
biod/ec_command_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2019 The Chromium OS 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 <gmock/gmock.h> #include <gtest/gtest.h> #include "biod/ec_command.h" using testing::_; using testing::InvokeWithoutArgs; using testing::Return; namespace biod { namespace { constexpr int kDummyFd = 0; constexpr int kIoctlFailureRetVal = -1; template <typename O, typename I> class MockEcCommand : public EcCommand<O, I> { public: using EcCommand<O, I>::EcCommand; ~MockEcCommand() override = default; using Data = typename EcCommand<O, I>::Data; MOCK_METHOD(int, ioctl, (int fd, uint32_t request, Data* data)); }; class MockFpModeCommand : public MockEcCommand<struct ec_params_fp_mode, struct ec_response_fp_mode> { public: MockFpModeCommand() : MockEcCommand(EC_CMD_FP_MODE, 0, {.mode = 1}) {} }; // ioctl behavior for EC commands: // returns sizeof(EC response) (>=0) on success, -1 on failure // cmd.result is error code from EC (EC_RES_SUCCESS, etc) TEST(EcCommand, Run_Success) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl).WillOnce(Return(mock.RespSize())); EXPECT_TRUE(mock.Run(kDummyFd)); } TEST(EcCommand, Run_IoctlFailure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl).WillOnce(Return(kIoctlFailureRetVal)); EXPECT_FALSE(mock.Run(kDummyFd)); } TEST(EcCommand, Run_CommandFailure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { // Test the case where the ioctl itself succeeds, the but the EC // command did not. In this case, "result" will be set, but the // response size will not match the command's response size. data->cmd.result = EC_RES_ACCESS_DENIED; return 0; }); EXPECT_FALSE(mock.Run(kDummyFd)); } TEST(EcCommand, ConstReq) { const MockFpModeCommand mock; EXPECT_TRUE(mock.Req()); } TEST(EcCommand, ConstResp) { const MockFpModeCommand mock; EXPECT_TRUE(mock.Resp()); } TEST(EcCommand, Run_CheckResult_Success) { constexpr int kExpectedResult = 42; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { data->cmd.result = kExpectedResult; return data->cmd.insize; }); EXPECT_TRUE(mock.Run(kDummyFd)); EXPECT_EQ(mock.Result(), kExpectedResult); } TEST(EcCommand, Run_CheckResult_Failure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { // Note that it's not expected that the result would be set by the // kernel driver in this case, but we want to be defensive against // the behavior in case there is an instance where it does. data->cmd.result = EC_RES_ERROR; return kIoctlFailureRetVal; }); EXPECT_FALSE(mock.Run(kDummyFd)); EXPECT_EQ(mock.Result(), kEcCommandUninitializedResult); } TEST(EcCommand, RunWithMultipleAttempts_Success) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .Times(kNumAttempts) // First ioctl() fails .WillOnce(InvokeWithoutArgs([]() { errno = ETIMEDOUT; return kIoctlFailureRetVal; })) // Second ioctl() succeeds .WillOnce(Return(mock.RespSize())); EXPECT_TRUE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } TEST(EcCommand, RunWithMultipleAttempts_Timeout_Failure) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .Times(kNumAttempts) // All calls to ioctl() timeout .WillRepeatedly(InvokeWithoutArgs([]() { errno = ETIMEDOUT; return kIoctlFailureRetVal; })); EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } TEST(EcCommand, RunWithMultipleAttempts_ErrorNotTimeout_Failure) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) // Errors other than timeout should cause immediate failure even when // attempting retries. .Times(1) .WillOnce(InvokeWithoutArgs([]() { errno = EINVAL; return kIoctlFailureRetVal; })); EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } } // namespace } // namespace biod
30.10274
76
0.698521
kalyankondapally
dcc869cf1d46f33d81b28dd7a3d0131fb0832472
1,857
cxx
C++
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2021-06-11T20:36:16.000Z
2021-06-11T20:36:16.000Z
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2017-03-14T15:11:43.000Z
2017-03-14T15:53:09.000Z
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2018-09-22T01:09:25.000Z
2018-09-22T01:09:25.000Z
#include "AliAnalysisTaskEventCutsValidation.h" // ROOT includes #include <TChain.h> #include <TH2F.h> #include <TList.h> // ALIROOT includes #include "AliAODEvent.h" #include "AliAODHeader.h" #include "AliAODTrack.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliVEvent.h" ///\cond CLASSIMP ClassImp(AliAnalysisTaskEventCutsValidation); ///\endcond /// Standard and default constructor of the class. /// /// \param taskname Name of the task /// \param partname Name of the analysed particle /// AliAnalysisTaskEventCutsValidation::AliAnalysisTaskEventCutsValidation(bool storeCuts, TString taskname) : AliAnalysisTaskSE(taskname.Data()), fEventCut(false), fList(nullptr), fStoreCuts(storeCuts) { DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); if (storeCuts) DefineOutput(2, AliEventCuts::Class()); } /// Standard destructor /// AliAnalysisTaskEventCutsValidation::~AliAnalysisTaskEventCutsValidation() { if (fList) delete fList; } /// This function creates all the histograms and all the objects in general used during the analysis /// \return void /// void AliAnalysisTaskEventCutsValidation::UserCreateOutputObjects() { fList = new TList(); fList->SetOwner(true); fEventCut.AddQAplotsToList(fList,true); PostData(1,fList); if (fStoreCuts) PostData(2,&fEventCut); } /// This is the function that is evaluated for each event. The analysis code stays here. /// /// \param options Deprecated parameter /// \return void /// void AliAnalysisTaskEventCutsValidation::UserExec(Option_t *) { AliVEvent* ev = InputEvent(); fEventCut.AcceptEvent(ev); PostData(1,fList); if (fStoreCuts) PostData(2,&fEventCut); return; } /// Merge the output. Called once at the end of the query. /// /// \return void /// void AliAnalysisTaskEventCutsValidation::Terminate(Option_t *) { return; }
24.116883
106
0.740442
AudreyFrancisco
dcc9cf2a648f6f4c0768a1b376fc711fe500e9bc
1,216
cpp
C++
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
1
2022-03-28T07:52:21.000Z
2022-03-28T07:52:21.000Z
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include <core/view.hpp> #include <dml/detail/ml/result.hpp> namespace dml::detail::ml { detail::execution_status get_status(completion_record &record) noexcept { return static_cast<execution_status>(0b111111 & core::any_completion_record(record).status()); } detail::result_t get_result(completion_record &record) noexcept { return core::any_completion_record(record).result(); } detail::transfer_size_t get_bytes_completed(completion_record &record) noexcept { return core::any_completion_record(record).bytes_completed(); } detail::transfer_size_t get_delta_record_size(completion_record &record) noexcept { return core::make_view<core::operation::create_delta>(record).delta_record_size(); } detail::transfer_size_t get_crc_value(completion_record &record) noexcept { return core::make_view<core::operation::crc>(record).crc_value(); } } // namespace dml::detail::ml
32
102
0.621711
hhb584520
dcceb8b3b20685b8b2bb61e847810b3470c47996
403
hpp
C++
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
null
null
null
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
1
2019-08-16T21:18:21.000Z
2019-08-16T21:18:21.000Z
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
4
2019-09-02T14:06:08.000Z
2020-02-20T05:36:46.000Z
#pragma once #include "Spike/Synapses/Synapses.hpp" namespace Backend { namespace Dummy { class Synapses : public virtual ::Backend::Synapses { public: ~Synapses() override = default; void prepare() override; void reset_state() override; void copy_to_frontend() override; void copy_to_backend() override; }; } // namespace Dummy } // namespace Backend
20.15
57
0.665012
elliotelliot
dcced838bfab5c139c3d430666f146f38aca72c2
3,451
cpp
C++
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
1
2020-10-11T08:10:53.000Z
2020-10-11T08:10:53.000Z
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
#include "LeetCodeLib.h" class Solution { public: // iterative approach int calculate(string s) { int result = 0; int sign = 1; stack<int> st; for (int i = 0; i < s.size(); i++) { // get the number from string if (s[i] >= '0') { int num = 0; while (i < s.size() && s[i] >= '0') { num *= 10; num += int(s[i]) - '0'; i++; } i--; result += num * sign; } else if (s[i] == '+') { sign = 1; } else if (s[i] == '-') { sign = -1; } else if (s[i] == '(') { st.push(result); st.push(sign); result = 0; sign = 1; } else if (s[i] == ')') { sign = st.top(); st.pop(); result *= sign; result += st.top(); st.pop(); } } return result; } // prev own approach // #define LEFT_PARA_VALUE -999999 /* -999999 represents '('*/ // stack<int> reverse, order; // int calculate(string s) { // int result = 0; // // for (int i = 0; i < s.size(); ++i) { // if (s[i] == ' ') { // continue; // } // if(s[i]=='('){ // reverse.push(LEFT_PARA_VALUE); // continue; // } // if (s[i] == ')') { // while (reverse.top() != LEFT_PARA_VALUE/*represents '('*/) { // order.push(reverse.top()); // reverse.pop(); // } // reverse.pop();// get rid of "(" // result = calculatePara(); // reverse.push(result); // } else { // // check each input is a num or not // if (isdigit(s[i])) { // string numString = s.substr(i, 20); // int num = stoi(numString); // reverse.push(num); // i += to_string(num).size() - 1; // } else { // reverse.push((s[i])); // } // } // } // // // handle all nums in () // if (reverse.empty()) { // return result; // } else { // while (!reverse.empty()) { // order.push(reverse.top()); // reverse.pop(); // } // return calculatePara(); // } // } // // int calculatePara() { // if(order.empty()){ // cout<<"Problem in order stack"<<endl; // return 0; // } // int result = (order.top()), right; // int op; // order.pop(); // // do operations on each num // while (!order.empty()) { // op = order.top(); // order.pop(); // right = order.top(); // order.pop(); // if (op == '+') { // result = result + right; // } else { // result = result - right; // } // } // return result; // } }; string stringToString(string input) { assert(input.length() >= 2); string result; for (int i = 1; i < input.length() - 1; i++) { char currentChar = input[i]; if (input[i] == '\\') { char nextChar = input[i + 1]; switch (nextChar) { case '\"': result.push_back('\"'); break; case '/' : result.push_back('/'); break; case '\\': result.push_back('\\'); break; case 'b' : result.push_back('\b'); break; case 'f' : result.push_back('\f'); break; case 'r' : result.push_back('\r'); break; case 'n' : result.push_back('\n'); break; case 't' : result.push_back('\t'); break; default: break; } i++; } else { result.push_back(currentChar); } } return result; } int main() { string line; while (getline(cin, line)) { string s = stringToString(line); int ret = Solution().calculate(s); string out = to_string(ret); cout << out << endl; } return 0; } /* * testcase * "1 + 1"=2 * "(1+(4+5+2)-3)+(6+8)"=23 * */
19.833333
67
0.474065
yuyangh
dcd1f03705bda70716cfff206fff0721f0f39208
2,928
cp
C++
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
/***** * TFractalViewerWindow.c * * The window methods for the application. * * TFractalViewerWindow inherits its Draw method from TWindow. * TMandelbrot, TJulia, and others override DrawShape to draw their own kind of CGI. * *****/ #include <Packages.h> // for NumToString prototype #include "TFractalViewerWindow.h" #include <stdlib.h> #include "Utils.h" /**** * TFractalViewerWindow constructor * * Create a bullseye window. This constructor relies * on the TWindow constructor to place the window in * in attractive place. Then it appends a number to the * window title. * ****/ TFractalViewerWindow::TFractalViewerWindow(void) { Str15 numStr; Str255 title; long windowNumber; // Set the title of the window to be // the title in the resource // plus the window counter. // The window counter is a class variable // declared in the TWindow class. GetWindowTitle(title); windowNumber = GetWindowNumber(); NumToString(GetWindowNumber(), numStr); concat(title, numStr); SetWindowTitle(title); } /**** * Hit * * Handle a mouse down in the window. * Bullseye window just force a refresh. * ****/ void TFractalViewerWindow::Hit(Point where) { RefreshWindow(false); // preserve the scroll bars } /**** * GetStyle * SetStyle * * Get and set the color style * ****/ short TFractalViewerWindow::GetStyle() { return style; } void TFractalViewerWindow::SetStyle(short w) { style = w; RefreshWindow(true); } short TFractalViewerWindow::GetDrawMode() { return drawMode; } void TFractalViewerWindow::SetDrawMode(short m) { if (drawMode != m) { drawMode = m; RefreshWindow(true); } } /**** * Draw * * Draw the bullseye figures. * Repeatedly call DrawShape with a smaller drawing area. * The drawing area gets smaller by 2 * the width. * ****/ void TFractalViewerWindow::Draw(void) { RgnHandle saveClip = NewRgn(); PenState pen; Rect drawingRect; GetPenState(&pen); GetClip(saveClip); inherited::Draw(); GetWindowRect(&drawingRect, false); // Don't draw in the scroll // bar areas. Note that it's // ok to pass the address of // drawingRect because // GetWindowRect won't move // memory. sTop = drawingRect.top; sLeft = drawingRect.left; DrawShape(&drawingRect); SetClip(saveClip); DisposeRgn(saveClip); SetPenState(&pen); } /**** * DrawShape methods * * These are the DrawShape methods for * TBullWindow: does nothing * TCircleBull: Circles * TSquareBull: Squares * TPlasma: "Triangles" * * All the DrawShape methods take a drawingRect * as a parameter. The pen width * is already set to the appropriate width. * ****/ void TFractalViewerWindow::DrawShape(Rect *drawingRect) { } // // ZOOM CONTENT // void TFractalViewerWindow::ZoomContent(short z) { RefreshWindow(false); // preserve the scroll bars }
2,928
2,928
0.676913
pfuentes69
dcd24d5a9b94a8f29c988684fd2c44d7ab91e342
1,105
cpp
C++
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
4,526
2015-01-01T15:31:00.000Z
2022-03-31T17:33:49.000Z
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
4,497
2015-01-01T15:29:12.000Z
2022-03-31T19:19:35.000Z
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
3,023
2015-01-01T18:40:53.000Z
2022-03-30T13:30:46.000Z
#include <cstring> #include <stdexcept> #include "common.hpp" class TestHandler123 : public osmium::handler::Handler { public: TestHandler123() : osmium::handler::Handler() { } void way(const osmium::Way& way) const { if (way.id() == 123800) { REQUIRE(way.version() == 1); REQUIRE(way.nodes().size() == 2); REQUIRE(way.nodes()[0] != way.nodes()[1]); REQUIRE(way.nodes()[0].location() == way.nodes()[1].location()); } else { throw std::runtime_error{"Unknown ID"}; } } }; // class TestHandler123 TEST_CASE("123") { osmium::io::Reader reader{dirname + "/1/123/data.osm"}; index_pos_type index_pos; index_neg_type index_neg; location_handler_type location_handler{index_pos, index_neg}; location_handler.ignore_errors(); CheckBasicsHandler check_basics_handler{123, 2, 1, 0}; CheckWKTHandler check_wkt_handler{dirname, 123}; TestHandler123 test_handler; osmium::apply(reader, location_handler, check_basics_handler, check_wkt_handler, test_handler); }
25.697674
99
0.637104
zhaitianduo
dcddf1ed62acf71cefecdfbb5e14b82b07b2098d
6,223
hpp
C++
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
39
2015-01-01T07:59:51.000Z
2021-10-01T18:11:46.000Z
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
1
2019-04-24T09:56:15.000Z
2019-04-24T14:45:46.000Z
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
18
2015-01-11T15:10:23.000Z
2022-02-24T20:02:10.000Z
/*========================================================================= * * Copyright David Doria 2012 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef DilatedVarianceDifferenceAcceptanceVisitor_HPP #define DilatedVarianceDifferenceAcceptanceVisitor_HPP #include <boost/graph/graph_traits.hpp> // Parent class #include "Visitors/AcceptanceVisitors/AcceptanceVisitorParent.h" // Custom #include <Mask/Mask.h> #include <ITKHelpers/ITKHelpers.h> // ITK #include "itkImage.h" #include "itkImageRegion.h" /** */ template <typename TGraph, typename TImage> struct DilatedVarianceDifferenceAcceptanceVisitor : public AcceptanceVisitorParent<TGraph> { TImage* Image; Mask* MaskImage; const unsigned int HalfWidth; unsigned int NumberOfFinishedVertices = 0; float DifferenceThreshold; typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType; DilatedVarianceDifferenceAcceptanceVisitor(TImage* const image, Mask* const mask, const unsigned int halfWidth, const float differenceThreshold = 100) : Image(image), MaskImage(mask), HalfWidth(halfWidth), DifferenceThreshold(differenceThreshold) { } bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override { //std::cout << "DilatedVarianceDifferenceAcceptanceVisitor::AcceptMatch" << std::endl; itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target); itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth); itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source); itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth); //std::cout << "Extracting target region mask..." << std::endl; Mask::Pointer targetRegionMask = Mask::New(); ITKHelpers::ExtractRegion(MaskImage, targetRegion, targetRegionMask.GetPointer()); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(targetRegionMask.GetPointer(), targetRegionMask->GetHoleValue()) << " hole pixels in the target region." << std::endl; //std::cout << "Dilating target region mask..." << std::endl; Mask::Pointer dilatedTargetRegionMask = Mask::New(); ITKHelpers::DilateImage(targetRegionMask.GetPointer(), dilatedTargetRegionMask.GetPointer(), 6); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetHoleValue()) << " dilated hole pixels in the target region." << std::endl; // Separate so that only the newly dilated part of the hole remains //std::cout << "XORing dilated target mask with target mask..." << std::endl; typedef itk::Image<bool, 2> BoolImage; BoolImage::Pointer rindImage = BoolImage::New(); // "rind" like an "orange rind" ITKHelpers::XORRegions(targetRegionMask.GetPointer(), targetRegionMask->GetLargestPossibleRegion(), dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetLargestPossibleRegion(), rindImage.GetPointer()); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(rindImage.GetPointer(), true) << " XORed hole pixels in the target region." << std::endl; std::vector<itk::Index<2> > rindPixels = ITKHelpers::GetPixelsWithValue(rindImage.GetPointer(), rindImage->GetLargestPossibleRegion(), true); //std::cout << "There are " << rindPixels.size() << " rindPixels." << std::endl; std::vector<itk::Offset<2> > rindOffsets = ITKHelpers::IndicesToOffsets(rindPixels, ITKHelpers::ZeroIndex()); //std::cout << "There are " << rindOffsets.size() << " rindOffsets." << std::endl; //std::cout << "Computing variances..." << std::endl; // Compute the variance of the rind pixels in the target region std::vector<itk::Index<2> > targetRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, targetRegion.GetIndex()); //std::cout << "There are " << targetRindPixels.size() << " targetRindPixels." << std::endl; //std::cout << "Computing target variances..." << std::endl; typename TImage::PixelType targetRegionSourcePixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, targetRindPixels); //std::cout << "targetRegionSourcePixelVariance: " << targetRegionSourcePixelVariance << std::endl; // Compute the variance of the rind pixels in the source region std::vector<itk::Index<2> > sourceRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, sourceRegion.GetIndex()); //std::cout << "There are " << sourceRindPixels.size() << " targetRindPixels." << std::endl; //std::cout << "Computing source variances..." << std::endl; typename TImage::PixelType sourceRegionTargetPixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, sourceRindPixels); //std::cout << "sourceRegionTargetPixelVariance: " << sourceRegionTargetPixelVariance << std::endl; // Compute the difference computedEnergy = (targetRegionSourcePixelVariance - sourceRegionTargetPixelVariance).GetNorm(); std::cout << "DilatedVarianceDifferenceAcceptanceVisitor Energy: " << computedEnergy << std::endl; if(computedEnergy < DifferenceThreshold) { std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match accepted (less than " << DifferenceThreshold << ")" << std::endl; return true; } else { std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match rejected (greater than " << DifferenceThreshold << ")" << std::endl; return false; } }; }; #endif
49.388889
208
0.703198
jingtangliao
dcdf01b01665dec4690b9d0213b32be1f7039302
7,145
cpp
C++
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
1
2021-07-26T16:27:28.000Z
2021-07-26T16:27:28.000Z
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
3
2020-10-23T22:59:07.000Z
2020-10-23T23:02:35.000Z
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
1
2022-01-18T04:57:14.000Z
2022-01-18T04:57:14.000Z
/* * See header for notes. */ #include "vfd_task.h" #include "board_defs.h" #include "catch_errors.h" #include "packet_utils.h" #include "string.h" // memcpy #include "vfd_defs.h" VfdTask::VfdTask( // const char* name, UartTasks& uart, Writable& target, TaskUtilitiesArg& utilArg, UBaseType_t priority) : uart{ uart } , target{ target } , util{ utilArg } , task{ name, funcWrapper, this, priority } , bus{ uart, responseDelayMs, target, packet, util } {} void VfdTask::func() { // Assuming sequential address, including broadcast address (0) // Todo - more flexible address configuration const uint8_t numNodes = 3; // node 1, 2, and broadcast // const uint8_t numNodes = 6; // nodes 1-5, and broadcast uint16_t lastFrequency[numNodes]; for (int i = 0; i < numNodes; i++) { lastFrequency[i] = -1; // invalid, max of 4000 } uint16_t setFrequency[numNodes] = { 0 }; // Which address we're focusing on updating. // Address 0 is broadcast, which does not get any responses. uint8_t focus = 0; util.watchdogRegisterTask(); while (1) { util.watchdogKick(); // Collect all incoming host commands before deciding what modbus commands to send while (msgbuf.read(&packet, sizeof(packet), 0)) { switch (packet.id) { case PacketID::VfdSetFrequency: { uint8_t node = packet.body.vfdSetFrequency.node; uint16_t freq = packet.body.vfdSetFrequency.frequency; util.logln( // "%s got command to set vfd %u frequency to %u.%u Hz", pcTaskGetName(task.handle), node, freq / 10, freq % 10); if (node < numNodes) { setFrequency[node] = freq; } else { util.logln( // "%s got invalid address %u, exceeds %u", pcTaskGetName(task.handle), node, numNodes - 1); } break; } default: util.logln( // "%s doesn't know what to do with packet id: %s", pcTaskGetName(task.handle), packetIdToString(packet.id)); critical(); break; } } // For each address in round-robbin fashion, // create a modbus "Request" packet to send. // If there's a new frequency setpoint, send that, // otherwise request status. focus += 1; focus %= numNodes; if (setFrequency[focus] != lastFrequency[focus]) { // Write frequency value bus.outPkt->nodeAddress = focus; bus.outPkt->command = FunctionCode::WriteSingleRegister; bus.outPkt->writeSingleRegisterRequest.registerAddress = frequencyRegAddress; bus.outPkt->writeSingleRegisterRequest.data = setFrequency[focus]; } else { // Don't broadcast status request. Won't get a response. if (focus == 0) { continue; } // Read status registers bus.outPkt->nodeAddress = focus; bus.outPkt->command = FunctionCode::ReadMultipleRegisters; bus.outPkt->readMultipleRegistersRequest.startingAddress = statusRegAddress; bus.outPkt->readMultipleRegistersRequest.numRegisters = statusRegNum; } // Set origin for all outgoing reporting packets. // Note that this packet is reused by modbus driver. packet.origin = PacketOrigin::TargetToHost; uint32_t respLen = bus.sendRequest(); // Special handling for broadcast messages if (respLen == 1 && bus.outPkt->nodeAddress == 0) { // If frequency setpoint update if (bus.outPkt->command == FunctionCode::WriteSingleRegister && // __builtin_bswap16(bus.outPkt->writeSingleRegisterRequest.registerAddress) == frequencyRegAddress) { // Only update last frequency setpoint if write succeeded. // Otherwise, will attempt retransmission next lap. // For broadcast, failure could be due to a bad echo. lastFrequency[focus] = setFrequency[focus]; } else { error("Unexpected modbus broadcast"); } // Successful non-broadcast requests } else if (respLen) { switch (bus.inPkt->command) { case FunctionCode::ReadMultipleRegisters: { // The requested register is not returned in the response, // and the outgoing request packet inverted endianness, so // need to reverse that conversion. uint16_t regAddr = __builtin_bswap16(bus.outPkt->readMultipleRegistersRequest.startingAddress); switch (regAddr) { case statusRegAddress: // Response size is already verified by modbus driver. // Form packet for reporting setPacketIdAndLength(packet, PacketID::VfdStatus); packet.body.vfdStatus.nodeAddress = bus.inPkt->nodeAddress; memcpy(&packet.body.vfdStatus.payload, bus.inPkt->readMultipleRegistersResponse.payload, sizeof(VfdStatus::payload)); // Report result of modbus request util.write(target, &packet, packet.length); break; default: // util.logln("Unexpected multi-reg modbus read response at address 0x%x", regAddr); break; } break; } case FunctionCode::WriteSingleRegister: { uint16_t regAddr = bus.inPkt->writeSingleRegisterResponse.registerAddress; switch (regAddr) { case frequencyRegAddress: util.logln( // "node %u: wrote frequency %u, %u.%u Hz", bus.inPkt->nodeAddress, bus.inPkt->writeSingleRegisterResponse.data, bus.inPkt->writeSingleRegisterResponse.data / 10, bus.inPkt->writeSingleRegisterResponse.data % 10); // Only update last frequency setpoint if write succeeded. // Otherwise, will attempt retransmission next lap. lastFrequency[focus] = setFrequency[focus]; break; default: // util.logln("Unexpected single-reg modbus write response at address 0x%x", regAddr); break; } } case FunctionCode::WriteMultipleRegisters: // not expecting anything for this yet case FunctionCode::Exception: // error bit convenience default: // util.logln( // "node %u unexpected modbus response command 0x%x - possible exception", bus.outPkt->nodeAddress, bus.inPkt->command); VfdErrorDbgPinHigh(); VfdErrorDbgPinLow(); VfdErrorDbgPinHigh(); // Hold to allow capture by low sample rate scope osDelay(1); VfdErrorDbgPinLow(); break; } bus.shiftOutConsumedBytes(respLen); } else { util.logln("node %u: Unsuccessful modbus request", bus.outPkt->nodeAddress); VfdErrorDbgPinHigh(); // Hold to allow capture by low sample rate scope osDelay(1); VfdErrorDbgPinLow(); } } } size_t VfdTask::write(const void* buf, size_t len, TickType_t ticks) { return msgbuf.write(buf, len, ticks); }
32.330317
131
0.613436
milesfrain
dcdf739247cfd9069822d09dcb438ea035b20678
463
cpp
C++
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
#include <exodus/library.h> libraryinit() function main(in x, in y, in x2, in y2, in readwrite, io buffer) { //TODO implement if screen handling required //VIDEO.RW(0,0,@CRTWIDE-1,@CRTHIGH-1,'R',startBUFFER) //eg to copy a whole screen sized 80x25, use 0,0,79,24 //R=Read, W=Write //evade warning "usused" false and x and y and x2 and y2 and readwrite; if (readwrite=="R") { buffer=""; } else if (readwrite=="W") { } return 0; } libraryexit()
18.52
66
0.660907
BOBBYWY
dce1a9d48c363461b86d90f7c8ebc32d37e1fe13
6,887
cpp
C++
editor/src/editor.cpp
gabyrobles93/worms-game-remake
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
2
2019-04-24T18:27:29.000Z
2020-04-06T17:15:34.000Z
editor/src/editor.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
editor/src/editor.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <SDL2/SDL.h> #include <QApplication> #include <QMessageBox> #include <QDebug> #include "editor.h" #include "yaml.h" #include "map_game.h" #include "yaml.h" #include "inventory.h" #include "inventory_editor.h" #define EXIT_PADDING 5 #define EXIT_ICON_SIDE 20 #define SAVE_PADDING 10 #define SAVE_ICON_SIDE 60 Editor::Editor(YAML::Node map, std::string mn, std::string bgn, std::string bgp) : bg_name(bgn), bg_path(bgp), map_name(mn), mapNode(YAML::Clone(map)), staticNode(mapNode["static"]), mapGame(mapNode), editorWindow(staticNode, 0, 0, true, true), camera(editorWindow.getScreenWidth(), editorWindow.getScreenHeight(), editorWindow.getBgWidth(), editorWindow.getBgHeight()), renderer(editorWindow.getRenderer()), editorInventory(renderer, mapNode["static"]["teams_amount"].as<int>(), mapNode["static"]["worms_health"].as<int>()) { this->teamsAmount = mapNode["static"]["teams_amount"].as<int>(); this->wormsHealth = mapNode["static"]["worms_health"].as<int>(); this->editorInventory.toggleOpen(); this->mapGame.setRenderer(this->renderer); this->mapGame.initializeStates(); this->mapGame.createMapToSave(); this->exitTexture.loadFromFile(gPath.PATH_EXIT_ICON, this->renderer); this->exitTexture.setX(this->editorWindow.getScreenWidth() - EXIT_PADDING - EXIT_ICON_SIDE); this->exitTexture.setY(EXIT_PADDING); this->saveTexture.loadFromFile(gPath.PATH_SAVE_ICON, this->renderer); this->saveTexture.setX(this->editorWindow.getScreenWidth() - SAVE_PADDING - SAVE_ICON_SIDE); this->saveTexture.setY(EXIT_PADDING + EXIT_ICON_SIDE + SAVE_PADDING); this->unsaved_changes = false; this->notice.setScreenWidth(this->editorWindow.getScreenWidth()); this->notice.setScreenHeight(this->editorWindow.getScreenHeight()); } int Editor::start(void) { bool quit = false; SDL_Event e; while (!quit) { int camX = camera.getX(), camY = camera.getY(); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; editorWindow.hide(); validMap = mapGame.hasWorms(); if (!validMap) { QMessageBox msgBox; msgBox.setWindowTitle("Mapa inválido."); msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { editorWindow.show(); quit = false; } } } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_z && (e.key.keysym.mod & KMOD_CTRL)) { mapGame.setPreviousState(editorInventory); } if (e.key.keysym.sym == SDLK_y && (e.key.keysym.mod & KMOD_CTRL)) { mapGame.setNextState(editorInventory); } } if (e.type == SDL_MOUSEBUTTONDOWN) { int mouseX, mouseY; SDL_GetMouseState(&mouseX, &mouseY); if (e.button.button == SDL_BUTTON_LEFT) { if ( mouseX > this->saveTexture.getX() && mouseX < this->saveTexture.getX() + SAVE_ICON_SIDE && mouseY > this->saveTexture.getY() && mouseY < this->saveTexture.getY() + SAVE_ICON_SIDE ) { if (!this->unsaved_changes) { std::cout << "No hay cambios sin guardar." << std::endl; this->notice.showFlashNotice(this->renderer, "No hay cambios sin guardar."); continue; } validMap = mapGame.hasWorms(); if (!validMap) { std::cout << "El mapa debe tener al menos un worm de cada team." << std::endl; this->notice.showFlashError(this->renderer, "El mapa debe tener al menos un worm de cada team."); continue; } mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; std::cout << "Mapa guardado." << std::endl; this->notice.showFlashNotice(this->renderer, "Mapa guardado en /usr/etc/worms/maps/" + this->map_name); } else if ( mouseX > this->exitTexture.getX() && mouseX < this->exitTexture.getX() + EXIT_ICON_SIDE && mouseY > this->exitTexture.getY() && mouseY < this->exitTexture.getY() + EXIT_ICON_SIDE) { quit = true; editorWindow.hide(); validMap = mapGame.hasWorms(); if (!validMap) { QMessageBox msgBox; msgBox.setWindowTitle("Mapa inválido."); msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { editorWindow.show(); quit = false; continue; } } if (this->unsaved_changes) { QMessageBox msgBox; msgBox.setWindowTitle("Guardar antes de salir."); msgBox.setText("Hay cambios sin guardar. Desea guardar el mapa antes de salir?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; continue; } } } else { editorInventory.handleEvent(renderer, e, mapGame, camX, camY); this->unsaved_changes = true; } } } else { editorInventory.handleEvent(renderer, e, mapGame, camX, camY); } } SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); camera.updateCameraPosition(); editorWindow.render(camera); mapGame.render(renderer, camX, camY); editorInventory.renderSelectedInMouse(renderer); editorWindow.renderWater(camera); editorInventory.render(renderer); notice.render(renderer); this->saveTexture.render(this->renderer, this->saveTexture.getX(), this->saveTexture.getY(), SAVE_ICON_SIDE, SAVE_ICON_SIDE); this->exitTexture.render(this->renderer, this->exitTexture.getX(), this->exitTexture.getY(), EXIT_ICON_SIDE, EXIT_ICON_SIDE); SDL_RenderPresent(renderer); SDL_Delay(50); // Para no usar al mango el CPU } if (validMap && this->unsaved_changes) { QMessageBox msgBox; msgBox.setWindowTitle("Fin de edición"); msgBox.setText("¿Desea guardar el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; return 0; } } return -1; }
34.782828
127
0.652098
gabyrobles93
dce1aa108a1408397a6280c0e66fdf626d083d24
2,589
cc
C++
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 SK Telecom Co., Ltd. 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 "base/nugu_log.h" #include "capability_manager.hh" #include "wakeup_handler.hh" namespace NuguCore { WakeupHandler::WakeupHandler(const std::string& model_path) : wakeup_detector(std::unique_ptr<WakeupDetector>(new WakeupDetector(WakeupDetector::Attribute { "", "", "", model_path }))) , uniq(0) { wakeup_detector->setListener(this); } WakeupHandler::~WakeupHandler() { } void WakeupHandler::setListener(IWakeupListener* listener) { this->listener = listener; } bool WakeupHandler::startWakeup() { std::string id = "id#" + std::to_string(uniq++); setWakeupId(id); return wakeup_detector->startWakeup(id); } void WakeupHandler::stopWakeup() { wakeup_detector->stopWakeup(); } void WakeupHandler::onWakeupState(WakeupState state, const std::string& id, float noise, float speech) { if (request_wakeup_id != id) { nugu_warn("[id: %s] ignore [id: %s]'s state %d", request_wakeup_id.c_str(), id.c_str(), state); return; } switch (state) { case WakeupState::FAIL: nugu_dbg("[id: %s] WakeupState::FAIL", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_FAIL, noise, speech); break; case WakeupState::DETECTING: nugu_dbg("[id: %s] WakeupState::DETECTING", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTING, noise, speech); break; case WakeupState::DETECTED: nugu_dbg("[id: %s] WakeupState::DETECTED", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTED, noise, speech); break; case WakeupState::DONE: nugu_dbg("[id: %s] WakeupState::DONE", id.c_str()); break; } } void WakeupHandler::setWakeupId(const std::string& id) { request_wakeup_id = id; nugu_dbg("startListening with new id(%s)", request_wakeup_id.c_str()); } } // NuguCore
28.141304
128
0.676323
nugulinux
dce1dfd76f66d0749bdacb0cdf77658fefd4cc9d
3,652
cpp
C++
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ //HACK ME, PLEASE! ^_^ #include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <vector> #include <set> #include <utility> #include <math.h> #include <cstdlib> #include <memory.h> #include <queue> #define pb push_back #define i64 long long #define mp make_pair #define pii pair <int,int> #define vi vector <int> #define vii vector <pii> #define f first #define s second #define foran(i,a,b) for (int i=a;i<(int)b;i++) #define forn(i,n) for (int i=0;i<(int)n;i++) #define ford(i,n) for (int i=(int)n-1;i>=0;i--) const double eps = 1e-9; const int int_inf = 2000000000; const i64 i64_inf = 1000000000000000000LL; const double pi = acos(-1.0); using namespace std; struct p { int x,y; p() {}; }; struct tr { p a,b; tr(int x1=0,int y1=0,int x2=0,int y2=0) { a.x=x1; a.y=y1; b.x=x2; b.y=y2; }; }; int dest(tr F, tr S) { if (F.a.x == F.b.x && S.a.x == S.b.x) { int y = F.a.y; int yy = F.b.y; int y1 = S.a.y; int yy1 = S.b.y; if ( min(y,yy) > max(y1,yy1) || min(y1,yy1) > max(y,yy)) { if (y1 < yy1) swap(y1,yy1); if (y < yy) swap(y,yy); int dx = abs(F.a.x - S.b.x); int dy = min(abs(yy1 - y),abs(y1-yy)); return dx * dx + dy * dy; } else return (F.a.x - S.a.x) * (F.a.x - S.a.x); } else if (F.a.y == F.b.y && S.a.y == S.b.y) { int x = F.a.x; int xx = F.b.x; int x1 = S.a.x; int xx1 = S.b.x; if ( min(x,xx) > max(x1,xx1) || min(x1,xx1) > max(x,xx)) { if (x1 < xx1) swap(x1,xx1); if (x < xx) swap(x,xx); int dy = abs(F.a.y - S.b.y); int dx = min(abs(xx1 - x), abs(x1-xx)); return dx * dx + dy * dy; } else return (F.a.y - S.a.y) * (F.a.y - S.a.y); } else { if (F.a.y == F.b.y) swap(F,S); int y = F.b.y; int y1 = F.a.y; int x = S.a.x; int x1 = S.b.x; if (y1 < y) swap(y,y1); if (x1 < x) swap(x,x1); if (S.a.y <= y1 && S.a.y >= y) return min( (x - F.b.x)*(x - F.b.x), (x1 - F.b.x)*(x1 - F.b.x) ); if (F.a.x >= x && F.a.x <= x1) return min( (y1 - S.a.y)*(y1 - S.a.y), (y - S.a.y) * (y - S.a.y) ); if (abs(x - F.a.x) > abs(x1 - F.a.x)) swap(x,x1); if (abs(y - S.a.y) < abs(y1 - S.a.y)) swap(y,y1); int dx = F.a.x - x; int dy = y1 - S.a.y; return dx * dx + dy * dy; } } int n; int a,aa,b; p A; p B; tr c[1100]; int d[1050]; int main() { cin >> a >> b; aa = a; a = a * a; cin >> A.x >> A.y >> B.x >> B.y; cin >> n; forn(i,n) scanf("%d%d%d%d",&c[i].a.x,&c[i].a.y,&c[i].b.x,&c[i].b.y); if ( (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y) <= a) { int de = (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); printf("%.8lf",(double)sqrt((double)de)); return 0; } forn(i,n) if (dest(tr(A.x,A.y,A.x,A.y),c[i]) <= a) d[i] = 1; else d[i] = int_inf; queue <int> q; forn(i,n) if (d[i] < int_inf) q.push(i); double res = int_inf; while (!q.empty()) { int j = q.front(); q.pop(); if (dest(tr(B.x,B.y,B.x,B.y),c[j]) <= a) res = min(res,(double)d[j]*(aa+b) + (double)sqrt((double)dest(tr(B.x,B.y,B.x,B.y),c[j]))); forn(i,n) if (dest(c[i],c[j]) <= a && i != j && d[i] > d[j] + 1) q.push(i), d[i] = d[j] + 1; } if (res == int_inf) { cout << "-1"; return 0; } printf("%.8lf",(double)res); return 0; }
26.463768
107
0.441128
AmrARaouf
dce21c1663f64fff45a035362b019a7ee5de494a
1,089
cpp
C++
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "binary_tree.h" using namespace std; class Solution { public: TreeNode* bstFromPreorder(vector<int>& preorder) { if (preorder.size() == 0) return nullptr; TreeNode* root = new TreeNode {preorder[0]}; for (int i = 1; i < preorder.size(); i++) { TreeNode *parent = nullptr; TreeNode *child = root; // TreeNode *child = root; int val = preorder[i]; while (child) { parent = child; if (child->val < val) { child = child->right; } else { child = child->left; } } if (parent->val < val) { parent->right = new TreeNode {val}; } else { parent->left = new TreeNode {val}; } } return root; } }; int main() { vector<int> v {8, 5, 1, 7, 10, 12}; TreeNode* root = Solution().bstFromPreorder(v); prettyPrintTree(root); }
27.225
59
0.458219
qiufengyu
dce7c7e21f38167ab9d28022a0e0c56bf0c96614
13,250
cpp
C++
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
2
2021-11-06T07:23:27.000Z
2021-11-07T14:29:21.000Z
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
null
null
null
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
3
2020-09-28T02:42:26.000Z
2020-09-28T09:01:08.000Z
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "rtklib.h" #include "convopt.h" #include "codeopt.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TCodeOptDialog *CodeOptDialog; //--------------------------------------------------------------------------- __fastcall TCodeOptDialog::TCodeOptDialog(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::FormShow(TObject *Sender) { char mask[7][64]={""}; for (int i=0;i<7;i++) strcpy(mask[i],ConvOptDialog->CodeMask[i].c_str()); G01->Checked=mask[0][ 0]=='1'; G02->Checked=mask[0][ 1]=='1'; G03->Checked=mask[0][ 2]=='1'; G04->Checked=mask[0][ 3]=='1'; G05->Checked=mask[0][ 4]=='1'; G06->Checked=mask[0][ 5]=='1'; G07->Checked=mask[0][ 6]=='1'; G08->Checked=mask[0][ 7]=='1'; G14->Checked=mask[0][13]=='1'; G15->Checked=mask[0][14]=='1'; G16->Checked=mask[0][15]=='1'; G17->Checked=mask[0][16]=='1'; G18->Checked=mask[0][17]=='1'; G19->Checked=mask[0][18]=='1'; G20->Checked=mask[0][19]=='1'; G21->Checked=mask[0][20]=='1'; G22->Checked=mask[0][21]=='1'; G23->Checked=mask[0][22]=='1'; G24->Checked=mask[0][23]=='1'; G25->Checked=mask[0][24]=='1'; G26->Checked=mask[0][25]=='1'; R01->Checked=mask[1][ 0]=='1'; R02->Checked=mask[1][ 1]=='1'; R14->Checked=mask[1][13]=='1'; R19->Checked=mask[1][18]=='1'; R44->Checked=mask[1][43]=='1'; R45->Checked=mask[1][44]=='1'; R46->Checked=mask[1][45]=='1'; E01->Checked=mask[2][ 0]=='1'; E10->Checked=mask[2][ 9]=='1'; E11->Checked=mask[2][10]=='1'; E12->Checked=mask[2][11]=='1'; E13->Checked=mask[2][12]=='1'; E24->Checked=mask[2][23]=='1'; E25->Checked=mask[2][24]=='1'; E26->Checked=mask[2][25]=='1'; E27->Checked=mask[2][26]=='1'; E28->Checked=mask[2][27]=='1'; E29->Checked=mask[2][28]=='1'; E30->Checked=mask[2][29]=='1'; E31->Checked=mask[2][30]=='1'; E32->Checked=mask[2][31]=='1'; E33->Checked=mask[2][32]=='1'; E34->Checked=mask[2][33]=='1'; E37->Checked=mask[2][36]=='1'; E38->Checked=mask[2][37]=='1'; E39->Checked=mask[2][38]=='1'; J01->Checked=mask[3][ 0]=='1'; J07->Checked=mask[3][ 6]=='1'; J08->Checked=mask[3][ 7]=='1'; J13->Checked=mask[3][12]=='1'; J12->Checked=mask[3][11]=='1'; J16->Checked=mask[3][15]=='1'; J17->Checked=mask[3][16]=='1'; J18->Checked=mask[3][17]=='1'; J24->Checked=mask[3][23]=='1'; J25->Checked=mask[3][24]=='1'; J26->Checked=mask[3][25]=='1'; J35->Checked=mask[3][34]=='1'; J36->Checked=mask[3][35]=='1'; J33->Checked=mask[3][32]=='1'; C40->Checked=mask[5][39]=='1'; C41->Checked=mask[5][40]=='1'; C12->Checked=mask[5][11]=='1'; C27->Checked=mask[5][26]=='1'; C28->Checked=mask[5][27]=='1'; C29->Checked=mask[5][28]=='1'; C42->Checked=mask[5][41]=='1'; C43->Checked=mask[5][42]=='1'; C33->Checked=mask[5][32]=='1'; I49->Checked=mask[6][48]=='1'; I50->Checked=mask[6][49]=='1'; I51->Checked=mask[6][50]=='1'; I26->Checked=mask[6][25]=='1'; I52->Checked=mask[6][51]=='1'; I53->Checked=mask[6][52]=='1'; I54->Checked=mask[6][53]=='1'; I55->Checked=mask[6][54]=='1'; S01->Checked=mask[4][ 0]=='1'; S24->Checked=mask[4][23]=='1'; S25->Checked=mask[4][24]=='1'; S26->Checked=mask[4][25]=='1'; UpdateEnable(); } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::BtnOkClick(TObject *Sender) { char mask[7][64]={""}; for (int i=0;i<7;i++) for (int j=0;j<MAXCODE;j++) mask[i][j]='0'; if (G01->Checked) mask[0][ 0]='1'; if (G02->Checked) mask[0][ 1]='1'; if (G03->Checked) mask[0][ 2]='1'; if (G04->Checked) mask[0][ 3]='1'; if (G05->Checked) mask[0][ 4]='1'; if (G06->Checked) mask[0][ 5]='1'; if (G07->Checked) mask[0][ 6]='1'; if (G08->Checked) mask[0][ 7]='1'; if (G14->Checked) mask[0][13]='1'; if (G15->Checked) mask[0][14]='1'; if (G16->Checked) mask[0][15]='1'; if (G17->Checked) mask[0][16]='1'; if (G18->Checked) mask[0][17]='1'; if (G19->Checked) mask[0][18]='1'; if (G20->Checked) mask[0][19]='1'; if (G21->Checked) mask[0][20]='1'; if (G22->Checked) mask[0][21]='1'; if (G23->Checked) mask[0][22]='1'; if (G24->Checked) mask[0][23]='1'; if (G25->Checked) mask[0][24]='1'; if (G26->Checked) mask[0][25]='1'; if (R01->Checked) mask[1][ 0]='1'; if (R02->Checked) mask[1][ 1]='1'; if (R14->Checked) mask[1][13]='1'; if (R19->Checked) mask[1][18]='1'; if (R44->Checked) mask[1][43]='1'; if (R45->Checked) mask[1][44]='1'; if (R46->Checked) mask[1][45]='1'; if (E01->Checked) mask[2][ 0]='1'; if (E10->Checked) mask[2][ 9]='1'; if (E11->Checked) mask[2][10]='1'; if (E12->Checked) mask[2][11]='1'; if (E13->Checked) mask[2][12]='1'; if (E24->Checked) mask[2][23]='1'; if (E25->Checked) mask[2][24]='1'; if (E26->Checked) mask[2][25]='1'; if (E27->Checked) mask[2][26]='1'; if (E28->Checked) mask[2][27]='1'; if (E29->Checked) mask[2][28]='1'; if (E30->Checked) mask[2][29]='1'; if (E31->Checked) mask[2][30]='1'; if (E32->Checked) mask[2][31]='1'; if (E33->Checked) mask[2][32]='1'; if (E34->Checked) mask[2][33]='1'; if (E37->Checked) mask[2][36]='1'; if (E38->Checked) mask[2][37]='1'; if (E39->Checked) mask[2][38]='1'; if (J01->Checked) mask[3][ 0]='1'; if (J07->Checked) mask[3][ 6]='1'; if (J08->Checked) mask[3][ 7]='1'; if (J13->Checked) mask[3][12]='1'; if (J12->Checked) mask[3][11]='1'; if (J16->Checked) mask[3][15]='1'; if (J17->Checked) mask[3][16]='1'; if (J18->Checked) mask[3][17]='1'; if (J24->Checked) mask[3][23]='1'; if (J25->Checked) mask[3][24]='1'; if (J26->Checked) mask[3][25]='1'; if (J35->Checked) mask[3][34]='1'; if (J36->Checked) mask[3][35]='1'; if (J33->Checked) mask[3][32]='1'; if (C40->Checked) mask[5][39]='1'; if (C41->Checked) mask[5][40]='1'; if (C12->Checked) mask[5][11]='1'; if (C27->Checked) mask[5][26]='1'; if (C28->Checked) mask[5][27]='1'; if (C29->Checked) mask[5][28]='1'; if (C42->Checked) mask[5][41]='1'; if (C43->Checked) mask[5][42]='1'; if (C33->Checked) mask[5][32]='1'; if (I49->Checked) mask[6][48]='1'; if (I50->Checked) mask[6][49]='1'; if (I51->Checked) mask[6][50]='1'; if (I26->Checked) mask[6][25]='1'; if (I52->Checked) mask[6][51]='1'; if (I53->Checked) mask[6][52]='1'; if (I54->Checked) mask[6][53]='1'; if (I55->Checked) mask[6][54]='1'; if (S01->Checked) mask[4][ 0]='1'; if (S24->Checked) mask[4][23]='1'; if (S25->Checked) mask[4][24]='1'; if (S26->Checked) mask[4][25]='1'; for (int i=0;i<7;i++) ConvOptDialog->CodeMask[i]=mask[i]; } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::BtnSetAllClick(TObject *Sender) { int set=BtnSetAll->Caption=="Set All"; G01->Checked=set; G02->Checked=set; G03->Checked=set; G04->Checked=set; G05->Checked=set; G06->Checked=set; G07->Checked=set; G08->Checked=set; G14->Checked=set; G15->Checked=set; G16->Checked=set; G17->Checked=set; G18->Checked=set; G19->Checked=set; G20->Checked=set; G21->Checked=set; G22->Checked=set; G23->Checked=set; G24->Checked=set; G25->Checked=set; G26->Checked=set; R01->Checked=set; R02->Checked=set; R14->Checked=set; R19->Checked=set; R44->Checked=set; R45->Checked=set; R46->Checked=set; E01->Checked=set; E10->Checked=set; E11->Checked=set; E12->Checked=set; E13->Checked=set; E24->Checked=set; E25->Checked=set; E26->Checked=set; E27->Checked=set; E28->Checked=set; E29->Checked=set; E30->Checked=set; E31->Checked=set; E32->Checked=set; E33->Checked=set; E34->Checked=set; E37->Checked=set; E38->Checked=set; E39->Checked=set; J01->Checked=set; J07->Checked=set; J08->Checked=set; J13->Checked=set; J12->Checked=set; J16->Checked=set; J17->Checked=set; J18->Checked=set; J24->Checked=set; J25->Checked=set; J26->Checked=set; J35->Checked=set; J36->Checked=set; J33->Checked=set; C40->Checked=set; C41->Checked=set; C12->Checked=set; C27->Checked=set; C28->Checked=set; C29->Checked=set; C42->Checked=set; C43->Checked=set; C33->Checked=set; I49->Checked=set; I50->Checked=set; I51->Checked=set; I26->Checked=set; I52->Checked=set; I53->Checked=set; I54->Checked=set; I55->Checked=set; S01->Checked=set; S24->Checked=set; S25->Checked=set; S26->Checked=set; BtnSetAll->Caption=BtnSetAll->Caption=="Set All"?"Unset All":"Set All"; } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::UpdateEnable(void) { G01->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G02->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G03->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G04->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G05->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G06->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G07->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G08->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G14->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G15->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G16->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G17->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G18->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G19->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G20->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G21->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G22->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G23->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G24->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); G25->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); G26->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); R01->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1); R02->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1); R14->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2); R19->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2); R44->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); R45->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); R46->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); E01->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E10->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E11->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E12->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E13->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E24->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E25->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E26->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E27->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E28->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E29->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E30->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E31->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E32->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E33->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E34->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E37->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); E38->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); E39->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); J01->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J07->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J08->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J13->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J12->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J16->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J17->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J18->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J24->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J25->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J26->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J35->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); J36->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); J33->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); C40->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C41->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C12->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C27->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C28->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C29->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C42->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); C43->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); C33->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); I49->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I50->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I51->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I26->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I52->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I53->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I54->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I55->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); S01->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L1); S24->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); S25->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); S26->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); } //---------------------------------------------------------------------------
35.333333
77
0.621057
mws-rmain
dce93554c6735c0cd9fe675aaa1c4e96a80b1b64
10,164
hpp
C++
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
#ifndef OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP #define OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP #include <atomic> #include <limits> // std::numeric_limits #include <tuple> #include <openpose/core/common.hpp> #include <openpose/core/datum.hpp> #include <openpose/utilities/fastMath.hpp> #include <openpose/producer/producer.hpp> #include <iostream> #include <string> namespace op { template<typename TDatum> class DatumProducer { public: explicit DatumProducer( const std::shared_ptr<Producer>& producerSharedPtr, const unsigned long long frameFirst = 0, const unsigned long long frameStep = 1, const unsigned long long frameLast = std::numeric_limits<unsigned long long>::max(), const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr = nullptr); virtual ~DatumProducer(); std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> checkIfRunningAndGetDatum(); private: const unsigned long long mNumberFramesToProcess; std::shared_ptr<Producer> spProducer; unsigned long long mGlobalCounter; unsigned long long mFrameStep; unsigned int mNumberConsecutiveEmptyFrames; std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>> spVideoSeek; void checkIfTooManyConsecutiveEmptyFrames( unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const; DELETE_COPY(DatumProducer); }; } // Implementation #include <opencv2/imgproc/imgproc.hpp> // cv::cvtColor #include <openpose/producer/datumProducer.hpp> namespace op { template<typename TDatum> DatumProducer<TDatum>::DatumProducer( const std::shared_ptr<Producer>& producerSharedPtr, const unsigned long long frameFirst, const unsigned long long frameStep, const unsigned long long frameLast, const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr) : mNumberFramesToProcess{(frameLast != std::numeric_limits<unsigned long long>::max() ? frameLast - frameFirst : frameLast)}, spProducer{producerSharedPtr}, mGlobalCounter{0ll}, mFrameStep{frameStep}, mNumberConsecutiveEmptyFrames{0u}, spVideoSeek{videoSeekSharedPtr} { try { // Sanity check if (frameLast < frameFirst) error("The desired initial frame must be lower than the last one (flags `--frame_first` vs." " `--frame_last`). Current: " + std::to_string(frameFirst) + " vs. " + std::to_string(frameLast) + ".", __LINE__, __FUNCTION__, __FILE__); if (frameLast != std::numeric_limits<unsigned long long>::max() && frameLast > spProducer->get(CV_CAP_PROP_FRAME_COUNT)-1) error("The desired last frame must be lower than the length of the video or the number of images." " Current: " + std::to_string(frameLast) + " vs. " + std::to_string(positiveIntRound(spProducer->get(CV_CAP_PROP_FRAME_COUNT))-1) + ".", __LINE__, __FUNCTION__, __FILE__); // Set frame first and step if (spProducer->getType() != ProducerType::FlirCamera && spProducer->getType() != ProducerType::IPCamera && spProducer->getType() != ProducerType::Webcam) { // Frame first spProducer->set(CV_CAP_PROP_POS_FRAMES, (double)frameFirst); // Frame step spProducer->set(ProducerProperty::FrameStep, (double)frameStep); } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatum> DatumProducer<TDatum>::~DatumProducer() { } template<typename TDatum> std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> DatumProducer<TDatum>::checkIfRunningAndGetDatum() { try { auto datums = std::make_shared<std::vector<std::shared_ptr<TDatum>>>(); // Check last desired frame has not been reached if (mNumberFramesToProcess != std::numeric_limits<unsigned long long>::max() && mGlobalCounter > mNumberFramesToProcess) { spProducer->release(); } // If producer released -> it sends an empty cv::Mat + a datumProducerRunning signal const bool datumProducerRunning = spProducer->isOpened(); // If device is open if (datumProducerRunning) { // Fast forward/backward - Seek to specific frame index desired if (spVideoSeek != nullptr) { // Fake pause vs. normal mode const auto increment = spVideoSeek->second - (spVideoSeek->first ? 1 : 0); // Normal mode if (increment != 0) spProducer->set(CV_CAP_PROP_POS_FRAMES, spProducer->get(CV_CAP_PROP_POS_FRAMES) + increment); // It must be always reset or bug in fake pause spVideoSeek->second = 0; } auto nextFrameName = spProducer->getNextFrameName(); const auto nextFrameNumber = (unsigned long long)spProducer->get(CV_CAP_PROP_POS_FRAMES); const auto cvMats = spProducer->getFrames(); const auto cameraMatrices = spProducer->getCameraMatrices(); auto cameraExtrinsics = spProducer->getCameraExtrinsics(); auto cameraIntrinsics = spProducer->getCameraIntrinsics(); // Check frames are not empty checkIfTooManyConsecutiveEmptyFrames(mNumberConsecutiveEmptyFrames, cvMats.empty() || cvMats[0].empty()); if (!cvMats.empty()) { datums->resize(cvMats.size()); // Datum cannot be assigned before resize() auto& datumPtr = (*datums)[0]; datumPtr = std::make_shared<TDatum>(); // Filling first element std::swap(datumPtr->name, nextFrameName); datumPtr->frameNumber = nextFrameNumber; datumPtr->cvInputData = cvMats[0]; if (!cameraMatrices.empty()) { datumPtr->cameraMatrix = cameraMatrices[0]; datumPtr->cameraExtrinsics = cameraExtrinsics[0]; datumPtr->cameraIntrinsics = cameraIntrinsics[0]; } // Image integrity if (datumPtr->cvInputData.channels() != 3) { const std::string commonMessage{"Input images must be 3-channel BGR."}; // Grey to RGB if required if (datumPtr->cvInputData.channels() == 1) { log(commonMessage + " Converting grey image into BGR.", Priority::High); cv::cvtColor(datumPtr->cvInputData, datumPtr->cvInputData, CV_GRAY2BGR); } else error(commonMessage, __LINE__, __FUNCTION__, __FILE__); } // std::cout << "DatumProducer:: datumPtr->cvOutputData is empty? " << datumPtr->cvOutputData.empty() << "\n"; datumPtr->cvOutputData = datumPtr->cvInputData; // Resize if it's stereo-system if (datums->size() > 1) { // Stereo-system: Assign all cv::Mat for (auto i = 1u ; i < datums->size() ; i++) { auto& datumIPtr = (*datums)[i]; datumIPtr = std::make_shared<TDatum>(); datumIPtr->name = datumPtr->name; datumIPtr->frameNumber = datumPtr->frameNumber; datumIPtr->cvInputData = cvMats[i]; datumIPtr->cvOutputData = datumIPtr->cvInputData; if (cameraMatrices.size() > i) { datumIPtr->cameraMatrix = cameraMatrices[i]; datumIPtr->cameraExtrinsics = cameraExtrinsics[i]; datumIPtr->cameraIntrinsics = cameraIntrinsics[i]; } } } // Check producer is running if (!datumProducerRunning || (*datums)[0]->cvInputData.empty()) datums = nullptr; // Increase counter if successful image if (datums != nullptr) mGlobalCounter += mFrameStep; } } // Return result return std::make_pair(datumProducerRunning, datums); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(false, std::make_shared<std::vector<std::shared_ptr<TDatum>>>()); } } template<typename TDatum> void DatumProducer<TDatum>::checkIfTooManyConsecutiveEmptyFrames( unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const { numberConsecutiveEmptyFrames = (emptyFrame ? numberConsecutiveEmptyFrames+1 : 0); const auto threshold = 500u; if (numberConsecutiveEmptyFrames >= threshold) error("Detected too many (" + std::to_string(numberConsecutiveEmptyFrames) + ") empty frames in a row.", __LINE__, __FUNCTION__, __FILE__); } extern template class DatumProducer<BASE_DATUM>; } #endif // OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP
45.375
130
0.55854
mooktj
dcec710ff4c3a62228b325e1546ef90961b041af
2,076
cpp
C++
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
1
2018-11-03T02:48:20.000Z
2018-11-03T02:48:20.000Z
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include "nativeparticipantimpl.h" #include "nativesubscriberimpl.h" #include <iostream> #include <chrono> #include <thread> using namespace us::ihmc::rtps::impl::fastRTPS; class ExampleParticipantListener : public NativeParticipantListener { void onParticipantDiscovery(int64_t infoPtr, int64_t guidHigh, int64_t guidLow, DISCOVERY_STATUS status) { std::cout << "Discovered participant " << getName(infoPtr) << std::endl; } }; class ExampleSubscriberListener : public NativeSubscriberListener { virtual void onSubscriptionMatched(MatchingStatus status, int64_t guidHigh, int64_t guidLow) { std::cout << "Found publisher" << std::endl; } virtual void onNewDataMessage() { std::cout << "Got callback" << std::endl; } }; int main() { RTPSParticipantAttributes rtps; rtps.setName("Participant"); rtps.builtin.domainId = 1; ExampleParticipantListener participantListener; NativeParticipantImpl participant(rtps, &participantListener); participant.registerType("chat::ChatMessage", 64000, false); SubscriberAttributes attr; attr.topic.topicName = "ChatBox1"; attr.topic.topicDataType = "chat::ChatMessage"; attr.qos.m_reliability.kind = BEST_EFFORT_RELIABILITY_QOS; attr.qos.m_partition.push_back("us/ihmc"); ExampleSubscriberListener subscriberListener; NativeSubscriberImpl subscriber(-1, -1, 528, PREALLOCATED_MEMORY_MODE, &attr.topic, &attr.qos, &attr.times, &attr.unicastLocatorList, &attr.multicastLocatorList, &attr.outLocatorList, false, &participant, &subscriberListener); subscriber.createSubscriber(); std::vector<unsigned char> data(64000); SampleInfoMarshaller marshaller; while(true) { subscriber.waitForUnreadMessage(); if(subscriber.takeNextData(64000, data.data(), &marshaller, NO_KEY, SHARED_OWNERSHIP_QOS)) { std::cout << "Got message of length " << marshaller.dataLength << std::endl; } } }
28.833333
148
0.688343
loulansuiye
dcef3916bce8005255e1572fbfb090a643a8dbcc
6,860
cpp
C++
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
1
2021-11-03T08:05:57.000Z
2021-11-03T08:05:57.000Z
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
null
null
null
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include "Window.h" #include "TaskSystem.h" #include "Timer.h" #include "Graphics.h" #include "Renderer.h" #include "State.h" #include "DefaultLoadState.h" #include "StateManager.h" #include "GuiSystem.h" using namespace jsh; using namespace jsh::_internal; namespace jshEngine { void BeginUpdate(float dt); void EndUpdate(float dt); uint32 g_FPS = 0u; Time g_DeltaTime = 0.f; uint32 g_FixedUpdateFrameRate; float g_FixedUpdateDeltaTime; StateManager g_State; GuiSystem g_GuiSystem; enum JSH_ENGINE_STATE : uint8 { JSH_ENGINE_STATE_NONE, JSH_ENGINE_STATE_INITIALIZING, JSH_ENGINE_STATE_INITIALIZED, JSH_ENGINE_STATE_RUNNING, JSH_ENGINE_STATE_CLOSING, JSH_ENGINE_STATE_CLOSED }; JSH_ENGINE_STATE g_EngineState = JSH_ENGINE_STATE_NONE; bool Initialize(jsh::State* state, jsh::State* loadState) { jshTimer::Initialize(); jshDebug::_internal::Initialize(); if (g_EngineState != JSH_ENGINE_STATE_NONE) { jshDebug::LogW("jshEngine is already initialized"); return false; } g_EngineState = JSH_ENGINE_STATE_INITIALIZING; try { if (!jshTask::Initialize()) { jshDebug::LogE("Can't initialize jshTaskSystem"); return false; } SetFixedUpdateFrameRate(60u); if (!jshWindow::Initialize()) { jshDebug::LogE("Can't initialize jshWindow"); return false; } if (!jshRenderer::_internal::Initialize()) { jshDebug::LogE("Can't initialize jshRenderer"); return false; } //im gui initialize jshImGui(if (!jshGraphics::_internal::InitializeImGui()) { jshDebug::LogE("Cant't initialize ImGui"); return false; }); jshScene::Initialize(); g_GuiSystem.Initialize(); LoadState(state, loadState); jshDebug::LogI("jshEngine initialized"); jshDebug::LogSeparator(); g_EngineState = JSH_ENGINE_STATE_INITIALIZED; } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); return false; } catch (...) { jshFatalError("Unknown error"); return false; } return true; } void Run() { if (g_EngineState != JSH_ENGINE_STATE_INITIALIZED) { jshFatalError("You must initialize jshEngine"); } g_EngineState = JSH_ENGINE_STATE_RUNNING; try { Time lastTime = jshTimer::Now(); g_DeltaTime = lastTime; Time actualTime = 0.f; const float SHOW_FPS_RATE = 1.0f; float dtCount = 0.f; float fpsCount = 0u; float fixedUpdateCount = 0.f; while (jshWindow::UpdateInput()) { actualTime = jshTimer::Now(); g_DeltaTime = actualTime - lastTime; lastTime = actualTime; fixedUpdateCount += g_DeltaTime; if (g_DeltaTime > 0.2f) g_DeltaTime = 0.2f; g_State.Prepare(); // update BeginUpdate(g_DeltaTime); g_State.Update(g_DeltaTime); if (fixedUpdateCount >= 0.01666666f) { fixedUpdateCount -= 0.01666666f; g_State.FixedUpdate(); } EndUpdate(g_DeltaTime); // render jshRenderer::_internal::Begin(); g_State.Render(); jshRenderer::_internal::Render(); jshRenderer::_internal::End(); // FPS count dtCount += g_DeltaTime; fpsCount++; if (dtCount >= SHOW_FPS_RATE) { g_FPS = uint32(fpsCount / SHOW_FPS_RATE); //jshDebug::Log("%u", g_FPS); fpsCount = 0.f; dtCount -= SHOW_FPS_RATE; } } } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); } catch (...) { jshFatalError("Unknown error"); } } bool Close() { jshDebug::LogSeparator(); if (g_EngineState == JSH_ENGINE_STATE_CLOSING || g_EngineState == JSH_ENGINE_STATE_CLOSED) { jshDebug::LogW("jshEngine is already closed"); } g_EngineState = JSH_ENGINE_STATE_CLOSING; try { g_State.ClearState(); jshScene::Close(); if (!jshTask::Close()) return false; if (!jshWindow::Close()) return false; if (!jshRenderer::_internal::Close()) return false; jshDebug::LogI("jshEngine closed"); jshDebug::_internal::Close(); g_EngineState = JSH_ENGINE_STATE_CLOSED; } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); return false; } catch (...) { jshFatalError("Unknown error"); return false; } return true; } void Exit(int code) { if (g_EngineState != JSH_ENGINE_STATE_CLOSED) { if (!Close()) jshDebug::LogE("Can't close jshEngine properly"); } exit(code); } ///////////////////////////////////////UPDATE///////////////////////////////////// void BeginUpdate(float dt) { if (jshInput::IsKey(JSH_KEY_CONTROL) && jshInput::IsKeyPressed(JSH_KEY_F11)) jshEngine::Exit(0); // Update Camera matrices { auto& cameras = jshScene::_internal::GetComponentsList()[CameraComponent::ID]; for (uint32 i = 0; i < cameras.size(); i += uint32(CameraComponent::SIZE)) { CameraComponent* camera = reinterpret_cast<CameraComponent*>(&cameras[i]); camera->UpdateMatrices(); } } // Update Gui g_GuiSystem.Update(dt); } void EndUpdate(float dt) { } ////////////////////////////////////////STATE MANAGEMENT//////////////////////////// void LoadState(jsh::State* state, jsh::State* loadState) { g_State.LoadState(state, loadState); } State* GetCurrentState() { return g_State.GetCurrentState(); } uint32 GetFPS() { return g_FPS; } float GetDeltaTime() { return g_DeltaTime; } bool IsInitialized() { return g_EngineState != JSH_ENGINE_STATE_NONE && g_EngineState != JSH_ENGINE_STATE_INITIALIZING; } // FIXED UPDATE METHODS void SetFixedUpdateFrameRate(uint32 frameRate) { g_FixedUpdateFrameRate = frameRate; g_FixedUpdateDeltaTime = 1.f / (float)frameRate; } float GetFixedUpdateDeltaTime() { return g_FixedUpdateDeltaTime; } // VERSION constexpr uint64 g_MajorVersion = 0u; constexpr uint64 g_MinorVersion = 1u; constexpr uint64 g_RevisionVersion = 2u; uint64 GetMajorVersion() { return g_MajorVersion; } uint64 GetMinorVersion() { return g_MinorVersion; } uint64 GetRevisionVersion() { return g_RevisionVersion; } uint64 GetVersion() { return g_MajorVersion * 1000000u + g_MinorVersion * 1000u + g_RevisionVersion; } const char* GetVersionStr() { const static std::string str = std::string(std::to_string(g_MajorVersion) + '.' + std::to_string(g_MinorVersion) + '.' + std::to_string(g_RevisionVersion)); return str.c_str(); } const wchar* GetVersionStrW() { const static std::wstring str = std::wstring(std::to_wstring(g_MajorVersion) + L'.' + std::to_wstring(g_MinorVersion) + L'.' + std::to_wstring(g_RevisionVersion)); return str.c_str(); } // PROPERTIES const char* GetName() { const static std::string str = std::string("jshEngine " + std::string(GetVersionStr())); return str.c_str(); } const wchar* GetNameW() { const static std::wstring str = std::wstring(L"jshEngine " + std::wstring(GetVersionStrW())); return str.c_str(); } }
21.847134
165
0.669388
JoseLRM
fd63b8fb642c55df7570d013d857ccc936715c9e
64,295
cpp
C++
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2004-2017 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "clangUtil.h" #include <inttypes.h> #include <cctype> #include <cstring> #include <cstdio> #include <sstream> #include "astutil.h" #include "driver.h" #include "expr.h" #include "files.h" #include "mysystem.h" #include "passes.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "type.h" #include "codegen.h" #include "clangSupport.h" #include "build.h" #include "llvmDebug.h" typedef Type ChapelType; #ifndef HAVE_LLVM void readExternC(void) { // Do nothing if we don't have LLVM support. } void cleanupExternC(void) { // Do nothing if we don't have LLVM support. } #else using namespace clang; using namespace llvm; #define GLOBAL_PTR_SPACE 100 #define WIDE_PTR_SPACE 101 #define GLOBAL_PTR_SIZE 64 #define GLOBAL_PTR_ABI_ALIGN 64 #define GLOBAL_PTR_PREF_ALIGN 64 #include "llvmGlobalToWide.h" #include "llvmAggregateGlobalOps.h" // TODO - add functionality to clang so that we don't // have to have what are basically copies of // ModuleBuilder.cpp // ( and BackendUtil.cpp but we used PassManagerBuilder::addGlobalExtension) // // This one is not normally included by clang clients // and not normally installed in the include directory. // // Q. Could we instead call methods on clang::CodeGenerator subclass of // ASTConsumer such as HandleTopLevelDecl to achieve what we want? // We would have a different AST visitor for populating the LVT. // // It is likely that we can leave the C parser "open" somehow and then // add statements to it at the end. // BUT we couldn't call EmitDeferredDecl. // // #include "CodeGenModule.h" #include "CGRecordLayout.h" #include "CGDebugInfo.h" #include "clang/CodeGen/BackendUtil.h" static void setupForGlobalToWide(); fileinfo gAllExternCode; fileinfo gChplCompilationConfig; static VarSymbol *minMaxConstant(int nbits, bool isSigned, bool isMin) { if( nbits == 8 && isSigned && isMin ) return new_IntSymbol(INT8_MIN, INT_SIZE_8); else if( nbits == 8 && isSigned && !isMin ) return new_IntSymbol(INT8_MAX, INT_SIZE_8); else if( nbits == 8 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_8); else if( nbits == 8 && !isSigned && !isMin ) return new_IntSymbol(UINT8_MAX, INT_SIZE_8); else if( nbits == 16 && isSigned && isMin ) return new_IntSymbol(INT16_MIN, INT_SIZE_16); else if( nbits == 16 && isSigned && !isMin ) return new_IntSymbol(INT16_MAX, INT_SIZE_16); else if( nbits == 16 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_16); else if( nbits == 16 && !isSigned && !isMin ) return new_IntSymbol(UINT16_MAX, INT_SIZE_16); else if( nbits == 32 && isSigned && isMin ) return new_IntSymbol(INT32_MIN, INT_SIZE_32); else if( nbits == 32 && isSigned && !isMin ) return new_IntSymbol(INT32_MAX, INT_SIZE_32); else if( nbits == 32 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_32); else if( nbits == 32 && !isSigned && !isMin ) return new_IntSymbol(UINT32_MAX, INT_SIZE_32); else if( nbits == 64 && isSigned && isMin ) return new_IntSymbol(INT64_MIN, INT_SIZE_64); else if( nbits == 64 && isSigned && !isMin ) return new_IntSymbol(INT64_MAX, INT_SIZE_64); else if( nbits == 64 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_64); else if( nbits == 64 && !isSigned && !isMin ) return new_IntSymbol(UINT64_MAX, INT_SIZE_64); else INT_ASSERT(0 && "Bad options for minMaxConstant"); return NULL; } static void addMinMax(const char* prefix, int nbits, bool isSigned) { GenInfo* info = gGenInfo; LayeredValueTable *lvt = info->lvt; astlocT prevloc = currentAstLoc; currentAstLoc.lineno = 0; currentAstLoc.filename = astr("<internal>"); const char* min_name = astr(prefix, "_MIN"); const char* max_name = astr(prefix, "_MAX"); if( isSigned ) { // only signed versions have a meaningful min. lvt->addGlobalVarSymbol(min_name, minMaxConstant(nbits, isSigned, true)); } // but signed and unsigned both have a max lvt->addGlobalVarSymbol(max_name, minMaxConstant(nbits, isSigned, false)); currentAstLoc = prevloc; } static void addMinMax(ASTContext* Ctx, const char* prefix, clang::CanQualType qt) { const clang::Type* ct = qt.getTypePtr(); int nbits = Ctx->getTypeSize(ct); bool isSigned = ct->isSignedIntegerType(); addMinMax(prefix, nbits, isSigned); } static void setupClangContext(GenInfo* info, ASTContext* Ctx) { std::string layout; info->Ctx = Ctx; if( ! info->parseOnly ) { info->module->setTargetTriple( info->Ctx->getTargetInfo().getTriple().getTriple()); // Also setup some basic TBAA metadata nodes. llvm::LLVMContext& cx = info->module->getContext(); // Create the TBAA root node { LLVM_METADATA_OPERAND_TYPE* Ops[1]; Ops[0] = llvm::MDString::get(cx, "Chapel types"); info->tbaaRootNode = llvm::MDNode::get(cx, Ops); } // Create type for ftable { LLVM_METADATA_OPERAND_TYPE* Ops[3]; Ops[0] = llvm::MDString::get(cx, "Chapel ftable"); Ops[1] = info->tbaaRootNode; // and mark it as constant Ops[2] = llvm_constant_as_metadata( ConstantInt::get(llvm::Type::getInt64Ty(cx), 1)); info->tbaaFtableNode = llvm::MDNode::get(cx, Ops); } { LLVM_METADATA_OPERAND_TYPE* Ops[3]; Ops[0] = llvm::MDString::get(cx, "Chapel vmtable"); Ops[1] = info->tbaaRootNode; // and mark it as constant Ops[2] = llvm_constant_as_metadata( ConstantInt::get(llvm::Type::getInt64Ty(cx), 1)); info->tbaaVmtableNode = llvm::MDNode::get(cx, Ops); } } info->targetLayout = info->Ctx->getTargetInfo().getTargetDescription(); layout = info->targetLayout; if( fLLVMWideOpt && ! info->parseOnly ) { char buf[200]; //needs to store up to 8 32-bit numbers in decimal assert(GLOBAL_PTR_SIZE == GLOBAL_PTR_BITS); // Add global pointer info to layout. snprintf(buf, sizeof(buf), "-p%u:%u:%u:%u-p%u:%u:%u:%u", GLOBAL_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN, WIDE_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN); layout += buf; // Save the global address space we are using in info. info->globalToWideInfo.globalSpace = GLOBAL_PTR_SPACE; info->globalToWideInfo.wideSpace = WIDE_PTR_SPACE; } // Always set the module layout. This works around an apparent bug in // clang or LLVM (trivial/deitz/test_array_low.chpl would print out the // wrong answer because some i64s were stored at the wrong alignment). if( info->module ) info->module->setDataLayout(layout); info->targetData = new LLVM_TARGET_DATA(info->Ctx->getTargetInfo().getTargetDescription()); if( ! info->parseOnly ) { info->cgBuilder = new CodeGen::CodeGenModule(*Ctx, #if HAVE_LLVM_VER >= 37 info->Clang->getHeaderSearchOpts(), info->Clang->getPreprocessorOpts(), #endif info->codegenOptions, *info->module, *info->targetData, *info->Diags); } // Set up some constants that depend on the Clang context. { addMinMax(Ctx, "CHAR", Ctx->CharTy); addMinMax(Ctx, "SCHAR", Ctx->SignedCharTy); addMinMax(Ctx, "UCHAR", Ctx->UnsignedCharTy); addMinMax(Ctx, "SHRT", Ctx->ShortTy); addMinMax(Ctx, "USHRT", Ctx->UnsignedShortTy); addMinMax(Ctx, "INT", Ctx->IntTy); addMinMax(Ctx, "UINT", Ctx->UnsignedIntTy); addMinMax(Ctx, "LONG", Ctx->LongTy); addMinMax(Ctx, "ULONG", Ctx->UnsignedLongTy); addMinMax(Ctx, "LLONG", Ctx->LongLongTy); addMinMax(Ctx, "ULLONG", Ctx->UnsignedLongLongTy); } } // Adds a mapping from id->getName() to a variable or CDecl to info->lvt static void handleMacro(const IdentifierInfo* id, const MacroInfo* macro) { GenInfo* info = gGenInfo; Preprocessor &preproc = info->Clang->getPreprocessor(); VarSymbol* varRet = NULL; TypeDecl* cTypeRet = NULL; ValueDecl* cValueRet = NULL; const bool debugPrint = false; if( debugPrint) printf("Adding macro %s\n", id->getName().str().c_str()); //Handling only simple string or integer defines if(macro->getNumArgs() > 0) { if( debugPrint) { printf("the macro takes arguments\n"); } return; // TODO -- handle macro functions. } // Check that we have a single token surrounded by any // number of parens. ie 1, (1), ((1)) Token tok; // the main token. size_t left_parens = 0; size_t right_parens = 0; ssize_t ntokens = macro->getNumTokens(); ssize_t t_idx; bool negate = false; if( ntokens > 0 ) { MacroInfo::tokens_iterator ti = macro->tokens_end() - 1; for( t_idx = ntokens - 1; t_idx >= 0; t_idx-- ) { tok = *ti; if(tok.getKind() == tok::r_paren) right_parens++; else break; --ti; } } { MacroInfo::tokens_iterator ti = macro->tokens_begin(); for( t_idx = 0; t_idx < ntokens; t_idx++ ) { tok = *ti; if(tok.getKind() == tok::l_paren) left_parens++; else if(tok.getKind() == tok::minus) { negate = true; ntokens--; } else break; ++ti; } } if( left_parens == right_parens && ntokens - left_parens - right_parens == 1 ) { // OK! } else { if( debugPrint) { printf("the following macro is too complicated or empty:\n"); } return; // we don't handle complicated expressions like A+B } switch(tok.getKind()) { case tok::numeric_constant: { std::string numString; int hex; int isfloat; if( negate ) numString.append("-"); if (tok.getLiteralData() && tok.getLength()) { numString.append(tok.getLiteralData(), tok.getLength()); } if( debugPrint) printf("num = %s\n", numString.c_str()); hex = 0; if( numString[0] == '0' && (numString[1] == 'x' || numString[1] == 'X')) { hex = 1; } isfloat = 0; if(numString.find('.') != std::string::npos) { isfloat = 1; } // also check for exponent since e.g. 1e10 is a float. if( hex ) { // C99 hex floats use p for exponent if(numString.find('p') != std::string::npos || numString.find('P') != std::string::npos) { isfloat = 1; } } else { if(numString.find('e') != std::string::npos || numString.find('E') != std::string::npos) { isfloat = 1; } } if( !isfloat ) { IF1_int_type size = INT_SIZE_32; if(tolower(numString[numString.length() - 1]) == 'l') { numString[numString.length() - 1] = '\0'; size = INT_SIZE_64; } if(tolower(numString[numString.length() - 1]) == 'u') { numString[numString.length() - 1] = '\0'; varRet = new_UIntSymbol(strtoul(numString.c_str(), NULL, 0), size); } else { varRet = new_IntSymbol(strtol(numString.c_str(), NULL, 0), size); } } else { IF1_float_type size = FLOAT_SIZE_64; if(tolower(numString[numString.length() - 1]) == 'l') { numString[numString.length() - 1] = '\0'; } varRet = new_RealSymbol(numString.c_str(), size); } break; } case tok::string_literal: { std::string body = std::string(tok.getLiteralData(), tok.getLength()); if( debugPrint) printf("str = %s\n", body.c_str()); varRet = new_CStringSymbol(body.c_str()); break; } case tok::identifier: { IdentifierInfo* tokId = tok.getIdentifierInfo(); std::string idName = tokId->getName(); if( debugPrint) { printf("id = %s\n", idName.c_str()); } // Handle the case where the macro refers to something we've // already parsed in C varRet = info->lvt->getVarSymbol(idName); if( !varRet ) { info->lvt->getCDecl(idName, &cTypeRet, &cValueRet); } if( !varRet && !cTypeRet && !cValueRet ) { // Check to see if it's another macro. MacroInfo* otherMacro = preproc.getMacroInfo(tokId); if( otherMacro && otherMacro != macro ) { // Handle the other macro to add it to the LVT under the new name // The recursive call will add it to the LVT if( debugPrint) printf("other macro\n"); handleMacro(tokId, otherMacro); // Get whatever was added in the recursive call // so that we can add it under the new name. varRet = info->lvt->getVarSymbol(idName); info->lvt->getCDecl(idName, &cTypeRet, &cValueRet); } } if( debugPrint ) { if( varRet ) printf("found var %s\n", varRet->cname); if( cTypeRet ) { std::string s = cTypeRet->getName(); printf("found cdecl type %s\n", s.c_str()); } if( cValueRet ) { std::string s = cValueRet->getName(); printf("found cdecl value %s\n", s.c_str()); } } break; } default: break; } if( debugPrint ) { std::string s = id->getName(); const char* kind = NULL; if( varRet ) kind = "var"; if( cTypeRet ) kind = "cdecl type"; if( cValueRet ) kind = "cdecl value"; if( kind ) printf("%s: adding an %s to the lvt\n", s.c_str(), kind); } if( varRet ) { info->lvt->addGlobalVarSymbol(id->getName(), varRet); } if( cTypeRet ) { info->lvt->addGlobalCDecl(id->getName(), cTypeRet); } if( cValueRet ) { info->lvt->addGlobalCDecl(id->getName(), cValueRet); } } static void readMacrosClang(void) { GenInfo* info = gGenInfo; LayeredValueTable *lvt = info->lvt; SET_LINENO(rootModule); // Pre-populate with important INTxx_MIN/MAX from stdint.h // because we have trouble reading these because they have // special stuff to get the right constant width, but they // are all known integer values. lvt->addGlobalVarSymbol("NULL", new_IntSymbol(0, INT_SIZE_64)); // Add INT{8,16,32,64}_{MIN,MAX} and INT_MAX and friends. addMinMax("INT8", 8, true); addMinMax("UINT8", 8, false); addMinMax("INT16", 16, true); addMinMax("UINT16", 16, false); addMinMax("INT32", 32, true); addMinMax("UINT32", 32, false); addMinMax("INT64", 64, true); addMinMax("UINT64", 64, false); //printf("Running ReadMacrosAction\n"); Preprocessor &preproc = info->Clang->getPreprocessor(); // Identify macro-functions and macro-values. // Later, if we see a use of a macro-function, we can // compile it to a static/inline function with args types based an use // how will we know the return type? // expr->getType() stmt->getRetValue()->getType.... // ... add function wrapping macro with wrong type // parse/analyze squelching errors; get the macro expression type; // correct the type and recompile to LLVM // See ClangExpressionParser.cpp in lldb which parses // a C expression from a command line... we need to // do something similar. for(Preprocessor::macro_iterator i = preproc.macro_begin(); i != preproc.macro_end(); i++) { #if HAVE_LLVM_VER >= 37 handleMacro(i->first, i->second.getLatest()->getMacroInfo()); #elif HAVE_LLVM_VER >= 33 handleMacro(i->first, i->second->getMacroInfo()); #else handleMacro(i->first, i->second); #endif } }; // We need a way to: // 1: parse code only // 2: keep the code generator open until we finish generating Chapel code, // since we might need to code generate called functions. // 3: append to the target description // 4: get LLVM values for code generated C things (e.g. types, function ptrs) // // This code is boiler-plate code mostly copied from ModuleBuilder.cpp - see // http://clang.llvm.org/doxygen/ModuleBuilder_8cpp_source.html // Note that ModuleBuilder.cpp is from the clang project and distributed // under a BSD-like license. // // As far as we know, there is no public API for clang that // would allow us the level of control we need over code generation. // The portions that are not copied are delineated by // comments indicating that they are custom to Chapel. class CCodeGenConsumer : public ASTConsumer { private: GenInfo* info; unsigned HandlingTopLevelDecls; SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions; struct HandlingTopLevelDeclRAII { CCodeGenConsumer &Self; HandlingTopLevelDeclRAII(CCodeGenConsumer &Self) : Self(Self) { ++Self.HandlingTopLevelDecls; } ~HandlingTopLevelDeclRAII() { if (--Self.HandlingTopLevelDecls == 0) Self.EmitDeferredDecls(); } }; public: CCodeGenConsumer() : ASTConsumer(), info(gGenInfo), HandlingTopLevelDecls(0) { } virtual ~CCodeGenConsumer() { } // these macros help us to copy and paste the code from ModuleBuilder. #define Ctx (info->Ctx) #define Diags (* info->Diags) #define Builder (info->cgBuilder) #define CodeGenOpts (info->codegenOptions) // mostly taken from ModuleBuilder.cpp /// ASTConsumer override: // Initialize - This is called to initialize the consumer, providing // the ASTContext. virtual void Initialize(ASTContext &Context) LLVM_CXX_OVERRIDE { // This does setTargetTriple, setDataLayout, initialize targetData // and cgBuilder. setupClangContext(info, &Context); for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i) HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]); } // ASTConsumer override: // HandleCXXStaticMemberVarInstantiation - Tell the consumer that // this variable has been instantiated. virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) LLVM_CXX_OVERRIDE { // Custom to Chapel if( info->parseOnly ) return; // End custom to Chapel if (Diags.hasErrorOccurred()) return; Builder->HandleCXXStaticMemberVarInstantiation(VD); } // ASTConsumer override: // // HandleTopLevelDecl - Handle the specified top-level declaration. // This is called by the parser to process every top-level Decl*. // // \returns true to continue parsing, or false to abort parsing. virtual bool HandleTopLevelDecl(DeclGroupRef DG) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return true; HandlingTopLevelDeclRAII HandlingDecl(*this); // Make sure to emit all elements of a Decl. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { // Custom to Chapel if(TypedefDecl *td = dyn_cast<TypedefDecl>(*I)) { const clang::Type *ctype= td->getUnderlyingType().getTypePtrOrNull(); //printf("Adding typedef %s\n", td->getNameAsString().c_str()); if(ctype != NULL) { info->lvt->addGlobalCDecl(td); } } else if(FunctionDecl *fd = dyn_cast<FunctionDecl>(*I)) { info->lvt->addGlobalCDecl(fd); } else if(VarDecl *vd = dyn_cast<VarDecl>(*I)) { info->lvt->addGlobalCDecl(vd); } else if(clang::RecordDecl *rd = dyn_cast<RecordDecl>(*I)) { if( rd->getName().size() > 0 ) { // Handle forward declaration for structs info->lvt->addGlobalCDecl(rd); } } if( info->parseOnly ) continue; // End custom to Chapel Builder->EmitTopLevelDecl(*I); } return true; } // ModuleBuilder.cpp has EmitDeferredDecls but that's not in ASTConsumer. void EmitDeferredDecls() { if (DeferredInlineMethodDefinitions.empty()) return; // Emit any deferred inline method definitions. Note that more deferred // methods may be added during this loop, since ASTConsumer callbacks // can be invoked if AST inspection results in declarations being added. HandlingTopLevelDeclRAII HandlingDecl(*this); for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I) Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]); DeferredInlineMethodDefinitions.clear(); } // ASTConsumer override: // \brief This callback is invoked each time an inline method // definition is completed. virtual void HandleInlineMethodDefinition(CXXMethodDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; assert(D->doesThisDeclarationHaveABody()); // We may want to emit this definition. However, that decision might be // based on computing the linkage, and we have to defer that in case we // are inside of something that will change the method's final linkage, // e.g. // typedef struct { // void bar(); // void foo() { bar(); } // } A; DeferredInlineMethodDefinitions.push_back(D); // Provide some coverage mapping even for methods that aren't emitted. // Don't do this for templated classes though, as they may not be // instantiable. if (!D->getParent()->getDescribedClassTemplate()) Builder->AddDeferredUnusedCoverageMapping(D); } // skipped ASTConsumer HandleInterestingDecl // HandleTagDeclRequiredDefinition // HandleCXXImplicitFunctionInstantiation // HandleTopLevelDeclInObjCContainer // HandleImplicitImportDecl // GetASTMutationListener // GetASTDeserializationListener // PrintStats // shouldSkipFunctionBody // ASTConsumer override: // HandleTagDeclDefinition - This callback is invoked each time a TagDecl // to (e.g. struct, union, enum, class) is completed. This allows the // client hack on the type, which can occur at any point in the file // (because these can be defined in declspecs). virtual void HandleTagDeclDefinition(TagDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel - make a note of C globals if(EnumDecl *ed = dyn_cast<EnumDecl>(D)) { // Add the enum type info->lvt->addGlobalCDecl(ed); // Add the enum values for(EnumDecl::enumerator_iterator e = ed->enumerator_begin(); e != ed->enumerator_end(); e++) { info->lvt->addGlobalCDecl(*e); // & goes away with newer clang } } else if(RecordDecl *rd = dyn_cast<RecordDecl>(D)) { const clang::Type *ctype = rd->getTypeForDecl(); if(ctype != NULL && rd->getDefinition() != NULL) { info->lvt->addGlobalCDecl(rd); } } if( info->parseOnly ) return; // End Custom to Chapel Builder->UpdateCompletedType(D); // For MSVC compatibility, treat declarations of static data members with // inline initializers as definitions. if (Ctx->getLangOpts().MSVCCompat) { for (Decl *Member : D->decls()) { if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && Ctx->DeclMustBeEmitted(VD)) { Builder->EmitGlobal(VD); } } } } } // ASTConsumer override: // \brief This callback is invoked the first time each TagDecl is required // to be complete. virtual void HandleTagDeclRequiredDefinition(const TagDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; if( info->parseOnly ) return; if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) DI->completeRequiredType(RD); } // ASTConsumer override: // HandleTranslationUnit - This method is called when the ASTs for // entire translation unit have been parsed. virtual void HandleTranslationUnit(ASTContext &Context) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) { if(Builder) Builder->clear(); return; } /* custom to Chapel - we don't release the builder now, because we want to add a bunch of uses of functions that may not have been codegened yet. Instead, we call this in cleanupClang. if (Builder) Builder->Release(); */ } // ASTConsumer override: // // CompleteTentativeDefinition - Callback invoked at the end of a // translation unit to notify the consumer that the given tentative // definition should be completed. // // The variable declaration // itself will be a tentative definition. If it had an incomplete // array type, its type will have already been changed to an array // of size 1. However, the declaration remains a tentative // definition and has not been modified by the introduction of an // implicit zero initializer. virtual void CompleteTentativeDefinition(VarDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel if( info->parseOnly ) return; // End Custom to Chapel Builder->EmitTentativeDefinition(D); } // ASTConsumer override: // \brief Callback involved at the end of a translation unit to // notify the consumer that a vtable for the given C++ class is // required. // // \param RD The class whose vtable was used. virtual void HandleVTable(CXXRecordDecl *RD #if HAVE_LLVM_VER < 37 , bool DefinitionRequired #endif ) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel if( info->parseOnly ) return; // End Custom to Chapel Builder->EmitVTable(RD #if HAVE_LLVM_VER < 37 , DefinitionRequired #endif ); } // ASTConsumer override: // // \brief Handle a pragma that appends to Linker Options. Currently // this only exists to support Microsoft's #pragma comment(linker, // "/foo"). void HandleLinkerOptionPragma(llvm::StringRef Opts) override { Builder->AppendLinkerOptions(Opts); } // HandleLinkerOptionPragma // ASTConsumer override: // \brief Handle a pragma that emits a mismatch identifier and value to // the object file for the linker to work with. Currently, this only // exists to support Microsoft's #pragma detect_mismatch. virtual void HandleDetectMismatch(llvm::StringRef Name, llvm::StringRef Value) LLVM_CXX_OVERRIDE { Builder->AddDetectMismatch(Name, Value); } // ASTConsumer override: // \brief Handle a dependent library created by a pragma in the source. /// Currently this only exists to support Microsoft's /// #pragma comment(lib, "/foo"). virtual void HandleDependentLibrary(llvm::StringRef Lib) LLVM_CXX_OVERRIDE { Builder->AddDependentLib(Lib); } // undefine macros we created to help with ModuleBuilder #undef Ctx #undef Diags #undef Builder #undef CodeGenOpts }; #if HAVE_LLVM_VER >= 36 #define CREATE_AST_CONSUMER_RETURN_TYPE std::unique_ptr<ASTConsumer> #else #define CREATE_AST_CONSUMER_RETURN_TYPE ASTConsumer* #endif class CCodeGenAction : public ASTFrontendAction { public: CCodeGenAction() { } protected: virtual CREATE_AST_CONSUMER_RETURN_TYPE CreateASTConsumer( CompilerInstance &CI, StringRef InFile); }; CREATE_AST_CONSUMER_RETURN_TYPE CCodeGenAction::CreateASTConsumer( CompilerInstance &CI, StringRef InFile) { #if HAVE_LLVM_VER >= 36 return std::unique_ptr<ASTConsumer>(new CCodeGenConsumer()); #else return new CCodeGenConsumer(); #endif }; static void finishClang(GenInfo* info){ if( info->cgBuilder ) { info->cgBuilder->Release(); } info->Diags.reset(); info->DiagID.reset(); } static void deleteClang(GenInfo* info){ if( info->cgBuilder ) { delete info->cgBuilder; info->cgBuilder = NULL; } delete info->targetData; delete info->Clang; info->Clang = NULL; delete info->cgAction; info->cgAction = NULL; } static void cleanupClang(GenInfo* info) { finishClang(info); deleteClang(info); } void setupClang(GenInfo* info, std::string mainFile) { std::string clangexe = info->clangCC; std::vector<const char*> clangArgs; for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) { clangArgs.push_back(info->clangCCArgs[i].c_str()); } for( size_t i = 0; i < info->clangLDArgs.size(); ++i ) { clangArgs.push_back(info->clangLDArgs[i].c_str()); } for( size_t i = 0; i < info->clangOtherArgs.size(); ++i ) { clangArgs.push_back(info->clangOtherArgs[i].c_str()); } if (llvmCodegen) { clangArgs.push_back("-emit-llvm"); } //clangArgs.push_back("-c"); clangArgs.push_back(mainFile.c_str()); // chpl - always compile rt file info->diagOptions = new DiagnosticOptions(); info->DiagClient= new TextDiagnosticPrinter(errs(),&*info->diagOptions); info->DiagID = new DiagnosticIDs(); #if HAVE_LLVM_VER >= 32 info->Diags = new DiagnosticsEngine( info->DiagID, &*info->diagOptions, info->DiagClient); #else info->Diags = new DiagnosticsEngine(info->DiagID, info->DiagClient); #endif CompilerInvocation* CI = createInvocationFromCommandLine(clangArgs, info->Diags); // Get the codegen options from the clang command line. info->codegenOptions = CI->getCodeGenOpts(); // if --fast is given, we should be at least at -O3. if(fFastFlag && info->codegenOptions.OptimizationLevel < 3) { info->codegenOptions.OptimizationLevel = 3; } { // Make sure we include clang's internal header dir #if HAVE_LLVM_VER >= 34 SmallString<128> P; SmallString<128> P2; // avoids a valgrind overlapping memcpy P = clangexe; // Remove /clang from foo/bin/clang P2 = sys::path::parent_path(P); // Remove /bin from foo/bin P = sys::path::parent_path(P2); if( ! P.equals("") ) { // Get foo/lib/clang/<version>/ sys::path::append(P, "lib"); sys::path::append(P, "clang"); sys::path::append(P, CLANG_VERSION_STRING); } CI->getHeaderSearchOpts().ResourceDir = P.str(); sys::path::append(P, "include"); #else sys::Path P(clangexe); if (!P.isEmpty()) { P.eraseComponent(); // Remove /clang from foo/bin/clang P.eraseComponent(); // Remove /bin from foo/bin // Get foo/lib/clang/<version>/ P.appendComponent("lib"); P.appendComponent("clang"); P.appendComponent(CLANG_VERSION_STRING); } CI->getHeaderSearchOpts().ResourceDir = P.str(); sys::Path P2(P); P.appendComponent("include"); #endif #if HAVE_LLVM_VER >= 33 CI->getHeaderSearchOpts().AddPath( P.str(), frontend::System,false, false); #else CI->getHeaderSearchOpts().AddPath( P.str(), frontend::System,false, false, false, true, false); #endif } // Create a compiler instance to handle the actual work. info->Clang = new CompilerInstance(); info->Clang->setInvocation(CI); // Save the TargetOptions and LangOptions since these // are used during machine code generation. info->clangTargetOptions = info->Clang->getTargetOpts(); info->clangLangOptions = info->Clang->getLangOpts(); // Create the compilers actual diagnostics engine. // Create the compilers actual diagnostics engine. #if HAVE_LLVM_VER >= 33 info->Clang->createDiagnostics(); #else info->Clang->createDiagnostics(int(clangArgs.size()),&clangArgs[0]); #endif if (!info->Clang->hasDiagnostics()) INT_FATAL("Bad diagnostics from clang"); } void finishCodegenLLVM() { GenInfo* info = gGenInfo; // Codegen extra stuff for global-to-wide optimization. setupForGlobalToWide(); // Finish up our cleanup optimizers... info->FPM_postgen->doFinalization(); // We don't need our postgen function pass manager anymore. delete info->FPM_postgen; info->FPM_postgen = NULL; // Now finish any Clang code generation. finishClang(info); if(debug_info)debug_info->finalize(); // Verify the LLVM module. if( developer ) { bool problems; #if HAVE_LLVM_VER >= 35 problems = verifyModule(*info->module, &errs()); //problems = false; #else problems = verifyModule(*info->module, PrintMessageAction); #endif if(problems) { INT_FATAL("LLVM module verification failed"); } } } void prepareCodegenLLVM() { GenInfo *info = gGenInfo; LEGACY_FUNCTION_PASS_MANAGER *fpm = new LEGACY_FUNCTION_PASS_MANAGER(info->module); PassManagerBuilder PMBuilder; // Set up the optimizer pipeline. // Start with registering info about how the // target lays out data structures. #if HAVE_LLVM_VER >= 37 // We already set the data layout in setupClangContext // don't need to do anything else. #elif HAVE_LLVM_VER >= 36 // We already set the data layout in setupClangContext fpm->add(new DataLayoutPass()); #elif HAVE_LLVM_VER >= 35 fpm->add(new DataLayoutPass(info->module)); #else fpm->add(new DataLayout(info->module)); #endif if( fFastFlag ) { PMBuilder.OptLevel = 2; PMBuilder.populateFunctionPassManager(*fpm); } info->FPM_postgen = fpm; info->FPM_postgen->doInitialization(); } #if HAVE_LLVM_VER >= 33 static void handleErrorLLVM(void* user_data, const std::string& reason, bool gen_crash_diag) #else static void handleErrorLLVM(void* user_data, const std::string& reason) #endif { INT_FATAL("llvm fatal error: %s", reason.c_str()); } struct ExternBlockInfo { GenInfo* gen_info; fileinfo file; ExternBlockInfo() : gen_info(NULL), file() { } ~ExternBlockInfo() { } }; typedef std::set<ModuleSymbol*> module_set_t; typedef module_set_t::iterator module_set_iterator_t; module_set_t gModulesWithExternBlocks; bool lookupInExternBlock(ModuleSymbol* module, const char* name, clang::TypeDecl** cTypeOut, clang::ValueDecl** cValueOut, ChapelType** chplTypeOut) { if( ! module->extern_info ) return false; module->extern_info->gen_info->lvt->getCDecl(name, cTypeOut, cValueOut); VarSymbol* var = module->extern_info->gen_info->lvt->getVarSymbol(name); if( var ) *chplTypeOut = var->typeInfo(); return ( (*cTypeOut) || (*cValueOut) || (*chplTypeOut) ); } bool alreadyConvertedExtern(ModuleSymbol* module, const char* name) { return module->extern_info->gen_info->lvt->isAlreadyInChapelAST(name); } bool setAlreadyConvertedExtern(ModuleSymbol* module, const char* name) { return module->extern_info->gen_info->lvt->markAddedToChapelAST(name); } void runClang(const char* just_parse_filename) { static bool is_installed_fatal_error_handler = false; /* TODO -- note that clang/examples/clang-interpreter/main.cpp includes an example for getting the executable path, so that we could automatically set CHPL_HOME. */ std::string home(CHPL_HOME); std::string compileline = home + "/util/config/compileline"; compileline += " COMP_GEN_WARN="; compileline += istr(ccwarnings); compileline += " COMP_GEN_DEBUG="; compileline += istr(debugCCode); compileline += " COMP_GEN_OPT="; compileline += istr(optimizeCCode); compileline += " COMP_GEN_SPECIALIZE="; compileline += istr(specializeCCode); compileline += " COMP_GEN_FLOAT_OPT="; compileline += istr(ffloatOpt); std::string readargsfrom; if( !llvmCodegen && just_parse_filename ) { // We're handling an extern block and not using the LLVM backend. // Don't ask for any compiler-specific C flags. readargsfrom = compileline + " --llvm" " --clang" " --clang-sysroot-arguments" " --includes-and-defines"; } else { // We're parsing extern blocks AND any parts of the runtime // in order to prepare for an --llvm compilation. // Use compiler-specific flags for clang-included. readargsfrom = compileline + " --llvm" " --clang" " --clang-sysroot-arguments" " --cflags" " --includes-and-defines"; } std::vector<std::string> args; std::vector<std::string> clangCCArgs; std::vector<std::string> clangLDArgs; std::vector<std::string> clangOtherArgs; std::string clangCC, clangCXX; // Gather information from readargsfrom into clangArgs. readArgsFromCommand(readargsfrom.c_str(), args); if( args.size() < 2 ) USR_FATAL("Could not find runtime dependencies for --llvm build"); clangCC = args[0]; clangCXX = args[1]; // Note that these CC arguments will be saved in info->clangCCArgs // and will be used when compiling C files as well. for( size_t i = 2; i < args.size(); ++i ) { clangCCArgs.push_back(args[i]); } forv_Vec(const char*, dirName, incDirs) { clangCCArgs.push_back(std::string("-I") + dirName); } clangCCArgs.push_back(std::string("-I") + getIntermediateDirName()); //split ccflags by spaces std::stringstream ccArgsStream(ccflags); std::string ccArg; while(ccArgsStream >> ccArg) clangCCArgs.push_back(ccArg); clangCCArgs.push_back("-pthread"); // libFlag and ldflags are handled during linking later. clangCCArgs.push_back("-DCHPL_GEN_CODE"); // Always include sys_basic because it might change the // behaviour of macros! clangOtherArgs.push_back("-include"); clangOtherArgs.push_back("sys_basic.h"); if (!just_parse_filename) { // Running clang to compile all runtime and extern blocks // Include header files from the command line. { int filenum = 0; while (const char* inputFilename = nthFilename(filenum++)) { if (isCHeader(inputFilename)) { clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(inputFilename); } } } // Include extern C blocks if( externC && gAllExternCode.filename ) { clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(gAllExternCode.filename); } } else { // Just running clang to parse the extern blocks for this module. clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(just_parse_filename); } if( printSystemCommands ) { printf("<internal clang> "); for( size_t i = 0; i < clangCCArgs.size(); i++ ) { printf("%s ", clangCCArgs[i].c_str()); } for( size_t i = 0; i < clangOtherArgs.size(); i++ ) { printf("%s ", clangOtherArgs[i].c_str()); } printf("\n"); } // Initialize gGenInfo // Toggle LLVM code generation in our clang run; // turn it off if we just wanted to parse some C. gGenInfo = new GenInfo(clangCC, clangCXX, compileline, clangCCArgs, clangLDArgs, clangOtherArgs, just_parse_filename != NULL); if( llvmCodegen || externC ) { GenInfo *info = gGenInfo; // Install an LLVM Fatal Error Handler. if (!is_installed_fatal_error_handler) { is_installed_fatal_error_handler = true; install_fatal_error_handler(handleErrorLLVM); } // Run the Start Generation action // Now initialize a code generator... // this will enable us to ask for addresses of static (inline) functions // and cause them to be emitted eventually. // CCodeGenAction is defined above. It traverses the C AST // and does the code generation. info->cgAction = new CCodeGenAction(); if (!info->Clang->ExecuteAction(*info->cgAction)) { if (just_parse_filename) { USR_FATAL("error running clang on extern block"); } else { USR_FATAL("error running clang during code generation"); } } if( ! info->parseOnly ) { // This seems to be needed, even though it is strange. // (otherwise we segfault in info->builder->CreateGlobalString) // Some IRBuilder methods, codegenning a string, // need a basic block in order to get to the module // so we create a dummy function to code generate into llvm::Type * voidTy = llvm::Type::getVoidTy(info->module->getContext()); std::vector<llvm::Type*> args; llvm::FunctionType * FT = llvm::FunctionType::get(voidTy, args, false); Function * F = Function::Create(FT, Function::InternalLinkage, "chplDummyFunction", info->module); llvm::BasicBlock *block = llvm::BasicBlock::Create(info->module->getContext(), "entry", F); info->builder->SetInsertPoint(block); } // read macros. May call IRBuilder methods to codegen a string, // so needs to happen after we set the insert point. readMacrosClang(); if( ! info->parseOnly ) { info->builder->CreateRetVoid(); } } } static void saveExternBlock(ModuleSymbol* module, const char* extern_code) { if( ! gAllExternCode.filename ) { openCFile(&gAllExternCode, "extern-code", "c"); INT_ASSERT(gAllExternCode.fptr); // Allow code in extern block to use malloc/calloc/realloc/free // Note though that e.g. strdup or other library routines that // allocate memory might still be an issue... fprintf(gAllExternCode.fptr, "#include \"chpl-mem-no-warning-macros.h\"\n"); } if( ! module->extern_info ) { // Figure out what file to place the C code into. module->extern_info = new ExternBlockInfo(); const char* name = astr("extern_block_", module->cname); openCFile(&module->extern_info->file, name, "c"); // Could put #ifndef/define/endif wrapper start here. } FILE* f = module->extern_info->file.fptr; INT_ASSERT(f); // Append the C code to that file. fputs(extern_code, f); // Always make sure it ends in a close semi (solves errors) fputs("\n;\n", f); // Add this module to the set of modules needing extern compilation. std::pair<module_set_iterator_t,bool> already_there; already_there = gModulesWithExternBlocks.insert(module); if( already_there.second ) { // A new element was added to the map -> // first time we have worked with this module. // Add a #include of this module's extern block code to the // global extern code file. fprintf(gAllExternCode.fptr, "#include \"%s\"\n", module->extern_info->file.filename); } } void readExternC(void) { // Handle extern C blocks. forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) { // Figure out the parent module symbol. ModuleSymbol* module = eb->getModule(); saveExternBlock(module, eb->c_code); } // Close extern_c_file. if( gAllExternCode.fptr ) closefile(&gAllExternCode); // Close any extern files for any modules we had generated code for. module_set_iterator_t it; for( it = gModulesWithExternBlocks.begin(); it != gModulesWithExternBlocks.end(); ++it ) { ModuleSymbol* module = *it; INT_ASSERT(module->extern_info); // Could put #ifndef/define/endif wrapper end here. closefile(&module->extern_info->file); // Now parse the extern C code for that module. runClang(module->extern_info->file.filename); // Now swap what went into the global layered value table // into the module's own layered value table. module->extern_info->gen_info = gGenInfo; gGenInfo = NULL; } } void cleanupExternC(void) { module_set_iterator_t it; for( it = gModulesWithExternBlocks.begin(); it != gModulesWithExternBlocks.end(); ++it ) { ModuleSymbol* module = *it; INT_ASSERT(module->extern_info); cleanupClang(module->extern_info->gen_info); delete module->extern_info->gen_info; delete module->extern_info; // Remove all ExternBlockStmts from this module. forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) { eb->remove(); } gExternBlockStmts.clear(); } } llvm::Function* getFunctionLLVM(const char* name) { GenInfo* info = gGenInfo; Function* fn = info->module->getFunction(name); if( fn ) return fn; GenRet got = info->lvt->getValue(name); if( got.val ) { fn = cast<Function>(got.val); return fn; } return NULL; } llvm::Type* getTypeLLVM(const char* name) { GenInfo* info = gGenInfo; llvm::Type* t = info->module->getTypeByName(name); if( t ) return t; t = info->lvt->getType(name); if( t ) return t; return NULL; } // should support TypedefDecl,EnumDecl,RecordDecl llvm::Type* codegenCType(const TypeDecl* td) { GenInfo* info = gGenInfo; CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes(); QualType qType; // handle TypedefDecl if( const TypedefNameDecl* tnd = dyn_cast<TypedefNameDecl>(td) ) { qType = tnd->getCanonicalDecl()->getUnderlyingType(); // had const Type *ctype = td->getUnderlyingType().getTypePtrOrNull(); //could also do: // qType = // tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else if( const EnumDecl* ed = dyn_cast<EnumDecl>(td) ) { qType = ed->getCanonicalDecl()->getIntegerType(); // could also use getPromotionType() //could also do: // qType = // tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else if( const RecordDecl* rd = dyn_cast<RecordDecl>(td) ) { RecordDecl *def = rd->getDefinition(); INT_ASSERT(def); qType=def->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else { INT_FATAL("Unknown clang type declaration"); } return cdt.ConvertTypeForMem(qType); } // should support FunctionDecl,VarDecl,EnumConstantDecl GenRet codegenCValue(const ValueDecl *vd) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { ret.c = vd->getName(); return ret; } if(const FunctionDecl *fd = dyn_cast<FunctionDecl>(vd)) { // It's a function decl. ret.val = info->cgBuilder->GetAddrOfFunction(fd); ret.isLVPtr = GEN_VAL; } else if(const VarDecl *vard = dyn_cast<VarDecl>(vd)) { // It's a (global) variable decl ret.val = info->cgBuilder->GetAddrOfGlobalVar(vard); ret.isLVPtr = GEN_PTR; } else if(const EnumConstantDecl *ed = dyn_cast<EnumConstantDecl>(vd)) { // It's a constant enum value APInt v = ed->getInitVal(); ret.isUnsigned = ! ed->getType()->hasSignedIntegerRepresentation(); CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes(); llvm::Type* type = cdt.ConvertTypeForMem(ed->getType()); ret.val = ConstantInt::get(type, v); ret.isLVPtr = GEN_VAL; } else { INT_FATAL("Unknown clang value declaration"); } return ret; } LayeredValueTable::LayeredValueTable(){ layers.push_front(map_type()); } void LayeredValueTable::addLayer(){ layers.push_front(map_type()); } void LayeredValueTable::removeLayer(){ if(layers.size() != 1) { layers.pop_front(); } } void LayeredValueTable::addValue( StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) { Storage store; store.u.value = value; store.isLVPtr = isLVPtr; store.isUnsigned = isUnsigned; (layers.front())[name] = store; } void LayeredValueTable::addGlobalValue( StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) { Storage store; store.u.value = value; store.isLVPtr = isLVPtr; store.isUnsigned = isUnsigned; (layers.back())[name] = store; } void LayeredValueTable::addGlobalValue(StringRef name, GenRet gend) { addGlobalValue(name, gend.val, gend.isLVPtr, gend.isUnsigned); } void LayeredValueTable::addGlobalType(StringRef name, llvm::Type *type) { Storage store; store.u.type = type; /*fprintf(stderr, "Adding global type %s ", name.str().c_str()); type->dump(); fprintf(stderr, "\n"); */ (layers.back())[name] = store; } void LayeredValueTable::addGlobalCDecl(NamedDecl* cdecl) { addGlobalCDecl(cdecl->getName(), cdecl); // Also file structs under 'struct struct_name' if(isa<RecordDecl>(cdecl)) { std::string sname = "struct "; sname += cdecl->getName(); addGlobalCDecl(sname, cdecl); } } void LayeredValueTable::addGlobalCDecl(StringRef name, NamedDecl* cdecl) { if(RecordDecl *rd = dyn_cast<RecordDecl>(cdecl)) { // For record decls, always use the completed definition // if it is available. // E.g., we might visit decls in this order: // struct stat { ... } // struct stat; RecordDecl* completed = rd->getDefinition(); if (completed) { // Use the completed version below. cdecl = completed; } } // Add to an existing Storage record, so that it can store // both a type and a value (e.g. struct stat and function stat). Storage & store = (layers.back())[name]; if (isa<TypeDecl>(cdecl)) store.u.cTypeDecl = cast<TypeDecl>(cdecl); if (isa<ValueDecl>(cdecl)) store.u.cValueDecl = cast<ValueDecl>(cdecl); } void LayeredValueTable::addGlobalVarSymbol(llvm::StringRef name, VarSymbol* var) { Storage store; store.u.chplVar = var; (layers.back())[name] = store; } void LayeredValueTable::addBlock(StringRef name, llvm::BasicBlock *block) { Storage store; store.u.block = block; layer_iterator blockLayer = --layers.end(); if(layers.size() > 1) { blockLayer = --blockLayer; } (*blockLayer)[name] = store; } GenRet LayeredValueTable::getValue(StringRef name) { if(Storage *store = get(name)) { if( store->u.value ) { INT_ASSERT(isa<Value>(store->u.value)); GenRet ret; ret.val = store->u.value; ret.isLVPtr = store->isLVPtr; ret.isUnsigned = store->isUnsigned; return ret; } if( store->u.cValueDecl ) { INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl)); // we have a clang value decl. // maybe FunctionDecl,VarDecl,EnumConstantDecl // Convert it to an LLVM value // should support FunctionDecl,VarDecl,EnumConstantDecl return codegenCValue(store->u.cValueDecl); } if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) { VarSymbol* var = store->u.chplVar; GenRet ret = var; // code generate it! return ret; } } GenRet ret; return ret; } llvm::BasicBlock *LayeredValueTable::getBlock(StringRef name) { if(Storage *store = get(name)) { if( store->u.block && isa<llvm::BasicBlock>(store->u.block) ) return store->u.block; } return NULL; } llvm::Type *LayeredValueTable::getType(StringRef name) { if(Storage *store = get(name)) { if( store->u.type ) { INT_ASSERT(isa<llvm::Type>(store->u.type)); return store->u.type; } if( store->u.cTypeDecl ) { INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl)); // we have a clang type decl. // maybe TypedefDecl,EnumDecl,RecordDecl // Convert it to an LLVM type. return codegenCType(store->u.cTypeDecl); } } return NULL; } // Returns a type or a name decl for a given name // Note that C can have a function and a type sharing the same name // (e.g. stat/struct stat). // Sets the output arguments to NULL if a type/value was not found. // Either output argument can be NULL. void LayeredValueTable::getCDecl(StringRef name, TypeDecl** cTypeOut, ValueDecl** cValueOut) { if (cValueOut) *cValueOut = NULL; if (cTypeOut) *cTypeOut = NULL; if(Storage *store = get(name)) { if( store->u.cValueDecl ) { INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl)); // we have a clang value decl. // maybe FunctionDecl,VarDecl,EnumConstantDecl if (cValueOut) *cValueOut = store->u.cValueDecl; } if( store->u.cTypeDecl ) { INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl)); // we have a clang type decl. // maybe TypedefDecl,EnumDecl,RecordDecl if (cTypeOut) *cTypeOut = store->u.cTypeDecl; } } } VarSymbol* LayeredValueTable::getVarSymbol(StringRef name) { if(Storage *store = get(name)) { if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) { // we have a Chapel Var Symbol. // maybe immediate number or string, possibly variable reference. // These come from macros. return store->u.chplVar; } } return NULL; } LayeredValueTable::Storage* LayeredValueTable::get(StringRef name) { for(layer_iterator i = layers.begin(); i != layers.end(); ++i) { value_iterator j = i->find(name); if(j != i->end()) { return &j->second; } } return NULL; } bool LayeredValueTable::isAlreadyInChapelAST(llvm::StringRef name) { if(Storage *store = get(name)) { return store->addedToChapelAST; } return false; } bool LayeredValueTable::markAddedToChapelAST(llvm::StringRef name) { if(Storage *store = get(name)) { if( store->addedToChapelAST ) return false; store->addedToChapelAST = true; return true; } else { // Otherwise, make a new entry. Storage toStore; toStore.addedToChapelAST = true; (layers.back())[name] = toStore; return true; } } void LayeredValueTable::swap(LayeredValueTable* other) { this->layers.swap(other->layers); } int getCRecordMemberGEP(const char* typeName, const char* fieldName) { GenInfo* info = gGenInfo; TypeDecl* d = NULL; int ret; info->lvt->getCDecl(typeName, &d, NULL); INT_ASSERT(d); if( isa<TypedefDecl>(d) ) { TypedefDecl* td = cast<TypedefDecl>(d); const clang::Type* t = td->getUnderlyingType().getTypePtr(); while( t->isPointerType() ) { t = t->getPointeeType().getTypePtr(); } const RecordType* rt = t->getAsStructureType(); INT_ASSERT(rt); d = rt->getDecl(); // getAsUnionType also available, but we don't support extern unions } INT_ASSERT(isa<RecordDecl>(d)); RecordDecl* rec = cast<RecordDecl>(d); // Find the field decl. RecordDecl::field_iterator it; FieldDecl* field = NULL; for( it = rec->field_begin(); it != rec->field_end(); ++it ) { if( fieldName == it->getName() ) { field = *it; break; } } INT_ASSERT(field); ret=info->cgBuilder->getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); return ret; } bool isBuiltinExternCFunction(const char* cname) { if( 0 == strcmp(cname, "sizeof") ) return true; else return false; } static void addAggregateGlobalOps(const PassManagerBuilder &Builder, LEGACY_PASS_MANAGER &PM) { GenInfo* info = gGenInfo; if( fLLVMWideOpt ) { PM.add(createAggregateGlobalOpsOptPass(info->globalToWideInfo.globalSpace)); } } static void addGlobalToWide(const PassManagerBuilder &Builder, LEGACY_PASS_MANAGER &PM) { GenInfo* info = gGenInfo; if( fLLVMWideOpt ) { PM.add(createGlobalToWide(&info->globalToWideInfo, info->targetLayout)); } } // If we're using the LLVM wide optimizations, we have to add // some functions to call put/get into the Chapel runtime layers // (the optimization is meant to be portable to other languages) static void setupForGlobalToWide(void) { if( ! fLLVMWideOpt ) return; GenInfo* ginfo = gGenInfo; GlobalToWideInfo* info = &ginfo->globalToWideInfo; info->localeIdType = ginfo->lvt->getType("chpl_localeID_t"); assert(info->localeIdType); info->nodeIdType = ginfo->lvt->getType("c_nodeid_t"); assert(info->nodeIdType); info->addrFn = getFunctionLLVM("chpl_wide_ptr_get_address"); INT_ASSERT(info->addrFn); info->locFn = getFunctionLLVM("chpl_wide_ptr_read_localeID"); INT_ASSERT(info->locFn); info->nodeFn = getFunctionLLVM("chpl_wide_ptr_get_node"); INT_ASSERT(info->nodeFn); info->makeFn = getFunctionLLVM("chpl_return_wide_ptr_loc_ptr"); INT_ASSERT(info->makeFn); info->getFn = getFunctionLLVM("chpl_gen_comm_get_ctl"); INT_ASSERT(info->getFn); info->putFn = getFunctionLLVM("chpl_gen_comm_put_ctl"); INT_ASSERT(info->putFn); info->getPutFn = getFunctionLLVM("chpl_gen_comm_getput"); INT_ASSERT(info->getPutFn); info->memsetFn = getFunctionLLVM("chpl_gen_comm_memset"); INT_ASSERT(info->memsetFn); // Call these functions in a dummy externally visible // function which GlobalToWide should remove. We need to do that // in order to prevent the functions from being removed for // not having references when they are inline/internal linkage. // Our function here just returns a pointer to the i'th (i is the argument) // such function - and since it is marked externally visible, there // is no way that the compiler can completely remove the needed // runtime functions. const char* dummy = "chpl_wide_opt_dummy"; if( getFunctionLLVM(dummy) ) INT_FATAL("dummy function already exists"); llvm::Type* retType = llvm::Type::getInt8PtrTy(ginfo->module->getContext()); llvm::Type* argType = llvm::Type::getInt64Ty(ginfo->module->getContext()); llvm::Value* fval = ginfo->module->getOrInsertFunction( dummy, retType, argType, NULL); llvm::Function* fn = llvm::dyn_cast<llvm::Function>(fval); // Mark the function as external so that it will not be removed fn->setLinkage(llvm::GlobalValue::ExternalLinkage); llvm::BasicBlock* block = llvm::BasicBlock::Create(ginfo->module->getContext(), "entry", fn); ginfo->builder->SetInsertPoint(block); llvm::Constant* fns[] = {info->addrFn, info->locFn, info->nodeFn, info->makeFn, info->getFn, info->putFn, info->getPutFn, info->memsetFn, NULL}; llvm::Value* ret = llvm::Constant::getNullValue(retType); llvm::Function::arg_iterator args = fn->arg_begin(); llvm::Value* arg = args++; for( int i = 0; fns[i]; i++ ) { llvm::Constant* f = fns[i]; llvm::Value* ptr = ginfo->builder->CreatePointerCast(f, retType); llvm::Value* id = llvm::ConstantInt::get(argType, i); llvm::Value* eq = ginfo->builder->CreateICmpEQ(arg, id); ret = ginfo->builder->CreateSelect(eq, ptr, ret); } ginfo->builder->CreateRet(ret); #if HAVE_LLVM_VER >= 35 llvm::verifyFunction(*fn, &errs()); #endif info->preservingFn = fn; } void makeBinaryLLVM(void) { #if HAVE_LLVM_VER >= 36 std::error_code errorInfo; #else std::string errorInfo; #endif GenInfo* info = gGenInfo; std::string moduleFilename = genIntermediateFilename("chpl__module.bc"); std::string preOptFilename = genIntermediateFilename("chpl__module-nopt.bc"); if( saveCDir[0] != '\0' ) { // Save the generated LLVM before optimization. tool_output_file output (preOptFilename.c_str(), errorInfo, #if HAVE_LLVM_VER >= 34 sys::fs::F_None #else raw_fd_ostream::F_Binary #endif ); WriteBitcodeToFile(info->module, output.os()); output.keep(); output.os().flush(); } tool_output_file output (moduleFilename.c_str(), errorInfo, #if HAVE_LLVM_VER >= 34 sys::fs::F_None #else raw_fd_ostream::F_Binary #endif ); static bool addedGlobalExts = false; if( ! addedGlobalExts ) { // Add the Global to Wide optimization if necessary. PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addAggregateGlobalOps); PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addGlobalToWide); PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addGlobalToWide); addedGlobalExts = true; } EmitBackendOutput(*info->Diags, info->codegenOptions, info->clangTargetOptions, info->clangLangOptions, #if HAVE_LLVM_VER >= 35 info->Ctx->getTargetInfo().getTargetDescription(), #endif info->module, Backend_EmitBC, &output.os()); output.keep(); output.os().flush(); //finishClang is before the call to the debug finalize deleteClang(info); std::string options = ""; std::string home(CHPL_HOME); std::string compileline = info->compileline; compileline += " --llvm" " --clang" " --main.o" " --clang-sysroot-arguments" " --libraries"; std::vector<std::string> args; readArgsFromCommand(compileline.c_str(), args); INT_ASSERT(args.size() >= 1); std::string clangCC = args[0]; std::string clangCXX = args[1]; std::string maino = args[2]; std::vector<std::string> dotOFiles; // Gather C flags for compiling C files. std::string cargs; for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) { cargs += " "; cargs += info->clangCCArgs[i]; } // Compile any C files. { // Start with configuration settings const char* inputFilename = gChplCompilationConfig.pathname; const char* objFilename = objectFileForCFile(inputFilename); mysystem(astr(clangCC.c_str(), " -c -o ", objFilename, " ", inputFilename, cargs.c_str()), "Compile C File"); dotOFiles.push_back(objFilename); } int filenum = 0; while (const char* inputFilename = nthFilename(filenum++)) { if (isCSource(inputFilename)) { const char* objFilename = objectFileForCFile(inputFilename); mysystem(astr(clangCC.c_str(), " -c -o ", objFilename, " ", inputFilename, cargs.c_str()), "Compile C File"); dotOFiles.push_back(objFilename); } else if( isObjFile(inputFilename) ) { dotOFiles.push_back(inputFilename); } } // Start linker options with C args // This is important to get e.g. -O3 -march=native // since with LLVM we are doing link-time optimization. // We know it's OK to include -I (e.g.) since we're calling // clang++ to link so that it can optimize the .bc files. options = cargs; if(debugCCode) { options += " -g"; } options += " "; options += ldflags; options += " -pthread"; // Now, if we're doing a multilocale build, we have to make a launcher. // For this reason, we create a makefile. codegen_makefile // also gives us the name of the temporary place to save // the generated program. fileinfo mainfile; mainfile.filename = "chpl__module.bc"; mainfile.pathname = moduleFilename.c_str(); const char* tmpbinname = NULL; codegen_makefile(&mainfile, &tmpbinname, true); INT_ASSERT(tmpbinname); // Run the linker. We always use clang++ because some third-party // libraries are written in C++. With the C backend, this switcheroo // is accomplished in the Makefiles somewhere std::string command = clangCXX + " " + options + " " + moduleFilename + " " + maino + " -o " + tmpbinname; for( size_t i = 0; i < dotOFiles.size(); i++ ) { command += " "; command += dotOFiles[i]; } // 0 is clang, 1 is clang++, 2 is main.o for(size_t i = 3; i < args.size(); ++i) { command += " "; command += args[i]; } // Put user-requested libraries at the end of the compile line, // they should at least be after the .o files and should be in // order where libraries depend on libraries to their right. for (int i=0; i<numLibFlags; i++) { command += " "; command += libFlag[i]; } if( printSystemCommands ) { printf("%s\n", command.c_str()); } mysystem(command.c_str(), "Make Binary - Linking"); // Now run the makefile to move from tmpbinname to the proper program // name and to build a launcher (if necessary). const char* makeflags = printSystemCommands ? "-f " : "-s -f "; const char* makecmd = astr(astr(CHPL_MAKE, " "), makeflags, getIntermediateDirName(), "/Makefile"); if( printSystemCommands ) { printf("%s\n", makecmd); } mysystem(makecmd, "Make Binary - Building Launcher and Copying"); } #endif
31.766304
219
0.653052
krishnakeshav
fd65a275b913fb8299109047f325f9caef81e801
160
cpp
C++
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
#include "output.h"//use file code that I created #include<iostream>//use standard library using std::cout; int main() { cout<<"Hello World!"; return 0; }
14.545455
49
0.6875
acc-cosc-1337-spring-2020
fd6b2581413138bd5080f874be9df0cf35e6fb1c
37,123
cc
C++
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
8
2018-12-27T14:57:13.000Z
2021-04-07T07:03:15.000Z
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
1
2019-03-13T01:35:03.000Z
2020-10-08T04:13:04.000Z
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
9
2018-12-28T11:45:12.000Z
2021-05-11T02:15:31.000Z
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_processing/audio_processing_impl.h" #include <assert.h> #include "webrtc/base/checks.h" #include "webrtc/base/platform_file.h" #include "webrtc/common_audio/include/audio_util.h" #include "webrtc/common_audio/channel_buffer.h" #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h" extern "C" { #include "webrtc/modules/audio_processing/aec/aec_core.h" } #include "webrtc/modules/audio_processing/agc/agc_manager_direct.h" #include "webrtc/modules/audio_processing/audio_buffer.h" #include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h" #include "webrtc/modules/audio_processing/common.h" #include "webrtc/modules/audio_processing/echo_cancellation_impl.h" #include "webrtc/modules/audio_processing/echo_control_mobile_impl.h" #include "webrtc/modules/audio_processing/gain_control_impl.h" #include "webrtc/modules/audio_processing/high_pass_filter_impl.h" #include "webrtc/modules/audio_processing/level_estimator_impl.h" #include "webrtc/modules/audio_processing/noise_suppression_impl.h" #include "webrtc/modules/audio_processing/processing_component.h" #include "webrtc/modules/audio_processing/transient/transient_suppressor.h" #include "webrtc/modules/audio_processing/voice_detection_impl.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/file_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/metrics.h" #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Files generated at build-time by the protobuf compiler. #ifdef WEBRTC_ANDROID_PLATFORM_BUILD #include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h" #else #include "webrtc/audio_processing/debug.pb.h" #endif #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP #define RETURN_ON_ERR(expr) \ do { \ int err = (expr); \ if (err != kNoError) { \ return err; \ } \ } while (0) namespace webrtc { // Throughout webrtc, it's assumed that success is represented by zero. static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero"); // This class has two main functionalities: // // 1) It is returned instead of the real GainControl after the new AGC has been // enabled in order to prevent an outside user from overriding compression // settings. It doesn't do anything in its implementation, except for // delegating the const methods and Enable calls to the real GainControl, so // AGC can still be disabled. // // 2) It is injected into AgcManagerDirect and implements volume callbacks for // getting and setting the volume level. It just caches this value to be used // in VoiceEngine later. class GainControlForNewAgc : public GainControl, public VolumeCallbacks { public: explicit GainControlForNewAgc(GainControlImpl* gain_control) : real_gain_control_(gain_control), volume_(0) { } // GainControl implementation. int Enable(bool enable) override { return real_gain_control_->Enable(enable); } bool is_enabled() const override { return real_gain_control_->is_enabled(); } int set_stream_analog_level(int level) override { volume_ = level; return AudioProcessing::kNoError; } int stream_analog_level() override { return volume_; } int set_mode(Mode mode) override { return AudioProcessing::kNoError; } Mode mode() const override { return GainControl::kAdaptiveAnalog; } int set_target_level_dbfs(int level) override { return AudioProcessing::kNoError; } int target_level_dbfs() const override { return real_gain_control_->target_level_dbfs(); } int set_compression_gain_db(int gain) override { return AudioProcessing::kNoError; } int compression_gain_db() const override { return real_gain_control_->compression_gain_db(); } int enable_limiter(bool enable) override { return AudioProcessing::kNoError; } bool is_limiter_enabled() const override { return real_gain_control_->is_limiter_enabled(); } int set_analog_level_limits(int minimum, int maximum) override { return AudioProcessing::kNoError; } int analog_level_minimum() const override { return real_gain_control_->analog_level_minimum(); } int analog_level_maximum() const override { return real_gain_control_->analog_level_maximum(); } bool stream_is_saturated() const override { return real_gain_control_->stream_is_saturated(); } // VolumeCallbacks implementation. void SetMicVolume(int volume) override { volume_ = volume; } int GetMicVolume() override { return volume_; } private: GainControl* real_gain_control_; int volume_; }; AudioProcessing* AudioProcessing::Create() { Config config; return Create(config, nullptr); } AudioProcessing* AudioProcessing::Create(const Config& config) { return Create(config, nullptr); } AudioProcessing* AudioProcessing::Create(const Config& config, Beamformer<float>* beamformer) { AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer); if (apm->Initialize() != kNoError) { delete apm; apm = NULL; } return apm; } AudioProcessingImpl::AudioProcessingImpl(const Config& config) : AudioProcessingImpl(config, nullptr) {} AudioProcessingImpl::AudioProcessingImpl(const Config& config, Beamformer<float>* beamformer) : echo_cancellation_(NULL), echo_control_mobile_(NULL), gain_control_(NULL), high_pass_filter_(NULL), level_estimator_(NULL), noise_suppression_(NULL), voice_detection_(NULL), crit_(CriticalSectionWrapper::CreateCriticalSection()), #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP debug_file_(FileWrapper::Create()), event_msg_(new audioproc::Event()), #endif fwd_in_format_(kSampleRate16kHz, 1), fwd_proc_format_(kSampleRate16kHz), fwd_out_format_(kSampleRate16kHz, 1), rev_in_format_(kSampleRate16kHz, 1), rev_proc_format_(kSampleRate16kHz, 1), split_rate_(kSampleRate16kHz), stream_delay_ms_(0), delay_offset_ms_(0), was_stream_delay_set_(false), last_stream_delay_ms_(0), last_aec_system_delay_ms_(0), output_will_be_muted_(false), key_pressed_(false), #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) use_new_agc_(false), #else use_new_agc_(config.Get<ExperimentalAgc>().enabled), #endif agc_startup_min_volume_(config.Get<ExperimentalAgc>().startup_min_volume), #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) transient_suppressor_enabled_(false), #else transient_suppressor_enabled_(config.Get<ExperimentalNs>().enabled), #endif beamformer_enabled_(config.Get<Beamforming>().enabled), beamformer_(beamformer), array_geometry_(config.Get<Beamforming>().array_geometry), supports_48kHz_(config.Get<AudioProcessing48kHzSupport>().enabled) { echo_cancellation_ = new EchoCancellationImpl(this, crit_); component_list_.push_back(echo_cancellation_); echo_control_mobile_ = new EchoControlMobileImpl(this, crit_); component_list_.push_back(echo_control_mobile_); gain_control_ = new GainControlImpl(this, crit_); component_list_.push_back(gain_control_); high_pass_filter_ = new HighPassFilterImpl(this, crit_); component_list_.push_back(high_pass_filter_); level_estimator_ = new LevelEstimatorImpl(this, crit_); component_list_.push_back(level_estimator_); noise_suppression_ = new NoiseSuppressionImpl(this, crit_); component_list_.push_back(noise_suppression_); voice_detection_ = new VoiceDetectionImpl(this, crit_); component_list_.push_back(voice_detection_); gain_control_for_new_agc_.reset(new GainControlForNewAgc(gain_control_)); SetExtraOptions(config); } AudioProcessingImpl::~AudioProcessingImpl() { { CriticalSectionScoped crit_scoped(crit_); // Depends on gain_control_ and gain_control_for_new_agc_. agc_manager_.reset(); // Depends on gain_control_. gain_control_for_new_agc_.reset(); while (!component_list_.empty()) { ProcessingComponent* component = component_list_.front(); component->Destroy(); delete component; component_list_.pop_front(); } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { debug_file_->CloseFile(); } #endif } delete crit_; crit_ = NULL; } int AudioProcessingImpl::Initialize() { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(); } int AudioProcessingImpl::set_sample_rate_hz(int rate) { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(rate, rate, rev_in_format_.rate(), fwd_in_format_.num_channels(), fwd_out_format_.num_channels(), rev_in_format_.num_channels()); } int AudioProcessingImpl::Initialize(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, ChannelLayout input_layout, ChannelLayout output_layout, ChannelLayout reverse_layout) { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(input_sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz, ChannelsFromLayout(input_layout), ChannelsFromLayout(output_layout), ChannelsFromLayout(reverse_layout)); } int AudioProcessingImpl::InitializeLocked() { const int fwd_audio_buffer_channels = beamformer_enabled_ ? fwd_in_format_.num_channels() : fwd_out_format_.num_channels(); render_audio_.reset(new AudioBuffer(rev_in_format_.samples_per_channel(), rev_in_format_.num_channels(), rev_proc_format_.samples_per_channel(), rev_proc_format_.num_channels(), rev_proc_format_.samples_per_channel())); capture_audio_.reset(new AudioBuffer(fwd_in_format_.samples_per_channel(), fwd_in_format_.num_channels(), fwd_proc_format_.samples_per_channel(), fwd_audio_buffer_channels, fwd_out_format_.samples_per_channel())); // Initialize all components. for (auto item : component_list_) { int err = item->Initialize(); if (err != kNoError) { return err; } } InitializeExperimentalAgc(); InitializeTransient(); InitializeBeamformer(); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { int err = WriteInitMessage(); if (err != kNoError) { return err; } } #endif return kNoError; } int AudioProcessingImpl::InitializeLocked(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, int num_input_channels, int num_output_channels, int num_reverse_channels) { if (input_sample_rate_hz <= 0 || output_sample_rate_hz <= 0 || reverse_sample_rate_hz <= 0) { return kBadSampleRateError; } if (num_output_channels > num_input_channels) { return kBadNumberChannelsError; } // Only mono and stereo supported currently. if (num_input_channels > 2 || num_input_channels < 1 || num_output_channels > 2 || num_output_channels < 1 || num_reverse_channels > 2 || num_reverse_channels < 1) { return kBadNumberChannelsError; } if (beamformer_enabled_ && (static_cast<size_t>(num_input_channels) != array_geometry_.size() || num_output_channels > 1)) { return kBadNumberChannelsError; } fwd_in_format_.set(input_sample_rate_hz, num_input_channels); fwd_out_format_.set(output_sample_rate_hz, num_output_channels); rev_in_format_.set(reverse_sample_rate_hz, num_reverse_channels); // We process at the closest native rate >= min(input rate, output rate)... int min_proc_rate = std::min(fwd_in_format_.rate(), fwd_out_format_.rate()); int fwd_proc_rate; if (supports_48kHz_ && min_proc_rate > kSampleRate32kHz) { fwd_proc_rate = kSampleRate48kHz; } else if (min_proc_rate > kSampleRate16kHz) { fwd_proc_rate = kSampleRate32kHz; } else if (min_proc_rate > kSampleRate8kHz) { fwd_proc_rate = kSampleRate16kHz; } else { fwd_proc_rate = kSampleRate8kHz; } // ...with one exception. if (echo_control_mobile_->is_enabled() && min_proc_rate > kSampleRate16kHz) { fwd_proc_rate = kSampleRate16kHz; } fwd_proc_format_.set(fwd_proc_rate); // We normally process the reverse stream at 16 kHz. Unless... int rev_proc_rate = kSampleRate16kHz; if (fwd_proc_format_.rate() == kSampleRate8kHz) { // ...the forward stream is at 8 kHz. rev_proc_rate = kSampleRate8kHz; } else { if (rev_in_format_.rate() == kSampleRate32kHz) { // ...or the input is at 32 kHz, in which case we use the splitting // filter rather than the resampler. rev_proc_rate = kSampleRate32kHz; } } // Always downmix the reverse stream to mono for analysis. This has been // demonstrated to work well for AEC in most practical scenarios. rev_proc_format_.set(rev_proc_rate, 1); if (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz) { split_rate_ = kSampleRate16kHz; } else { split_rate_ = fwd_proc_format_.rate(); } return InitializeLocked(); } // Calls InitializeLocked() if any of the audio parameters have changed from // their current values. int AudioProcessingImpl::MaybeInitializeLocked(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, int num_input_channels, int num_output_channels, int num_reverse_channels) { if (input_sample_rate_hz == fwd_in_format_.rate() && output_sample_rate_hz == fwd_out_format_.rate() && reverse_sample_rate_hz == rev_in_format_.rate() && num_input_channels == fwd_in_format_.num_channels() && num_output_channels == fwd_out_format_.num_channels() && num_reverse_channels == rev_in_format_.num_channels()) { return kNoError; } return InitializeLocked(input_sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz, num_input_channels, num_output_channels, num_reverse_channels); } void AudioProcessingImpl::SetExtraOptions(const Config& config) { CriticalSectionScoped crit_scoped(crit_); for (auto item : component_list_) { item->SetExtraOptions(config); } if (transient_suppressor_enabled_ != config.Get<ExperimentalNs>().enabled) { transient_suppressor_enabled_ = config.Get<ExperimentalNs>().enabled; InitializeTransient(); } } int AudioProcessingImpl::input_sample_rate_hz() const { CriticalSectionScoped crit_scoped(crit_); return fwd_in_format_.rate(); } int AudioProcessingImpl::sample_rate_hz() const { CriticalSectionScoped crit_scoped(crit_); return fwd_in_format_.rate(); } int AudioProcessingImpl::proc_sample_rate_hz() const { return fwd_proc_format_.rate(); } int AudioProcessingImpl::proc_split_sample_rate_hz() const { return split_rate_; } int AudioProcessingImpl::num_reverse_channels() const { return rev_proc_format_.num_channels(); } int AudioProcessingImpl::num_input_channels() const { return fwd_in_format_.num_channels(); } int AudioProcessingImpl::num_output_channels() const { return fwd_out_format_.num_channels(); } void AudioProcessingImpl::set_output_will_be_muted(bool muted) { CriticalSectionScoped lock(crit_); output_will_be_muted_ = muted; if (agc_manager_.get()) { agc_manager_->SetCaptureMuted(output_will_be_muted_); } } bool AudioProcessingImpl::output_will_be_muted() const { CriticalSectionScoped lock(crit_); return output_will_be_muted_; } int AudioProcessingImpl::ProcessStream(const float* const* src, int samples_per_channel, int input_sample_rate_hz, ChannelLayout input_layout, int output_sample_rate_hz, ChannelLayout output_layout, float* const* dest) { CriticalSectionScoped crit_scoped(crit_); if (!src || !dest) { return kNullPointerError; } RETURN_ON_ERR(MaybeInitializeLocked(input_sample_rate_hz, output_sample_rate_hz, rev_in_format_.rate(), ChannelsFromLayout(input_layout), ChannelsFromLayout(output_layout), rev_in_format_.num_channels())); if (samples_per_channel != fwd_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::STREAM); audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t channel_size = sizeof(float) * fwd_in_format_.samples_per_channel(); for (int i = 0; i < fwd_in_format_.num_channels(); ++i) msg->add_input_channel(src[i], channel_size); } #endif capture_audio_->CopyFrom(src, samples_per_channel, input_layout); RETURN_ON_ERR(ProcessStreamLocked()); capture_audio_->CopyTo(fwd_out_format_.samples_per_channel(), output_layout, dest); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t channel_size = sizeof(float) * fwd_out_format_.samples_per_channel(); for (int i = 0; i < fwd_out_format_.num_channels(); ++i) msg->add_output_channel(dest[i], channel_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif return kNoError; } int AudioProcessingImpl::ProcessStream(AudioFrame* frame) { CriticalSectionScoped crit_scoped(crit_); if (!frame) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } if (echo_control_mobile_->is_enabled() && frame->sample_rate_hz_ > kSampleRate16kHz) { LOG(LS_ERROR) << "AECM only supports 16 or 8 kHz sample rates"; return kUnsupportedComponentError; } // TODO(ajm): The input and output rates and channels are currently // constrained to be identical in the int16 interface. RETURN_ON_ERR(MaybeInitializeLocked(frame->sample_rate_hz_, frame->sample_rate_hz_, rev_in_format_.rate(), frame->num_channels_, frame->num_channels_, rev_in_format_.num_channels())); if (frame->samples_per_channel_ != fwd_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::STREAM); audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_input_data(frame->data_, data_size); } #endif capture_audio_->DeinterleaveFrom(frame); RETURN_ON_ERR(ProcessStreamLocked()); capture_audio_->InterleaveTo(frame, output_copy_needed(is_data_processed())); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_output_data(frame->data_, data_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif return kNoError; } int AudioProcessingImpl::ProcessStreamLocked() { #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); msg->set_delay(stream_delay_ms_); msg->set_drift(echo_cancellation_->stream_drift_samples()); msg->set_level(gain_control()->stream_analog_level()); msg->set_keypress(key_pressed_); } #endif MaybeUpdateHistograms(); AudioBuffer* ca = capture_audio_.get(); // For brevity. if (use_new_agc_ && gain_control_->is_enabled()) { agc_manager_->AnalyzePreProcess(ca->channels()[0], ca->num_channels(), fwd_proc_format_.samples_per_channel()); } bool data_processed = is_data_processed(); if (analysis_needed(data_processed)) { ca->SplitIntoFrequencyBands(); } if (beamformer_enabled_) { beamformer_->ProcessChunk(*ca->split_data_f(), ca->split_data_f()); ca->set_num_channels(1); } RETURN_ON_ERR(high_pass_filter_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(gain_control_->AnalyzeCaptureAudio(ca)); RETURN_ON_ERR(noise_suppression_->AnalyzeCaptureAudio(ca)); RETURN_ON_ERR(echo_cancellation_->ProcessCaptureAudio(ca)); if (echo_control_mobile_->is_enabled() && noise_suppression_->is_enabled()) { ca->CopyLowPassToReference(); } RETURN_ON_ERR(noise_suppression_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(echo_control_mobile_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(voice_detection_->ProcessCaptureAudio(ca)); if (use_new_agc_ && gain_control_->is_enabled() && (!beamformer_enabled_ || beamformer_->is_target_present())) { agc_manager_->Process(ca->split_bands_const(0)[kBand0To8kHz], ca->num_frames_per_band(), split_rate_); } RETURN_ON_ERR(gain_control_->ProcessCaptureAudio(ca)); if (synthesis_needed(data_processed)) { ca->MergeFrequencyBands(); } // TODO(aluebs): Investigate if the transient suppression placement should be // before or after the AGC. if (transient_suppressor_enabled_) { float voice_probability = agc_manager_.get() ? agc_manager_->voice_probability() : 1.f; transient_suppressor_->Suppress(ca->channels_f()[0], ca->num_frames(), ca->num_channels(), ca->split_bands_const_f(0)[kBand0To8kHz], ca->num_frames_per_band(), ca->keyboard_data(), ca->num_keyboard_frames(), voice_probability, key_pressed_); } // The level estimator operates on the recombined data. RETURN_ON_ERR(level_estimator_->ProcessStream(ca)); was_stream_delay_set_ = false; return kNoError; } int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data, int samples_per_channel, int sample_rate_hz, ChannelLayout layout) { CriticalSectionScoped crit_scoped(crit_); if (data == NULL) { return kNullPointerError; } const int num_channels = ChannelsFromLayout(layout); RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(), fwd_out_format_.rate(), sample_rate_hz, fwd_in_format_.num_channels(), fwd_out_format_.num_channels(), num_channels)); if (samples_per_channel != rev_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::REVERSE_STREAM); audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream(); const size_t channel_size = sizeof(float) * rev_in_format_.samples_per_channel(); for (int i = 0; i < num_channels; ++i) msg->add_channel(data[i], channel_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif render_audio_->CopyFrom(data, samples_per_channel, layout); return AnalyzeReverseStreamLocked(); } int AudioProcessingImpl::AnalyzeReverseStream(AudioFrame* frame) { CriticalSectionScoped crit_scoped(crit_); if (frame == NULL) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } // This interface does not tolerate different forward and reverse rates. if (frame->sample_rate_hz_ != fwd_in_format_.rate()) { return kBadSampleRateError; } RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(), fwd_out_format_.rate(), frame->sample_rate_hz_, fwd_in_format_.num_channels(), fwd_in_format_.num_channels(), frame->num_channels_)); if (frame->samples_per_channel_ != rev_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::REVERSE_STREAM); audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_data(frame->data_, data_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif render_audio_->DeinterleaveFrom(frame); return AnalyzeReverseStreamLocked(); } int AudioProcessingImpl::AnalyzeReverseStreamLocked() { AudioBuffer* ra = render_audio_.get(); // For brevity. if (rev_proc_format_.rate() == kSampleRate32kHz) { ra->SplitIntoFrequencyBands(); } RETURN_ON_ERR(echo_cancellation_->ProcessRenderAudio(ra)); RETURN_ON_ERR(echo_control_mobile_->ProcessRenderAudio(ra)); if (!use_new_agc_) { RETURN_ON_ERR(gain_control_->ProcessRenderAudio(ra)); } return kNoError; } int AudioProcessingImpl::set_stream_delay_ms(int delay) { Error retval = kNoError; was_stream_delay_set_ = true; delay += delay_offset_ms_; if (delay < 0) { delay = 0; retval = kBadStreamParameterWarning; } // TODO(ajm): the max is rather arbitrarily chosen; investigate. if (delay > 500) { delay = 500; retval = kBadStreamParameterWarning; } stream_delay_ms_ = delay; return retval; } int AudioProcessingImpl::stream_delay_ms() const { return stream_delay_ms_; } bool AudioProcessingImpl::was_stream_delay_set() const { return was_stream_delay_set_; } void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) { key_pressed_ = key_pressed; } bool AudioProcessingImpl::stream_key_pressed() const { return key_pressed_; } void AudioProcessingImpl::set_delay_offset_ms(int offset) { CriticalSectionScoped crit_scoped(crit_); delay_offset_ms_ = offset; } int AudioProcessingImpl::delay_offset_ms() const { return delay_offset_ms_; } int AudioProcessingImpl::StartDebugRecording( const char filename[AudioProcessing::kMaxFilenameSize]) { CriticalSectionScoped crit_scoped(crit_); static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, ""); if (filename == NULL) { return kNullPointerError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Stop any ongoing recording. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } if (debug_file_->OpenFile(filename, false) == -1) { debug_file_->CloseFile(); return kFileError; } int err = WriteInitMessage(); if (err != kNoError) { return err; } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } int AudioProcessingImpl::StartDebugRecording(FILE* handle) { CriticalSectionScoped crit_scoped(crit_); if (handle == NULL) { return kNullPointerError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Stop any ongoing recording. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } if (debug_file_->OpenFromFileHandle(handle, true, false) == -1) { return kFileError; } int err = WriteInitMessage(); if (err != kNoError) { return err; } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } int AudioProcessingImpl::StartDebugRecordingForPlatformFile( rtc::PlatformFile handle) { FILE* stream = rtc::FdopenPlatformFileForWriting(handle); return StartDebugRecording(stream); } int AudioProcessingImpl::StopDebugRecording() { CriticalSectionScoped crit_scoped(crit_); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // We just return if recording hasn't started. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } EchoCancellation* AudioProcessingImpl::echo_cancellation() const { return echo_cancellation_; } EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const { return echo_control_mobile_; } GainControl* AudioProcessingImpl::gain_control() const { if (use_new_agc_) { return gain_control_for_new_agc_.get(); } return gain_control_; } HighPassFilter* AudioProcessingImpl::high_pass_filter() const { return high_pass_filter_; } LevelEstimator* AudioProcessingImpl::level_estimator() const { return level_estimator_; } NoiseSuppression* AudioProcessingImpl::noise_suppression() const { return noise_suppression_; } VoiceDetection* AudioProcessingImpl::voice_detection() const { return voice_detection_; } bool AudioProcessingImpl::is_data_processed() const { if (beamformer_enabled_) { return true; } int enabled_count = 0; for (auto item : component_list_) { if (item->is_component_enabled()) { enabled_count++; } } // Data is unchanged if no components are enabled, or if only level_estimator_ // or voice_detection_ is enabled. if (enabled_count == 0) { return false; } else if (enabled_count == 1) { if (level_estimator_->is_enabled() || voice_detection_->is_enabled()) { return false; } } else if (enabled_count == 2) { if (level_estimator_->is_enabled() && voice_detection_->is_enabled()) { return false; } } return true; } bool AudioProcessingImpl::output_copy_needed(bool is_data_processed) const { // Check if we've upmixed or downmixed the audio. return ((fwd_out_format_.num_channels() != fwd_in_format_.num_channels()) || is_data_processed || transient_suppressor_enabled_); } bool AudioProcessingImpl::synthesis_needed(bool is_data_processed) const { return (is_data_processed && (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz)); } bool AudioProcessingImpl::analysis_needed(bool is_data_processed) const { if (!is_data_processed && !voice_detection_->is_enabled() && !transient_suppressor_enabled_) { // Only level_estimator_ is enabled. return false; } else if (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz) { // Something besides level_estimator_ is enabled, and we have super-wb. return true; } return false; } void AudioProcessingImpl::InitializeExperimentalAgc() { if (use_new_agc_) { if (!agc_manager_.get()) { agc_manager_.reset(new AgcManagerDirect(gain_control_, gain_control_for_new_agc_.get(), agc_startup_min_volume_)); } agc_manager_->Initialize(); agc_manager_->SetCaptureMuted(output_will_be_muted_); } } void AudioProcessingImpl::InitializeTransient() { if (transient_suppressor_enabled_) { if (!transient_suppressor_.get()) { transient_suppressor_.reset(new TransientSuppressor()); } transient_suppressor_->Initialize(fwd_proc_format_.rate(), split_rate_, fwd_out_format_.num_channels()); } } void AudioProcessingImpl::InitializeBeamformer() { if (beamformer_enabled_) { if (!beamformer_) { beamformer_.reset(new NonlinearBeamformer(array_geometry_)); } beamformer_->Initialize(kChunkSizeMs, split_rate_); } } void AudioProcessingImpl::MaybeUpdateHistograms() { static const int kMinDiffDelayMs = 60; if (echo_cancellation()->is_enabled()) { // Detect a jump in platform reported system delay and log the difference. const int diff_stream_delay_ms = stream_delay_ms_ - last_stream_delay_ms_; if (diff_stream_delay_ms > kMinDiffDelayMs && last_stream_delay_ms_ != 0) { RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump", diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100); } last_stream_delay_ms_ = stream_delay_ms_; // Detect a jump in AEC system delay and log the difference. const int frames_per_ms = rtc::CheckedDivExact(split_rate_, 1000); const int aec_system_delay_ms = WebRtcAec_system_delay(echo_cancellation()->aec_core()) / frames_per_ms; const int diff_aec_system_delay_ms = aec_system_delay_ms - last_aec_system_delay_ms_; if (diff_aec_system_delay_ms > kMinDiffDelayMs && last_aec_system_delay_ms_ != 0) { RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump", diff_aec_system_delay_ms, kMinDiffDelayMs, 1000, 100); } last_aec_system_delay_ms_ = aec_system_delay_ms; // TODO(bjornv): Consider also logging amount of jumps. This gives a better // indication of how frequent jumps are. } } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP int AudioProcessingImpl::WriteMessageToDebugFile() { int32_t size = event_msg_->ByteSize(); if (size <= 0) { return kUnspecifiedError; } #if defined(WEBRTC_ARCH_BIG_ENDIAN) // TODO(ajm): Use little-endian "on the wire". For the moment, we can be // pretty safe in assuming little-endian. #endif if (!event_msg_->SerializeToString(&event_str_)) { return kUnspecifiedError; } // Write message preceded by its size. if (!debug_file_->Write(&size, sizeof(int32_t))) { return kFileError; } if (!debug_file_->Write(event_str_.data(), event_str_.length())) { return kFileError; } event_msg_->Clear(); return kNoError; } int AudioProcessingImpl::WriteInitMessage() { event_msg_->set_type(audioproc::Event::INIT); audioproc::Init* msg = event_msg_->mutable_init(); msg->set_sample_rate(fwd_in_format_.rate()); msg->set_num_input_channels(fwd_in_format_.num_channels()); msg->set_num_output_channels(fwd_out_format_.num_channels()); msg->set_num_reverse_channels(rev_in_format_.num_channels()); msg->set_reverse_sample_rate(rev_in_format_.rate()); msg->set_output_sample_rate(fwd_out_format_.rate()); int err = WriteMessageToDebugFile(); if (err != kNoError) { return err; } return kNoError; } #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } // namespace webrtc
34.373148
84
0.679309
JokeJoe8806
fd6f38712b3dc29d17a87f86edc8d8f16a1b4938
846
cpp
C++
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
3
2021-05-13T14:05:21.000Z
2021-05-13T14:05:39.000Z
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
#include "opt-methods/util/Charting.hpp" using namespace Charting; void Charting::addToChart(QtCharts::QChart *chart, QtCharts::QAbstractSeries *s) { s->setUseOpenGL(); chart->addSeries(s); s->attachAxis(axisX(chart)); s->attachAxis(axisY(chart)); } qreal Charting::getAxisRange(QtCharts::QValueAxis *axis) { return axis->max() - axis->min(); } void Charting::growAxisRange(QtCharts::QValueAxis *axis, double coef) { qreal r = getAxisRange(axis); axis->setRange(axis->min() - r * coef, axis->max() + r * coef); } void Charting::createNaturalSequenceAxes(QtCharts::QChart* chart, [[maybe_unused]] int n) { using namespace QtCharts; chart->createDefaultAxes(); auto* x = axisX<QtCharts::QValueAxis>(chart); auto* y = axisY<QtCharts::QValueAxis>(chart); growAxisRange(x, 0.01); x->setLabelFormat("%i"); growAxisRange(y, 0.01); }
25.636364
94
0.712766
kp2pml30
fd74d7a645e78d29cffcd3b134de025abd4490d2
1,348
cpp
C++
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
/******************************************************************************************* * @file MergeTwoSortedListsSolution.cpp 2015\12\7 18:00:31 $ * @author Wang Xiaotao<[email protected]> (中文编码测试) * @note LeetCode No.21 Merge Two Sorted Lists *******************************************************************************************/ #include "MergeTwoSortedListsSolution.hpp" #include "Struct.hpp" // ------------------------------------------------------------------------------------------ // LeetCode No.21 Merge Two Sorted Lists ListNode* MergeTwoSortedListsSolution::mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* pRealHead = new ListNode(0); ListNode* pCurrent = pRealHead; while (l1 && l2) { if ((l1->val) > (l2->val)) { pCurrent->next = l2; pCurrent = pCurrent->next; l2 = l2->next; } else { pCurrent->next = l1; pCurrent = pCurrent->next; l1 = l1->next; } } if (l1) { pCurrent->next = l1; } if (l2) { pCurrent->next = l2; } ListNode* pResult = pRealHead->next; delete pRealHead; return pResult; } // // ------------------------------------------------------------------------------------------
28.680851
94
0.396884
wangxiaotao1980
fd76422330862fd1ee98feb18e6f9351912ecdac
2,194
cc
C++
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
1
2019-01-13T21:39:32.000Z
2019-01-13T21:39:32.000Z
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
null
null
null
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
1
2019-01-02T22:04:21.000Z
2019-01-02T22:04:21.000Z
/* * * Copyright 2018 Asylo authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "asylo/platform/common/debug_strings.h" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace asylo { namespace { using ::testing::Eq; using ::testing::StrEq; TEST(DebugStringsTest, Null) { EXPECT_THAT(buffer_to_hex_string(nullptr, 0), StrEq("null")); } TEST(DebugStringsTest, ZeroLength) { char buffer[] = "abc"; EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 0), StrEq("[]")); } TEST(DebugStringsTest, NegativeLength) { char buffer[] = "abc"; EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), -4), StrEq("[ERROR: negative length -4]")); } TEST(DebugStringsTest, SingletonNullBuffer) { uint8_t buffer[] = {0}; ASSERT_THAT(sizeof(buffer), Eq(1)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 1), StrEq("[0x00]")); } TEST(DebugStringsTest, NonemptyBufferDecimalDigits) { char buffer[] = "ABC"; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x41424300]")); } TEST(DebugStringsTest, NonemptyBufferHighDigits) { char buffer[] = "[-]"; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x5B2D5D00]")); } TEST(DebugStringsTest, NonemptyNullBuffer) { uint8_t buffer[] = {0, 0, 0, 0}; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x00000000]")); } } // namespace } // namespace asylo
29.253333
75
0.690064
kevin405
fd77e307f7ff4ebbe739acd4ba3d54542df12a31
3,411
cpp
C++
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
null
null
null
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
6
2021-07-13T22:25:55.000Z
2022-01-16T15:16:09.000Z
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
null
null
null
#include "LFO.hpp" #include "lookup_tables.hpp" #include "PRNG.hpp" #include "wave_scanner.hpp" LFO::LFO(uint32_t sample_rate) : sample_rate(sample_rate) {} void LFO::tick(void) { phase_accumulator += tuning_word; updateWaveshapes(); } void LFO::setInput(Input_t input_type, int value) { input[input_type] = value; if (input_type == FREQ_mHz) { updateTuningWord(); } } int LFO::getOutput(Shape_t output_type) { return output[output_type]; } void LFO::updateTuningWord(void) { /* * In DDS, the tuning word M = (2^N * f_out)/(f_c), where N is the number of * bits in the accumulator, f_out is the desired output frequency, and f_c * is the sample rate. * * Since the LFO frequency is measured in milli Hertz, this becomes * M = (2^N * f_out_mHz)/(f_c * 1000) * * Note that the MAX_ACCUMULATOR value is actually equal to 2^N - 1, but this * off-by-one does not meaningfully impact the calculation. */ const uint32_t two_to_the_N = ACCUMULATOR_FULL_SCALE; const uint32_t f_c = sample_rate; const uint32_t f_out_mHz = input[FREQ_mHz]; const uint32_t mSec_per_sec = 1000u; const uint32_t M = (two_to_the_N / (f_c * mSec_per_sec)) * f_out_mHz; tuning_word = M; } void LFO::updateWaveshapes(void) { updateTriangle(); updateSine(); updateSquare(); updateRandom(); updateCrossfade(); } void LFO::updateSine(void) { const uint32_t lut_idx = phase_accumulator >> NUM_FRACTIONAL_BITS_IN_ACCUMULATOR; const uint32_t next_idx = (lut_idx + 1u) % SINE_LOOKUP_TABLE_SIZE; const uint32_t fraction = phase_accumulator & ACCUMULATOR_FRACTION_MASK; output[SINE] = linearInterpolation(Lookup_Tables::SINE_LUT[lut_idx], Lookup_Tables::SINE_LUT[next_idx], fraction); } void LFO::updateTriangle(void) { // keep the tri in phase with the sine const uint32_t phase_shifted_accum = phase_accumulator + ACCUMULATOR_QUARTER_SCALE; // derive the triangle directly from the phase accumulator if (phase_shifted_accum <= ACCUMULATOR_HALF_SCALE) { output[TRIANGLE] = (phase_shifted_accum >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL; } else { output[TRIANGLE] = ((ACCUMULATOR_FULL_SCALE - phase_shifted_accum) >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL; } } void LFO::updateSquare(void) { output[SQUARE] = phase_accumulator < ACCUMULATOR_HALF_SCALE ? OUTPUT_MAX_VAL : OUTPUT_MIN_VAL; } void LFO::updateRandom(void) { // the LFO "feels" better if the random signal updates at twice the base frequency const uint32_t double_time_accum = phase_accumulator << 1u; static uint32_t last_double_time_accum; const bool accum_rolled_over = double_time_accum < last_double_time_accum; if (accum_rolled_over) { // get a random sample in the bounds of the LFO range, centered around zero const int random_sample = (PRNG::nextRand() & ((1 << OUTPUT_NUM_BITS) - 1)) - OUTPUT_MAX_VAL; output[RANDOM] = random_sample; } last_double_time_accum = double_time_accum; } void LFO::updateCrossfade(void) { output[CROSSFADED] = Wave_Scanner::crossfade(output, NUM_LFO_SHAPES - 1, input[WAVE_SCAN]); } int LFO::linearInterpolation(int y1, int y2, uint32_t fraction) { return y1 + (fraction * (y2 - y1)) / ACCUMULATOR_FRACTION_MASK; }
28.90678
143
0.703313
JordanAceto
fd788cf6029b78c1e8987ddba8568ed05cc64ddd
353
cpp
C++
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
#include "../../headers/renderpasses/Renderpass.hpp" #include "../../headers/RTFilterDemo.hpp" namespace rtf { void Renderpass::setRtFilterDemo(RTFilterDemo* rtFilterDemo) { m_rtFilterDemo = rtFilterDemo; m_vulkanDevice = rtFilterDemo->vulkanDevice; m_attachmentManager = rtFilterDemo->m_attachmentManager; m_rtFilterDemo = rtFilterDemo; } }
27.153846
61
0.773371
Realtime-RT-Filters
fd823c10c00187180754b42fdfd38d4b830d51b6
46
cpp
C++
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
#include "i4pch.h" #include "WinShipLinker.h"
15.333333
26
0.73913
Morderaccman
fd89614e4a1f4d53cdb77144c91da2d3c147a1ec
750
cpp
C++
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
5
2019-11-21T23:14:00.000Z
2021-02-03T15:39:30.000Z
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
null
null
null
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
4
2020-02-23T22:38:04.000Z
2021-02-05T16:59:31.000Z
#include "../Shared.h" namespace UnitTests { namespace Arrays { TEST(ArrayCat, One) { const std::string innerCode = "@ = (((3 * 1).arrayCreate * 1 * 2).arraySet * 2 * 3).arraySet.(id * arrayCat).(print * ([-1] * 0 * 0).arraySet.print * print);"; const std::string expected = "[1, 2, 3]"; GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode)); } TEST(ArrayCat, Three) { const std::string innerCode = R"( @ = ( (1 * 1).arrayCreate * ((2 * 2).arrayCreate * 1 * 3).arraySet * (((3 * 4).arrayCreate * 1 * 5).arraySet * 2 * 6).arraySet ).arrayCat.print;)"; const std::string expected = "[1, 2, 3, 4, 5, 6]"; GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode)); } } }
25.862069
162
0.6
Psy-Rat
fd89f6d824ab982c0dfb7108248aec3f088e6f18
870
cpp
C++
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "CeilingRenderer.h" #include "Tracer.h" //---- CeilingRenderer --------------------------------------------------------------- RegisterRenderer(CeilingRenderer); CeilingRenderer::CeilingRenderer(const char *name) : ComparingRenderer(name) { } CeilingRenderer::~CeilingRenderer() { } long CeilingRenderer::FindSlot(String &key, const ROAnything &list) { StartTrace(CeilingRenderer.FindSlot); long i = 0; long sz = list.GetSize(); while ((i < sz) && (key.Compare(list.SlotName(i)) > 0) ) { ++i; } return i < sz ? i : -1; }
28.064516
102
0.666667
zer0infinity
fd8f62263a6b544ba6ec739cdb6ee84623310cbc
35,174
cpp
C++
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
1
2019-06-05T19:23:47.000Z
2019-06-05T19:23:47.000Z
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <cstdio> #include "AMReX_LevelBld.H" #include <AMReX_ParmParse.H> #include "Castro.H" #include "Castro_F.H" #ifdef AMREX_DIMENSION_AGNOSTIC #include "Castro_bc_fill_nd_F.H" #include "Castro_bc_fill_nd.H" #else #include "Castro_bc_fill_F.H" #include "Castro_bc_fill.H" #endif #include "Castro_generic_fill_F.H" #include "Castro_generic_fill.H" #include <Derive_F.H> #include "Derive.H" #ifdef RADIATION # include "Radiation.H" # include "RAD_F.H" #endif #include "AMReX_buildInfo.H" using std::string; using namespace amrex; static Box the_same_box (const Box& b) { return b; } static Box grow_box_by_one (const Box& b) { return amrex::grow(b,1); } typedef StateDescriptor::BndryFunc BndryFunc; // // Components are: // Interior, Inflow, Outflow, Symmetry, SlipWall, NoSlipWall // static int scalar_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN }; static int norm_vel_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_ODD, REFLECT_ODD, REFLECT_ODD }; static int tang_vel_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN }; static void set_scalar_bc (BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); for (int i = 0; i < BL_SPACEDIM; i++) { bc.setLo(i,scalar_bc[lo_bc[i]]); bc.setHi(i,scalar_bc[hi_bc[i]]); } } static void set_x_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,norm_vel_bc[lo_bc[0]]); bc.setHi(0,norm_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,tang_vel_bc[lo_bc[1]]); bc.setHi(1,tang_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,tang_vel_bc[lo_bc[2]]); bc.setHi(2,tang_vel_bc[hi_bc[2]]); #endif } static void set_y_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,tang_vel_bc[lo_bc[0]]); bc.setHi(0,tang_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,norm_vel_bc[lo_bc[1]]); bc.setHi(1,norm_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,tang_vel_bc[lo_bc[2]]); bc.setHi(2,tang_vel_bc[hi_bc[2]]); #endif } static void set_z_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,tang_vel_bc[lo_bc[0]]); bc.setHi(0,tang_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,tang_vel_bc[lo_bc[1]]); bc.setHi(1,tang_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,norm_vel_bc[lo_bc[2]]); bc.setHi(2,norm_vel_bc[hi_bc[2]]); #endif } void Castro::variableSetUp () { // Castro::variableSetUp is called in the constructor of Amr.cpp, so // it should get called every time we start or restart a job // initialize the start time for our CPU-time tracker startCPUTime = ParallelDescriptor::second(); // Output the git commit hashes used to build the executable. if (ParallelDescriptor::IOProcessor()) { const char* castro_hash = buildInfoGetGitHash(1); const char* amrex_hash = buildInfoGetGitHash(2); const char* microphysics_hash = buildInfoGetGitHash(3); const char* buildgithash = buildInfoGetBuildGitHash(); const char* buildgitname = buildInfoGetBuildGitName(); if (strlen(castro_hash) > 0) { std::cout << "\n" << "Castro git describe: " << castro_hash << "\n"; } if (strlen(amrex_hash) > 0) { std::cout << "AMReX git describe: " << amrex_hash << "\n"; } if (strlen(microphysics_hash) > 0) { std::cout << "Microphysics git describe: " << microphysics_hash << "\n"; } if (strlen(buildgithash) > 0){ std::cout << buildgitname << " git describe: " << buildgithash << "\n"; } std::cout << "\n"; } BL_ASSERT(desc_lst.size() == 0); // Get options, set phys_bc read_params(); // Initialize the runtime parameters for any of the external // microphysics extern_init(); // Initialize the network network_init(); #ifdef REACTIONS // Initialize the burner burner_init(); #endif #ifdef SPONGE // Initialize the sponge sponge_init(); #endif // Initialize the amr info amrinfo_init(); const int dm = BL_SPACEDIM; // // Set number of state variables and pointers to components // // Get the number of species from the network model. ca_get_num_spec(&NumSpec); // Get the number of auxiliary quantities from the network model. ca_get_num_aux(&NumAux); // Get the number of advected quantities -- set at compile time ca_get_num_adv(&NumAdv); #include "set_conserved.H" NUM_STATE = cnt; #include "set_primitive.H" #include "set_godunov.H" // Define NUM_GROW from the f90 module. ca_get_method_params(&NUM_GROW); const Real run_strt = ParallelDescriptor::second() ; // Read in the input values to Fortran. ca_set_castro_method_params(); // set the conserved, primitive, aux, and godunov indices in Fortran ca_set_method_params(dm, Density, Xmom, #ifdef HYBRID_MOMENTUM Rmom, #endif Eden, Eint, Temp, FirstAdv, FirstSpec, FirstAux, #ifdef SHOCK_VAR Shock, #endif #ifdef MHD QMAGX, QMAGY, QMAGZ, #endif #ifdef RADIATION QPTOT, QREITOT, QRAD, #endif QRHO, QU, QV, QW, QGAME, QGC, QPRES, QREINT, QTEMP, QFA, QFS, QFX, #ifdef RADIATION GDLAMS, GDERADS, #endif GDRHO, GDU, GDV, GDW, GDPRES, GDGAME); // Get the number of primitive variables from Fortran. ca_get_nqsrc(&NQSRC); // and the auxiliary variables ca_get_nqaux(&NQAUX); // and the number of primitive variable source terms ca_get_nqsrc(&NQSRC); // initialize the Godunov state array used in hydro ca_get_ngdnv(&NGDNV); // NQ will be used to dimension the primitive variable state // vector it will include the "pure" hydrodynamical variables + // any radiation variables ca_get_nq(&NQ); Real run_stop = ParallelDescriptor::second() - run_strt; ParallelDescriptor::ReduceRealMax(run_stop,ParallelDescriptor::IOProcessorNumber()); if (ParallelDescriptor::IOProcessor()) std::cout << "\nTime in ca_set_method_params: " << run_stop << '\n' ; const Geometry& dgeom = DefaultGeometry(); const int coord_type = dgeom.Coord(); // Get the center variable from the inputs and pass it directly to Fortran. Vector<Real> center(BL_SPACEDIM, 0.0); ParmParse ppc("castro"); ppc.queryarr("center",center,0,BL_SPACEDIM); ca_set_problem_params(dm,phys_bc.lo(),phys_bc.hi(), Interior,Inflow,Outflow,Symmetry,SlipWall,NoSlipWall,coord_type, dgeom.ProbLo(),dgeom.ProbHi(),center.dataPtr()); // Read in the parameters for the tagging criteria // and store them in the Fortran module. const int probin_file_length = probin_file.length(); Vector<int> probin_file_name(probin_file_length); for (int i = 0; i < probin_file_length; i++) probin_file_name[i] = probin_file[i]; ca_get_tagging_params(probin_file_name.dataPtr(),&probin_file_length); #ifdef SPONGE // Read in the parameters for the sponge // and store them in the Fortran module. ca_get_sponge_params(probin_file_name.dataPtr(),&probin_file_length); #endif Interpolater* interp; if (state_interp_order == 0) { interp = &pc_interp; } else { if (lin_limit_state_interp == 1) interp = &lincc_interp; else interp = &cell_cons_interp; } #ifdef RADIATION // cell_cons_interp is not conservative in spherical coordinates. // We could do this for other cases too, but I'll confine it to // neutrino problems for now so as not to change the results of // other people's tests. Better to fix cell_cons_interp! if (dgeom.IsSPHERICAL() && Radiation::nNeutrinoSpecies > 0) { interp = &pc_interp; } #endif // Note that the default is state_data_extrap = false, // store_in_checkpoint = true. We only need to put these in // explicitly if we want to do something different, // like not store the state data in a checkpoint directory bool state_data_extrap = false; bool store_in_checkpoint; #ifdef RADIATION // Radiation should always have at least one ghost zone. int ngrow_state = std::max(1, state_nghost); #else int ngrow_state = state_nghost; #endif BL_ASSERT(ngrow_state >= 0); store_in_checkpoint = true; desc_lst.addDescriptor(State_Type,IndexType::TheCellType(), StateDescriptor::Point,ngrow_state,NUM_STATE, interp,state_data_extrap,store_in_checkpoint); #ifdef SELF_GRAVITY store_in_checkpoint = true; desc_lst.addDescriptor(PhiGrav_Type, IndexType::TheCellType(), StateDescriptor::Point, 1, 1, &cell_cons_interp, state_data_extrap, store_in_checkpoint); store_in_checkpoint = false; desc_lst.addDescriptor(Gravity_Type,IndexType::TheCellType(), StateDescriptor::Point,NUM_GROW,3, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif // Source terms -- for the CTU method, because we do characteristic // tracing on the source terms, we need NUM_GROW ghost cells to do // the reconstruction. For MOL and SDC, on the other hand, we only // need 1 (for the fourth-order stuff). Simplified SDC uses the CTU // advance, so it behaves the same way as CTU here. store_in_checkpoint = true; int source_ng; if (time_integration_method == CornerTransportUpwind || time_integration_method == SimplifiedSpectralDeferredCorrections) { source_ng = NUM_GROW; } else if (time_integration_method == MethodOfLines || time_integration_method == SpectralDeferredCorrections) { source_ng = 1; } else { amrex::Error("Unknown time_integration_method"); } desc_lst.addDescriptor(Source_Type, IndexType::TheCellType(), StateDescriptor::Point, source_ng, NUM_STATE, &cell_cons_interp, state_data_extrap, store_in_checkpoint); #ifdef ROTATION store_in_checkpoint = false; desc_lst.addDescriptor(PhiRot_Type, IndexType::TheCellType(), StateDescriptor::Point, 1, 1, &cell_cons_interp, state_data_extrap, store_in_checkpoint); store_in_checkpoint = false; desc_lst.addDescriptor(Rotation_Type,IndexType::TheCellType(), StateDescriptor::Point,NUM_GROW,3, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif #ifdef REACTIONS // Components 0:Numspec-1 are omegadot_i // Component NumSpec is enuc = (eout-ein) // Component NumSpec+1 is rho_enuc= rho * (eout-ein) store_in_checkpoint = true; desc_lst.addDescriptor(Reactions_Type,IndexType::TheCellType(), StateDescriptor::Point,0,NumSpec+2, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif #ifdef REACTIONS // For simplified SDC, we want to store the reactions source. if (time_integration_method == SimplifiedSpectralDeferredCorrections) { store_in_checkpoint = true; desc_lst.addDescriptor(Simplified_SDC_React_Type, IndexType::TheCellType(), StateDescriptor::Point, NUM_GROW, NQSRC, &cell_cons_interp, state_data_extrap, store_in_checkpoint); } #endif Vector<BCRec> bcs(NUM_STATE); Vector<std::string> name(NUM_STATE); BCRec bc; set_scalar_bc(bc, phys_bc); bcs[Density] = bc; name[Density] = "density"; set_x_vel_bc(bc, phys_bc); bcs[Xmom] = bc; name[Xmom] = "xmom"; set_y_vel_bc(bc, phys_bc); bcs[Ymom] = bc; name[Ymom] = "ymom"; set_z_vel_bc(bc, phys_bc); bcs[Zmom] = bc; name[Zmom] = "zmom"; #ifdef HYBRID_MOMENTUM set_scalar_bc(bc, phys_bc); bcs[Rmom] = bc; name[Rmom] = "rmom"; set_scalar_bc(bc, phys_bc); bcs[Lmom] = bc; name[Lmom] = "lmom"; set_scalar_bc(bc, phys_bc); bcs[Pmom] = bc; name[Pmom] = "pmom"; #endif set_scalar_bc(bc, phys_bc); bcs[Eden] = bc; name[Eden] = "rho_E"; set_scalar_bc(bc, phys_bc); bcs[Eint] = bc; name[Eint] = "rho_e"; set_scalar_bc(bc, phys_bc); bcs[Temp] = bc; name[Temp] = "Temp"; for (int i=0; i<NumAdv; ++i) { char buf[64]; sprintf(buf, "adv_%d", i); set_scalar_bc(bc, phys_bc); bcs[FirstAdv+i] = bc; name[FirstAdv+i] = string(buf); } // Get the species names from the network model. std::vector<std::string> spec_names; for (int i = 0; i < NumSpec; i++) { int len = 20; Vector<int> int_spec_names(len); // This call return the actual length of each string in "len" ca_get_spec_names(int_spec_names.dataPtr(),&i,&len); char char_spec_names[len+1]; for (int j = 0; j < len; j++) char_spec_names[j] = int_spec_names[j]; char_spec_names[len] = '\0'; spec_names.push_back(std::string(char_spec_names)); } if ( ParallelDescriptor::IOProcessor()) { std::cout << NumSpec << " Species: " << std::endl; for (int i = 0; i < NumSpec; i++) std::cout << spec_names[i] << ' ' << ' '; std::cout << std::endl; } for (int i=0; i<NumSpec; ++i) { set_scalar_bc(bc, phys_bc); bcs[FirstSpec+i] = bc; name[FirstSpec+i] = "rho_" + spec_names[i]; } // Get the auxiliary names from the network model. std::vector<std::string> aux_names; for (int i = 0; i < NumAux; i++) { int len = 20; Vector<int> int_aux_names(len); // This call return the actual length of each string in "len" ca_get_aux_names(int_aux_names.dataPtr(),&i,&len); char char_aux_names[len+1]; for (int j = 0; j < len; j++) char_aux_names[j] = int_aux_names[j]; char_aux_names[len] = '\0'; aux_names.push_back(std::string(char_aux_names)); } if ( ParallelDescriptor::IOProcessor()) { std::cout << NumAux << " Auxiliary Variables: " << std::endl; for (int i = 0; i < NumAux; i++) std::cout << aux_names[i] << ' ' << ' '; std::cout << std::endl; } for (int i=0; i<NumAux; ++i) { set_scalar_bc(bc, phys_bc); bcs[FirstAux+i] = bc; name[FirstAux+i] = "rho_" + aux_names[i]; } #ifdef SHOCK_VAR set_scalar_bc(bc, phys_bc); bcs[Shock] = bc; name[Shock] = "Shock"; #endif desc_lst.setComponent(State_Type, Density, name, bcs, BndryFunc(ca_denfill,ca_hypfill)); #ifdef SELF_GRAVITY set_scalar_bc(bc,phys_bc); desc_lst.setComponent(PhiGrav_Type,0,"phiGrav",bc,BndryFunc(ca_phigravfill)); set_x_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,0,"grav_x",bc,BndryFunc(ca_gravxfill)); set_y_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,1,"grav_y",bc,BndryFunc(ca_gravyfill)); set_z_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,2,"grav_z",bc,BndryFunc(ca_gravzfill)); #endif #ifdef ROTATION set_scalar_bc(bc,phys_bc); desc_lst.setComponent(PhiRot_Type,0,"phiRot",bc,BndryFunc(ca_phirotfill)); set_x_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,0,"rot_x",bc,BndryFunc(ca_rotxfill)); set_y_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,1,"rot_y",bc,BndryFunc(ca_rotyfill)); set_z_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,2,"rot_z",bc,BndryFunc(ca_rotzfill)); #endif // Source term array will use standard hyperbolic fill. Vector<BCRec> source_bcs(NUM_STATE); Vector<std::string> state_type_source_names(NUM_STATE); for (int i = 0; i < NUM_STATE; ++i) { state_type_source_names[i] = name[i] + "_source"; source_bcs[i] = bcs[i]; // Replace inflow BCs with FOEXTRAP. for (int j = 0; j < AMREX_SPACEDIM; ++j) { if (source_bcs[i].lo(j) == EXT_DIR) source_bcs[i].setLo(j, FOEXTRAP); if (source_bcs[i].hi(j) == EXT_DIR) source_bcs[i].setHi(j, FOEXTRAP); } } desc_lst.setComponent(Source_Type,Density,state_type_source_names,source_bcs, BndryFunc(ca_generic_single_fill,ca_generic_multi_fill)); #ifdef REACTIONS std::string name_react; for (int i=0; i<NumSpec; ++i) { set_scalar_bc(bc,phys_bc); name_react = "omegadot_" + spec_names[i]; desc_lst.setComponent(Reactions_Type, i, name_react, bc,BndryFunc(ca_reactfill)); } desc_lst.setComponent(Reactions_Type, NumSpec , "enuc", bc, BndryFunc(ca_reactfill)); desc_lst.setComponent(Reactions_Type, NumSpec+1, "rho_enuc", bc, BndryFunc(ca_reactfill)); #endif #ifdef REACTIONS if (time_integration_method == SimplifiedSpectralDeferredCorrections) { for (int i = 0; i < NQSRC; ++i) { char buf[64]; sprintf(buf, "sdc_react_source_%d", i); set_scalar_bc(bc,phys_bc); // Replace inflow BCs with FOEXTRAP. for (int j = 0; j < AMREX_SPACEDIM; ++j) { if (bc.lo(j) == EXT_DIR) bc.setLo(j, FOEXTRAP); if (bc.hi(j) == EXT_DIR) bc.setHi(j, FOEXTRAP); } desc_lst.setComponent(Simplified_SDC_React_Type,i,std::string(buf),bc,BndryFunc(ca_generic_single_fill)); } } #endif #ifdef RADIATION int ngrow = 1; int ncomp = Radiation::nGroups; desc_lst.addDescriptor(Rad_Type, IndexType::TheCellType(), StateDescriptor::Point, ngrow, ncomp, interp); set_scalar_bc(bc,phys_bc); if (ParallelDescriptor::IOProcessor()) { std::cout << "Radiation::nGroups = " << Radiation::nGroups << std::endl; std::cout << "Radiation::nNeutrinoSpecies = " << Radiation::nNeutrinoSpecies << std::endl; if (Radiation::nNeutrinoSpecies > 0) { std::cout << "Radiation::nNeutrinoGroups = "; for (int n = 0; n < Radiation::nNeutrinoSpecies; n++) { std::cout << " " << Radiation::nNeutrinoGroups[n]; } std::cout << std::endl; if (Radiation::nNeutrinoGroups[0] > 0 && NumAdv != 0) { amrex::Error("Neutrino solver assumes NumAdv == 0"); } if (Radiation::nNeutrinoGroups[0] > 0 && (NumSpec != 1 || NumAux != 1)) { amrex::Error("Neutrino solver assumes NumSpec == NumAux == 1"); } } } char rad_name[10]; if (!Radiation::do_multigroup) { desc_lst .setComponent(Rad_Type, Rad, "rad", bc, BndryFunc(ca_radfill)); } else { if (Radiation::nNeutrinoSpecies == 0 || Radiation::nNeutrinoGroups[0] == 0) { for (int i = 0; i < Radiation::nGroups; i++) { sprintf(rad_name, "rad%d", i); desc_lst .setComponent(Rad_Type, i, rad_name, bc, BndryFunc(ca_radfill)); } } else { int indx = 0; for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) { for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) { sprintf(rad_name, "rads%dg%d", j, i); desc_lst.setComponent(Rad_Type, indx, rad_name, bc, BndryFunc(ca_radfill)); indx++; } } } } #endif // some optional State_Type's -- since these depend on the value of // runtime parameters, we don't add these to the enum, but instead // add them to the count of State_Type's if we will use them if (use_custom_knapsack_weights) { Knapsack_Weight_Type = desc_lst.size(); desc_lst.addDescriptor(Knapsack_Weight_Type, IndexType::TheCellType(), StateDescriptor::Point, 0, 1, &pc_interp); // Because we use piecewise constant interpolation, we do not use bc and BndryFunc. desc_lst.setComponent(Knapsack_Weight_Type, 0, "KnapsackWeight", bc, BndryFunc(ca_nullfill)); } #ifdef REACTIONS if (time_integration_method == SpectralDeferredCorrections && (mol_order == 4 || sdc_order == 4)) { // we are doing 4th order reactive SDC. We need 2 ghost cells here SDC_Source_Type = desc_lst.size(); store_in_checkpoint = false; desc_lst.addDescriptor(SDC_Source_Type, IndexType::TheCellType(), StateDescriptor::Point, 2, NUM_STATE, interp, state_data_extrap, store_in_checkpoint); // this is the same thing we do for the sources desc_lst.setComponent(SDC_Source_Type, Density, state_type_source_names, source_bcs, BndryFunc(ca_generic_single_fill, ca_generic_multi_fill)); } #endif num_state_type = desc_lst.size(); // // DEFINE DERIVED QUANTITIES // // Pressure // derive_lst.add("pressure",IndexType::TheCellType(),1,ca_derpres,the_same_box); derive_lst.addComponent("pressure",desc_lst,State_Type,Density,NUM_STATE); // // Kinetic energy // derive_lst.add("kineng",IndexType::TheCellType(),1,ca_derkineng,the_same_box); derive_lst.addComponent("kineng",desc_lst,State_Type,Density,1); derive_lst.addComponent("kineng",desc_lst,State_Type,Xmom,3); // // Sound speed (c) // derive_lst.add("soundspeed",IndexType::TheCellType(),1,ca_dersoundspeed,the_same_box); derive_lst.addComponent("soundspeed",desc_lst,State_Type,Density,NUM_STATE); // // Gamma_1 // derive_lst.add("Gamma_1",IndexType::TheCellType(),1,ca_dergamma1,the_same_box); derive_lst.addComponent("Gamma_1",desc_lst,State_Type,Density,NUM_STATE); // // Mach number(M) // derive_lst.add("MachNumber",IndexType::TheCellType(),1,ca_dermachnumber,the_same_box); derive_lst.addComponent("MachNumber",desc_lst,State_Type,Density,NUM_STATE); #if (BL_SPACEDIM == 1) // // Wave speed u+c // derive_lst.add("uplusc",IndexType::TheCellType(),1,ca_deruplusc,the_same_box); derive_lst.addComponent("uplusc",desc_lst,State_Type,Density,NUM_STATE); // // Wave speed u-c // derive_lst.add("uminusc",IndexType::TheCellType(),1,ca_deruminusc,the_same_box); derive_lst.addComponent("uminusc",desc_lst,State_Type,Density,NUM_STATE); #endif // // Gravitational forcing // #ifdef SELF_GRAVITY // derive_lst.add("rhog",IndexType::TheCellType(),1, // BL_FORT_PROC_CALL(CA_RHOG,ca_rhog),the_same_box); // derive_lst.addComponent("rhog",desc_lst,State_Type,Density,1); // derive_lst.addComponent("rhog",desc_lst,Gravity_Type,0,BL_SPACEDIM); #endif // // Entropy (S) // derive_lst.add("entropy",IndexType::TheCellType(),1,ca_derentropy,the_same_box); derive_lst.addComponent("entropy",desc_lst,State_Type,Density,NUM_STATE); #ifdef DIFFUSION if (diffuse_temp) { // // thermal conductivity (k_th) // derive_lst.add("thermal_cond",IndexType::TheCellType(),1,ca_dercond,the_same_box); derive_lst.addComponent("thermal_cond",desc_lst,State_Type,Density,NUM_STATE); // // thermal diffusivity (k_th/(rho c_v)) // derive_lst.add("diff_coeff",IndexType::TheCellType(),1,ca_derdiffcoeff,the_same_box); derive_lst.addComponent("diff_coeff",desc_lst,State_Type,Density,NUM_STATE); // // diffusion term (the divergence of thermal flux) // derive_lst.add("diff_term",IndexType::TheCellType(),1,ca_derdiffterm,grow_box_by_one); derive_lst.addComponent("diff_term",desc_lst,State_Type,Density,NUM_STATE); } #endif // // Vorticity // derive_lst.add("magvort",IndexType::TheCellType(),1,ca_dermagvort,grow_box_by_one); // Here we exploit the fact that Xmom = Density + 1 // in order to use the correct interpolation. if (Xmom != Density+1) amrex::Error("We are assuming Xmom = Density + 1 in Castro_setup.cpp"); derive_lst.addComponent("magvort",desc_lst,State_Type,Density,4); // // Div(u) // derive_lst.add("divu",IndexType::TheCellType(),1,ca_derdivu,grow_box_by_one); derive_lst.addComponent("divu",desc_lst,State_Type,Density,1); derive_lst.addComponent("divu",desc_lst,State_Type,Xmom,3); // // Internal energy as derived from rho*E, part of the state // derive_lst.add("eint_E",IndexType::TheCellType(),1,ca_dereint1,the_same_box); derive_lst.addComponent("eint_E",desc_lst,State_Type,Density,NUM_STATE); // // Internal energy as derived from rho*e, part of the state // derive_lst.add("eint_e",IndexType::TheCellType(),1,ca_dereint2,the_same_box); derive_lst.addComponent("eint_e",desc_lst,State_Type,Density,NUM_STATE); // // Log(density) // derive_lst.add("logden",IndexType::TheCellType(),1,ca_derlogden,the_same_box); derive_lst.addComponent("logden",desc_lst,State_Type,Density,NUM_STATE); derive_lst.add("StateErr",IndexType::TheCellType(),3,ca_derstate,grow_box_by_one); derive_lst.addComponent("StateErr",desc_lst,State_Type,Density,1); derive_lst.addComponent("StateErr",desc_lst,State_Type,Temp,1); derive_lst.addComponent("StateErr",desc_lst,State_Type,FirstSpec,1); // // X from rhoX // for (int i = 0; i < NumSpec; i++){ std::string spec_string = "X("+spec_names[i]+")"; derive_lst.add(spec_string,IndexType::TheCellType(),1,ca_derspec,the_same_box); derive_lst.addComponent(spec_string,desc_lst,State_Type,Density,1); derive_lst.addComponent(spec_string,desc_lst,State_Type,FirstSpec+i,1); } // // Abar // derive_lst.add("abar",IndexType::TheCellType(),1,ca_derabar,the_same_box); derive_lst.addComponent("abar",desc_lst,State_Type,Density,1); derive_lst.addComponent("abar",desc_lst,State_Type,FirstSpec,NumSpec); // // Velocities // derive_lst.add("x_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("x_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("x_velocity",desc_lst,State_Type,Xmom,1); derive_lst.add("y_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("y_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("y_velocity",desc_lst,State_Type,Ymom,1); derive_lst.add("z_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("z_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("z_velocity",desc_lst,State_Type,Zmom,1); #ifdef REACTIONS // // Nuclear energy generation timescale t_e == e / edot // Sound-crossing time t_s == dx / c_s // Ratio of these is t_s_t_e == t_s / t_e // derive_lst.add("t_sound_t_enuc",IndexType::TheCellType(),1,ca_derenuctimescale,the_same_box); derive_lst.addComponent("t_sound_t_enuc",desc_lst,State_Type,Density,NUM_STATE); derive_lst.addComponent("t_sound_t_enuc",desc_lst,Reactions_Type,NumSpec,1); #endif derive_lst.add("magvel",IndexType::TheCellType(),1,ca_dermagvel,the_same_box); derive_lst.addComponent("magvel",desc_lst,State_Type,Density,1); derive_lst.addComponent("magvel",desc_lst,State_Type,Xmom,3); derive_lst.add("radvel",IndexType::TheCellType(),1,ca_derradialvel,the_same_box); derive_lst.addComponent("radvel",desc_lst,State_Type,Density,1); derive_lst.addComponent("radvel",desc_lst,State_Type,Xmom,3); derive_lst.add("magmom",IndexType::TheCellType(),1,ca_dermagmom,the_same_box); derive_lst.addComponent("magmom",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_x",IndexType::TheCellType(),1,ca_derangmomx,the_same_box); derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_y",IndexType::TheCellType(),1,ca_derangmomy,the_same_box); derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_z",IndexType::TheCellType(),1,ca_derangmomz,the_same_box); derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Xmom,3); #ifdef SELF_GRAVITY derive_lst.add("maggrav",IndexType::TheCellType(),1,ca_dermaggrav,the_same_box); derive_lst.addComponent("maggrav",desc_lst,Gravity_Type,0,3); #endif #ifdef AMREX_PARTICLES // // We want a derived type that corresponds to the number of particles // in each cell. We only intend to use it in plotfiles for debugging // purposes. We'll just use the DERNULL since don't do anything in // fortran for now. We'll actually set the values in writePlotFile(). // derive_lst.add("particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box); derive_lst.addComponent("particle_count",desc_lst,State_Type,Density,1); derive_lst.add("total_particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box); derive_lst.addComponent("total_particle_count",desc_lst,State_Type,Density,1); #endif #ifdef RADIATION if (Radiation::do_multigroup) { derive_lst.add("Ertot", IndexType::TheCellType(),1,ca_derertot,the_same_box); derive_lst.addComponent("Ertot",desc_lst,Rad_Type,0,Radiation::nGroups); } #endif #ifdef NEUTRINO if (Radiation::nNeutrinoSpecies > 0 && Radiation::plot_neutrino_group_energies_per_MeV) { char rad_name[10]; int indx = 0; for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) { for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) { sprintf(rad_name, "Neuts%dg%d", j, i); derive_lst.add(rad_name,IndexType::TheCellType(),1,ca_derneut,the_same_box); derive_lst.addComponent(rad_name,desc_lst,Rad_Type,indx,1); indx++; } } } if (Radiation::nNeutrinoSpecies > 0 && Radiation::nNeutrinoGroups[0] > 0) { derive_lst.add("Enue", IndexType::TheCellType(),1,ca_derenue,the_same_box); derive_lst.addComponent("Enue",desc_lst,Rad_Type,0,Radiation::nGroups); derive_lst.add("Enuae", IndexType::TheCellType(),1,ca_derenuae,the_same_box); derive_lst.addComponent("Enuae",desc_lst,Rad_Type,0,Radiation::nGroups); // // rho_Yl = rho(Ye + Ynue - Ynuebar) // derive_lst.add("rho_Yl",IndexType::TheCellType(),1,ca_derrhoyl,the_same_box); // Don't actually need density for rho * Yl derive_lst.addComponent("rho_Yl",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("rho_Yl",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("rho_Yl",desc_lst,Rad_Type,0,Radiation::nGroups); // // Yl = (Ye + Ynue - Ynuebar) // derive_lst.add("Yl",IndexType::TheCellType(),1,ca_deryl,the_same_box); derive_lst.addComponent("Yl",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Yl",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Yl",desc_lst,Rad_Type,0,Radiation::nGroups); // // Ynue // derive_lst.add("Ynue",IndexType::TheCellType(),1,ca_derynue,the_same_box); derive_lst.addComponent("Ynue",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Ynue",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Ynue",desc_lst,Rad_Type,0,Radiation::nGroups); // // Ynuebar // derive_lst.add("Ynuae",IndexType::TheCellType(),1,ca_derynuae,the_same_box); derive_lst.addComponent("Ynuae",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Ynuae",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Ynuae",desc_lst,Rad_Type,0,Radiation::nGroups); } #endif for (int i = 0; i < NumAux; i++) { derive_lst.add(aux_names[i],IndexType::TheCellType(),1,ca_derspec,the_same_box); derive_lst.addComponent(aux_names[i],desc_lst,State_Type,Density,1); derive_lst.addComponent(aux_names[i],desc_lst,State_Type,FirstAux+i,1); } #if 0 // // A derived quantity equal to all the state variables. // derive_lst.add("FULLSTATE",IndexType::TheCellType(),NUM_STATE,FORT_DERCOPY,the_same_box); derive_lst.addComponent("FULLSTATE",desc_lst,State_Type,Density,NUM_STATE); #endif // // Problem-specific adds #include <Problem_Derives.H> // // DEFINE ERROR ESTIMATION QUANTITIES // ErrorSetUp(); // // Construct an array holding the names of the source terms. // source_names.resize(num_src); // Fill with an empty string to initialize. for (int n = 0; n < num_src; ++n) source_names[n] = ""; source_names[ext_src] = "user-defined external"; source_names[thermo_src] = "pdivU source"; #ifdef SPONGE source_names[sponge_src] = "sponge"; #endif #ifdef DIFFUSION source_names[diff_src] = "diffusion"; #endif #ifdef HYBRID_MOMENTUM source_names[hybrid_src] = "hybrid"; #endif #ifdef GRAVITY source_names[grav_src] = "gravity"; #endif #ifdef ROTATION source_names[rot_src] = "rotation"; #endif #ifdef AMREX_USE_CUDA // Set the minimum number of threads needed per // threadblock to do BC fills with CUDA. We will // force this to be 8. The reason is that it is // not otherwise guaranteed for our thread blocks // to be aligned with the grid in such a way that // the synchronization logic in amrex_filccn works // out. We need at least NUM_GROW + 1 threads in a // block for CTU. If we used this minimum of 5, we // would hit cases where this doesn't work since // our blocking_factor is usually a power of 2, and // the thread blocks would not be aligned to guarantee // that the threadblocks containing the ghost zones // contained all of the ghost zones, as well as the // required interior zone. And for reflecting BCs, // we need NUM_GROW * 2 == 8 threads anyway. This logic // then requires that blocking_factor be a multiple // of 8. It is a little wasteful for MOL/SDC and for // problems that only have outflow BCs, but the BC // fill is not the expensive part of the algorithm // for our production science problems anyway, so // we ignore this extra cost in favor of safety. for (int dim = 0; dim < AMREX_SPACEDIM; ++dim) { numBCThreadsMin[dim] = 8; } #endif // method of lines Butcher tableau if (mol_order == 1) { // first order Euler MOL_STAGES = 1; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {1}; b_mol = {1.0}; c_mol = {0.0}; } else if (mol_order == 2) { // second order TVD MOL_STAGES = 2; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0, 0,}; a_mol[1] = {1.0, 0,}; b_mol = {0.5, 0.5}; c_mol = {0.0, 1.0}; } else if (mol_order == 3) { // third order TVD MOL_STAGES = 3; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0.0, 0.0, 0.0}; a_mol[1] = {1.0, 0.0, 0.0}; a_mol[2] = {0.25, 0.25, 0.0}; b_mol = {1./6., 1./6., 2./3.}; c_mol = {0.0, 1.0, 0.5}; } else if (mol_order == 4) { // fourth order TVD MOL_STAGES = 4; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0.0, 0.0, 0.0, 0.0}; a_mol[1] = {0.5, 0.0, 0.0, 0.0}; a_mol[2] = {0.0, 0.5, 0.0, 0.0}; a_mol[3] = {0.0, 0.0, 1.0, 0.0}; b_mol = {1./6., 1./3., 1./3., 1./6.}; c_mol = {0.0, 0.5, 0.5, 1.0}; } else { amrex::Error("invalid value of mol_order\n"); } if (sdc_order == 2) { SDC_NODES = 2; dt_sdc.resize(SDC_NODES); dt_sdc = {0.0, 1.0}; } else if (sdc_order == 4) { SDC_NODES = 3; dt_sdc.resize(SDC_NODES); dt_sdc = {0.0, 0.5, 1.0}; } else { amrex::Error("invalid value of sdc_order"); } }
30.218213
125
0.682948
taehoryu
fd950068b66f62a9cda8be91187ffc09d07c0317
347
cpp
C++
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
5
2020-05-02T17:29:32.000Z
2021-09-20T19:19:15.000Z
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
null
null
null
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
3
2020-05-02T19:03:48.000Z
2021-09-22T03:44:22.000Z
#include <windows.h> #define MAX_SPRITES 500 static char * sprites[MAX_SPRITES]; void add_sprite (int id, const char * sprite) { if ( id >= 0 && id < MAX_SPRITES ) sprites[id] = _strdup(sprite); } const char * sprite_lookup (int id) { if ( id >= 0 && id < MAX_SPRITES && sprites[id] ) return sprites[id]; else return "unknown"; }
15.086957
50
0.642651
playday3008
fd959e3560b430d01b109c088e8fdc86c2af665d
324
cpp
C++
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> p(n); for (int i = 0; i < n; i++) { cin >> p.at(i); } sort(p.begin(), p.end()); int ans = 0; for (int i = 0; i < k; i++) { ans += p.at(i); } cout << ans << endl; }
16.2
31
0.398148
shikij1
fd9608a96dc28699a5f4d4a75a9407d3b75524cc
1,057
cpp
C++
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
/* File: osx_clipboard.cpp Author: Taylor Robbins Date: 10\07\2017 Description: ** Holds the functions that handle interfacing with the OSX clipboard #included from osx_main.cpp */ // +==============================+ // | OSX_CopyToClipboard | // +==============================+ // void OSX_CopyToClipboard(const void* dataPntr, u32 dataSize) CopyToClipboard_DEFINITION(OSX_CopyToClipboard) { char* tempSpace = (char*)malloc(dataSize+1); memcpy(tempSpace, dataPntr, dataSize); tempSpace[dataSize] = '\0'; glfwSetClipboardString(PlatformInfo.window, tempSpace); free(tempSpace); } // +==============================+ // | OSX_CopyFromClipboard | // +==============================+ // void* OSX_CopyFromClipboard(MemoryArena_t* arenaPntr, u32* dataLengthOut) CopyFromClipboard_DEFINITION(OSX_CopyFromClipboard) { *dataLengthOut = 0; const char* contents = glfwGetClipboardString(PlatformInfo.window); if (contents == nullptr) { return nullptr; } *dataLengthOut = (u32)strlen(contents); return (void*)contents; }
25.780488
76
0.645222
robbitay
fd970f34f194556769ef7690cc14f1031e52ea60
2,182
cpp
C++
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
#include "./utility/rt.h" int DIM_SIZE; int TILE_SIZE; void stencil_trace(int *a, int *b, unsigned int dim_size, unsigned int tile_size) { vector<int> idx; for (int i = 1; i < dim_size+1 ; i += tile_size) { for (int j = 1; j < dim_size+1; j += tile_size) { for (int i_tiled = i; i_tiled < min(i+tile_size, dim_size+1); i_tiled++) { for (int j_tiled = j; j_tiled < min(j+tile_size, dim_size+1); j_tiled++) { idx.clear(); idx.push_back(i); idx.push_back(j); idx.push_back(i_tiled), idx.push_back(j_tiled); b[i_tiled* (DIM_SIZE + 2) +j_tiled] = a[i_tiled* (DIM_SIZE + 2)+j_tiled] + a[i_tiled* (DIM_SIZE + 2)+j_tiled + 1] + a[i_tiled* (DIM_SIZE + 2)+j_tiled - 1] + a[(i_tiled-1)* (DIM_SIZE + 2) +j_tiled] + a[(i_tiled+1)* (DIM_SIZE + 2) +j_tiled]; rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled, 0, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + 1, 1, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled - 1, 2, 0, idx); rtTmpAccess( (i_tiled-1) * (DIM_SIZE + 2) + j_tiled, 3, 0, idx); rtTmpAccess( (i_tiled+1) * (DIM_SIZE + 2) + j_tiled, 4, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + (DIM_SIZE + 2)* (DIM_SIZE + 2), 5, 0, idx); } } } } return; } int main(int argc, char* argv[]) { if (argc != 3) { cout << "This benchmark needs 1 loop bounds" << endl; return 0; } for (int i = 1; i < argc; i++) { if (!isdigit(argv[i][0])) { cout << "arguments must be integer" << endl; return 0; } } DIM_SIZE = stoi(argv[1]); TILE_SIZE = stoi(argv[2]); int* a = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int)); int* b = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int)); for (int i = 0; i < (DIM_SIZE+2) * (DIM_SIZE+2); i++) { a[i] = i % 256; } stencil_trace(a, b, DIM_SIZE, TILE_SIZE); dumpRIHistogram(); return 0; }
34.09375
260
0.502291
dongchen-coder
fd9bac4ea6c171531547acca5321b589e4b835f5
331
hpp
C++
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_BLT_LUA_BLT_DEBUG_HPP_ #define BE_BLT_LUA_BLT_DEBUG_HPP_ #include <lua/lua.h> #include <lua/lauxlib.h> namespace be::belua { /////////////////////////////////////////////////////////////////////////////// int open_blt_debug(lua_State* L); extern const luaL_Reg blt_debug_module; } // be::belua #endif
18.388889
79
0.586103
magicmoremagic
fd9c2ba127d918e8af4c838a2055f606c87b22f5
3,133
cpp
C++
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
22
2019-08-19T21:09:29.000Z
2022-03-25T23:19:15.000Z
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
6
2019-11-08T22:17:03.000Z
2022-03-10T05:02:59.000Z
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
6
2019-08-24T08:03:14.000Z
2022-02-04T15:04:52.000Z
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ #ifdef EDITOR #include <string.h> #include "main_d1/inferno.h" #include "editor.h" #include "kdefs.h" static fix r1scale, r4scale; static int curve; int InitCurve() { curve = 0; return 1; } int GenerateCurve() { if ( (Markedsegp != 0) && !IS_CHILD(Markedsegp->children[Markedside])) { r1scale = r4scale = F1_0*20; autosave_mine( mine_filename ); diagnostic_message("Curve Generated."); Update_flags |= UF_WORLD_CHANGED; curve = generate_curve(r1scale, r4scale); mine_changed = 1; if (curve == 1) { strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n"); } if (curve == 0) diagnostic_message("Cannot generate curve -- check Current segment."); } else diagnostic_message("Cannot generate curve -- check Marked segment."); warn_if_concave_segments(); return 1; } int DecreaseR4() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r4scale -= F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R4 vector decreased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int IncreaseR4() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r4scale += F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R4 vector increased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int DecreaseR1() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r1scale -= F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R1 vector decreased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int IncreaseR1() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r1scale += F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R1 vector increased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int DeleteCurve() { // fix_bogus_uvs_all(); set_average_light_on_curside(); if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); curve = 0; mine_changed = 1; diagnostic_message("Curve Deleted."); warn_if_concave_segments(); } return 1; } int SetCurve() { if (curve) curve = 0; //autosave_mine( mine_filename ); //strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n"); return 1; } #endif
23.734848
94
0.691031
ziplantil
fd9c65cff4c22e9600b1a2369c1c0ef5af326a73
2,822
cpp
C++
Components/Paging/src/OgrePageContentCollection.cpp
rjdgtn/OgreCPPBuilder
1d3fa5874e54da9c19f4fe9fd128fcda19285b5e
[ "MIT" ]
108
2015-01-23T01:43:56.000Z
2021-12-23T07:00:48.000Z
Components/Paging/src/OgrePageContentCollection.cpp
venscn/ogre
069a43c4c4fcb5264c995fca65a28acd3154b230
[ "MIT" ]
2
2016-03-05T14:40:20.000Z
2017-02-20T11:33:51.000Z
Components/Paging/src/OgrePageContentCollection.cpp
venscn/ogre
069a43c4c4fcb5264c995fca65a28acd3154b230
[ "MIT" ]
92
2015-01-13T08:57:11.000Z
2021-09-19T05:20:55.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd 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 "OgrePageContentCollection.h" #include "OgrePageContentCollectionFactory.h" #include "OgreStreamSerialiser.h" #include "OgrePageContent.h" #include "OgrePage.h" namespace Ogre { //--------------------------------------------------------------------- const uint32 PageContentCollection::CHUNK_ID = StreamSerialiser::makeIdentifier("PGCC"); const uint16 PageContentCollection::CHUNK_VERSION = 1; //--------------------------------------------------------------------- PageContentCollection::PageContentCollection(PageContentCollectionFactory* creator) : mCreator(creator), mParent(0) { } //--------------------------------------------------------------------- PageContentCollection::~PageContentCollection() { // don't call destroy(), we're not the final subclass } //--------------------------------------------------------------------- PageManager* PageContentCollection::getManager() const { return mParent->getManager(); } //--------------------------------------------------------------------- const String& PageContentCollection::getType() const { return mCreator->getName(); } //--------------------------------------------------------------------- void PageContentCollection::_notifyAttached(Page* parent) { mParent = parent; } //--------------------------------------------------------------------- SceneManager* PageContentCollection::getSceneManager() const { return mParent->getSceneManager(); } }
38.135135
89
0.600283
rjdgtn
fd9f677956fdd04c41a4c5bc69eebff87eeb6257
3,156
hpp
C++
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
#pragma once #include "matrix.hpp" #include "max-or-inf.hpp" #include "global-greedy.hpp" #include "edge.hpp" #include "print-info.hpp" #include "k-opt.hpp" #include <unordered_set> #include <random> #include <iostream> #include <cmath> template<typename T> class Sigma_Male { public: Sigma_Male(uint32_t seed, double recency = 1.0 / 1024.0); void grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt = true); const Matrix<double>& get_freq_mat(); T get_min_path_length() const; const std::vector<size_t>& get_shortest_path_found(); private: Matrix<double> frequency; std::vector<size_t> shortest_path_found; T min_path_length; std::mt19937 rng; double recency; }; template<typename T> Sigma_Male<T>::Sigma_Male(uint32_t s, double r) : min_path_length{get_max_val_or_inf<T>()}, rng{s}, recency(r) {} template<typename T> void Sigma_Male<T>::grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt) { frequency = Matrix<double>(mat.get_num_rows(), mat.get_num_cols(), [](){ return 0; }); Global_Greedy<T> gg; Matrix<T> cur_mat = mat; K_Opt<T> kopt(137, 5); double cur_path_length = 1.0; double thing_to_add = 0.0; for (size_t i = 0; i < num_iterations; i++) { gg.run(cur_mat, start); std::vector<size_t> path = gg.get_path(); if (run_kopt) { //print_path(path); //std::cout << "Path Length: " << get_path_length(path, mat) << "\n"; kopt.run(mat, start, path); //print_path(path); //std::cout << "Path Length: " << get_path_length(path, mat) << "\n"; //std::cout << "--------------------------------------------------------------------------------\n"; } cur_path_length = get_path_length(path, mat); if (cur_path_length < min_path_length) { min_path_length = get_path_length(path, mat); shortest_path_found = path; } std::vector<Edge> edges; edges.reserve(path.size()); T path_length{}; for (size_t j = 0; j < path.size() - 1; j++) { const size_t& cur = path[j]; const size_t& next = path[j + 1]; if (cur_path_length <= min_path_length) { thing_to_add = 1.0; } else { thing_to_add = 1.0 / (1.0 + cur_path_length - min_path_length); thing_to_add *= thing_to_add; } frequency.at(cur, next) *= (1.0 - recency); frequency.at(cur, next) += thing_to_add * recency; edges.push_back({cur, next}); path_length += mat.at(cur, next); } // std::cout << "Path Length: " << path_length << "\n"; cur_mat = mat; std::vector<double> edge_weights; edge_weights.reserve(edges.size()); for (const Edge& edge : edges) { T cur_edge_length = mat.at(edge.start, edge.end); edge_weights.push_back(mat.at(edge.start, edge.end)); } std::discrete_distribution<size_t> dist{edge_weights.begin(), edge_weights.end()}; for (size_t j = 0; j < 2 * sqrt(edges.size()); j++) { const Edge& cur_edge = edges[dist(rng)]; cur_mat.at(cur_edge.start, cur_edge.end) = get_max_val_or_inf<T>() / mat.get_num_cols(); } } } template<typename T> const Matrix<double>& Sigma_Male<T>::get_freq_mat() { return frequency; } template<typename T> T Sigma_Male<T>::get_min_path_length() const { return min_path_length; }
32.204082
113
0.66033
TheLandfill
fd9f7924ebf04332cf47b9b218a81f138e03bb0e
2,920
hpp
C++
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
8
2016-06-13T20:47:18.000Z
2021-12-22T17:29:32.000Z
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
11
2016-03-14T07:00:04.000Z
2019-05-07T18:20:15.000Z
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
11
2016-02-03T07:41:00.000Z
2019-09-11T10:03:48.000Z
/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * 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 StatusInitializerStub_hpp #define StatusInitializerStub_hpp #include <stdio.h> #include "StatusInitializer.hpp" namespace loc{ class StatusInitializerStub : public StatusInitializer{ public: Locations initializeLocations(int n){ Locations locs; //int n= 100; for(int i=0; i<n; i++){ Location loc(0,0,0,0); locs.push_back(loc); } return locs; } Poses initializePoses(int n){ Locations locs = initializeLocations(n); //int n = (int) locs.size(); Poses poses(n); for(int i=0; i<n; i++){ Location loc = locs.at(i); Pose pose; pose.x(loc.x()).y(loc.y()).floor(loc.floor()).z(loc.z()); pose.orientation(0.0).velocity(1.0).normalVelocity(1.0); poses[i]=pose; } return poses; } States initializeStates(int n){ Poses poses = initializePoses(n); //int n = (int) poses.size(); States states(n); for(int i=0; i<n; i++){ Pose pose = poses.at(i); State state; state.x(pose.x()).y(pose.y()).floor(pose.floor()).z(pose.z()); state.orientation(0.0).velocity(1.0).normalVelocity(1.0); state.orientationBias(0.0).rssiBias(0.0); states[i]=state; } return states; } }; } #endif /* StatusInitializerStub_hpp */
37.922078
81
0.561986
harsh-agarwal
fd9fa1cb52f4650aa6bc9139634f2be98da4524b
706
cpp
C++
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
2
2020-09-13T07:31:22.000Z
2022-03-26T08:37:32.000Z
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
// c:/Users/user/Documents/Programming/Music/Chou/OnKai/a.cpp #include "../../Header.hpp" #include "a_Body.hpp" #include "../../../Error/FaultInCoding/a.hpp" const PitchClass& OnKai::PitchClassTable( const KaiMei& num ) const noexcept { const PitchClass* p_Table[7] = { &m_I , &m_II , &m_III , &m_IV , &m_V , &m_VI , &m_VII }; return *p_Table[ num.Represent() ]; } DEFINITION_OF_GLOBAL_CONST_ON_KAI( ChouOnKai , 0 , 2 , 4 , 5 , 7 , 9 , 11 ); DEFINITION_OF_GLOBAL_CONST_ON_KAI( WaSeiTekiTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 11 ); DEFINITION_OF_GLOBAL_CONST_ON_KAI( ShiZenTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 10 );
22.774194
85
0.580737
p-adic
fda1d5ce2c84d7bc8d28f9369623e7ed5f1a1fd9
983
cpp
C++
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(nlogn) // Space: O(n) class Solution { public: int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) { static const int MOD = 1e9 + 7; vector<int> sorted_nums1(cbegin(nums1), cend(nums1)); sort(begin(sorted_nums1), end(sorted_nums1)); int result = 0, max_change = 0; for (int i = 0; i < size(nums2); ++i) { int diff = abs(nums1[i] - nums2[i]); result = (result + diff) % MOD; if (diff < max_change) { continue; } const auto cit = lower_bound(cbegin(sorted_nums1), cend(sorted_nums1), nums2[i]); if (cit != cend(sorted_nums1)) { max_change = max(max_change, diff - abs(*cit - nums2[i])); } if (cit != cbegin(sorted_nums1)) { max_change = max(max_change, diff - abs(*prev(cit) - nums2[i])); } } return (result - max_change + MOD) % MOD; } };
33.896552
93
0.513733
Priyansh2
fda2321fad5286503ca80c58a301c01a2e4d797d
2,258
cpp
C++
src/Core/Utils/Attribs.cpp
Yasoo31/Radium-Engine
e22754d0abe192207fd946509cbd63c4f9e52dd4
[ "Apache-2.0" ]
78
2017-12-01T12:23:22.000Z
2022-03-31T05:08:09.000Z
src/Core/Utils/Attribs.cpp
neurodiverseEsoteric/Radium-Engine
ebebc29d889a9d32e0637e425e589e403d8edef8
[ "Apache-2.0" ]
527
2017-09-25T13:05:32.000Z
2022-03-31T18:47:44.000Z
src/Core/Utils/Attribs.cpp
neurodiverseEsoteric/Radium-Engine
ebebc29d889a9d32e0637e425e589e403d8edef8
[ "Apache-2.0" ]
48
2018-01-04T22:08:08.000Z
2022-03-03T08:13:41.000Z
#include <Core/Types.hpp> #include <Core/Utils/Attribs.hpp> #include <Core/Utils/Log.hpp> namespace Ra { namespace Core { namespace Utils { AttribBase::~AttribBase() { notify(); } template <> size_t Attrib<float>::getElementSize() const { return 1; } template <> size_t Attrib<double>::getElementSize() const { return 1; } AttribManager::~AttribManager() { clear(); } void AttribManager::clear() { m_attribs.clear(); m_attribsIndex.clear(); } void AttribManager::copyAllAttributes( const AttribManager& m ) { for ( const auto& attr : m.m_attribs ) { if ( attr == nullptr ) continue; if ( attr->isFloat() ) { auto h = addAttrib<Scalar>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Scalar>*>( attr.get() )->data() ); } else if ( attr->isVector2() ) { auto h = addAttrib<Vector2>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector2>*>( attr.get() )->data() ); } else if ( attr->isVector3() ) { auto h = addAttrib<Vector3>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector3>*>( attr.get() )->data() ); } else if ( attr->isVector4() ) { auto h = addAttrib<Vector4>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector4>*>( attr.get() )->data() ); } else LOG( logWARNING ) << "Warning, copy of mesh attribute " << attr->getName() << " type is not supported (only float, vec2, vec3 nor vec4 are " "supported) [from AttribManager::copyAllAttribute()]"; } } bool AttribManager::hasSameAttribs( const AttribManager& other ) { // one way for ( const auto& attr : m_attribsIndex ) { if ( other.m_attribsIndex.find( attr.first ) == other.m_attribsIndex.cend() ) { return false; } } // the other way for ( const auto& attr : other.m_attribsIndex ) { if ( m_attribsIndex.find( attr.first ) == m_attribsIndex.cend() ) { return false; } } return true; } } // namespace Utils } // namespace Core } // namespace Ra
27.876543
95
0.564659
Yasoo31
fda6887ac89caed203cb87e0564c5addc3e98af8
5,654
cpp
C++
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
8
2016-04-14T17:17:07.000Z
2021-12-06T06:49:28.000Z
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
null
null
null
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
2
2019-06-13T10:01:32.000Z
2021-11-19T18:53:52.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_, const bool deleteSourceWhenDeleted) : source (source_, deleteSourceWhenDeleted), requiredNumberOfChannels (2) { remappedInfo.buffer = &buffer; remappedInfo.startSample = 0; } ChannelRemappingAudioSource::~ChannelRemappingAudioSource() {} //============================================================================== void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) { const ScopedLock sl (lock); requiredNumberOfChannels = requiredNumberOfChannels_; } void ChannelRemappingAudioSource::clearAllMappings() { const ScopedLock sl (lock); remappedInputs.clear(); remappedOutputs.clear(); } void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) { const ScopedLock sl (lock); while (remappedInputs.size() < destIndex) remappedInputs.add (-1); remappedInputs.set (destIndex, sourceIndex); } void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) { const ScopedLock sl (lock); while (remappedOutputs.size() < sourceIndex) remappedOutputs.add (-1); remappedOutputs.set (sourceIndex, destIndex); } int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const { const ScopedLock sl (lock); if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size()) return remappedInputs.getUnchecked (inputChannelIndex); return -1; } int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const { const ScopedLock sl (lock); if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size()) return remappedOutputs .getUnchecked (outputChannelIndex); return -1; } //============================================================================== void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate) { source->prepareToPlay (samplesPerBlockExpected, sampleRate); } void ChannelRemappingAudioSource::releaseResources() { source->releaseResources(); } void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { const ScopedLock sl (lock); buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true); const int numChans = bufferToFill.buffer->getNumChannels(); for (int i = 0; i < buffer.getNumChannels(); ++i) { const int remappedChan = getRemappedInputChannel (i); if (remappedChan >= 0 && remappedChan < numChans) { buffer.copyFrom (i, 0, *bufferToFill.buffer, remappedChan, bufferToFill.startSample, bufferToFill.numSamples); } else { buffer.clear (i, 0, bufferToFill.numSamples); } } remappedInfo.numSamples = bufferToFill.numSamples; source->getNextAudioBlock (remappedInfo); bufferToFill.clearActiveBufferRegion(); for (int i = 0; i < requiredNumberOfChannels; ++i) { const int remappedChan = getRemappedOutputChannel (i); if (remappedChan >= 0 && remappedChan < numChans) { bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample, buffer, i, 0, bufferToFill.numSamples); } } } //============================================================================== XmlElement* ChannelRemappingAudioSource::createXml() const { XmlElement* e = new XmlElement ("MAPPINGS"); String ins, outs; const ScopedLock sl (lock); for (int i = 0; i < remappedInputs.size(); ++i) ins << remappedInputs.getUnchecked(i) << ' '; for (int i = 0; i < remappedOutputs.size(); ++i) outs << remappedOutputs.getUnchecked(i) << ' '; e->setAttribute ("inputs", ins.trimEnd()); e->setAttribute ("outputs", outs.trimEnd()); return e; } void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) { if (e.hasTagName ("MAPPINGS")) { const ScopedLock sl (lock); clearAllMappings(); StringArray ins, outs; ins.addTokens (e.getStringAttribute ("inputs"), false); outs.addTokens (e.getStringAttribute ("outputs"), false); for (int i = 0; i < ins.size(); ++i) remappedInputs.add (ins[i].getIntValue()); for (int i = 0; i < outs.size(); ++i) remappedOutputs.add (outs[i].getIntValue()); } }
30.562162
102
0.616732
ChrSacher
fdac081e1c692002a920c526e8b4021cdf42a4b5
3,129
cpp
C++
src/NetWidgets/Widgets/nTldEditor.cpp
Vladimir-Lin/QtNetWidgets
e09339c47d40b65875f15bd0839e0bdf89951601
[ "MIT" ]
null
null
null
src/NetWidgets/Widgets/nTldEditor.cpp
Vladimir-Lin/QtNetWidgets
e09339c47d40b65875f15bd0839e0bdf89951601
[ "MIT" ]
null
null
null
src/NetWidgets/Widgets/nTldEditor.cpp
Vladimir-Lin/QtNetWidgets
e09339c47d40b65875f15bd0839e0bdf89951601
[ "MIT" ]
null
null
null
#include <netwidgets.h> N::TldEditor:: TldEditor ( QWidget * parent , Plan * p ) : TreeWidget ( parent , p ) , NetworkManager ( p ) { WidgetClass ; Configure ( ) ; } N::TldEditor::~TldEditor(void) { } void N::TldEditor::Configure(void) { setWindowTitle ( tr("Top level domains") ) ; setDragDropMode ( DragOnly ) ; setRootIsDecorated ( false ) ; setAlternatingRowColors ( true ) ; setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ; setVerticalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ; setColumnCount ( 6 ) ; NewTreeWidgetItem ( header ) ; header->setText ( 0,tr("Top level domain")) ; header->setText ( 1,tr("Country" )) ; header->setText ( 2,tr("NIC" )) ; header->setText ( 3,tr("SLDs" )) ; header->setText ( 4,tr("Sites" )) ; header->setText ( 5,tr("Comment" )) ; setHeaderItem ( header ) ; plan -> setFont ( this ) ; } bool N::TldEditor::FocusIn(void) { LinkAction ( Refresh , List () ) ; LinkAction ( Copy , CopyToClipboard() ) ; return true ; } void N::TldEditor::List(void) { SqlConnection SC ( plan->sql ) ; QString CN = QtUUID::createUuidString ( ) ; if (SC.open("TldEditor",CN)) { if (LoadDomainIndex(SC)) { QString tld ; foreach (tld,TLDs) { NewTreeWidgetItem ( IT ) ; SUID uuid = TldUuids [ tld ] ; int country = TldNations [ uuid ] ; SUID cuid = Countries [ country ] ; QString nic = NICs [ uuid ] ; int slds = TldCounts ( SC,uuid ) ; int tlds = TldTotal ( SC,uuid ) ; QString comment = Comments [ uuid ] ; IT -> setData (0,Qt::UserRole,uuid ) ; IT -> setTextAlignment(3,Qt::AlignRight) ; IT -> setTextAlignment(4,Qt::AlignRight) ; IT -> setText (0,tld ) ; IT -> setText (1,Nations[cuid] ) ; IT -> setText (2,nic ) ; IT -> setText (3,QString::number(slds) ) ; IT -> setText (4,QString::number(tlds) ) ; IT -> setText (5,comment ) ; addTopLevelItem ( IT ) ; } ; } ; SC . close ( ) ; } ; SC.remove() ; SuitableColumns ( ) ; Alert ( Done ) ; }
41.171053
61
0.388623
Vladimir-Lin
fdad58b919553a96e292c08df88a8af29d0a0cb6
1,264
cpp
C++
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
1
2022-03-16T08:56:31.000Z
2022-03-16T08:56:31.000Z
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
2
2022-03-17T11:27:14.000Z
2022-03-18T07:41:00.000Z
Fudl/easy/solved/Encryption Decryption of Enigma Machine.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
6
2022-03-13T19:56:11.000Z
2022-03-17T12:08:22.000Z
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ int main() { string operation; getline(cin, operation); int pseudo_random_number; cin >> pseudo_random_number; cin.ignore(); string rotor[3]; for (int i = 0; i < 3; i++) { getline(cin, rotor[i]); } string message; getline(cin, message); if (operation[0] == 'E') { for (int i = 0; i < message.size(); i++) { message[i] = ((message[i] - 'A' + pseudo_random_number + i) % 26) + 'A'; } for (int i = 0; i < 3; i++) for (int j = 0; j < message.size(); j++) message[j] = rotor[i][message[j] - 'A']; } else { for (int i = 2; i > -1; i--) for (int j = 0; j < message.size(); j++) message[j] = rotor[i].find(message[j]) + 'A'; for (int i = 0; i < message.size(); i++) { int idx = (message[i] - 'A' - pseudo_random_number - i); while (idx < 0) idx += 26; message[i] = (idx % 26) + 'A'; } } // Write an answer using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; cout << message << endl; }
25.28
78
0.544304
AhmedMostafa7474
fdaff450fae58a320c147339e085c3fe07618ada
4,968
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Remoting/IPEndPoint_Properties/CPP/ipendpoint_properties.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
// System.Net.IPEndPoint.MaxPort; System.Net.IPEndPoint.MinPort; // System.Net.IPEndPoint.AddressFamily; System.Net.IPEndPoint.IPEndPoint(long,int) // System.Net.IPEndPoint.Address; System.Net.IPEndPoint.Port; /*This program demonstrates the properties 'MaxPort', 'MinPort','Address','Port' and 'AddressFamily' and a constructor 'IPEndPoint(long,int)' of class 'IPEndPoint'. A procedure DoSocketGet is created which internally uses a socket to transmit http "Get" requests to a Web resource. The program accepts a resource Url, Resolves it to obtain 'IPAddress',Constructs 'IPEndPoint' instance using this 'IPAddress' and port 80.Invokes DoSocketGet procedure to obtain a response and displays the response to a console. It then accepts another Url, Resolves it to obtain 'IPAddress'. Assigns this IPAddress and port to the 'IPEndPoint' and again invokes DoSocketGet to obtain a response and display. */ #using <System.dll> using namespace System; using namespace System::Net; using namespace System::Text; using namespace System::Net::Sockets; using namespace System::Runtime::InteropServices; String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString ); // forward reference int main() { try { Console::Write( "\nPlease enter an INTRANET Url as shown: [e.g. www.microsoft.com]:" ); String^ hostString1 = Console::ReadLine(); // <Snippet1> // <Snippet2> // <Snippet3> // <Snippet4> IPAddress^ hostIPAddress1 = (Dns::Resolve( hostString1 ))->AddressList[ 0 ]; Console::WriteLine( hostIPAddress1 ); IPEndPoint^ hostIPEndPoint = gcnew IPEndPoint( hostIPAddress1,80 ); Console::WriteLine( "\nIPEndPoint information:{0}", hostIPEndPoint ); Console::WriteLine( "\n\tMaximum allowed Port Address :{0}", IPEndPoint::MaxPort ); Console::WriteLine( "\n\tMinimum allowed Port Address :{0}", (int^)IPEndPoint::MinPort ); Console::WriteLine( "\n\tAddress Family :{0}", hostIPEndPoint->AddressFamily ); // </Snippet4> Console::Write( "\nPress Enter to continue" ); Console::ReadLine(); String^ getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString1 ); String^ pageContent = DoSocketGet( hostIPEndPoint, getString ); if ( pageContent != nullptr ) { Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString1, pageContent ); } // </Snippet3> // </Snippet2> // </Snippet1> Console::Write( "\n\n\nPlease enter another INTRANET Url as shown[e.g. www.microsoft.com]: " ); String^ hostString2 = Console::ReadLine(); // <Snippet5> // <Snippet6> IPAddress^ hostIPAddress2 = (Dns::Resolve( hostString2 ))->AddressList[ 0 ]; hostIPEndPoint->Address = hostIPAddress2; hostIPEndPoint->Port = 80; getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString2 ); pageContent = DoSocketGet( hostIPEndPoint, getString ); if ( pageContent != nullptr ) { Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString2, pageContent ); } // </Snippet6> // </Snippet5> } catch ( SocketException^ e ) { Console::WriteLine( "SocketException caught!!!" ); Console::WriteLine( "Source : {0}", e->Source ); Console::WriteLine( "Message : {0}", e->Message ); } catch ( Exception^ e ) { Console::WriteLine( "Exception caught!!!" ); Console::WriteLine( "Message : {0}", e->Message ); } } String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString ) { try { // Set up variables and String to write to the server. Encoding^ ASCII = Encoding::ASCII; array<Byte>^ byteGet = ASCII->GetBytes( getString ); array<Byte>^ recvBytes = gcnew array<Byte>(256); String^ strRetPage = nullptr; // Create the Socket for sending data over TCP. Socket^ mySocket = gcnew Socket( AddressFamily::InterNetwork, SocketType::Stream,ProtocolType::Tcp ); // Connect to host using IPEndPoint. mySocket->Connect( hostIPEndPoint ); // Send the GET text to the host. mySocket->Send( byteGet, byteGet->Length, (SocketFlags)( 0 ) ); // Receive the page, loop until all bytes are received. Int32 byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) ); strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) ); while ( byteCount > 0 ) { byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) ); strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) ); } return strRetPage; } catch ( Exception^ e ) { Console::WriteLine( "Exception : {0}", e->Message ); Console::WriteLine( "WinSock Error : {0}", Convert::ToString( Marshal::GetLastWin32Error() ) ); return nullptr; } }
40.064516
116
0.665056
BaruaSourav
fdb88e251cd9269f4c7ee441c391c7eb1f7f181d
1,715
cpp
C++
tests/ranges/wrappers.cpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
30
2015-04-19T17:04:33.000Z
2022-03-22T13:26:53.000Z
tests/ranges/wrappers.cpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
4
2018-05-27T18:20:10.000Z
2021-11-28T15:22:12.000Z
tests/ranges/wrappers.cpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
8
2016-10-28T16:46:05.000Z
2021-02-24T16:49:20.000Z
#include <gtest/gtest.h> #include <vector> #include <spcppl/ranges/wrappers.hpp> #include <spcppl/ranges/Range.hpp> TEST(WrappersTest, Reversed) { EXPECT_EQ(reversed(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{3, 2, 7, 5})); } TEST(WrappersTest, Sorted) { EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{2, 3, 5, 7})); } TEST(WrapperTest, SortedWithComparator) { EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}, std::greater<int>()), (std::vector<int>{7, 5, 3, 2})); } TEST(WrapperTest, Unique) { std::vector<int> v = {5, 7, 7, 7, 3}; unique(v); EXPECT_EQ(v, (std::vector<int>{5, 7, 3})); } TEST(WrapperTest, UniquePreservesNotAdjascentElements) { std::vector<int> v = {1, 2, 1}; std::vector<int> original_v = v; unique(v); EXPECT_EQ(v, original_v); } TEST(WrapperTest, FindsMaxElement) { std::vector<int> v = {5, 7, 3}; EXPECT_EQ(*max_element(v), 7); } TEST(WrapperTest, MaxOfEmptyRangeIsBegin) { std::vector<int> v; EXPECT_EQ(max_element(v), v.begin()); } TEST(WrapperTest, FindsMinElement) { std::vector<int> v = {5, 7, 3}; EXPECT_EQ(*min_element(v), 3); } TEST(WrapperTest, MinOfEmptyRangeIsBegin) { std::vector<int> v; EXPECT_EQ(min_element(v), v.begin()); } TEST(WrapperTest, FindsMaxOfPartOfRange) { std::vector<int> v = {100, 1, 2, 5, 0, 15, -1}; EXPECT_EQ(*max_element(make_range(v.begin() + 1, v.begin() + 4)), 5); } TEST(WrappersTest, FindsNextPermutation) { std::vector<int> v = {1, 3, 2}; EXPECT_TRUE(next_permutation(v)); EXPECT_EQ(v, (std::vector<int>{2, 1, 3})); } TEST(WrappersTest, NextPermuationCyclesAfterLastPermutation) { std::vector<int> v = {3, 2, 1}; EXPECT_FALSE(next_permutation(v)); EXPECT_EQ(v, (std::vector<int>{1, 2, 3})); }
25.597015
102
0.662974
s0rav
fdb9b06bf5f7c550eaf00083038d44ebe9096470
4,343
hpp
C++
libraries/fc/include/fc/container/flat.hpp
Laighno/evt
90b94e831aebb62c6ad19ce59c9089e9f51cfd77
[ "MIT" ]
1,411
2018-04-23T03:57:30.000Z
2022-02-13T10:34:22.000Z
libraries/fc/include/fc/container/flat.hpp
Zhang-Zexi/evt
e90fe4dbab4b9512d120c79f33ecc62791e088bd
[ "Apache-2.0" ]
27
2018-06-11T10:34:42.000Z
2019-07-27T08:50:02.000Z
libraries/fc/include/fc/container/flat.hpp
Zhang-Zexi/evt
e90fe4dbab4b9512d120c79f33ecc62791e088bd
[ "Apache-2.0" ]
364
2018-06-09T12:11:53.000Z
2020-12-15T03:26:48.000Z
#pragma once #include <fc/variant.hpp> #include <fc/container/flat_fwd.hpp> #include <fc/container/container_detail.hpp> #include <fc/crypto/hex.hpp> namespace fc { namespace raw { template<typename Stream, typename T, typename A> void pack(Stream& s, const boost::container::vector<T, A>& value) { FC_ASSERT(value.size() <= MAX_NUM_ARRAY_ELEMENTS); pack(s, unsigned_int((uint32_t)value.size())); if(!std::is_fundamental<T>::value) { for(const auto& item : value) { pack(s, item); } } else if(value.size()) { s.write((const char*)value.data(), value.size()); } } template<typename Stream, typename T, typename A> void unpack(Stream& s, boost::container::vector<T, A>& value) { unsigned_int size; unpack(s, size); FC_ASSERT(size.value <= MAX_NUM_ARRAY_ELEMENTS); value.clear(); value.resize(size.value); if(!std::is_fundamental<T>::value) { for(auto& item : value) { unpack(s, item); } } else if(value.size()) { s.read((char*)value.data(), value.size()); } } template<typename Stream, typename A> void pack(Stream& s, const boost::container::vector<char, A>& value) { FC_ASSERT(value.size() <= MAX_SIZE_OF_BYTE_ARRAYS); pack(s, unsigned_int((uint32_t)value.size())); if(value.size()) s.write((const char*)value.data(), value.size()); } template<typename Stream, typename A> void unpack(Stream& s, boost::container::vector<char, A>& value) { unsigned_int size; unpack(s, size); FC_ASSERT(size.value <= MAX_SIZE_OF_BYTE_ARRAYS); value.clear(); value.resize(size.value); if(value.size()) s.read((char*)value.data(), value.size()); } template<typename Stream, typename T, typename... U> void pack(Stream& s, const flat_set<T, U...>& value) { detail::pack_set(s, value); } template<typename Stream, typename T, typename... U> void unpack(Stream& s, flat_set<T, U...>& value) { detail::unpack_flat_set(s, value); } template<typename Stream, typename K, typename V, typename... U> void pack(Stream& s, const flat_map<K, V, U...>& value) { detail::pack_map(s, value); } template<typename Stream, typename K, typename V, typename... U> void unpack(Stream& s, flat_map<K, V, U...>& value) { detail::unpack_flat_map(s, value); } } // namespace raw template<typename T, typename... U> void to_variant(const boost::container::vector<T, U...>& vec, fc::variant& vo) { FC_ASSERT(vec.size() <= MAX_NUM_ARRAY_ELEMENTS); variants vars; vars.reserve(vec.size()); for(const auto& item : vec) { vars.emplace_back(item); } vo = std::move(vars); } template<typename T, typename... U> void from_variant(const fc::variant& v, boost::container::vector<T, U...>& vec) { const variants& vars = v.get_array(); FC_ASSERT(vars.size() <= MAX_NUM_ARRAY_ELEMENTS); vec.clear(); vec.resize(vars.size()); for(uint32_t i = 0; i < vars.size(); ++i) { from_variant(vars[i], vec[i]); } } template<typename... U> void to_variant(const boost::container::vector<char, U...>& vec, fc::variant& vo) { FC_ASSERT(vec.size() <= MAX_SIZE_OF_BYTE_ARRAYS); if(vec.size()) vo = variant(fc::to_hex(vec.data(), vec.size())); else vo = ""; } template<typename... U> void from_variant(const fc::variant& v, boost::container::vector<char, U...>& vec) { const auto& str = v.get_string(); FC_ASSERT(str.size() <= 2 * MAX_SIZE_OF_BYTE_ARRAYS); // Doubled because hex strings needs two characters per byte vec.resize(str.size() / 2); if(vec.size()) { size_t r = fc::from_hex(str, vec.data(), vec.size()); FC_ASSERT(r == vec.size()); } } template<typename T, typename... U> void to_variant(const flat_set<T, U...>& s, fc::variant& vo) { detail::to_variant_from_set(s, vo); } template<typename T, typename... U> void from_variant(const fc::variant& v, flat_set<T, U...>& s) { detail::from_variant_to_flat_set(v, s); } template<typename K, typename V, typename... U> void to_variant(const flat_map<K, V, U...>& m, fc::variant& vo) { detail::to_variant_from_map(m, vo); } template<typename K, typename V, typename... U> void from_variant(const variant& v, flat_map<K, V, U...>& m) { detail::from_variant_to_flat_map(v, m); } } // namespace fc
26.975155
119
0.638729
Laighno
fdbac7b8eb60f180a6ca5e891dbe15ee393486fd
801
cc
C++
0389_Find_the_Difference/0389.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
0389_Find_the_Difference/0389.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
0389_Find_the_Difference/0389.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
#include <string> using std::string; class Solution { public: char findTheDifference(const string s, const string t) { size_t dict_s[26] = {0}; size_t dict_t[26] = {0}; for (const char ch : s) ++dict_s[ch - 'a']; for (const char ch : t) ++dict_t[ch - 'a']; for (size_t i = 0; i < 26; ++i) if (dict_s[i] != dict_t[i]) return static_cast<char>(i + 'a'); return '?'; } private: char moreGeneralFunction(const string s, const string t) { size_t dict_s[0x100] = {0}; size_t dict_t[0x100] = {0}; for (const char ch : s) ++dict_s[ch]; for (const char ch : t) ++dict_t[ch]; for (size_t i = 0; i < 0x100; ++i) if (dict_s[i] != dict_t[i]) return static_cast<char>(i); return '?'; } }; int main(void) { Solution sln; return 0; }
23.558824
68
0.569288
LuciusKyle
fdc16a9ddcdc7a213723934395290ff533153525
4,708
hpp
C++
include/lexer/Lexer.hpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
4
2021-01-07T10:29:49.000Z
2021-07-17T22:10:54.000Z
include/lexer/Lexer.hpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
null
null
null
include/lexer/Lexer.hpp
SimplyDanny/bitsy-llvm
125e404388ef65847eac8cb533c5321a2289bb85
[ "MIT" ]
2
2021-02-07T21:15:20.000Z
2021-07-17T22:10:55.000Z
#ifndef LEXER_HPP #define LEXER_HPP #include "lexer/Token.hpp" #include "llvm/ADT/StringSwitch.h" #include <functional> #include <iterator> #include <memory> #include <optional> #include <string> #include <type_traits> template <class InputIterator> class Lexer : public std::iterator<std::input_iterator_tag, Token> { static_assert(std::is_same<typename std::iterator_traits<InputIterator>::value_type, char>(), "Expecting iterator over 'char' type."); InputIterator current_character; InputIterator characters_end; std::optional<Token> current_token; public: Lexer(InputIterator begin, InputIterator end); Lexer() = default; Token operator*() const; Token &operator++(); Token operator++(int); bool operator==(const Lexer &other) const; bool operator!=(const Lexer &other) const; private: std::optional<Token> next(); template <class TokenMatcher> std::string get_while_matching(const TokenMatcher &matcher); static bool is_operator(char c); static bool is_identifier(char c); }; template <class InputIterator> Lexer<InputIterator>::Lexer(InputIterator begin, InputIterator end) : current_character(begin) , characters_end(end) { if (current_character != characters_end) { ++(*this); } } template <class InputIterator> Token Lexer<InputIterator>::operator*() const { return *current_token; } template <class InputIterator> Token &Lexer<InputIterator>::operator++() { return *(current_token = next()); } template <class InputIterator> Token Lexer<InputIterator>::operator++(int) { auto tmp_token = std::move(current_token); ++(*this); return *tmp_token; } template <class InputIterator> bool Lexer<InputIterator>::operator==(const Lexer &other) const { return current_token.has_value() == other.current_token.has_value(); } template <class InputIterator> bool Lexer<InputIterator>::operator!=(const Lexer &other) const { return !(*this == other); } template <class InputIterator> std::optional<Token> Lexer<InputIterator>::next() { while (current_character != characters_end) { if (isspace(*current_character) != 0) { ++current_character; } else if (isdigit(*current_character) != 0) { return Token(TokenType::number_t, get_while_matching(isdigit)); } else if (is_operator(*current_character)) { return Token(TokenType::operator_t, get_while_matching(is_operator)); } else if (*current_character == '=') { return Token(TokenType::assignment_t, *current_character++); } else if (*current_character == '(') { return Token(TokenType::left_parenthesis_t, *current_character++); } else if (*current_character == ')') { return Token(TokenType::right_parenthesis_t, *current_character++); } else if (is_identifier(*current_character)) { auto token = get_while_matching(is_identifier); auto token_type = llvm::StringSwitch<TokenType>(token) .Case("BEGIN", TokenType::begin_t) .Case("END", TokenType::end_t) .Case("LOOP", TokenType::loop_t) .Case("BREAK", TokenType::break_t) .Case("IFN", TokenType::ifn_t) .Case("IFP", TokenType::ifp_t) .Case("IFZ", TokenType::ifz_t) .Case("ELSE", TokenType::else_t) .Case("PRINT", TokenType::print_t) .Case("READ", TokenType::read_t) .Default(TokenType::variable_t); return Token(token_type, token); } else if (*current_character == '{') { current_character = std::next(std::find(current_character, characters_end, '}')); } else { throw std::logic_error("Cannot handle the current character."); } } return {}; } template <class InputIterator> template <class TokenMatcher> std::string Lexer<InputIterator>::get_while_matching(const TokenMatcher &matcher) { std::string value; do { value += *current_character++; } while (current_character != characters_end && matcher(*current_character)); return value; } template <class InputIterator> bool Lexer<InputIterator>::is_operator(const char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; } template <class InputIterator> bool Lexer<InputIterator>::is_identifier(const char c) { return (isalnum(c) != 0) || c == '_'; } #endif
33.390071
97
0.618946
SimplyDanny
fdc5bfdbe96aa0f222ba2f7c68a1225e1bf52b25
4,835
hpp
C++
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
baykaner/ledger
f45fbd49297a419e3a90a46e9aed0cfa65602109
[ "Apache-2.0" ]
null
null
null
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
baykaner/ledger
f45fbd49297a419e3a90a46e9aed0cfa65602109
[ "Apache-2.0" ]
null
null
null
libs/ledger/include/ledger/storage_unit/storage_unit_client.hpp
baykaner/ledger
f45fbd49297a419e3a90a46e9aed0cfa65602109
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/future_timepoint.hpp" #include "core/logging.hpp" #include "core/service_ids.hpp" #include "crypto/merkle_tree.hpp" #include "ledger/shard_config.hpp" #include "ledger/storage_unit/lane_connectivity_details.hpp" #include "ledger/storage_unit/lane_identity.hpp" #include "ledger/storage_unit/lane_identity_protocol.hpp" #include "ledger/storage_unit/lane_service.hpp" #include "ledger/storage_unit/storage_unit_interface.hpp" #include "network/generics/backgrounded_work.hpp" #include "network/generics/has_worker_thread.hpp" #include "network/management/connection_register.hpp" #include "network/muddle/muddle.hpp" #include "network/muddle/rpc/client.hpp" #include "network/muddle/rpc/server.hpp" #include "network/service/service_client.hpp" #include "storage/document_store_protocol.hpp" #include "storage/object_stack.hpp" #include "storage/object_store_protocol.hpp" #include <array> #include <cassert> #include <cstdint> #include <cstring> #include <exception> #include <memory> #include <string> #include <vector> namespace fetch { namespace ledger { class StorageUnitClient final : public StorageUnitInterface { public: using MuddleEndpoint = muddle::MuddleEndpoint; using Address = MuddleEndpoint::Address; static constexpr char const *LOGGING_NAME = "StorageUnitClient"; // Construction / Destruction StorageUnitClient(MuddleEndpoint &muddle, ShardConfigs const &shards, uint32_t log2_num_lanes); StorageUnitClient(StorageUnitClient const &) = delete; StorageUnitClient(StorageUnitClient &&) = delete; ~StorageUnitClient() override = default; // Helpers uint32_t num_lanes() const; /// @name Storage Unit Interface /// @{ void AddTransaction(Transaction const &tx) override; bool GetTransaction(ConstByteArray const &digest, Transaction &tx) override; bool HasTransaction(ConstByteArray const &digest) override; void IssueCallForMissingTxs(DigestSet const &tx_set) override; TxLayouts PollRecentTx(uint32_t max_to_poll) override; Document GetOrCreate(ResourceAddress const &key) override; Document Get(ResourceAddress const &key) override; void Set(ResourceAddress const &key, StateValue const &value) override; Keys KeyDump() const override; void Reset() override; // state hash functions byte_array::ConstByteArray CurrentHash() override; byte_array::ConstByteArray LastCommitHash() override; bool RevertToHash(Hash const &hash, uint64_t index) override; byte_array::ConstByteArray Commit(uint64_t index) override; bool HashExists(Hash const &hash, uint64_t index) override; bool Lock(ShardIndex index) override; bool Unlock(ShardIndex index) override; /// @} StorageUnitClient &operator=(StorageUnitClient const &) = delete; StorageUnitClient &operator=(StorageUnitClient &&) = delete; private: using Client = muddle::rpc::Client; using ClientPtr = std::shared_ptr<Client>; using LaneIndex = LaneIdentity::lane_type; using AddressList = std::vector<MuddleEndpoint::Address>; using MerkleTree = crypto::MerkleTree; using PermanentMerkleStack = fetch::storage::ObjectStack<crypto::MerkleTree>; static constexpr char const *MERKLE_FILENAME_DOC = "merkle_stack.db"; static constexpr char const *MERKLE_FILENAME_INDEX = "merkle_stack_index.db"; Address const &LookupAddress(ShardIndex shard) const; Address const &LookupAddress(storage::ResourceID const &resource) const; bool HashInStack(Hash const &hash, uint64_t index); /// @name Client Information /// @{ AddressList const addresses_; uint32_t const log2_num_lanes_ = 0; ClientPtr rpc_client_; /// @} /// @name State Hash Support /// @{ mutable Mutex merkle_mutex_; MerkleTree current_merkle_; PermanentMerkleStack permanent_state_merkle_stack_{}; /// @} }; } // namespace ledger } // namespace fetch
36.908397
97
0.706101
baykaner
fdc6621e2f738b0a2c93f23596b3172bab14487e
1,977
hpp
C++
sprout/container/get_deep_internal.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/container/get_deep_internal.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/container/get_deep_internal.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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) =============================================================================*/ #ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP #define SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/container/get_internal.hpp> #include <sprout/container/deep_internal.hpp> #include <sprout/container/is_sub_container.hpp> #include <sprout/utility/forward.hpp> #include <sprout/type_traits/enabler_if.hpp> namespace sprout { namespace detail { template< typename Container, typename sprout::enabler_if<!sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type get_deep_internal_impl(Container&& cont) { return SPROUT_FORWARD(Container, cont); } template< typename Container, typename sprout::enabler_if<sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type get_deep_internal_impl(Container&& cont) { return sprout::detail::get_deep_internal_impl( sprout::get_internal(SPROUT_FORWARD(Container, cont)) ); } } // namespace detail // // get_deep_internal // template<typename Container> inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type get_deep_internal(Container&& cont) { return sprout::detail::get_deep_internal_impl(SPROUT_FORWARD(Container, cont)); } } // namespace sprout #endif // #ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
38.764706
112
0.70258
kariya-mitsuru
fdc6ddc3909e7f24bf93a655ebf075562f6b5a18
5,084
cpp
C++
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
code-hunger/lecture-notes
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
[ "MIT" ]
32
2016-11-24T01:40:21.000Z
2021-11-01T19:24:22.000Z
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
code-hunger/lecture-notes
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
[ "MIT" ]
6
2016-10-15T05:57:00.000Z
2021-08-13T12:29:24.000Z
samples/03_sdp/2019-20_kn/stacks/rpn.cpp
code-hunger/lecture-notes
0200c57a4c2539b4d8b7cb172c2b6e4f5c689268
[ "MIT" ]
49
2016-01-26T13:36:02.000Z
2022-03-16T10:24:41.000Z
#include <iostream> #include <stack> #include <cassert> #include <vector> #include <sstream> bool isdigit (char c) { return c >= '0' && c <= '9'; } int apply (char op, int x, int y) { switch (op) { case '+': return x+y; case '*': return x*y; default: assert (false); } return 0; } void killwhite (std::istream &in) { while (in.peek () == ' ' || in.peek() == '\n') { in.get(); } } int calcrpp (std::istream &in) { killwhite (in); std::stack <int> s; while (in.peek() != ';') { if (isdigit (in.peek())) { int arg; in >> arg; s.push (arg); } else { char op = in.get(); assert (s.size() >= 2); int larg = s.top(); s.pop(); int rarg = s.top(); s.pop(); s.push (apply(op,larg,rarg)); } killwhite (in); } assert (s.size() == 1); return s.top(); } struct Token { int type; static const int NUM = 0; static const int OPER = 1; static const int LPAR = 2; static const int RPAR = 3; int val; char op; }; int priority (char op) { switch (op) { case '*': return 10; case '+': return 5; default: assert (false); } return 0; } std::vector<Token> makerpn (std::istream &in) { std::vector<Token> result; std::stack<Token> s; killwhite (in); while (in.peek() != ';') { Token next; if (isdigit (in.peek())) { next.type = Token::NUM; in >> next.val; result.push_back (next); } else if (in.peek() == '(') { next.type = Token::LPAR; s.push (next); in.get(); } else if (in.peek() == ')') { in.get(); while (s.size() >= 1 && s.top().type != Token::LPAR) { next = s.top(); s.pop(); result.push_back (next); assert (next.type == Token::OPER); } assert (s.size () >= 1); s.pop(); } else { next.type = Token::OPER; next.op = in.get(); while (s.size()>=1 && s.top().type == Token::OPER && priority(s.top().op) > priority (next.op)) { result.push_back(s.top()); s.pop(); } s.push (next); } killwhite (in); } while (s.size () > 0) { result.push_back (s.top()); s.pop(); } return result; } std::stringstream tostream (std::vector<Token> rpn) { std::stringstream res; for (Token t : rpn) { switch (t.type) { case Token::NUM: res << t.val; break; case Token::OPER: res << t.op; break; default: assert (false); } res << " "; } return res; } int calcexprrec (std::istream &in) { killwhite (in); if (isdigit (in.peek())) { int x; in >> x; return x; } assert (in.peek() == '('); in.get(); int larg = calcexprrec (in); killwhite (in); char op = in.get(); int rarg = calcexprrec (in); killwhite (in); assert (in.get() == ')'); return apply (op,larg,rarg); } Token readToken (std::istream &in) { killwhite (in); Token t; if (isdigit (in.peek())) { t.type = Token::NUM; in >> t.val; return t; } else if (in.peek() == '(') { t.type = Token::LPAR; in.get(); return t; } else if (in.peek() == ')') { t.type = Token::RPAR; in.get(); return t; } else { t.type = Token::OPER; t.op = in.get(); return t; } } int calcexprit (std::istream &in) { std::stack <Token> s; Token next = readToken (in); s.push (next); while (s.size () > 1 || s.top().type != Token::NUM) { next = readToken (in); if (next.type == Token::RPAR) { assert (s.top().type == Token::NUM); int rarg = s.top().val; s.pop(); assert (s.top().type == Token::OPER); char op = s.top().op; s.pop(); assert (s.top().type == Token::NUM); int larg = s.top().val; s.pop(); assert (s.top().type == Token::LPAR); s.pop(); next.type = Token::NUM; next.val = apply (op,larg,rarg); s.push (next); } else { s.push (next); } } // std::cerr << "Top of stack = " << s.top().type << std::endl; assert (s.top().type == Token::NUM); return s.top().val; } int main () { //std::cout << calcrpp (std::cin); //std::vector<Token> rpn = makerpn (std::cin); //std::stringstream srpn = tostream (rpn); //std::cout << srpn.str(); //std::cout << calcexprrec (std::cin); std::cout << calcexprit (std::cin); }
20.417671
66
0.428993
code-hunger
fdcbb9e33a74a8a0b0961d1f6963d5806d5f8896
997
cpp
C++
tests/Dogecoin/TWDogeTests.cpp
taha-husain/pp-wallet-core
68862468398854cef2d194cad8498801afcc3344
[ "MIT" ]
null
null
null
tests/Dogecoin/TWDogeTests.cpp
taha-husain/pp-wallet-core
68862468398854cef2d194cad8498801afcc3344
[ "MIT" ]
null
null
null
tests/Dogecoin/TWDogeTests.cpp
taha-husain/pp-wallet-core
68862468398854cef2d194cad8498801afcc3344
[ "MIT" ]
1
2020-12-03T03:24:12.000Z
2020-12-03T03:24:12.000Z
// Copyright © 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "../interface/TWTestUtilities.h" #include <PPTrustWalletCore/TWBitcoinScript.h> #include <gtest/gtest.h> TEST(Doge, LockScripts) { auto script = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("DLSSSUS3ex7YNDACJDxMER1ZMW579Vy8Zy").get(), TWCoinTypeDogecoin)); auto scriptData = WRAPD(TWBitcoinScriptData(script.get())); assertHexEqual(scriptData, "76a914a7d191ec42aa113e28cd858cceaa7c733ba2f77788ac"); auto script2 = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("AETZJzedcmLM2rxCM6VqCGF3YEMUjA3jMw").get(), TWCoinTypeDogecoin)); auto scriptData2 = WRAPD(TWBitcoinScriptData(script2.get())); assertHexEqual(scriptData2, "a914f191149f72f235548746654f5b473c58258f7fb687"); }
45.318182
145
0.791374
taha-husain
fdcd4306f93d23ab3a6de17a15d56edffd128c4a
4,921
cpp
C++
src/bbf_fix_file.cpp
trapexit/bbf
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
[ "0BSD" ]
82
2016-12-05T22:58:48.000Z
2022-03-21T12:38:19.000Z
src/bbf_fix_file.cpp
trapexit/bbf
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
[ "0BSD" ]
7
2018-12-12T03:33:51.000Z
2020-11-30T23:14:52.000Z
src/bbf_fix_file.cpp
trapexit/bbf
c57696e74dd87e00d3ac660eb3ee9423b6f55c89
[ "0BSD" ]
5
2019-07-10T17:39:55.000Z
2021-07-17T21:47:31.000Z
/* ISC License Copyright (c) 2016, Antonio SJ Musumeci <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "blkdev.hpp" #include "captcha.hpp" #include "errors.hpp" #include "file.hpp" #include "filetoblkdev.hpp" #include "options.hpp" #include "signals.hpp" #include <iostream> #include <utility> #include <errno.h> #include <stdint.h> namespace l { static int fix_file_loop_core(BlkDev &blkdev_, char *buf_, const uint64_t buflen_, const unsigned int retries_, const uint64_t badblock_) { int rv; uint64_t attempts; if(signals::signaled_to_exit()) return -EINTR; rv = blkdev_.read(badblock_,1,buf_,buflen_); for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++) { std::cout << "Reading block " << badblock_ << " failed (attempt " << attempts << " of " << retries_ << "[" << Error::to_string(-rv) << "]: trying again" << std::endl; rv = blkdev_.read(badblock_,1,buf_,buflen_); } if(rv < 0) { std::cout << "Reading block " << badblock_ << " failed (" << attempts << " attempts) " << "[" << Error::to_string(-rv) << "]: using zeros" << std::endl; ::memset(buf_,0,buflen_); } rv = blkdev_.write(badblock_,1,buf_,buflen_); for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++) { std::cout << "Writing block " << badblock_ << " failed (attempt " << attempts << " of " << retries_ << "[" << Error::to_string(-rv) << "]: trying again" << std::endl; rv = blkdev_.write(badblock_,1,buf_,buflen_); } if(rv < 0) std::cout << "Writing block " << badblock_ << " failed (" << attempts << " attempts) " << "[" << Error::to_string(-rv) << "]" << std::endl; return 0; } static int fix_file_loop(BlkDev &blkdev_, const File::BlockVector &blockvector_, const unsigned int retries_) { int rv; char *buf; uint64_t buflen; buflen = blkdev_.logical_block_size(); buf = new char[buflen]; for(uint64_t i = 0, ei = blockvector_.size(); i != ei; i++) { uint64_t j = blockvector_[i].block; const uint64_t ej = blockvector_[i].length + j; for(; j != ej; j++) { rv = l::fix_file_loop_core(blkdev_,buf,buflen,retries_,j); if(rv < 0) break; } } delete[] buf; return rv; } static void set_blkdev_rwtype(BlkDev &blkdev, const Options::RWType rwtype) { switch(rwtype) { case Options::ATA: blkdev.set_rw_ata(); break; case Options::OS: blkdev.set_rw_os(); break; } } static AppError fix_file(const Options &opts_) { int rv; BlkDev blkdev; std::string devpath; File::BlockVector blockvector; rv = File::blocks(opts_.device,blockvector); if(rv < 0) return AppError::opening_file(-rv,opts_.device); devpath = FileToBlkDev::find(opts_.device); if(devpath.empty()) return AppError::opening_device(ENOENT,opts_.device); rv = blkdev.open_rdwr(devpath,!opts_.force); if(rv < 0) return AppError::opening_device(-rv,devpath); l::set_blkdev_rwtype(blkdev,opts_.rwtype); const std::string captcha = captcha::calculate(blkdev); if(opts_.captcha != captcha) return AppError::captcha(opts_.captcha,captcha); rv = l::fix_file_loop(blkdev,blockvector,opts_.retries); rv = blkdev.close(); if(rv < 0) return AppError::closing_device(-rv,opts_.device); return AppError::success(); } } namespace bbf { AppError fix_file(const Options &opts_) { return l::fix_file(opts_); } }
26.175532
74
0.555375
trapexit
fdce1591412dba7a60268b232e46262eb9f26acb
5,172
cpp
C++
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
1
2019-05-28T06:33:01.000Z
2019-05-28T06:33:01.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_SysInfoClass.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
// // FILE NAME: CIDMacroEng_SysInfoClass.cpp // // AUTHOR: Dean Roddey // // CREATED: 02/20/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the macro level MEng.System.Runtime.SysInfo class. // It just provides some global information of interest, and defines a // commonly used error enum. // // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // Magic RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TMEngSysInfoInfo,TMEngClassInfo) // --------------------------------------------------------------------------- // Local data // --------------------------------------------------------------------------- namespace CIDMacroEng_SysInfoClass { }; // --------------------------------------------------------------------------- // CLASS: TMEngSysInfoInfo // PREFIX: meci // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngSysInfoInfo: Constructors and Destructor // --------------------------------------------------------------------------- TMEngSysInfoInfo::TMEngSysInfoInfo(TCIDMacroEngine& meOwner) : TMEngClassInfo ( L"SysInfo" , TFacCIDMacroEng::strRuntimeClassPath , meOwner , kCIDLib::False , tCIDMacroEng::EClassExt::Final , L"MEng.Object" ) , m_c2MethId_DefCtor(kMacroEng::c2BadId) , m_c2MethId_GetCPUCount(kMacroEng::c2BadId) , m_c2MethId_GetNodeName(kMacroEng::c2BadId) { } TMEngSysInfoInfo::~TMEngSysInfoInfo() { } // --------------------------------------------------------------------------- // TMEngSysInfoInfo: Public, inherited methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngSysInfoInfo::Init(TCIDMacroEngine&) { // Add the default constructor { TMEngMethodInfo methiNew ( L"ctor1_MEng.System.Runtime.SysInfo" , tCIDMacroEng::EIntrinsics::Void , tCIDMacroEng::EVisTypes::Public , tCIDMacroEng::EMethExt::Final ); methiNew.bIsCtor(kCIDLib::True); m_c2MethId_DefCtor = c2AddMethodInfo(methiNew); } // Get the local node name { TMEngMethodInfo methiNew ( L"GetNodeName" , tCIDMacroEng::EIntrinsics::String , tCIDMacroEng::EVisTypes::Public , tCIDMacroEng::EMethExt::Final , tCIDMacroEng::EConstTypes::Const ); m_c2MethId_GetNodeName = c2AddMethodInfo(methiNew); } // Get the number of CPUs { TMEngMethodInfo methiNew ( L"GetCPUCount" , tCIDMacroEng::EIntrinsics::Card4 , tCIDMacroEng::EVisTypes::Public , tCIDMacroEng::EMethExt::Final , tCIDMacroEng::EConstTypes::Const ); m_c2MethId_GetCPUCount = c2AddMethodInfo(methiNew); } } TMEngClassVal* TMEngSysInfoInfo::pmecvMakeStorage( const TString& strName , TCIDMacroEngine& meOwner , const tCIDMacroEng::EConstTypes eConst) const { return new TMEngStdClassVal(strName, c2Id(), eConst); } // --------------------------------------------------------------------------- // TMacroEngSysInfoInfo: Protected, inherited methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TMEngSysInfoInfo::bInvokeMethod( TCIDMacroEngine& meOwner , const TMEngMethodInfo& methiTarget , TMEngClassVal& mecvInstance) { const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget); const tCIDLib::TCard2 c2MethId = methiTarget.c2Id(); if (c2MethId == m_c2MethId_DefCtor) { // Nothing to do } else if (c2MethId == m_c2MethId_GetCPUCount) { // Get the return value and set it with the indicated char TMEngCard4Val& mecvRet = meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1); mecvRet.c4Value(TSysInfo::c4CPUCount()); } else if (c2MethId == m_c2MethId_GetNodeName) { // Get the return value and set it with the indicated char TMEngStringVal& mecvRet = meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd - 1); mecvRet.strValue(TSysInfo::strIPHostName()); } else { return kCIDLib::False; } return kCIDLib::True; }
29.724138
84
0.490333
eudora-jia
fdd1f31279f6c08494f94939cbe42d4e27b68267
10,476
cpp
C++
SOURCES/sim/digi/gunsjink.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/sim/digi/gunsjink.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/sim/digi/gunsjink.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include "stdhdr.h" #include "simveh.h" #include "digi.h" #include "object.h" #include "simbase.h" #include "airframe.h" #include "team.h" #include "aircrft.h" #include "sms.h" #define INIT_GUN_VEL 4500.0f //me123 changed from 3500.0F extern float SimLibLastMajorFrameTime; void DigitalBrain::GunsJinkCheck(void) { float tgt_time=0.0F,att_time=0.0F,z=0.0F, timeDelta=0.0F; int twoSeconds=0; unsigned long lastUpdate=0; SimObjectType* obj = targetPtr; SimObjectLocalData* localData=NULL; /*-----------------------------------------------*/ /* Entry conditions- */ /* */ /* 1. Target range <= INIT_GUN_VEL feet. */ /* 2. Target time to fire < ownship time to fire */ /* 3. Predicted bullet fire <= 2 seconds. */ /*-----------------------------------------------*/ //me123 lets check is closure is resonable too before goin into jink mode if (curMode != GunsJinkMode) { if ( obj == NULL ) return; if ( obj->BaseData()->IsSim() && (((SimBaseClass*)obj->BaseData())->IsFiring() || TeamInfo[self->GetTeam()]->TStance(obj->BaseData()->GetTeam()) == War)) { localData = obj->localData; if ((localData->range > 0.0f) && (localData->range < 6000.0f))//localData->rangedot > -240.0f * FTPSEC_TO_KNOTS )//me123 don't jink if he's got a high closure, he probaly woun't shoot a low Pk shot { if (localData->range < INIT_GUN_VEL ) { /*-----------------------------------*/ /* predict time of possible gun fire */ /*-----------------------------------*/ twoSeconds = FALSE; jinkTime = -1; z = localData->range / INIT_GUN_VEL; if ( localData->azFrom > -15.0F * DTR && localData->azFrom < (15.0F * DTR))//me123 status test. changed from 2.0 to 5.0 multible places here becourse we are not always in plane when gunning { twoSeconds = TRUE; } else if (localData->azFrom > (5.0F * DTR) && localData->azFromdot < 0.0F) { if (localData->azFrom + z * localData->azFromdot < (5.0F * DTR)) twoSeconds = TRUE; } else if (localData->azFrom < (-5.0F * DTR) && localData->azFromdot > 0.0F) { if (localData->azFrom + z * localData->azFromdot > (-5.0F * DTR)) twoSeconds = TRUE; } if (twoSeconds) { twoSeconds = FALSE; if (localData->elFrom < (4.0F *DTR) && localData->elFrom > (-10.0F * DTR))//me123 status test. changed all { twoSeconds = TRUE; } // else if (localData->elFrom > (-2.0F *DTR) && localData->elFromdot < 0.0F) // { // if (localData->elFrom + z* localData->elFromdot < (-2.0F *DTR)) // twoSeconds = TRUE; // } // else if (localData->elFrom < (-13.0F * DTR) && localData->elFromdot > 0.0F) // { // if (localData->elFrom + z* localData->elFromdot > (-13.0F * DTR)) // twoSeconds = TRUE; // } /*-------------------------------------------------*/ /* estimate time to be targeted and time to attack */ /*-------------------------------------------------*/ lastUpdate = targetPtr->BaseData()->LastUpdateTime(); if (lastUpdate == vuxGameTime) timeDelta = SimLibMajorFrameTime; else timeDelta = SimLibLastMajorFrameTime; /*-----------*/ /* him -> me */ /*-----------*/ tgt_time = ((localData->ataFrom / localData->ataFromdot) * timeDelta); // if (tgt_time < 0.0F)//me123 status test, // tgt_time = 99.0F;//me123 status test, if (localData->ataFrom > -13.0f *DTR && localData->ataFrom < 13.0f *DTR) {tgt_time = 0.0f;}//me123 status test, /*-----------*/ /* me -> him */ /*-----------*/ att_time = (localData->ata / localData->atadot) * timeDelta; // if (att_time < 0.0F)//me123 status test, // att_time = 99.0F;//me123 status test, if (localData->ata > -13.0f *DTR && localData->ata < 13.0f *DTR) {att_time = 0.0f;}//me123 status test, } /*--------------*/ /* trigger jink */ /*--------------*/ if (twoSeconds && tgt_time <= att_time) { AddMode(GunsJinkMode); } } } } } // if not guns jink mode /*------------------------------------*/ /* else already in guns jink */ /* this maneuver is timed and removes */ /* itself, but we must make sure the */ /* threat is still around */ /*------------------------------------*/ } void DigitalBrain::GunsJink(void) { float aspect, roll_offset, eroll; SimObjectLocalData* gunsJinkData; SimObjectType* obj = targetList; //int randVal; float maxPull; /*------------------------------------*/ /* this maneuver is timed and removes */ /* itself, but we must make sure the */ /* threat is still around */ /*------------------------------------*/ if ( targetPtr == NULL || targetPtr->BaseData()->IsExploding() || targetPtr && targetPtr->localData->range > 4000) { // bail, no target jinkTime = -1; return; } // Cobra No need to go through all the stuff if we need to avoid the ground if(groundAvoidNeeded) return; /*-------------------*/ /* energy management */ /*-------------------*/ MachHold(cornerSpeed,self->GetKias(), FALSE);//me123 from TRUE /*--------------------*/ /* find target aspect */ /*--------------------*/ gunsJinkData = targetPtr->localData; aspect = 180.0F * DTR - gunsJinkData->ata; /*-----------------*/ /* pick roll angle */ /*-----------------*/ if (jinkTime == -1) { // Should I jettison stores? if (self->CombatClass() != MnvrClassBomber) { //Cobra we do this always self->Sms->AGJettison(); SelectGroundWeapon(); } ResetMaxRoll(); /*--------------------------------*/ /* aspect >= 60 degrees */ /* put plane of wings on attacker */ /*--------------------------------*/ if (aspect >= 90.0F * DTR)//me123 changed from 60 { /* offset required to put wings on attacker */ if (gunsJinkData->droll >= 0.0F) roll_offset = gunsJinkData->droll - 90.0F * DTR; else roll_offset = gunsJinkData->droll + 90.0F * DTR; /* generate new phi angle */ newroll = self->Roll() + roll_offset; } /*---------------------*/ /* aspect < 60 degrees */ /* roll +- 90 degrees */ /*---------------------*/ else { /* special in-plane crossing case, go the opposite direction */ if (targetPtr && ((targetPtr->BaseData()->Yaw() - self->Yaw() < 15.0F * DTR) && (targetPtr->BaseData()->Pitch() - self->Pitch() < 15.0F * DTR) && (targetPtr->BaseData()->Roll() - self->Roll() < 15.0F * DTR))) { if (gunsJinkData->droll >= 0.0F && gunsJinkData->az > 0.0F) { newroll = self->Roll() + 90.0F * DTR; } else if (gunsJinkData->droll < 0.0F && gunsJinkData->az < 0.0F) { newroll = self->Roll() - 90.0F * DTR; } else /* fall out, normal case */ { if (gunsJinkData->droll > 0.0F) newroll = self->Roll() - 70.0F * DTR; //me123 status test changed from 90 else newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90 } } /* normal jink */ else { if (gunsJinkData->droll > 0.0F) newroll = self->Roll() - 70.0F * DTR;//me123 status test changed from 90 else newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90 } /*--------------------------------------------*/ /* roll down if speed <= 60% of corner speed */ /*--------------------------------------------*/ if (self->GetKias() <= 0.8F * cornerSpeed)//me123 status test. changed from 0.6 { if (newroll >= 0.0F && newroll <= 45.0F * DTR) newroll += 30.0F * DTR;//me123 status test changed from 20 else if (newroll <= 0.0F && newroll >= -45.0F * DTR) newroll -= 30.0F * DTR;//me123 status test changed from 20 } } /*------------------------*/ /* roll angle corrections */ /*------------------------*/ if (newroll > 180.0F * DTR) newroll -= 360.0F * DTR; else if (newroll < -180.0F * DTR) newroll += 360.0F * DTR; // Clamp roll to limits if (newroll > af->MaxRoll()) newroll = af->MaxRoll(); else if (newroll < -af->MaxRoll()) newroll = -af->MaxRoll(); jinkTime = 0; } // Allow unlimited rolling if (self->CombatClass() != MnvrClassBomber) SetMaxRoll (190.0F); /*---------------------------*/ /* roll to the desired angle */ /*---------------------------*/ if (jinkTime == 0) { SetPstick (-2.0F, maxGs, AirframeClass::GCommand); /*------------*/ /* roll error */ /*------------*/ eroll = newroll - self->Roll(); /*-----------------------------*/ /* roll the shortest direction */ /*-----------------------------*/ eroll = SetRstick( eroll * RTD * 4.0F) * DTR; SetMaxRollDelta (eroll); //me123 and pull like hell maxPull = max (0.8F * af->MaxGs(), maxGs); SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand); /*-----------------------*/ /* stop rolling and pull */ /*-----------------------*/ if (fabs(eroll) < 5.0F * DTR)//me123 status test, from 5 { jinkTime = 1; SetRstick( 0.5F );//me123 status test, from 0 } } /*-----------------------*/ /* pull max gs for 2 sec */ /*-----------------------*/ if (jinkTime > 0 || groundAvoidNeeded) { maxPull = max (0.8F * af->MaxGs(), maxGs); SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand); if (jinkTime++ > SimLibMajorFrameRate*2.0F + 1.0F)//me123 status test, pull for 5sec instead of 2 { ResetMaxRoll(); jinkTime = -1; } else { // Stay in guns jink AddMode(GunsJinkMode); } } else { // Stay in guns jink AddMode(GunsJinkMode); } }
32.943396
200
0.473559
IsraelyFlightSimulator
fdd2c7bf730c3af1a54fb47ca81e2795b43c8b7a
16,978
cpp
C++
src/FileContainer.cpp
ElliotAlexander/EDSAC-FORTRAN-Compiler
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
[ "Apache-2.0" ]
null
null
null
src/FileContainer.cpp
ElliotAlexander/EDSAC-FORTRAN-Compiler
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
[ "Apache-2.0" ]
null
null
null
src/FileContainer.cpp
ElliotAlexander/EDSAC-FORTRAN-Compiler
f5a14d0f4c42fcba5eb1d277cab4b8d700eab699
[ "Apache-2.0" ]
null
null
null
#include "FileContainer.h" /** * * Class FileContainer: * * Member Variables: * std::string file_name; -> initialised in the constructor * std::vector<std::string> -> loaded from file file_name in the constructor. * * **/ // FileContainer::FileContainer(std::string file_name_in); // @param file_name_in - the name of the input file the FileContainer object represents. // FileContainer is a 1:1 relationship between an input file and it's representation in the program. // each FileContainer is a container for one specific file. // The constructor loads the file into a std::vector<std::string> stored as a member variable. FileContainer::FileContainer(std::string file_name_in) : file_name(file_name_in){ std::ifstream input(FileContainer::file_name); std::string line_buffer_temp; int line_counter_temp = 1; // Iterate through the whole file. while( std::getline( input, line_buffer_temp ) ) { // if a line is too short, remove it and mark it as a comment (where line length < MINIMUM_LINE_LENGTH) line_buffer_temp = removeShortLines(line_buffer_temp, line_counter_temp); // If a line is blank, remove it and mark it as a comment. line_buffer_temp = removeNewlines(line_buffer_temp); // Build a member variable of the complete file text. FileContainer::file_text.push_back(line_buffer_temp); // update line counter. line_counter_temp++; } if(Globals::dump_data_structures){ // enabled through a commmand line flag, dump the file to the command line if required. dumpFileText(); } } // std::vector<Segment> FileContainer::dissectSegments(){ // @return std::vector<Segment> - The built list of Segment objects contained within the file represented by the FileContainer object. // This function breaks down the program text contained in the member variable file_text into a list of Segment objects. // This function does not change class state std::vector<Segment> FileContainer::dissectSegments(){ std::vector<Segment> segment_arr; // Start outside a segment, the first line of the file willl input bool in_function_or_subroutine_block = false; // Start inside the main program block, remain there until we see a FUNCTION or SUBROUTINE statement. bool in_main_block = true; // Indicating the current type of segment we are inside, FUNCTION, SUBROUTINE or MAIN PROGRAM. SEGMENT_TYPE current_type = {}; int start_line = 0; /** * This loop iterates through each line in the file text * The loop tracks which a) type of segment it is currently in b) if it is currently in a segment c) where the current segment started * At the end of each segment (i.e. when a return or END statement is seen) the loop backtracks, builds a string vector of * all the lines in that segment (since the starting line), and then builds a segment object with this list * Once a segment object is built, it is added to segment_arr, the return value for the whole function. * This algorithm hence breaks down the file into a list of segments, and warns the user when they try to do things * they shouldn't either outside of a segment or in the wrong segment type * */ for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) { // Skip comments if(!::lineIsComment(FileContainer::file_text[i])){ // Set the program text to a local variable. Ignore the line label i.e. chars 0 -> 6 std::string useful_statement = FileContainer::file_text[i].substr(LINE_LABEL_LENGTH, FileContainer::file_text[i].length()); // If the line is an END statement. Note that there might be possible problems here with ENDVARIABLE, for example. if(useful_statement.substr(0,END_STATEMENT_LENGTH) == "END" && useful_statement.length() == END_STATEMENT_LENGTH){ // END should signify the END of the program as a whole. If we're inside a segment, the prgorammer needs to RETURN first. // This only applies to FUNCTION and SUBROUTINE blocks, as the MAIN program can exit without a return. if(in_function_or_subroutine_block){ Logging::logErrorMessage( "END statement found inside a segment block. Are you missing a return? [" + std::to_string(i) + "]."); } else if(in_main_block){ // Leave the main block in_main_block = false; // Begin building a list of thee lines inside that segment. std::vector<std::string> segment_text; // For each line in the segment for(int x = start_line; x < ( i+1 ); x++){ segment_text.push_back(FileContainer::file_text.at(x)); } Logging::logMessage("+" + ::getEnumString(SEGMENT_TYPE::PROGRAM) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]"); // Build a segment with our list of strings, add it to the overarching data structure. segment_arr.push_back(Segment(SEGMENT_TYPE::PROGRAM, start_line, i, segment_text)); } else { Logging::logWarnMessage("END detected outside of Main Program Block[" + std::to_string(i) + "]"); // THis should only catch if the program starts with END. } } else if(useful_statement.substr(0, 6) == "RETURN") { // If we're not in a function or subroutine block, we can't call return. Throw the user an error if they try this. if(in_function_or_subroutine_block){ // Build an array of the program lines in this segment std::vector<std::string> segment_text; // iterate through the segment for(int x = start_line; x < ( i+1 ); x++){ segment_text.push_back(FileContainer::file_text.at(x)); } Logging::logMessage("+" + ::getEnumString(current_type) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]{" + ::stripWhitespaceString(segment_text.at(0)) + "}."); // Construct a segment object, add it back to our return array. This segment is now finished with. segment_arr.push_back(Segment(current_type, start_line, i, segment_text)); // We are no longer in a function or subroutine block, the user has just exited this by calling return. in_function_or_subroutine_block = false; start_line = i+1; current_type = {}; } else { // if we're in the main program block - the user should not be calling return. Logging::logWarnMessage("RETURN detected outside of Subroutine Block [start=" + std::to_string(start_line + 1) + ", end=" + std::to_string(i+1) + "]."); } } else if(useful_statement.substr(0, 10) == "SUBROUTINE"){ // Nested subrutines / functions aren't allowed - so we should never see this statement inside another function or subroutine. if(!in_function_or_subroutine_block){ // Set current type current_type = SEGMENT_TYPE::SUBROUTINE; // Set start line - once we see a RETURN statement, we'll iterate from this line down and build the segment. start_line = i; in_function_or_subroutine_block = true; } else { Logging::logWarnMessage("SUBROUTINE Block detected inside another segment block [start=" + std::to_string(start_line+1) + ", end=" + std::to_string(i+1) + "]."); } } else if(useful_statement.substr(0, 8) == "FUNCTION"){ // Nested subroutines / functions aren't allowed - we should never see this statemenet when inside another function or subroutine if(!in_function_or_subroutine_block){ // Set current segmetn type current_type = SEGMENT_TYPE::FUNCTION; // Set start line - we'll iterate from this to the end of the function once we see it start_line = i; in_function_or_subroutine_block = true; } else { Logging::logWarnMessage("FUNCTION Block detected inside another segment block [start=" + std::to_string(start_line+1)+ ", end=" + std::to_string(i+1) + "]."); } // If we're not in the main block, and see a statement that isn't already specified - enter the main block! } else if(!in_main_block) { in_main_block = true; current_type = SEGMENT_TYPE::PROGRAM; Logging::logInfoMessage("Entered main program at line " + std::to_string(i + 1)); } } } // If we find a segment with no statements in it - warn the user. // This also catches non-terminated segments - i.e. a Main Program segment without an END. if(segment_arr.size() == 0){ Logging::logErrorMessage("Warning - failed to load a fail program block from file " + file_name); Logging::logErrorMessage("Did you forget to include an END Statement?"); } Logging::logNewLine(); // Returns std::vector<Segment> -> built inside above for loop. return segment_arr; } // void FileContainer::dumpFileText() // // // This function takes and returns no arguments // the purpose of this function is to dump + format the file text to the command line. // This is activated upon a user enabled command line flag. // The file text is loaded and constructed in the constructor. void FileContainer::dumpFileText(){ Logging::logMessage("Begin File Dump(Name=" + file_name + "):\n"); // Pretty printing for (std::vector<std::string>::const_iterator i = FileContainer::file_text.begin(); i != FileContainer::file_text.end(); ++i) // Logging::logMessage(*i + ' '); // For each - print that line with no formmatting. Logging::logMessage("\nEnd File Dump\n"); } // bool FileContainer::expandContinuations() // // @return bool -> indicates success / failure. // @member file_text // // This function modifies class state // This function iterates through the member variable file_text, removing continuations and appending them into a single line. // The continuation lines removed as replaced by comments. // This modification is done *in place* inside FileContainer::file_text. bool FileContainer::expandContinuations(){ int continuation_count = CONTINUATION_COUNT_STARTING; // Iterate through file text for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) { // Ignore comments in the file text - they cannot be continuations. if(!::lineIsComment(FileContainer::file_text[i])){ // FAIL - if over 20 consecutive continuations have been seen. if(continuation_count == 20) { // Exit with an error - return this to the calling class. Logging::logErrorMessage("Over 20 Continuations detected! Aborting. Line[" + std::to_string(i-19) + "]{'" + FileContainer::file_text[i-continuation_count] + "'}."); return false; } else if( ( FileContainer::file_text[i].at(CONTINUATION_INDICATION_BIT) != ' ') && (i != 0)) { // Continuations cannot be line labels. Warn the user and abort if it is. if( FileContainer::file_text[i].substr(0,4).find_first_not_of(' ') != std::string::npos){ Logging::logErrorMessage("Line {'" + FileContainer::file_text[i] + "'}[" + std::to_string(i+1) + "] is marked as a continuation, but contains a label. Aborting."); return false; // Exit to the calling class. } else { // Make a copy of the line we're modifying - in case we need to print it later. std::string line_text_backup = FileContainer::file_text[i]; // This MUST be empty - so it can be removed. This includes deleting the continuation character. FileContainer::file_text[i].erase(0,6); // Check that the rest of the line is not zero. if(FileContainer::file_text[i].length() == 0){ Logging::logErrorMessage("Empty continuation - Continuation labelled lines must contained at least one character."); // Print an error - note use case of previous backup. ::printErrorLocation(7, line_text_backup); } else { // Append continuation to prervious non-continuation line, forming one longer line. FileContainer::file_text[i-continuation_count] += FileContainer::file_text[i]; // Mark the line IN PLACE as a blank comment FileContainer::file_text[i] = std::string("C"); // Keep track of the number of continuations we've seen. continuation_count += 1; } } } else { // If the line is not a continuation - reset the continuation count. continuation_count = 1; } } } return true; } // std::string FileContainer::removeNewlines(std::string line) // // @param an input line - a single line input which will have it's newline characters removed. // @return The modified input line, with all CR LF characters removed // //This function acts as a utility class - it has no impact on class state nor does it use any member variables. // std::string FileContainer::removeNewlines(std::string line){ std::string::size_type pos = 0; // iterate from position zero while ( ( pos = line.find ("\r",pos) ) != std::string::npos ) // Find all \r characters, remove them. { line.erase ( pos, 2 ); } pos = 0; // Repeat this process for \r\n while ( ( pos = line.find ("\r\n",pos) ) != std::string::npos ) // { line.erase ( pos, 2 ); } return line; // Return the modified line. } // std::string FileContainer::removeShortLines(std::string line, int line_counter) // // @param std::string line - the input line to check // @param int line_counter - The line number - used for error messages. // // This function takes an input line, check's it's length and informs the user if it's too short // If the line is of a proper length, it's returned to the calling class intact. // If the line is too shorrt, it's marked as a COMMENT and returned to the calling class alongside an error message to the user. std::string FileContainer::removeShortLines(std::string line, int line_counter){ // If line length warnings are enabled, warn the user on lines < 5 chars long. if((line.length() < MINIMUM_LINE_LENGTH) && !(::lineIsComment(line))) { Logging::logWarnMessage("Line { " + line + " }[" + std::to_string(line_counter) + "] has an unusually short length. It will be marked as a comment and ignored."); line.insert(0, COMMENT_STRING); } return line; }
61.292419
207
0.570503
ElliotAlexander
fdd493d32f76a7ed6b8fa178d9fcc64a0da46888
2,889
cpp
C++
stacks-and-queues/queue-implementation-using-stacks.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
1
2019-12-29T17:47:53.000Z
2019-12-29T17:47:53.000Z
stacks-and-queues/queue-implementation-using-stacks.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
null
null
null
stacks-and-queues/queue-implementation-using-stacks.cpp
kanishkdudeja/cracking-the-coding-interview-solutions
b6b495eb838e3739fd09aaf1ea5a5a5eb15923d0
[ "MIT" ]
null
null
null
/* Implement a Queue (FIFO) using 2 Stacks (LIFO) Method 1 (By making enQueue operation costly): This method makes sure that oldest entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used. enQueue(q, x) 1) While stack1 is not empty, push everything from satck1 to stack2. 2) Push x to stack1 (assuming size of stacks is unlimited). 3) Push everything back to stack1. dnQueue(q) 1) If stack1 is empty then error 2) Pop an item from stack1 and return it Method 2 (By making deQueue operation costly): In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned. enQueue(q, x) 1) Push x to stack1 (assuming size of stacks is unlimited). deQueue(q) 1) If both stacks are empty then error. 2) If stack2 is empty While stack1 is not empty, push everything from stack1 to stack2. 3) Pop the element from stack2 and return it. Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once and moves elements only if stack2 empty. Space Complexity = O(n) where n is the number of elements in the stack Time Complexuity = O(n) where n is the number of elements in the stack */ #include <iostream> using namespace std; struct Node { int data; Node* next; }; class Stack { Node* head; public: Stack() { head = NULL; } Node* getNewNode(int data) { Node* newNode = new Node(); newNode->data = data; newNode->next = NULL; return newNode; } void push(int data) { if(head == NULL) { head = getNewNode(data); } else { Node* newNode = getNewNode(data); newNode->next = head; head = newNode; } } int pop() { if(head == NULL) { return -1; } else { int data = head->data; if(head->next == NULL) { free(head); head = NULL; } else { Node* tmp; tmp = head; head = head->next; free(tmp); } return data; } } bool isEmpty() { if(head == NULL) { return true; } else { return false; } } int getElementAtTop() { if(head == NULL) { return -1; } else { return head->data; } } }; class Queue { Stack s1; Stack s2; public: Queue() { s1 = Stack(); s2 = Stack(); } void enqueue(int data) { s1.push(data); } int dequeue() { if(s2.isEmpty()) { while(!(s1.isEmpty())) { s2.push(s1.pop()); } } return s2.pop(); } bool isEmpty() { return s1.isEmpty() && s2.isEmpty(); } }; int main() { Queue q = Queue(); q.enqueue(1); q.enqueue(2); q.enqueue(3); q.enqueue(4); cout<<q.dequeue(); cout<<q.dequeue(); cout<<q.dequeue(); cout<<q.dequeue(); }
17.833333
101
0.642437
kanishkdudeja
fdd4964cc6e19703f63f2854dec0de25a2a2d478
989
cpp
C++
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
cqtd/custom-il2cpp-build-pipeline-example
9ec4973d98ddfcefee72b01225a3b7613312096b
[ "MIT" ]
1
2022-03-28T07:59:17.000Z
2022-03-28T07:59:17.000Z
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
cqtd/custom-il2cpp-build-pipeline-example
9ec4973d98ddfcefee72b01225a3b7613312096b
[ "MIT" ]
null
null
null
Customized-Build/il2cpp/Il2CppOutputProject/IL2CPP/libil2cpp/vm-utils/NativeDelegateMethodCache.cpp
cqtd/custom-il2cpp-build-pipeline-example
9ec4973d98ddfcefee72b01225a3b7613312096b
[ "MIT" ]
2
2022-03-24T19:58:31.000Z
2022-03-24T22:55:43.000Z
#include "il2cpp-config.h" #if !RUNTIME_TINY #include "NativeDelegateMethodCache.h" #include "os/Mutex.h" namespace il2cpp { namespace utils { baselib::ReentrantLock NativeDelegateMethodCache::m_CacheMutex; NativeDelegateMap NativeDelegateMethodCache::m_NativeDelegateMethods; const VmMethod* NativeDelegateMethodCache::GetNativeDelegate(Il2CppMethodPointer nativeFunctionPointer) { os::FastAutoLock lock(&m_CacheMutex); NativeDelegateMap::iterator i = m_NativeDelegateMethods.find(nativeFunctionPointer); if (i == m_NativeDelegateMethods.end()) return NULL; return i->second; } void NativeDelegateMethodCache::AddNativeDelegate(Il2CppMethodPointer nativeFunctionPointer, const VmMethod* managedMethodInfo) { os::FastAutoLock lock(&m_CacheMutex); m_NativeDelegateMethods.insert(std::make_pair(nativeFunctionPointer, managedMethodInfo)); } } // namespace utils } // namespace il2cpp #endif
28.257143
131
0.751264
cqtd
fdd6494a5c9ea4e7546efa4dd559c5d98be9614f
2,192
cc
C++
day05/ex05/Form.cc
BimManager/cpp_piscine
170cdb37a057bff5a5d1299d51a6dcfef469bfad
[ "MIT" ]
null
null
null
day05/ex05/Form.cc
BimManager/cpp_piscine
170cdb37a057bff5a5d1299d51a6dcfef469bfad
[ "MIT" ]
null
null
null
day05/ex05/Form.cc
BimManager/cpp_piscine
170cdb37a057bff5a5d1299d51a6dcfef469bfad
[ "MIT" ]
null
null
null
// Copyright 2020 kkozlov #include <string> #include <iostream> #include "Form.h" Form::Form(std::string const &name, unsigned minGradeToSign, unsigned minGradeToExecute, std::string const &target) throw() : name_(name) , minGradeToSign_(minGradeToSign), minGradeToExecute_(minGradeToExecute), target_(target) { if (minGradeToSign > Bureaucrat::MinGrade() || minGradeToExecute > Bureaucrat::MinGrade() ) throw GradeTooLowException(); if (minGradeToSign < Bureaucrat::MaxGrade() || minGradeToExecute < Bureaucrat::MaxGrade()) throw GradeTooHighException(); } Form::Form(Form const &other) : name_(other.Name()), minGradeToSign_(other.MinGradeToSign()), minGradeToExecute_(other.MinGradeToExecute()) {} Form::~Form(void) {} Form &Form::operator=(Form const &rhs) { if (&rhs != this) { isSigned_ = rhs.IsSigned(); } return *this; } std::string const &Form::Name(void) const { return name_; } unsigned Form::MinGradeToSign(void) const { return minGradeToSign_; } unsigned Form::MinGradeToExecute(void) const { return minGradeToExecute_; } bool Form::IsSigned(void) const { return isSigned_; } std::string const &Form::Target(void) const { return target_; } void Form::BeSigned(Bureaucrat const &bureaucrat) throw() { if (bureaucrat.Grade() > minGradeToSign_) throw GradeTooLowException(); isSigned_ = true; } void Form::Execute(Bureaucrat const &bureaucrat) throw() { if (bureaucrat.Grade() > minGradeToExecute_) throw GradeTooLowException(); if (!isSigned_) { std::cout << name_ << " is not signed." << std::endl; } else { this->Action(); } } char const *Form::GradeTooLowException::what(void) const throw() { return "The grade too low exception\n"; } char const *Form::GradeTooHighException::what(void) const throw() { return "The maximum grade is 150\n"; } std::ostream &operator<<(std::ostream &os, Form const &in) { os << in.Name() << "\nMinimum grade to sign it: " << in.MinGradeToSign() << "\nMinimum grade to execute it: " << in.MinGradeToExecute() << "\nIs signed: " << (in.IsSigned() ? "yes" : "no") << std::endl; return os; }
25.788235
74
0.671533
BimManager
fdda4badbd4738a5852cf2ad0007285c82b92690
17,015
cc
C++
programs/mctimings/mctimings.cc
rualso/kv_engine
17680c38a77d3a67fda55f763cc2631f924ed42d
[ "BSD-3-Clause" ]
null
null
null
programs/mctimings/mctimings.cc
rualso/kv_engine
17680c38a77d3a67fda55f763cc2631f924ed42d
[ "BSD-3-Clause" ]
null
null
null
programs/mctimings/mctimings.cc
rualso/kv_engine
17680c38a77d3a67fda55f763cc2631f924ed42d
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "programs/hostname_utils.h" #include "programs/getpass.h" #include <getopt.h> #include <memcached/protocol_binary.h> #include <nlohmann/json.hpp> #include <platform/string_hex.h> #include <protocol/connection/client_connection.h> #include <protocol/connection/client_mcbp_commands.h> #include <utilities/json_utilities.h> #include <utilities/terminate_handler.h> #include <inttypes.h> #include <strings.h> #include <array> #include <cstdlib> #include <gsl/gsl> #include <iostream> #include <stdexcept> #define JSON_DUMP_INDENT_SIZE 4 class Timings { public: explicit Timings(const nlohmann::json& json) { initialize(json); } uint64_t getTotal() const { return total; } void dumpHistogram(const std::string& opcode) { if (data.is_null()) { return; } std::cout << "The following data is collected for \"" << opcode << "\"" << std::endl; auto dataArray = data.get<std::vector<std::vector<nlohmann::json>>>(); for (auto item : dataArray) { auto count = item[1].get<uint64_t>(); if (count > maxCount) { maxCount = count; } } using namespace std::chrono; // loop though all the buckets in the json object and print them // to std out uint64_t lastBuckLow = bucketsLow; for (auto bucket : dataArray) { // Get the current bucket's highest value it would track counts for auto buckHigh = bucket[0].get<uint64_t>(); // Get the counts for this bucket auto count = bucket[1].get<uint64_t>(); // Get the percentile of counts that are <= buckHigh auto percentile = bucket[2].get<double>(); if (lastBuckLow != buckHigh) { // Cast the high bucket width to us, ms and seconds so we // can check which units we should be using for this bucket auto buckHighUs = microseconds(buckHigh); auto buckHighMs = duration_cast<milliseconds>(buckHighUs); auto buckHighS = duration_cast<seconds>(buckHighUs); // If the bucket width values are in the order of tens of // seconds or milli seconds then print them as seconds or milli // seconds respectively. Otherwise print them as micro seconds // We're using tens of unit thresh holds so that each bucket // has 2 sig fig of differentiation in their width, so we dont // have buckets that are [1 - 1]s 100 (90.000%) if (buckHighS.count() > 10) { auto low = duration_cast<seconds>(microseconds(lastBuckLow)); dump("s", low.count(), buckHighS.count(), count, percentile); } else if (buckHighMs.count() > 10) { auto low = duration_cast<milliseconds>( microseconds(lastBuckLow)); dump("ms", low.count(), buckHighMs.count(), count, percentile); } else { dump("us", lastBuckLow, buckHigh, count, percentile); } } // Set the low bucket value to this buckets high width value. lastBuckLow = buckHigh; } std::cout << "Total: " << total << " operations" << std::endl; } private: void initialize(const nlohmann::json& root) { if (root.find("error") != root.end()) { // The server responded with an error.. send that to the user throw std::runtime_error(root["error"].get<std::string>()); } if (root.find("data") != root.end()) { total = cb::jsonGet<uint64_t>(root, "total"); data = cb::jsonGet<nlohmann::json>(root, "data"); bucketsLow = cb::jsonGet<uint64_t>(root, "bucketsLow"); } } void dump(const char* timeunit, int64_t low, int64_t high, int64_t count, double percentile) { char buffer[1024]; int offset = sprintf( buffer, "[%5" PRId64 " - %5" PRId64 "]%s", low, high, timeunit); offset += sprintf(buffer + offset, " (%6.4lf%%)\t", percentile); // Determine how wide the max value would be, and pad all counts // to that width. int max_width = snprintf(buffer, 0, "%" PRIu64, maxCount); offset += sprintf(buffer + offset, " %*" PRId64, max_width, count); double factionOfHashes = (count / static_cast<double>(maxCount)); int num = static_cast<int>(44.0 * factionOfHashes); offset += sprintf(buffer + offset, " | "); for (int ii = 0; ii < 44 && ii < num; ++ii) { offset += sprintf(buffer + offset, "#"); } std::cout << buffer << std::endl; } /** * The highest value of all the samples (used to figure out the width * used for each sample in the printout) */ uint64_t maxCount = 0; /** * Json object to store the data returned by memcached */ nlohmann::json data; /** * The starting point of the lowest buckets width. * E.g. if buckets were [10 - 20][20 - 30] it would be 10. * Used to help reduce the amount the amount of json sent to * mctimings */ uint64_t bucketsLow = 0; /** * Total number of counts recorded in the histogram */ uint64_t total = 0; }; std::string opcode2string(cb::mcbp::ClientOpcode opcode) { try { return to_string(opcode); } catch (const std::exception&) { return cb::to_hex(uint8_t(opcode)); } } static void request_cmd_timings(MemcachedConnection& connection, const std::string& bucket, cb::mcbp::ClientOpcode opcode, bool verbose, bool skip, bool json) { BinprotGetCmdTimerCommand cmd; cmd.setBucket(bucket); cmd.setOpcode(opcode); connection.sendCommand(cmd); BinprotGetCmdTimerResponse resp; connection.recvResponse(resp); if (!resp.isSuccess()) { switch (resp.getStatus()) { case cb::mcbp::Status::KeyEnoent: std::cerr << "Cannot find bucket: " << bucket << std::endl; break; case cb::mcbp::Status::Eaccess: if (bucket == "/all/") { std::cerr << "Not authorized to access aggregated timings data." << std::endl << "Try specifying a bucket by using -b bucketname" << std::endl; } else { std::cerr << "Not authorized to access timings data" << std::endl; } break; default: std::cerr << "Command failed: " << to_string(resp.getStatus()) << std::endl; } exit(EXIT_FAILURE); } try { auto command = opcode2string(opcode); if (json) { auto timings = resp.getTimings(); if (timings == nullptr) { if (!skip) { std::cerr << "The server doesn't have information about \"" << command << "\"" << std::endl; } } else { timings["command"] = command; std::cout << timings.dump(JSON_DUMP_INDENT_SIZE) << std::endl; } } else { Timings timings(resp.getTimings()); if (timings.getTotal() == 0) { if (skip == 0) { std::cout << "The server doesn't have information about \"" << command << "\"" << std::endl; } } else { if (verbose) { timings.dumpHistogram(command); } else { std::cout << command << " " << timings.getTotal() << " operations" << std::endl; } } } } catch (const std::exception& e) { std::cerr << "Fatal error: " << e.what() << std::endl; exit(EXIT_FAILURE); } } static void request_stat_timings(MemcachedConnection& connection, const std::string& key, bool verbose, bool json_output) { std::map<std::string, std::string> map; try { map = connection.statsMap(key); } catch (const ConnectionError& ex) { if (ex.isNotFound()) { std::cerr << "Cannot find statistic: " << key << std::endl; } else if (ex.isAccessDenied()) { std::cerr << "Not authorized to access timings data" << std::endl; } else { std::cerr << "Fatal error: " << ex.what() << std::endl; } exit(EXIT_FAILURE); } // The return value from stats injects the result in a k-v pair, but // these responses (i.e. subdoc_execute) don't include a key, // so the statsMap adds them into the map with a counter to make sure // that you can fetch all of them. We only expect a single entry, which // would be named "0" auto iter = map.find("0"); if (iter == map.end()) { std::cerr << "Failed to fetch statistics for \"" << key << "\"" << std::endl; exit(EXIT_FAILURE); } // And the value for the item should be valid JSON nlohmann::json json = nlohmann::json::parse(iter->second); if (json.is_null()) { std::cerr << "Failed to fetch statistics for \"" << key << "\". Not json" << std::endl; exit(EXIT_FAILURE); } try { if (json_output) { json["command"] = key; std::cout << json.dump(JSON_DUMP_INDENT_SIZE) << std::endl; } else { Timings timings(json); if (verbose) { timings.dumpHistogram(key); } else { std::cout << key << " " << timings.getTotal() << " operations" << std::endl; } } } catch (const std::exception& e) { std::cerr << "Fatal error: " << e.what() << std::endl; exit(EXIT_FAILURE); } } void usage() { std::cerr << "Usage mctimings [options] [opcode / statname]\n" << R"(Options: -h or --host hostname[:port] The host (with an optional port) to connect to -p or --port port The port number to connect to -b or --bucket bucketname The name of the bucket to operate on -u or --user username The name of the user to authenticate as -P or --password password The passord to use for authentication (use '-' to read from standard input) -s or --ssl Connect to the server over SSL -4 or --ipv4 Connect over IPv4 -6 or --ipv6 Connect over IPv6 -v or --verbose Use verbose output -S Read password from standard input -j or --json[=pretty] Print JSON instead of histograms --help This help text )" << std::endl << std::endl << "Example:" << std::endl << " mctimings --user operator --bucket /all/ --password - " "--verbose GET SET" << std::endl; } int main(int argc, char** argv) { // Make sure that we dump callstacks on the console install_backtrace_terminate_handler(); int cmd; std::string port{"11210"}; std::string host{"localhost"}; std::string user{}; std::string password{}; std::string bucket{"/all/"}; sa_family_t family = AF_UNSPEC; bool verbose = false; bool secure = false; bool json = false; /* Initialize the socket subsystem */ cb_initialize_sockets(); struct option long_options[] = { {"ipv4", no_argument, nullptr, '4'}, {"ipv6", no_argument, nullptr, '6'}, {"host", required_argument, nullptr, 'h'}, {"port", required_argument, nullptr, 'p'}, {"bucket", required_argument, nullptr, 'b'}, {"password", required_argument, nullptr, 'P'}, {"user", required_argument, nullptr, 'u'}, {"ssl", no_argument, nullptr, 's'}, {"verbose", no_argument, nullptr, 'v'}, {"json", optional_argument, nullptr, 'j'}, {"help", no_argument, nullptr, 0}, {nullptr, 0, nullptr, 0}}; while ((cmd = getopt_long( argc, argv, "46h:p:u:b:P:sSvj", long_options, nullptr)) != EOF) { switch (cmd) { case '6': family = AF_INET6; break; case '4': family = AF_INET; break; case 'h': host.assign(optarg); break; case 'p': port.assign(optarg); break; case 'S': password.assign("-"); break; case 'b': bucket.assign(optarg); break; case 'u': user.assign(optarg); break; case 'P': password.assign(optarg); break; case 's': secure = true; break; case 'v': verbose = true; break; case 'j': json = true; if (optarg && strcasecmp(optarg, "pretty") == 0) { verbose = true; } break; default: usage(); return cmd == 0 ? EXIT_SUCCESS : EXIT_FAILURE; } } if (password == "-") { password.assign(getpass()); } else if (password.empty()) { const char* env_password = std::getenv("CB_PASSWORD"); if (env_password) { password = env_password; } } try { in_port_t in_port; sa_family_t fam; std::tie(host, in_port, fam) = cb::inet::parse_hostname(host, port); if (family == AF_UNSPEC) { // The user may have used -4 or -6 family = fam; } MemcachedConnection connection(host, in_port, family, secure); connection.connect(); // MEMCACHED_VERSION contains the git sha connection.setAgentName("mctimings " MEMCACHED_VERSION); connection.setFeatures({cb::mcbp::Feature::XERROR}); if (!user.empty()) { connection.authenticate(user, password, connection.getSaslMechanisms()); } if (!bucket.empty() && bucket != "/all/") { connection.selectBucket(bucket); } if (optind == argc) { for (int ii = 0; ii < 256; ++ii) { request_cmd_timings(connection, bucket, cb::mcbp::ClientOpcode(ii), verbose, true, json); } } else { for (; optind < argc; ++optind) { try { const auto opcode = to_opcode(argv[optind]); request_cmd_timings( connection, bucket, opcode, verbose, false, json); } catch (const std::invalid_argument&) { // Not a command timing, try as statistic timing. request_stat_timings( connection, argv[optind], verbose, json); } } } } catch (const ConnectionError& ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
34.866803
80
0.505848
rualso
fddcc50a16eccb727b556de2749bbb3f4f47376b
5,536
cc
C++
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
249
2015-01-15T16:50:53.000Z
2022-03-24T13:23:34.000Z
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
2,917
2015-01-12T16:17:49.000Z
2022-03-31T11:57:47.000Z
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/hmi/bc_get_app_properties_request.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
306
2015-01-12T09:23:20.000Z
2022-01-28T18:06:30.000Z
/* Copyright (c) 2020, Ford Motor Company, Livio All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the the copyright holders nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sdl_rpc_plugin/commands/hmi/bc_get_app_properties_request.h" #include "application_manager/policies/policy_handler_interface.h" #include "application_manager/rpc_service.h" #include "interfaces/MOBILE_API.h" namespace sdl_rpc_plugin { using namespace application_manager; namespace commands { SDL_CREATE_LOG_VARIABLE("Commands") BCGetAppPropertiesRequest::BCGetAppPropertiesRequest( const application_manager::commands::MessageSharedPtr& message, ApplicationManager& application_manager, app_mngr::rpc_service::RPCService& rpc_service, app_mngr::HMICapabilities& hmi_capabilities, policy::PolicyHandlerInterface& policy_handler) : RequestFromHMI(message, application_manager, rpc_service, hmi_capabilities, policy_handler) {} void BCGetAppPropertiesRequest::FillAppProperties( const std::string& policy_app_id, smart_objects::SmartObject& out_properties) const { SDL_LOG_AUTO_TRACE(); policy::AppProperties app_properties; const bool result = policy_handler_.GetAppProperties(policy_app_id, app_properties); if (!result) { SDL_LOG_DEBUG( "Failed to get app parameters for policy_app_id: " << policy_app_id); return; } out_properties[strings::policy_app_id] = policy_app_id; out_properties[strings::enabled] = app_properties.enabled; policy::StringArray nicknames; policy::StringArray app_hmi_types; policy_handler_.GetInitialAppData(policy_app_id, &nicknames, &app_hmi_types); smart_objects::SmartObject nicknames_array(smart_objects::SmartType_Array); size_t i = 0; for (const auto& nickname : nicknames) { nicknames_array[i++] = nickname; } out_properties[strings::nicknames] = nicknames_array; if (!app_properties.auth_token.empty()) { out_properties[strings::auth_token] = app_properties.auth_token; } if (!app_properties.transport_type.empty()) { out_properties[strings::transport_type] = app_properties.transport_type; } if (!app_properties.hybrid_app_preference.empty()) { out_properties[strings::hybrid_app_preference] = app_properties.hybrid_app_preference; } if (!app_properties.endpoint.empty()) { out_properties[strings::endpoint] = app_properties.endpoint; } } void BCGetAppPropertiesRequest::Run() { SDL_LOG_AUTO_TRACE(); const auto& msg_params = (*message_)[strings::msg_params]; smart_objects::SmartObject response_params(smart_objects::SmartType_Map); if (msg_params.keyExists(strings::policy_app_id)) { const auto policy_app_id = msg_params[strings::policy_app_id].asString(); smart_objects::SmartObject properties(smart_objects::SmartType_Map); FillAppProperties(policy_app_id, properties); if (!properties.empty()) { response_params[strings::properties][0] = properties; } } else { SDL_LOG_DEBUG( "policyAppID was absent in request, all apps properties " "will be returned."); const auto app_ids = policy_handler_.GetApplicationPolicyIDs(); int i = 0; for (auto& app_id : app_ids) { smart_objects::SmartObject properties(smart_objects::SmartType_Map); FillAppProperties(app_id, properties); response_params[strings::properties][i++] = properties; } } if (response_params[strings::properties].empty()) { SendErrorResponse( (*message_)[strings::params][strings::correlation_id].asUInt(), hmi_apis::FunctionID::BasicCommunication_GetAppProperties, hmi_apis::Common_Result::DATA_NOT_AVAILABLE, "Requested data not available", application_manager::commands::Command::SOURCE_SDL_TO_HMI); return; } SendResponse(true, (*message_)[strings::params][strings::correlation_id].asUInt(), hmi_apis::FunctionID::BasicCommunication_GetAppProperties, hmi_apis::Common_Result::SUCCESS, &response_params); } } // namespace commands } // namespace sdl_rpc_plugin
37.917808
79
0.748736
Sohei-Suzuki-Nexty
fddd0fa97b30ca9e0f8cb35a3252b3458570fc21
3,368
cpp
C++
common/Log.cpp
MaynardMiner/energiminer
25fabd8293de254e62b6d5117a8c077c120124ec
[ "MIT" ]
null
null
null
common/Log.cpp
MaynardMiner/energiminer
25fabd8293de254e62b6d5117a8c077c120124ec
[ "MIT" ]
null
null
null
common/Log.cpp
MaynardMiner/energiminer
25fabd8293de254e62b6d5117a8c077c120124ec
[ "MIT" ]
null
null
null
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Log.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Log.h" #include "common.h" #include <iomanip> #include <iostream> #include <mutex> #include <thread> #ifdef __APPLE__ #include <pthread.h> #endif using namespace std; using namespace energi; //⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙ // Logging int g_logVerbosity = 5; bool g_logNoColor = false; bool g_logSyslog = false; const char* LogChannel::name() { return EthGray ".."; } const char* WarnChannel::name() { return EthRed " X"; } const char* NoteChannel::name() { return EthBlue " i"; } LogOutputStreamBase::LogOutputStreamBase(char const* _id, unsigned _v) : m_verbosity(_v) { static std::locale logLocl = std::locale(""); if ((int)_v <= g_logVerbosity) { m_sstr.imbue(logLocl); if (g_logSyslog) m_sstr << std::left << std::setw(8) << getThreadName() << " " EthReset; else { time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buf[24]; if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0) buf[0] = '\0'; // empty if case strftime fails m_sstr << _id << " " EthViolet << buf << " " EthBlue << std::left << std::setw(8) << getThreadName() << " " EthReset; } } } /// Associate a name with each thread for nice logging. struct ThreadLocalLogName { ThreadLocalLogName(char const* _name) { name = _name; } thread_local static char const* name; }; thread_local char const* ThreadLocalLogName::name; ThreadLocalLogName g_logThreadName("main"); string energi::getThreadName() { #if defined(__linux__) || defined(__APPLE__) char buffer[128]; pthread_getname_np(pthread_self(), buffer, 127); buffer[127] = 0; return buffer; #else return ThreadLocalLogName::name ? ThreadLocalLogName::name : "<unknown>"; #endif } void energi::setThreadName(char const* _n) { #if defined(__linux__) pthread_setname_np(pthread_self(), _n); #elif defined(__APPLE__) pthread_setname_np(_n); #else ThreadLocalLogName::name = _n; #endif } void energi::simpleDebugOut(std::string const& _s) { try { if (!g_logNoColor) { std::cerr << _s + '\n'; return; } bool skip = false; std::stringstream ss; for (auto it : _s) { if (!skip && it == '\x1b') skip = true; else if (skip && it == 'm') skip = false; else if (!skip) ss << it; } ss << '\n'; std::cerr << ss.str(); } catch (...) { return; } }
25.134328
100
0.610154
MaynardMiner
fde0d375f28b846216645d07210a2389a7a18f58
9,665
cpp
C++
src/condor_utils/filesystem_remap.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
1
2017-02-13T01:25:34.000Z
2017-02-13T01:25:34.000Z
src/condor_utils/filesystem_remap.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
1
2021-04-06T04:19:40.000Z
2021-04-06T04:19:40.000Z
src/condor_utils/filesystem_remap.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
2
2016-05-24T17:12:13.000Z
2017-02-13T01:25:35.000Z
/*************************************************************** * * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "filename_tools.h" #include "condor_debug.h" #include "MyString.h" #include "condor_uid.h" #include "filesystem_remap.h" #include "condor_config.h" #include "directory.h" #if defined(LINUX) #include <sys/mount.h> #endif FilesystemRemap::FilesystemRemap() : m_mappings(), m_mounts_shared(), m_remap_proc(false) { ParseMountinfo(); FixAutofsMounts(); } int FilesystemRemap::AddMapping(std::string source, std::string dest) { if (!is_relative_to_cwd(source) && !is_relative_to_cwd(dest)) { std::list<pair_strings>::const_iterator it; for (it = m_mappings.begin(); it != m_mappings.end(); it++) { if ((it->second.length() == dest.length()) && (it->second.compare(dest) == 0)) { dprintf(D_ALWAYS, "Mapping already present for %s.\n", dest.c_str()); return -1; } } if (CheckMapping(dest)) { dprintf(D_ALWAYS, "Failed to convert shared mount to private mapping"); return -1; } m_mappings.push_back( std::pair<std::string, std::string>(source, dest) ); } else { dprintf(D_ALWAYS, "Unable to add mappings for relative directories (%s, %s).\n", source.c_str(), dest.c_str()); return -1; } return 0; } int FilesystemRemap::CheckMapping(const std::string & mount_point) { #ifndef HAVE_UNSHARE dprintf(D_ALWAYS, "This system doesn't support remounting of filesystems: %s\n", mount_point.c_str()); return -1; #else bool best_is_shared = false; size_t best_len = 0; const std::string *best = NULL; dprintf(D_FULLDEBUG, "Checking the mapping of mount point %s.\n", mount_point.c_str()); for (std::list<pair_str_bool>::const_iterator it = m_mounts_shared.begin(); it != m_mounts_shared.end(); it++) { std::string first = it->first; if ((strncmp(first.c_str(), mount_point.c_str(), first.size()) == 0) && (first.size() > best_len)) { best_len = first.size(); best = &(it->first); best_is_shared = it->second; } } if (!best_is_shared) { return 0; } dprintf(D_ALWAYS, "Current mount, %s, is shared.\n", best->c_str()); #if !defined(HAVE_MS_SLAVE) && !defined(HAVE_MS_REC) TemporaryPrivSentry sentry(PRIV_ROOT); // Re-mount the mount point as a bind mount, so we can subsequently // re-mount it as private. if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_BIND, NULL)) { dprintf(D_ALWAYS, "Marking %s as a bind mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno)); return -1; } #ifdef HAVE_MS_PRIVATE if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_PRIVATE, NULL)) { dprintf(D_ALWAYS, "Marking %s as a private mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno)); return -1; } else { dprintf(D_FULLDEBUG, "Marking %s as a private mount successful.\n", mount_point.c_str()); } #endif #endif return 0; #endif } int FilesystemRemap::FixAutofsMounts() { #ifndef HAVE_UNSHARE // An appropriate error message is printed in FilesystemRemap::CheckMapping; // Not doing anything here. return -1; #else #ifdef HAVE_MS_SHARED TemporaryPrivSentry sentry(PRIV_ROOT); for (std::list<pair_strings>::const_iterator it=m_mounts_autofs.begin(); it != m_mounts_autofs.end(); it++) { if (mount(it->first.c_str(), it->second.c_str(), NULL, MS_SHARED, NULL)) { dprintf(D_ALWAYS, "Marking %s->%s as a shared-subtree autofs mount failed. (errno=%d, %s)\n", it->first.c_str(), it->second.c_str(), errno, strerror(errno)); return -1; } else { dprintf(D_FULLDEBUG, "Marking %s as a shared-subtree autofs mount successful.\n", it->second.c_str()); } } #endif return 0; #endif } // This is called within the exec // IT CANNOT CALL DPRINTF! int FilesystemRemap::PerformMappings() { int retval = 0; #if defined(LINUX) std::list<pair_strings>::iterator it; for (it = m_mappings.begin(); it != m_mappings.end(); it++) { if (strcmp(it->second.c_str(), "/") == 0) { if ((retval = chroot(it->first.c_str()))) { break; } if ((retval = chdir("/"))) { break; } } else if ((retval = mount(it->first.c_str(), it->second.c_str(), NULL, MS_BIND, NULL))) { break; } } if ((!retval) && m_remap_proc) { retval = mount("proc", "/proc", "proc", 0, NULL); } #endif return retval; } std::string FilesystemRemap::RemapFile(std::string target) { if (target[0] != '/') return std::string(); size_t pos = target.rfind("/"); if (pos == std::string::npos) return target; std::string filename = target.substr(pos, target.size() - pos); std::string directory = target.substr(0, target.size() - filename.size()); return RemapDir(directory) + filename; } std::string FilesystemRemap::RemapDir(std::string target) { if (target[0] != '/') return std::string(); std::list<pair_strings>::iterator it; for (it = m_mappings.begin(); it != m_mappings.end(); it++) { if ((it->first.compare(0, it->first.length(), target, 0, it->first.length()) == 0) && (it->second.compare(0, it->second.length(), it->first, 0, it->second.length()) == 0)) { target.replace(0, it->first.length(), it->second); } } return target; } void FilesystemRemap::RemapProc() { m_remap_proc = true; } /* Sample mountinfo contents (from http://www.kernel.org/doc/Documentation/filesystems/proc.txt): 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) (1) mount ID: unique identifier of the mount (may be reused after umount) (2) parent ID: ID of parent (or of self for the top of the mount tree) (3) major:minor: value of st_dev for files on filesystem (4) root: root of the mount within the filesystem (5) mount point: mount point relative to the process's root (6) mount options: per mount options (7) optional fields: zero or more fields of the form "tag[:value]" (8) separator: marks the end of the optional fields (9) filesystem type: name of filesystem of the form "type[.subtype]" (10) mount source: filesystem specific information or "none" (11) super options: per super block options */ #define ADVANCE_TOKEN(token, str) { \ if ((token = str.GetNextToken(" ", false)) == NULL) { \ fclose(fd); \ dprintf(D_ALWAYS, "Invalid line in mountinfo file: %s\n", str.Value()); \ return; \ } \ } #define SHARED_STR "shared:" void FilesystemRemap::ParseMountinfo() { MyString str, str2; const char * token; FILE *fd; bool is_shared; if ((fd = fopen("/proc/self/mountinfo", "r")) == NULL) { if (errno == ENOENT) { dprintf(D_FULLDEBUG, "The /proc/self/mountinfo file does not exist; kernel support probably lacking. Will assume normal mount structure.\n"); } else { dprintf(D_ALWAYS, "Unable to open the mountinfo file (/proc/self/mountinfo). (errno=%d, %s)\n", errno, strerror(errno)); } return; } while (str2.readLine(fd, false)) { str = str2; str.Tokenize(); ADVANCE_TOKEN(token, str) // mount ID ADVANCE_TOKEN(token, str) // parent ID ADVANCE_TOKEN(token, str) // major:minor ADVANCE_TOKEN(token, str) // root ADVANCE_TOKEN(token, str) // mount point std::string mp(token); ADVANCE_TOKEN(token, str) // mount options ADVANCE_TOKEN(token, str) // optional fields is_shared = false; while (strcmp(token, "-") != 0) { is_shared = is_shared || (strncmp(token, SHARED_STR, strlen(SHARED_STR)) == 0); ADVANCE_TOKEN(token, str) } ADVANCE_TOKEN(token, str) // filesystem type if ((!is_shared) && (strcmp(token, "autofs") == 0)) { ADVANCE_TOKEN(token, str) m_mounts_autofs.push_back(pair_strings(token, mp)); } // This seems a bit too chatty - disabling for now. // dprintf(D_FULLDEBUG, "Mount: %s, shared: %d.\n", mp.c_str(), is_shared); m_mounts_shared.push_back(pair_str_bool(mp, is_shared)); } fclose(fd); } pair_strings_vector root_dir_list() { pair_strings_vector execute_dir_list; execute_dir_list.push_back(pair_strings("root","/")); const char * allowed_root_dirs = param("NAMED_CHROOT"); if (allowed_root_dirs) { StringList chroot_list(allowed_root_dirs); chroot_list.rewind(); const char * next_chroot; while ( (next_chroot=chroot_list.next()) ) { MyString chroot_spec(next_chroot); chroot_spec.Tokenize(); const char * chroot_name = chroot_spec.GetNextToken("=", false); if (chroot_name == NULL) { dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value()); continue; } const char * next_dir = chroot_spec.GetNextToken("=", false); if (next_dir == NULL) { dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value()); continue; } if (IsDirectory(next_dir)) { pair_strings p(chroot_name, next_dir); execute_dir_list.push_back(p); } } } return execute_dir_list; } bool is_trivial_rootdir(const std::string &root_dir) { for (std::string::const_iterator it=root_dir.begin(); it!=root_dir.end(); it++) { if (*it != '/') return false; } return true; }
31.792763
160
0.66715
zhangzhehust
fde789f3bde884920d5184fb047ba1a61817cd56
13,463
cpp
C++
src/commonui/CNodeEdgePropertiesUI.cpp
wojtek48/qvge
3c39128384a3ab3456bc559bda2e957e5bc814af
[ "MIT" ]
null
null
null
src/commonui/CNodeEdgePropertiesUI.cpp
wojtek48/qvge
3c39128384a3ab3456bc559bda2e957e5bc814af
[ "MIT" ]
null
null
null
src/commonui/CNodeEdgePropertiesUI.cpp
wojtek48/qvge
3c39128384a3ab3456bc559bda2e957e5bc814af
[ "MIT" ]
null
null
null
/* This file is a part of QVGE - Qt Visual Graph Editor (c) 2016-2019 Ars L. Masiuk ([email protected]) It can be used freely, maintaining the information above. */ #include <QInputDialog> #include <QMessageBox> #include "CAttributesEditorUI.h" #include "CPropertyEditorUIBase.h" #include "CNodeEdgePropertiesUI.h" #include "ui_CNodeEdgePropertiesUI.h" #include <qvge/CNodeEditorScene.h> #include <qvge/CNode.h> #include <qvge/CEdge.h> #include <qvge/CDirectEdge.h> #include <qvge/CAttribute.h> #include <qvge/CEditorSceneDefines.h> #include <Const.h> #include <qvge/currentvalues.h> CNodeEdgePropertiesUI::CNodeEdgePropertiesUI(QWidget *parent) : QWidget(parent), m_scene(NULL), m_updateLock(false), ui(new Ui::CNodeEdgePropertiesUI) { m_nodeFactory = new CNode; m_edgeFactory = new CDirectEdge; ui->setupUi(this); //WPaw - dodawanie ikon nodów ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/bankDanych.PNG"), cBankDanych, cBankDanych); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/harmonogram.PNG"), cHarmonogram, cHarmonogram); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/generatorZdarzen.PNG"), cGeneratorZdarzen, cGeneratorZdarzen); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/procedury.PNG"), cProcedury, cProcedury); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zasobStatyczny.PNG"), cZasobStatyczny, cZasobStatyczny); ui->NodeProcShape->addAction(QIcon(":/Icons/Icons/komponenty/zegar.PNG"), cZegar, cZegar); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompUniwersalny.PNG"), cKompUniwersalny, cKompUniwersalny); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzetwarzania.PNG"), cKompPrzetwarzania, cKompPrzetwarzania); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompPrzeplywu.PNG"), cKompPrzeplywu, cKompPrzeplywu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/kompWymuszPrzeplyw.PNG"), cKompWymuszPrzeplywu, cKompWymuszPrzeplywu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/zrodloZasobu.PNG"), cZrodloZasobu, cZrodloZasobu); ui->NodeFlowShape->addAction(QIcon(":/Icons/Icons/komponenty/celZasobu.PNG"), cCelZasobu, cCelZasobu); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Directed"), tr("Directed (one end)"), "directed"); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Mutual"), tr("Mutual (both ends)"), "mutual"); // ui->EdgeDirection->addAction(QIcon(":/Icons/Edge-Undirected"), tr("None (no ends)"), "undirected"); // ui->EdgeColor->setColorScheme(QSint::OpenOfficeColors()); //ui->EdgeStyle->setUsedRange(Qt::SolidLine, Qt::DashDotDotLine); ui->Edge->addAction (QIcon(cIkonaKanalZdarzen), cKanalZdarzen, cKanalZdarzen); ui->Edge->addAction (QIcon(cIkonaKanalZasobu), cKanalZasobu, cKanalZasobu); ui->Edge->addAction (QIcon(cIkonaKanalDanych), cKanalDanych, cKanalDanych); ui->Edge->addAction (QIcon(cIkonaKanalKomunikacyjny), cKanalKomunikacyjny, cKanalKomunikacyjny); ui->Edge->addAction (QIcon(cIkonaProceduryWbudowane), cProceduryWbudowane, cProceduryWbudowane); ui->Edge->addAction (QIcon(cIkonaDostepnoscZasobu), cDostepnoscZasobu, cDostepnoscZasobu); // font size QList<int> fontSizes = { 5,6,7,8,9,10,11,12,14,16,18,20,24,28,32,36,40,44,48,54,60,66,72,80,88,96 }; ui->LabelFontSize->setValueList(fontSizes); // node size QList<int> nodeSizes = { 5,10,15,20,30,40,50,75,100,150,200 }; ui->NodeSizeX->setValueList(nodeSizes); // update status & tooltips etc. ui->retranslateUi(this); } CNodeEdgePropertiesUI::~CNodeEdgePropertiesUI() { delete m_nodeFactory; delete ui; } void CNodeEdgePropertiesUI::doReadSettings(QSettings& settings) { int pos = settings.value("nodes/splitterPosition", -1).toInt(); /*int*/ pos = settings.value("edges/splitterPosition", -1).toInt(); } void CNodeEdgePropertiesUI::doWriteSettings(QSettings& settings) { } void CNodeEdgePropertiesUI::setScene(CNodeEditorScene* scene) { if (m_scene) onSceneDetached(m_scene); m_scene = scene; setEnabled(m_scene); if (m_scene) onSceneAttached(m_scene); } void CNodeEdgePropertiesUI::connectSignals(CEditorScene* scene) { connect(scene, SIGNAL(sceneChanged()), this, SLOT(onSceneChanged())); connect(scene, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged())); } void CNodeEdgePropertiesUI::updateFromScene(CEditorScene* scene) { // default attrs auto nodeAttrs = scene->getClassAttributes("node", false); ui->NodeFlowShape->selectAction(nodeAttrs["shape"].defaultValue); QSize size = nodeAttrs["size"].defaultValue.toSize(); ui->NodeSizeX->setValue(size.width()); auto edgeAttrs = scene->getClassAttributes("edge", false); // ui->EdgeColor->setColor(edgeAttrs["color"].defaultValue.value<QColor>()); // ui->EdgeWeight->setValue(edgeAttrs["weight"].defaultValue.toDouble()); // ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edgeAttrs["style"].defaultValue.toString())); //ui->EdgeDirection->selectAction(edgeAttrs["direction"].defaultValue); QFont f(edgeAttrs["label.font"].defaultValue.value<QFont>()); ui->LabelFont->setCurrentFont(f); ui->LabelFontSize->setValue(f.pointSize()); ui->LabelColor->setColor(edgeAttrs["label.color"].defaultValue.value<QColor>()); } void CNodeEdgePropertiesUI::onSceneAttached(CEditorScene* scene) { // factories for new items //scene->setActiveItemFactory(m_nodeFactory); //scene->setActiveItemFactory(m_edgeFactory); // default attrs updateFromScene(scene); // connect & go connectSignals(scene); onSceneChanged(); } void CNodeEdgePropertiesUI::onSceneDetached(CEditorScene* scene) { scene->disconnect(this); } void CNodeEdgePropertiesUI::onSceneChanged() { // update active selections if any onSelectionChanged(); } void CNodeEdgePropertiesUI::onSelectionChanged() { if (m_updateLock || m_scene == NULL) return; m_updateLock = true; QList<CEdge*> edges = m_scene->getSelectedEdges(); QList<CNode*> nodes = m_scene->getSelectedNodes(); // nodes ui->NodesBox->setTitle(tr("Selected components (%1)").arg(nodes.count())); if (nodes.count()) { auto node = nodes.first(); ui->NodeFlowShape->selectAction(node->getAttribute("shape")); QSize size = node->getAttribute("size").toSize(); ui->NodeSizeX->setValue(size.width()); } QList<CItem*> nodeItems; // edges ui->EdgesBox->setTitle(tr("Selected connections (%1)").arg(edges.count())); if (edges.count()) { auto edge = edges.first(); // ui->EdgeColor->setColor(edge->getAttribute("color").value<QColor>()); // ui->EdgeWeight->setValue(edge->getAttribute("weight").toDouble()); // ui->EdgeStyle->setPenStyle(CUtils::textToPenStyle(edge->getAttribute("style").toString())); // ui->EdgeDirection->selectAction(edge->getAttribute("direction")); } QList<CItem*> edgeItems; for (auto item: edges) edgeItems << item; // labels QList<CItem*> itemList; for (auto edgeItem: edges) itemList << edgeItem; for (auto nodeItem: nodes) itemList << nodeItem; for (auto item: itemList) { QFont f(item->getAttribute("label.font").value<QFont>()); ui->LabelFont->setCurrentFont(f); ui->LabelFontSize->setValue(f.pointSize()); ui->LabelFontBold->setChecked(f.bold()); ui->LabelFontItalic->setChecked(f.italic()); ui->LabelFontUnderline->setChecked(f.underline()); ui->LabelColor->setColor(item->getAttribute("label.color").value<QColor>()); break; } // allow updates m_updateLock = false; } void CNodeEdgePropertiesUI::setNodesAttribute(const QByteArray& attrId, const QVariant& v) { QString s = QVariant(v).toString(); if (attrId == "shape") CurrentValues::instance().shape = s; if (m_nodeFactory) m_nodeFactory->setAttribute(attrId, v); if (m_updateLock || m_scene == NULL) return; QList<CNode*> nodes = m_scene->getSelectedNodes(); if (nodes.isEmpty()) return; //WPaw - tu ustawia się atrybut dla konkretnego noda for (auto node : nodes) node->setAttribute(attrId, v); m_scene->addUndoState(); } void CNodeEdgePropertiesUI::setEdgesAttribute(const QByteArray& attrId, const QVariant& v) { if (m_edgeFactory) m_edgeFactory->setAttribute(attrId, v); if (m_updateLock || m_scene == NULL) return; QList<CEdge*> edges = m_scene->getSelectedEdges(); if (edges.isEmpty()) return; for (auto edge : edges) edge->setAttribute(attrId, v); m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_NodeColor_activated(const QColor &color) { setNodesAttribute("color", color); } void CNodeEdgePropertiesUI::on_NodeFlowShape_activated(QVariant data) { setNodesAttribute("shape", data); ui->rButFlow->setChecked(1); // ui->rButFlow->clicked(true); // ui->rButProc->clicked(false); } void CNodeEdgePropertiesUI::on_NodeProcShape_activated(QVariant data) { setNodesAttribute("shape", data); ui->rButProc->setChecked(1); // ui->rButFlow->clicked(false); // ui->rButProc->clicked(true); } void CNodeEdgePropertiesUI::on_NodeSizeX_valueChanged(int /*value*/) { ui->NodeSizeX->blockSignals(true); QSize size(ui->NodeSizeX->value(), ui->NodeSizeX->value()); setNodesAttribute("size", size); ui->NodeSizeX->blockSignals(false); } void CNodeEdgePropertiesUI::on_StrokeColor_activated(const QColor &color) { setNodesAttribute("stroke.color", color); } void CNodeEdgePropertiesUI::on_StrokeStyle_activated(QVariant data) { QString style = CUtils::penStyleToText(data.toInt()); setNodesAttribute("stroke.style", style); } void CNodeEdgePropertiesUI::on_StrokeSize_valueChanged(double value) { setNodesAttribute("stroke.size", value); } void CNodeEdgePropertiesUI::on_EdgeColor_activated(const QColor &color) { setEdgesAttribute("color", color); } void CNodeEdgePropertiesUI::on_EdgeWeight_valueChanged(double value) { setEdgesAttribute("weight", value); } void CNodeEdgePropertiesUI::on_EdgeStyle_activated(QVariant data) { QString style = CUtils::penStyleToText(data.toInt()); setEdgesAttribute("style", style); } void CNodeEdgePropertiesUI::on_Edge_activated(QVariant data) { QString s = QVariant(data).toString(); CurrentValues::instance().connection = s; setEdgesAttribute("style", data); } void CNodeEdgePropertiesUI::on_EdgeDirection_activated(QVariant data) { setEdgesAttribute("direction", data); } void CNodeEdgePropertiesUI::on_LabelFont_activated(const QFont &font) { ui->LabelFontSize->blockSignals(true); ui->LabelFontSize->setValue(font.pointSize()); ui->LabelFontSize->blockSignals(false); if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; for (auto item : items) { item->setAttribute(attr_label_font, font); } m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelColor_activated(const QColor &color) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; for (auto item : items) { item->setAttribute(attr_label_color, color); } m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontSize_valueChanged(int value) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.pointSize() != value) { font.setPointSize(value); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontBold_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.bold() != on) { font.setBold(on); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontItalic_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.italic() != on) { font.setItalic(on); item->setAttribute(attr_label_font, font); item->updateLabelContent(); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_LabelFontUnderline_toggled(bool on) { if (m_updateLock || m_scene == NULL) return; QList<CItem*> items = m_scene->getSelectedNodesEdges(); if (items.isEmpty()) return; bool set = false; for (auto item : items) { QFont font = item->getAttribute(attr_label_font).value<QFont>(); if (font.underline() != on) { font.setUnderline(on); item->setAttribute(attr_label_font, font); set = true; } } if (set) m_scene->addUndoState(); } void CNodeEdgePropertiesUI::on_NodeFlowShape_windowIconChanged(const QIcon &icon) { QMessageBox qmb; qmb.setText( " duuuap"); qmb.exec(); }
25.449905
135
0.714997
wojtek48
fde988d21be7b6ef5651632c1be04987542238f8
606
cc
C++
Part-II/Ch09/9.3.3/9.25.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
1
2021-09-23T13:13:12.000Z
2021-09-23T13:13:12.000Z
Part-II/Ch09/9.3.3/9.25.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
null
null
null
Part-II/Ch09/9.3.3/9.25.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { { vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto elem1 = vec.begin() + 2, elem2 = vec.begin() + 2; elem1 = vec.erase(elem1, elem2); for (auto &v: vec) { cout << v << " "; } cout << "\n"; } { vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto elem1 = vec.end(), elem2 = vec.end(); elem1 = vec.erase(elem1, elem2); for (auto &v: vec) { cout << v << " "; } cout << "\n"; } return 0; }
23.307692
62
0.410891
RingZEROtlf
fdeb4e989fe8830379629f873cd7d1c30e777d6b
17,596
cc
C++
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
skarvtech/uwrosys
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
[ "Apache-2.0" ]
null
null
null
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
skarvtech/uwrosys
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
[ "Apache-2.0" ]
null
null
null
repos/ComponentRosJoystick/smartsoft/src-gen/ComponentRosJoystick.cc
skarvtech/uwrosys
c9e82e4496c5d334b53e835ca6a2d8c3c3a82dc4
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #include "ComponentRosJoystick.hh" #include "smartTimedTaskTrigger.h" //FIXME: implement logging //#include "smartGlobalLogger.hh" // the ace port-factory is used as a default port-mapping #include "ComponentRosJoystickAcePortFactory.hh" // initialize static singleton pointer to zero ComponentRosJoystick* ComponentRosJoystick::_componentRosJoystick = 0; // constructor ComponentRosJoystick::ComponentRosJoystick() { std::cout << "constructor of ComponentRosJoystick\n"; // set all pointer members to NULL joystickActivity = NULL; joystickActivityTrigger = NULL; joystickServiceOut = NULL; //_joy = NULL; stateChangeHandler = NULL; stateSlave = NULL; wiringSlave = NULL; // set default ini parameter values connections.component.name = "ComponentRosJoystick"; connections.component.initialComponentMode = "Neutral"; connections.component.defaultScheduler = "DEFAULT"; connections.component.useLogger = false; connections.joystickServiceOut.serviceName = "JoystickServiceOut"; connections.joystickServiceOut.roboticMiddleware = "ACE_SmartSoft"; connections.joystickActivity.minActFreq = 0.0; connections.joystickActivity.maxActFreq = 0.0; connections.joystickActivity.trigger = "PeriodicTimer"; connections.joystickActivity.periodicActFreq = 10.0; // scheduling default parameters connections.joystickActivity.scheduler = "DEFAULT"; connections.joystickActivity.priority = -1; connections.joystickActivity.cpuAffinity = -1; // initialize members of ComponentRosJoystickROSExtension rosPorts = 0; // initialize members of OpcUaBackendComponentGeneratorExtension // initialize members of PlainOpcUaComponentRosJoystickExtension } void ComponentRosJoystick::addPortFactory(const std::string &name, ComponentRosJoystickPortFactoryInterface *portFactory) { portFactoryRegistry[name] = portFactory; } void ComponentRosJoystick::addExtension(ComponentRosJoystickExtension *extension) { componentExtensionRegistry[extension->getName()] = extension; } SmartACE::SmartComponent* ComponentRosJoystick::getComponentImpl() { return dynamic_cast<ComponentRosJoystickAcePortFactory*>(portFactoryRegistry["ACE_SmartSoft"])->getComponentImpl(); } /** * Notify the component that setup/initialization is finished. * You may call this function from anywhere in the component. * * Set component's internal lifecycle state automaton (if any) into * Alive mode (from here on the component is ready to provide its services) */ void ComponentRosJoystick::setStartupFinished() { stateSlave->setWaitState("Alive"); std::cout << "ComponentDefinition initialization/startup finished." << std::endl; } /** * First connect ALL client ports contained in this component, then start all services: * activate state, push, etc... */ Smart::StatusCode ComponentRosJoystick::connectAndStartAllServices() { Smart::StatusCode status = Smart::SMART_OK; return status; } /** * Start all tasks contained in this component. */ void ComponentRosJoystick::startAllTasks() { // start task JoystickActivity if(connections.joystickActivity.scheduler != "DEFAULT") { ACE_Sched_Params joystickActivity_SchedParams(ACE_SCHED_OTHER, ACE_THR_PRI_OTHER_DEF); if(connections.joystickActivity.scheduler == "FIFO") { joystickActivity_SchedParams.policy(ACE_SCHED_FIFO); joystickActivity_SchedParams.priority(ACE_THR_PRI_FIFO_MIN); } else if(connections.joystickActivity.scheduler == "RR") { joystickActivity_SchedParams.policy(ACE_SCHED_RR); joystickActivity_SchedParams.priority(ACE_THR_PRI_RR_MIN); } joystickActivity->start(joystickActivity_SchedParams, connections.joystickActivity.cpuAffinity); } else { joystickActivity->start(); } } /** * Start all timers contained in this component */ void ComponentRosJoystick::startAllTimers() { } Smart::TaskTriggerSubject* ComponentRosJoystick::getInputTaskTriggerFromString(const std::string &client) { return NULL; } void ComponentRosJoystick::init(int argc, char *argv[]) { try { Smart::StatusCode status; // load initial parameters from ini-file (if found) loadParameter(argc, argv); // initializations of ComponentRosJoystickROSExtension // initializations of OpcUaBackendComponentGeneratorExtension // initializations of PlainOpcUaComponentRosJoystickExtension // initialize all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->initialize(this, argc, argv); } // initialize all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->initialize(this, argc, argv); } ComponentRosJoystickPortFactoryInterface *acePortFactory = portFactoryRegistry["ACE_SmartSoft"]; if(acePortFactory == 0) { std::cerr << "ERROR: acePortFactory NOT instantiated -> exit(-1)" << std::endl; exit(-1); } // this pointer is used for backwards compatibility (deprecated: should be removed as soon as all patterns, including coordination, are moved to port-factory) SmartACE::SmartComponent *component = dynamic_cast<ComponentRosJoystickAcePortFactory*>(acePortFactory)->getComponentImpl(); std::cout << "ComponentDefinition ComponentRosJoystick is named " << connections.component.name << std::endl; if(connections.component.useLogger == true) { //FIXME: use logging //Smart::LOGGER->openLogFileInFolder("data/"+connections.component.name); //Smart::LOGGER->startLogging(); } // create event-test handlers (if needed) // create server ports // TODO: set minCycleTime from Ini-file joystickServiceOut = portFactoryRegistry[connections.joystickServiceOut.roboticMiddleware]->createJoystickServiceOut(connections.joystickServiceOut.serviceName); // create client ports // create InputTaskTriggers and UpcallManagers // create input-handler // create request-handlers // create state pattern stateChangeHandler = new SmartStateChangeHandler(); stateSlave = new SmartACE::StateSlave(component, stateChangeHandler); status = stateSlave->setUpInitialState(connections.component.initialComponentMode); if (status != Smart::SMART_OK) std::cerr << status << "; failed setting initial ComponentMode: " << connections.component.initialComponentMode << std::endl; // activate state slave status = stateSlave->activate(); if(status != Smart::SMART_OK) std::cerr << "ERROR: activate state" << std::endl; wiringSlave = new SmartACE::WiringSlave(component); // add client port to wiring slave // create Task JoystickActivity joystickActivity = new JoystickActivity(component); // configure input-links // configure task-trigger (if task is configurable) if(connections.joystickActivity.trigger == "PeriodicTimer") { // create PeriodicTimerTrigger int microseconds = 1000*1000 / connections.joystickActivity.periodicActFreq; if(microseconds > 0) { Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger(); triggerPtr->attach(joystickActivity); component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds)); // store trigger in class member joystickActivityTrigger = triggerPtr; } else { std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl; } } else if(connections.joystickActivity.trigger == "DataTriggered") { joystickActivityTrigger = getInputTaskTriggerFromString(connections.joystickActivity.inPortRef); if(joystickActivityTrigger != NULL) { joystickActivityTrigger->attach(joystickActivity, connections.joystickActivity.prescale); } else { std::cerr << "ERROR: could not set-up InPort " << connections.joystickActivity.inPortRef << " as activation source for Task JoystickActivity" << std::endl; } } else { // setup default task-trigger as PeriodicTimer Smart::TimedTaskTrigger *triggerPtr = new Smart::TimedTaskTrigger(); int microseconds = 1000*1000 / 10.0; if(microseconds > 0) { component->getTimerManager()->scheduleTimer(triggerPtr, (void *) 0, std::chrono::microseconds(microseconds), std::chrono::microseconds(microseconds)); triggerPtr->attach(joystickActivity); // store trigger in class member joystickActivityTrigger = triggerPtr; } else { std::cerr << "ERROR: could not set-up Timer with cycle-time " << microseconds << " as activation source for Task JoystickActivity" << std::endl; } } // link observers with subjects } catch (const std::exception &ex) { std::cerr << "Uncaught std exception" << ex.what() << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } } // run the component void ComponentRosJoystick::run() { stateSlave->acquire("init"); // startup all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->onStartup(); } // startup all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->onStartup(); } stateSlave->release("init"); // do not call this handler within the init state (see above) as this handler internally calls setStartupFinished() (this should be fixed in future) compHandler.onStartup(); // this call blocks until the component is commanded to shutdown stateSlave->acquire("shutdown"); // shutdown all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->onShutdown(); } // shutdown all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->onShutdown(); } if(connections.component.useLogger == true) { //FIXME: use logging //Smart::LOGGER->stopLogging(); } compHandler.onShutdown(); stateSlave->release("shutdown"); } // clean-up component's resources void ComponentRosJoystick::fini() { // unlink all observers // destroy all task instances // unlink all UpcallManagers // unlink the TaskTrigger if(joystickActivityTrigger != NULL){ joystickActivityTrigger->detach(joystickActivity); delete joystickActivity; } // destroy all input-handler // destroy InputTaskTriggers and UpcallManagers // destroy client ports // destroy server ports delete joystickServiceOut; // destroy event-test handlers (if needed) // destroy request-handlers delete stateSlave; // destroy state-change-handler delete stateChangeHandler; // destroy all master/slave ports delete wiringSlave; // destroy all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->destroy(); } // destroy all registered port-factories for(auto portFactory = portFactoryRegistry.begin(); portFactory != portFactoryRegistry.end(); portFactory++) { portFactory->second->destroy(); } // destruction of ComponentRosJoystickROSExtension // destruction of OpcUaBackendComponentGeneratorExtension // destruction of PlainOpcUaComponentRosJoystickExtension } void ComponentRosJoystick::loadParameter(int argc, char *argv[]) { /* Parameters can be specified via command line --filename=<filename> or -f <filename> With this parameter present: - The component will look for the file in the current working directory, a path relative to the current directory or any absolute path - The component will use the default values if the file cannot be found With this parameter absent: - <Name of Component>.ini will be read from current working directory, if found there - $SMART_ROOT/etc/<Name of Component>.ini will be read otherwise - Default values will be used if neither found in working directory or /etc */ SmartACE::SmartIniParameter parameter; std::ifstream parameterfile; bool parameterFileFound = false; // load parameters try { // if paramfile is given as argument if(parameter.tryAddFileFromArgs(argc,argv,"filename", 'f')) { parameterFileFound = true; std::cout << "parameter file is loaded from an argv argument \n"; } else if(parameter.searchFile("ComponentRosJoystick.ini", parameterfile)) { parameterFileFound = true; std::cout << "load ComponentRosJoystick.ini parameter file\n"; parameter.addFile(parameterfile); } else { std::cout << "WARNING: ComponentRosJoystick.ini parameter file not found! (using default values or command line arguments)\n"; } // add command line arguments to allow overwriting of parameters // from file parameter.addCommandLineArgs(argc,argv,"component"); // initialize the naming service using the command line parameters parsed in the // SmartIniParameter class. The naming service parameters are expected to be in // the "component" parameter group. SmartACE::NAMING::instance()->checkForHelpArg(argc,argv); if(parameterFileFound) { if(SmartACE::NAMING::instance()->init(parameter.getAllParametersFromGroup("component")) != 0) { // initialization of naming service failed throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" ); } } else { if(SmartACE::NAMING::instance()->init(argc, argv) != 0) { // initialization of naming service failed throw std::logic_error( "<NamingService> Service initialization failed!\nPossible causes could be:\n-> Erroneous configuration.\n-> Naming service not reachable.\n" ); } } // print all known parameters // parameter.print(); //--- server port // client port // other parameter --- // load parameter parameter.getString("component", "name", connections.component.name); parameter.getString("component", "initialComponentMode", connections.component.initialComponentMode); if(parameter.checkIfParameterExists("component", "defaultScheduler")) { parameter.getString("component", "defaultScheduler", connections.component.defaultScheduler); } if(parameter.checkIfParameterExists("component", "useLogger")) { parameter.getBoolean("component", "useLogger", connections.component.useLogger); } // load parameters for server JoystickServiceOut parameter.getString("JoystickServiceOut", "serviceName", connections.joystickServiceOut.serviceName); if(parameter.checkIfParameterExists("JoystickServiceOut", "roboticMiddleware")) { parameter.getString("JoystickServiceOut", "roboticMiddleware", connections.joystickServiceOut.roboticMiddleware); } // load parameters for task JoystickActivity parameter.getDouble("JoystickActivity", "minActFreqHz", connections.joystickActivity.minActFreq); parameter.getDouble("JoystickActivity", "maxActFreqHz", connections.joystickActivity.maxActFreq); parameter.getString("JoystickActivity", "triggerType", connections.joystickActivity.trigger); if(connections.joystickActivity.trigger == "PeriodicTimer") { parameter.getDouble("JoystickActivity", "periodicActFreqHz", connections.joystickActivity.periodicActFreq); } else if(connections.joystickActivity.trigger == "DataTriggered") { parameter.getString("JoystickActivity", "inPortRef", connections.joystickActivity.inPortRef); parameter.getInteger("JoystickActivity", "prescale", connections.joystickActivity.prescale); } if(parameter.checkIfParameterExists("JoystickActivity", "scheduler")) { parameter.getString("JoystickActivity", "scheduler", connections.joystickActivity.scheduler); } if(parameter.checkIfParameterExists("JoystickActivity", "priority")) { parameter.getInteger("JoystickActivity", "priority", connections.joystickActivity.priority); } if(parameter.checkIfParameterExists("JoystickActivity", "cpuAffinity")) { parameter.getInteger("JoystickActivity", "cpuAffinity", connections.joystickActivity.cpuAffinity); } // load parameters for ComponentRosJoystickROSExtension // load parameters for OpcUaBackendComponentGeneratorExtension // load parameters for PlainOpcUaComponentRosJoystickExtension // load parameters for all registered component-extensions for(auto extension = componentExtensionRegistry.begin(); extension != componentExtensionRegistry.end(); extension++) { extension->second->loadParameters(parameter); } } catch (const SmartACE::IniParameterError & e) { std::cerr << e.what() << std::endl; } catch (const std::exception &ex) { std::cerr << "Uncaught std::exception: " << ex.what() << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } }
36.734864
171
0.746874
skarvtech
fdf571cbf3745b06c7a985d99512bf853c0d87b2
12,639
cpp
C++
src/effects/SkColorCubeFilter.cpp
tmpvar/skia.cc
6e36ba7bf19cc7597837bb0416882ad4d699916b
[ "Apache-2.0" ]
3
2015-08-16T03:44:19.000Z
2015-08-16T17:31:59.000Z
third_party/skia/src/effects/SkColorCubeFilter.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/skia/src/effects/SkColorCubeFilter.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorCubeFilter.h" #include "SkColorPriv.h" #include "SkOnce.h" #include "SkOpts.h" #include "SkReadBuffer.h" #include "SkUnPreMultiply.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrCoordTransform.h" #include "GrInvariantOutput.h" #include "GrTexturePriv.h" #include "SkGr.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramDataManager.h" #include "glsl/GrGLSLUniformHandler.h" #endif /////////////////////////////////////////////////////////////////////////////// namespace { int32_t SkNextColorCubeUniqueID() { static int32_t gColorCubeUniqueID; // do a loop in case our global wraps around, as we never want to return a 0 int32_t genID; do { genID = sk_atomic_inc(&gColorCubeUniqueID) + 1; } while (0 == genID); return genID; } } // end namespace static const int MIN_CUBE_SIZE = 4; static const int MAX_CUBE_SIZE = 64; static bool is_valid_3D_lut(SkData* cubeData, int cubeDimension) { size_t minMemorySize = sizeof(uint8_t) * 4 * cubeDimension * cubeDimension * cubeDimension; return (cubeDimension >= MIN_CUBE_SIZE) && (cubeDimension <= MAX_CUBE_SIZE) && (nullptr != cubeData) && (cubeData->size() >= minMemorySize); } sk_sp<SkColorFilter> SkColorCubeFilter::Make(sk_sp<SkData> cubeData, int cubeDimension) { if (!is_valid_3D_lut(cubeData.get(), cubeDimension)) { return nullptr; } return sk_sp<SkColorFilter>(new SkColorCubeFilter(std::move(cubeData), cubeDimension)); } SkColorCubeFilter::SkColorCubeFilter(sk_sp<SkData> cubeData, int cubeDimension) : fCubeData(std::move(cubeData)) , fUniqueID(SkNextColorCubeUniqueID()) , fCache(cubeDimension) {} uint32_t SkColorCubeFilter::getFlags() const { return this->INHERITED::getFlags() | kAlphaUnchanged_Flag; } SkColorCubeFilter::ColorCubeProcesingCache::ColorCubeProcesingCache(int cubeDimension) : fCubeDimension(cubeDimension) { fColorToIndex[0] = fColorToIndex[1] = nullptr; fColorToFactors[0] = fColorToFactors[1] = nullptr; fColorToScalar = nullptr; } void SkColorCubeFilter::ColorCubeProcesingCache::getProcessingLuts( const int* (*colorToIndex)[2], const SkScalar* (*colorToFactors)[2], const SkScalar** colorToScalar) { fLutsInitOnce(SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts, this); SkASSERT((fColorToIndex[0] != nullptr) && (fColorToIndex[1] != nullptr) && (fColorToFactors[0] != nullptr) && (fColorToFactors[1] != nullptr) && (fColorToScalar != nullptr)); (*colorToIndex)[0] = fColorToIndex[0]; (*colorToIndex)[1] = fColorToIndex[1]; (*colorToFactors)[0] = fColorToFactors[0]; (*colorToFactors)[1] = fColorToFactors[1]; (*colorToScalar) = fColorToScalar; } void SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts( SkColorCubeFilter::ColorCubeProcesingCache* cache) { static const SkScalar inv8bit = SkScalarInvert(SkIntToScalar(255)); // We need 256 int * 2 for fColorToIndex, so a total of 512 int. // We need 256 SkScalar * 2 for fColorToFactors and 256 SkScalar // for fColorToScalar, so a total of 768 SkScalar. cache->fLutStorage.reset(512 * sizeof(int) + 768 * sizeof(SkScalar)); uint8_t* storage = cache->fLutStorage.get(); cache->fColorToIndex[0] = (int*)storage; cache->fColorToIndex[1] = cache->fColorToIndex[0] + 256; cache->fColorToFactors[0] = (SkScalar*)(storage + (512 * sizeof(int))); cache->fColorToFactors[1] = cache->fColorToFactors[0] + 256; cache->fColorToScalar = cache->fColorToFactors[1] + 256; SkScalar size = SkIntToScalar(cache->fCubeDimension); SkScalar scale = (size - SK_Scalar1) * inv8bit; for (int i = 0; i < 256; ++i) { SkScalar index = scale * i; cache->fColorToIndex[0][i] = SkScalarFloorToInt(index); cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i] + 1; cache->fColorToScalar[i] = inv8bit * i; if (cache->fColorToIndex[1][i] < cache->fCubeDimension) { cache->fColorToFactors[1][i] = index - SkIntToScalar(cache->fColorToIndex[0][i]); cache->fColorToFactors[0][i] = SK_Scalar1 - cache->fColorToFactors[1][i]; } else { cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i]; cache->fColorToFactors[0][i] = SK_Scalar1; cache->fColorToFactors[1][i] = 0; } } } void SkColorCubeFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const { const int* colorToIndex[2]; const SkScalar* colorToFactors[2]; const SkScalar* colorToScalar; fCache.getProcessingLuts(&colorToIndex, &colorToFactors, &colorToScalar); SkOpts::color_cube_filter_span(src, count, dst, colorToIndex, colorToFactors, fCache.cubeDimension(), (const SkColor*)fCubeData->data()); } sk_sp<SkFlattenable> SkColorCubeFilter::CreateProc(SkReadBuffer& buffer) { int cubeDimension = buffer.readInt(); auto cubeData(buffer.readByteArrayAsData()); if (!buffer.validate(is_valid_3D_lut(cubeData.get(), cubeDimension))) { return nullptr; } return Make(std::move(cubeData), cubeDimension); } void SkColorCubeFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeInt(fCache.cubeDimension()); buffer.writeDataAsByteArray(fCubeData.get()); } #ifndef SK_IGNORE_TO_STRING void SkColorCubeFilter::toString(SkString* str) const { str->append("SkColorCubeFilter "); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU class GrColorCubeEffect : public GrFragmentProcessor { public: static const GrFragmentProcessor* Create(GrTexture* colorCube) { return (nullptr != colorCube) ? new GrColorCubeEffect(colorCube) : nullptr; } virtual ~GrColorCubeEffect(); const char* name() const override { return "ColorCube"; } int colorCubeSize() const { return fColorCubeAccess.getTexture()->width(); } void onComputeInvariantOutput(GrInvariantOutput*) const override; class GLSLProcessor : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs&) override; static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*); protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: GrGLSLProgramDataManager::UniformHandle fColorCubeSizeUni; GrGLSLProgramDataManager::UniformHandle fColorCubeInvSizeUni; typedef GrGLSLFragmentProcessor INHERITED; }; private: virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const override; GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; bool onIsEqual(const GrFragmentProcessor&) const override { return true; } GrColorCubeEffect(GrTexture* colorCube); GrTextureAccess fColorCubeAccess; typedef GrFragmentProcessor INHERITED; }; /////////////////////////////////////////////////////////////////////////////// GrColorCubeEffect::GrColorCubeEffect(GrTexture* colorCube) : fColorCubeAccess(colorCube, GrTextureParams::kBilerp_FilterMode) { this->initClassID<GrColorCubeEffect>(); this->addTextureAccess(&fColorCubeAccess); } GrColorCubeEffect::~GrColorCubeEffect() { } void GrColorCubeEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GLSLProcessor::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrColorCubeEffect::onCreateGLSLInstance() const { return new GLSLProcessor; } void GrColorCubeEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const { inout->setToUnknown(GrInvariantOutput::kWill_ReadInput); } /////////////////////////////////////////////////////////////////////////////// void GrColorCubeEffect::GLSLProcessor::emitCode(EmitArgs& args) { if (nullptr == args.fInputColor) { args.fInputColor = "vec4(1)"; } GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; fColorCubeSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat_GrSLType, kDefault_GrSLPrecision, "Size"); const char* colorCubeSizeUni = uniformHandler->getUniformCStr(fColorCubeSizeUni); fColorCubeInvSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat_GrSLType, kDefault_GrSLPrecision, "InvSize"); const char* colorCubeInvSizeUni = uniformHandler->getUniformCStr(fColorCubeInvSizeUni); const char* nonZeroAlpha = "nonZeroAlpha"; const char* unPMColor = "unPMColor"; const char* cubeIdx = "cubeIdx"; const char* cCoords1 = "cCoords1"; const char* cCoords2 = "cCoords2"; // Note: if implemented using texture3D in OpenGL ES older than OpenGL ES 3.0, // the shader might need "#extension GL_OES_texture_3D : enable". GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; // Unpremultiply color fragBuilder->codeAppendf("\tfloat %s = max(%s.a, 0.00001);\n", nonZeroAlpha, args.fInputColor); fragBuilder->codeAppendf("\tvec4 %s = vec4(%s.rgb / %s, %s);\n", unPMColor, args.fInputColor, nonZeroAlpha, nonZeroAlpha); // Fit input color into the cube. fragBuilder->codeAppendf( "vec3 %s = vec3(%s.rg * vec2((%s - 1.0) * %s) + vec2(0.5 * %s), %s.b * (%s - 1.0));\n", cubeIdx, unPMColor, colorCubeSizeUni, colorCubeInvSizeUni, colorCubeInvSizeUni, unPMColor, colorCubeSizeUni); // Compute y coord for for texture fetches. fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (floor(%s.b) + %s.g) * %s);\n", cCoords1, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); fragBuilder->codeAppendf("vec2 %s = vec2(%s.r, (ceil(%s.b) + %s.g) * %s);\n", cCoords2, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); // Apply the cube. fragBuilder->codeAppendf("%s = vec4(mix(", args.fOutputColor); fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords1); fragBuilder->codeAppend(".bgr, "); fragBuilder->appendTextureLookup(args.fTexSamplers[0], cCoords2); // Premultiply color by alpha. Note that the input alpha is not modified by this shader. fragBuilder->codeAppendf(".bgr, fract(%s.b)) * vec3(%s), %s.a);\n", cubeIdx, nonZeroAlpha, args.fInputColor); } void GrColorCubeEffect::GLSLProcessor::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { const GrColorCubeEffect& colorCube = proc.cast<GrColorCubeEffect>(); SkScalar size = SkIntToScalar(colorCube.colorCubeSize()); pdman.set1f(fColorCubeSizeUni, SkScalarToFloat(size)); pdman.set1f(fColorCubeInvSizeUni, SkScalarToFloat(SkScalarInvert(size))); } void GrColorCubeEffect::GLSLProcessor::GenKey(const GrProcessor& proc, const GrGLSLCaps&, GrProcessorKeyBuilder* b) { } const GrFragmentProcessor* SkColorCubeFilter::asFragmentProcessor(GrContext* context) const { static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; GrUniqueKey::Builder builder(&key, kDomain, 2); builder[0] = fUniqueID; builder[1] = fCache.cubeDimension(); builder.finish(); GrSurfaceDesc desc; desc.fWidth = fCache.cubeDimension(); desc.fHeight = fCache.cubeDimension() * fCache.cubeDimension(); desc.fConfig = kRGBA_8888_GrPixelConfig; desc.fIsMipMapped = false; SkAutoTUnref<GrTexture> textureCube( context->textureProvider()->findAndRefTextureByUniqueKey(key)); if (!textureCube) { textureCube.reset(context->textureProvider()->createTexture( desc, SkBudgeted::kYes, fCubeData->data(), 0)); if (textureCube) { context->textureProvider()->assignUniqueKeyToTexture(key, textureCube); } else { return nullptr; } } return GrColorCubeEffect::Create(textureCube); } #endif
38.416413
99
0.662552
tmpvar
fdfa888bcb63bc22509d43a5a2e44fe9eef792d4
2,802
cpp
C++
Codeforces/EDU/Segment Tree/Sum.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
Codeforces/EDU/Segment Tree/Sum.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
Codeforces/EDU/Segment Tree/Sum.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
/**************************************************** * Template for coding contests * * Author : Sanjeev Sharma * * Email : [email protected] * *****************************************************/ #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("fast-math") #pragma GCC target("sse4") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define deb(x) cout << #x << " is " << x << "\n" #define int long long #define mod 1000000007 const double PI = 2 * acos(0.0); const long long INF = 1e18L + 5; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class... Args> auto create(size_t n, Args&&... args) { if constexpr (sizeof...(args) == 1) return vector(n, args...); else return vector(n, create(args...)); } template <typename... T> void read(T&... args) { ((cin >> args), ...); } template <typename... T> void write(T&&... args) { ((cout << args), ...); } struct segtree { int size; vector<int> tree; void init(int n) { size = 1; while (size < n) size *= 2; tree.assign(2 * size, 0LL); } void set(int i, int v, int x, int lx, int rx) { if (rx - lx == 1) { tree[x] = v; return; } int mx = lx + (rx - lx) / 2; if (i < mx) { set(i, v, 2 * x + 1, lx, mx); } else { set(i, v, 2 * x + 2, mx, rx); } tree[x] = tree[2 * x + 1] + tree[2 * x + 2]; } int sum(int l, int r, int x, int lx, int rx) { if (lx >= r || rx <= l) return 0; if (lx >= l && rx <= r) return tree[x]; int mx = lx + (rx - lx) / 2; return sum(l, r, 2 * x + 1, lx, mx) + sum(l, r, 2 * x + 2, mx, rx); } int sum(int l, int r) { return sum(l, r, 0, 0, size); } void set(int i, int v) { set(i, v, 0, 0, size); } }; void solve() { int n, m, a, b, c; read(n, m); segtree st; st.init(n); vector<int> arr(n); for (int i = 0; i < n; i++) { read(arr[i]); st.set(i, arr[i]); } while (m--) { read(a, b, c); if (a == 1) { st.set(b, c); } else { write(st.sum(b, c), "\n"); } } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif solve(); return 0; }
23.35
96
0.47359
Code-With-Aagam
a9007d06abceb1d5719325ef85ae1ee771867234
3,018
cpp
C++
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
src/PhysicalEntities/Characters/Enemies/Enemy.cpp
edusidsan/GameProg-OO
c74bedb6c592386a40eefbd61770184994a75aa6
[ "MIT" ]
null
null
null
#include "Enemy.hpp" namespace OgrO // Namespace com o nome do jogo. { namespace PhysicalEntities // Namespace do Pacote Entities. { namespace Characters // Namespace do Pacote Personagens. { namespace Enemies // Namespace do Pacote Enemies. { // Construtora da classe Enemy. Enemy::Enemy(Utilities::gameVector2F pos, Utilities::gameVector2F s, const char *tPath, unsigned int life) : Character(pos, s, tPath, life), timeReference(0), projectileInterval(0) { } Enemy::Enemy(nlohmann::json source) : Enemy(Utilities::gameVector2F{static_cast<float>(source["position x"]), static_cast<float>(source["position y"])}, Utilities::gameVector2F{static_cast<float>(source["speed x"]), static_cast<float>(source["speed y"])}, "", static_cast<unsigned int>(source["life"])) { } // Destrutora da classe Enemy. Enemy::~Enemy() { } // Método carrega a textura do enemy na window e inicializa gerenciadores do mesmo. void Enemy::initialize() { // Carrega textura no player. pGraphicManager->loadAsset(texturePath); // Retorna dimensão da imagem. dimension = pGraphicManager->getDimensionsOfAsset(texturePath); // Adiciona enemy na lista de entidades físicas colidiveis. pCollisionManager->addToLCollidablesPhysicalEntities((this)); } void Enemy::update(float t) { } // Método verifica colisão entre dois objetos da classe Entidade Física. void Enemy::collided(int idOther, Utilities::gameVector2F positionOther, Utilities::gameVector2F dimensionOther) { // Caso colida com Enemy. if ((idOther == 102) || (idOther == 103)) { // Cálculo da distância entre os enemy no momento da colisão. Utilities::gameVector2F distance = position - positionOther; // Medida para não manter um enemy preso dentro do outro. position += distance * (1 / 2); // std::cout << "OBJETO ENEMY >>> COLISAO COM OBJETO ENEMY." << std::endl; // Muda o sentido da velocidade em x. speed.coordX *= -1; // Muda o sentido da velocidade em y. speed.coordY *= -1; } } } } } }
51.152542
318
0.474818
edusidsan
a902cfee6f0885ca8c4c5a44f5d5425588582219
757
hpp
C++
src/roq/samples/zeromq/strategy.hpp
roq-trading/roq-examples
7b7d9508b624c7ec6d74e2fd0206796cf934263b
[ "BSD-3-Clause" ]
null
null
null
src/roq/samples/zeromq/strategy.hpp
roq-trading/roq-examples
7b7d9508b624c7ec6d74e2fd0206796cf934263b
[ "BSD-3-Clause" ]
null
null
null
src/roq/samples/zeromq/strategy.hpp
roq-trading/roq-examples
7b7d9508b624c7ec6d74e2fd0206796cf934263b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2022, Hans Erik Thrane */ #pragma once #include <arpa/inet.h> #include "roq/api.hpp" #include "roq/client.hpp" // note! thin wrappers around libzmq #include "roq/samples/zeromq/zmq/context.hpp" #include "roq/samples/zeromq/zmq/socket.hpp" namespace roq { namespace samples { namespace zeromq { // strategy implementation class Strategy final : public client::Handler { public: explicit Strategy(client::Dispatcher &); Strategy(Strategy &&) = default; Strategy(const Strategy &) = delete; protected: void operator()(const Event<TopOfBook> &) override; private: client::Dispatcher &dispatcher_; zmq::Context context_; zmq::Socket socket_; }; } // namespace zeromq } // namespace samples } // namespace roq
19.410256
53
0.714663
roq-trading
a9045f9e0fb0defe3869a05acf4a63b3bf08a65f
1,860
cpp
C++
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/dp_h_6221550_808_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/dp/tasks/dp_h H - Grid 1Editorial // ソースコードの引用元 : https://atcoder.jp/contests/dp/submissions/6221550 // 提出ID : 6221550 // 問題ID : dp_h // コンテストID : dp // ユーザID : xryuseix // コード長 : 2238 // 実行時間 : 19 */ #include <algorithm> #include <bitset> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<ll> vi; typedef vector<char> vc; typedef vector<string> vs; typedef vector<pair<ll, ll>> vpii; typedef vector<vector<ll>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; #define rep(i, n) for (ll i = 0; i < (n); ++i) #define rrep(i, n) for (ll i = 1; i <= (n); ++i) #define drep(i, n) for (ll i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << endl #define P 1000000007 int main(void) { ll h, w; cin >> h >> w; char grid[h][w]; ll path[h][w]; rep(i, h) rep(j, w) cin >> grid[i][j]; for (ll i = 0; i < h; i++) { for (ll j = 0; j < w; j++) { path[i][j] = 0; } } for (ll i = 0; i < w; i++) { if (grid[0][i] == '.') path[0][i] = 1; else break; } for (ll i = 0; i < h; i++) { if (grid[i][0] == '.') path[i][0] = 1; else break; } for (ll i = 1; i < h; i++) { for (ll j = 1; j < w; j++) { if (grid[i][j] == '#') path[i][j] = 0; else { path[i][j] = max(path[i][j], path[i - 1][j] + path[i][j - 1]); path[i][j] %= P; } } } cout << path[h - 1][w - 1] << endl; }
22.682927
78
0.499462
xryuseix
a907ac64e0a1b8f272e75afa3d08dc5eeb0f4f42
1,903
cc
C++
nn/simplenet/main/Simplenet.cc
research-note/Many-as-One
eb9520c30b4b2b944d4f3713aada256feaf322bc
[ "Apache-2.0" ]
null
null
null
nn/simplenet/main/Simplenet.cc
research-note/Many-as-One
eb9520c30b4b2b944d4f3713aada256feaf322bc
[ "Apache-2.0" ]
4
2021-11-13T23:49:46.000Z
2021-12-03T03:09:44.000Z
nn/simplenet/main/Simplenet.cc
research-note/Many-as-One
eb9520c30b4b2b944d4f3713aada256feaf322bc
[ "Apache-2.0" ]
2
2021-11-13T03:45:19.000Z
2021-11-13T03:47:42.000Z
/* Copyright 2021 The Many as One 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 <stdexcept> #include <utility> #include <random> template <typename T> Simplenet<T>::Simplenet(size_t width, size_t height) : mWidth(width) , mHeight(height) { mCells.resize(mWidth); for (auto& column : mCells) { column.resize(mHeight); } } template <typename T> void randomize() { random_device seeder; const auto seed = seeder.entropy() ? seeder() : time(nullptr); mt19937 eng(static_cast<mt19937::result_type>(seed)); normal_distribution<T> dist(0.0, 1.0); auto gen = bind(dist, eng); // for (auto& column : mCells) { // for (auto& row : column) { // row = gen(); // std::cout << ' ' << row << std::end; // } // std::cout << std::end; // } } template <typename T> void Simplenet<T>::verifyCoordinate(size_t x, size_t y) const { if (x >= mWidth || y >= mHeight) { throw std::out_of_range(""); } } template <typename T> const std::optional<T>& Simplenet<T>::at(size_t x, size_t y) const { verifyCoordinate(x, y); return mCells[x][y]; } template <typename T> std::optional<T>& Simplenet<T>::at(size_t x, size_t y) { return const_cast<std::optional<T>&>(std::as_const(*this).at(x, y)); }
28.402985
80
0.630583
research-note
a90a2e236f493055edc524d068f061a3d88f074c
581
cpp
C++
rotate-image.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
rotate-image.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
rotate-image.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
class Solution { public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { //A[i][j] -> A[j][n-1-i] -> A[n-1-i][n-1-j] -> A[n-1-j][i] -> A[i][j] int temp = matrix[j][n-i-1]; matrix[j][n-i-1] = matrix[i][j]; matrix[i][j] = matrix[n-j-1][i]; matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = temp; } } } };
27.666667
85
0.349398
5ooo
a90c0ad639940bfe3953ad0683c03bebad2f0616
11,888
cpp
C++
source/model/Model.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
source/model/Model.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
source/model/Model.cpp
sormo/simpleSDL
79a830a013f911c4670c86ccf68bd068a887670d
[ "MIT" ]
null
null
null
#include "Model.h" #include "OpenGL.h" #include "model_generated.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "utils/Texture.h" #include "utils/Shader.h" #include "Common.h" #include "CommonProject.h" #include "TextureManager.h" glm::mat4 Convert(const ModelData::Mat4 & m) { return glm::mat4{ { m.a1(), m.b1(), m.c1(), m.d1() }, { m.a2(), m.b2(), m.c2(), m.d2() }, { m.a3(), m.b3(), m.c3(), m.d3() }, { m.a4(), m.b4(), m.c4(), m.d4() } }; } Mesh::Mesh(const ModelData::MeshT & mesh, std::vector<std::unique_ptr<ModelMaterial>> & materials) { uint32_t materialIndex = mesh.material; if (materialIndex >= materials.size()) { printf("Error loading model, mesh has invalid material index (%d)", materialIndex); throw std::runtime_error("Error loading model."); } m_material = materials[materialIndex].get(); InitBuffers(mesh.positions, mesh.normals, mesh.texCoords, mesh.tangents, mesh.bitangents, mesh.indices); } Mesh::~Mesh() { glDeleteBuffers(1, &m_positions); glDeleteBuffers(1, &m_vboIndices); glDeleteBuffers(1, &m_normals); if (m_material->shader->GetConfig().GetUVChannelsCount()) glDeleteBuffers(m_texCoords.size(), m_texCoords.data()); if (m_material->shader->GetConfig().textures.normal.size()) { glDeleteBuffers(1, &m_tangents); glDeleteBuffers(1, &m_bitangents); } if (IsVAOSupported()) glDeleteVertexArrays(1, &m_vao); } void Mesh::BindUniforms(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { glm::mat4 MVP = projection * view * model; m_material->shader->GetShader().SetUniform(MVP, "MVP"); m_material->shader->GetShader().SetUniform(model, "M"); } void Mesh::BindBuffers() { if (IsVAOSupported()) { m_material->shader->GetShader().BindVAO(m_vao); } else { m_material->shader->GetShader().BindBuffer<glm::vec3>(m_positions, m_material->shader->GetLocations().buffers.positions); m_material->shader->GetShader().BindBuffer<glm::vec3>(m_normals, m_material->shader->GetLocations().buffers.normals); for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i) m_material->shader->GetShader().BindBuffer<glm::vec2>(m_texCoords[i], m_material->shader->GetLocations().buffers.texCoords[i]); if (m_material->shader->GetConfig().textures.normal.size()) { m_material->shader->GetShader().BindBuffer<glm::vec3>(m_tangents, m_material->shader->GetLocations().buffers.tangents); //m_material->shader->GetShader().BindBuffer<glm::vec3>(m_bitangents, m_shader->GetLocations().buffers.bitangents); } } // TODO can be bound to VAO ??? m_material->shader->GetShader().BindElementBuffer(m_vboIndices); } // render the mesh void Mesh::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { m_material->shader->BeginRender(); m_material->shader->BindTransform(model, view, projection); m_material->shader->BindTextures(m_material->textures); BindBuffers(); glDrawElements(GL_TRIANGLES, m_verticesCount, GL_UNSIGNED_SHORT, (void*)0); CheckGlError("glDrawElements"); m_material->shader->EndRender(); } template<class T, uint32_t N> GLuint CreateFloatVBO(GLuint index, const T * data, size_t size, bool isVaoBinded) { GLuint vbo; glGenBuffers(1, &vbo); CheckGlError("glGenBuffers"); glBindBuffer(GL_ARRAY_BUFFER, vbo); CheckGlError("glBindBuffer"); glBufferData(GL_ARRAY_BUFFER, size*sizeof(T), data, GL_STATIC_DRAW); CheckGlError("glBufferData"); if (isVaoBinded) { glEnableVertexAttribArray(index); CheckGlError("glEnableVertexAttribArray"); glVertexAttribPointer(index, N, GL_FLOAT, GL_FALSE, 0, nullptr); CheckGlError("glVertexAttribPointer"); } return vbo; } template<class T, uint32_t N> GLuint CreateFloatVBO(GLuint index, const std::vector<T> & data, bool isVaoBinded) { return CreateFloatVBO<T, N>(index, &data[0], data.size(), isVaoBinded); } void Mesh::InitBuffers(const std::vector<ModelData::Vec3> & positions, const std::vector<ModelData::Vec3> & normals, const std::vector<ModelData::Vec2> & texCoords, const std::vector<ModelData::Vec3> & tangents, const std::vector<ModelData::Vec3> & bitangents, const std::vector<uint16_t> & indices) { bool bindVAO = IsVAOSupported(); // prepare and bind VAO if possible if (bindVAO) { glGenVertexArrays(1, &m_vao); CheckGlError("glGenVertexArrays"); glBindVertexArray(m_vao); CheckGlError("glBindVertexArray"); } m_positions = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("positionModelSpace", Shader::LocationType::Attrib), positions, bindVAO); m_normals = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("normalModelSpace", Shader::LocationType::Attrib), normals, bindVAO); if (m_material->shader->GetConfig().textures.normal.size()) { m_tangents = CreateFloatVBO<ModelData::Vec3, 3>(m_material->shader->GetShader().GetLocation("tangentModelSpace", Shader::LocationType::Attrib), tangents, bindVAO); //m_bitangents = CreateFloatVBO<ModelData::Vec3, 3>(m_shader->GetShader().GetLocation("bitangentModelSpace", Shader::LocationType::Attrib), bitangents, bindVAO); } for (uint32_t i = 0; i < m_material->shader->GetConfig().GetUVChannelsCount(); ++i) { m_texCoords.push_back(CreateFloatVBO<ModelData::Vec2, 2>(m_material->shader->GetShader().GetLocation("vertexUV" + std::to_string(i), Shader::LocationType::Attrib), &texCoords[i * positions.size()], positions.size(), bindVAO)); } glBindVertexArray(0); // TODO can be element buffer binded to vao ??? glGenBuffers(1, &m_vboIndices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_vboIndices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(uint16_t), &indices[0], GL_STATIC_DRAW); m_verticesCount = indices.size(); } ModelShader::TextureStackEntry::Operation Convert(ModelData::TextureOperation operation) { switch (operation) { case ModelData::TextureOperation_Add: return ModelShader::TextureStackEntry::Operation::Add; case ModelData::TextureOperation_Multiply: return ModelShader::TextureStackEntry::Operation::Multiply; case ModelData::TextureOperation_Substract: return ModelShader::TextureStackEntry::Operation::Substract; case ModelData::TextureOperation_Divide: return ModelShader::TextureStackEntry::Operation::Divide; case ModelData::TextureOperation_SmoothAdd: return ModelShader::TextureStackEntry::Operation::SmoothAdd; case ModelData::TextureOperation_SignedAdd: return ModelShader::TextureStackEntry::Operation::SignedAdd; } return ModelShader::TextureStackEntry::Operation::Add; } bool ProcessTextures(const std::string & root, std::vector<std::unique_ptr<ModelData::TextureT>> & data, std::vector<ModelShader::TextureStackEntry> & stack, std::vector<GLuint> & textures) { for (size_t i = 0; i < data.size(); ++i) { ModelShader::TextureStackEntry entry; entry.factor = data[i]->blendFactor; entry.operation = Convert(data[i]->operation); entry.uvIndex = data[i]->uvIndex; auto texture = TextureManager::Instance().GetTexture((root + data[i]->path).c_str()); if (!texture) { printf("Error loading texture %s", (root + data[i]->path).c_str()); return false; } textures.push_back(*texture); stack.push_back(entry); } return true; } std::unique_ptr<ModelMaterial> Model::CreateMaterial(const std::string & root, ModelData::MaterialT & material) { ModelShader::Config config; std::unique_ptr<ModelMaterial> result = std::make_unique<ModelMaterial>(); config.light = m_configLight; memset(&config.material, 0, sizeof(config.material)); if (material.ambient) config.material.ambient = Convert(*material.ambient); if (material.diffuse) config.material.diffuse = Convert(*material.diffuse); if (material.specular) config.material.specular = Convert(*material.specular); config.material.shininess = material.shininess; config.material.shininessStrength = material.shininessStrength; if (!ProcessTextures(root, material.textureAmbient, config.textures.ambient, result->textures.ambient)) return nullptr; if (!ProcessTextures(root, material.textureDiffuse, config.textures.diffuse, result->textures.diffuse)) return nullptr; if (!ProcessTextures(root, material.textureSpecular, config.textures.specular, result->textures.specular)) return nullptr; if (!ProcessTextures(root, material.textureNormal, config.textures.normal, result->textures.normal)) return nullptr; if (!ProcessTextures(root, material.textureLightmap, config.textures.lightmap, result->textures.lightmap)) return nullptr; config.shading = ModelShader::ShadingModel::BlinnPhong; result->shader = std::make_unique<ModelShader>(config); if (!result->shader.get()) return nullptr; return result; } Model::Model(const char * path, Light::Config light) : m_configLight(light) { auto data = Common::ReadFile(path); auto model = ModelData::UnPackModel(data.data()); auto root = Common::GetDirectoryFromFilePath(path); // process materials ProcessMaterials(model.get(), root); // process meshes ProcessMeshes(model.get()); // recursively process tree m_tree = ProcessTree(*model->tree); } Model::~Model() { // clear meshes before materials m_meshes.clear(); } void Model::ProcessMaterials(ModelData::ModelT * model, const std::string & root) { for (size_t i = 0; i < model->materials.size(); ++i) { auto material = CreateMaterial(root, *model->materials[i].get()); if (!material) { printf("Error creating material."); throw std::runtime_error("Error creating material."); } m_materials.push_back(std::move(material)); } } void Model::ProcessMeshes(ModelData::ModelT * model) { for (size_t i = 0; i < model->meshes.size(); ++i) { // TODO check is mesh constructed successfully m_meshes.push_back(std::make_unique<Mesh>(*model->meshes[i].get(), m_materials)); } } Model::Tree Model::ProcessTree(ModelData::TreeT & node) { Model::Tree result; result.transform = Convert(*node.transform); result.meshes = node.meshes; for (auto & child : node.childs) result.childs.push_back(ProcessTree(*child)); return result; } void Model::Bind(const Data & data) { for (auto & material : m_materials) { material->shader->BeginRender(); material->shader->BindCamera(data.cameraWorldSpace); material->shader->BindLight(data.light); material->shader->BindMaterial(data.material); material->shader->EndRender(); } } void Model::Draw(const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { DrawInternal(m_tree, model, view, projection); } void Model::DrawInternal(Tree & tree, const glm::mat4 & model, const glm::mat4 & view, const glm::mat4 & projection) { glm::mat4 nodeModel = model * tree.transform; //glm::mat4 nodeModel = model; for (uint32_t i : tree.meshes) m_meshes[i]->Draw(nodeModel, view, projection); for (Tree & child : tree.childs) DrawInternal(child, nodeModel, view, projection); }
33.965714
189
0.672527
sormo
a90f9d7637d0ef9210d781ad9adf49453fa08067
317
hpp
C++
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/game/CityAreaType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace game { enum class CityAreaType : uint32_t { Undefined = 0, PublicZone = 1, SafeZone = 2, RestrictedZone = 3, DangerousZone = 4, }; } // namespace game } // namespace RED4ext
16.684211
57
0.678233
jackhumbert
a911e7c5a1bfe9267b42dd3ca297bf4fd789b61b
2,662
hpp
C++
src/main/include/communications/PublishNode.hpp
MattSa952073/PubSubLub
a20bd82d72f3d5a1599234d638afd578259f3553
[ "BSD-2-Clause" ]
null
null
null
src/main/include/communications/PublishNode.hpp
MattSa952073/PubSubLub
a20bd82d72f3d5a1599234d638afd578259f3553
[ "BSD-2-Clause" ]
null
null
null
src/main/include/communications/PublishNode.hpp
MattSa952073/PubSubLub
a20bd82d72f3d5a1599234d638afd578259f3553
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2018-2019 FRC Team 3512. All Rights Reserved. #pragma once #include <atomic> #include <condition_variable> #include <string> #include <thread> #include <vector> #include <frc/circular_buffer.h> #include "communications/PublishNodeBase.hpp" namespace frc3512 { /** * A communication layer that can pass messages between others who have * inherited it through a publish-subscribe architecture */ class PublishNode : public PublishNodeBase { public: /** * Construct a PublishNode. * * @param nodeName Name of node. */ explicit PublishNode(std::string nodeName = "Misc"); virtual ~PublishNode(); /** * Adds this object to the specified PublishNode's subscriber list. * * @param publisher The PublishNode that this instance wants to recieve * event from. */ void Subscribe(PublishNode& publisher); /** * Removes this object from the specified PublishNode's subscriber list. * * @param publisher The PublishNode that this instance wants to stop * recieving event from. */ void Unsubscribe(PublishNode& publisher); /** * Get the button value (starting at button 1). * * The buttons are returned in a single 16 bit value with one bit * representing the state of each button. The appropriate button is returned * as a boolean value. * * @param message The message whose member variables contain deserialized * data. * @param joystick The joystick number. * @param button The button number to be read (starting at 1). * @return The state of the button. */ static bool GetRawButton(const HIDPacket& msg, int joystick, int button); /** * Sends a packet to every subscriber. * * @param p Any packet with a Serialize() method. */ template <class P> void Publish(P p); /** * Sends a packet to the object it's called on. * * @param p Any packet with a Serialize() method. */ template <class P> void PushMessage(P p); private: static constexpr int kNodeQueueSize = 1024; std::string m_nodeName; std::vector<PublishNode*> m_subList; frc::circular_buffer<char> m_queue{kNodeQueueSize}; std::thread m_thread; std::atomic<bool> m_isRunning{true}; std::condition_variable m_ready; /** * Blocks the thread until the queue receives at least one set of characters * of a message or until the node deconstructs, then processes each message. */ void RunFramework(); }; } // namespace frc3512 #include "PublishNode.inc"
26.888889
80
0.654395
MattSa952073
a91368140c5cc9f9ac4178c80b0985b4212cf130
29,900
cpp
C++
src/armnn/Runtime.cpp
Srivathsav-max/armnn-clone
af2daa6526623c91ee97f7141be4d1b07de92a48
[ "MIT" ]
1
2022-03-31T18:21:59.000Z
2022-03-31T18:21:59.000Z
src/armnn/Runtime.cpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
null
null
null
src/armnn/Runtime.cpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "Runtime.hpp" #include <armnn/Version.hpp> #include <armnn/BackendRegistry.hpp> #include <armnn/BackendHelper.hpp> #include <armnn/Logging.hpp> #include <armnn/utility/Timer.hpp> #include <armnn/backends/IBackendContext.hpp> #include <backendsCommon/DynamicBackendUtils.hpp> #include <backendsCommon/memoryOptimizerStrategyLibrary/MemoryOptimizerStrategyLibrary.hpp> #include <armnn/utility/PolymorphicDowncast.hpp> #include <common/include/LabelsAndEventClasses.hpp> #include <iostream> #include <backends/BackendProfiling.hpp> using namespace armnn; using namespace std; namespace armnn { IRuntime::IRuntime() : pRuntimeImpl( new RuntimeImpl(armnn::IRuntime::CreationOptions())) {} IRuntime::IRuntime(const IRuntime::CreationOptions& options) : pRuntimeImpl(new RuntimeImpl(options)) {} IRuntime::~IRuntime() = default; IRuntime* IRuntime::CreateRaw(const CreationOptions& options) { return new IRuntime(options); } IRuntimePtr IRuntime::Create(const CreationOptions& options) { return IRuntimePtr(CreateRaw(options), &IRuntime::Destroy); } void IRuntime::Destroy(IRuntime* runtime) { delete runtime; } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network)); } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network, std::string& errorMessage) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage); } Status IRuntime::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network, std::string& errorMessage, const INetworkProperties& networkProperties) { return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage, networkProperties); } armnn::TensorInfo IRuntime::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return pRuntimeImpl->GetInputTensorInfo(networkId, layerId); } armnn::TensorInfo IRuntime::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return pRuntimeImpl->GetOutputTensorInfo(networkId, layerId); } std::vector<ImportedInputId> IRuntime::ImportInputs(NetworkId networkId, const InputTensors& inputTensors, MemorySource forceImportMemorySource) { return pRuntimeImpl->ImportInputs(networkId, inputTensors, forceImportMemorySource); } std::vector<ImportedOutputId> IRuntime::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors, MemorySource forceImportMemorySource) { return pRuntimeImpl->ImportOutputs(networkId, outputTensors, forceImportMemorySource); } void IRuntime::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds) { return pRuntimeImpl->ClearImportedInputs(networkId, inputIds); } void IRuntime::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds) { return pRuntimeImpl->ClearImportedOutputs(networkId, outputIds); } Status IRuntime::EnqueueWorkload(NetworkId networkId, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputIds, std::vector<ImportedOutputId> preImportedOutputIds) { return pRuntimeImpl->EnqueueWorkload(networkId, inputTensors, outputTensors, preImportedInputIds, preImportedOutputIds); } Status IRuntime::Execute(IWorkingMemHandle& workingMemHandle, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputs, std::vector<ImportedOutputId> preImportedOutputs) { return pRuntimeImpl->Execute(workingMemHandle, inputTensors, outputTensors, preImportedInputs, preImportedOutputs); } Status IRuntime::UnloadNetwork(NetworkId networkId) { return pRuntimeImpl->UnloadNetwork(networkId); } const IDeviceSpec& IRuntime::GetDeviceSpec() const { return pRuntimeImpl->GetDeviceSpec(); } std::unique_ptr<IWorkingMemHandle> IRuntime::CreateWorkingMemHandle(NetworkId networkId) { return pRuntimeImpl->CreateWorkingMemHandle(networkId); } const std::shared_ptr<IProfiler> IRuntime::GetProfiler(NetworkId networkId) const { return pRuntimeImpl->GetProfiler(networkId); } void IRuntime::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func) { return pRuntimeImpl->RegisterDebugCallback(networkId, func); } int RuntimeImpl::GenerateNetworkId() { return m_NetworkIdCounter++; } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork) { std::string ignoredErrorMessage; return LoadNetwork(networkIdOut, std::move(inNetwork), ignoredErrorMessage); } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork, std::string& errorMessage) { INetworkProperties networkProperties( false, MemorySource::Undefined, MemorySource::Undefined); return LoadNetwork(networkIdOut, std::move(inNetwork), errorMessage, networkProperties); } Status RuntimeImpl::LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr inNetwork, std::string& errorMessage, const INetworkProperties& networkProperties) { // Register the profiler auto profiler = inNetwork->GetProfiler(); ProfilerManager::GetInstance().RegisterProfiler(profiler.get()); IOptimizedNetwork* rawNetwork = inNetwork.release(); networkIdOut = GenerateNetworkId(); for (auto&& context : m_BackendContexts) { context.second->BeforeLoadNetwork(networkIdOut); } unique_ptr<LoadedNetwork> loadedNetwork = LoadedNetwork::MakeLoadedNetwork( std::unique_ptr<IOptimizedNetwork>(rawNetwork), errorMessage, networkProperties, m_ProfilingService); if (!loadedNetwork) { return Status::Failure; } { std::lock_guard<std::mutex> lockGuard(m_Mutex); // Stores the network m_LoadedNetworks[networkIdOut] = std::move(loadedNetwork); } for (auto&& context : m_BackendContexts) { context.second->AfterLoadNetwork(networkIdOut); } if (m_ProfilingService.IsProfilingEnabled()) { m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_LOADS); } return Status::Success; } Status RuntimeImpl::UnloadNetwork(NetworkId networkId) { bool unloadOk = true; for (auto&& context : m_BackendContexts) { unloadOk &= context.second->BeforeUnloadNetwork(networkId); } if (!unloadOk) { ARMNN_LOG(warning) << "RuntimeImpl::UnloadNetwork(): failed to unload " "network with ID:" << networkId << " because BeforeUnloadNetwork failed"; return Status::Failure; } std::unique_ptr<profiling::TimelineUtilityMethods> timelineUtils = profiling::TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); { std::lock_guard<std::mutex> lockGuard(m_Mutex); // If timeline recording is on mark the Network end of life if (timelineUtils) { auto search = m_LoadedNetworks.find(networkId); if (search != m_LoadedNetworks.end()) { profiling::ProfilingGuid networkGuid = search->second->GetNetworkGuid(); timelineUtils->RecordEvent(networkGuid, profiling::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS); } } if (m_LoadedNetworks.erase(networkId) == 0) { ARMNN_LOG(warning) << "WARNING: RuntimeImpl::UnloadNetwork(): " << networkId << " not found!"; return Status::Failure; } if (m_ProfilingService.IsProfilingEnabled()) { m_ProfilingService.IncrementCounterValue(armnn::profiling::NETWORK_UNLOADS); } } for (auto&& context : m_BackendContexts) { context.second->AfterUnloadNetwork(networkId); } // Unregister the profiler ProfilerManager::GetInstance().RegisterProfiler(nullptr); ARMNN_LOG(debug) << "RuntimeImpl::UnloadNetwork(): Unloaded network with ID: " << networkId; return Status::Success; } const std::shared_ptr<IProfiler> RuntimeImpl::GetProfiler(NetworkId networkId) const { auto it = m_LoadedNetworks.find(networkId); if (it != m_LoadedNetworks.end()) { auto& loadedNetwork = it->second; return loadedNetwork->GetProfiler(); } return nullptr; } void RuntimeImpl::ReportStructure() // armnn::profiling::IProfilingService& profilingService as param { // No-op for the time being, but this may be useful in future to have the profilingService available // if (profilingService.IsProfilingEnabled()){} LoadedNetworks::iterator it = m_LoadedNetworks.begin(); while (it != m_LoadedNetworks.end()) { auto& loadedNetwork = it->second; loadedNetwork->SendNetworkStructure(); // Increment the Iterator to point to next entry it++; } } RuntimeImpl::RuntimeImpl(const IRuntime::CreationOptions& options) : m_NetworkIdCounter(0), m_ProfilingService(*this) { const auto start_time = armnn::GetTimeNow(); ARMNN_LOG(info) << "ArmNN v" << ARMNN_VERSION; if ( options.m_ProfilingOptions.m_TimelineEnabled && !options.m_ProfilingOptions.m_EnableProfiling ) { throw RuntimeException( "It is not possible to enable timeline reporting without profiling being enabled"); } // Load any available/compatible dynamic backend before the runtime // goes through the backend registry LoadDynamicBackends(options.m_DynamicBackendsPath); BackendIdSet supportedBackends; for (const auto& id : BackendRegistryInstance().GetBackendIds()) { // Store backend contexts for the supported ones try { auto factoryFun = BackendRegistryInstance().GetFactory(id); ARMNN_ASSERT(factoryFun != nullptr); auto backend = factoryFun(); ARMNN_ASSERT(backend != nullptr); ARMNN_ASSERT(backend.get() != nullptr); auto customAllocatorMapIterator = options.m_CustomAllocatorMap.find(id); if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end() && customAllocatorMapIterator->second == nullptr) { // We need to manually clean up the dynamic backends before throwing an exception. DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends()); m_DeviceSpec.ClearDynamicBackends(); throw armnn::Exception("Allocator associated with id " + id.Get() + " is null"); } // If the runtime is created in protected mode only add backends that support this mode if (options.m_ProtectedMode) { // check if backend supports ProtectedMode using BackendCapability = BackendOptions::BackendOption; BackendCapability protectedContentCapability {"ProtectedContentAllocation", true}; if (!HasCapability(protectedContentCapability, id)) { // Protected Content Allocation is not supported by the backend // backend should not be registered ARMNN_LOG(warning) << "Backend " << id << " is not registered as does not support protected content allocation."; continue; } // The user is responsible to provide a custom memory allocator which allows to allocate // protected memory if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end()) { std::string err; if (customAllocatorMapIterator->second->GetMemorySourceType() == armnn::MemorySource::DmaBufProtected) { if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err)) { ARMNN_LOG(error) << "The backend " << id << " reported an error when entering protected mode. Backend won't be" << " used. ErrorMsg: " << err; continue; } // No errors so register the Custom Allocator with the BackendRegistry BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second); } else { ARMNN_LOG(error) << "The CustomAllocator provided with the runtime options doesn't support " "protected memory. Protected mode can't be activated. The backend " << id << " is not going to be used. MemorySource must be MemorySource::DmaBufProtected"; continue; } } else { ARMNN_LOG(error) << "Protected mode can't be activated for backend: " << id << " no custom allocator was provided to the runtime options."; continue; } } else { // If a custom memory allocator is provided make the backend use that instead of the default if (customAllocatorMapIterator != options.m_CustomAllocatorMap.end()) { std::string err; if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err)) { ARMNN_LOG(error) << "The backend " << id << " reported an error when trying to use the provided custom allocator." " Backend won't be used." << " ErrorMsg: " << err; continue; } // No errors so register the Custom Allocator with the BackendRegistry BackendRegistryInstance().RegisterAllocator(id, customAllocatorMapIterator->second); } } // check if custom memory optimizer strategy map is set if (!options.m_MemoryOptimizerStrategyMap.empty()) { auto customMemoryOptimizerStrategyMapIterator = options.m_MemoryOptimizerStrategyMap.find(id); // if a memory optimizer strategy is provided make the backend use that instead of the default if (customMemoryOptimizerStrategyMapIterator != options.m_MemoryOptimizerStrategyMap.end()) { // no errors.. register the memory optimizer strategy with the BackendRegistry BackendRegistryInstance().RegisterMemoryOptimizerStrategy( id, customMemoryOptimizerStrategyMapIterator->second); ARMNN_LOG(info) << "MemoryOptimizerStrategy " << customMemoryOptimizerStrategyMapIterator->second->GetName() << " set for the backend " << id << "."; } } else { // check if to use one of the existing memory optimizer strategies is set std::string memoryOptimizerStrategyName = ""; ParseOptions(options.m_BackendOptions, id, [&](std::string name, const BackendOptions::Var& value) { if (name == "MemoryOptimizerStrategy") { memoryOptimizerStrategyName = ParseStringBackendOption(value, ""); } }); if (memoryOptimizerStrategyName != "") { std::shared_ptr<IMemoryOptimizerStrategy> strategy = GetMemoryOptimizerStrategy(memoryOptimizerStrategyName); if (!strategy) { ARMNN_LOG(warning) << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << " was not found."; } else { using BackendCapability = BackendOptions::BackendOption; auto strategyType = GetMemBlockStrategyTypeName(strategy->GetMemBlockStrategyType()); BackendCapability memOptimizeStrategyCapability {strategyType, true}; if (HasCapability(memOptimizeStrategyCapability, id)) { BackendRegistryInstance().RegisterMemoryOptimizerStrategy(id, strategy); ARMNN_LOG(info) << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << " set for the backend " << id << "."; } else { ARMNN_LOG(warning) << "Backend " << id << " does not have multi-axis packing capability and cannot support" << "MemoryOptimizerStrategy: " << memoryOptimizerStrategyName << "."; } } } } auto context = backend->CreateBackendContext(options); // backends are allowed to return nullptrs if they // don't wish to create a backend specific context if (context) { m_BackendContexts.emplace(std::make_pair(id, std::move(context))); } supportedBackends.emplace(id); unique_ptr<armnn::profiling::IBackendProfiling> profilingIface = std::make_unique<armnn::profiling::BackendProfiling>(armnn::profiling::BackendProfiling( options, m_ProfilingService, id)); // Backends may also provide a profiling context. Ask for it now. auto profilingContext = backend->CreateBackendProfilingContext(options, profilingIface); // Backends that don't support profiling will return a null profiling context. if (profilingContext) { // Pass the context onto the profiling service. m_ProfilingService.AddBackendProfilingContext(id, profilingContext); } } catch (const BackendUnavailableException&) { // Ignore backends which are unavailable } } BackendRegistryInstance().SetProfilingService(m_ProfilingService); // pass configuration info to the profiling service m_ProfilingService.ConfigureProfilingService(options.m_ProfilingOptions); if (options.m_ProfilingOptions.m_EnableProfiling) { // try to wait for the profiling service to initialise m_ProfilingService.WaitForProfilingServiceActivation(3000); } m_DeviceSpec.AddSupportedBackends(supportedBackends); ARMNN_LOG(info) << "Initialization time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(start_time).count() << " ms."; } RuntimeImpl::~RuntimeImpl() { const auto startTime = armnn::GetTimeNow(); std::vector<int> networkIDs; try { // Coverity fix: The following code may throw an exception of type std::length_error. std::transform(m_LoadedNetworks.begin(), m_LoadedNetworks.end(), std::back_inserter(networkIDs), [](const auto &pair) { return pair.first; }); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: An error has occurred when getting the IDs of the networks to unload: " << e.what() << "\nSome of the loaded networks may not be unloaded" << std::endl; } // We then proceed to unload all the networks which IDs have been appended to the list // up to the point the exception was thrown (if any). for (auto networkID : networkIDs) { try { // Coverity fix: UnloadNetwork() may throw an exception of type std::length_error, // boost::log::v2s_mt_posix::odr_violation or boost::log::v2s_mt_posix::system_error UnloadNetwork(networkID); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: An error has occurred when unloading network " << networkID << ": " << e.what() << std::endl; } } // Clear all dynamic backends. DynamicBackendUtils::DeregisterDynamicBackends(m_DeviceSpec.GetDynamicBackends()); m_DeviceSpec.ClearDynamicBackends(); m_BackendContexts.clear(); BackendRegistryInstance().SetProfilingService(armnn::EmptyOptional()); ARMNN_LOG(info) << "Shutdown time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; } LoadedNetwork* RuntimeImpl::GetLoadedNetworkPtr(NetworkId networkId) const { std::lock_guard<std::mutex> lockGuard(m_Mutex); return m_LoadedNetworks.at(networkId).get(); } TensorInfo RuntimeImpl::GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return GetLoadedNetworkPtr(networkId)->GetInputTensorInfo(layerId); } TensorInfo RuntimeImpl::GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const { return GetLoadedNetworkPtr(networkId)->GetOutputTensorInfo(layerId); } std::vector<ImportedInputId> RuntimeImpl::ImportInputs(NetworkId networkId, const InputTensors& inputTensors, MemorySource forceImportMemorySource) { return GetLoadedNetworkPtr(networkId)->ImportInputs(inputTensors, forceImportMemorySource); } std::vector<ImportedOutputId> RuntimeImpl::ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors, MemorySource forceImportMemorySource) { return GetLoadedNetworkPtr(networkId)->ImportOutputs(outputTensors, forceImportMemorySource); } void RuntimeImpl::ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds) { return GetLoadedNetworkPtr(networkId)->ClearImportedInputs(inputIds); } void RuntimeImpl::ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds) { return GetLoadedNetworkPtr(networkId)->ClearImportedOutputs(outputIds); } Status RuntimeImpl::EnqueueWorkload(NetworkId networkId, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputIds, std::vector<ImportedOutputId> preImportedOutputIds) { const auto startTime = armnn::GetTimeNow(); LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return Status::Failure; } if (loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Network " << networkId << " is async enabled."; return Status::Failure; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "EnqueueWorkload"); static thread_local NetworkId lastId = networkId; if (lastId != networkId) { LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network) { network->FreeWorkingMemory(); }); } lastId=networkId; auto status = loadedNetwork->EnqueueWorkload(inputTensors, outputTensors, preImportedInputIds, preImportedOutputIds); // Check if we imported, if not there's no need to call the After EnqueueWorkload events if (!preImportedInputIds.empty() || !preImportedOutputIds.empty()) { // Call After EnqueueWorkload events for (auto&& context : m_BackendContexts) { context.second->AfterEnqueueWorkload(networkId); } } ARMNN_LOG(info) << "Execution time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; return status; } Status RuntimeImpl::Execute(IWorkingMemHandle& iWorkingMemHandle, const InputTensors& inputTensors, const OutputTensors& outputTensors, std::vector<ImportedInputId> preImportedInputs, std::vector<ImportedOutputId> preImportedOutputs) { const auto startTime = armnn::GetTimeNow(); NetworkId networkId = iWorkingMemHandle.GetNetworkId(); LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return Status::Failure; } if (!loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Attempting execute " << networkId << " when it is not async enabled."; return Status::Failure; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "Execute"); auto status = loadedNetwork->Execute(inputTensors, outputTensors, iWorkingMemHandle, preImportedInputs, preImportedOutputs); ARMNN_LOG(info) << "Execution time: " << std::setprecision(2) << std::fixed << armnn::GetTimeDuration(startTime).count() << " ms."; return status; } /// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have /// overlapped Execution by calling this function from different threads. std::unique_ptr<IWorkingMemHandle> RuntimeImpl::CreateWorkingMemHandle(NetworkId networkId) { LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); if (!loadedNetwork) { ARMNN_LOG(error) << "A Network with an id of " << networkId << " does not exist."; return nullptr; } if (!loadedNetwork->IsAsyncEnabled()) { ARMNN_LOG(error) << "Network " << networkId << " is not async enabled."; return nullptr; } ProfilerManager::GetInstance().RegisterProfiler(loadedNetwork->GetProfiler().get()); ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "CreateWorkingMemHandle"); static thread_local NetworkId lastId = networkId; if (lastId != networkId) { LoadedNetworkFuncSafe(lastId, [](LoadedNetwork* network) { network->FreeWorkingMemory(); }); } lastId=networkId; return loadedNetwork->CreateWorkingMemHandle(networkId); } void RuntimeImpl::RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func) { LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId); loadedNetwork->RegisterDebugCallback(func); } void RuntimeImpl::LoadDynamicBackends(const std::string& overrideBackendPath) { // Get the paths where to load the dynamic backends from std::vector<std::string> backendPaths = DynamicBackendUtils::GetBackendPaths(overrideBackendPath); // Get the shared objects to try to load as dynamic backends std::vector<std::string> sharedObjects = DynamicBackendUtils::GetSharedObjects(backendPaths); // Create a list of dynamic backends m_DynamicBackends = DynamicBackendUtils::CreateDynamicBackends(sharedObjects); // Register the dynamic backends in the backend registry BackendIdSet registeredBackendIds = DynamicBackendUtils::RegisterDynamicBackends(m_DynamicBackends); // Add the registered dynamic backend ids to the list of supported backends m_DeviceSpec.AddSupportedBackends(registeredBackendIds, true); } } // namespace armnn
40.242261
119
0.621605
Srivathsav-max
a913bc466d97d9bf64475a01ab64256980fa1294
6,670
hpp
C++
src/base/util/TimeSystemConverter.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/util/TimeSystemConverter.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/util/TimeSystemConverter.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // TimeSystemConverter //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Allison Greene // Created: 2005/02/03 // /** * Definition of the TimeSystemConverter class */ //------------------------------------------------------------------------------ #ifndef TimeSystemConverter_hpp #define TimeSystemConverter_hpp //#include <iostream> //#include <iomanip> //#include <sstream> //#include "BaseException.hpp" #include "EopFile.hpp" #include "LeapSecsFileReader.hpp" //#include "GmatConstants.hpp" // struct TimeSystemConverterExceptions // { class GMAT_API UnimplementedException : public BaseException { public: UnimplementedException(const std::string &message = "TimeSystemConverter: Conversion not implemented: ") : BaseException(message) {}; }; class GMAT_API TimeFileException : public BaseException { public: TimeFileException(const std::string &message = "TimeSystemConverter: File is unknown: ") : BaseException(message) {}; }; class GMAT_API TimeFormatException : public BaseException { public: TimeFormatException(const std::string &message = "TimeSystemConverter: Requested format not implemented: ") : BaseException(message) {}; }; class GMAT_API InvalidTimeException : public BaseException { public: InvalidTimeException(const std::string &message = "TimeSystemConverter: Requested time is invalid: ") : BaseException(message) {}; }; // }; namespace TimeConverterUtil { // Specified in Math Spec section 2.3 static const Real TDB_COEFF1 = 0.001658; static const Real TDB_COEFF2 = 0.00001385; static const Real M_E_OFFSET = 357.5277233; static const Real M_E_COEFF1 = 35999.05034; static const Real T_TT_OFFSET = GmatTimeConstants::JD_OF_J2000; static const Real T_TT_COEFF1 = GmatTimeConstants::DAYS_PER_JULIAN_CENTURY; static const Real L_B = 1.550505e-8; static const Real NUM_SECS = GmatTimeConstants::SECS_PER_DAY; enum TimeSystemTypes { A1MJD = 0, TAIMJD, UTCMJD, UT1MJD, TDBMJD, TTMJD, A1, TAI, UTC, UT1, TDB, TT, TimeSystemCount }; static const std::string TIME_SYSTEM_TEXT[TimeSystemCount] = { "A1Mjd", "TaiMjd", "UtcMjd", "Ut1Mjd", "TdbMjd", "TtMjd", // New entries added by DJC "A1", "TAI", "UTC", "UT1", "TDB", "TT", }; /* Real Convert(const Real origValue, const std::string &fromType, const std::string &toType, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real ConvertToTaiMjd(std::string fromType, Real origValue, Real refJd= GmatTimeConstants::JD_NOV_17_1858); Real ConvertFromTaiMjd(std::string toType, Real origValue, Real refJd= GmatTimeConstants::JD_NOV_17_1858); */ Integer GMAT_API GetTimeTypeID(std::string &str); Real GMAT_API Convert(const Real origValue, const Integer fromType, const Integer toType, Real refJd = GmatTimeConstants::JD_JAN_5_1941); Real GMAT_API ConvertToTaiMjd(Integer fromType, Real origValue, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real GMAT_API ConvertFromTaiMjd(Integer toType, Real origValue, Real refJd = GmatTimeConstants::JD_NOV_17_1858); Real GMAT_API NumberOfLeapSecondsFrom(Real utcMjd, Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941); Real GMAT_API GetFirstLeapSecondMJD(Real fromUtcMjd, Real toUtcMjd, Real jdOfMjdRef = GmatTimeConstants::JD_JAN_5_1941); void GMAT_API SetEopFile(EopFile *eopFile); void GMAT_API SetLeapSecsFileReader(LeapSecsFileReader *leapSecsFileReader); void GMAT_API GetTimeSystemAndFormat(const std::string &type, std::string &system, std::string &format); std::string GMAT_API ConvertMjdToGregorian(const Real mjd, bool handleLeapSecond = false, Integer format = 1); Real GMAT_API ConvertGregorianToMjd(const std::string &greg); void GMAT_API Convert(const char *fromType, Real fromMjd, const char *fromStr, const char *toType, Real &toMjd, std::string &toStr, Integer format = 1); void GMAT_API Convert(const char *fromType, Real fromMjd, const std::string &fromStr, const std::string &toType, Real &toMjd, std::string &toStr, Integer format = 1); void GMAT_API Convert(const std::string &fromType, Real fromMjd, const std::string &fromStr, const std::string &toType, Real &toMjd, std::string &toStr, Integer format = 1); bool GMAT_API ValidateTimeSystem(std::string sys); bool GMAT_API ValidateTimeFormat(const std::string &format, const std::string &value, bool checkValue = true); StringArray GMAT_API GetValidTimeRepresentations(); bool GMAT_API IsValidTimeSystem(const std::string& system); bool GMAT_API IsInLeapSecond(Real theTaiMjd); bool GMAT_API HandleLeapSecond(); static bool isInLeapSecond; } #endif // TimeSystemConverter_hpp
36.25
96
0.610945
supalogix
a9165d97ffaa13234978dbbe69f1b17ac2ee4cbd
22,130
cpp
C++
3.Auction/Static-Bin/scv-main.cpp
Parwatsingh/OptSmart
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
[ "Apache-2.0" ]
1
2021-03-13T08:55:13.000Z
2021-03-13T08:55:13.000Z
3.Auction/Static-Bin/scv-main.cpp
Parwatsingh/OptSmart
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
[ "Apache-2.0" ]
null
null
null
3.Auction/Static-Bin/scv-main.cpp
Parwatsingh/OptSmart
0564abdd04e7bc37a3586982a1d7ca5a97be88d5
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include "Util/Timer.cpp" #include "Contract/SimpleAuctionSCV.cpp" #include "Util/FILEOPR.cpp" #include <unistd.h> #include <list> #include <vector> #include <atomic> #include <condition_variable> #include <set> #include <algorithm> #define maxThreads 128 #define maxBObj 5000 #define maxbEndT 5000 //millseconds #define funInContract 6 #define pl "===================================================\n" #define MValidation true //! true or false #define malMiner true //! set the flag to make miner malicious. #define NumOfDoubleSTx 2 //! # double-spending Tx for malicious final state by Miner. using namespace std; using namespace std::chrono; int NumBlock = 26; //! at least two blocks, the first run is warmup run. int numValidator = 50; int beneficiary = 0; //! fixed beneficiary id to 0, it can be any unique address/id. int nBidder = 2; //! nBidder: number of bidder shared objects. default is 2. int nThread = 1; //! nThread: total number of concurrent threads; default is 1. int numAUs; //! numAUs: total number of Atomic Unites to be executed. double lemda; //! λ: random delay seed. int bidEndT; //! time duration for auction. double tTime[2]; //! total time taken by miner and validator algorithm respectively. SimpleAuction *auction; //! smart contract for miner. int *aCount = NULL; //! aborted transaction count. float_t *mTTime = NULL; //! time taken by each miner Thread to execute AUs (Transactions). float_t *vTTime = NULL; //! time taken by each validator Thread to execute AUs (Transactions). float_t *gTtime = NULL; //! time taken by each miner Thread to add edges and nodes in the conflict graph. vector<string>listAUs; //! holds AUs to be executed on smart contract: "listAUs" index+1 represents AU_ID. vector<string>seqBin; //! holds sequential Bin AUs. vector<string>concBin; //! holds concurrent Bin AUs. vector<int>ccSet; //! Set holds the IDs of the shared objects accessed by concurrent Bin Tx. std::atomic<int>currAU; //! used by miner-thread to get index of Atomic Unit to execute. std::atomic<int>vCount; //! # of valid AU node added in graph (invalid AUs will not be part of the graph & conflict list). std::atomic<int>eAUCount; //! used by validator threads to keep track of how many valid AUs executed by validator threads. mutex concLock, seqLock; //! Lock used to access seq and conc bin. float_t seqTime[3]; //! Used to store seq exe time. std::atomic<bool>mm; //! miner is malicious, this is used by validators. //! STATE DATA int mHBidder; int mHBid; int vHBidder; int vHBid; int *mPendingRet; int *vPendingRet; /*************************BARRIER CODE BEGINS****************************/ std::mutex mtx; std::mutex pmtx; // to print in concurrent scene std::condition_variable cv; bool launch = false; void wait_for_launch() { std::unique_lock<std::mutex> lck(mtx); while (!launch) cv.wait(lck); } void shoot() { std::unique_lock<std::mutex> lck(mtx); launch = true; cv.notify_all(); } /*************************BARRIER CODE ENDS*****************************/ /*************************MINER CODE BEGINS*****************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! Class "Miner" create & run "n" miner-thread concurrently ! !"concMiner()" called by miner-thread to perfrom oprs of respective AUs ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ class Miner { public: Miner( ) { //! initialize the counter used to execute the numAUs currAU = 0; vCount = 0; //! index location represents respective thread id. mTTime = new float_t [nThread]; gTtime = new float_t [nThread]; aCount = new int [nThread]; for(int i = 0; i < nThread; i++) { mTTime[i] = 0; gTtime[i] = 0; aCount[i] = 0; } auction = new SimpleAuction(bidEndT, beneficiary, nBidder); } //!-------------------------------------------- //!!!!!! MAIN MINER:: CREATE MINER THREADS !!!! //!-------------------------------------------- void mainMiner() { Timer mTimer; thread T[nThread]; // seqTime[0] = 0; Timer staticTimer; //! start timer to get time taken by static analysis. auto start = staticTimer._timeStart(); staticAnalysis(); seqTime[0] += staticTimer._timeStop( start ); //!--------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //!!!!!!!!!! Create 'nThread' Miner threads !!!!!!!!!! //!--------------------------------------------------------- double s = mTimer.timeReq(); for(int i = 0; i < nThread; i++) T[i] = thread(concMiner, i, concBin.size()); for(auto& th : T) th.join(); tTime[0] = mTimer.timeReq() - s; //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ // seqTime[1] = 0; Timer SeqTimer; //! start timer to get time taken by this thread. start = SeqTimer._timeStart(); seqBinExe(); seqTime[1] += SeqTimer._timeStop( start ); //! print the final state of the shared objects. finalState(); } //! returns the sObj accessed by AU. void getSobjId(vector<int> &sObj, string AU) { istringstream ss(AU); string tmp; ss >> tmp; //! AU_ID to Execute. ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID sObj.push_back(bID); return; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID sObj.push_back(bID); return; } } //!----------------------------------------------------------- //! Performs the static analysis based on set Operations. ! //!----------------------------------------------------------- void staticAnalysis() { //holds the IDs of the shared object accessed by an AU. vector<int> sObj; if(numAUs != 0) { //! Add first AU to concBin and Add Sobj accessed by it to ccSet. concBin.push_back(listAUs[0]); getSobjId(sObj, listAUs[0]); auto it = sObj.begin(); for( ; it != sObj.end(); ++it) { ccSet.push_back(*it); } } int index = 1; while( index < numAUs ) { sObj.clear(); getSobjId(sObj, listAUs[index]); sort (ccSet.begin(), ccSet.end()); sort (sObj.begin(), sObj.end()); vector<int> intersect(ccSet.size() + sObj.size()); vector<int>:: iterator it; it = set_intersection( ccSet.begin(), ccSet.end(), sObj.begin(), sObj.end(), intersect.begin()); intersect.resize(it-intersect.begin()); if(intersect.size() == 0 ) { auto it = sObj.begin(); for(; it != sObj.end(); ++it) ccSet.push_back(*it); concBin.push_back(listAUs[index]); } else { seqBin.push_back(listAUs[index]); } index++; } } //!----------------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //! The function to be executed by all the miner threads. Thread ! //! executes the transaction concurrently from Concurrent Bin ! //!----------------------------------------------------------------- static void concMiner(int t_ID, int numAUs) { Timer thTimer; //! get the current index, and increment it. int curInd = currAU++; //! statrt clock to get time taken by this.AU auto start = thTimer._timeStart(); while(curInd < concBin.size()) { //!get the AU to execute, which is of string type. istringstream ss(concBin[curInd]); string tmp; ss >> tmp; int AU_ID = stoi(tmp); ss >> tmp; if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } //! get the current index to execute, and increment it. curInd = currAU++; } mTTime[t_ID] += thTimer._timeStop(start); } //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ void seqBinExe( ) { int t_ID = 0; int count = 0; while(count < seqBin.size()) { //! get the AU to execute, which is of string type. istringstream ss(seqBin[count]); string tmp; ss >> tmp; int AU_ID = stoi(tmp); ss >> tmp; if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } count++; } } //!------------------------------------------------- //!Final state of all the shared object. Once all | //!AUs executed. We are geting this using state_m()| //!------------------------------------------------- void finalState() { auction->state(&mHBidder, &mHBid, mPendingRet); } ~Miner() { }; }; /********************MINER CODE ENDS*********************************/ /********************VALIDATOR CODE BEGINS***************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! Class "Validator" create & run "n" validator-Thread concurrently ! ! based on CONC and SEQ BIN given by miner operations of respective ! ! AUs. Thread 0 is considered as smart contract deployer. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ class Validator { public: Validator() { //! int the execution counter used by validator threads. eAUCount = 0; //! array index location represents respective thread id. vTTime = new float_t [nThread]; for(int i = 0; i < nThread; i++) vTTime[i] = 0; }; //!---------------------------------------- //! create n concurrent validator threads | //! to execute valid AUs. | //!---------------------------------------- void mainValidator() { for(int i = 0; i < nThread; i++) vTTime[i] = 0; eAUCount = 0; Timer vTimer; thread T[nThread]; auction->reset(bidEndT); //!--------------------------------------------------------- //!!!!!!!!!! Concurrent Phase !!!!!!!!!! //!!!!!!!!!! Create 'nThread' Validator threads !!!!!!!!!! //!--------------------------------------------------------- double s = vTimer.timeReq(); for(int i = 0; i<nThread; i++) T[i] = thread(concValidator, i); shoot(); for(auto& th : T) th.join( ); tTime[1] = vTimer.timeReq() - s; //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ // seqTime[2] = 0; Timer SeqTimer; auto start = SeqTimer._timeStart(); seqBinExe(); seqTime[2] += SeqTimer._timeStop( start ); //!print the final state of the shared objects by validator. finalState(); // auction->AuctionEnded( ); } //!------------------------------------------------------------ //!!!!!!! Concurrent Phase !!!!!!!! //!!!!!! 'nThread' Validator threads Executes this Fun !!!!!!! //!------------------------------------------------------------ static void concValidator( int t_ID ) { //barrier to synchronise all threads for a coherent launch wait_for_launch(); Timer Ttimer; //!statrt clock to get time taken by this thread. auto start = Ttimer._timeStart(); int curInd = eAUCount++; while( curInd< concBin.size() && mm == false) { //! get the AU to execute, which is of string type. istringstream ss(concBin[curInd]); string tmp; ss >> tmp; //! AU_ID to Execute. int AU_ID = stoi(tmp); ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); if(v == -1) mm = true; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); if(v == -1) mm = true; } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } curInd = eAUCount++; } //!stop timer to get time taken by this thread vTTime[t_ID] += Ttimer._timeStop( start ); } //!------------------------------------------ //!!!!!!!!! Sequential Phase !!!!!!!!!! //!------------------------------------------ void seqBinExe( ) { int t_ID = 0; int count = 0; while(count < seqBin.size() && mm == false) { //! get the AU to execute, which is of string type. istringstream ss(seqBin[count]); string tmp; ss >> tmp; //! AU_ID to Execute. int AU_ID = stoi(tmp); ss >> tmp; //! Function Name (smart contract). if(tmp.compare("bid") == 0) { ss >> tmp; int payable = stoi(tmp);//! payable ss >> tmp; int bID = stoi(tmp);//! Bidder ID ss >> tmp; int bAmt = stoi(tmp);//! Bidder value int v = auction->bid(payable, bID, bAmt); if(v == -1) mm = true; } if(tmp.compare("withdraw") == 0) { ss >> tmp; int bID = stoi(tmp);//! Bidder ID int v = auction->withdraw(bID); if(v == -1) mm = true; } if(tmp.compare("auction_end") == 0) { int v = auction->auction_end( ); } count++; } } //!------------------------------------------------- //!Final state of all the shared object. Once all | //!AUs executed. We are geting this using state() | //!------------------------------------------------- void finalState() { //state auction->state(&vHBidder, &vHBid, vPendingRet); } ~Validator() { }; }; /**********************VALIDATOR CODE ENDS***************************/ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //! atPoss:: from which double-spending Tx to be stored at begining ! //! of the list. Add malicious final state with double-spending Tx ! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool addMFS(int atPoss) { istringstream ss(listAUs[atPoss-2]); string trns1; ss >> trns1; //! AU_ID to Execute. int AU_ID1 = stoi(trns1); ss >> trns1;//function name ss >> trns1; //! payable. int payable = stoi(trns1); ss >> trns1; //! bidder ID. int bidderID = stoi(trns1); ss >> trns1; //! Ammount to bid. int bidValue = stoi(trns1); istringstream ss1(listAUs[atPoss-1]); string trns2; ss1 >> trns1; //! AU_ID to Execute. int AU_ID2 = stoi(trns1); ss1 >> trns1;//function name ss1 >> trns1; //! payable. int payable1 = stoi(trns1); ss1 >> trns1; //! bidderID. int bidderID1 = stoi(trns1); ss1 >> trns1; //! Ammount to bid. int bidValue1 = stoi(trns1); bidValue = 999; trns1 = to_string(AU_ID1)+" bid "+to_string(payable)+" " +to_string(bidderID)+" "+to_string(bidValue); listAUs[AU_ID1-1] = trns1; bidValue1 = 1000; trns2 = to_string(AU_ID2)+" bid "+to_string(payable1)+" " +to_string(bidderID1)+" "+to_string(bidValue1); listAUs[AU_ID2-1] = trns1; mHBidder = bidderID1; mHBid = bidValue; //! add the confliciting AUs in conc bin and remove them from seq bin. Add //! one of the AU from seq bin to conc Bin and remove that AU from seq bin. auto it = concBin.begin(); concBin.erase(it); concBin.insert(concBin.begin(), trns1); concBin.insert(concBin.begin()+1, trns2); it = seqBin.begin(); seqBin.erase(it); return true; } void printBins( ) { int concCount = 0, seqCount = 0; cout<<endl<<"=====================\n" <<"Concurrent Bin AUs\n====================="; for(int i = 0; i < concBin.size(); i++) { cout<<"\n"<<concBin[i]; concCount++; } cout<<endl; cout<<endl<<"=====================\n" <<"Sequential Bin AUs\n====================="; for(int i = 0; i < seqBin.size(); i++) { cout<<"\n"<<seqBin[i]; seqCount++; } cout<<"\n=====================\n" <<"Conc AU Count "<< concCount <<"\nSeq AU Count "<<seqCount <<"\n=====================\n"; } /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /*!!!!!!!! State Validation !!!!!!!!!!*/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ bool stateVal() { //State Validation bool flag = false; if(mHBidder != vHBidder || mHBid != vHBid) flag = true; // cout<<"\n============================================" // <<"\n Miner Auction Winer "<<mHBidder // <<" | Amount "<<mHBid; // cout<<"\n Validator Auction Winer "<<to_string(vHBidder) // <<" | Amount "<<to_string(vHBid); // cout<<"\n============================================\n"; return flag; } /**********************MAIN FUN CODE BEGINS***************************/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /*!!!!!!!! main() !!!!!!!!!!*/ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ int main(int argc, char *argv[]) { cout<<pl<<"Static Bin Miner and Smart Concurrent Validator\n"; cout<<"--------------------------------\n"; if(argc<3) cout<<"\nPlease Enter Command Line Argument as follows:" <<"\n\t./a.out <num Blocks> <num Validator> <num Iteration>\n"; NumBlock = atoi(argv[1]); numValidator = atoi(argv[2]); int nItertion = atoi(argv[3]); if(NumBlock < 2) cout<<"\nNumber of Blocks should be >= 2\n"; if(numValidator < 1)cout<<"\nNumber of Validators should be >= 1\n"; if(nItertion < 1)cout<<"\nNumber of Iterations should be >= 1\n"; float tMiner = 0, tVal = 0; int tReject = 0, tMaxAcc = 0; float tStatT = 0, tSeqMT = 0; float tSeqVT = 0; //! list holds the avg time taken by miner and Validator //! thread s for multiple consecutive runs. list<float>mItrT; list<float>vItrT; int totalRejCont = 0; //number of validator rejected the blocks; int maxAccepted = 0; int totalRun = NumBlock; //at least 2 FILEOPR file_opr; //! read from input file:: nBidder = #nBidder; nThread = #threads; //! numAUs = #AUs; λ = random delay seed. file_opr.getInp(&nBidder, &bidEndT, &nThread, &numAUs, &lemda); if(nBidder > maxBObj) { nBidder = maxBObj; cout<<"Max number Bidder Shared Object can be "<<maxBObj<<"\n"; } float valTime; for(int itr = 0; itr < nItertion; itr++) { seqTime[0] = seqTime[1] = seqTime[2] = 0; totalRejCont = 0; maxAccepted = 0; valTime = 0; float Blockvalt; for(int nBlock = 0; nBlock < NumBlock; nBlock++) { file_opr.genAUs(numAUs, nBidder, funInContract, listAUs); tTime[0] = 0, tTime[1] = 0; Blockvalt = 0; mPendingRet = new int [nBidder+1]; vPendingRet = new int [nBidder+1]; mm = new std::atomic<bool>; mm = false; Timer mTimer; mTimer.start(); //MINER Miner *miner = new Miner(); miner ->mainMiner(); if(lemda != 0) bool rv = addMFS(NumOfDoubleSTx); // printBins(); //VALIDATOR float valt = 0; int acceptCount = 0, rejectCount = 0; for(int nval = 0; nval < numValidator; nval++) { valt = 0; Validator *validator = new Validator(); validator ->mainValidator(); bool flag = stateVal(); if(flag == true) rejectCount++; else acceptCount++; mm = false; int counterv = 0; for( int x = 0; x < nThread; x++ ){ if(vTTime[x] != 0) { valt += vTTime[x]; counterv++; } } if(nBlock > 0) Blockvalt += valt/counterv; } if(nBlock > 0 && malMiner == true) { totalRejCont += rejectCount; if(maxAccepted < acceptCount ) maxAccepted = acceptCount; } //! total valid AUs among total AUs executed //! by miner and varified by Validator. int vAUs = seqBin.size() + concBin.size(); if(nBlock > 0) file_opr.writeOpt(nBidder, nThread, numAUs, tTime, mTTime, vTTime, aCount, vAUs, mItrT, vItrT, 1); ccSet.clear(); concBin.clear(); seqBin.clear(); listAUs.clear(); delete miner; miner = NULL; valTime += Blockvalt/numValidator; } //to get total avg miner and validator //time after number of totalRun runs. float tAvgMinerT = 0, tAvgValidT = 0; int cnt = 0; auto mit = mItrT.begin(); auto vit = vItrT.begin(); for(int j = 1; j < totalRun; j++){ tAvgMinerT = tAvgMinerT + *mit; if(*vit != 0){ tAvgValidT = tAvgValidT + *vit; cnt++; } mit++; vit++; } tMiner += tAvgMinerT/(NumBlock-1); tVal += valTime/(NumBlock-1); tReject += totalRejCont /(NumBlock-1); tStatT += seqTime[0]; tSeqMT += seqTime[1]; tSeqVT += seqTime[2]; if(tMaxAcc < maxAccepted) tMaxAcc = maxAccepted; mItrT.clear(); vItrT.clear(); } //Static Analysis Time float avgMAtime = tStatT/(NumBlock*nItertion); //Miner Sequential Phase Time float avgMStime = tSeqMT/(NumBlock*nItertion); //Validator Sequential Phase Time float avgVStime = tSeqVT/(nItertion*NumBlock*numValidator); cout<< "Avg Miner Time in microseconds = " <<(tMiner/nItertion)+avgMStime+avgMAtime; cout<<"\nAvg Validator Time in microseconds = " <<(tVal/nItertion)+avgVStime; cout<<"\n-----------------------------"; cout<<"\nStaic Analysis Time in microseconds = "<<avgMAtime; cout<<"\nMiner Seq Time in microseconds = "<<avgMStime <<"\nValidator Seq Time in microseconds = "<<avgVStime; cout<<"\n-----------------------------"; cout<<"\nAvg Validator Accepted a Block = " <<(numValidator-(tReject/nItertion)); cout<<"\nAvg Validator Rejcted a Block = " <<tReject/nItertion; cout<<"\nMax Validator Accepted any Block = "<<tMaxAcc; cout<<"\n"<<endl; mItrT.clear(); vItrT.clear(); delete mTTime; delete vTTime; return 0; } /*********************MAIN FUN CODE ENDS***********************/
30.524138
124
0.534388
Parwatsingh
a9181f05a86adc49ff9697c7d7d99a3ef2d7f872
939
cpp
C++
src/cpp/uml/signal.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
src/cpp/uml/signal.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
1
2022-02-25T18:14:21.000Z
2022-03-10T08:59:55.000Z
src/cpp/uml/signal.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
#include "uml/signal.h" #include "uml/interface.h" #include "uml/operation.h" #include "uml/manifestation.h" #include "uml/stereotype.h" #include "uml/behavior.h" #include "uml/dataType.h" #include "uml/association.h" #include "uml/deployment.h" using namespace UML; Set<Property, Signal>& Signal::getOwnedAttributesSet() { return m_ownedAttributes; } void Signal::init() { m_ownedAttributes.subsets(m_attributes); m_ownedAttributes.subsets(m_ownedMembers); m_ownedAttributes.m_signature = &Signal::getOwnedAttributesSet; } Signal::Signal() : Element(ElementType::SIGNAL) { init(); } Signal::~Signal() { mountAndRelease(); } OrderedSet<Property, Signal>& Signal::getOwnedAttributes() { return m_ownedAttributes; } bool Signal::isSubClassOf(ElementType eType) const { bool ret = Classifier::isSubClassOf(eType); if (!ret) { ret = eType == ElementType::SIGNAL; } return ret; }
21.837209
67
0.707135
nemears
a91a44a393e834ff5c1f02ae15d203733cb04796
1,857
cpp
C++
libraries/lnn/src/NeuronInitializer.cpp
langelog/lnn
aaa6e4847886649ee78337237fbe01521a994136
[ "MIT" ]
null
null
null
libraries/lnn/src/NeuronInitializer.cpp
langelog/lnn
aaa6e4847886649ee78337237fbe01521a994136
[ "MIT" ]
null
null
null
libraries/lnn/src/NeuronInitializer.cpp
langelog/lnn
aaa6e4847886649ee78337237fbe01521a994136
[ "MIT" ]
null
null
null
#include "NeuronInitializer.h" void Initializators::ConstantInitializer(double *weigths, unsigned int n_values, double value) { for(unsigned int i=0; i<n_values; i++) { weigths[i] = value; } } void Initializators::NormalDistributionInitializer(double *weights, unsigned int n_values, default_random_engine &randEngine, double mean, double dev) { normal_distribution<double> dist(mean,dev); for(unsigned int i=0; i<n_values; i++) { double val = dist(randEngine); //std::cout << "Value: " << val << std::endl; weights[i] = val; } } void** Initializators::ConstantParamsGen(double value) { void **vals; double* val = new double; *val = value; vals = new void*[1]; vals[0] = (void*)val; return vals; } void** Initializators::GaussParamsGen(default_random_engine &randEngine, double mean, double dev) { void **vals; double* val_mean = new double; double* val_dev = new double; *val_mean = mean; *val_dev = dev; vals = new void*[3]; vals[0] = (void*)&randEngine; vals[1] = (void*)val_mean; vals[2] = (void*)val_dev; return vals; } Initializer NeuronInitializer::ConstantInitializer(double value) { Initializer initer; initer.init = Initializators::Constant; initer.initializatorFunction = (void*)&Initializators::ConstantInitializer; initer.vals = Initializators::ConstantParamsGen(value); return initer; } Initializer NeuronInitializer::NormalInitializer(default_random_engine& randEngine, double mean, double deviation) { Initializer initer; initer.init = Initializators::Gauss; initer.initializatorFunction = (void*)&Initializators::NormalDistributionInitializer; initer.vals = Initializators::GaussParamsGen(randEngine, mean, deviation); return initer; }
32.578947
152
0.677975
langelog
a91a9d4c6aa6bf35c63cea531c34b537431fd9dc
4,583
hpp
C++
3rdparty/stout/include/stout/os/process.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
4,537
2015-01-01T03:26:40.000Z
2022-03-31T03:07:00.000Z
3rdparty/stout/include/stout/os/process.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
227
2015-01-29T02:21:39.000Z
2022-03-29T13:35:50.000Z
3rdparty/stout/include/stout/os/process.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
1,992
2015-01-05T12:29:19.000Z
2022-03-31T03:07:07.000Z
// 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 __STOUT_OS_PROCESS_HPP__ #define __STOUT_OS_PROCESS_HPP__ #include <sys/types.h> // For pid_t. #include <list> #include <ostream> #include <sstream> #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/none.hpp> #include <stout/option.hpp> #include <stout/strings.hpp> namespace os { struct Process { Process(pid_t _pid, pid_t _parent, pid_t _group, const Option<pid_t>& _session, const Option<Bytes>& _rss, const Option<Duration>& _utime, const Option<Duration>& _stime, const std::string& _command, bool _zombie) : pid(_pid), parent(_parent), group(_group), session(_session), rss(_rss), utime(_utime), stime(_stime), command(_command), zombie(_zombie) {} const pid_t pid; const pid_t parent; const pid_t group; const Option<pid_t> session; const Option<Bytes> rss; const Option<Duration> utime; const Option<Duration> stime; const std::string command; const bool zombie; // TODO(bmahler): Add additional data as needed. bool operator<(const Process& p) const { return pid < p.pid; } bool operator<=(const Process& p) const { return pid <= p.pid; } bool operator>(const Process& p) const { return pid > p.pid; } bool operator>=(const Process& p) const { return pid >= p.pid; } bool operator==(const Process& p) const { return pid == p.pid; } bool operator!=(const Process& p) const { return pid != p.pid; } }; class ProcessTree { public: // Returns a process subtree rooted at the specified PID, or none if // the specified pid could not be found in this process tree. Option<ProcessTree> find(pid_t pid) const { if (process.pid == pid) { return *this; } foreach (const ProcessTree& tree, children) { Option<ProcessTree> option = tree.find(pid); if (option.isSome()) { return option; } } return None(); } // Checks if the specified pid is contained in this process tree. bool contains(pid_t pid) const { return find(pid).isSome(); } operator Process() const { return process; } operator pid_t() const { return process.pid; } const Process process; const std::list<ProcessTree> children; private: friend struct Fork; friend Try<ProcessTree> pstree(pid_t, const std::list<Process>&); ProcessTree( const Process& _process, const std::list<ProcessTree>& _children) : process(_process), children(_children) {} }; inline std::ostream& operator<<(std::ostream& stream, const ProcessTree& tree) { if (tree.children.empty()) { stream << "--- " << tree.process.pid << " "; if (tree.process.zombie) { stream << "(" << tree.process.command << ")"; } else { stream << tree.process.command; } } else { stream << "-+- " << tree.process.pid << " "; if (tree.process.zombie) { stream << "(" << tree.process.command << ")"; } else { stream << tree.process.command; } size_t size = tree.children.size(); foreach (const ProcessTree& child, tree.children) { std::ostringstream out; out << child; stream << "\n"; if (--size != 0) { stream << " |" << strings::replace(out.str(), "\n", "\n |"); } else { stream << " \\" << strings::replace(out.str(), "\n", "\n "); } } } return stream; } } // namespace os { // An overload of stringify for printing a list of process trees // (since printing a process tree is rather particular). inline std::string stringify(const std::list<os::ProcessTree>& list) { std::ostringstream out; out << "[ " << std::endl; std::list<os::ProcessTree>::const_iterator iterator = list.begin(); while (iterator != list.end()) { out << stringify(*iterator); if (++iterator != list.end()) { out << std::endl << std::endl; } } out << std::endl << "]"; return out.str(); } #endif // __STOUT_OS_PROCESS_HPP__
25.747191
78
0.629937
zagrev
a91f5eae1d62155313a958230e905ffee7110b9a
2,395
cpp
C++
OpenCVDemo/sobel_edge.cpp
sumandeepb/OpenCVDemo2.4
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
[ "Apache-2.0" ]
null
null
null
OpenCVDemo/sobel_edge.cpp
sumandeepb/OpenCVDemo2.4
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
[ "Apache-2.0" ]
null
null
null
OpenCVDemo/sobel_edge.cpp
sumandeepb/OpenCVDemo2.4
0a1d4ef6cef913a5bc3de928327a1678794fcf8e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2012-2018 Sumandeep Banerjee, [email protected] 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 <opencv2\opencv.hpp> //OpenCV library of IP functions void sobel_edge_demo () { //declare image buffer pointers IplImage *pImage, *pSobelXImage, *pSobelYImage, *pOutXImage, *pOutYImage; // create display windows cvNamedWindow ("Input"); cvNamedWindow ("Sobel X"); cvNamedWindow ("Sobel Y"); // load image as grayscale pImage = cvLoadImage ("input/lena_grey.bmp", CV_LOAD_IMAGE_GRAYSCALE); cvShowImage ("Input", pImage); // allocate memory buffer for output of same size as input pOutXImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels); pOutYImage = cvCreateImage (cvGetSize(pImage), pImage->depth, pImage->nChannels); // sobel operator may produce -ve pixel values, therefore it requires 32bit floating images for temporary storage pSobelXImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels); pSobelYImage = cvCreateImage (cvGetSize(pImage), IPL_DEPTH_32F, pImage->nChannels); // perform sobel edge detection cvSobel (pImage, pSobelXImage, 1, 0); cvSobel (pImage, pSobelYImage, 0, 1); // convert sobel output back to 8bit grayscale image cvConvert (pSobelXImage, pOutXImage); cvConvert (pSobelYImage, pOutYImage); // show output cvShowImage ("Sobel X", pOutXImage); cvShowImage ("Sobel Y", pOutYImage); // save output cvSaveImage ("output/sobelx.bmp", pOutXImage); cvSaveImage ("output/sobely.bmp", pOutYImage); // wait till key press cvWaitKey (0); // release memory cvReleaseImage (&pImage); cvReleaseImage (&pOutXImage); cvReleaseImage (&pOutYImage); cvReleaseImage (&pSobelXImage); cvReleaseImage (&pSobelYImage); // destroy gui windows cvDestroyAllWindows (); }
34.214286
115
0.721921
sumandeepb
a91fbb85a53efdf53fc96181a577fc97d870379b
11,058
cpp
C++
TripPrep/Read_Activity.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
TripPrep/Read_Activity.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
TripPrep/Read_Activity.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Read_Activity.cpp - Read the Activity File //********************************************************* #include "TripPrep.hpp" //--------------------------------------------------------- // Read_Activity //--------------------------------------------------------- bool TripPrep::Read_Activity (int file_num) { int last_hhold, last_person, hhold, person, purpose, mode, start, end, origin, destination; int time1, time2, num_kept, num_out, count, vehicle, *parking, nparking, pass; int next_in, next_merge, replace_id, last_keep; bool flag, read_merge, read_in, save_merge, keep; Activity_File *activity_file, *new_file; Trip_File *trip_file, *in_file; Vehicle_File *veh_file; Vehicle_Data *veh_ptr; Location_Data *loc_ptr; Access_Data *acc_ptr; activity_file = (Activity_File *) Demand_Db_Base (ACTIVITY); in_file = (Trip_File *) Demand_Db_Base (TRIP); nparking = 0; parking = 0; if (file_num > 0) { if (!split_flag) { if (!activity_file->Open (file_num)) return (false); } else { activity_file->Rewind (); } if (hhlist_flag && hhlist_file.Extend ()) { if (!Household_List (file_num)) { if (split_flag) return (false); Error ("Opening %s", hhlist_file.File_Type ()); } } } if (output_flag) { new_file = (Activity_File *) Demand_Db_Base (NEW_ACTIVITY); if (file_num > 0) { if (new_file->Extend ()) { if (!new_file->Open (file_num)) { Error ("Creating %s", new_file->File_Type ()); } } if (prob_flag && newhh_flag && newhh_file.Extend ()) { if (!newhh_file.Open (file_num)) { Error ("Opening %s", newhh_file.File_Type ()); } } if (merge_act_flag && merge_act_file.Extend ()) { if (!merge_act_file.Open (file_num)) { Error ("Opening %s", merge_act_file.File_Type ()); } } } } if (create_flag || convert_flag) { trip_file = (Trip_File *) Demand_Db_Base (NEW_TRIP); if (file_num > 0 && trip_file->Extend ()) { if (!trip_file->Open (file_num)) { Error ("Creating %s", trip_file->File_Type ()); } } if (create_flag) { veh_file = (Vehicle_File *) Demand_Db_Base (NEW_VEHICLE); if (file_num > 0) { if (newhh_flag && newhh_file.Extend ()) { if (!newhh_file.Open (file_num)) { Error ("Opening %s", newhh_file.File_Type ()); } fprintf (newhh_file.File (), "HHOLD\tOLDHH\n"); } } else if (newhh_flag) { fprintf (newhh_file.File (), "HHOLD\tOLDHH\n"); } //---- build the parking map ---- loc_ptr = location_data.Last (); nparking = loc_ptr->Location () + 1; parking = new int [nparking]; memset (parking, '\0', nparking * sizeof (int)); for (acc_ptr = access_data.First (); acc_ptr; acc_ptr = access_data.Next ()) { if (acc_ptr->From_Type () == LOCATION_ID && acc_ptr->To_Type () == PARKING_ID) { parking [acc_ptr->From_ID ()] = acc_ptr->To_ID (); } } } } //---- process each trip ---- if (merge_act_flag) { if (activity_file->Extend ()) { Show_Message ("Merging %s %s -- Record", activity_file->File_Type (), activity_file->Extension ()); } else { Show_Message ("Merging %s -- Record", activity_file->File_Type ()); } if (merge_act_file.Read ()) { next_merge = merge_act_file.Household (); } else { next_merge = MAX_INTEGER; } } else { if (activity_file->Extend ()) { Show_Message ("Reading %s %s -- Record", activity_file->File_Type (), activity_file->Extension ()); } else { Show_Message ("Reading %s -- Record", activity_file->File_Type ()); } next_merge = MAX_INTEGER; } Set_Progress (10000); last_hhold = last_person = num_kept = num_out = replace_id = last_keep = 0; read_merge = read_in = save_merge = false; count = 1; flag = true; if (activity_file->Read ()) { next_in = activity_file->Household (); } else { next_in = MAX_INTEGER; } //---- process each record ---- while (next_in != MAX_INTEGER || next_merge != MAX_INTEGER) { Show_Progress (); //---- set the processing flags ---- if (next_merge < next_in) { if (next_merge == replace_id) { save_merge = false; } else { save_merge = true; } read_merge = true; read_in = false; } else { hhold = activity_file->Household (); if (hhlist_flag && hhold_list.Get_Index (hhold) == 0) { if (all_flag) { new_file->Copy_Fields (activity_file); flag = false; if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; keep = true; replace_id = next_in; } else { keep = false; } } else { person = activity_file->Person (); purpose = activity_file->Purpose (); mode = activity_file->Mode (); vehicle = activity_file->Vehicle (); destination = activity_file->Location (); time1 = time_periods.Step (activity_file->Start_Min ()); time2 = time_periods.Step (activity_file->Start_Max ()); if (time1 < 0 || time2 < 0) { Error ("Converting Start Time for Household %d", hhold); } end = (time1 + time2 + 1) / 2; if (hhold == last_hhold && person == last_person) { flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle); if (flag) { if (create_flag) { trip_file->Household (hhold_id); trip_file->Person (person); trip_file->Trip (activity_file->Activity ()); trip_file->Purpose (purpose); pass = activity_file->Passengers (); if (mode == DRIVE_ALONE) { if (pass > 2) { mode = CARPOOL4; } else if (pass > 1) { mode = CARPOOL3; } else if (pass > 0) { mode = CARPOOL2; } } else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) { mode = MAGIC_MOVE; } trip_file->Mode (mode); trip_file->Start (time_periods.Format_Step (start)); trip_file->Origin (origin); trip_file->Arrive (time_periods.Format_Step (end)); trip_file->Destination (destination); trip_file->Constraint (activity_file->Constraint ()); if (vehicle > 0) { trip_file->Vehicle (veh_id); veh_ptr = vehicle_data.Get (vehicle); if (veh_ptr != NULL && origin < nparking) { veh_file->Vehicle (veh_id); veh_file->Household (hhold_id); veh_file->Location (parking [origin]); veh_file->Type (veh_ptr->Type ()); veh_file->Sub_Type (veh_ptr->Sub_Type ()); if (!veh_file->Write ()) { Error ("Writing %s", veh_file->File_Type ()); } } veh_id++; } else { trip_file->Vehicle (vehicle); } if (!trip_file->Write ()) { Error ("Writing %s", trip_file->File_Type ()); } if (newhh_flag) { fprintf (newhh_file.File (), "%d\t%d\n", hhold_id, hhold); } hhold_id++; } else if (convert_flag) { trip_file->Household (hhold); trip_file->Person (person); trip_file->Trip (activity_file->Activity ()); trip_file->Purpose (purpose); pass = activity_file->Passengers (); if (mode == DRIVE_ALONE) { if (pass > 2) { mode = CARPOOL4; } else if (pass > 1) { mode = CARPOOL3; } else if (pass > 0) { mode = CARPOOL2; } } else if (mode == CARPOOL2 || mode == CARPOOL3 || mode == CARPOOL4) { mode = MAGIC_MOVE; } trip_file->Mode (mode); trip_file->Start (time_periods.Format_Step (start)); trip_file->Origin (origin); trip_file->Arrive (time_periods.Format_Step (end)); trip_file->Destination (destination); trip_file->Constraint (activity_file->Constraint ()); trip_file->Vehicle (vehicle); if (!trip_file->Write ()) { Error ("Writing %s", trip_file->File_Type ()); } } } } else { flag = Trip_Check (hhold, origin, destination, start, end, mode, purpose, vehicle); } origin = destination; time1 = time_periods.Step (activity_file->End_Min ()); time2 = time_periods.Step (activity_file->End_Max ()); if (time1 < 0 || time2 < 0) { Error ("Converting End Time for Household %d", hhold); } start = (time1 + time2 + 1) / 2; last_hhold = hhold; last_person = person; if ((flag || all_flag) && output_flag) { new_file->Copy_Fields (activity_file); if (script_flag) { if (trip_flag) { in_file->Reset_Record (); } keep = (program.Execute () != 0); } else { keep = flag; } if (keep || all_flag) { if (flag && keep) { num_kept++; if (newhh_flag && hhold != last_keep) { fprintf (newhh_file.File (), "%d\n", hhold); last_keep = hhold; } } if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; } } } if (next_merge == next_in) { if (flag) { replace_id = next_in; save_merge = false; } else { save_merge = true; } read_merge = read_in = true; } else { read_in = true; read_merge = save_merge = false; } } //---- write the merge activity to the output file ---- if (save_merge) { vehicle = merge_act_file.Vehicle (); if (vehicle_list.Get_Index (vehicle) == 0) { if (!vehicle_list.Add (vehicle)) { Error ("Adding Vehicle %d to the List", vehicle); } } if (output_flag) { new_file->Copy_Fields (&merge_act_file); if (script_flag) { if (trip_flag) { in_file->Reset_Record (); } keep = (program.Execute () != 0); } else { keep = true; } if (keep) { if (!new_file->Write ()) { Error ("Writing %s", new_file->File_Type ()); } num_out++; } } } //---- get the next merge activity ---- if (read_merge) { if (merge_act_file.Read ()) { next_merge = merge_act_file.Household (); } else { next_merge = MAX_INTEGER; } } //---- get the next input activity ---- if (read_in) { if (activity_file->Read ()) { next_in = activity_file->Household (); } else { next_in = MAX_INTEGER; } } } End_Progress (); if (file_num == 0 || !split_flag) { total_in += Progress_Count (); } if (activity_file->Extend ()) { Print (2, "Number of Activity Records Read from %s = %d", activity_file->Extension (), Progress_Count ()); } else { Print (2, "Number of Activity Records Read = %d", Progress_Count ()); } if (output_flag) { total_out += num_out; if (new_file->Extend ()) { Print (1, "Number of Activity Records Written to %s = %d", new_file->Extension (), num_out); } else { Print (1, "Number of Activity Records Written = %d", num_out); } } total_used += num_kept; if (prob_flag) { Print (1, "Number of Activity Records Selected = %d", num_kept); if (num_out > 0) Print (0, " (%.1lf%%)", 100.0 * num_kept / num_out); } if (nparking > 0 && parking) { delete [] parking; } return (true); }
27.036675
108
0.570356
kravitz
a9222c686d83fb4dd6644b7109300184a01ede33
8,628
cc
C++
src/QmlControls/QmlObjectListModel.cc
uav-operation-system/qgroundcontrol
c24029938e88d7a45a04f4e4e64bf588f595afed
[ "Apache-2.0" ]
2,133
2015-01-04T03:10:22.000Z
2022-03-31T01:51:07.000Z
src/QmlControls/QmlObjectListModel.cc
uav-operation-system/qgroundcontrol
c24029938e88d7a45a04f4e4e64bf588f595afed
[ "Apache-2.0" ]
6,166
2015-01-02T18:47:42.000Z
2022-03-31T03:44:10.000Z
src/QmlControls/QmlObjectListModel.cc
uav-operation-system/qgroundcontrol
c24029938e88d7a45a04f4e4e64bf588f595afed
[ "Apache-2.0" ]
2,980
2015-01-01T03:09:18.000Z
2022-03-31T04:13:55.000Z
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ /// @file /// @author Don Gagne <[email protected]> #include "QmlObjectListModel.h" #include <QDebug> #include <QQmlEngine> const int QmlObjectListModel::ObjectRole = Qt::UserRole; const int QmlObjectListModel::TextRole = Qt::UserRole + 1; QmlObjectListModel::QmlObjectListModel(QObject* parent) : QAbstractListModel (parent) , _dirty (false) , _skipDirtyFirstItem (false) , _externalBeginResetModel (false) { } QmlObjectListModel::~QmlObjectListModel() { } QObject* QmlObjectListModel::get(int index) { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } int QmlObjectListModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return _objectList.count(); } QVariant QmlObjectListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (index.row() < 0 || index.row() >= _objectList.count()) { return QVariant(); } if (role == ObjectRole) { return QVariant::fromValue(_objectList[index.row()]); } else if (role == TextRole) { return QVariant::fromValue(_objectList[index.row()]->objectName()); } else { return QVariant(); } } QHash<int, QByteArray> QmlObjectListModel::roleNames(void) const { QHash<int, QByteArray> hash; hash[ObjectRole] = "object"; hash[TextRole] = "text"; return hash; } bool QmlObjectListModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (index.isValid() && role == ObjectRole) { _objectList.replace(index.row(), value.value<QObject*>()); emit dataChanged(index, index); return true; } return false; } bool QmlObjectListModel::insertRows(int position, int rows, const QModelIndex& parent) { Q_UNUSED(parent); if (position < 0 || position > _objectList.count() + 1) { qWarning() << "Invalid position position:count" << position << _objectList.count(); } beginInsertRows(QModelIndex(), position, position + rows - 1); endInsertRows(); emit countChanged(count()); return true; } bool QmlObjectListModel::removeRows(int position, int rows, const QModelIndex& parent) { Q_UNUSED(parent); if (position < 0 || position >= _objectList.count()) { qWarning() << "Invalid position position:count" << position << _objectList.count(); } else if (position + rows > _objectList.count()) { qWarning() << "Invalid rows position:rows:count" << position << rows << _objectList.count(); } beginRemoveRows(QModelIndex(), position, position + rows - 1); for (int row=0; row<rows; row++) { _objectList.removeAt(position); } endRemoveRows(); emit countChanged(count()); return true; } void QmlObjectListModel::move(int from, int to) { if(0 <= from && from < count() && 0 <= to && to < count() && from != to) { // Workaround to allow move item to the bottom. Done according to // beginMoveRows() documentation and implementation specificity: // https://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows // (see 3rd picture explanation there) if(from == to - 1) { to = from++; } beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); _objectList.move(from, to); endMoveRows(); } } QObject* QmlObjectListModel::operator[](int index) { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } const QObject* QmlObjectListModel::operator[](int index) const { if (index < 0 || index >= _objectList.count()) { return nullptr; } return _objectList[index]; } void QmlObjectListModel::clear() { if (!_externalBeginResetModel) { beginResetModel(); } _objectList.clear(); if (!_externalBeginResetModel) { endResetModel(); emit countChanged(count()); } } QObject* QmlObjectListModel::removeAt(int i) { QObject* removedObject = _objectList[i]; if(removedObject) { // Look for a dirtyChanged signal on the object if (_objectList[i]->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || i != 0) { QObject::disconnect(_objectList[i], SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } } removeRows(i, 1); setDirty(true); return removedObject; } void QmlObjectListModel::insert(int i, QObject* object) { if (i < 0 || i > _objectList.count()) { qWarning() << "Invalid index index:count" << i << _objectList.count(); } if(object) { QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); // Look for a dirtyChanged signal on the object if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || i != 0) { QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } } _objectList.insert(i, object); insertRows(i, 1); setDirty(true); } void QmlObjectListModel::insert(int i, QList<QObject*> objects) { if (i < 0 || i > _objectList.count()) { qWarning() << "Invalid index index:count" << i << _objectList.count(); } int j = i; for (QObject* object: objects) { QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); // Look for a dirtyChanged signal on the object if (object->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("dirtyChanged(bool)")) != -1) { if (!_skipDirtyFirstItem || j != 0) { QObject::connect(object, SIGNAL(dirtyChanged(bool)), this, SLOT(_childDirtyChanged(bool))); } } j++; _objectList.insert(j, object); } insertRows(i, objects.count()); setDirty(true); } void QmlObjectListModel::append(QObject* object) { insert(_objectList.count(), object); } void QmlObjectListModel::append(QList<QObject*> objects) { insert(_objectList.count(), objects); } QObjectList QmlObjectListModel::swapObjectList(const QObjectList& newlist) { QObjectList oldlist(_objectList); if (!_externalBeginResetModel) { beginResetModel(); } _objectList = newlist; if (!_externalBeginResetModel) { endResetModel(); emit countChanged(count()); } return oldlist; } int QmlObjectListModel::count() const { return rowCount(); } void QmlObjectListModel::setDirty(bool dirty) { if (_dirty != dirty) { _dirty = dirty; if (!dirty) { // Need to clear dirty from all children for(QObject* object: _objectList) { if (object->property("dirty").isValid()) { object->setProperty("dirty", false); } } } emit dirtyChanged(_dirty); } } void QmlObjectListModel::_childDirtyChanged(bool dirty) { _dirty |= dirty; // We want to emit dirtyChanged even if the actual value of _dirty didn't change. It can be a useful // signal to know when a child has changed dirty state emit dirtyChanged(_dirty); } void QmlObjectListModel::deleteListAndContents() { for (int i=0; i<_objectList.count(); i++) { _objectList[i]->deleteLater(); } deleteLater(); } void QmlObjectListModel::clearAndDeleteContents() { beginResetModel(); for (int i=0; i<_objectList.count(); i++) { _objectList[i]->deleteLater(); } clear(); endResetModel(); } void QmlObjectListModel::beginReset() { if (_externalBeginResetModel) { qWarning() << "QmlObjectListModel::beginReset already set"; } _externalBeginResetModel = true; beginResetModel(); } void QmlObjectListModel::endReset() { if (!_externalBeginResetModel) { qWarning() << "QmlObjectListModel::endReset begin not set"; } _externalBeginResetModel = false; endResetModel(); }
26.878505
120
0.6137
uav-operation-system
a9228b75912aec7497a8c3d41725d5f40d5cca6c
2,163
cpp
C++
src/tolua/LuaImGui.cpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
29
2020-04-22T01:31:30.000Z
2022-02-03T12:21:29.000Z
src/tolua/LuaImGui.cpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
6
2020-04-17T10:31:56.000Z
2021-09-10T12:07:22.000Z
src/tolua/LuaImGui.cpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
7
2020-03-13T01:50:41.000Z
2022-03-06T23:44:29.000Z
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include <sol/sol.hpp> #include "tolua/LuaImGui.hpp" #include "imgui/ImGui.hpp" void tnt::lua::loadImGui(sol::state_view lua_) { auto imgui{lua_["imgui"].get_or_create<sol::table>()}; imgui.new_enum("win_flags", "colapsible", ImGui::WindowFlags::Collapsible, "closable", ImGui::WindowFlags::Closable, "resizable", ImGui::WindowFlags::Resizable, "movable", ImGui::WindowFlags::Movable, "with_titlebar", ImGui::WindowFlags::WithTitleBar, "opaque_bg", ImGui::WindowFlags::OpaqueBackground, "widget_first", ImGui::WindowFlags::WidgetThenText); imgui["init"] = &tnt_imgui_init; imgui["Begin"] = sol::overload( [](Window const &win, std::string_view name, int x, int y) -> bool { return ImGui::Begin(win, name, x, y); }, &ImGui::Begin); imgui["End"] = &ImGui::End; imgui["begin_section"] = &ImGui::BeginSection; imgui["end_section"] = &ImGui::EndSection; imgui["begin_list"] = &ImGui::BeginList; imgui["list_item"] = &ImGui::list_item; imgui["end_list"] = &ImGui::EndList; imgui["begin_menubar"] = &ImGui::BeginMenuBar; imgui["menu_button"] = &ImGui::menu_button; imgui["menu_item"] = &ImGui::menu_item; imgui["end_menubar"] = &ImGui::EndMenuBar; imgui["button"] = &ImGui::button; imgui["slider_int"] = &ImGui::slider_int; imgui["slider_float"] = &ImGui::slider_float; imgui["hslider_int"] = &ImGui::hslider_int; imgui["hslider_float"] = &ImGui::hslider_float; imgui["hslider_int2"] = &ImGui::hslider_int2; imgui["hslider_float2"] = &ImGui::hslider_float2; imgui["hslider_vec"] = &ImGui::hslider_vec; imgui["checkbox"] = &ImGui::checkbox; imgui["progress_bar"] = &ImGui::progress_bar; imgui["newline"] = &ImGui::newline; imgui["text"] = &ImGui::text; imgui["colored_text"] = &ImGui::colored_text; }
35.459016
95
0.624595
TerensTare
a92473dcfc041be42ed1281ed2d4ee8cd47660e6
1,259
cpp
C++
project/Harman_T500/idlecurrentpage.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
project/Harman_T500/idlecurrentpage.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
project/Harman_T500/idlecurrentpage.cpp
happyrabbit456/Qt5_dev
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
[ "MIT" ]
null
null
null
#include "idlecurrentpage.h" #include <QGridLayout> #include <QVBoxLayout> #include "testform.h" #include "currentform.h" #include "mainwindow.h" IdleCurrentPage::IdleCurrentPage(QWidget *parent) { currentForm=qobject_cast<TestForm*>(parent); // setTitle(QString::fromLocal8Bit("关机电流测试")); QFont font; font.setPointSize(11); QLabel *label = new QLabel(QString::fromLocal8Bit("二维码扫描操作完成了,现在请准备好关机电流测试,然后点击测试按钮,开始测试。")); label->setWordWrap(true); label->setFont(font); setButtonText(QWizard::NextButton,QString::fromLocal8Bit("测试")); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(label); setLayout(layout); } bool IdleCurrentPage::validatePage() { TestForm* pCurrentForm=static_cast<TestForm*>(currentForm); MainWindow *pMainWindow=MainWindow::getMainWindow(); string value; pCurrentForm->appendMessagebox(tr("The idle current test begin to test ......")); pMainWindow->m_niVisaGPIB.reset(); // pMainWindow->m_niVisaGPIB.autoZero(true); bool bGetCurrent=pMainWindow->m_niVisaGPIB.getCurrent(value); if(bGetCurrent){ bool bUpdate=pCurrentForm->updateIdleCurrent(true,value); if(bUpdate){ return true; } } return false; }
25.693878
97
0.702145
happyrabbit456
a926983810a119de6841da246c3b28ec38d4e45e
880
cpp
C++
android-30/javax/xml/xpath/XPathFactoryConfigurationException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/javax/xml/xpath/XPathFactoryConfigurationException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/javax/xml/xpath/XPathFactoryConfigurationException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JString.hpp" #include "../../../JThrowable.hpp" #include "./XPathFactoryConfigurationException.hpp" namespace javax::xml::xpath { // Fields // QJniObject forward XPathFactoryConfigurationException::XPathFactoryConfigurationException(QJniObject obj) : javax::xml::xpath::XPathException(obj) {} // Constructors XPathFactoryConfigurationException::XPathFactoryConfigurationException(JString arg0) : javax::xml::xpath::XPathException( "javax.xml.xpath.XPathFactoryConfigurationException", "(Ljava/lang/String;)V", arg0.object<jstring>() ) {} XPathFactoryConfigurationException::XPathFactoryConfigurationException(JThrowable arg0) : javax::xml::xpath::XPathException( "javax.xml.xpath.XPathFactoryConfigurationException", "(Ljava/lang/Throwable;)V", arg0.object<jthrowable>() ) {} // Methods } // namespace javax::xml::xpath
30.344828
131
0.748864
YJBeetle
a9284fbfd3b12d64acf1b5ae32823bb6ccc32984
1,336
cpp
C++
ros_ws/src/intro_pkg1/src/TempSensor.cpp
TheProjectsGuy/Learning-ROS
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
[ "MIT" ]
2
2019-08-14T11:46:45.000Z
2020-05-13T21:03:40.000Z
ros_ws/src/intro_pkg1/src/TempSensor.cpp
TheProjectsGuy/Learning-ROS
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
[ "MIT" ]
1
2018-12-07T18:54:09.000Z
2018-12-08T13:18:44.000Z
ros_ws/src/intro_pkg1/src/TempSensor.cpp
TheProjectsGuy/Learning-ROS
612f8eeeed0d3308cfff9084dbf7dda4732ec1ae
[ "MIT" ]
null
null
null
#include "ros/ros.h" #include "std_msgs/Header.h" #include "sensor_msgs/Temperature.h" int main(int argc, char **argv) { // Initialize the ROS node ros::init(argc, argv, "TemperatureSensor", ros::init_options::AnonymousName); // Node handler ros::NodeHandle nodeHandler; // Publisher object ros::Publisher publisherObject = nodeHandler.advertise<sensor_msgs::Temperature>("temp_readings", 5); // Rate handler (5 Hz) ros::Rate rateHandler = ros::Rate(5); // Buffer variables float tempValue = 30.0; bool increment = true; // Publishing message sensor_msgs::Temperature msg; // Default properties msg.header.frame_id = "source"; msg.variance = 0.05; while(ros::ok()) { // Assign it time msg.header.stamp = ros::Time::now(); // Temperature value msg.temperature = tempValue; ROS_DEBUG("Temperature value : %f", tempValue); // Modify the temperature value tempValue += (increment) ? 0.1 : -0.1; if (tempValue >= 50 || tempValue <= 20) { increment = !increment; } // Publish the message publisherObject.publish(msg); // Increase sequence number msg.header.seq++; // Sleep for the rate satisfaction rateHandler.sleep(); } return 0; }
32.585366
105
0.614521
TheProjectsGuy
a92da91d699517c4ae2ef6a0627f450aaa3b6abe
5,810
hpp
C++
include/ecoro/when_any.hpp
msvetkin/ecoro
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
[ "MIT" ]
4
2021-10-24T00:50:22.000Z
2022-01-10T11:53:40.000Z
include/ecoro/when_any.hpp
msvetkin/ecoro
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
[ "MIT" ]
3
2022-02-01T20:14:15.000Z
2022-02-02T19:29:48.000Z
include/ecoro/when_any.hpp
msvetkin/ecoro
3d292f0d8bf16d57dcacdf6868c81669bdcb15e7
[ "MIT" ]
null
null
null
// Copyright 2021 - present, Mikhail Svetkin // All rights reserved. // // For the license information refer to LICENSE #ifndef ECORO_WHEN_ANY_HPP #define ECORO_WHEN_ANY_HPP #include "ecoro/awaitable_traits.hpp" #include "ecoro/detail/invoke_or_pass.hpp" #include "ecoro/task.hpp" #include <tuple> #include <variant> namespace ecoro { namespace detail { class when_any_observer { public: explicit when_any_observer(const std::size_t awaitables_count) noexcept : completed_index_(awaitables_count) {} bool set_continuation(std::coroutine_handle<> awaiting_coroutine) noexcept { awaiting_coroutine_ = awaiting_coroutine; return true; } void on_awaitable_completed(const std::size_t index) noexcept { completed_index_ = index; if (awaiting_coroutine_) { awaiting_coroutine_.resume(); return; } } std::size_t completed_index() const noexcept { return completed_index_; } private: std::size_t completed_index_; std::coroutine_handle<> awaiting_coroutine_; }; template<std::size_t Index, typename T> class when_any_task_promise : public task_promise<T> { struct final_awaiter { bool await_ready() const noexcept { return false; } template<typename Promise> void await_suspend( std::coroutine_handle<Promise> current_coroutine) noexcept { current_coroutine.promise().observer_->on_awaitable_completed(Index); } void await_resume() noexcept {} }; public: using task_promise<T>::task_promise; using value_type = std::conditional_t<std::is_void_v<T>, std::monostate, T>; final_awaiter final_suspend() noexcept { return {}; } value_type result() { if constexpr (std::is_void_v<T>) { return {}; } else { return task_promise<T>::result(); } } void set_observer(when_any_observer &observer) noexcept { observer_ = &observer; } private: when_any_observer *observer_{nullptr}; }; template<std::size_t Index, typename T> class when_any_task final : public task<T, when_any_task_promise<Index, T>> { public: using base = task<T, when_any_task_promise<Index, T>>; using base::base; when_any_task(base &&other) noexcept : base(std::move(other)) {} void resume(when_any_observer &observer) noexcept { base::handle().promise().set_observer(observer); base::resume(); } }; template<std::size_t Index, typename Awaitable> when_any_task<Index, awaitable_return_type<Awaitable>> make_when_any_task( Awaitable awaitable) { co_return co_await awaitable; } template<typename... Awaitables> class when_any_executor { using storage_type = std::tuple<Awaitables...>; struct result { std::size_t index{0}; storage_type awaitables; result(const std::size_t i, storage_type &&awaitables) : index(i), awaitables(std::move(awaitables)) {} result(result &&) noexcept = default; result &operator=(result &&) noexcept = default; result(result &) = delete; result operator=(result &) = delete; }; struct awaiter { bool await_ready() const noexcept { return false; } bool await_suspend(std::coroutine_handle<> awaiting_coroutine) noexcept { return executor_.start(awaiting_coroutine); } result await_resume() noexcept { return {executor_.observer_.completed_index(), std::move(executor_.awaitables_)}; } when_any_executor &executor_; }; public: explicit when_any_executor(Awaitables &&...awaitables) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) : awaitables_(std::forward<Awaitables>(awaitables)...) {} explicit when_any_executor(when_any_executor &&other) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) : observer_(std::move(other.observer_)), awaitables_(std::exchange(other.awaitables_, {})) {} when_any_executor &operator=(when_any_executor &&other) noexcept( std::conjunction_v<std::is_nothrow_move_constructible<Awaitables>...>) { if (std::addressof(other) != this) { observer_ = std::move(other.observer_); awaitables_ = std::move(other.awaitables_); } return *this; } auto operator co_await() noexcept { return awaiter{const_cast<when_any_executor &>(*this)}; } protected: bool start(std::coroutine_handle<> awaiting_coroutine) noexcept { std::apply([this](auto &&...args) { (start(args), ...); }, awaitables_); if (finished()) { return false; } observer_.set_continuation(awaiting_coroutine); return true; } template<typename Awaitable> void start(Awaitable &awaitable) noexcept { if (!finished()) awaitable.resume(observer_); } bool finished() const noexcept { return observer_.completed_index() < sizeof...(Awaitables); } private: when_any_observer observer_{sizeof...(Awaitables)}; storage_type awaitables_; }; template<typename... Awaitables> decltype(auto) make_when_any_executor(Awaitables &&...awaitables) { return when_any_executor<Awaitables...>( std::forward<Awaitables>(awaitables)...); } template<std::size_t... Indexes, typename... Awaitables> [[nodiscard]] decltype(auto) when_any(std::index_sequence<Indexes...>, Awaitables &&...awaitables) { return detail::make_when_any_executor( detail::make_when_any_task<Indexes, Awaitables>( detail::invoke_or_pass(std::forward<Awaitables>(awaitables)))...); } } // namespace detail template<typename... Awaitables> [[nodiscard]] decltype(auto) when_any(Awaitables &&...awaitables) { return detail::when_any(std::index_sequence_for<Awaitables...>{}, std::forward<Awaitables>(awaitables)...); } } // namespace ecoro #endif // ECORO_WHEN_ANY_HPP
26.651376
78
0.694836
msvetkin
a9304e2cd440e9351966cca74c8df4a1362279da
729
cpp
C++
04_mp11_with_values/main.cpp
BorisSchaeling/boost-meta-programming-2020
1bb70e88070953daa4bc19f91f891b43583df06e
[ "BSL-1.0" ]
null
null
null
04_mp11_with_values/main.cpp
BorisSchaeling/boost-meta-programming-2020
1bb70e88070953daa4bc19f91f891b43583df06e
[ "BSL-1.0" ]
null
null
null
04_mp11_with_values/main.cpp
BorisSchaeling/boost-meta-programming-2020
1bb70e88070953daa4bc19f91f891b43583df06e
[ "BSL-1.0" ]
null
null
null
#include <boost/mp11/mpl.hpp> #include <type_traits> template <int I> using int_ = std::integral_constant<int, I>; using namespace boost::mp11; template <typename Sequence, typename Value> struct index_of_impl { using index = mp_find<Sequence, Value>; using size = mp_size<Sequence>; using index_smaller_than_size = mp_less<index, size>; using type = mp_if<index_smaller_than_size, index, int_<-1>>; }; template <typename Sequence, typename Value> using index_of = typename index_of_impl<Sequence, Value>::type; int main() { using l = mp_list_c<int, 5, 2, 3, 1, 4>; constexpr int r1 = index_of<l, int_<3>>::value; static_assert(r1 == 2); constexpr int r2 = index_of<l, int_<6>>::value; static_assert(r2 == -1); }
23.516129
63
0.720165
BorisSchaeling
a933008a9bdfb54d6295a005cbd838b10ea79a6f
472
cpp
C++
src/atcoder/abc211/c/sol_0.cpp
kagemeka/competitive-programming
c70fe481bcd518f507b885fc9234691d8ce63171
[ "MIT" ]
1
2021-07-11T03:20:10.000Z
2021-07-11T03:20:10.000Z
src/atcoder/abc211/c/sol_0.cpp
kagemeka/competitive-programming
c70fe481bcd518f507b885fc9234691d8ce63171
[ "MIT" ]
39
2021-07-10T05:21:09.000Z
2021-12-15T06:10:12.000Z
src/atcoder/abc211/c/sol_0.cpp
kagemeka/competitive-programming
c70fe481bcd518f507b885fc9234691d8ce63171
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int mod = (int)1e9 + 7; string s; cin >> s; string t = "$chokudai"; map<char, int> ind; for ( int i = 0; i < (int)t.size(); i++ ) { ind[t[i]] = i; } map<char, int> cnt; cnt['$'] = 1; for (char x: s) { if (!ind.count(x)) continue; cnt[x] += cnt[t[ind[x]-1]]; cnt[x] %= mod; } cout << cnt['i'] << '\n'; }
15.225806
31
0.466102
kagemeka
a935c326dcfd44a395c61a7eba62a08a3f340ca3
2,875
hpp
C++
implementations/Metal/pipeline_state.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
41
2016-03-25T18:14:37.000Z
2022-01-20T11:16:52.000Z
implementations/Metal/pipeline_state.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
4
2016-05-05T22:08:01.000Z
2021-12-10T13:06:55.000Z
implementations/Metal/pipeline_state.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
9
2016-05-23T01:51:25.000Z
2021-08-21T15:32:37.000Z
#ifndef AGPU_METAL_PIPELINE_STATE_HPP #define AGPU_METAL_PIPELINE_STATE_HPP #include "device.hpp" #include "pipeline_command_state.hpp" namespace AgpuMetal { class AMtlComputePipelineBuilder; class AMtlGraphicsPipelineBuilder; class AGPUMTLPipelineStateExtra { public: virtual ~AGPUMTLPipelineStateExtra() {} virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) {} virtual void applyComputeCommands(id<MTLComputeCommandEncoder> computeEncoder) {} virtual bool isRender() const { return false; } virtual bool isCompute() const { return false; } virtual MTLSize getLocalSize() { return MTLSize(); } virtual agpu_pipeline_command_state *getCommandState() { return nullptr; } }; class AGPUMTLRenderPipelineState : public AGPUMTLPipelineStateExtra { public: AGPUMTLRenderPipelineState(); ~AGPUMTLRenderPipelineState(); virtual void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder) override; virtual bool isRender() const override { return true; } virtual agpu_pipeline_command_state *getCommandState() override { return &commandState; } id<MTLRenderPipelineState> handle; id<MTLDepthStencilState> depthStencilState; agpu_pipeline_command_state commandState; agpu_float depthBiasConstantFactor; agpu_float depthBiasClamp; agpu_float depthBiasSlopeFactor; }; class AGPUMTLComputePipelineState : public AGPUMTLPipelineStateExtra { public: AGPUMTLComputePipelineState(); ~AGPUMTLComputePipelineState(); virtual void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder) override; virtual MTLSize getLocalSize() override { return localSize; } virtual bool isCompute() const override { return true; } id<MTLComputePipelineState> handle; MTLSize localSize; }; struct AMtlPipelineState : public agpu::pipeline_state { public: AMtlPipelineState(const agpu::device_ref &device); ~AMtlPipelineState(); static agpu::pipeline_state_ref createRender(const agpu::device_ref &device, AMtlGraphicsPipelineBuilder *builder, id<MTLRenderPipelineState> handle); static agpu::pipeline_state_ref createCompute(const agpu::device_ref &device, AMtlComputePipelineBuilder *builder, id<MTLComputePipelineState> handle); void applyRenderCommands(id<MTLRenderCommandEncoder> renderEncoder); void applyComputeCommands(id<MTLComputeCommandEncoder> renderEncoder); agpu_pipeline_command_state &getCommandState() { return *extraState->getCommandState(); } agpu::device_ref device; std::unique_ptr<AGPUMTLPipelineStateExtra> extraState; }; } // End of namespace AgpuMetal #endif //AGPU_METAL_PIPELINE_STATE_HPP
25.219298
155
0.737043
rsayers
a9393254e80008724c7ebebede9caf3dc7a1d303
112
hpp
C++
tests/mygtest.hpp
fretboardfreak/audiowav
ea7f8b5e0f34557f9fdf2a459320976739647395
[ "Apache-2.0" ]
20
2016-02-01T13:07:45.000Z
2020-08-30T18:59:39.000Z
tests/mygtest.hpp
fretboardfreak/audiowav
ea7f8b5e0f34557f9fdf2a459320976739647395
[ "Apache-2.0" ]
null
null
null
tests/mygtest.hpp
fretboardfreak/audiowav
ea7f8b5e0f34557f9fdf2a459320976739647395
[ "Apache-2.0" ]
4
2018-05-13T19:05:28.000Z
2021-12-29T18:08:46.000Z
/* A simple wrapper to suppress all warnings from gtest.h */ #pragma GCC system_header #include "gtest/gtest.h"
28
60
0.758929
fretboardfreak
a939ade4483227aa19a35cc587b363ac97506583
5,391
cpp
C++
lib/backend/cpu_x86.cpp
ptillet/neo-ica
f7290219f49169d4cd51c9e58b2b8ee95aeda543
[ "MIT" ]
8
2016-12-18T13:31:17.000Z
2021-11-03T09:31:14.000Z
lib/backend/cpu_x86.cpp
ptillet/DSHF-ICA
f7290219f49169d4cd51c9e58b2b8ee95aeda543
[ "MIT" ]
1
2017-08-16T06:42:33.000Z
2017-08-18T22:14:09.000Z
lib/backend/cpu_x86.cpp
ptillet/DSHF-ICA
f7290219f49169d4cd51c9e58b2b8ee95aeda543
[ "MIT" ]
3
2017-07-03T08:44:48.000Z
2018-08-30T06:54:10.000Z
/* cpu_x86.cpp * * Author : Alexander J. Yee * Date Created : 04/12/2014 * Last Modified : 04/12/2014 * */ // Dependencies #include <iostream> #include <cstring> #if _WIN32 #include <Windows.h> #include <intrin.h> #else #include <cpuid.h> #endif #include "neo_ica/backend/cpu_x86.h" namespace neo_ica { /* * --------------------- * WINDOWS CPUID * -------------------- */ #if _WIN32 void cpu_x86::cpuid(int32_t out[4], int32_t x){ __cpuidex(out, x, 0); } __int64 xgetbv(unsigned int x){ return _xgetbv(x); } // Detect 64-bit - Note that this snippet of code for detecting 64-bit has been copied from MSDN. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); BOOL IsWow64() { BOOL bIsWow64 = FALSE; LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress( GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { printf("Error Detecting Operating System.\n"); printf("Defaulting to 32-bit OS.\n\n"); bIsWow64 = FALSE; } } return bIsWow64; } bool cpu_x86::detect_OS_x64(){ #ifdef _M_X64 return true; #else return IsWow64() != 0; #endif } #elif (defined __linux) && (defined __GNUC__) /* * --------------------- * LINUX CPUID * -------------------- */ void cpu_x86::cpuid(int32_t out[4], int32_t x){ __cpuid_count(x, 0, out[0], out[1], out[2], out[3]); } uint64_t xgetbv(unsigned int index){ uint32_t eax, edx; __asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); return ((uint64_t)edx << 32) | eax; } #define _XCR_XFEATURE_ENABLED_MASK 0 // Detect 64-bit bool cpu_x86::detect_OS_x64(){ // We only support x64 on Linux. return true; } #else #error "No cpuid intrinsic defined." #endif bool cpu_x86::detect_OS_AVX(){ // Copied from: http://stackoverflow.com/a/22521619/922184 bool avxSupported = false; int cpuInfo[4]; cpuid(cpuInfo, 1); bool osUsesXSAVE_XrhoTORE = (cpuInfo[2] & (1 << 27)) != 0; bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0; if (osUsesXSAVE_XrhoTORE && cpuAVXSuport) { uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); avxSupported = (xcrFeatureMask & 0x6) == 0x6; } return avxSupported; } bool cpu_x86::detect_OS_AVX512(){ if (!detect_OS_AVX()) return false; uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); return (xcrFeatureMask & 0xe6) == 0xe6; } void cpu_x86::detect_host(){ // OS Features OS_x64 = detect_OS_x64(); OS_AVX = detect_OS_AVX(); OS_AVX512 = detect_OS_AVX512(); // Vendor std::string vendor(get_vendor_string()); if (vendor == "GenuineIntel"){ Vendor_Intel = true; }else if (vendor == "AuthenticAMD"){ Vendor_AMD = true; } int info[4]; cpuid(info, 0); int nIds = info[0]; cpuid(info, 0x80000000); uint32_t nExIds = info[0]; // Detect Features if (nIds >= 0x00000001){ cpuid(info, 0x00000001); HW_MMX = (info[3] & ((int)1 << 23)) != 0; HW_SSE = (info[3] & ((int)1 << 25)) != 0; HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; HW_AES = (info[2] & ((int)1 << 25)) != 0; HW_AVX = (info[2] & ((int)1 << 28)) != 0; HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; } if (nIds >= 0x00000007){ cpuid(info, 0x00000007); HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; HW_ADX = (info[1] & ((int)1 << 19)) != 0; HW_MPX = (info[1] & ((int)1 << 14)) != 0; HW_SHA = (info[1] & ((int)1 << 29)) != 0; HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0; HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0; HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0; HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0; HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0; HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0; HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0; HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0; HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0; } if (nExIds >= 0x80000001){ cpuid(info, 0x80000001); HW_x64 = (info[3] & ((int)1 << 29)) != 0; HW_ABM = (info[2] & ((int)1 << 5)) != 0; HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; HW_XOP = (info[2] & ((int)1 << 11)) != 0; } } cpu_x86::cpu_x86(){ detect_host(); } std::string cpu_x86::get_vendor_string(){ int32_t CPUInfo[4]; char name[13]; cpuid(CPUInfo, 0); memcpy(name + 0, &CPUInfo[1], 4); memcpy(name + 4, &CPUInfo[3], 4); memcpy(name + 8, &CPUInfo[2], 4); name[12] = '\0'; return name; } }
25.671429
98
0.523836
ptillet
a93cab4362153db35a3b95a592b642826bc2aada
441
cpp
C++
SysLib/Network/Data/AB_Data.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
SysLib/Network/Data/AB_Data.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
SysLib/Network/Data/AB_Data.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // AB_Data.cpp - network link A->B access classes //********************************************************* #include "AB_Data.hpp" //--------------------------------------------------------- // AB_Key constructor //--------------------------------------------------------- AB_Key::AB_Key (int max_records) : Complex_Array (sizeof (AB_Data), 2, false, max_records, false) { }
29.4
63
0.326531
kravitz
a93d28ecf46e8e53fa636c0b11369a3800a91a1c
6,352
cpp
C++
herald/src/datatype/signal_characteristic_data.cpp
w-liam-mcnair/herald-for-cpp
cc01c9364c69e4015542ea632efe184a4add9e86
[ "Apache-2.0" ]
null
null
null
herald/src/datatype/signal_characteristic_data.cpp
w-liam-mcnair/herald-for-cpp
cc01c9364c69e4015542ea632efe184a4add9e86
[ "Apache-2.0" ]
null
null
null
herald/src/datatype/signal_characteristic_data.cpp
w-liam-mcnair/herald-for-cpp
cc01c9364c69e4015542ea632efe184a4add9e86
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 VMware, Inc. // SPDX-License-Identifier: Apache-2.0 // #include "herald/datatype/signal_characteristic_data.h" #include "herald/ble/ble_sensor_configuration.h" #include <vector> #include <optional> namespace herald { namespace datatype { namespace SignalCharacteristicData { using namespace herald::ble; // PRIVATE METHODS std::byte signalDataActionCode(const Data& signalData) { if (signalData.size() == 0) { return std::byte(0); } return signalData.at(0); } int int16(const Data& data, std::size_t index, bool& success) { if (index < data.size() - 1) { // TODO TEST size() boundary limits - as it's two bytes, little endian int v = (((int)data.at(index)) << 8) | (int)data.at(index + 1); success = true; return v; } success = false; return 0; } // HEADER PUBLIC METHODS std::optional<Data> encodeWriteRssi(const BLESensorConfiguration& config,const RSSI& rssi) noexcept { int r = rssi.intValue(); std::vector<std::byte> vec(3); vec.push_back(config.signalCharacteristicActionWriteRSSI); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb return std::optional<Data>(Data(std::move(vec))); // constructs the optional with a value } std::optional<RSSI> decodeWriteRSSI(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWriteRSSI) { return {}; } if (data.size() != 3) { return {}; } bool success = true; int rssi = int16(data,1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } return std::optional<RSSI>(RSSI{rssi}); // constructs the optional with a value } std::optional<Data> encodeWritePayload(const BLESensorConfiguration& config,const PayloadData& payloadData) noexcept { int r = (int)payloadData.size(); std::vector<std::byte> vec(3 + r); vec.push_back(config.signalCharacteristicActionWritePayload); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb Data d(std::move(vec)); d.append(payloadData); return std::optional<Data>(d); // constructs the optional with a value } std::optional<PayloadData> decodeWritePayload(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayload) { return {}; } if (data.size() < 3) { return {}; } bool success = true; int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } if (data.size() != (3 + std::size_t(payloadDataCount))) { return {}; } return std::optional<PayloadData>(PayloadData(data.subdata(3))); // constructs the optional with a value } std::optional<Data> encodeWritePayloadSharing(const BLESensorConfiguration& config,const PayloadSharingData& payloadSharingData) noexcept { int r = payloadSharingData.rssi.intValue(); int r2 = (int)payloadSharingData.data.size(); std::vector<std::byte> vec(5 + r2); vec.push_back(config.signalCharacteristicActionWritePayloadSharing); vec.push_back(std::byte(r)); // force least significant bit vec.push_back(std::byte(r >> 8)); // msb vec.push_back(std::byte(r2)); // force least significant bit vec.push_back(std::byte(r2 >> 8)); // msb Data d(std::move(vec)); d.append(payloadSharingData.data); return std::optional<Data>(d); // constructs the optional with a value } std::optional<PayloadSharingData> decodeWritePayloadSharing(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWritePayloadSharing) { return {}; } if (data.size() < 5) { return {}; } bool success = true; int rssiValue = int16(data, 1, success); if (!success) { return {}; } int payloadDataCount = int16(data, 3, success); // idx 3 & 4 (little endian) if (!success) { return {}; } if (data.size() != (5 + std::size_t(payloadDataCount))) { return {}; } Data d = data.subdata(5); RSSI rssi(rssiValue); PayloadSharingData pd{std::move(rssi), std::move(data)}; return std::optional<PayloadSharingData>(pd); // constructs the optional with a value } std::optional<Data> encodeImmediateSend(const BLESensorConfiguration& config,const ImmediateSendData& immediateSendData) noexcept { int r = (int)immediateSendData.size(); std::vector<std::byte> vec(3 + r); vec.push_back(config.signalCharacteristicActionWriteImmediate); vec.push_back(static_cast<std::byte>(r)); // force least significant bit vec.push_back(static_cast<std::byte>(r >> 8)); // msb Data d(std::move(vec)); d.append(immediateSendData); return std::optional<Data>(d); // constructs the optional with a value } std::optional<ImmediateSendData> decodeImmediateSend(const BLESensorConfiguration& config,const Data& data) noexcept { if (signalDataActionCode(data) != config.signalCharacteristicActionWriteImmediate) { return {}; } if (data.size() < 3) { return {}; } bool success = true; int payloadDataCount = int16(data, 1, success); // idx 1 & 2 (little endian) if (!success) { return {}; } if (data.size() != (3 + std::size_t(payloadDataCount))) { return {}; } return std::optional<ImmediateSendData>(ImmediateSendData(data.subdata(3))); // constructs the optional with a value } SignalCharacteristicDataType detect(const BLESensorConfiguration& config,const Data& data) noexcept { auto val = signalDataActionCode(data); if (config.signalCharacteristicActionWriteRSSI == val) { return SignalCharacteristicDataType::rssi; } else if (config.signalCharacteristicActionWritePayload == val) { return SignalCharacteristicDataType::payload; } else if (config.signalCharacteristicActionWritePayloadSharing == val) { return SignalCharacteristicDataType::payloadSharing; } else if (config.signalCharacteristicActionWriteImmediate == val) { return SignalCharacteristicDataType::immediateSend; } else { return SignalCharacteristicDataType::unknown; } } } // end namespace } // end namespace } // end namespace
33.787234
120
0.687343
w-liam-mcnair