hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1b6bf09314cd5b26683a17a0e4e2e8c01b21d5f | 1,823 | hpp | C++ | Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp | KingKiller100/Krakatoa-Engine | ff07f7328d428c04e06b561b6afd315eea39865c | [
"Apache-2.0"
] | 1 | 2020-04-05T13:37:48.000Z | 2020-04-05T13:37:48.000Z | Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp | KingKiller100/Krakoa-Engine | 0f2a5a5109e256a384abe8dc21eacaa45c1de610 | [
"Apache-2.0"
] | null | null | null | Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp | KingKiller100/Krakoa-Engine | 0f2a5a5109e256a384abe8dc21eacaa45c1de610 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../Primitives2D/BatchRendererData.hpp"
#include "../../../Core/PointerTypes.hpp"
#include <Maths/Vectors/Vector2.hpp>
#include <Utility/Enum/kEnum.hpp>
#include <vector>
#include <cstdint>
namespace krakoa::gfx
{
class iTexture2D;
using TexCoordsList = std::vector<kmaths::Vector2f>;
ENUM_CLASS(GeometryType, std::uint16_t,
QUAD = batch::limits::quad::vertices,
CIRCLE = batch::limits::circle::vertices,
TRIANGLE = batch::limits::triangle::vertices,
UNKNOWN = 65535
);
class SubTexture2D
{
public:
struct TexCoordData
{
kmaths::Vector2f coordIndex;
kmaths::Vector2f spriteDimensions;
TexCoordsList baseCoords;
};
public:
SubTexture2D(GeometryType geo);
SubTexture2D(iTexture2D* texture, const TexCoordData& data);
SubTexture2D(const std::shared_ptr<iTexture2D>& texture, const TexCoordData& data);
~SubTexture2D() noexcept;
USE_RESULT const Multi_Ptr<iTexture2D>& GetTexture() const noexcept;
USE_RESULT Multi_Ptr<iTexture2D>& GetTexture() noexcept;
USE_RESULT const kmaths::Vector2f* GetTexCoord() const noexcept;
void SetTexture(iTexture2D* tex) noexcept;
void SetTexture(const std::shared_ptr<iTexture2D>& value) noexcept { (texture) = value; }
USE_RESULT const TexCoordData& GetTexCoordData() const noexcept { return texCoordData; }
USE_RESULT GeometryType GetGeometryType() const noexcept;
// Only for quads
static SubTexture2D* Create(iTexture2D* texture, const TexCoordData& texCoordData);
static SubTexture2D* Create(const std::shared_ptr<iTexture2D > & texture, const TexCoordData& data);
private:
void CreateTexCoords();
GeometryType DeduceGeometryType() const;
private:
Multi_Ptr<iTexture2D> texture;
std::vector<kmaths::Vector2f> texCoords;
TexCoordData texCoordData;
GeometryType geometry;
};
}
| 28.046154 | 102 | 0.752606 | KingKiller100 |
a1b84677e65a81ac1f44d4a6c110c910466bb307 | 3,377 | hpp | C++ | includes/reflex/function/function.hpp | Cylix/Reflex | b51433f6f07e88d5b167ea71f481aa685bedcb86 | [
"MIT"
] | 112 | 2015-08-12T01:12:46.000Z | 2022-03-27T13:11:22.000Z | includes/reflex/function/function.hpp | Cylix/Reflex | b51433f6f07e88d5b167ea71f481aa685bedcb86 | [
"MIT"
] | 2 | 2015-11-22T15:04:14.000Z | 2018-01-05T05:38:44.000Z | includes/reflex/function/function.hpp | Cylix/Reflex | b51433f6f07e88d5b167ea71f481aa685bedcb86 | [
"MIT"
] | 17 | 2015-10-16T02:50:58.000Z | 2021-09-10T09:41:58.000Z | #pragma once
#include <memory>
#include <string>
#include <reflex/function/callable_base.hpp>
#include <reflex/function/callable_with_instance.hpp>
#include <reflex/function/callable_without_instance.hpp>
#include <reflex/reflection_exception.hpp>
namespace reflex {
class function {
public:
struct functions_container {
std::shared_ptr<callable_base> callable_without_obj;
std::shared_ptr<callable_base> callable_with_obj;
};
public:
//! ctor & dtor
function(void) : m_name(""), m_functions{ nullptr, nullptr } {}
function(const std::string& name, const functions_container& functions) : m_name(name), m_functions(functions) {}
~function(void) = default;
//! copy ctor & assignment operator
function(const function&) = default;
function& operator=(const function&) = default;
//! member function call on new instance
//! c-style functions
//! static member functions
template <typename ReturnType, typename... Params>
ReturnType invoke(Params... params) {
if (not m_functions.callable_without_obj)
throw reflection_exception("Invalid callable_base pointer (nullptr) for function " + m_name);
return invoke<callable_without_instance<ReturnType(Params...)>, ReturnType, Params...>(m_functions.callable_without_obj, params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(Type* obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj, params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(const std::shared_ptr<Type>& obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj.get(), params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(const std::unique_ptr<Type>& obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj.get(), params...);
}
private:
template <typename RealFunctionType, typename ReturnType, typename... Params>
ReturnType invoke(const std::shared_ptr<callable_base>& function, Params... params) {
auto function_with_real_type = std::dynamic_pointer_cast<RealFunctionType>(function);
if (not function_with_real_type)
throw reflection_exception("Invalid function signature for function " + m_name);
return (*function_with_real_type)(params...);
}
private:
std::string m_name;
functions_container m_functions;
};
} //! reflex
| 39.729412 | 158 | 0.703583 | Cylix |
a1b88a2355cb3220ecebadbf4540b83294441f79 | 2,145 | cpp | C++ | tests/test_query.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | tests/test_query.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | tests/test_query.cpp | kamchatka-volcano/hot_teacup | ef894b6f333364f9768f1d2477580604affada87 | [
"MS-PL"
] | null | null | null | #include <hot_teacup/query.h>
#include <gtest/gtest.h>
TEST(Query, ToStringSingle)
{
auto query = http::Query{"foo", "bar"};
EXPECT_EQ(query.toString(), "foo=bar");
}
TEST(Query, ToString)
{
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(http::queriesToString(queries), "name=test&foo=bar");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(http::queriesToString(queries, {"foo"}), "name=test");
}
}
TEST(Query, PathWithQueries)
{
{
auto query = http::Query{"name", "test"};
auto path = "/test/";
EXPECT_EQ(http::pathWithQuery(path, query), "/test/?name=test");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
auto path = "/test/";
EXPECT_EQ(http::pathWithQueries(path, queries), "/test/?name=test&foo=bar");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
auto path = "/test/";
EXPECT_EQ(http::pathWithQueries(path, queries, {"name"}), "/test/?foo=bar");
}
}
TEST(Query, FromString)
{
{
auto queries = http::queriesFromString("name=test&foo=bar");
auto expectedQueries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("=");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("&");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("&&");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("=&=&=");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
}
| 27.857143 | 84 | 0.568765 | kamchatka-volcano |
a1b8ea777b5e7d97ac76aaccf46fd5aed5962867 | 729 | hpp | C++ | srook/tmpl/vt/replace.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | 1 | 2018-07-01T07:54:37.000Z | 2018-07-01T07:54:37.000Z | srook/tmpl/vt/replace.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | null | null | null | srook/tmpl/vt/replace.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | null | null | null | // Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_TMPL_VT_REPLACE_HPP
#define INCLUDED_SROOK_TMPL_VT_REPLACE_HPP
#include <srook/tmpl/vt/detail/config.hpp>
SROOK_NESTED_NAMESPACE(srook, tmpl, vt) {
SROOK_INLINE_NAMESPACE(v1)
template <class T, class... Ts>
struct replace
: public type_constant<SROOK_DEDUCED_TYPENAME detail::Replace<T, Ts...>::type::rebind_packer> {};
template <class T, class... Ts>
struct replace<T, packer<Ts...>> : public replace<T, Ts...> {};
#if SROOK_ALIAS_TEMPLATES
template <class T, class... Ts>
using replace_t = SROOK_DEDUCED_TYPENAME replace<T, Ts...>::type;
#endif
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(vt, tmpl, srook)
#endif
| 28.038462 | 101 | 0.761317 | falgon |
a1b922b304bdcae834e5f2ca99f020f565a70783 | 5,942 | cpp | C++ | windows/runner/main.cpp | alexmercerind/flutter-win32-acrylic | 734094d5f3c445934d1860aef849ddd6b8188d2e | [
"MIT"
] | 2 | 2021-08-03T16:51:20.000Z | 2021-08-04T10:39:53.000Z | windows/runner/main.cpp | alexmercerind/flutter-win32-acrylic | 734094d5f3c445934d1860aef849ddd6b8188d2e | [
"MIT"
] | null | null | null | windows/runner/main.cpp | alexmercerind/flutter-win32-acrylic | 734094d5f3c445934d1860aef849ddd6b8188d2e | [
"MIT"
] | null | null | null | #include <Unknwn.h>
#include <Windows.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <windows.ui.xaml.hosting.desktopwindowxamlsource.h>
#include "utils.h"
#include "flutter/generated_plugin_registrant.h"
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
static CONST WCHAR szWindowClassName[] = L"FLUTTER_WIN32_XAML_WINDOW";
static CONST WCHAR szWindowTitle[] = L"flutter_win32_xaml";
HWND g_window_handle = nullptr;
HWND g_flutter_view_handle = nullptr;
HWND g_xaml_handle = nullptr;
flutter::FlutterViewController* g_flutter_view_controller = nullptr;
static HINSTANCE g_instance = nullptr;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE h_instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) {
UNREFERENCED_PARAMETER(prev);
UNREFERENCED_PARAMETER(command_line);
WNDCLASSEXW window_class;
SecureZeroMemory(&window_class, sizeof(window_class));
window_class.cbSize = sizeof(window_class);
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.lpfnWndProc = WndProc;
window_class.hInstance = h_instance;
window_class.lpszClassName = szWindowClassName;
window_class.hCursor = LoadCursorW(nullptr, IDC_ARROW);
window_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
RegisterClassExW(&window_class);
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
CONST HWND window_handle = CreateWindowExW(
0L,
szWindowClassName,
szWindowTitle,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
nullptr,
nullptr,
h_instance,
nullptr
);
if (!window_handle) {
return EXIT_FAILURE;
}
g_instance = h_instance;
g_window_handle = window_handle;
RECT rect;
::GetClientRect(g_window_handle, &rect);
winrt::init_apartment(winrt::apartment_type::single_threaded);
const auto windows_xaml_manager = winrt::Windows::UI::Xaml::Hosting::WindowsXamlManager::InitializeForCurrentThread();
winrt::Windows::UI::Xaml::Hosting::DesktopWindowXamlSource desktop_window_xaml_source = {};
const auto interop = desktop_window_xaml_source.as<IDesktopWindowXamlSourceNative>();
winrt::check_hresult(interop->AttachToWindow(g_window_handle));
HWND xaml_handle = nullptr;
interop->get_WindowHandle(&xaml_handle);
g_xaml_handle = xaml_handle;
if (!xaml_handle) {
return false;
}
winrt::Windows::UI::Xaml::Controls::Grid grid = {};
winrt::Windows::UI::Xaml::Media::AcrylicBrush acrylic_brush = {};
acrylic_brush.TintColor(winrt::Windows::UI::ColorHelper::FromArgb(0, 0, 0, 0));
acrylic_brush.BackgroundSource(winrt::Windows::UI::Xaml::Media::AcrylicBackgroundSource::HostBackdrop);
grid.Background(acrylic_brush);
grid.UpdateLayout();
desktop_window_xaml_source.Content(grid);
::SetWindowPos(xaml_handle, 0, rect.left, rect.top, 400, rect.bottom - rect.top, SWP_SHOWWINDOW);
::ShowWindow(g_xaml_handle, show_command);
::UpdateWindow(g_xaml_handle);
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments = GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
flutter::FlutterViewController* flutter_view_controller = new flutter::FlutterViewController(
rect.right - rect.left, rect.bottom - rect.top, project
);
g_flutter_view_controller = flutter_view_controller;
if (!flutter_view_controller->engine() || !flutter_view_controller->view()) {
return false;
}
RegisterPlugins(flutter_view_controller->engine());
g_flutter_view_handle = flutter_view_controller->view()->GetNativeWindow();
SetParent(g_flutter_view_handle, g_window_handle);
::SetWindowPos(
g_flutter_view_handle, 0,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, true
);
::SetFocus(g_flutter_view_handle);
::MSG msg;
while (::GetMessageW(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
::CoUninitialize();
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) {
if (g_flutter_view_controller != nullptr) {
std::optional<LRESULT> result = g_flutter_view_controller->HandleTopLevelWindowProc(
hwnd, message, wparam, lparam
);
if (result) {
return *result;
}
}
switch (message) {
case WM_DESTROY: {
g_window_handle = nullptr;
DestroyWindow(g_window_handle);
PostQuitMessage(0);
return 0;
}
case WM_SIZE: {
RECT rect;
::GetClientRect(g_window_handle, &rect);
if (g_xaml_handle != nullptr) {
::MoveWindow(
g_xaml_handle,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE
);
}
if (g_flutter_view_handle != nullptr) {
::MoveWindow(
g_flutter_view_handle,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE
);
}
break;
}
case WM_FONTCHANGE: {
g_flutter_view_controller->engine()->ReloadSystemFonts();
break;
}
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
::SetWindowPos(
hwnd,
nullptr,
newRectSize->left,
newRectSize->top,
newWidth,
newHeight,
SWP_NOZORDER | SWP_NOACTIVATE
);
return 0;
}
default: {
break;
}
}
return DefWindowProcW(hwnd, message, wparam, lparam);
}
| 34.346821 | 126 | 0.71794 | alexmercerind |
a1bbfe880b82a0f0ff7a7fcf2d916ea88c83626a | 2,839 | cpp | C++ | dev/Gems/CryLegacy/Code/Source/CryAction/Mannequin/MannequinAGExistanceQuery.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/CryLegacy/Code/Source/CryAction/Mannequin/MannequinAGExistanceQuery.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/CryLegacy/Code/Source/CryAction/Mannequin/MannequinAGExistanceQuery.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "CryLegacy_precompiled.h"
#include "MannequinAGExistanceQuery.h"
// ============================================================================
// ============================================================================
namespace MannequinAG
{
// ============================================================================
// ============================================================================
//////////////////////////////////////////////////////////////////////////
CMannequinAGExistanceQuery::CMannequinAGExistanceQuery(IAnimationGraphState* pAnimationGraphState)
: m_pAnimationGraphState(pAnimationGraphState)
{
CRY_ASSERT(m_pAnimationGraphState != NULL);
}
//////////////////////////////////////////////////////////////////////////
CMannequinAGExistanceQuery::~CMannequinAGExistanceQuery()
{
}
//////////////////////////////////////////////////////////////////////////
IAnimationGraphState* CMannequinAGExistanceQuery::GetState()
{
return m_pAnimationGraphState;
}
//////////////////////////////////////////////////////////////////////////
void CMannequinAGExistanceQuery::SetInput(InputID, float)
{
}
//////////////////////////////////////////////////////////////////////////
void CMannequinAGExistanceQuery::SetInput(InputID, int)
{
}
//////////////////////////////////////////////////////////////////////////
void CMannequinAGExistanceQuery::SetInput(InputID, const char*)
{
}
//////////////////////////////////////////////////////////////////////////
bool CMannequinAGExistanceQuery::Complete()
{
return true;
}
//////////////////////////////////////////////////////////////////////////
CTimeValue CMannequinAGExistanceQuery::GetAnimationLength() const
{
return CTimeValue();
}
//////////////////////////////////////////////////////////////////////////
void CMannequinAGExistanceQuery::Reset()
{
}
// ============================================================================
// ============================================================================
} // MannequinAG
| 31.898876 | 102 | 0.41106 | jeikabu |
a1c149a5e8038daf6a0f7347a548e543975552da | 170 | cpp | C++ | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zball.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zball.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zball.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "zball.h"
ZBall::ZBall()
{
ZBall(0.0, 0.0, 0.0, 0.0);
}
ZBall::ZBall(double x, double y, double z, double r)
{
m_x = x;
m_y = y;
m_z = z;
m_r = r;
}
| 11.333333 | 52 | 0.529412 | zzhmark |
a1c21176bcbbeed90dda708c7ebcbac3106573d2 | 918 | cpp | C++ | Homeworks/HW 1/PartB/PartB/Actor.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | Homeworks/HW 1/PartB/PartB/Actor.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | Homeworks/HW 1/PartB/PartB/Actor.cpp | baykamsay/cs-201 | e8e2083748643a2bd4eed313ebb73c652d525a50 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Actor.h"
using namespace std;
Actor::Actor(const string aName, const string aBirthPlace,
const unsigned int aBirthYear) {
name = aName;
birthPlace = aBirthPlace;
birthYear = aBirthYear;
}
Actor::Actor(const Actor& actorToCopy) {
name = actorToCopy.getName();
birthPlace = actorToCopy.getBirthPlace();
birthYear = actorToCopy.getBirthYear();
}
Actor::~Actor() {
//cout << "Deleting actor " + name;
}
void Actor::operator=(const Actor& right) {
name = right.getName();
birthPlace = right.getBirthPlace();
birthYear = right.getBirthYear();
}
string Actor::getName() const {
return name;
}
string Actor::getBirthPlace() const {
return birthPlace;
}
unsigned int Actor::getBirthYear() const {
return birthYear;
}
ostream& operator<<(ostream& out, const Actor& a) {
out << a.getName() << ", " << a.getBirthPlace() << ", "
<< a.getBirthYear() << endl;
return out;
} | 20.4 | 58 | 0.689542 | baykamsay |
a1c2ba6577df4940cbd9170a8af486ddddc243b2 | 25,752 | hpp | C++ | rope/template/vec/vec3.hpp | StanLepunK/Rope_cpp | 4d86200854812295ed8f360af6e50e77fcea3d5e | [
"MIT"
] | null | null | null | rope/template/vec/vec3.hpp | StanLepunK/Rope_cpp | 4d86200854812295ed8f360af6e50e77fcea3d5e | [
"MIT"
] | null | null | null | rope/template/vec/vec3.hpp | StanLepunK/Rope_cpp | 4d86200854812295ed8f360af6e50e77fcea3d5e | [
"MIT"
] | null | null | null | #ifndef VEC3_H
# define VEC3_H
/*
* vec3
* v 0.0.7
* 2020-2020
* Template Vec adapted from Rope Vector, Processing PVector, Openframework and GLSL.
*/
#include "vec2.hpp"
template <class T>
class vec3 : public vec2<T> {
private:
static int instance;
static bool _warning;
protected:
T _z;
public:
vec3();
vec3(T const &arg);
vec3(T const &x, T const &y, T const &z);
vec3(vec3<T> const &src);
~vec3();
// set
vec3 & set(T const &arg);
vec3 & set(T const &x, T const &y, T const &z);
vec3 & x(T const &x);
vec3 & y(T const &y);
vec3 & z(T const &z);
vec3 & min(T const &x);
vec3 & max(T const &y);
vec3 & red(T const &x);
vec3 & gre(T const &y);
vec3 & blu(T const &z);
vec3 & hue(T const &x);
vec3 & sat(T const &y);
vec3 & bri(T const &z);
//get
T x() const;
T y() const;
T z() const;
T alt() const;
T min() const;
T max() const;
vec3 copy() const;
T * array() const;
T red() const;
T gre() const;
T blu() const;
T hue() const;
T sat() const;
T bri() const;
// get exotic
// special
vec3 rgb() const;
vec3 hsb() const;
vec2<T> xz() const;
vec2<T> yz() const;
vec2<T> zx() const;
vec2<T> zy() const;
vec2<T> zz() const;
// x3
vec3 xxx() const;
vec3 xxy() const;
vec3 xxz() const;
vec3 xyx() const;
vec3 xyy() const;
vec3 xyz() const;
vec3 xzx() const;
vec3 xzy() const;
// y3
vec3 yxx() const;
vec3 yxy() const;
vec3 yxz() const;
vec3 yyx() const;
vec3 yyy() const;
vec3 yyz() const;
vec3 yzx() const;
vec3 yzy() const;
// z3
vec3 zxx() const;
vec3 zxy() const;
vec3 zxz() const;
vec3 zyx() const;
vec3 zyy() const;
vec3 zyz() const;
vec3 zzx() const;
vec3 zzy() const;
vec3 zzz() const;
// dot
// from vec2
// cross
vec3 cross(vec3<T> const &v) const;
// dir
vec3 dir() const;
vec3 dir(vec3<T> const &origin) const;
// abs
vec3 & abs();
// square length can be usefull and faster when the real length is not necessary
T mag_sq() const;
T mag_sq(vec3<T> const &v) const;
// Calculate the magnitude, distance or length of the vector or between two vectors.
// mag and dist is a same methode
double mag() const;
double mag(vec3<T> const &v) const;
// Calculate the magnitude, distance or length of the vector or between two vectors.
// call mag to calculate the the dist
double dist() const;
double dist(vec3<T> const &v) const;
// tan
// from vec2
// angle
// from vec2
// heading
// from vec2
// mag_sq
// from vec2
// mag
// from vec2
// dist
// from vec2
// calcule the power of the vector for each component
vec3 & pow(T const &pow);
vec3 & pow(T const &pow_x, T const &pow_y, T const &pow_z);
// barycenter
vec3 barycenter(vec3<T> const &other) const;
//map
vec3 & map(T const &start_src, T const &stop_src, T const &start_dst, T const &stop_dst);
vec3 & map(vec3<T> const &start_src, vec3<T> const &stop_src, vec3<T> const &start_dst, vec3<T> const &stop_dst);
//normalize
vec3 & normalize();
static vec3 normalize(vec3<T> &target);
// limit
vec3 & limit(T const &max);
// constrain
vec3 & constrain(T const &min, T const &max);
vec3 & constrain(vec3<T> const &min, vec3<T> const &max);
// compare
// from vec2
// rand
vec3 & rand();
vec3 & rand(T const &max);
vec3 & rand(T const &min, T const &max);
vec3 & rand(vec3<T> const &min, vec3<T> const &max);
vec3 & rand(vec3<T> const &max);
vec3 & rand(T const &x_min, T const &y_min, T const &z_min,
T const &x_max, T const &y_max, T const &z_max);
vec3 & rand(std::default_random_engine &generator);
vec3 & rand(T const &max, std::default_random_engine &generator);
vec3 & rand(T const &min, T const &max, std::default_random_engine &generator);
vec3 & rand(vec3<T> const &min, vec3<T> const &max, std::default_random_engine &generator);
vec3 & rand(vec3<T> const &max, std::default_random_engine &generator);
vec3 & rand(T const &x_min, T const &y_min, T const &z_min,
T const &x_max, T const &y_max, T const &z_max,
std::default_random_engine &generator);
// wave
vec3 wave(T const &value, T const &s);
vec3 wave(T const &value, T const &sx, T const &sy, T const &sz);
vec3 cos_wave(T const &value, T const &s);
vec3 cos_wave(T const &value, T const &sx, T const &sy, T const &sz);
vec3 sin_wave(T const &value, T const &s);
vec3 sin_wave(T const &value, T const &sx, T const &sy, T const &sz);
// op += *= /= -=
// from vec2
// other op
vec3 operator+(vec3<T> const &rhs) const;
vec3 operator+(T const &rhs) const;
vec3 operator-(vec3<T> const &rhs) const;
vec3 operator-(T const &rhs) const;
vec3 operator*(vec3<T> const &rhs) const;
vec3 operator*(T const &rhs) const;
vec3 operator/(vec3<T> const &rhs) const;
vec3 operator/(T const &rhs) const;
vec3 & operator+=(vec3<T> const &rhs);
vec3 & operator+=(T const &rhs);
vec3 & operator-=(vec3<T> const &rhs);
vec3 & operator-=(T const &rhs);
vec3 & operator*=(vec3<T> const &rhs);
vec3 & operator*=(T const &rhs);
vec3 & operator/=(vec3<T> const &rhs);
vec3 & operator/=(T const &rhs);
// info
static void warning(bool is);
static int get_instance();
};
#include "vec3.hpp"
/**
* TEMPLATE DEFINITION
*/
template <class T>
std::ostream & operator<<(std::ostream & out, vec3<T> const &rhs);
// CONSTRUCTOR + DESTRUCTOR
template <class T>
vec3<T>::vec3() : vec2<T>(), _z(0) {
this->size = 3;
set_list(this->v_list, &this->_x, &this->_y, &_z);
if(vec3<T>::_warning) {
std::cout << "Default constructor vec3" << std::endl;
vec3<T>::instance++;
}
return;
}
template <class T>
vec3<T>::vec3(T const &arg) : vec2<T>(arg), _z(arg) {
this->size = 3;
set_list(this->v_list, &this->_x, &this->_y, &_z);
if(vec3<T>::_warning) {
std::cout << "Parametric constructor vec3" << std::endl;
vec3<T>::instance++;
}
return;
}
template <class T>
vec3<T>::vec3(T const &x, T const &y, T const &z) : vec2<T>(x,y), _z(z) {
this->size = 3;
set_list(this->v_list, &this->_x, &this->_y, &_z);
if(vec3<T>::_warning) {
std::cout << "Parametric constructor vec3" << std::endl;
vec3<T>::instance++;
}
return;
}
template <class T>
vec3<T>::vec3(vec3<T> const &src) : vec2<T>(src.x(),src.y()), _z(src.z()) {
this->size = 3;
set_list(this->v_list, &this->_x, &this->_y, &_z);
if(vec3<T>::_warning) {
std::cout << "Copy constructor vec3" << std::endl;
vec3<T>::instance++;
}
return;
}
template <class T>
vec3<T>::~vec3() {
if(vec3<T>::_warning) {
std::cout << "Destructor vec3" << std::endl;
vec3<T>::instance--;
}
return;
}
// SET
template <class T>
vec3<T> & vec3<T>::set(T const &arg) {
this->_x = arg;
this->_y = arg;
this->_z = arg;
return *this;
}
template <class T>
vec3<T> & vec3<T>::set(T const &x, T const &y, T const &z) {
this->_x = x;
this->_y = y;
this->_z = z;
return *this;
}
// set xyz
template <class T>
vec3<T> & vec3<T>::x(T const &x) {
this->_x = x;
return *this;
}
template <class T>
vec3<T> & vec3<T>::y(T const &y) {
this->_y = y;
return *this;
}
template <class T>
vec3<T> & vec3<T>::z(T const &z) {
this->_z = z;
return *this;
}
// set min max
template <class T>
vec3<T> & vec3<T>::min(T const &x) {
this->_x = x;
return *this;
}
template <class T>
vec3<T> & vec3<T>::max(T const &y) {
this->_y = y;
return *this;
}
template <class T>
vec3<T> vec3<T>::copy() const {
return *this;
}
template <class T>
T * vec3<T>::array() const {
static T arg[3];
for(size_t i = 0 ; i < this->get_size() ; i++) {
arg[i] = *this->v_list.at(i);
}
return arg;
}
// set rgb
template <class T>
vec3<T> & vec3<T>::red(T const &x) {
this->_x = x;
return *this;
}
template <class T>
vec3<T> & vec3<T>::gre(T const &y) {
this->_y = y;
return *this;
}
template <class T>
vec3<T> & vec3<T>::blu(T const &z) {
return this->z(z);
}
// set hsb
template <class T>
vec3<T> & vec3<T>::hue(T const &x) {
this->_x = x;
return *this;
}
template <class T>
vec3<T> & vec3<T>::sat(T const &y) {
this->_y = y;
return *this;
}
template <class T>
vec3<T> & vec3<T>::bri(T const &z) {
return this->z(z);
}
// GET
//get xyz
template <class T>
T vec3<T>::x() const {
return this->_x;
}
template <class T>
T vec3<T>::y() const {
return this->_y;
}
template <class T>
T vec3<T>::z() const {
return this->_z;
}
template <class T>
T vec3<T>::alt() const {
return this->_z;
}
// get min max
template <class T>
T vec3<T>::min() const {
return this->_x;
}
template <class T>
T vec3<T>::max() const {
return this->_y;
}
// get rgb
template <class T>
T vec3<T>::red() const {
return this->_x;
}
template <class T>
T vec3<T>::gre() const {
return this->_y;
}
template <class T>
T vec3<T>::blu() const {
return this->_z;
}
// get hsb
template <class T>
T vec3<T>::hue() const {
return this->_x;
}
template <class T>
T vec3<T>::sat() const {
return this->_y;
}
template <class T>
T vec3<T>::bri() const {
return this->_z;
}
// COMMMON ALGORITHM FOR VEC
//
// dir
template <class T>
vec3<T> vec3<T>::dir() const {
return vec3<T>::dir(vec3<T>());
}
template <class T>
vec3<T> vec3<T>::dir(vec3<T> const &origin) const {
vec3 temp = *this;
T dist = vec3<T>::dist(origin);
temp -= origin;
temp /= dist;
return temp;
}
// abs
template <class T>
vec3<T> & vec3<T>::abs() {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] = std::abs(this->list().at(i));
}
return *this;
}
// cross
template <class T>
vec3<T> vec3<T>::cross(vec3<T> const &v) const {
T cross_x = this->y() * v.z() - v.y() * this->z();
T cross_y = this->z() * v.x() - v.z() * this->x();
T cross_z = this->x() * v.y() - v.x() * this->y();
return vec3<T>(cross_x, cross_y, cross_z);
}
// mag_sq
template <class T>
T vec3<T>::mag_sq() const {
return ((this->_x * this->_x)
+ (this->_y * this->_y)
+ (this->_z * this->_z));
}
template <class T>
T vec3<T>::mag_sq(vec3<T> const &v) const {
return (((v.x() - this->_x) * (v.x() - this->_x))
+ ((v.y() - this->_y) * (v.y() - this->_y))
+ ((v.z() - this->_z) * (v.z() - this->_z)));
}
// mag
template <class T>
double vec3<T>::mag() const {
return ::sqrt(vec3<T>::mag_sq());
}
template <class T>
double vec3<T>::mag(vec3<T> const &v) const {
return ::sqrt(vec3<T>::mag_sq(v));
}
// dist
template <class T>
double vec3<T>::dist() const {
return vec3<T>::mag();
}
template <class T>
double vec3<T>::dist(vec3<T> const &v) const {
return vec3<T>::mag(v);
}
// pow
template <class T>
vec3<T> & vec3<T>::pow(T const &pow) {
return vec3<T>::pow(pow, pow, pow);
}
template <class T>
vec3<T> & vec3<T>::pow(T const &pow_x, T const &pow_y, T const &pow_z) {
this->_x = ::pow(this->x(), pow_x);
this->_y = ::pow(this->y(), pow_y);
this->_z = ::pow(this->z(), pow_z);
return *this;
}
template <class T>
vec3<T> vec3<T>::barycenter(vec3<T> const &other) const {
vec3<T> temp = *this;
return (temp += other) / 2;
}
//map
template <class T>
vec3<T> & vec3<T>::map(T const &start_src, T const &stop_src, T const &start_dst, T const &stop_dst) {
vec2<T>::map(start_src, stop_src, start_dst, stop_dst);
return *this;
}
template <class T>
vec3<T> & vec3<T>::map(vec3<T> const &start_src, vec3<T> const &stop_src, vec3<T> const &start_dst, vec3<T> const &stop_dst) {
vec2<T>::map(start_src, stop_src, start_dst, stop_dst);
return *this;
}
// normalize
template <class T>
vec3<T> & vec3<T>::normalize() {
vec2<T>::normalize();
return *this;
}
template <class T>
vec3<T> vec3<T>::normalize(vec3<T> &target) {
return target.normalize();
}
// limit
template <class T>
vec3<T> & vec3<T>::limit(T const &max) {
vec2<T>::limit(max);
return *this;
}
// constrain
template <class T>
vec3<T> & vec3<T>::constrain(T const &min, T const &max) {
vec2<T>::constrain(min,max);
return *this;
}
template <class T>
vec3<T> & vec3<T>::constrain(vec3<T> const &min, vec3<T> const &max) {
vec2<T>::constrain(min,max);
return *this;
}
// random
template <class T>
vec3<T> & vec3<T>::rand() {
return rand(0,0,0, 1,1,1);
}
template <class T>
vec3<T> & vec3<T>::rand(std::default_random_engine &generator) {
return rand(0,0,0, 1,1,1, generator);
}
//
template <class T>
vec3<T> & vec3<T>::rand(T const &max) {
return rand(0,0,0, max,max,max);
}
template <class T>
vec3<T> & vec3<T>::rand(T const &max, std::default_random_engine &generator) {
return rand(0,0,0, max,max,max, generator);
}
//
template <class T>
vec3<T> & vec3<T>::rand(T const &min, T const &max) {
return rand(min,min,min, max,max,max);
}
template <class T>
vec3<T> & vec3<T>::rand(T const &min, T const &max, std::default_random_engine &generator) {
return rand(min,min,min, max,max,max, generator);
}
//
template <class T>
vec3<T> & vec3<T>::rand(vec3<T> const &min, vec3<T> const &max) {
return rand(min.x(), min.y(), min.z(),
max.x(), max.y(), max.z());
}
template <class T>
vec3<T> & vec3<T>::rand(vec3<T> const &max) {
return rand(0, 0, 0,
max.x(), max.y(), max.z());
}
template <class T>
vec3<T> & vec3<T>::rand(vec3<T> const &min, vec3<T> const &max, std::default_random_engine &generator) {
return rand(min.x(), min.y(), min.z(),
max.x(), max.y(), max.z(),
generator);
}
template <class T>
vec3<T> & vec3<T>::rand(vec3<T> const &max, std::default_random_engine &generator) {
return rand(0, 0, 0,
max.x(), max.y(), max.z(),
generator);
}
//
template <class T>
vec3<T> & vec3<T>::rand(T const &x_min, T const &y_min, T const &z_min,
T const &x_max, T const &y_max, T const &z_max) {
std::random_device seed;
std::default_random_engine generator(seed());
return rand(x_min, y_min, z_min,
x_max, y_max, z_max,
generator);
}
template <class T>
vec3<T> & vec3<T>::rand(T const &x_min, T const &y_min, T const &z_min,
T const &x_max, T const &y_max, T const &z_max,
std::default_random_engine &generator) {
switch(vec<T>::get_type()) {
case 'c':
if(std::is_same<T, char>::value) {
this->x(random_char(static_cast<char>(x_min), static_cast<char>(x_max), generator));
this->y(random_char(static_cast<char>(x_min), static_cast<char>(x_max), generator));
this->z(random_char(static_cast<char>(z_min), static_cast<char>(z_max), generator));
}
if(std::is_same<T, uint8_t>::value) {
this->x(random_char(static_cast<uint8_t>(x_min), static_cast<uint8_t>(x_max), generator));
this->y(random_char(static_cast<uint8_t>(x_min), static_cast<uint8_t>(x_max), generator));
this->z(random_char(static_cast<uint8_t>(z_min), static_cast<uint8_t>(z_max), generator));
}
if(std::is_same<T, unsigned char>::value) {
this->x(random_char(static_cast<unsigned char>(x_min), static_cast<unsigned char>(x_max), generator));
this->y(random_char(static_cast<unsigned char>(x_min), static_cast<unsigned char>(x_max), generator));
this->z(random_char(static_cast<unsigned char>(z_min), static_cast<unsigned char>(z_max), generator));
}
break;
case 'b':
if(std::is_same<T, bool>::value) {
this->x(random_bool(generator));
this->y(random_bool(generator));
this->z(random_bool(generator));
}
break;
case 's':
if(std::is_same<T, short>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
if(std::is_same<T, uint16_t>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
if(std::is_same<T, unsigned short>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
break;
case 'i':
if(std::is_same<T, int>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
if(std::is_same<T, uint32_t>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
if(std::is_same<T, unsigned int>::value) {
this->x(random_int(x_min, x_max, generator));
this->y(random_int(y_min, y_max, generator));
this->z(random_int(z_min, z_max, generator));
}
break;
case 'l':
if(std::is_same<T, long>::value) {
this->x(random_long(x_min, x_max, generator));
this->y(random_long(y_min, y_max, generator));
this->z(random_long(z_min, z_max, generator));
}
if(std::is_same<T, uint64_t>::value) {
this->x(random_long(x_min, x_max, generator));
this->y(random_long(y_min, y_max, generator));
this->z(random_long(z_min, z_max, generator));
}
if(std::is_same<T, unsigned long>::value) {
this->x(random_long(x_min, x_max, generator));
this->y(random_long(y_min, y_max, generator));
this->z(random_long(z_min, z_max, generator));
}
break;
case 'f':
if(std::is_same<T, float>::value) {
this->x(random(x_min, x_max, generator));
this->y(random(y_min, y_max, generator));
this->z(random(z_min, z_max, generator));
}
break;
case 'd':
if(std::is_same<T, double>::value) {
this->x(random_double(x_min, x_max, generator));
this->y(random_double(y_min, y_max, generator));
this->z(random_double(z_min, z_max, generator));
}
break;
case 'h':
if(std::is_same<T, long double>::value) {
this->x(random_long_double(x_min, x_max, generator));
this->y(random_long_double(y_min, y_max, generator));
this->z(random_long_double(z_min, z_max, generator));
}
break;
default:
if(vec3<T>::_warning) {
std::cout << "vec3<T>::rand() wait <T arg> like bool, char, int, float, double" << std::endl;
}
abort();
}
return *this;
}
// wave
template <class T>
vec3<T> vec3<T>::wave(T const &value, T const &s) {
return cos_wave(value,s,s,s);
}
template <class T>
vec3<T> vec3<T>::wave(T const &value, T const &sx, T const &sy, T const &sz) {
return cos_wave(value,sx,sy,sz);
}
template <class T>
vec3<T> vec3<T>::cos_wave(T const &value, T const &s) {
return cos_wave(value,s,s,s);
}
template <class T>
vec3<T> vec3<T>::cos_wave(T const &value, T const &sx, T const &sy, T const &sz) {
T tx = cos(value * sx) + this->x();
T ty = cos(value * sy) + this->y();
T tz = cos(value * sz) + this->z();
return vec3<T>(tx,ty,tz);
}
template <class T>
vec3<T> vec3<T>::sin_wave(T const &value, T const &s) {
return sin_wave(value,s,s,s);
}
template <class T>
vec3<T> vec3<T>::sin_wave(T const &value, T const &sx, T const &sy, T const &sz) {
T tx = sin(value * sx) + this->x();
T ty = sin(value * sy) + this->y();
T tz = sin(value * sz) + this->z();
return vec3<T>(tx,ty,tz);
}
// OPERATOR + - * /
// op +
template <class T>
vec3<T> vec3<T>::operator+(vec3<T> const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] + rhs.ref().at(i)[0];
}
return temp;
}
template <class T>
vec3<T> vec3<T>::operator+(T const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] + rhs;
}
return temp;
}
// op -
template <class T>
vec3<T> vec3<T>::operator-(vec3<T> const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] - rhs.ref().at(i)[0];
}
return temp;
}
template <class T>
vec3<T> vec3<T>::operator-(T const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] - rhs;
}
return temp;
}
// op *
template <class T>
vec3<T> vec3<T>::operator*(vec3<T> const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] * rhs.ref().at(i)[0];
}
return temp;
}
template <class T>
vec3<T> vec3<T>::operator*(T const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] * rhs;
}
return temp;
}
// op *
template <class T>
vec3<T> vec3<T>::operator/(vec3<T> const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] / rhs.ref().at(i)[0];
}
return temp;
}
template <class T>
vec3<T> vec3<T>::operator/(T const &rhs) const {
vec3<T> temp;
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
temp.ref().at(i)[0] = this->ref().at(i)[0] / rhs;
}
return temp;
}
// op +=
template <class T>
vec3<T> & vec3<T>::operator+=(vec3<T> const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] += rhs.ref().at(i)[0];
}
return *this;
}
template <class T>
vec3<T> & vec3<T>::operator+=(T const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] += rhs;
}
return *this;
}
// op -=
template <class T>
vec3<T> & vec3<T>::operator-=(vec3<T> const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] -= rhs.ref().at(i)[0];
}
return *this;
}
template <class T>
vec3<T> & vec3<T>::operator-=(T const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] -= rhs;
}
return *this;
}
// op *=
template <class T>
vec3<T> & vec3<T>::operator*=(vec3<T> const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] *= rhs.ref().at(i)[0];
}
return *this;
}
template <class T>
vec3<T> & vec3<T>::operator*=(T const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] *= rhs;
}
return *this;
}
// op /=
template <class T>
vec3<T> & vec3<T>::operator/=(vec3<T> const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] /= rhs.ref().at(i)[0];
}
return *this;
}
template <class T>
vec3<T> & vec3<T>::operator/=(T const &rhs) {
for(unsigned short i = 0 ; i < this->get_size() ; i++) {
this->ref().at(i)[0] /= rhs;
}
return *this;
}
// info
template <class T>
void vec3<T>::warning(bool is) {
vec3<T>::_warning = is;
}
template <class T>
std::ostream & operator<<(std::ostream & out, vec3<T> const & rhs) {
out << "[ " << rhs.x() << ", " << rhs.y() << ", " << rhs.z() << " ]";
return out;
}
template <class T>
int vec3<T>::get_instance() {
return vec3<T>::instance;
}
// static instantiation
template <class T>
bool vec3<T>::_warning = false;
template <class T>
int vec3<T>::instance = 0;
// get exoctic
// special
template <class T>
vec3<T> vec3<T>::rgb() const{
return vec3<T>(this->x(),this->y(),this->z());
}
template <class T>
vec3<T> vec3<T>::hsb() const {
return vec3<T>(this->x(),this->y(),this->z());
}
template <class T>
vec2<T> vec3<T>::xz() const {
return vec2<T>(this->x(),this->x());
}
template <class T>
vec2<T> vec3<T>::yz() const {
return vec2<T>(this->y(),this->z());
}
template <class T>
vec2<T> vec3<T>::zx() const {
return vec2<T>(this->z(),this->x());
}
template <class T>
vec2<T> vec3<T>::zy() const {
return vec2<T>(this->z(),this->y());
}
template <class T>
vec2<T> vec3<T>::zz() const {
return vec2<T>(this->z(),this->z());
}
// x3
template <class T>
vec3<T> vec3<T>::xxx() const {
return vec3<T>(this->x(),this->x(),this->x());
}
template <class T>
vec3<T> vec3<T>::xxy() const {
return vec3<T>(this->x(),this->x(),this->y());
}
template <class T>
vec3<T> vec3<T>::xxz() const {
return vec3<T>(this->x(),this->x(),this->z());
}
template <class T>
vec3<T> vec3<T>::xyx() const {
return vec3<T>(this->x(),this->y(),this->x());
}
template <class T>
vec3<T> vec3<T>::xyy() const {
return vec3<T>(this->x(),this->y(),this->y());
}
template <class T>
vec3<T> vec3<T>::xyz() const {
return vec3<T>(this->x(),this->y(),this->z());
}
template <class T>
vec3<T> vec3<T>::xzx() const {
return vec3<T>(this->x(),this->z(),this->x());
}
template <class T>
vec3<T> vec3<T>::xzy() const {
return vec3<T>(this->x(),this->z(),this->y());
}
// y3
template <class T>
vec3<T> vec3<T>::yxx() const {
return vec3<T>(this->y(),this->x(),this->x());
}
template <class T>
vec3<T> vec3<T>::yxy() const {
return vec3<T>(this->y(),this->x(),this->y());
}
template <class T>
vec3<T> vec3<T>::yxz() const {
return vec3<T>(this->y(),this->x(),this->z());
}
template <class T>
vec3<T> vec3<T>::yyx() const {
return vec3<T>(this->y(),this->y(),this->x());
}
template <class T>
vec3<T> vec3<T>::yyy() const {
return vec3<T>(this->y(),this->y(),this->y());
}
template <class T>
vec3<T> vec3<T>::yyz() const {
return vec3<T>(this->y(),this->y(),this->z());
}
template <class T>
vec3<T> vec3<T>::yzx() const {
return vec3<T>(this->y(),this->z(),this->x());
}
template <class T>
vec3<T> vec3<T>::yzy() const {
return vec3<T>(this->y(),this->z(),this->y());
}
// z3
template <class T>
vec3<T> vec3<T>::zxx() const {
return vec3<T>(this->z(),this->x(),this->x());
}
template <class T>
vec3<T> vec3<T>::zxy() const {
return vec3<T>(this->z(),this->x(),this->y());
}
template <class T>
vec3<T> vec3<T>::zxz() const {
return vec3<T>(this->z(),this->x(),this->z());
}
template <class T>
vec3<T> vec3<T>::zyx() const {
return vec3<T>(this->z(),this->y(),this->x());
}
template <class T>
vec3<T> vec3<T>::zyy() const {
return vec3<T>(this->z(),this->y(),this->y());
}
template <class T>
vec3<T> vec3<T>::zyz() const {
return vec3<T>(this->z(),this->y(),this->z());
}
template <class T>
vec3<T> vec3<T>::zzx() const {
return vec3<T>(this->z(),this->z(),this->x());
}
template <class T>
vec3<T> vec3<T>::zzy() const {
return vec3<T>(this->z(),this->z(),this->y());
}
template <class T>
vec3<T> vec3<T>::zzz() const {
return vec3<T>(this->z(),this->z(),this->z());
}
#endif | 21.786802 | 126 | 0.605895 | StanLepunK |
a1c4531959f309f8a8710bb2ed045af97cc5bf32 | 2,541 | hpp | C++ | obcsim/obcsim_configuration.hpp | Zethian/proto-cubes-obc | a37aed0e9e3b3fd917baeb29b6279d91845818dd | [
"MIT"
] | null | null | null | obcsim/obcsim_configuration.hpp | Zethian/proto-cubes-obc | a37aed0e9e3b3fd917baeb29b6279d91845818dd | [
"MIT"
] | 4 | 2020-04-16T13:41:11.000Z | 2020-06-03T11:30:54.000Z | obcsim/obcsim_configuration.hpp | tstana/proto-cubes-obc | 671b0d1c44ee81973275d386ed70912fd06e275c | [
"MIT"
] | 2 | 2021-11-19T09:32:01.000Z | 2021-12-28T09:11:00.000Z | /* A generated header file from setup.py */
#ifndef OBCSIM_CONFIGURATION_H
#define OBCSIM_CONFIGURATION_H
#include "msp_obc.h"
#define EXP_ADDR 0x35
#define EXP_MTU 507
#define REQUEST_BUFFER_SIZE 25000
#define MSP_ERROR_THRESHOLD 5
#ifndef MSP_OP_REQ_PAYLOAD
#define MSP_OP_REQ_PAYLOAD 0x20
#endif
#ifndef MSP_OP_ACTIVE
#define MSP_OP_ACTIVE 0x10
#endif
#ifndef MSP_OP_REQ_PARAMS
#define MSP_OP_REQ_PARAMS 0x60
#endif
#ifndef MSP_OP_POWER_OFF
#define MSP_OP_POWER_OFF 0x12
#endif
#ifndef MSP_OP_SEND_PARAMS
#define MSP_OP_SEND_PARAMS 0x70
#endif
#ifndef MSP_OP_REQ_HK
#define MSP_OP_REQ_HK 0x21
#endif
#ifndef MSP_OP_SEND_CUBES_HVPS_CONF
#define MSP_OP_SEND_CUBES_HVPS_CONF 0x71
#endif
#ifndef MSP_OP_SEND_CUBES_CITI_CONF
#define MSP_OP_SEND_CUBES_CITI_CONF 0x72
#endif
#ifndef MSP_OP_SEND_CUBES_PROBE_CONF
#define MSP_OP_SEND_CUBES_PROBE_CONF 0x73
#endif
#ifndef MSP_OP_SEND_CUBES_DAQ_DUR
#define MSP_OP_SEND_CUBES_DAQ_DUR 0x74
#endif
#ifndef MSP_OP_SEND_CUBES_HVPS_TMP_VOLT
#define MSP_OP_SEND_CUBES_HVPS_TMP_VOLT 0x75
#endif
#ifndef MSP_OP_SEND_READ_REG_DEBUG
#define MSP_OP_SEND_READ_REG_DEBUG 0x76
#endif
#ifndef MSP_OP_SEND_CUBES_GATEWARE_CONF
#define MSP_OP_SEND_CUBES_GATEWARE_CONF 0x77
#endif
#ifndef MSP_OP_REQ_PUS
#define MSP_OP_REQ_PUS 0x22
#endif
#ifndef MSP_OP_SEND_TIME
#define MSP_OP_SEND_TIME 0x30
#endif
#ifndef MSP_OP_SEND_PUS
#define MSP_OP_SEND_PUS 0x31
#endif
#ifndef MSP_OP_SLEEP
#define MSP_OP_SLEEP 0x11
#endif
#ifndef MSP_OP_CUBES_DAQ_START
#define MSP_OP_CUBES_DAQ_START 0x53
#endif
#ifndef MSP_OP_CUBES_DAQ_STOP
#define MSP_OP_CUBES_DAQ_STOP 0x54
#endif
#ifndef MSP_OP_REQ_CUBES_ID
#define MSP_OP_REQ_CUBES_ID 0x61
#endif
/*
* Proto-CUBES Serial Port Commands
* - write commands (ground to Proto-CUBES) are in capital letters
* - read commands (ground from Proto-CUBES) are in non-capital letters
*/
#define CMD_SEND_CITIROC_CONF 'C'
#define CMD_SEND_PROBE_CONF 'P'
#define CMD_SEND_READ_REG_DEBUG 'R'
#define CMD_SEND_HVPS_CONF 'H'
#define CMD_SEND_HVPS_TMP_VOLT 'V'
#define CMD_SEND_DAQ_DUR 'D'
#define CMD_SEND_GATEWARE_CONF 'G'
#define CMD_DAQ_START 'S'
#define CMD_DAQ_STOP 'T'
#define CMD_DEL_FILES 'Q'
#define CMD_SEND_TIME 'Z'
#define CMD_REQ_HK 'h'
#define CMD_REQ_PAYLOAD 'p'
#define CMD_REQ_ID 'i'
/* Function prototypes */
void sequence_init(msp_link_t *lnk);
void sequence_loop(msp_link_t *lnk);
#endif /* OBCSIM_CONFIGURATION_H */
| 25.666667 | 72 | 0.783943 | Zethian |
a1c4ffdd5b57aa49d74c6225e0e9575b266d54dd | 2,628 | cpp | C++ | core/cc/connection_test.cpp | cdotstout/gapid | a729b0ca72b2a9fffa208577578725345695ed72 | [
"Apache-2.0"
] | 1 | 2021-02-26T16:08:00.000Z | 2021-02-26T16:08:00.000Z | core/cc/connection_test.cpp | cdotstout/gapid | a729b0ca72b2a9fffa208577578725345695ed72 | [
"Apache-2.0"
] | 25 | 2017-04-25T20:39:25.000Z | 2018-06-14T17:10:48.000Z | core/cc/connection_test.cpp | cdotstout/gapid | a729b0ca72b2a9fffa208577578725345695ed72 | [
"Apache-2.0"
] | 1 | 2017-07-28T03:00:42.000Z | 2017-07-28T03:00:42.000Z | /*
* Copyright (C) 2017 Google 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 "mock_connection.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
using ::testing::_;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::ReturnArg;
using ::testing::StrictMock;
using ::testing::WithArg;
using ::testing::ElementsAre;
namespace core {
namespace test {
namespace {
const std::string testString = "ABCDE";
class ConnectionTest : public ::testing::Test {
protected:
virtual void SetUp() {
mConnection.reset(new MockConnection());
}
std::unique_ptr<MockConnection> mConnection;
};
void pushBytes(std::vector<uint8_t>* buf, const std::vector<uint8_t>& v) {
buf->insert(buf->end(), v.begin(), v.end());
}
void pushString(std::vector<uint8_t>* buf, const std::string& str) {
for(char c : str) {
buf->push_back(c);
}
buf->push_back(0);
}
void pushString(std::vector<uint8_t>* buf, const char* str) {
for(char c = *str; c != 0; str++, c = *str) {
buf->push_back(c);
}
buf->push_back(0);
}
} // anonymous namespace
TEST_F(ConnectionTest, SendEmptyString) {
EXPECT_TRUE(mConnection->sendString(""));
EXPECT_THAT(mConnection->out, ElementsAre(0));
}
TEST_F(ConnectionTest, SendString) {
EXPECT_TRUE(mConnection->sendString(testString));
EXPECT_THAT(mConnection->out, ElementsAre(
'A', 'B', 'C', 'D', 'E', 0));
}
TEST_F(ConnectionTest, SendStringError) {
mConnection->out_limit = 3;
EXPECT_FALSE(mConnection->sendString(testString));
}
TEST_F(ConnectionTest, ReadEmptyString) {
pushString(&mConnection->in, "");
std::string s;
EXPECT_TRUE(mConnection->readString(&s));
EXPECT_EQ("", s);
}
TEST_F(ConnectionTest, ReadString) {
pushString(&mConnection->in, testString);
std::string s;
EXPECT_TRUE(mConnection->readString(&s));
EXPECT_EQ(testString, s);
}
TEST_F(ConnectionTest, ReadStringError) {
pushBytes(&mConnection->in, {'A', 'B'});
std::string s;
EXPECT_FALSE(mConnection->readString(&s));
}
} // namespace test
} // namespace core
| 25.028571 | 75 | 0.68417 | cdotstout |
a1c782b01ed8e6d08690a394a39c4e193bff2f61 | 25,016 | cpp | C++ | cpp/sdk/src/json_rpc.cpp | violas-core/violas-client-sdk | fc72fc0ea6e8e0e395759020038129736d93b64c | [
"MIT"
] | null | null | null | cpp/sdk/src/json_rpc.cpp | violas-core/violas-client-sdk | fc72fc0ea6e8e0e395759020038129736d93b64c | [
"MIT"
] | null | null | null | cpp/sdk/src/json_rpc.cpp | violas-core/violas-client-sdk | fc72fc0ea6e8e0e395759020038129736d93b64c | [
"MIT"
] | 2 | 2021-12-28T06:50:27.000Z | 2022-02-15T09:28:36.000Z | #include <cpprest/filestream.h>
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include "../include/utils.hpp"
#include "../include/json_rpc.hpp"
using namespace std;
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
namespace json_rpc
{
class ClientImp : public Client
{
http_client m_http_cli;
public:
ClientImp(string_view url) : m_http_cli(U(string(url)), client_config_for_proxy())
{
}
virtual ~ClientImp()
{
}
web::http::client::http_client_config client_config_for_proxy()
{
web::http::client::http_client_config client_config;
#ifdef _WIN32
wchar_t *pValue = nullptr;
std::unique_ptr<wchar_t, void (*)(wchar_t *)> holder(nullptr, [](wchar_t *p)
{ free(p); });
size_t len = 0;
auto err = _wdupenv_s(&pValue, &len, L"http_proxy");
if (pValue)
holder.reset(pValue);
if (!err && pValue && len)
{
std::wstring env_http_proxy_string(pValue, len - 1);
#else
if (const char *env_http_proxy = std::getenv("http_proxy"))
{
std::string env_http_proxy_string(env_http_proxy);
#endif
if (env_http_proxy_string == U("auto"))
client_config.set_proxy(web::web_proxy::use_auto_discovery);
else
client_config.set_proxy(web::web_proxy(env_http_proxy_string));
}
return client_config;
}
virtual void submit(const diem_types::SignedTransaction &signed_txn) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = rpc_response["diem_ledger_version"].as_integer();
}
//
// Async submit
//
virtual void async_submit(const diem_types::SignedTransaction &signed_txn,
std::function<void()> callback) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
string content_type = "application/json";
m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json();
; })
.then(
[=](json::value json_value)
{
auto error = json_value["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = json_value["diem_ledger_version"].as_integer();
if(callback)
callback();
; });
}
virtual Task<void>
await_submit2(dt::SignedTransaction &&signed_txn) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
struct awaitable
{
http_client &http_cli;
dt::SignedTransaction &&signed_txn;
string &&method;
bool await_ready() { return false; }
void await_resume() {}
void await_suspend(std::coroutine_handle<> h)
{
http_cli.request(methods::POST, "/", method, "application/json")
.then([=](http_response response) -> pplx::task<json::value>
{ //
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json();
})
.then([=](json::value json_value) { //
auto error = json_value["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = json_value["diem_ledger_version"].as_integer();
h.resume();
});
}
};
co_await awaitable{m_http_cli, move(signed_txn), move(method)};
}
virtual std::optional<TransactionView>
get_account_transaction(const diem_types::AccountAddress &address,
uint64_t sequence_number,
bool include_events) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account_transaction","params":["%s", %d, %s],"id":1})",
bytes_to_hex(address.value).c_str(),
sequence_number,
include_events ? "true" : "false");
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("get_account_transaction error, " + error.serialize()).c_str());
auto result = rpc_response["result"];
TransactionView txn;
if (!result.is_null())
{
auto vm_status = result["vm_status"];
auto type = vm_status["type"].as_string();
if (type == "executed")
txn.vm_status.value = VMStatus::Executed{type};
else if (type == "execution_failure")
{
txn.vm_status.value = VMStatus::ExecutionFailure{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["function_index"].as_integer(),
(uint64_t)vm_status["code_offset"].as_integer()};
}
else if (type == "out_of_gas")
txn.vm_status.value = VMStatus::OutOfGas{type};
else if (type == "miscellaneous_error")
txn.vm_status.value = VMStatus::MiscellaneousError{type};
else if (type == "move_abort")
txn.vm_status.value = VMStatus::MoveAbort{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["abort_code"].as_integer(),
{
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category_description"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason_description"].as_string(),
}};
else
throw runtime_error("unknow vm status");
// cout << result.serialize() << endl;
return txn;
}
else
return std::nullopt;
}
virtual Task<std::optional<TransactionView>>
await_get_account_transaction(const diem_types::AccountAddress &address,
uint64_t sequence_number,
bool include_events) override
{
struct Awaitable
{
http_client &_http_cli;
const diem_types::AccountAddress &address;
uint64_t sequence_number;
bool include_events;
json::value result;
TransactionView _txn_view;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account_transaction","params":["%s", %d, %s],"id":1})",
bytes_to_hex(address.value).c_str(),
sequence_number,
include_events ? "true" : "false");
string content_type = "application/json";
_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([this, h](json::value value)
{
try
{
result = value;
h.resume();
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
} });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, address, sequence_number, include_events};
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("get_account_transaction error, " + error.serialize()).c_str());
auto result = rpc_response["result"];
TransactionView txn;
if (!result.is_null())
{
auto vm_status = result["vm_status"];
auto type = vm_status["type"].as_string();
if (type == "executed")
txn.vm_status.value = VMStatus::Executed{type};
else if (type == "execution_failure")
{
txn.vm_status.value = VMStatus::ExecutionFailure{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["function_index"].as_integer(),
(uint64_t)vm_status["code_offset"].as_integer()};
}
else if (type == "out_of_gas")
txn.vm_status.value = VMStatus::OutOfGas{type};
else if (type == "miscellaneous_error")
txn.vm_status.value = VMStatus::MiscellaneousError{type};
else if (type == "move_abort")
txn.vm_status.value = VMStatus::MoveAbort{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["abort_code"].as_integer(),
{
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category_description"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason_description"].as_string(),
}};
else
throw runtime_error("unknow vm status");
// cout << result.serialize() << endl;
co_return txn;
}
else
co_return std::nullopt;
}
virtual std::optional<AccountView>
get_account(const diem_types::AccountAddress &address, std::optional<uint64_t> version) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account","params":["%s"],"id":1})", bytes_to_hex(address.value).c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
if (!result.is_null())
{
AccountView view;
if (!result["sequence_number"].is_null())
{
view.sequence_number = result["sequence_number"].as_number().to_int64();
view.address = diem_types::AccountAddress{hex_to_array_u8<16>(result["address"].as_string())};
}
return view;
}
else
return std::nullopt;
}
virtual std::vector<Currency> get_currencies() override
{
vector<Currency> crc;
return crc;
}
virtual AccountStateWithProof
get_account_state_blob(string account_address) override
{
AccountStateWithProof asp;
string method = format(R"({"jsonrpc":"2.0","method":"get_account_state_with_proof","params":["%s", null, null],"id":1})", account_address.c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
// printf("Response status code %u returned.\n", response.status_code());
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
// cout << result.serialize() << endl;
asp.version = result["version"].as_integer();
auto blob = result["blob"];
// if (blob.is_null())
// __throw_runtime_error(("fun : get_account_state_blob, error : " + rpc_response.serialize()).c_str());
if (!blob.is_null())
asp.blob = blob.as_string();
asp.proof.ledger_info_to_transaction_info_proof = result["proof"]["ledger_info_to_transaction_info_proof"].as_string();
asp.proof.transaction_info = result["proof"]["transaction_info"].as_string();
asp.proof.transaction_info_to_account_proof = result["proof"]["transaction_info_to_account_proof"].as_string();
return asp;
}
virtual Task<AccountStateWithProof>
await_get_account_state_blob(string account_address) override
{
struct Awaitable
{
http_client &_http_cli;
const string &address;
json::value result;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
AccountStateWithProof asp;
string method = format(R"({"jsonrpc":"2.0","method":"get_account_state_with_proof","params":["%s", null, null],"id":1})", address.c_str());
string content_type = "application/json";
_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([=](json::value rpc_response)
{
result = rpc_response;
h.resume(); });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, account_address, {}};
AccountStateWithProof asp;
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
// cout << result.serialize() << endl;
asp.version = result["version"].as_integer();
auto blob = result["blob"];
if (blob.is_null())
__throw_runtime_error(("json_rpc::await_get_account_state_blob, error : " + rpc_response.serialize()).c_str());
if (!blob.is_null())
asp.blob = blob.as_string();
asp.proof.ledger_info_to_transaction_info_proof = result["proof"]["ledger_info_to_transaction_info_proof"].as_string();
asp.proof.transaction_info = result["proof"]["transaction_info"].as_string();
asp.proof.transaction_info_to_account_proof = result["proof"]["transaction_info_to_account_proof"].as_string();
co_return asp;
}
virtual std::vector<EventView>
get_events(std::string event_key, uint64_t start, uint64_t limit, uint64_t rpc_id) override
{
vector<EventView> events;
string method = format(R"({"jsonrpc":"2.0","method":"get_events","params":["%s", %d, %d],"id":1})",
event_key.c_str(),
start,
limit,
rpc_id);
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_events, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
for (auto &e : result.as_array())
{
// cout << e.serialize() << endl;
EventView ev;
ev.key = e["key"].as_string();
ev.sequence_number = e["sequence_number"].as_integer();
ev.transaction_version = e["transaction_version"].as_integer();
if (e["data"]["type"].as_string() == "unknown")
{
UnknownEvent ue;
ue.bytes = hex_to_bytes(e["data"]["bytes"].as_string());
ev.event = ue;
}
events.emplace_back(ev);
}
return events;
}
virtual Task<std::vector<EventView>>
await_get_events(std::string event_key, uint64_t start, uint64_t limit, uint64_t rpc_id = 1) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_events","params":["%s", %d, %d],"id":1})",
event_key.c_str(),
start,
limit,
rpc_id);
string content_type = "application/json";
struct Awaitable
{
http_client _http_client;
string _method;
string _content_type;
string _event_key;
json::value result;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
_http_client.request(methods::POST, "/", _method, _content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([=](json::value value)
{
result = value;
h.resume(); });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, method, content_type};
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_events, error : " + error.serialize()).c_str());
vector<EventView> events;
auto result = rpc_response["result"];
for (auto &e : result.as_array())
{
// cout << e.serialize() << endl;
EventView ev;
ev.key = e["key"].as_string();
ev.sequence_number = e["sequence_number"].as_integer();
ev.transaction_version = e["transaction_version"].as_integer();
if (e["data"]["type"].as_string() == "unknown")
{
UnknownEvent ue;
ue.bytes = hex_to_bytes(e["data"]["bytes"].as_string());
ev.event = ue;
}
events.emplace_back(ev);
}
co_return events;
}
};
std::shared_ptr<Client>
Client::create(std::string_view url)
{
return make_shared<ClientImp>(url);
}
}
| 42.909091 | 159 | 0.473417 | violas-core |
a1c796e1d20d0cd9b45e813cf3b3102e62059d36 | 3,315 | cpp | C++ | src/sounds/Buzzer.cpp | iw4rr10r/gb-donkey-kong-jr | fe8e755b6c0c9c483ad543b6f2dce3168cdf989c | [
"MIT"
] | 5 | 2019-10-06T15:49:10.000Z | 2020-01-18T19:37:33.000Z | src/sounds/Buzzer.cpp | iw4rr10r/gb-donkey-kong-jr | fe8e755b6c0c9c483ad543b6f2dce3168cdf989c | [
"MIT"
] | null | null | null | src/sounds/Buzzer.cpp | iw4rr10r/gb-donkey-kong-jr | fe8e755b6c0c9c483ad543b6f2dce3168cdf989c | [
"MIT"
] | 1 | 2020-07-04T17:45:18.000Z | 2020-07-04T17:45:18.000Z | // -------------------------------------------------------------------------
// Donkey Kong Jr
// a Nintendo's Game & Watch adaptation on Gamebuino META
// -------------------------------------------------------------------------
// © 2019 Steph
// https://gamebuino.com/@steph
// -------------------------------------------------------------------------
// Sound Effects Controller
// -------------------------------------------------------------------------
// loads the header file of the class
#include "Buzzer.h"
// initializes the properties of the controller
Sound Buzzer::toRepeat = Sound::None;
uint8_t Buzzer::counter = 0;
uint32_t Buzzer::timer = 0;
uint8_t Buzzer::delay = 0;
bool Buzzer::mute = false;
bool Buzzer::hasRepeated = false;
// control loop
void Buzzer::update() {
// if there are any sounds left to play...
if (counter > 0) {
// and once the break is over...
if (gb.frameCount - timer > delay) {
// we continue the replay
repeat(toRepeat, counter, delay);
}
// otherwise, the repetitive loop is interrupted
} else if (!hasRepeated && toRepeat != Sound::None && gb.frameCount - timer > delay) {
hasRepeated = true;
toRepeat = Sound::None;
}
}
// plays a specific sound without delay
void Buzzer::play(Sound sound) {
// only if the sound has not been muted
if (mute) return;
switch (sound) {
case Sound::Tick:
gb.sound.fx(FxTick);
break;
case Sound::Move:
gb.sound.fx(FxMove);
break;
case Sound::Score:
gb.sound.fx(FxScore);
break;
case Sound::Lost:
gb.sound.fx(FxLost);
break;
}
}
// initiates the repetition of a sound effect with a regular interval
void Buzzer::repeat(Sound sound, uint8_t count, uint8_t delay) {
play(sound);
toRepeat = sound;
counter = count - 1;
timer = gb.frameCount;
Buzzer::delay = delay;
hasRepeated = false;
}
// switch the mute indicator
void Buzzer::toggleMute() {
mute = !mute;
}
// -------------------------------------------------------------------------
// WAV sounds consume toooooo much CPU... 🙁 set up FX are much better!
// -------------------------------------------------------------------------
// I left the WAV sounds on the repository so you could eventually test the
// difference. But you'll see that you'll give up the idea like me...
//
// When installing the game, you will need to copy the `sounds` folder to
// the root of the game folder.
// -------------------------------------------------------------------------
// void Buzzer::play(Sound sound) {
// switch (sound) {
// case Sound::Tick:
// gb.sound.play("sounds/tick.wav");
// break;
// case Sound::Move:
// gb.sound.play("sounds/move.wav");
// break;
// case Sound::Score:
// gb.sound.play("sounds/score.wav");
// break;
// case Sound::Lost:
// gb.sound.play("sounds/lost.wav");
// break;
// }
// } | 33.826531 | 90 | 0.460633 | iw4rr10r |
a1c893b151b1541f61768c2725659cf1b48d9591 | 1,957 | cpp | C++ | src/box_type.cpp | tnoho/cpp-mp4 | 3686ee530a459a554dee1a5d21a93a537c04e4e0 | [
"Apache-2.0"
] | null | null | null | src/box_type.cpp | tnoho/cpp-mp4 | 3686ee530a459a554dee1a5d21a93a537c04e4e0 | [
"Apache-2.0"
] | null | null | null | src/box_type.cpp | tnoho/cpp-mp4 | 3686ee530a459a554dee1a5d21a93a537c04e4e0 | [
"Apache-2.0"
] | null | null | null | #include "shiguredo/mp4/box_type.hpp"
#include <fmt/core.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdint>
#include <iterator>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace shiguredo::mp4 {
BoxType::BoxType(const std::string& str) {
if (std::size(str) != 4) {
throw std::invalid_argument(fmt::format("BoxType::BoxType(): invalid box type id length: [{}]", str));
}
m_data[0] = static_cast<std::uint8_t>(str[0]);
m_data[1] = static_cast<std::uint8_t>(str[1]);
m_data[2] = static_cast<std::uint8_t>(str[2]);
m_data[3] = static_cast<std::uint8_t>(str[3]);
}
BoxType::BoxType(const std::array<std::uint8_t, 4>& t_data) : m_data(t_data) {}
void BoxType::setData(const std::uint8_t d0, const std::uint8_t d1, const std::uint8_t d2, const std::uint8_t d3) {
m_data[0] = d0;
m_data[1] = d1;
m_data[2] = d2;
m_data[3] = d3;
}
std::array<std::uint8_t, 4> BoxType::getData() const {
return m_data;
}
bool BoxType::operator<(const BoxType& r) const {
return m_data < r.getData();
}
bool BoxType::operator==(const BoxType& r) const {
return m_data == r.getData();
}
std::string BoxType::toString() const {
if (std::all_of(std::begin(m_data), std::end(m_data),
[](const std::uint8_t ch) { return std::isprint(ch) != 0 || ch == 0xa9; })) {
auto s = std::string(std::begin(m_data), std::end(m_data));
return std::regex_replace(s, std::regex("\x00a9"), "©");
}
return fmt::format("0x{:02x}{:02x}{:02x}{:02x}", m_data[0], m_data[1], m_data[2], m_data[3]);
}
bool BoxType::matchWith(const BoxType& other) const {
const auto boxTypeAny = box_type_any();
if (*this == boxTypeAny || other == boxTypeAny) {
return true;
}
return *this == other;
}
BoxType box_type_any() {
static BoxType boxTypeAny(std::array<std::uint8_t, 4>{0x00, 0x00, 0x00, 0x00});
return boxTypeAny;
}
} // namespace shiguredo::mp4
| 27.180556 | 115 | 0.650996 | tnoho |
a1cba7d5801215052aff070ab51177e29b5a4f9c | 920 | cpp | C++ | src/core/simulate/src/dunesim_impl.cpp | henryiii/spatial-model-editor | 2138d03ae4c7cc353b40324dfd1a3e763d7085d9 | [
"MIT"
] | 1 | 2021-04-19T10:23:58.000Z | 2021-04-19T10:23:58.000Z | src/core/simulate/src/dunesim_impl.cpp | henryiii/spatial-model-editor | 2138d03ae4c7cc353b40324dfd1a3e763d7085d9 | [
"MIT"
] | 418 | 2020-10-08T07:42:27.000Z | 2022-03-08T12:10:52.000Z | src/core/simulate/src/dunesim_impl.cpp | henryiii/spatial-model-editor | 2138d03ae4c7cc353b40324dfd1a3e763d7085d9 | [
"MIT"
] | 2 | 2021-09-02T11:20:38.000Z | 2021-10-13T14:05:32.000Z | #include "dunesim_impl.hpp"
#include "duneconverter.hpp"
#include "dunegrid.hpp"
#include "logger.hpp"
namespace sme::simulate {
DuneImpl::DuneImpl(const simulate::DuneConverter &dc) {
for (const auto &ini : dc.getIniFiles()) {
std::stringstream ssIni(ini.toStdString());
auto &config = configs.emplace_back();
Dune::ParameterTreeParser::readINITree(ssIni, config);
}
// init Dune logging if not already done
if (!Dune::Logging::Logging::initialized()) {
Dune::Logging::Logging::init(
Dune::FakeMPIHelper::getCollectiveCommunication(),
configs[0].sub("logging"));
if (SPDLOG_ACTIVE_LEVEL > SPDLOG_LEVEL_DEBUG) {
// for release builds disable DUNE logging
Dune::Logging::Logging::mute();
}
}
// construct grid
std::tie(grid, hostGrid) = makeDuneGrid<HostGrid, MDGTraits>(*dc.getMesh());
}
DuneImpl::~DuneImpl() = default;
} // namespace sme::simulate
| 29.677419 | 78 | 0.68587 | henryiii |
a1cdea98253f76592ae406b07acc3f0ead46e044 | 1,676 | cpp | C++ | test/unit/jt_test/box2d_joint_test.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | test/unit/jt_test/box2d_joint_test.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | test/unit/jt_test/box2d_joint_test.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | #include "box2d_joint.hpp"
#include "mocks/box2d_world_mock.hpp"
#include "mocks/mock_game.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
class Box2dJointTest : public ::testing::Test {
public:
std::shared_ptr<Box2DWorldMock> m_mockWorld;
void SetUp() override { m_mockWorld = std::make_shared<NiceMock<Box2DWorldMock>>(); }
};
TEST_F(Box2dJointTest, ConstructorCallsCreateJoint)
{
EXPECT_CALL(*m_mockWorld, createJoint(nullptr));
jt::Box2DJoint joint { m_mockWorld, nullptr };
}
TEST_F(Box2dJointTest, GetBodyReturnsNullptrWhenCreatedWithNullptrJointDef)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
EXPECT_EQ(joint.getB2Joint(), nullptr);
}
TEST_F(Box2dJointTest, Create)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
auto g = std::make_shared<MockGame>();
joint.setGameInstance(g);
joint.create();
SUCCEED();
}
TEST_F(Box2dJointTest, Update)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
joint.update(1.0f);
SUCCEED();
}
TEST_F(Box2dJointTest, Draw)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
joint.draw();
SUCCEED();
}
TEST_F(Box2dJointTest, DestroyCallsDestroyJointOnWorld)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
EXPECT_CALL(*m_mockWorld, destroyJoint(_));
joint.destroy();
}
TEST_F(Box2dJointTest, DestroyJointWithoutWorld)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
m_mockWorld.reset();
joint.destroy();
}
TEST_F(Box2dJointTest, CreateJointWithNullptrWorldRaisesException)
{
auto func = []() { jt::Box2DJoint joint { nullptr, nullptr }; };
ASSERT_THROW(func(), std::invalid_argument);
}
| 22.958904 | 89 | 0.713604 | Thunraz |
a1d04f04c3dab7531aaa6a32c18821df6a9a8a5d | 316 | cpp | C++ | src/pot.cpp | JulianNeeleman/kattis | 035c1113ffb397c2d8538af8ba16b7ee4160393d | [
"MIT"
] | null | null | null | src/pot.cpp | JulianNeeleman/kattis | 035c1113ffb397c2d8538af8ba16b7ee4160393d | [
"MIT"
] | 1 | 2017-05-16T15:57:29.000Z | 2017-05-17T19:43:56.000Z | src/pot.cpp | JulianNeeleman/kattis | 035c1113ffb397c2d8538af8ba16b7ee4160393d | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
int main() {
int N, ans = 0;
cin >> N;
for(int i = 0; i < N; i++) {
int P;
cin >> P;
int b = P / 10,
e = P % 10;
ans += pow(b, e);
}
cout << ans << endl;
return 0;
} | 11.703704 | 29 | 0.531646 | JulianNeeleman |
a1d2d3fdd5f9cd898d5ad7629afc5b5efab9c5a2 | 6,106 | cxx | C++ | Base/IO/Testing/itktubeMetaClassPDFTest.cxx | jcfr/TubeTK | 3791790e206b5627a35c46f86eeb9671c8d4190f | [
"Apache-2.0"
] | 1 | 2019-07-19T09:27:37.000Z | 2019-07-19T09:27:37.000Z | Base/IO/Testing/itktubeMetaClassPDFTest.cxx | jcfr/TubeTK | 3791790e206b5627a35c46f86eeb9671c8d4190f | [
"Apache-2.0"
] | null | null | null | Base/IO/Testing/itktubeMetaClassPDFTest.cxx | jcfr/TubeTK | 3791790e206b5627a35c46f86eeb9671c8d4190f | [
"Apache-2.0"
] | 1 | 2019-07-19T09:28:56.000Z | 2019-07-19T09:28:56.000Z | /*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 "itktubeMetaClassPDF.h"
#include <cstdlib>
int itktubeMetaClassPDFTest( int argc, char * argv[] )
{
if( argc != 2 )
{
std::cout << "Usage: testname <tempfilename>" << std::endl;
return EXIT_FAILURE;
}
itk::tube::MetaClassPDF pdf1;
std::vector< unsigned int > dimSize(2);
dimSize[0] = 10;
dimSize[1] = 10;
std::vector< double > binMin(2);
binMin[0] = -5;
binMin[1] = 20;
std::vector< double > binSize(2);
binSize[0] = 10;
binSize[1] = 5;
float data[100];
for( unsigned int i = 0; i < 100; ++i )
{
data[i] = i;
}
pdf1.InitializeEssential( 2, dimSize, binMin, binSize, data );
bool result = EXIT_SUCCESS;
if( pdf1.GetBinMin()[0] != -5 )
{
std::cout << "BinMin Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetBinSize()[0] != 10 )
{
std::cout << "BinMin Initialize failed" << std::endl;
return EXIT_FAILURE;
}
binMin[0] = 5;
binSize[0] = 5;
pdf1.SetBinMin( binMin );
pdf1.SetBinSize( binSize );
pdf1.SetVoidId( 1 );
pdf1.SetErodeRadius( 5 );
pdf1.SetHoleFillIterations( 20 );
pdf1.SetHistogramSmoothingStandardDeviation( 2 );
pdf1.SetProbabilityImageSmoothingStandardDeviation( 1 );
pdf1.SetOutlierRejectPortion( 0.2 );
pdf1.SetReclassifyNotObjectLabels( true );
pdf1.SetReclassifyObjectLabels( true );
pdf1.SetForceClassification( true );
pdf1.SetDraft( true );
pdf1.Write( argv[1] );
itk::tube::MetaClassPDF pdf2( argv[1] );
if( pdf1.GetNumberOfFeatures() != pdf2.GetNumberOfFeatures() ||
pdf1.GetNumberOfBinsPerFeature()[0] !=
pdf2.GetNumberOfBinsPerFeature()[0] ||
pdf1.GetNumberOfBinsPerFeature()[1] !=
pdf2.GetNumberOfBinsPerFeature()[1] ||
pdf1.GetBinMin()[0] != pdf2.GetBinMin()[0] ||
pdf1.GetBinMin()[1] != pdf2.GetBinMin()[1] ||
pdf1.GetBinSize()[0] != pdf2.GetBinSize()[0] ||
pdf1.GetBinSize()[1] != pdf2.GetBinSize()[1] )
{
std::cout << pdf2.GetBinMin()[0] << ", " << pdf2.GetBinMin()[1]
<< std::endl;
std::cout << pdf2.GetBinSize()[0] << ", " << pdf2.GetBinSize()[1]
<< std::endl;
std::cout << "Written file and read file do not match" << std::endl;
return EXIT_FAILURE;
}
for( unsigned int i = 0; i < 100; ++i )
{
if( pdf2.GetPDF()[i] != i )
{
std::cout << "Written and read data does not match" << std::endl;
result = EXIT_FAILURE;
}
}
if( pdf1.GetVoidId() != pdf2.GetVoidId() )
{
std::cout << "VoidId Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetErodeRadius() != pdf2.GetErodeRadius() )
{
std::cout << "ErodeRadius Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetHoleFillIterations() != pdf2.GetHoleFillIterations() )
{
std::cout << "HoleFillIterations Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetHistogramSmoothingStandardDeviation() !=
pdf2.GetHistogramSmoothingStandardDeviation() )
{
std::cout << "HistogramSmoothingStandardDeviation Initialize failed"
<< std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetProbabilityImageSmoothingStandardDeviation() !=
pdf2.GetProbabilityImageSmoothingStandardDeviation() )
{
std::cout
<< "ProbabilityImageSmoothingStandardDeviation Initialize failed"
<< std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetOutlierRejectPortion() != pdf2.GetOutlierRejectPortion() )
{
std::cout << "OutlierRejectPortion Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetReclassifyObjectLabels() != pdf2.GetReclassifyObjectLabels() )
{
std::cout << "ReclassifyObjectLabels Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetReclassifyNotObjectLabels() !=
pdf2.GetReclassifyNotObjectLabels() )
{
std::cout << "ReclassifyNotObjectLabels Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetForceClassification() != pdf2.GetForceClassification() )
{
std::cout << "ForceClassification Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
if( pdf1.GetDraft() != pdf2.GetDraft() )
{
std::cout << "Draft Initialize failed" << std::endl;
result = EXIT_FAILURE;
}
pdf2.SetPDF( pdf1.ExportPDF() );
itk::tube::MetaClassPDF pdf3( 2, dimSize, binMin, binSize, data );
pdf3.Write( argv[1] );
dimSize[1] = 20;
pdf3.SetNumberOfBinsPerFeature( dimSize );
pdf3.Read( argv[1] );
if( pdf1.GetNumberOfFeatures() != pdf3.GetNumberOfFeatures() ||
pdf1.GetNumberOfBinsPerFeature()[0] !=
pdf3.GetNumberOfBinsPerFeature()[0] ||
pdf1.GetNumberOfBinsPerFeature()[1] !=
pdf3.GetNumberOfBinsPerFeature()[1] ||
pdf1.GetBinMin()[0] != pdf3.GetBinMin()[0] ||
pdf1.GetBinMin()[1] != pdf3.GetBinMin()[1] ||
pdf1.GetBinSize()[0] != pdf3.GetBinSize()[0] ||
pdf1.GetBinSize()[1] != pdf3.GetBinSize()[1] )
{
std::cout << "Re-written file and read file do not match" << std::endl;
return EXIT_FAILURE;
}
for( unsigned int i = 0; i < 100; ++i )
{
if( pdf3.GetPDF()[i] != i )
{
std::cout << "Re-written and read data does not match" << std::endl;
result = EXIT_FAILURE;
}
}
return result;
}
| 30.683417 | 76 | 0.628562 | jcfr |
a1d322f14d07e8cf043b041acf103d16e6012e80 | 7,914 | cpp | C++ | src/nvpsg/WaveformUtility.cpp | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 32 | 2016-06-17T05:04:26.000Z | 2022-03-28T17:54:44.000Z | src/nvpsg/WaveformUtility.cpp | timburrow/openvnmrj-source | f5e65eb2db4bded3437701f0fa91abd41928579c | [
"Apache-2.0"
] | 128 | 2016-07-13T17:09:02.000Z | 2022-03-28T17:53:52.000Z | src/nvpsg/WaveformUtility.cpp | timburrow/openvnmrj-source | f5e65eb2db4bded3437701f0fa91abd41928579c | [
"Apache-2.0"
] | 102 | 2016-01-23T15:27:16.000Z | 2022-03-20T05:41:54.000Z | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/* WaveformUtility.cpp */
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "WaveformUtility.h"
#include "cpsg.h"
#include "FFKEYS.h"
#define OFFSETPULSE_TIMESLICE (0.00000020L)
extern int bgflag;
WaveformUtility::WaveformUtility()
{ }
cPatternEntry *WaveformUtility::readRFWaveform(char *name, RFController *rf1, unsigned int *pStartPos, int rawwfgsize, double totalDuration)
{
/* read in a waveform file .RF and populate the incoming array & the cPatternEntry
Waveform is not added to Pattern Store in Control */
int i,l;
double f1,f2,f3,f4,f5,scalef;
double pwrf;
int wcount, eventcount, repeats;
int phaseWord, ampWord, gateWord;
char tname[200];
cPatternEntry *tmp;
pwrf=0.0;
wcount = 0; eventcount = 0;
scalef = 4095.0/1023.0;
strcpy(tname,name);
i = rf1->findPatternFile(tname);
if (i != 1)
{
text_error("%s could not find %s", "WaveformUtility readRFWaveform", tname);
psg_abort(1);
}
wcount=0; eventcount=0;
unsigned int *pOut = pStartPos;
// read in the file
do
{
l = rf1->scanLine(&f1,&f2,&f3,&f4,&f5);
if ((l > 2) && (f3 < 0.5))
{
scalef = 4095.0/f2;
continue;
}
repeats = 1;
if (l > 2) // 255 is low??
repeats = ((int) f3) & 0xff;
gateWord = GATEKEY | (RFGATEON(X_OUT) & 0xffffff);
switch (l)
{
case 4:
if (((int)f4) & 0x1)
{
gateWord = GATEKEY | (RFGATEON(X_OUT) & 0xffffff);
}
else
{
gateWord = GATEKEY | (RFGATEOFF(X_OUT) & 0xffffff);
}
case 3:
case 2:
ampWord = RFAMPKEY | rf1->amp2Binary(f2*scalef);
phaseWord = (rf1->degrees2Binary(f1) | RFPHASEKEY);
do
{
*pOut++ = gateWord;
*pOut++ = ampWord;
*pOut++ = phaseWord;
*pOut++ = LATCHKEY | DURATIONKEY; // no duration value yet
eventcount++;
wcount += 4;
repeats--;
} while (repeats > 0);
}
if (wcount > rawwfgsize)
{
abort_message("waveform too large for swift_acquire. create parameter largewfgsize and set it to value over %d",rawwfgsize);
}
} while (l > -1);
// fill in the duration in words with DURATION KEY
double duration = totalDuration/eventcount;
for (int i=0; i<wcount; i++)
{
if ( (*(pStartPos+i) & (31<<26)) == DURATIONKEY)
{
*(pStartPos+i) |= rf1->calcTicks(duration);
}
}
if (eventcount > 0)
{
pwrf = sqrt((pwrf)/((double) eventcount));
tmp = new cPatternEntry(name,1 /* flag */, eventcount,wcount);
tmp->setPowerFraction(pwrf); // use this in calling code.
}
else
abort_message("RF waveform file %s has no events",name);
return(tmp);
}
cPatternEntry *WaveformUtility::readDECWaveform(char *name, RFController *rf1, unsigned int *array)
{
/* read in a waveform file .RF and populate the incoming array & the cPatternEntry
Waveform is not added to Pattern Store in Controller */
return new cPatternEntry("abc",1, 1, 1024, 1024);
}
cPatternEntry *WaveformUtility::makeOffsetPattern(unsigned int *inp, unsigned int *out, RFController *rf1, int nInc, double phss, double pacc, int flag, char mode, char *tag, char *emsg, int action)
{
/* Frequency shift an input waveform by adding phase ramp
Waveform is not added to Pattern Store in Controller */
return new cPatternEntry("abc",1, 1, 1024, 1024);
}
cPatternEntry *WaveformUtility::weaveGatePattern(unsigned int *pFinalWfgOut, unsigned int *pInp, int num_rawwords, unsigned int *pGatePattern, int num_gatewords, long long totalDurationTicks)
{
/* Weave in a gate pattern into an input waveform array
Waveform is not added to Pattern Store in Controller */
int wcount, eventcount;
unsigned int *pRawWfgStart;
unsigned int *pOut;
//printf("WU:wGP num_rawwords=%d num_gatewords=%d totaDurationTicks=%lld\n",num_rawwords,num_gatewords,totalDurationTicks);
// weave two waveform patterns together to form an output pattern
int A_DUR_WORD=0, A_GATE_WORD=0, A_PHASE_WORD=0, A_AMP_WORD=0;
int B_DUR_WORD=0, B_GATE_WORD=0;
int runWord = 0;
unsigned int *pA, *pB;
pA = pInp;
pB = pGatePattern;
pRawWfgStart = pInp;
pOut = pFinalWfgOut;
wcount = 0;
eventcount = 0;
int stopLoad, lastAmpWord, lastGateWord, lastPhaseWord ;
stopLoad = 0; lastAmpWord=0; lastGateWord=0; lastPhaseWord=0;
while ( 1 ) // over the entire acq time
{
// read in one state from A stream ( raw wfg )
if ( pA >= (pRawWfgStart + num_rawwords))
pA = pRawWfgStart;
if ( A_DUR_WORD == 0)
{
A_GATE_WORD = (*pA);
pA++;
A_AMP_WORD = (*pA);
pA++;
A_PHASE_WORD= (*pA);
pA++;
A_DUR_WORD = (*pA) & 0x3ffffff ;
pA++;
}
// read in one state from B stream ( gate array )
if ( pB >= (pGatePattern + num_gatewords) )
pB = pGatePattern;
if ( B_DUR_WORD == 0 )
{
B_GATE_WORD = (*pB);
pB++;
B_DUR_WORD = (*pB) & 0x3ffffff;
pB++;
}
// check for any zero duration words
if ( (A_DUR_WORD <= 0) || (B_DUR_WORD <= 0))
{
abort_message("psg internal error in swift waveform merge duration word is 0. abort!\n");
}
// Now do the merging of the two streams
// logic to determine if we need to stop!
if ( A_DUR_WORD <= B_DUR_WORD )
runWord = A_DUR_WORD; // choose shortest
else
runWord = B_DUR_WORD;
//
if (totalDurationTicks <= runWord)
{
runWord = totalDurationTicks;
stopLoad = 1;
}
else
stopLoad = 0;
if (A_AMP_WORD != lastAmpWord)
{
//putPattern(A_AMP_WORD);
(*pOut++) = (A_AMP_WORD);
wcount++;
lastAmpWord = A_AMP_WORD;
}
if (A_PHASE_WORD != lastPhaseWord)
{
//putPattern(A_PHASE_WORD);
(*pOut++) = (A_PHASE_WORD);
wcount++;
lastPhaseWord = A_PHASE_WORD;
}
// gateWord comes from the B stream (gate array)
if (B_GATE_WORD != lastGateWord)
{
//putPattern(B_GATE_WORD);
(*pOut++) = (B_GATE_WORD);
wcount++;
lastGateWord = B_GATE_WORD;
}
// Now examine the two durations: A_DUR_WORD or B_DUR_WORD, which is shorter?
// GATEWORD from B stream (gate array) has precedence
if (runWord <= 1) // catch a single or zero tick
runWord = 2;
if (runWord >= 2) // insure legal time..
{
//putPattern(LATCHKEY | DURATIONKEY | runWord);
(*pOut++) = (LATCHKEY | DURATIONKEY | runWord);
wcount++;
eventcount++;
}
else
printf("psg internal error in swift waveform merge duration word invalid. abort!\n");
totalDurationTicks -= runWord;
B_DUR_WORD -= runWord;
A_DUR_WORD -= runWord;
if (A_DUR_WORD < 0) A_DUR_WORD = 0;
if (B_DUR_WORD < 0) B_DUR_WORD = 0;
if (stopLoad || (totalDurationTicks <= 0) ) break;
}
// add the waveform to Pattern List
cPatternEntry *tmp;
if (eventcount > 0)
{
tmp = new cPatternEntry("swift",1,eventcount,wcount);
}
else
abort_message("pattern swift has no events");
return tmp;
}
| 26.646465 | 198 | 0.580238 | DanIverson |
a1d3c14a1377aeb241db0d03dba8488685923ac1 | 1,221 | cpp | C++ | packages/simulation/tst/gameDataTest.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 2 | 2021-01-15T13:27:19.000Z | 2021-08-04T08:40:52.000Z | packages/simulation/tst/gameDataTest.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | null | null | null | packages/simulation/tst/gameDataTest.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 5 | 2018-05-01T10:39:31.000Z | 2022-03-25T03:02:35.000Z | // Copyright 2018-2019 Coen Tempelaars (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* gameDataTest.cpp
*
* Created on: Dec 27, 2018
* Author: Coen Tempelaars
*/
#include <gtest/gtest.h>
#include "int/gameDataFactory.hpp"
class AGame : public ::testing::Test
{
public:
AGame()
{
gameData = GameDataFactory::createGameData(5, 5);
}
GameData gameData;
};
TEST_F(AGame, ConsistsOfTwoTeams)
{
EXPECT_EQ(2, gameData.team.size());
}
TEST_F(AGame, ConsistsOfFiveRobotsPerTeam)
{
EXPECT_EQ(5, gameData.team[TeamID::A].size());
EXPECT_EQ(5, gameData.team[TeamID::B].size());
}
TEST_F(AGame, NoRobotIsMoving)
{
EXPECT_FALSE(gameData.anyRobotIsMoving());
}
TEST_F(AGame, OneRobotIsMoving)
{
gameData.team[TeamID::A][RobotID::r1].setVelocity(Velocity2D(1.0, 1.0, 0.0));
EXPECT_TRUE(gameData.anyRobotIsMoving());
}
TEST_F(AGame, DistanceOfClosestRobotToPOI)
{
EXPECT_FLOAT_EQ(1.0, gameData.getDistanceOfClosestRobotTo(Point2D(0.0, -1.0), TeamID::A));
EXPECT_FLOAT_EQ(3.0, gameData.getDistanceOfClosestRobotTo(Point2D(0.0, -1.0), TeamID::B));
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 20.694915 | 94 | 0.692056 | Falcons-Robocup |
a1d5ed260f26aa9f30174ca4a37bff0e7694c911 | 4,312 | cpp | C++ | CHEDAN_Universe/answer.cpp | Kwongrf/CHEDAN_Universe_v2 | 6d001ce08def738c4a145b4c4752e6b63298ed76 | [
"Apache-2.0"
] | null | null | null | CHEDAN_Universe/answer.cpp | Kwongrf/CHEDAN_Universe_v2 | 6d001ce08def738c4a145b4c4752e6b63298ed76 | [
"Apache-2.0"
] | null | null | null | CHEDAN_Universe/answer.cpp | Kwongrf/CHEDAN_Universe_v2 | 6d001ce08def738c4a145b4c4752e6b63298ed76 | [
"Apache-2.0"
] | null | null | null | <<<<<<< HEAD
#include "answer.h"
#include "global.h"
Answer::Answer()
{
}
void Answer::created(int id,int userId,QString content,QString createtime)
{
this->setId(id);
this->setUserId(userId);
this->setContent(content);
this->setTime(createtime);
}
int Answer::getPraisedNum()
{
return this->praisedNum;
}
void Answer::setPraisedNum(int praisedNum)
{
this->praisedNum = praisedNum;
}
int Answer::getId()
{
return this->id;
}
int Answer::getUserId()
{
return this->userId;
}
int Answer::getQuestionId()
{
return this->questionId;
}
QString Answer::getContent()
{
return this->content;
}
QString Answer::getTime()
{
return this->createtime;
}
void Answer::setId(int id)
{
this->id = id;
}
void Answer::setUserId(int id)
{
this->userId = id;
}
void Answer::setQuestionId(int id)
{
this->questionId = id;
}
void Answer::setContent(QString content)
{
this->content = content;
}
void Answer::setTime(QString createtime)
{
this->createtime = createtime;
}
std::ostream &operator<<(std::ostream &os,const Answer &ans)//这里出现了一个坑就是我把它定义在.h文件里,导致multiple definition,可以用inline或者定义到cpp
{
//os<<ans.getId()<<","<<ans.getUserId()<<","<<ans.getQuestionId()<<","<<ans.getPraisedNum()<<","<<ans.getContent()<<","<<ans.getTime();
QByteArray ba1 = ans.content.toLatin1();
char *contentstr = ba1.data();
QByteArray ba2 = ans.createtime.toLatin1();
char *timestr = ba2.data();
os<<ans.id<<ans.userId<<ans.questionId<<ans.praisedNum<<contentstr<<timestr;
Global::insert(ans);
return os;
}
std::istream &operator>>(std::istream &is,Answer &ans)
{
ans = Global::getAnswer(ans.getId());
QByteArray ba1 = ans.content.toLatin1();
char *contentstr = ba1.data();
QByteArray ba2 = ans.createtime.toLatin1();
char *timestr = ba2.data();
//is>>ans.getId()>>",">>ans.getUserId()>>",">>ans.getQuestionId()>>",">>ans.getPraisedNum()>>",">>ans.getContent()>>","<<ans.getTime();
is>>ans.id>>ans.userId>>ans.questionId>>ans.praisedNum>>contentstr>>timestr;
//输入判断
if(!is)
ans = Answer(); //如果失败,默认初始化
return is;
}
=======
#include "answer.h"
#include "global.h"
Answer::Answer()
{
}
void Answer::created(int id,int userId,QString content,QString createtime)
{
this->setId(id);
this->setUserId(userId);
this->setContent(content);
this->setTime(createtime);
}
int Answer::getPraisedNum()
{
return this->praisedNum;
}
void Answer::setPraisedNum(int praisedNum)
{
this->praisedNum = praisedNum;
}
int Answer::getId()
{
return this->id;
}
int Answer::getUserId()
{
return this->userId;
}
int Answer::getQuestionId()
{
return this->questionId;
}
QString Answer::getContent()
{
return this->content;
}
QString Answer::getTime()
{
return this->createtime;
}
void Answer::setId(int id)
{
this->id = id;
}
void Answer::setUserId(int id)
{
this->userId = id;
}
void Answer::setQuestionId(int id)
{
this->questionId = id;
}
void Answer::setContent(QString content)
{
this->content = content;
}
void Answer::setTime(QString createtime)
{
this->createtime = createtime;
}
std::ostream &operator<<(std::ostream &os,const Answer &ans)//这里出现了一个坑就是我把它定义在.h文件里,导致multiple definition,可以用inline或者定义到cpp
{
//os<<ans.getId()<<","<<ans.getUserId()<<","<<ans.getQuestionId()<<","<<ans.getPraisedNum()<<","<<ans.getContent()<<","<<ans.getTime();
QByteArray ba1 = ans.content.toLatin1();
char *contentstr = ba1.data();
QByteArray ba2 = ans.createtime.toLatin1();
char *timestr = ba2.data();
os<<ans.id<<ans.userId<<ans.questionId<<ans.praisedNum<<contentstr<<timestr;
Global::insert(ans);
return os;
}
std::istream &operator>>(std::istream &is,Answer &ans)
{
ans = Global::getAnswer(ans.getId());
QByteArray ba1 = ans.content.toLatin1();
char *contentstr = ba1.data();
QByteArray ba2 = ans.createtime.toLatin1();
char *timestr = ba2.data();
//is>>ans.getId()>>",">>ans.getUserId()>>",">>ans.getQuestionId()>>",">>ans.getPraisedNum()>>",">>ans.getContent()>>","<<ans.getTime();
is>>ans.id>>ans.userId>>ans.questionId>>ans.praisedNum>>contentstr>>timestr;
//输入判断
if(!is)
ans = Answer(); //如果失败,默认初始化
return is;
}
>>>>>>> cfdf638c3bdfa8efdbbb0c911ad54fe243c63989
| 21.137255 | 139 | 0.649814 | Kwongrf |
a1d5f4fea153f2541dadf6b73858d3c145f66815 | 11,899 | cc | C++ | tile/lang/fpconv.cc | redoclag/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 4,535 | 2017-10-20T05:03:57.000Z | 2022-03-30T15:42:33.000Z | tile/lang/fpconv.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 984 | 2017-10-20T17:16:09.000Z | 2022-03-30T05:43:18.000Z | tile/lang/fpconv.cc | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 492 | 2017-10-20T18:22:32.000Z | 2022-03-30T09:00:05.000Z | /*
The MIT License
Copyright (c) 2013 Andreas Samoljuk
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 "tile/lang/fpconv.h"
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#define npowers 87
#define steppowers 8
#define firstpower -348 /* 10 ^ -348 */
#define expmax -32
#define expmin -60
typedef struct Fp {
uint64_t frac;
int exp;
} Fp;
static Fp powers_ten[] = {
{18054884314459144840U, -1220}, {13451937075301367670U, -1193}, {10022474136428063862U, -1166},
{14934650266808366570U, -1140}, {11127181549972568877U, -1113}, {16580792590934885855U, -1087},
{12353653155963782858U, -1060}, {18408377700990114895U, -1034}, {13715310171984221708U, -1007},
{10218702384817765436U, -980}, {15227053142812498563U, -954}, {11345038669416679861U, -927},
{16905424996341287883U, -901}, {12595523146049147757U, -874}, {9384396036005875287U, -847},
{13983839803942852151U, -821}, {10418772551374772303U, -794}, {15525180923007089351U, -768},
{11567161174868858868U, -741}, {17236413322193710309U, -715}, {12842128665889583758U, -688},
{9568131466127621947U, -661}, {14257626930069360058U, -635}, {10622759856335341974U, -608},
{15829145694278690180U, -582}, {11793632577567316726U, -555}, {17573882009934360870U, -529},
{13093562431584567480U, -502}, {9755464219737475723U, -475}, {14536774485912137811U, -449},
{10830740992659433045U, -422}, {16139061738043178685U, -396}, {12024538023802026127U, -369},
{17917957937422433684U, -343}, {13349918974505688015U, -316}, {9946464728195732843U, -289},
{14821387422376473014U, -263}, {11042794154864902060U, -236}, {16455045573212060422U, -210},
{12259964326927110867U, -183}, {18268770466636286478U, -157}, {13611294676837538539U, -130},
{10141204801825835212U, -103}, {15111572745182864684U, -77}, {11258999068426240000U, -50},
{16777216000000000000U, -24}, {12500000000000000000U, 3}, {9313225746154785156U, 30},
{13877787807814456755U, 56}, {10339757656912845936U, 83}, {15407439555097886824U, 109},
{11479437019748901445U, 136}, {17105694144590052135U, 162}, {12744735289059618216U, 189},
{9495567745759798747U, 216}, {14149498560666738074U, 242}, {10542197943230523224U, 269},
{15709099088952724970U, 295}, {11704190886730495818U, 322}, {17440603504673385349U, 348},
{12994262207056124023U, 375}, {9681479787123295682U, 402}, {14426529090290212157U, 428},
{10748601772107342003U, 455}, {16016664761464807395U, 481}, {11933345169920330789U, 508},
{17782069995880619868U, 534}, {13248674568444952270U, 561}, {9871031767461413346U, 588},
{14708983551653345445U, 614}, {10959046745042015199U, 641}, {16330252207878254650U, 667},
{12166986024289022870U, 694}, {18130221999122236476U, 720}, {13508068024458167312U, 747},
{10064294952495520794U, 774}, {14996968138956309548U, 800}, {11173611982879273257U, 827},
{16649979327439178909U, 853}, {12405201291620119593U, 880}, {9242595204427927429U, 907},
{13772540099066387757U, 933}, {10261342003245940623U, 960}, {15290591125556738113U, 986},
{11392378155556871081U, 1013}, {16975966327722178521U, 1039}, {12648080533535911531U, 1066}};
#define fracmask 0x000FFFFFFFFFFFFFU
#define expmask 0x7FF0000000000000U
#define hiddenbit 0x0010000000000000U
#define signmask 0x8000000000000000U
#define expbias (1023 + 52)
#define absv(n) ((n) < 0 ? -(n) : (n))
#define minv(a, b) ((a) < (b) ? (a) : (b))
static uint64_t tens[] = {10000000000000000000U,
1000000000000000000U,
100000000000000000U,
10000000000000000U,
1000000000000000U,
100000000000000U,
10000000000000U,
1000000000000U,
100000000000U,
10000000000U,
1000000000U,
100000000U,
10000000U,
1000000U,
100000U,
10000U,
1000U,
100U,
10U,
1U};
static Fp find_cachedpow10(int exp, int* k) {
const double one_log_ten = 0.30102999566398114;
int approx = -(exp + npowers) * one_log_ten;
int idx = (approx - firstpower) / steppowers;
for (;;) {
int current = exp + powers_ten[idx].exp + 64;
if (current < expmin) {
idx++;
continue;
}
if (current > expmax) {
idx--;
continue;
}
*k = (firstpower + idx * steppowers);
return powers_ten[idx];
}
}
static inline uint64_t get_dbits(double d) {
union {
double dbl;
uint64_t i;
} dbl_bits = {d};
return dbl_bits.i;
}
static Fp build_fp(double d) {
uint64_t bits = get_dbits(d);
Fp fp;
fp.frac = bits & fracmask;
fp.exp = (bits & expmask) >> 52;
if (fp.exp) {
fp.frac += hiddenbit;
fp.exp -= expbias;
} else {
fp.exp = -expbias + 1;
}
return fp;
}
static void normalize(Fp* fp) {
while ((fp->frac & hiddenbit) == 0) {
fp->frac <<= 1;
fp->exp--;
}
int shift = 64 - 52 - 1;
fp->frac <<= shift;
fp->exp -= shift;
}
static void get_normalized_boundaries(Fp* fp, Fp* lower, Fp* upper) {
upper->frac = (fp->frac << 1) + 1;
upper->exp = fp->exp - 1;
while ((upper->frac & (hiddenbit << 1)) == 0) {
upper->frac <<= 1;
upper->exp--;
}
int u_shift = 64 - 52 - 2;
upper->frac <<= u_shift;
upper->exp = upper->exp - u_shift;
int l_shift = fp->frac == hiddenbit ? 2 : 1;
lower->frac = (fp->frac << l_shift) - 1;
lower->exp = fp->exp - l_shift;
lower->frac <<= lower->exp - upper->exp;
lower->exp = upper->exp;
}
static Fp multiply(Fp* a, Fp* b) {
const uint64_t lomask = 0x00000000FFFFFFFF;
uint64_t ah_bl = (a->frac >> 32) * (b->frac & lomask);
uint64_t al_bh = (a->frac & lomask) * (b->frac >> 32);
uint64_t al_bl = (a->frac & lomask) * (b->frac & lomask);
uint64_t ah_bh = (a->frac >> 32) * (b->frac >> 32);
uint64_t tmp = (ah_bl & lomask) + (al_bh & lomask) + (al_bl >> 32);
/* round up */
tmp += 1U << 31;
Fp fp = {ah_bh + (ah_bl >> 32) + (al_bh >> 32) + (tmp >> 32), a->exp + b->exp + 64};
return fp;
}
static void round_digit(char* digits, int ndigits, uint64_t delta, uint64_t rem, uint64_t kappa, uint64_t frac) {
while (rem < frac && delta - rem >= kappa && (rem + kappa < frac || frac - rem > rem + kappa - frac)) {
digits[ndigits - 1]--;
rem += kappa;
}
}
static int generate_digits(Fp* fp, Fp* upper, Fp* lower, char* digits, int* K) {
uint64_t wfrac = upper->frac - fp->frac;
uint64_t delta = upper->frac - lower->frac;
Fp one;
one.frac = 1ULL << -upper->exp;
one.exp = upper->exp;
uint64_t part1 = upper->frac >> -one.exp;
uint64_t part2 = upper->frac & (one.frac - 1);
int idx = 0, kappa = 10;
uint64_t* divp;
/* 1000000000 */
for (divp = tens + 10; kappa > 0; divp++) {
uint64_t div = *divp;
unsigned digit = static_cast<unsigned>(part1 / div);
if (digit || idx) {
digits[idx++] = digit + '0';
}
part1 -= digit * div;
kappa--;
uint64_t tmp = (part1 << -one.exp) + part2;
if (tmp <= delta) {
*K += kappa;
round_digit(digits, idx, delta, tmp, div << -one.exp, wfrac);
return idx;
}
}
/* 10 */
uint64_t* unit = tens + 18;
for (;;) {
part2 *= 10;
delta *= 10;
kappa--;
unsigned digit = static_cast<unsigned>(part2 >> -one.exp);
if (digit || idx) {
digits[idx++] = digit + '0';
}
part2 &= one.frac - 1;
if (part2 < delta) {
*K += kappa;
round_digit(digits, idx, delta, part2, one.frac, wfrac * *unit);
return idx;
}
unit--;
}
}
static int fpconv_grisu2(double d, char* digits, int* K) {
Fp w = build_fp(d);
Fp lower, upper;
get_normalized_boundaries(&w, &lower, &upper);
normalize(&w);
int k;
Fp cp = find_cachedpow10(upper.exp, &k);
w = multiply(&w, &cp);
upper = multiply(&upper, &cp);
lower = multiply(&lower, &cp);
lower.frac++;
upper.frac--;
*K = -k;
return generate_digits(&w, &upper, &lower, digits, K);
}
static int emit_digits(char* digits, int ndigits, char* dest, int K, bool neg) {
int exp = absv(K + ndigits - 1);
/* write plain integer */
if (K >= 0 && (exp < (ndigits + 7))) {
memcpy(dest, digits, ndigits);
memset(dest + ndigits, '0', K);
return ndigits + K;
}
/* write decimal w/o scientific notation */
if (K < 0 && (K > -7 || exp < 4)) {
int offset = ndigits - absv(K);
/* fp < 1.0 -> write leading zero */
if (offset <= 0) {
offset = -offset;
dest[0] = '0';
dest[1] = '.';
memset(dest + 2, '0', offset);
memcpy(dest + offset + 2, digits, ndigits);
return ndigits + 2 + offset;
/* fp > 1.0 */
} else {
memcpy(dest, digits, offset);
dest[offset] = '.';
memcpy(dest + offset + 1, digits + offset, ndigits - offset);
return ndigits + 1;
}
}
/* write decimal w/ scientific notation */
ndigits = minv(ndigits, 18 - neg);
int idx = 0;
dest[idx++] = digits[0];
if (ndigits > 1) {
dest[idx++] = '.';
memcpy(dest + idx, digits + 1, ndigits - 1);
idx += ndigits - 1;
}
dest[idx++] = 'e';
char sign = K + ndigits - 1 < 0 ? '-' : '+';
dest[idx++] = sign;
int cent = 0;
if (exp > 99) {
cent = exp / 100;
dest[idx++] = cent + '0';
exp -= cent * 100;
}
if (exp > 9) {
int dec = exp / 10;
dest[idx++] = dec + '0';
exp -= dec * 10;
} else if (cent) {
dest[idx++] = '0';
}
dest[idx++] = exp % 10 + '0';
return idx;
}
static int filter_special(double fp, char* dest) {
if (fp == 0.0) {
dest[0] = '0';
return 1;
}
uint64_t bits = get_dbits(fp);
bool nan = (bits & expmask) == expmask;
if (!nan) {
return 0;
}
if (bits & fracmask) {
dest[0] = 'n';
dest[1] = 'a';
dest[2] = 'n';
} else {
dest[0] = 'i';
dest[1] = 'n';
dest[2] = 'f';
}
return 3;
}
static int fpconv_dtoa(double d, char dest[24]) {
char digits[18];
int str_len = 0;
bool neg = false;
if (get_dbits(d) & signmask) {
dest[0] = '-';
str_len++;
neg = true;
}
int spec = filter_special(d, dest + str_len);
if (spec) {
return str_len + spec;
}
int K = 0;
int ndigits = fpconv_grisu2(d, digits, &K);
str_len += emit_digits(digits, ndigits, dest + str_len, K, neg);
return str_len;
}
namespace vertexai {
namespace tile {
namespace lang {
std::string DoubleToString(double f) {
char buf[24];
int str_len = fpconv_dtoa(f, buf);
return std::string(buf, str_len);
}
} // namespace lang
} // namespace tile
} // namespace vertexai
| 27.543981 | 113 | 0.603328 | redoclag |
a1d6550c64c7e456709826e6bc241890bb08aa65 | 567 | cpp | C++ | src/Looper.cpp | sovcik/iot-minilib | d325710e0476206d1397a3b941ce8e40703b6858 | [
"MIT"
] | null | null | null | src/Looper.cpp | sovcik/iot-minilib | d325710e0476206d1397a3b941ce8e40703b6858 | [
"MIT"
] | null | null | null | src/Looper.cpp | sovcik/iot-minilib | d325710e0476206d1397a3b941ce8e40703b6858 | [
"MIT"
] | null | null | null | #include "Looper.h"
LooperHandler::LooperHandler(){
_loopers = 0;
}
LooperHandler::~LooperHandler(){
LooperEntry *n, *e;
e = _loopers;
while (e->next){
n = e->next;
delete e;
e = n;
}
if (e) delete e;
_loopers = 0;
}
void LooperHandler::registerLooper(Looper *looper){
LooperEntry *le = new LooperEntry();
le->looper = looper;
le->next = _loopers;
_loopers = le;
}
void LooperHandler::loop(){
LooperEntry *n = _loopers;
while(n){
n->looper->loop();
n = n->next;
}
}
| 16.676471 | 51 | 0.552028 | sovcik |
a1d9290a99edc51de314d70e72f64b04709f91a8 | 3,211 | cpp | C++ | aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lexv2-models/model/ExportSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LexModelsV2
{
namespace Model
{
ExportSummary::ExportSummary() :
m_exportIdHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_fileFormat(ImportExportFileFormat::NOT_SET),
m_fileFormatHasBeenSet(false),
m_exportStatus(ExportStatus::NOT_SET),
m_exportStatusHasBeenSet(false),
m_creationDateTimeHasBeenSet(false),
m_lastUpdatedDateTimeHasBeenSet(false)
{
}
ExportSummary::ExportSummary(JsonView jsonValue) :
m_exportIdHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_fileFormat(ImportExportFileFormat::NOT_SET),
m_fileFormatHasBeenSet(false),
m_exportStatus(ExportStatus::NOT_SET),
m_exportStatusHasBeenSet(false),
m_creationDateTimeHasBeenSet(false),
m_lastUpdatedDateTimeHasBeenSet(false)
{
*this = jsonValue;
}
ExportSummary& ExportSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("exportId"))
{
m_exportId = jsonValue.GetString("exportId");
m_exportIdHasBeenSet = true;
}
if(jsonValue.ValueExists("resourceSpecification"))
{
m_resourceSpecification = jsonValue.GetObject("resourceSpecification");
m_resourceSpecificationHasBeenSet = true;
}
if(jsonValue.ValueExists("fileFormat"))
{
m_fileFormat = ImportExportFileFormatMapper::GetImportExportFileFormatForName(jsonValue.GetString("fileFormat"));
m_fileFormatHasBeenSet = true;
}
if(jsonValue.ValueExists("exportStatus"))
{
m_exportStatus = ExportStatusMapper::GetExportStatusForName(jsonValue.GetString("exportStatus"));
m_exportStatusHasBeenSet = true;
}
if(jsonValue.ValueExists("creationDateTime"))
{
m_creationDateTime = jsonValue.GetDouble("creationDateTime");
m_creationDateTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("lastUpdatedDateTime"))
{
m_lastUpdatedDateTime = jsonValue.GetDouble("lastUpdatedDateTime");
m_lastUpdatedDateTimeHasBeenSet = true;
}
return *this;
}
JsonValue ExportSummary::Jsonize() const
{
JsonValue payload;
if(m_exportIdHasBeenSet)
{
payload.WithString("exportId", m_exportId);
}
if(m_resourceSpecificationHasBeenSet)
{
payload.WithObject("resourceSpecification", m_resourceSpecification.Jsonize());
}
if(m_fileFormatHasBeenSet)
{
payload.WithString("fileFormat", ImportExportFileFormatMapper::GetNameForImportExportFileFormat(m_fileFormat));
}
if(m_exportStatusHasBeenSet)
{
payload.WithString("exportStatus", ExportStatusMapper::GetNameForExportStatus(m_exportStatus));
}
if(m_creationDateTimeHasBeenSet)
{
payload.WithDouble("creationDateTime", m_creationDateTime.SecondsWithMSPrecision());
}
if(m_lastUpdatedDateTimeHasBeenSet)
{
payload.WithDouble("lastUpdatedDateTime", m_lastUpdatedDateTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
| 23.785185 | 117 | 0.760822 | perfectrecall |
a1db887ad3e0071857721412f59e517d367fff9b | 2,017 | cpp | C++ | Contests/Atcoder_ABC_222/probF.cpp | francoisvogel/cp | ae59cf635ab19382d924344fbb137ab9ae631103 | [
"MIT"
] | 1 | 2021-10-02T15:40:33.000Z | 2021-10-02T15:40:33.000Z | Contests/Atcoder_ABC_222/probF.cpp | francoisvogel/cp | ae59cf635ab19382d924344fbb137ab9ae631103 | [
"MIT"
] | null | null | null | Contests/Atcoder_ABC_222/probF.cpp | francoisvogel/cp | ae59cf635ab19382d924344fbb137ab9ae631103 | [
"MIT"
] | null | null | null | /*
* File created on 10/09/2021 at 14:56:58.
* Link to problem:
* Description:
* Time complexity: O()
* Space complexity: O()
* Status: DEV (most of the time I don't update status, so it stays DEV which is the default value)
* Copyright: Ⓒ 2021 Francois Vogel
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace std;
using namespace __gnu_pbds;
#define pii pair<int, int>
#define f first
#define s second
#define vi vector<int>
#define all(x) x.begin(), x.end()
#define size(x) (int)(x.size())
#define pb push_back
#define ins insert
#define cls clear
#define int ll
#define ll long long
#define ld long double
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
const int siz = 2e5+40;
vector<pii> graph [siz];
int cost [siz];
int mx [siz];
int furthest [siz];
void dfs(int x, int p) {
mx[x] = cost[x];
for (pii y : graph[x]) if (y.f != p) {
dfs(y.f, x);
mx[x] = max(mx[x], mx[y.f]+y.s);
}
}
void calc(int x, int p, int till) {
furthest[x] = till;
vi ms;
ms.pb(cost[x]);
ms.pb(till);
for (pii y : graph[x]) if (y.f != p) {
int loc = mx[y.f]+y.s;
ms.pb(loc);
furthest[x] = max(furthest[x], loc);
}
sort(all(ms));
for (pii y : graph[x]) if (y.f != p) {
int loc = ms.back();
if (ms.back() == mx[y.f]+y.s) loc = ms[size(ms)-2];
loc += y.s;
calc(y.f, x, loc);
}
}
signed main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int n;
cin >> n;
for (int i = 0; i < n-1; i++) {
int na, nb, lw;
cin >> na >> nb >> lw;
na--;
nb--;
graph[na].pb(pii(nb, lw));
graph[nb].pb(pii(na, lw));
}
for (int i = 0; i < n; i++) cin >> cost[i];
dfs(0, -1);
calc(0, -1, 0);
for (int i = 0; i < n; i++) cout << furthest[i] << '\n';
cout.flush();
int d = 0;
d++;
} | 21.923913 | 100 | 0.548339 | francoisvogel |
a1df9c9046e271bdf30acb12203b7fba722c1f0a | 3,044 | hpp | C++ | src/opencv_bridge/shape_finder_impl.hpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | null | null | null | src/opencv_bridge/shape_finder_impl.hpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | null | null | null | src/opencv_bridge/shape_finder_impl.hpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | 1 | 2018-04-11T15:20:14.000Z | 2018-04-11T15:20:14.000Z | /*
MIT License
Copyright (c) 2018 Cognitive Machines
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 __opencv__bridge__shape__finder__impl__hpp__
#define __opencv__bridge__shape__finder__impl__hpp__
#include "../common_includes.hpp"
#include "../computed_result.hpp"
#include "../json_reader.hpp"
using namespace cv;
using namespace std;
namespace cm {
namespace lib_bridge {
const int k_threshold_min = 0 ;
const int k_threshold_max = 255 ;
bool circle_finder_impl(Mat& in,
double dp,
double min_dist,
double canny_param_1,
double canny_param_2,
int min_radius,
int max_radius,
bool clear_and_add,
computed_objects & circles_found);
bool rectangle_finder_impl(Mat &in,
int threshold_step,
double shape_appoximator_ratio,
double min_contour_area,
double max_contour_area,
double cosine_angle,
bool clear_and_add,
computed_objects & rectangles_found);
bool line_finder_impl(Mat &in,
double rho,
double theta,
double threshold,
double length_factor,
double max_seperation,
bool clear_and_add,
computed_objects & lines_found);
//Utility functions
double angle_between_points(cv::Point pt1, cv::Point pt2, cv::Point pt0);
bool get_tracker(Mat & image1, Mat & image2, cm::rectangle_i &tracker, int min_good_features, int nfeatures);
void drawBoundingBox(Mat image, vector<Point2f> bb);
struct time_counter
{
TickMeter tm;
explicit time_counter() {
tm.start();
}
~time_counter() {
tm.stop();
CM_LOG << "FPS = " << 1.0 / tm.getTimeSec() << std::endl;
}
};
}
}
#endif
| 32.042105 | 109 | 0.639947 | cognitive-machines |
a1e4e796164e3a04eb35f74968455d8692f77745 | 1,274 | cpp | C++ | src/constexpr/static_assert2.cpp | victorcruceru/my_tour_of_cplusplus | c9627e9355a8cf6eaa8f5d51a0001947cfe86e48 | [
"Beerware"
] | null | null | null | src/constexpr/static_assert2.cpp | victorcruceru/my_tour_of_cplusplus | c9627e9355a8cf6eaa8f5d51a0001947cfe86e48 | [
"Beerware"
] | null | null | null | src/constexpr/static_assert2.cpp | victorcruceru/my_tour_of_cplusplus | c9627e9355a8cf6eaa8f5d51a0001947cfe86e48 | [
"Beerware"
] | 1 | 2021-06-21T07:22:10.000Z | 2021-06-21T07:22:10.000Z | /*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Victor Cruceru wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
/*
* Description: Trying static_assert (compile time check) in various
* scenarios like template parameters and basic types.
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <type_traits>
/* check a template parameter value */
template <typename T, size_t L>
struct Record { // struct is just a class with all members public
static_assert(L >= 1, "Length must be a scalar >= 1");
T vector[L];
};
int main() {
// Record<std::string, 0> failed_rec; // This fails at compile time
Record<int, 10> ok_rec; // This is OK.
ok_rec = {{1, 2, 3}};
// Next two might fail or not at compile time depending on your machine
static_assert(sizeof(int) == 4, "int type must be of size 4");
static_assert(sizeof(int *) == 8, "int* pointer type must be of size 8");
return (EXIT_SUCCESS);
} | 35.388889 | 80 | 0.584772 | victorcruceru |
a1e67ee3ec0a3d9562b8636cac8c53768dc9b838 | 3,170 | cpp | C++ | libs/spirit/example/qi/calc6/calc6.cpp | oudream/boost_1_42_0 | e92227bf374e478030e89876ec353de6eecaeac0 | [
"BSL-1.0"
] | 3 | 2019-06-25T23:20:19.000Z | 2021-03-14T19:38:34.000Z | libs/spirit/example/qi/calc6/calc6.cpp | ksundberg/boost-svn | 5694e7831f7afc8f6e25d03d0fd375e7be758d0f | [
"BSL-1.0"
] | null | null | null | libs/spirit/example/qi/calc6/calc6.cpp | ksundberg/boost-svn | 5694e7831f7afc8f6e25d03d0fd375e7be758d0f | [
"BSL-1.0"
] | 3 | 2016-07-26T08:07:09.000Z | 2019-06-25T23:20:21.000Z | /*=============================================================================
Copyright (c) 2001-2010 Joel de Guzman
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)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
// Now we'll introduce variables and assignment. This time, we'll also
// be renaming some of the rules -- a strategy for a grander scheme
// to come ;-)
//
// This version also shows off grammar modularization. Here you will
// see how expressions and statements are built as modular grammars.
//
// [ JDG April 9, 2007 ] spirit2
//
///////////////////////////////////////////////////////////////////////////////
#include "calc6.hpp"
template <typename Grammar>
bool compile(Grammar const& calc, std::string const& expr)
{
using ascii::space;
std::string::const_iterator iter = expr.begin();
std::string::const_iterator end = expr.end();
bool r = phrase_parse(iter, end, calc, space);
if (r && iter == end)
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
std::cout << "-------------------------\n";
return true;
}
else
{
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "-------------------------\n";
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main program
///////////////////////////////////////////////////////////////////////////////
struct var_printer
{
var_printer(std::vector<int> const& stack)
: stack(stack)
{
}
template <typename String, typename Data>
void operator()(String const& s, Data const& data)
{
std::cout << " " << s << ": " << stack[data] << std::endl;
}
std::vector<int> const& stack;
};
int
main()
{
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Expression parser...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Type some statements... ";
std::cout << "Then type period ('.') to compile, run and print results\n\n";
typedef std::string::const_iterator iterator_type;
typedef statement<iterator_type> statement;
vmachine mach; // Our virtual machine
std::vector<int> code; // Our VM code
statement calc(code); // Our grammar
std::string str;
std::string program;
while (std::getline(std::cin, str))
{
if (str.empty() || str[0] == '.')
break;
program += str;
}
if (::compile(calc, program))
{
mach.execute(code, calc.nvars);
std::cout << "Results------------------\n\n";
calc.vars.for_each(var_printer(mach.get_stack()));
std::cout << "-------------------------\n\n";
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| 30.480769 | 81 | 0.436593 | oudream |
a1e7fe36b81ac869fa99a279404946eada191401 | 4,095 | cpp | C++ | Brain/sustain.cpp | vikbez/PlayerPianoController | 098e0a9df2be3d029490986eedd1bf2eac0a44ca | [
"MIT"
] | null | null | null | Brain/sustain.cpp | vikbez/PlayerPianoController | 098e0a9df2be3d029490986eedd1bf2eac0a44ca | [
"MIT"
] | null | null | null | Brain/sustain.cpp | vikbez/PlayerPianoController | 098e0a9df2be3d029490986eedd1bf2eac0a44ca | [
"MIT"
] | null | null | null | #include "sustain.h"
#include "sustain.h"
#include "serial.h"
#include "settings.h"
#include "note.h"
SustainPedal sustain;
SustainPedal::SustainPedal()
{
//initialize one row of vectors so program won't crash while comparing
//initialize sustain as off by default
for(int index = 0; index < 4; index++)
{
schedule[index].reserve(6);
schedule[index].resize(1);
}
schedule[OFF].push_back(millis());
}
void SustainPedal::prepareToSchedule(uint8_t velocity)
{
const uint8_t SUSTAIN_MIN_VELOCITY = 64;
if(Setting::handleNotes && Setting::scheduleNotes)
{
if(velocity < SUSTAIN_MIN_VELOCITY)
{
scheduleSustain(false);
} else if(instances == 0) //only schedule if sustain is off
scheduleSustain(true);
} else
{
if(velocity < SUSTAIN_MIN_VELOCITY)
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
else
sendMidiToProMicro(SUSTAIN_NOTE, 127); // ledcWrite(0, 255);
}
}
void SustainPedal::checkSchedule()
{
unsigned long ms = millis();
//less checks for sustain because it's slower and less important
if(schedule[OFF].size() > 1 && schedule[DEACTIVATION].size() > 1 &&
ms >= schedule[OFF].at(1) && schedule[OFF].at(1) >= schedule[DEACTIVATION].at(1))
{
schedule[DEACTIVATION].erase(schedule[DEACTIVATION].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
}
if(schedule[ACTIVATION].size() > 1 && schedule[OFF].size() > 1 &&
ms >= schedule[ACTIVATION].at(1) && schedule[ACTIVATION].at(1) >= schedule[OFF].at(1))
{
schedule[OFF].erase(schedule[OFF].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 127); // ledcWrite(0, 255);
}
if(schedule[ON].size() > 1 && schedule[ACTIVATION].size() > 1 &&
ms >= schedule[ON].at(1) && schedule[ON].at(1) >= schedule[ACTIVATION].at(1))
{
schedule[ACTIVATION].erase(schedule[ACTIVATION].begin()++);
}
if(schedule[DEACTIVATION].size() > 1 && schedule[ON].size() > 1 &&
ms >= schedule[DEACTIVATION].at(1) && schedule[DEACTIVATION].at(1) >= schedule[ON].at(1))
{
schedule[ON].erase(schedule[ON].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 15); // ledcWrite(0, 30);
}
}
void SustainPedal::checkForErrors()
{
unsigned long ms = millis();
if(ms >= timeSinceActivation + Setting::sustainTimeoutMs && timeSinceActivation > 0) resetSchedule();
if(schedule[ON].size() > 1) if(ms >= schedule[ON].at(1) + Setting::sustainTimeoutMs) resetSchedule();
}
void SustainPedal::resetSchedule()
{
for(int index = 0; index < 4; index++)
schedule[index].resize(1);
schedule[OFF].push_back(millis());
timeSinceActivation = 0;
instances = 0;
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
}
void SustainPedal::scheduleSustain(bool state)
{
unsigned long ms = millis();
unsigned long msAndDelay = ms + fullDelay;
using namespace Setting;
if(state)
{
if(msAndDelay - sustainOnMs >= schedule[OFF].back()) //if sustain can be scheduled with current scheduling
{
schedule[ACTIVATION].push_back(msAndDelay - sustainOnMs);
schedule[ON]. push_back(msAndDelay);
timeSinceActivation = ms;
instances++;
} else if(msAndDelay - sustainOffMs - sustainOnMs >= schedule[ON].back()) //if current scheduling can be modified to still schedule the sustain
{
schedule[ON]. push_back(msAndDelay - sustainOnMs - sustainOffMs);
schedule[ON]. erase(----schedule[ON].end());
schedule[OFF]. push_back(msAndDelay - sustainOnMs);
schedule[OFF]. erase(----schedule[OFF].end());
schedule[ACTIVATION].push_back(msAndDelay - sustainOnMs);
schedule[ON]. push_back(msAndDelay);
timeSinceActivation = ms;
instances++;
}
} else if(instances > 0) //if sustain off command and sustain is not already off
{
instances = 0;
if(msAndDelay - sustainOffMs >= schedule[ON].back()) //if sustain can be ideally deactivated
{
schedule[DEACTIVATION].push_back(msAndDelay - sustainOffMs);
schedule[OFF]. push_back(msAndDelay);
} else //deactivate sustain anyways so it's not stuck on
{
schedule[DEACTIVATION].push_back(msAndDelay);
schedule[OFF]. push_back(msAndDelay + sustainOffMs);
}
}
} | 33.024194 | 145 | 0.689133 | vikbez |
a1e90cce1eb6405ebfb14cec7e15e0ab47a0a40c | 4,922 | cpp | C++ | PathFinding/src/Ember/File/CinderStructure.cpp | strah19/PathFinding | 309cf923313feead344acbf3c299f29025d5a66c | [
"MIT"
] | null | null | null | PathFinding/src/Ember/File/CinderStructure.cpp | strah19/PathFinding | 309cf923313feead344acbf3c299f29025d5a66c | [
"MIT"
] | null | null | null | PathFinding/src/Ember/File/CinderStructure.cpp | strah19/PathFinding | 309cf923313feead344acbf3c299f29025d5a66c | [
"MIT"
] | null | null | null | #include "CinderStructure.h"
namespace Ember {
bool CinderStructure::Load(const std::string& file_path) {
core_file = new File(file_path.c_str());
bool inside_section = false;
bool reading_a_key = true;
size_t current_section = -1;
std::string save_key;
core_file->DoEachWord([&](std::string& word, unsigned int counter) {
if (word.back() == ':') {
std::string copy_word = word;
copy_word.pop_back();
sections.push_back(Section(copy_word, counter));
inside_section = true;
current_section++;
}
else if (inside_section) {
if (word.back() == ':')
inside_section = false;
else {
if (reading_a_key) {
save_key = word;
reading_a_key = false;
}
else if (!reading_a_key && word != "=") {
sections[current_section].keys.push_back(KeyToValues(save_key, word));
reading_a_key = true;
}
}
}
return true;
});
return true;
}
CinderStructure::~CinderStructure() {
delete core_file;
}
CinderStructure::CinderReturnCodes CinderStructure::WriteSection(const CinderStructureType& section_name) {
for (size_t i = 0; i < sections.size(); i++) {
if (sections[i].section_name == section_name) {
std::string all = core_file->ReadAll();
unsigned top, bottom;
top = all.find(section_name + ":");
if (i == sections.size() - 1)
bottom = all.find(all.length() - top);
else
bottom = all.find(sections[i + 1].section_name + ":");
all.erase(top, bottom - top);
core_file->EmptyFile();
core_file->Write(all);
sections.erase(sections.begin() + i);
return CinderStructure::CinderReturnCodes::DeletedSection;
}
}
std::string code_input = section_name + ":\n";
core_file->Write(code_input);
sections.push_back(Section(section_name, core_file->WordCount() - 1));
return CinderStructure::CinderReturnCodes::Null;
}
CinderStructure::CinderReturnCodes CinderStructure::WriteKeyValueToSection(const CinderStructureType& section_name, const CinderStructureType& key, const CinderStructureType& value) {
for (size_t i = 0; i < sections.size(); i++) {
if (sections[i].section_name == section_name) {
for (size_t j = 0; j < sections[i].keys.size(); j++) {
if (sections[i].keys[j].key == key) {
std::string all = core_file->ReadAll();
unsigned top_section = all.find(section_name + ":");
unsigned bottom_section;
if (i == sections.size() - 1)
bottom_section = all.find(all.length() - top_section);
else
bottom_section = all.find(sections[i + 1].section_name + ":");
std::string section = all.substr(top_section, bottom_section - top_section);
unsigned find_key = section.find(key);
section.erase(find_key + key.size() + 3, sections[i].keys[j].value.size());
section.insert(find_key + key.size() + 3, value);
all.erase(top_section, bottom_section - top_section);
all.insert(top_section, section);
core_file->EmptyFile();
core_file->Write(all);
sections[i].keys[j].value = value;
return CinderStructure::CinderReturnCodes::Null;
}
}
std::string code_input = section_name + ":\n";
sections[i].keys.push_back(KeyToValues(key, value));
core_file->WriteAfterWord(key + " = " + value + '\n', code_input);
return CinderStructure::CinderReturnCodes::Null;
}
}
return CinderStructure::CinderReturnCodes::Null;
}
CinderStructure::CinderReturnCodes CinderStructure::DeleteKey(const CinderStructureType& section_name, const CinderStructureType& key) {
for (size_t i = 0; i < sections.size(); i++) {
if (sections[i].section_name == section_name) {
for (size_t j = 0; j < sections[i].keys.size(); j++) {
if (sections[i].keys[j].key == key) {
std::string all = core_file->ReadAll();
unsigned top_section = all.find(section_name + ":");
unsigned bottom_section;
if (i == sections.size() - 1)
bottom_section = all.find(all.length() - top_section);
else
bottom_section = all.find(sections[i + 1].section_name + ":");
std::string section = all.substr(top_section, bottom_section - top_section);
unsigned find_key = section.find(key);
section.erase(find_key, key.size() + 3 + sections[i].keys[j].value.size());
all.erase(top_section, bottom_section - top_section);
all.insert(top_section, section);
core_file->EmptyFile();
core_file->Write(all);
}
}
}
}
return CinderStructure::CinderReturnCodes::Null;
}
std::string CinderStructure::GetValue(const CinderStructureType& section_name, const CinderStructureType& key) {
for (size_t i = 0; i < sections.size(); i++) {
if (sections[i].section_name == section_name) {
for (size_t j = 0; j < sections[i].keys.size(); j++) {
if (sections[i].keys[j].key == key) {
return sections[i].keys[j].value;
}
}
}
}
return "";
}
} | 30.955975 | 184 | 0.646485 | strah19 |
a1ec0ab68080b9c9b82ce1e5dabc4fbc18dde4ab | 721 | hpp | C++ | src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/formula/functions/Sumx2py2.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/ss/formula/functions/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <org/apache/poi/ss/formula/functions/XYNumericFunction_Accumulator.hpp>
struct default_init_tag;
class poi::ss::formula::functions::Sumx2py2_1
: public virtual ::java::lang::Object
, public virtual XYNumericFunction_Accumulator
{
public:
typedef ::java::lang::Object super;
double accumulate(double x, double y) override;
// Generated
Sumx2py2_1();
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class Sumx2py2;
};
| 24.862069 | 80 | 0.725381 | pebble2015 |
a1ec56221d0b2b9656ed3614ab88d3b3b68e6598 | 3,724 | cpp | C++ | tests/tests/referral_mandatory_transfer_test.cpp | edinar-dev/edinarcoin | d3f11ab57acd745fd407f87999f2ab72378f5194 | [
"MIT"
] | 1 | 2019-08-05T08:09:37.000Z | 2019-08-05T08:09:37.000Z | tests/tests/referral_mandatory_transfer_test.cpp | reactivespace/Dex | d5716eab035f993dad3e5b4df664f9ebd32ab3a0 | [
"MIT"
] | null | null | null | tests/tests/referral_mandatory_transfer_test.cpp | reactivespace/Dex | d5716eab035f993dad3e5b4df664f9ebd32ab3a0 | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <fc/crypto/digest.hpp>
#include "../common/database_fixture.hpp"
#include "../common/test_utils.hpp"
using namespace graphene::chain;
using namespace graphene::chain::test;
#define MEASURE_TIME(operation, description) \
auto start = fc::time_point::now(); \
operation; \
std::cout << " "<< description <<" completed in " \
<< (fc::time_point::now() - start).count() / 1000000.0 \
<< " seconds " << std::endl;
BOOST_FIXTURE_TEST_SUITE( referral_mandatory_transfer_test, database_fixture )
BOOST_AUTO_TEST_CASE( no_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
generate_block();
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( recent_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
transfer(alice_id, committee_account, asset(1000, asset_id_type()));
generate_block();
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
BOOST_REQUIRE_NO_THROW(db.apply_operation(evalState, ref_op));
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( old_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
transfer(alice_id, committee_account, asset(1000, asset_id_type()));
generate_block();
fc::time_point_sec target = db.head_block_time() + fc::hours(24);
while(db.head_block_time() < target)
{
generate_block();
}
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
MEASURE_TIME(
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception),
"apply operation"
);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( appply_time_test_tx_each_block )
{
ACTOR(alice);
fc::time_point_sec target = db.head_block_time() + fc::hours(24);
while(db.head_block_time() < target)
{
transfer(committee_account, alice_id, asset(1, asset_id_type()));
generate_block();
}
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
MEASURE_TIME(
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception),
"apply operation"
);
}
BOOST_AUTO_TEST_SUITE_END()
| 25.861111 | 86 | 0.686627 | edinar-dev |
a1ec7be46d1d5dec918d69c61a92522de5ab7d54 | 8,633 | cpp | C++ | src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2020-2022 Intel Corporation
*
* 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 "ir_module.hpp"
#include <atomic>
#include <utility>
#include "builder.hpp"
#include "pass/func_dependency.hpp"
#include "visitor.hpp"
#include <unordered_set>
#include <util/any_map.hpp>
namespace sc {
static std::atomic<int> rename_cnt = {0};
// this pass will
// break the link from call_nodes to function nodes with bodies
class func_unlinker_t : public ir_inplace_visitor_t {
public:
using ir_inplace_visitor_t::dispatch_impl;
expr visit_impl(call c) override {
auto ret = ir_inplace_visitor_t::visit_impl(std::move(c)).as<call>();
func_t callee = ret->func_;
// if the callee has a function body, unlink the call_node with the
// function with body. Use the decl_ instead
if (callee->body_.defined()) {
assert(callee->decl_);
callee = callee->decl_;
return builder::remake_call(callee, ret->args_, ret);
} else {
assert(!callee->decl_);
}
// if the call is to a decl_, no changes
return ret;
}
func_t dispatch_impl(func_t f) override {
if (f->decl_) {
if (f->decl_->name_ != f->name_) { f->decl_->name_ = f->name_; }
}
return ir_inplace_visitor_t::dispatch_impl(std::move(f));
}
};
std::shared_ptr<ir_module_t> ir_module_t::from_entry_func(
context_ptr ctx, func_t funct) {
auto ret = from_entry_func(
std::move(ctx), std::vector<func_t> {std::move(funct)});
ret->entry_func_idx_ = 0;
return ret;
}
// resolve function dependency, returns funcs with their dependency
static std::vector<func_t> resolve_func(const std::vector<func_t> &funcs) {
std::vector<func_t> dep;
std::unordered_set<func_t> set;
func_dependency_finder_t finder(dep);
for (auto &f : funcs) {
if (set.find(f) != set.end()) { continue; }
dep.emplace_back(f);
set.insert(f);
size_t old_size = 0;
do {
size_t last_size = old_size;
old_size = set.size();
// run dependency_finder on newly added functions
for (size_t i = last_size; i < dep.size(); i++) {
finder(dep[i], set);
}
assert(set.size() == dep.size());
// if old_size == set.size(), no dependency added, can exit
} while (old_size != set.size());
}
return dep;
}
std::shared_ptr<ir_module_t> ir_module_t::from_entry_func(
context_ptr ctx, const std::vector<func_t> &funcs) {
auto ret = std::make_shared<ir_module_t>(std::move(ctx));
ret->add_resolved_func(resolve_func(funcs));
return ret;
}
ir_module_t *ir_module_t::merge(const ir_module_t &m) {
assert(m.ctx_ == ctx_);
add_resolved_func(m.get_contents());
for (auto &v : m.module_vars_) {
add_global_var(v);
}
return this;
}
ir_module_t *ir_module_t::merge(const std::vector<ir_module_ptr> &list) {
for (auto &m : list) {
merge(*m);
}
return this;
}
func_t ir_module_t::get_func(const std::string &name) const {
auto itr = symbols_.find(name);
if (itr != symbols_.end()) { return contents_.at(itr->second); }
return func_t();
}
ir_module_ptr ir_module_t::copy() const {
return std::make_shared<ir_module_t>(*this);
}
void ir_module_t::add_func(const std::vector<func_t> &funcs) {
add_resolved_func(resolve_func(funcs));
}
var ir_module_t::make_global_var(sc_data_type_t dtype, const std::string &name,
linkage linkage, expr init) {
var ret = builder::make_var(dtype, name).static_as<var>();
auto def = builder::make_var_tensor_def_unattached(
ret, linkage, std::move(init))
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
tensor ir_module_t::make_global_tensor(sc_data_type_t dtype,
const std::string &name, const std::vector<expr> &dims,
linkage linkage) {
tensor ret = builder::make_tensor(name, dims, dtype).static_as<tensor>();
auto def = builder::make_var_tensor_def_unattached(ret, linkage)
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
tensor ir_module_t::make_global_stensor(sc_data_type_t dtype,
const std::string &name, const std::vector<expr> &dims,
const std::vector<expr> &strides, linkage linkage) {
tensor ret = builder::make_stensor(name, dims, strides, dtype)
.static_as<tensor>();
auto def = builder::make_var_tensor_def_unattached(ret, linkage)
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
void ir_module_t::add_global_var(define def) {
auto &name = def->var_.isa<var>() ? def->var_.static_as<var>()->name_
: def->var_.checked_as<tensor>()->name_;
auto itr = var_symbols_.find(name);
if (itr != var_symbols_.end()) {
COMPILE_ASSERT(def->linkage_ != linkage::public_global,
"Global var redefinition: " << name);
std::string new_name;
do {
new_name = name + '_' + std::to_string(++rename_cnt);
itr = var_symbols_.find(new_name);
} while (itr != var_symbols_.end());
name = new_name;
}
var_symbols_.insert(std::make_pair(name, def));
module_vars_.emplace_back(std::move(def));
}
void ir_module_t::add_resolved_func(const std::vector<func_t> &funcs) {
func_unlinker_t replacer;
// all dependencies found, now check if any function name duplications
for (auto &f : funcs) {
// skip function decl_
if (!f->body_.defined()) { continue; }
auto itr = symbols_.find(f->name_);
if (itr != symbols_.end()) {
// if the function is already added to the module, skip
if (contents_.at(itr->second) == f) { continue; }
// try to rename the function if we are allowed to
COMPILE_ASSERT(!f->attr_ || !f->attr_->has_key("entry_func"),
"The function "
<< f->name_
<< " is duplicated and is marked \'entry_func\'.")
std::string name;
do {
name = f->name_ + '_' + std::to_string(++rename_cnt);
itr = symbols_.find(name);
} while (itr != symbols_.end());
f->name_ = name;
assert(f->decl_);
}
symbols_.insert(std::make_pair(f->name_, contents_.size()));
replacer.dispatch_impl(f);
contents_.emplace_back(f);
}
}
void ir_module_t::run_pass(function_pass_t &pass) {
for (auto &f : contents_) {
f = std::const_pointer_cast<func_base>(pass(f));
}
}
func_t ir_module_t::make_init_func() const {
if (!module_vars_.empty()) {
stmts seq = make_stmt<stmts_node_t>(std::vector<stmt>());
for (auto &v : module_vars_) {
assert(v->linkage_ == linkage::private_global
|| v->linkage_ == linkage::public_global);
if (v->init_.defined()) {
seq->seq_.emplace_back(
builder::make_assign_unattached(v->var_, v->init_));
}
}
if (seq->seq_.empty()) return func_t();
auto ret = builder::make_func("__sc_init__", std::vector<expr_c>(),
std::move(seq), datatypes::void_t);
return ret;
}
return func_t();
}
ostream &operator<<(ostream &os, const ir_module_t &m) {
for (auto &f : m.get_module_vars()) {
os << f << '\n';
}
for (auto &f : m.get_contents()) {
os << f << '\n';
}
return os;
}
ostream &operator<<(ostream &os, const const_ir_module_ptr &m) {
return (os << *m);
}
ostream &operator<<(ostream &os, const ir_module_ptr &m) {
return (os << const_ir_module_ptr(m));
}
} // namespace sc
| 34.810484 | 81 | 0.595042 | wuxun-zhang |
a1ee2fc709c984224707c8ed48f797207f9d69e9 | 3,564 | cc | C++ | mindspore/lite/tools/converter/legacy_optimizer/fusion/matmul_biasadd_fusion_pass.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 1 | 2021-12-27T13:42:29.000Z | 2021-12-27T13:42:29.000Z | mindspore/lite/tools/converter/legacy_optimizer/fusion/matmul_biasadd_fusion_pass.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/legacy_optimizer/fusion/matmul_biasadd_fusion_pass.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/converter/legacy_optimizer/fusion/matmul_biasadd_fusion_pass.h"
#include <string>
#include <unordered_map>
#include <vector>
#include <memory>
#include "schema/inner/model_generated.h"
#include "tools/common/meta_graph_utils.h"
namespace {
constexpr int kNumBiasMatchPathLen = 2;
constexpr const char *MulName = "MATMUL";
constexpr const char *BiasName = "BIASADD";
} // namespace
namespace mindspore {
namespace lite {
STATUS MatMulBiasAddFusionPass::Run(MetaGraphT *graph) { return FusionPass::Run(graph); }
STATUS MatMulBiasAddFusionPass::DefinePattern() {
auto mul_op = std::make_shared<PatternOp>();
mul_op->id = MulName;
mul_op->types = {schema::PrimitiveType_MatMulFusion};
auto bias_op = std::make_shared<PatternOp>();
bias_op->id = BiasName;
bias_op->types = {schema::PrimitiveType_BiasAdd};
bias_op->left = mul_op;
std::unique_ptr<FusionPattern> fusion_pattern(new (std::nothrow) FusionPattern("MatMulBiasAddFusion"));
if (fusion_pattern == nullptr) {
MS_LOG(ERROR) << "new fusion_pattern failed";
return RET_ERROR;
}
fusion_pattern->AddPatternOp(mul_op);
fusion_pattern->AddPatternOp(bias_op);
fusion_pattern->Finish();
this->patterns.emplace_back(fusion_pattern.release());
return RET_OK;
}
STATUS MatMulBiasAddFusionPass::DoFusion(MetaGraphT *graph, const std::string &pattern_name,
std::unordered_map<std::string, std::shared_ptr<Path>> &matched_path) {
MS_ASSERT(graph != nullptr);
if (matched_path.size() != kNumBiasMatchPathLen) {
MS_LOG(ERROR) << "MatMul-BiasAdd-Fusion should have two NodeIndex in matchedPair";
return RET_PARAM_INVALID;
}
auto mul_path = matched_path[MulName];
auto bias_path = matched_path[BiasName];
auto mul_index = mul_path->nodeIdx;
auto bias_index = bias_path->nodeIdx;
auto &mul_node = graph->nodes.at(mul_index);
auto &bias_node = graph->nodes.at(bias_index);
auto bias_tensor_index = bias_node->inputIndex.at(1);
if (mul_node->inputIndex.size() != 2) {
MS_LOG(DEBUG) << "cat not fusion.";
return RET_NO_CHANGE;
}
mul_node->inputIndex.push_back(bias_tensor_index);
mul_node->outputIndex = {bias_node->outputIndex};
graph->nodes.erase(bias_index + graph->nodes.begin());
auto it = find(graph->subGraph.at(0)->nodeIndices.begin(), graph->subGraph.at(0)->nodeIndices.end(),
static_cast<uint32_t>(bias_index));
if (it == graph->subGraph.at(0)->nodeIndices.end()) {
MS_LOG(ERROR) << "can not find node in subgraph.";
return RET_ERROR;
}
graph->subGraph.at(0)->nodeIndices.erase(it);
for (size_t i = 0; i < graph->subGraph.at(0)->nodeIndices.size(); i++) {
if (graph->subGraph.at(0)->nodeIndices.at(i) > static_cast<uint32_t>(bias_index)) {
graph->subGraph.at(0)->nodeIndices.at(i)--;
}
}
return RET_OK;
}
MatMulBiasAddFusionPass::~MatMulBiasAddFusionPass() = default;
} // namespace lite
} // namespace mindspore
| 38.322581 | 112 | 0.717733 | PowerOlive |
a1f032b3dc62745f9cdad320aca73b9796f99240 | 1,618 | hh | C++ | functions/concepts.hh | GuylainGreer/manifolds | 96f996f67fc523c726f2edbc9705125c212bedae | [
"MIT"
] | null | null | null | functions/concepts.hh | GuylainGreer/manifolds | 96f996f67fc523c726f2edbc9705125c212bedae | [
"MIT"
] | null | null | null | functions/concepts.hh | GuylainGreer/manifolds | 96f996f67fc523c726f2edbc9705125c212bedae | [
"MIT"
] | null | null | null | #ifndef MANIFOLDS_FUNCTIONS_CONCEPTS_HH
#define MANIFOLDS_FUNCTIONS_CONCEPTS_HH
#include "variables.hh"
#include "composition.hh"
#include "addition.hh"
#include "multiplication.hh"
namespace manifolds {
template <class T> struct is_variable : std::false_type {};
template <int N, bool a, bool c>
struct is_variable<Variable<N, a, c> > : std::true_type {};
template <class, class> struct is_same_v : std::false_type {};
template <template <class...> class T, class... T1s, class... T2s>
struct is_same_v<T<T1s...>, T<T2s...> > : std::true_type {};
template <class F, class = void> struct is_reorderable : std::false_type {};
template <class F>
struct is_reorderable<
F, typename std::enable_if<is_same_v<F, Multiplication<> >::value>::
type> : bool_<F::abelian_arithmetic> {};
template <class F>
struct is_reorderable<F, typename std::enable_if<is_same_v<
F, Addition<> >::value>::type> : std::true_type {};
template <class F> struct is_composition : std::false_type {};
template <class... Fs>
struct is_composition<Composition<Fs...> > : std::true_type {};
template <class...> using void_t = void;
template <class F>
using Variable_c = typename std::enable_if<is_variable<F>::value>::type;
template <class F>
using Composition_c = typename std::enable_if<is_composition<F>::value>::type;
template <class F>
using IsFunctionContainer = void_t<decltype(std::declval<F>().GetFunctions())>;
template <class F>
using IsReorderableFunctionContainer =
void_t<IsFunctionContainer<F>,
typename std::enable_if<is_reorderable<F>::value>::type>;
}
#endif
| 30.528302 | 80 | 0.70581 | GuylainGreer |
a1f1506404fa5a3207e701f62d2d0d4b679d5156 | 1,523 | cpp | C++ | SQLiteFS/SQLiteArchive.cpp | sedawk/SqliteFS | d308c7d8bc178afffec86290b29c3754188aa4a2 | [
"MIT"
] | 1 | 2022-02-10T02:55:16.000Z | 2022-02-10T02:55:16.000Z | SQLiteFS/SQLiteArchive.cpp | sedawk/SqliteFS | d308c7d8bc178afffec86290b29c3754188aa4a2 | [
"MIT"
] | null | null | null | SQLiteFS/SQLiteArchive.cpp | sedawk/SqliteFS | d308c7d8bc178afffec86290b29c3754188aa4a2 | [
"MIT"
] | 1 | 2022-02-10T07:08:58.000Z | 2022-02-10T07:08:58.000Z | #include <stdexcept>
#include "SQLiteArchive.hpp"
#include "Util.hpp"
#include "SQLitePreparedStatementFactory.hpp"
#include "SQLiteRootDirectory.hpp"
#include "SQLiteDirectory.hpp"
#include "SQLiteFile.hpp"
#include "SQLitePath.hpp"
namespace SQLite {
void Archive::open(std::shared_ptr<SQLite::Database> db) {
mDB = db;
}
void Archive::open(const std::string& path) {
try {
mDB = std::make_shared<SQLite::Database>(path);
SQLite::PreparedStatementFactory(mDB).createTable().execute();
}
catch (const std::runtime_error& e) {
throw std::invalid_argument(e.what());
}
}
void Archive::open(const std::wstring& path) {
open(util::string::to_string(path, CP_UTF8));
}
static std::string normalize(const std::string& path) {
return util::string::trim(util::string::replace(path, '\\', '/'), '/');
}
std::shared_ptr<SQLite::Entry> Archive::get(const std::string& path) {
auto pathToFile = normalize(path);
if (pathToFile == "") {
return std::make_shared<SQLite::RootDirectory>(mDB);
}
auto stmt = SQLite::PreparedStatementFactory(mDB).findByName(pathToFile);
if (!stmt.fetch()) {
return std::make_shared<SQLite::Path>(mDB, pathToFile);
}
if (stmt.getColumn("type").getInt() == SQLite::Directory::TYPE) {
return std::make_shared<SQLite::Directory>(mDB, pathToFile);
}
return std::make_shared <SQLite::File>(mDB, pathToFile);
}
std::shared_ptr<SQLite::Entry> Archive::get(const std::wstring& path) {
return get(util::string::to_string(path, CP_UTF8));
}
}
| 27.196429 | 75 | 0.692712 | sedawk |
a1f49cd8093ef780910463cf69a89249c7e7138e | 4,147 | cpp | C++ | src/Settings.cpp | discord-intech/MotorDaemon | 0521d16e9e97ecae4a48f4727430ae73ac593101 | [
"Apache-2.0"
] | null | null | null | src/Settings.cpp | discord-intech/MotorDaemon | 0521d16e9e97ecae4a48f4727430ae73ac593101 | [
"Apache-2.0"
] | null | null | null | src/Settings.cpp | discord-intech/MotorDaemon | 0521d16e9e97ecae4a48f4727430ae73ac593101 | [
"Apache-2.0"
] | 1 | 2017-05-04T20:22:38.000Z | 2017-05-04T20:22:38.000Z | //
// Created by discord on 24/02/17.
//
#include "Settings.hpp"
#define NO_SETTINGS_FAIL "cannot_find_setting"
/**
* Constructor
* @param p path to config file
*/
Settings::Settings(const std::string &p) : path(p)
{
parse();
}
void Settings::parse(void)
{
FILE* file = fopen(path.c_str(), "r");
if(file == NULL)
{
std::cerr << "Can't open settings file " << path << " !" << std::endl;
return;
}
std::string content = "";
int currentChar;
int ignore = 0;
while((currentChar = fgetc(file)) != EOF)
{
if(ignore == 0)
{
if (currentChar == '#')
{
ignore = 1;
continue;
}
else if (currentChar == '/')
{
int nextChar = fgetc(file);
if(nextChar == '*')
{
ignore = 2;
continue;
}
fseek(file, -1, SEEK_CUR);
}
else if (currentChar == '\\') // Ignoring special chars with backslash
{
int nextChar = fgetc(file);
if(nextChar == '/' || nextChar == '#')
{
content += (char)nextChar;
continue;
}
fseek(file, -1, SEEK_CUR);
}
content += (char)currentChar;
}
else
{
if (ignore == 1 && currentChar == '\n')
{
ignore = 0;
}
else if(ignore == 2 && currentChar == '*')
{
int nextChar = fgetc(file);
if(nextChar == '/')
{
ignore = 0;
continue;
}
fseek(file, -1, SEEK_CUR);
}
}
}
fclose(file);
std::string name, value;
int mode = 0;
name.clear();
value.clear();
for(char c : content)
{
if(name.empty())
{
if(c == ' ') continue;
}
if(c == '=' && mode == 0)
{
mode = 1;
continue;
}
else if(c == '\r') continue;
else if(c == '\n')
{
mode = 0;
if(!name.empty()) settings.emplace(name, value);
name.clear();
value.clear();
continue;
}
if(mode)value += c;
else name+=c;
}
if(!name.empty()) settings.emplace(name, value);
}
std::string Settings::get(const std::string &name)
{
if(settings.count(name) == 0)
{
return NO_SETTINGS_FAIL;
}
return settings[name];
}
double Settings::getDouble(const std::string &name)
{
std::string r = get(name);
if(name == NO_SETTINGS_FAIL) throw FailedToParse();
try {
return std::stod(r);
}
catch(const std::invalid_argument& ia)
{
throw FailedToParse();
}
catch(const std::out_of_range& ia)
{
throw FailedToParse();
}
}
int Settings::getInt(const std::string &name)
{
std::string r = get(name);
if(name == NO_SETTINGS_FAIL) throw FailedToParse();
try {
return std::stoi(r);
}
catch(const std::invalid_argument& ia)
{
throw FailedToParse();
}
catch(const std::out_of_range& ia)
{
throw FailedToParse();
}
}
long Settings::getLong(const std::string &name)
{
std::string r = get(name);
if(name == NO_SETTINGS_FAIL) throw FailedToParse();
try {
return std::stol(r);
}
catch(const std::invalid_argument& ia)
{
throw FailedToParse();
}
catch(const std::out_of_range& ia)
{
throw FailedToParse();
}
}
float Settings::getFloat(const std::string &name)
{
std::string r = get(name);
if(name == NO_SETTINGS_FAIL) throw FailedToParse();
try {
return std::stof(r);
}
catch(const std::invalid_argument& ia)
{
throw FailedToParse();
}
catch(const std::out_of_range& ia)
{
throw FailedToParse();
}
} | 19.199074 | 82 | 0.457198 | discord-intech |
a1f7bfb4375a4eaae3698d9ee7a8f14d0b297603 | 447 | cpp | C++ | sources/Panel/src/main.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | null | null | null | sources/Panel/src/main.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | null | null | null | sources/Panel/src/main.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | 1 | 2020-03-08T18:55:21.000Z | 2020-03-08T18:55:21.000Z | // (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by
#include "defines.h"
#include "HAL.h"
#include "Interface.h"
#include "Keyboard.h"
#include "PowerSupply.h"
int main()
{
HAL::Init();
Keyboard::Init();
while (1)
{
Keyboard::Update();
KeyboardEvent event = Keyboard::Buffer::GetNextEvent();
if (!PowerSupply::AttemptToTurnOn(event))
{
Interface::Update(event);
}
}
}
| 16.555556 | 63 | 0.579418 | Sasha7b9Work |
a1fa1d0301f911238570cbf318c39dc22b42ded2 | 5,604 | cpp | C++ | SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp | Therobodavo/Purification-Camp | fe511459c4d938157f3ebb7f9256a02c12be675b | [
"MIT"
] | null | null | null | SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp | Therobodavo/Purification-Camp | fe511459c4d938157f3ebb7f9256a02c12be675b | [
"MIT"
] | null | null | null | SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp | Therobodavo/Purification-Camp | fe511459c4d938157f3ebb7f9256a02c12be675b | [
"MIT"
] | null | null | null | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "SideProject/MyCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMyCharacter() {}
// Cross Module References
SIDEPROJECT_API UClass* Z_Construct_UClass_AMyCharacter_NoRegister();
SIDEPROJECT_API UClass* Z_Construct_UClass_AMyCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_SideProject();
SIDEPROJECT_API UClass* Z_Construct_UClass_AProjectileSphere_NoRegister();
COREUOBJECT_API UClass* Z_Construct_UClass_UClass();
// End Cross Module References
void AMyCharacter::StaticRegisterNativesAMyCharacter()
{
}
UClass* Z_Construct_UClass_AMyCharacter_NoRegister()
{
return AMyCharacter::StaticClass();
}
struct Z_Construct_UClass_AMyCharacter_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_proj_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_proj;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ProjSphereClass_MetaData[];
#endif
static const UE4CodeGen_Private::FClassPropertyParams NewProp_ProjSphereClass;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AMyCharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_SideProject,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "MyCharacter.h" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData[] = {
{ "Category", "MyCharacter" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj = { UE4CodeGen_Private::EPropertyClass::Object, "proj", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000010005, 1, nullptr, STRUCT_OFFSET(AMyCharacter, proj), Z_Construct_UClass_AProjectileSphere_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData[] = {
{ "Category", "MyCharacter" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass = { UE4CodeGen_Private::EPropertyClass::Class, "ProjSphereClass", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0014000000000004, 1, nullptr, STRUCT_OFFSET(AMyCharacter, ProjSphereClass), Z_Construct_UClass_AProjectileSphere_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AMyCharacter_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AMyCharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AMyCharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AMyCharacter_Statics::ClassParams = {
&AMyCharacter::StaticClass,
DependentSingletons, ARRAY_COUNT(DependentSingletons),
0x009000A0u,
nullptr, 0,
Z_Construct_UClass_AMyCharacter_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::PropPointers),
nullptr,
&StaticCppClassTypeInfo,
nullptr, 0,
METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AMyCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AMyCharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AMyCharacter, 2803804649);
static FCompiledInDefer Z_CompiledInDefer_UClass_AMyCharacter(Z_Construct_UClass_AMyCharacter, &AMyCharacter::StaticClass, TEXT("/Script/SideProject"), TEXT("AMyCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AMyCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 52.373832 | 570 | 0.813526 | Therobodavo |
a1faf478182abac5bc9d6ef285c68d1f15532d59 | 17,327 | cpp | C++ | GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp | dmhud/AllSamples | 9bfa3d26a51d7722927f05a48e1dbf5fc399d150 | [
"Unlicense"
] | null | null | null | GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp | dmhud/AllSamples | 9bfa3d26a51d7722927f05a48e1dbf5fc399d150 | [
"Unlicense"
] | null | null | null | GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp | dmhud/AllSamples | 9bfa3d26a51d7722927f05a48e1dbf5fc399d150 | [
"Unlicense"
] | null | null | null | #include "DX11_Triangle.h"
#include <vector>
#include <d3d11.h>
#include <dxgi1_2.h>
#include <d3dcompiler.h>
#include "Common/DX.Utils/DxException.h"
#include "Common/Math.Utils/Math.h"
#include "Common/Win.Utils/ExePath.h"
void DX11_Triangle::DrawTriangle(HWND hWnd, uint32_t windowWidth, uint32_t windowHeight)
{
using namespace dx;
using namespace math;
auto exePath = win::exe_path();
///////////////////////////////
/// Initialize API ///
///////////////////////////////
/**
* Factory
*/
ComPtr<IDXGIFactory> factory;
ThrowIfFailed(CreateDXGIFactory(IID_PPV_ARGS(factory.GetAddressOf())));
/**
* Adapter
*/
ComPtr<IDXGIAdapter> adapter;
ThrowIfFailed(factory->EnumAdapters(0, adapter.GetAddressOf()));
/**
* Adapter Output
*/
ComPtr<IDXGIOutput> adapterOutput;
ThrowIfFailed(adapter->EnumOutputs(0, adapterOutput.GetAddressOf()));
// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display
// format for the adapter output (monitor).
unsigned int numModes;
ThrowIfFailed(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED,
&numModes, nullptr));
// Create a list to hold all the possible display modes for this monitor/video
// card combination.
std::vector<DXGI_MODE_DESC> displayModeList;
displayModeList.resize(numModes);
ThrowIfFailed(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED,
&numModes, displayModeList.data()));
// Now go through all the display modes and find the one that matches the screen
// width and height. When a match is found store the numerator and denominator
// of the refresh rate for that monitor.
unsigned numerator = 0;
unsigned denominator = 1;
for (size_t i = 0; i < numModes; i++)
{
if (displayModeList[i].Width = windowWidth && displayModeList[i].Height == windowHeight)
{
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;
break;
}
}
/**
* Device
*/
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> deviceContext;
D3D_FEATURE_LEVEL featureLevelInputs[7] = {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1 };
D3D_FEATURE_LEVEL featureLevelOutputs = D3D_FEATURE_LEVEL_11_1;
ThrowIfFailed(D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr,
D3D11_CREATE_DEVICE_SINGLETHREADED |
D3D11_CREATE_DEVICE_DEBUG,
featureLevelInputs, 7u, D3D11_SDK_VERSION,
device.GetAddressOf(), &featureLevelOutputs, deviceContext.GetAddressOf()));
// Optionally enable the Debug Controller to validate your commands on runtime.
#if defined(_DEBUG)
ComPtr<ID3D11Debug> debugController;
ThrowIfFailed(device.As(&debugController));
#endif
///////////////////////////////
/// Frame Backing ///
///////////////////////////////
/**
* Swapchain
*/
bool isEnabledVSync = false;
bool isFullScreenWindow = false;
DXGI_SWAP_CHAIN_DESC swapchainDesc;
ZeroMemory(&swapchainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
swapchainDesc.BufferCount = 1;
swapchainDesc.BufferDesc.Width = windowWidth;
swapchainDesc.BufferDesc.Height = windowHeight;
swapchainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// Set the refresh rate of the back buffer.
if (isEnabledVSync)
{
swapchainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapchainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else
{
swapchainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapchainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
// Set the usage of the back buffer.
swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// Turn multi-sampling off.
swapchainDesc.SampleDesc.Count = 1;
swapchainDesc.SampleDesc.Quality = 0;
// Set the scan line ordering and scaling to unspecified.
swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// Discard the back buffer contents after presenting.
swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// Don't set the advanced flags.
swapchainDesc.Flags = 0;
swapchainDesc.OutputWindow = hWnd;
swapchainDesc.Windowed = !isFullScreenWindow;
ComPtr<IDXGISwapChain> swapchain;
ThrowIfFailed(factory->CreateSwapChain(device.Get(), &swapchainDesc, swapchain.GetAddressOf()));
/**
* Render Targets
*/
// Get the back buffer texture.
ComPtr<ID3D11Texture2D> texBackBuffer;
ThrowIfFailed(swapchain->GetBuffer(0, IID_PPV_ARGS(texBackBuffer.GetAddressOf())));
// Create the render target view with the back buffer pointer.
ComPtr<ID3D11RenderTargetView> rtv;
ThrowIfFailed(device->CreateRenderTargetView(texBackBuffer.Get(), nullptr, rtv.GetAddressOf()));
// Create the texture for the depth buffer.
D3D11_TEXTURE2D_DESC depthBufferDesc;
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
depthBufferDesc.Width = windowWidth;
depthBufferDesc.Height = windowHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
ComPtr<ID3D11Texture2D> texDepthStencilBuffer;
ThrowIfFailed(device->CreateTexture2D(&depthBufferDesc, nullptr, texDepthStencilBuffer.GetAddressOf()));
// Create the depth stencil view.
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
ComPtr<ID3D11DepthStencilView> dsv;
ThrowIfFailed(device->CreateDepthStencilView(texDepthStencilBuffer.Get(), &depthStencilViewDesc, dsv.GetAddressOf()));
///////////////////////////////
/// Resources ///
///////////////////////////////
/**
* Vertex Buffer
*/
// Declare Data
struct Vertex
{
float position[3];
float color[3];
};
Vertex vertexBufferData[3] = { {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}},
{{-1.0f, -1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}},
{{ 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}} };
// Set up the description of the static vertex buffer.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertexBufferData;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now create the vertex buffer.
ComPtr<ID3D11Buffer> vertexBuffer;
ThrowIfFailed(device->CreateBuffer(&vertexBufferDesc, &vertexData, vertexBuffer.GetAddressOf()));
/**
* Index Buffer
*/
// Declare Data
uint32_t indexBufferData[3] = { 0, 1, 2 };
// Set up the description of the static index buffer.
D3D11_BUFFER_DESC indexBufferDesc;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned) * 3;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indexBufferData;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
ComPtr<ID3D11Buffer> indexBuffer;
ThrowIfFailed(device->CreateBuffer(&indexBufferDesc, &indexData, indexBuffer.GetAddressOf()));
/**
* Constant Buffer
*/
struct
{
float4x4 projectionMatrix = float4x4::Identity();
float4x4 modelMatrix = float4x4::Identity();
float4x4 viewMatrix = float4x4::Identity();
} cbVS;
// Setup the description of the dynamic matrix constant buffer that is in the
// vertex shader.
D3D11_BUFFER_DESC constantBufferDesc;
constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
constantBufferDesc.ByteWidth = sizeof(cbVS);
constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
constantBufferDesc.MiscFlags = 0;
constantBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader
// constant buffer from within this class.
ComPtr<ID3D11Buffer> constantBuffer;
ThrowIfFailed(device->CreateBuffer(&constantBufferDesc, nullptr, constantBuffer.GetAddressOf()));
/**
* Shaders options
*/
#if defined(_DEBUG)
// Enable better shader debugging with the graphics debugging tools.
UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
UINT compileFlags = 0;
#endif
ComPtr<ID3DBlob> errors;
/**
* Vertex Shader
*/
ComPtr<ID3DBlob> vertexShaderBlob = nullptr;
std::wstring pathVS = exePath / "shaders" / "triangle.vs.hlsl";
ThrowIfFailed(D3DCompileFromFile(pathVS.c_str(), nullptr, nullptr, "main",
"vs_5_0", compileFlags, 0, vertexShaderBlob.GetAddressOf(),
errors.ReleaseAndGetAddressOf()), errors);
// Create the vertex shader from the buffer.
ComPtr<ID3D11VertexShader> vertexShader;
ThrowIfFailed(device->CreateVertexShader(
vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(),
nullptr, vertexShader.GetAddressOf()));
/**
* Pixel Shader
*/
ComPtr<ID3DBlob> pixelShaderBlob;
std::wstring pathPS = exePath / "shaders" / "triangle.ps.hlsl";
ThrowIfFailed(D3DCompileFromFile(pathPS.c_str(), nullptr, nullptr, "main",
"ps_5_0", compileFlags, 0, pixelShaderBlob.GetAddressOf(),
errors.ReleaseAndGetAddressOf()), errors);
// Create the pixel shader from the buffer.
ComPtr<ID3D11PixelShader> pixelShader;
ThrowIfFailed(device->CreatePixelShader(
pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(),
nullptr, pixelShader.GetAddressOf()));
///////////////////////////////
/// Rendering ///
///////////////////////////////
/**
* Pipeline State
*/
// Input Assembly
D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "COLOR";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
unsigned numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
ComPtr<ID3D11InputLayout> inputLayout;
ThrowIfFailed(device->CreateInputLayout(polygonLayout, numElements,
vertexShaderBlob->GetBufferPointer(),
vertexShaderBlob->GetBufferSize(),
inputLayout.GetAddressOf()));
// Depth/Stencil
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing.
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing.
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the depth stencil state.
ComPtr<ID3D11DepthStencilState> depthStencilState;
ThrowIfFailed(device->CreateDepthStencilState(&depthStencilDesc, depthStencilState.GetAddressOf()));
// Set the depth stencil state.
deviceContext->OMSetDepthStencilState(depthStencilState.Get(), 1);
// Rasterization
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_NONE;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// Create the rasterizer state from the description we just filled out.
ComPtr<ID3D11RasterizerState> rasterState;
ThrowIfFailed(device->CreateRasterizerState(&rasterDesc, rasterState.GetAddressOf()));
// Now set the rasterizer state.
deviceContext->RSSetState(rasterState.Get());
/**
* Viewport
*/
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = windowWidth;
viewport.Height = windowHeight;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
/**
* Draw Calls
*/
// Set the position of the constant buffer in the vertex shader.
unsigned int bufferNumber = 0;
// Lock the constant buffer so it can be written to.
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(deviceContext->Map(constantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD,
0, &mappedResource));
// Get a pointer to the data in the constant buffer.
memcpy(mappedResource.pData, &cbVS, sizeof(cbVS));
// Unlock the constant buffer.
deviceContext->Unmap(constantBuffer.Get(), 0);
// Finally set the constant buffer in the vertex shader with the updated
// values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, constantBuffer.GetAddressOf());
// Bind the render target view and depth stencil buffer to the output render
// pipeline.
deviceContext->OMSetRenderTargets(1, rtv.GetAddressOf(), dsv.Get());
deviceContext->RSSetViewports(1, &viewport);
// Clear textures
float color[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
deviceContext->ClearRenderTargetView(rtv.Get(), color);
// Clear the depth buffer.
deviceContext->ClearDepthStencilView(dsv.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
// Set the vertex input layout.
deviceContext->IASetInputLayout(inputLayout.Get());
// Set the vertex and pixel shaders that will be used to render this
// triangle.
deviceContext->VSSetShader(vertexShader.Get(), nullptr, 0);
deviceContext->PSSetShader(pixelShader.Get(), nullptr, 0);
// Set the vertex buffer to active in the input assembler so it can be
// rendered.
unsigned stride = sizeof(Vertex);
unsigned offset = 0;
deviceContext->IASetVertexBuffers(0, 1, vertexBuffer.GetAddressOf(), &stride, &offset);
// Set the index buffer to active in the input assembler so it can be
// rendered.
deviceContext->IASetIndexBuffer(indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex
// buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Render the triangle.
deviceContext->DrawIndexed(3, 0, 0);
if (isEnabledVSync)
{
swapchain->Present(1, 0);
}
else
{
swapchain->Present(0, 0);
}
return;
}
| 36.097917 | 122 | 0.702141 | dmhud |
a1fb06dcff245c9be8201765eb59c7b0851cbfbc | 6,898 | cpp | C++ | src/xlOil-COM/AppObjects.cpp | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | src/xlOil-COM/AppObjects.cpp | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | src/xlOil-COM/AppObjects.cpp | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | #include <xloil/AppObjects.h>
#include <xlOil-COM/Connect.h>
#include <xlOil-COM/ComVariant.h>
#include <xlOil/ExcelTypeLib.h>
#include <xlOil/ExcelRange.h>
#include <xloil/Log.h>
#include <xloil/Throw.h>
#include <xloil/State.h>
#include <functional>
#include <comdef.h>
using std::shared_ptr;
using std::make_shared;
using std::vector;
namespace xloil
{
namespace
{
template <class T>
struct CollectionToVector
{
template <class V>
vector<T> operator()(const V& collection) const
{
try
{
vector<T> result;
const auto N = collection->Count;
for (auto i = 1; i <= N; ++i)
result.emplace_back(collection->GetItem(i));
return std::move(result);
}
XLO_RETHROW_COM_ERROR;
}
};
_variant_t stringToVariant(const std::wstring_view& str)
{
auto variant = COM::stringToVariant(str);
return _variant_t(variant, false);
}
}
Excel::_Application& excelApp() noexcept
{
return COM::excelApp();
}
IAppObject::~IAppObject()
{
if (_ptr)
_ptr->Release();
}
void IAppObject::init(IDispatch* ptr)
{
_ptr = ptr;
if (ptr)
ptr->AddRef();
}
void IAppObject::assign(const IAppObject& that)
{
if (_ptr) _ptr->Release();
_ptr = that._ptr;
_ptr->AddRef();
}
ExcelWindow::ExcelWindow(const std::wstring_view& caption)
{
try
{
if (caption.empty())
init(excelApp().ActiveWindow);
else
init(excelApp().Windows->GetItem(stringToVariant(caption)));
}
XLO_RETHROW_COM_ERROR;
}
size_t ExcelWindow::hwnd() const
{
return (size_t)ptr()->Hwnd;
}
std::wstring ExcelWindow::name() const
{
return ptr()->Caption.bstrVal;
}
ExcelWorkbook ExcelWindow::workbook() const
{
try
{
return ExcelWorkbook(Excel::_WorkbookPtr(ptr()->Parent));
}
XLO_RETHROW_COM_ERROR;
}
ExcelWorkbook::ExcelWorkbook(const std::wstring_view& name)
{
try
{
if (name.empty())
init(excelApp().ActiveWorkbook);
else
init(excelApp().Workbooks->GetItem(stringToVariant(name)));
}
XLO_RETHROW_COM_ERROR;
}
std::wstring ExcelWorkbook::name() const
{
return ptr()->Name.GetBSTR();
}
std::wstring ExcelWorkbook::path() const
{
return ptr()->Path.GetBSTR();
}
std::vector<ExcelWindow> ExcelWorkbook::windows() const
{
return CollectionToVector<ExcelWindow>()(ptr()->Windows);
}
void ExcelWorkbook::activate() const
{
ptr()->Activate();
}
vector<ExcelWorksheet> ExcelWorkbook::worksheets() const
{
try
{
vector<ExcelWorksheet> result;
const auto N = ptr()->Worksheets->Count;
for (auto i = 1; i <= N; ++i)
result.push_back((Excel::_Worksheet*)(IDispatch*)ptr()->Worksheets->GetItem(i));
return std::move(result);
}
XLO_RETHROW_COM_ERROR;
}
ExcelWorksheet ExcelWorkbook::worksheet(const std::wstring_view& name) const
{
try
{
return (Excel::_Worksheet*)(IDispatch*)(ptr()->Worksheets->GetItem(stringToVariant(name)));
}
XLO_RETHROW_COM_ERROR;
}
std::wstring ExcelWorksheet::name() const
{
return ptr()->Name.GetBSTR();
}
ExcelWorkbook ExcelWorksheet::parent() const
{
return ExcelWorkbook((Excel::_Workbook*)(IDispatch*)ptr()->Parent);
}
ExcelRange ExcelWorksheet::range(
int fromRow, int fromCol,
int toRow, int toCol) const
{
try
{
if (toRow == Range::TO_END)
toRow = ptr()->Rows->GetCount();
if (toCol == Range::TO_END)
toCol = ptr()->Columns->GetCount();
auto r = ptr()->GetRange(
ptr()->Cells->Item[fromRow + 1][fromCol + 1],
ptr()->Cells->Item[toRow + 1][toCol + 1]);
return ExcelRange(r);
}
XLO_RETHROW_COM_ERROR;
}
ExcelRange ExcelWorksheet::range(const std::wstring_view& address) const
{
auto fullAddress = std::wstring(ptr()->Name);
fullAddress += '!';
fullAddress += address;
return ExcelRange(fullAddress.c_str());
}
ExcelObj ExcelWorksheet::value(Range::row_t i, Range::col_t j) const
{
return COM::variantToExcelObj(ptr()->Cells->Item[i][j]);
}
void ExcelWorksheet::activate()
{
try
{
ptr()->Activate();
}
XLO_RETHROW_COM_ERROR;
}
void ExcelWorksheet::calculate()
{
try
{
ptr()->Calculate();
}
XLO_RETHROW_COM_ERROR;
}
namespace App
{
namespace
{
template <typename F, typename T, std::size_t N, std::size_t... Idx>
decltype(auto) appRun_impl(F func, T(&args)[N], std::index_sequence<Idx...>) {
return excelApp().Run(func, args[Idx]...);
}
template <typename T, std::size_t N>
decltype(auto) appRun(const wchar_t* func, T(&args)[N]) {
return appRun_impl(func, args, std::make_index_sequence<N>{});
}
}
ExcelObj Run(const std::wstring& func, const size_t nArgs, const ExcelObj* args[])
{
if (nArgs > 30)
XLO_THROW("Application::Run maximum number of args is 30");
static _variant_t vArgs[30] = {
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
vtMissing, vtMissing, vtMissing, vtMissing, vtMissing
};
// The construction of 'cleanup' is all noexcept
auto finally = [begin = vArgs, end = vArgs + nArgs](void*)
{
for (auto i = begin; i != end; ++i)
*i = vtMissing;
};
std::unique_ptr<void, decltype(finally)> cleanup((void*)1, finally);
for (size_t i = 0; i < nArgs; ++i)
COM::excelObjToVariant(&vArgs[i], *args[i], true);
try
{
auto result = appRun(func.c_str(), vArgs);
return COM::variantToExcelObj(result);
}
XLO_RETHROW_COM_ERROR;
}
ExcelWorkbook Workbooks::active()
{
return ExcelWorkbook();
}
std::vector<ExcelWorkbook> Workbooks::list()
{
return CollectionToVector<ExcelWorkbook>()(excelApp().Workbooks);
}
size_t Workbooks::count()
{
return excelApp().Workbooks->Count;
}
ExcelWindow Windows::active()
{
return ExcelWindow();
}
std::vector<ExcelWindow> Windows::list()
{
return CollectionToVector<ExcelWindow>()(excelApp().Windows);
}
size_t Windows::count()
{
return excelApp().Windows->Count;
}
ExcelWorksheet Worksheets::active()
{
try
{
Excel::_Worksheet* sheet = nullptr;
excelApp().ActiveSheet->QueryInterface(&sheet);
return ExcelWorksheet(sheet);
}
XLO_RETHROW_COM_ERROR;
}
}
}
| 23.304054 | 97 | 0.607857 | cunnane |
a1fc0d174cf444e0ab58d32893339a3af96e1a68 | 1,620 | cpp | C++ | Suffix-Array(Doubling).cpp | cirno99/Algorithms | 6425b143f406693caf8f882bdfe5497c81df255a | [
"Unlicense"
] | 1,210 | 2016-08-07T13:32:12.000Z | 2022-03-21T01:01:57.000Z | Suffix-Array(Doubling).cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 7 | 2016-09-11T11:41:03.000Z | 2017-10-29T02:12:57.000Z | Suffix-Array(Doubling).cpp | NeilQingqing/Algorithms-2 | c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa | [
"Unlicense"
] | 514 | 2016-10-17T03:52:16.000Z | 2022-03-19T16:23:33.000Z | #include <cstdio>
#include <cstring>
#define STRING_LENGTH 100000
using namespace std;
struct sortinfo
{
int x, y, ord;
};
int l;
char s[STRING_LENGTH];
int rank[STRING_LENGTH * 2], sa[STRING_LENGTH];
void radix_sort(sortinfo *d)
{
static sortinfo _d[STRING_LENGTH], res[STRING_LENGTH];
static int c[STRING_LENGTH];
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[d[i].y]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
_d[--c[d[i].y]] = d[i];
}
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[_d[i].x]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
res[--c[_d[i].x]] = _d[i];
}
for (int i = 0; i < l; i++)
{
d[i] = res[i];
}
}
void init_rank()
{
static int c[256];
static sortinfo d[STRING_LENGTH];
int x = 1;
for (int i = 0; i < l; i++)
{
c[(int)s[i]] = 1;
}
for (int i = 0; i < 256; i++)
{
if (c[i] == 1)
{
c[i] = x++;
}
}
for (int i = 0; i < l; i++)
{
rank[i] = c[(int)s[i]];
}
for (int k = 1; k < l; k <<= 1)
{
for (int i = 0; i < l; i++)
{
d[i].x = rank[i];
d[i].y = rank[i + k];
d[i].ord = i;
}
radix_sort(d);
x = 1;
rank[d[0].ord] = 1;
for (int i = 1; i < l; i++)
{
rank[d[i].ord] = (d[i].x == d[i - 1].x && d[i].y == d[i - 1].y ? x : ++x);
}
if (x == l)
{
break;
}
}
}
void rank_to_sa()
{
for (int i = 0; i < l; i++)
{
sa[rank[i] - 1] = i + 1;
}
}
int main()
{
scanf("%d%s", &l, s);
init_rank();
rank_to_sa();
for (int i = 0; i < l; i++)
{
printf("%d\n", sa[i]);
}
return 0;
}
| 14.210526 | 77 | 0.448148 | cirno99 |
a1fe0d7c1cf06943b39286420805b97bd9fdb09b | 4,912 | cpp | C++ | src/adtfUser/common/katanaWorld/src/RoadJunction.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/common/katanaWorld/src/RoadJunction.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | src/adtfUser/common/katanaWorld/src/RoadJunction.cpp | KAtana-Karlsruhe/AADC_2015_KAtana | c6e55be189b8b2d46c905926b6533df2aba5979e | [
"BSD-4-Clause"
] | null | null | null | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Christoph Rist <rist@fzi.de>
* \date 2014-12-07
*
*/
//----------------------------------------------------------------------
#include "RoadJunction.h"
namespace katana
{
RoadPatch::TrajectoryPtr RoadJunction::getDrivingStrip(RoadBase::DrivingStripId drivingStrip) const
{
DiversionId diversion = 0;
if(m_direction == Action::LEFT) {
diversion = 0;
} else if(m_direction == Action::RIGHT) {
diversion = 2;
} else if(m_direction == Action::STRAIGHT) {
diversion = 1;
} else {
assert(false && "Unkown direction passed.");
}
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC Maneuver; Diversion of junction with id " << this->getId() << " " << this->getAnchorPose() << " is " << (int32_t) diversion << std::endl;
#endif
return katana::RoadBase::getDrivingStrip(drivingStrip, diversion);
}
void RoadJunction::setRightOfWay(const RightOfWayDirection& right_of_way)
{
if (right_of_way.first == right_of_way.second && right_of_way.first != RIGHT_OF_WAY::PRIORITY_FROM_RIGHT) //< error
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::UNDEFINED, RIGHT_OF_WAY::UNDEFINED);
else
m_right_of_way = right_of_way;
if (m_right_of_way.first == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT || m_right_of_way.first == RIGHT_OF_WAY::OWN)
return;
if (m_right_of_way.second == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.second == RIGHT_OF_WAY::OWN)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.second == RIGHT_OF_WAY::RIGHT)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.first == RIGHT_OF_WAY::LEFT)
std::swap(m_right_of_way.first, m_right_of_way.second);
}
void RoadJunction::setRightOfWay(TrafficSign ts)
{
m_is_stop = false;
switch(ts)
{
case TrafficSign::JUNCTION_STOP_GIVE_WAY:
m_is_stop = true;
case TrafficSign::JUNCTION_GIVE_WAY:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::RIGHT, RIGHT_OF_WAY::LEFT);
break;
case TrafficSign::JUNCTION_PRIORITY:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::OWN, RIGHT_OF_WAY::STRAIGHT);
break;
case TrafficSign::JUNCTION_PRIORITY_FROM_RIGHT:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::PRIORITY_FROM_RIGHT, RIGHT_OF_WAY::UNDEFINED);
break;
default:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::UNDEFINED, RIGHT_OF_WAY::UNDEFINED);
m_is_stop = true;
break;
}
}
std::vector<DIVERSION> RoadJunction::yieldRightOfWayTo(DIVERSION where_to_go) const
{
std::vector<DIVERSION> yield_to;
if (where_to_go == DIVERSION::UNDEFINED) //< error
{
yield_to.push_back(DIVERSION::RIGHT);
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
return yield_to;
}
if (m_right_of_way.first == RIGHT_OF_WAY::OWN)
{
if (m_right_of_way.second == RIGHT_OF_WAY::STRAIGHT && where_to_go == DIVERSION::LEFT)
{
yield_to.push_back(DIVERSION::STRAIGHT);
}
else if (m_right_of_way.second == RIGHT_OF_WAY::RIGHT && where_to_go == DIVERSION::STRAIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
}
}
else if (m_right_of_way.first == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT)
{
if (where_to_go != DIVERSION::RIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
if (where_to_go == DIVERSION::LEFT)
{
yield_to.push_back(DIVERSION::STRAIGHT);
}
}
}
else if (m_right_of_way.first == RIGHT_OF_WAY::UNDEFINED || m_right_of_way.second == RIGHT_OF_WAY::UNDEFINED)
{
yield_to.push_back(DIVERSION::RIGHT);
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
}
else
{
if (m_right_of_way.first == RIGHT_OF_WAY::RIGHT)
{
// right - left
if (m_right_of_way.second == RIGHT_OF_WAY::LEFT)
{
yield_to.push_back(DIVERSION::LEFT);
if (where_to_go != DIVERSION::RIGHT)
yield_to.push_back(DIVERSION::RIGHT);
if (where_to_go == DIVERSION::LEFT)
yield_to.push_back(DIVERSION::STRAIGHT);
}
// right - straight
else
{
yield_to.push_back(DIVERSION::STRAIGHT);
if (where_to_go != DIVERSION::RIGHT)
yield_to.push_back(DIVERSION::RIGHT);
}
}
// straight - left
else
{
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
if (where_to_go != DIVERSION::RIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
}
}
}
return yield_to;
}
} //ns
| 30.893082 | 158 | 0.652484 | KAtana-Karlsruhe |
a1ff1251e626289c4dc32899b0f29f8c4cfacc9d | 3,105 | cpp | C++ | jit/bf.cpp | Mark1626/performance-case-studies | 06890e80a945f66bade639a9dedd6bf6eeb4e2f1 | [
"CC0-1.0"
] | null | null | null | jit/bf.cpp | Mark1626/performance-case-studies | 06890e80a945f66bade639a9dedd6bf6eeb4e2f1 | [
"CC0-1.0"
] | null | null | null | jit/bf.cpp | Mark1626/performance-case-studies | 06890e80a945f66bade639a9dedd6bf6eeb4e2f1 | [
"CC0-1.0"
] | null | null | null | #include "parser.h"
#include "util.h"
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
constexpr int MEMORY_SIZE = 30000;
void interpretor(const Program &p, bool verbose) {
std::vector<uint8_t> memory(MEMORY_SIZE, 0);
size_t pc = 0;
size_t dataptr = 0;
while (pc < p.instructions.size()) {
char instruction = p.instructions[pc];
switch (instruction) {
case '>':
dataptr++;
break;
case '<':
dataptr--;
break;
case '+':
memory[dataptr]++;
break;
case '-':
memory[dataptr]--;
break;
case '.':
std::cout.put(memory[dataptr]);
break;
case ',':
memory[dataptr] = std::cin.get();
break;
case '[':
if (memory[dataptr] == 0) {
int bracket_nesting = 1;
size_t saved_pc = pc;
while (bracket_nesting && ++pc < p.instructions.size()) {
if (p.instructions[pc] == ']') {
bracket_nesting--;
} else if (p.instructions[pc] == ']') {
bracket_nesting++;
}
}
if (!bracket_nesting) {
break;
} else {
DIE << "unmatched [ " << saved_pc;
}
}
break;
case ']':
if (memory[dataptr] != 0) {
int bracket_nesting = 1;
size_t saved_pc = pc;
while (bracket_nesting && pc > 0) {
pc--;
if (p.instructions[pc] == '[') {
bracket_nesting--;
} else if (p.instructions[pc] == ']') {
bracket_nesting++;
}
}
if (!bracket_nesting) {
break;
} else {
DIE << "unmatched ] " << saved_pc;
}
}
break;
default:
DIE << "unknown character at " << pc;
break;
}
pc++;
}
if (verbose) {
std::cout << "\n";
std::cout << " * pc = " << pc << "\n";
std::cout << " * dataptr = " << dataptr << "\n";
std::cout << " * Memory Nonzero locations "
<< "\n";
for (size_t i = 0, pcount = 0; i < memory.size(); ++i) {
if (memory[i]) {
std::cout << std::right << "[" << std::setw(3) << i
<< " ] = " << std::setw(3) << std::left
<< static_cast<int32_t>(memory[i]) << " ";
pcount++;
if (pcount > 0 && pcount % 4 == 0) {
std::cout << "\n";
}
std::cout << "\n";
}
}
}
}
int main(int argc, char **argv) {
bool verbose = false;
std::string bf_line_path;
parse_command_line(argc, argv, &bf_line_path, &verbose);
Timer t1;
std::ifstream file(bf_line_path);
if (!file) {
DIE << "unable to open file " << bf_line_path;
}
Program program = parse_from_stream(file);
std::cout << "Parsing took " << t1.elapsed() << "\n";
if (verbose) {
std::cout << "Program size " << program.instructions.size() << "\n";
std::cout << "Instructions " << program.instructions << "\n";
}
Timer t2;
interpretor(program, verbose);
std::cout << "Done (elapsed) " << t2.elapsed() << "\n";
return EXIT_SUCCESS;
}
| 23.171642 | 72 | 0.485668 | Mark1626 |
b80026d2b70cfdb47bd1cb5e7d134da481591096 | 2,257 | cpp | C++ | src/tmsocket/cpp/server_communicator.cpp | Timothy-LiuXuefeng/TMChat | cd69441524f1b86914477f3061e36ffbb8d17478 | [
"MIT"
] | 1 | 2022-01-30T01:09:15.000Z | 2022-01-30T01:09:15.000Z | src/tmsocket/cpp/server_communicator.cpp | Timothy-LiuXuefeng/TMChat | cd69441524f1b86914477f3061e36ffbb8d17478 | [
"MIT"
] | null | null | null | src/tmsocket/cpp/server_communicator.cpp | Timothy-LiuXuefeng/TMChat | cd69441524f1b86914477f3061e36ffbb8d17478 | [
"MIT"
] | null | null | null | #include "../include/server_communicator.hpp"
#include <prep/include/prep.h>
#include <cstddef>
#include <string>
#include <utility>
#include <algorithm>
TMSOCKET_NAMESPACE_BEGIN
#include "details/protocol.ipp"
server_communicator::
server_communicator()
{
this->m_stm.on_reveive
(
[this] (tmsocket_t fd, const ::std::string& str)
{
this->m_buffers[fd].append(str);
::std::string msg;
while (protocol_ns::protocol::try_decode_message(this->m_buffers[fd], msg))
{
this->m_on_receive.invoke(fd, msg);
}
}
);
}
PREP_NODISCARD bool
server_communicator::
is_connected() const
{
return this->m_stm.is_connected();
}
PREP_NODISCARD bool
server_communicator::
is_finished() const
{
return this->m_stm.is_finished();
}
void
server_communicator::
add_log(::std::function<void(const ::std::string&)> log_func)
{
this->m_stm.add_log(::std::move(log_func));
}
void
server_communicator::
on_reveive(::std::function<void(tmsocket_t, const ::std::string&)> func)
{
m_on_receive.subscript(::std::move(func));
}
void
server_communicator::
listen(const ::std::string& host, const ::std::string& port)
{
this->m_stm.listen(host, port);
}
void
server_communicator::
listen(const ::std::string& port)
{
this->m_stm.listen(port);
}
void
server_communicator::
on_listen(::std::function<void(void)> listen_func)
{
this->m_stm.on_listen(::std::move(listen_func));
}
void
server_communicator::
on_connect(::std::function<void(tmsocket_t)> connect_func)
{
this->m_stm.on_connect(::std::move(connect_func));
}
void
server_communicator::
on_disconnect(::std::function<void(tmsocket_t)> disconnect_func)
{
this->m_stm.on_disconnect(::std::move(disconnect_func));
}
void
server_communicator::
send_to_one_client(tmsocket_t client_fd, const ::std::string& msg)
{
this->m_stm.send_to_one_client(client_fd, protocol_ns::protocol::encode_message(msg));
}
void
server_communicator::
send_to_all_clients(const ::std::string& msg)
{
this->m_stm.send_to_all_clients(protocol_ns::protocol::encode_message(msg));
}
void
server_communicator::
end_communication()
{
this->m_stm.end_communication();
}
TMSOCKET_NAMESPACE_END
| 19.626087 | 90 | 0.701817 | Timothy-LiuXuefeng |
b8017d93c4850e975c5fc579e0dd964bfd1b45ab | 1,150 | cpp | C++ | Source/Engine/Core/Resources/ResourceFactory.cpp | everard/SELENE-Device | 775bb5cf66ba9fdbc55eac7b216e035c36d82954 | [
"MIT"
] | null | null | null | Source/Engine/Core/Resources/ResourceFactory.cpp | everard/SELENE-Device | 775bb5cf66ba9fdbc55eac7b216e035c36d82954 | [
"MIT"
] | null | null | null | Source/Engine/Core/Resources/ResourceFactory.cpp | everard/SELENE-Device | 775bb5cf66ba9fdbc55eac7b216e035c36d82954 | [
"MIT"
] | null | null | null | // Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)
#include "ResourceFactory.h"
#include "ResourceManager.h"
namespace selene
{
ResourceFactory::ResourceFactory(FileManager* fileManager):
fileManager_(fileManager), resourceManager_(nullptr), resourceFactory_(nullptr) {}
ResourceFactory::~ResourceFactory() {}
//----------------------------------------------------------------------------------------
void ResourceFactory::setFileManager(FileManager* fileManager)
{
fileManager_ = fileManager;
}
//----------------------------------------------------------------------------------------
void ResourceFactory::setResourceManager(ResourceManager* resourceManager)
{
resourceManager_ = resourceManager;
}
//----------------------------------------------------------------------------------------
void ResourceFactory::setResourceFactory(ResourceFactory* resourceFactory)
{
resourceFactory_ = resourceFactory;
}
}
| 34.848485 | 98 | 0.493043 | everard |
b802a0b7659d1f22dd4ea2aee5aaafc8177026fb | 4,853 | cpp | C++ | unit_tests/os_interface/windows/driver_info_tests.cpp | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | 1 | 2022-03-04T22:47:19.000Z | 2022-03-04T22:47:19.000Z | unit_tests/os_interface/windows/driver_info_tests.cpp | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | null | null | null | unit_tests/os_interface/windows/driver_info_tests.cpp | abhi5658054/compute-runtime | 894060de5010874381fc981cf96a722769e65a76 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 - 2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "unit_tests/os_interface/windows/wddm_fixture.h"
#include "runtime/os_interface/windows/driver_info.h"
#include "runtime/os_interface/windows/registry_reader.h"
#include "runtime/os_interface/windows/os_interface.h"
#include "runtime/memory_manager/os_agnostic_memory_manager.h"
#include "runtime/helpers/options.h"
#include "unit_tests/mocks/mock_device.h"
#include "unit_tests/mocks/mock_csr.h"
#include "unit_tests/libult/create_command_stream.h"
#include "gtest/gtest.h"
namespace OCLRT {
extern CommandStreamReceiverCreateFunc commandStreamReceiverFactory[2 * IGFX_MAX_CORE];
CommandStreamReceiver *createMockCommandStreamReceiver(const HardwareInfo &hwInfoIn, bool withAubDump);
class DriverInfoDeviceTest : public ::testing::Test {
public:
static Wddm *wddmMock;
void SetUp() {
wddmMock = nullptr;
hwInfo = platformDevices[0];
commandStreamReceiverCreateFunc = commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily];
commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily] = createMockCommandStreamReceiver;
}
void TearDown() {
commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily] = commandStreamReceiverCreateFunc;
delete wddmMock;
}
CommandStreamReceiverCreateFunc commandStreamReceiverCreateFunc;
const HardwareInfo *hwInfo;
};
CommandStreamReceiver *createMockCommandStreamReceiver(const HardwareInfo &hwInfoIn, bool withAubDump) {
auto csr = new MockCommandStreamReceiver();
OSInterface *osInterface = new OSInterface();
DriverInfoDeviceTest::wddmMock = new WddmMock();
osInterface->get()->setWddm(DriverInfoDeviceTest::wddmMock);
csr->setOSInterface(osInterface);
return csr;
}
Wddm *DriverInfoDeviceTest::wddmMock = nullptr;
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWhenCorrectOSInterfaceThenCreateDriverInfo) {
overrideCommandStreamReceiverCreation = true;
auto device = Device::create<OCLRT::MockDevice>(hwInfo);
EXPECT_TRUE(device->hasDriverInfo());
delete device;
}
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWithoutCorrectOSInterfaceThenDontCreateDriverInfo) {
overrideCommandStreamReceiverCreation = false;
auto device = Device::create<OCLRT::MockDevice>(hwInfo);
EXPECT_FALSE(device->hasDriverInfo());
delete device;
}
class RegistryReaderMock : public SettingsReader {
public:
std::string nameString;
std::string versionString;
std::string getSetting(const char *settingName, const std::string &value) {
std::string key(settingName);
if (key == "HardwareInformation.AdapterString") {
properNameKey = true;
} else if (key == "DriverVersion") {
properVersionKey = true;
}
return value;
}
bool getSetting(const char *settingName, bool defaultValue) { return defaultValue; };
int32_t getSetting(const char *settingName, int32_t defaultValue) { return defaultValue; };
bool properNameKey = false;
bool properVersionKey = false;
};
TEST(DriverInfo, GivenDriverInfoWhenThenReturnNonNullptr) {
DriverInfoWindows driverInfo;
RegistryReaderMock *registryReaderMock = new RegistryReaderMock();
driverInfo.setRegistryReader(registryReaderMock);
std::string defaultName = "defaultName";
auto name = driverInfo.getDeviceName(defaultName);
EXPECT_STREQ(defaultName.c_str(), name.c_str());
EXPECT_TRUE(registryReaderMock->properNameKey);
std::string defaultVersion = "defaultVersion";
auto driverVersion = driverInfo.getVersion(defaultVersion);
EXPECT_STREQ(defaultVersion.c_str(), driverVersion.c_str());
EXPECT_TRUE(registryReaderMock->properVersionKey);
}
} // namespace OCLRT
| 37.620155 | 109 | 0.762209 | abhi5658054 |
b8033f5c4f1d9d07692592354e4e646209e29962 | 2,563 | cpp | C++ | usaco/january-2022/bronze/problem-2/problem-2.cpp | Yash-Singh1/competitive-programming | 3b9d278ed8138ab614e2a3d748627db8f4a2cdbd | [
"MIT"
] | null | null | null | usaco/january-2022/bronze/problem-2/problem-2.cpp | Yash-Singh1/competitive-programming | 3b9d278ed8138ab614e2a3d748627db8f4a2cdbd | [
"MIT"
] | null | null | null | usaco/january-2022/bronze/problem-2/problem-2.cpp | Yash-Singh1/competitive-programming | 3b9d278ed8138ab614e2a3d748627db8f4a2cdbd | [
"MIT"
] | null | null | null | #include <iostream>
#include <ios>
using std::cin;
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t{0};
cin >> t;
for (int i{0}; i < t; ++i)
{
int die1[4], die2[4];
for (int j{0}; j < 4; ++j)
{
cin >> die1[j];
}
double prob2{0};
double prob1{0};
for (int j{0}; j < 4; ++j)
{
cin >> die2[j];
for (int k{0}; k < 4; ++k)
{
if (die2[j] > die1[k])
{
prob2 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die1[j] > die2[k])
{
prob1 += 0.25;
}
}
}
bool done{false};
for (int j{1}; j <= 10; ++j)
{
for (int k{j}; k <= 10; ++k)
{
for (int l{k}; l <= 10; ++l)
{
for (int m{l}; m <= 10; ++m)
{
double prob3{0};
double prob4{0};
int die3[4]{j, k, l, m};
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die2[j] > die3[k])
{
prob3 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die3[j] > die2[k])
{
prob4 += 0.25;
}
}
}
if (prob3 > prob4)
{
continue;
}
double prob5{0};
double prob6{0};
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die1[j] > die3[k])
{
prob5 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die3[j] > die1[k])
{
prob6 += 0.25;
}
}
}
if (prob6 < prob5)
{
continue;
}
std::cout << "yes\n";
done = true;
break;
}
if (done)
{
break;
}
}
if (done)
{
break;
}
}
if (done)
{
break;
}
}
if (done)
{
continue;
}
else
{
std::cout << "no\n";
}
}
}
| 19.270677 | 40 | 0.261022 | Yash-Singh1 |
b803a92fde0ba7aaaa3ced85b55a34f0068c7d3d | 46,476 | cpp | C++ | indra/newview/llpanellandmarks.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/newview/llpanellandmarks.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/newview/llpanellandmarks.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | /**
* @file llpanellandmarks.cpp
* @brief Landmarks tab for Side Bar "Places" panel
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llpanellandmarks.h"
#include "llbutton.h"
#include "llfloaterreg.h"
#include "llnotificationsutil.h"
#include "llsdutil.h"
#include "llsdutil_math.h"
#include "llregionhandle.h"
#include "llaccordionctrl.h"
#include "llaccordionctrltab.h"
#include "llagent.h"
#include "llagentpicksinfo.h"
#include "llagentui.h"
#include "llcallbacklist.h"
#include "lldndbutton.h"
#include "llfloatersidepanelcontainer.h"
#include "llfloaterworldmap.h"
#include "llfolderviewitem.h"
#include "llinventorymodelbackgroundfetch.h"
#include "llinventorypanel.h"
#include "llinventoryfunctions.h"
#include "lllandmarkactions.h"
#include "llmenubutton.h"
#include "llplacesinventorybridge.h"
#include "llplacesinventorypanel.h"
#include "llplacesfolderview.h"
#include "lltoggleablemenu.h"
#include "llviewermenu.h"
#include "llviewerregion.h"
// [RLVa:KB]
#include "rlvhandler.h"
// [/RLVa:KB]
// Not yet implemented; need to remove buildPanel() from constructor when we switch
//static LLPanelInjector<LLLandmarksPanel> t_landmarks("panel_landmarks");
static const std::string OPTIONS_BUTTON_NAME = "options_gear_btn";
static const std::string ADD_BUTTON_NAME = "add_btn";
static const std::string ADD_FOLDER_BUTTON_NAME = "add_folder_btn";
static const std::string TRASH_BUTTON_NAME = "trash_btn";
// helper functions
static void filter_list(LLPlacesInventoryPanel* inventory_list, const std::string& string);
static bool category_has_descendents(LLPlacesInventoryPanel* inventory_list);
static void collapse_all_folders(LLFolderView* root_folder);
static void expand_all_folders(LLFolderView* root_folder);
static bool has_expanded_folders(LLFolderView* root_folder);
static bool has_collapsed_folders(LLFolderView* root_folder);
static void toggle_restore_menu(LLMenuGL* menu, BOOL visible, BOOL enabled);
/**
* Functor counting expanded and collapsed folders in folder view tree to know
* when to enable or disable "Expand all folders" and "Collapse all folders" commands.
*/
class LLCheckFolderState : public LLFolderViewFunctor
{
public:
LLCheckFolderState()
: mCollapsedFolders(0),
mExpandedFolders(0)
{}
virtual ~LLCheckFolderState() {}
virtual void doFolder(LLFolderViewFolder* folder);
virtual void doItem(LLFolderViewItem* item) {}
S32 getCollapsedFolders() { return mCollapsedFolders; }
S32 getExpandedFolders() { return mExpandedFolders; }
private:
S32 mCollapsedFolders;
S32 mExpandedFolders;
};
// virtual
void LLCheckFolderState::doFolder(LLFolderViewFolder* folder)
{
// Counting only folders that pass the filter.
// The listener check allow us to avoid counting the folder view
// object itself because it has no listener assigned.
if (folder->getViewModelItem()->descendantsPassedFilter())
{
if (folder->isOpen())
{
++mExpandedFolders;
}
else
{
++mCollapsedFolders;
}
}
}
// Functor searching and opening a folder specified by UUID
// in a folder view tree.
class LLOpenFolderByID : public LLFolderViewFunctor
{
public:
LLOpenFolderByID(const LLUUID& folder_id)
: mFolderID(folder_id)
, mIsFolderOpen(false)
{}
virtual ~LLOpenFolderByID() {}
/*virtual*/ void doFolder(LLFolderViewFolder* folder);
/*virtual*/ void doItem(LLFolderViewItem* item) {}
bool isFolderOpen() { return mIsFolderOpen; }
private:
bool mIsFolderOpen;
LLUUID mFolderID;
};
// virtual
void LLOpenFolderByID::doFolder(LLFolderViewFolder* folder)
{
if (folder->getViewModelItem() && static_cast<LLFolderViewModelItemInventory*>(folder->getViewModelItem())->getUUID() == mFolderID)
{
if (!folder->isOpen())
{
folder->setOpen(TRUE);
mIsFolderOpen = true;
}
}
}
/**
* Bridge to support knowing when the inventory has changed to update Landmarks tab
* ShowFolderState filter setting to show all folders when the filter string is empty and
* empty folder message when Landmarks inventory category has no children.
* Ensures that "Landmarks" folder in the Library is open on strart up.
*/
class LLLandmarksPanelObserver : public LLInventoryObserver
{
public:
LLLandmarksPanelObserver(LLLandmarksPanel* lp)
: mLP(lp),
mIsLibraryLandmarksOpen(false)
{}
virtual ~LLLandmarksPanelObserver() {}
/*virtual*/ void changed(U32 mask);
private:
LLLandmarksPanel* mLP;
bool mIsLibraryLandmarksOpen;
};
void LLLandmarksPanelObserver::changed(U32 mask)
{
mLP->updateShowFolderState();
LLPlacesInventoryPanel* library = mLP->getLibraryInventoryPanel();
if (!mIsLibraryLandmarksOpen && library)
{
// Search for "Landmarks" folder in the Library and open it once on start up. See EXT-4827.
const LLUUID &landmarks_cat = gInventory.findLibraryCategoryUUIDForType(LLFolderType::FT_LANDMARK, false);
if (landmarks_cat.notNull())
{
LLOpenFolderByID opener(landmarks_cat);
library->getRootFolder()->applyFunctorRecursively(opener);
mIsLibraryLandmarksOpen = opener.isFolderOpen();
}
}
}
LLLandmarksPanel::LLLandmarksPanel()
: LLPanelPlacesTab()
, mFavoritesInventoryPanel(NULL)
, mLandmarksInventoryPanel(NULL)
, mMyInventoryPanel(NULL)
, mLibraryInventoryPanel(NULL)
, mCurrentSelectedList(NULL)
, mListCommands(NULL)
, mGearButton(NULL)
, mGearFolderMenu(NULL)
, mGearLandmarkMenu(NULL)
{
mInventoryObserver = new LLLandmarksPanelObserver(this);
gInventory.addObserver(mInventoryObserver);
buildFromFile( "panel_landmarks.xml");
}
LLLandmarksPanel::~LLLandmarksPanel()
{
if (gInventory.containsObserver(mInventoryObserver))
{
gInventory.removeObserver(mInventoryObserver);
}
}
BOOL LLLandmarksPanel::postBuild()
{
if (!gInventory.isInventoryUsable())
return FALSE;
// mast be called before any other initXXX methods to init Gear menu
initListCommandsHandlers();
initFavoritesInventoryPanel();
initLandmarksInventoryPanel();
initMyInventoryPanel();
initLibraryInventoryPanel();
return TRUE;
}
// virtual
void LLLandmarksPanel::onSearchEdit(const std::string& string)
{
// <FS:Ansariel> Fix for landmark search (FIRE-6611): We don't have
// accordion tabs but normal tabs!
// give FolderView a chance to be refreshed. So, made all accordions visible
//for (accordion_tabs_t::const_iterator iter = mAccordionTabs.begin(); iter != mAccordionTabs.end(); ++iter)
//{
// LLAccordionCtrlTab* tab = *iter;
// tab->setVisible(TRUE);
// // expand accordion to see matched items in each one. See EXT-2014.
// if (string != "")
// {
// tab->changeOpenClose(false);
// }
// LLPlacesInventoryPanel* inventory_list = dynamic_cast<LLPlacesInventoryPanel*>(tab->getAccordionView());
// if (NULL == inventory_list) continue;
if (mFavoritesInventoryPanel)
{
filter_list(mFavoritesInventoryPanel, string);
}
if (mLandmarksInventoryPanel)
{
filter_list(mLandmarksInventoryPanel, string);
}
if (mMyInventoryPanel)
{
filter_list(mMyInventoryPanel, string);
}
if (mLibraryInventoryPanel)
{
filter_list(mLibraryInventoryPanel, string);
}
// </FS:Ansariel> Fix for landmark search (FIRE-6611)
if (sFilterSubString != string)
sFilterSubString = string;
// show all folders in Landmarks Accordion for empty filter
// only if Landmarks inventory folder is not empty
updateShowFolderState();
}
// virtual
void LLLandmarksPanel::onShowOnMap()
{
if (NULL == mCurrentSelectedList)
{
LL_WARNS() << "There are no selected list. No actions are performed." << LL_ENDL;
return;
}
// Disable the "Map" button because loading landmark can take some time.
// During this time the button is useless. It will be enabled on callback finish
// or upon switching to other item.
mShowOnMapBtn->setEnabled(FALSE);
doActionOnCurSelectedLandmark(boost::bind(&LLLandmarksPanel::doShowOnMap, this, _1));
}
//virtual
void LLLandmarksPanel::onShowProfile()
{
LLFolderViewModelItemInventory* cur_item = getCurSelectedViewModelItem();
if(!cur_item)
return;
cur_item->performAction(mCurrentSelectedList->getModel(),"about");
}
// virtual
void LLLandmarksPanel::onTeleport()
{
LLFolderViewModelItemInventory* view_model_item = getCurSelectedViewModelItem();
if (view_model_item && view_model_item->getInventoryType() == LLInventoryType::IT_LANDMARK)
{
view_model_item->openItem();
}
}
// virtual
bool LLLandmarksPanel::isSingleItemSelected()
{
bool result = false;
if (mCurrentSelectedList != NULL)
{
LLFolderView* root_view = mCurrentSelectedList->getRootFolder();
if (root_view->getSelectedCount() == 1)
{
result = isLandmarkSelected();
}
}
return result;
}
// virtual
void LLLandmarksPanel::updateVerbs()
{
if (!isTabVisible())
return;
bool landmark_selected = isLandmarkSelected();
mTeleportBtn->setEnabled(landmark_selected && isActionEnabled("teleport"));
mShowProfile->setEnabled(landmark_selected && isActionEnabled("more_info"));
mShowOnMapBtn->setEnabled(landmark_selected && isActionEnabled("show_on_map"));
// TODO: mantipov: Uncomment when mShareBtn is supported
// Share button should be enabled when neither a folder nor a landmark is selected
//mShareBtn->setEnabled(NULL != current_item);
updateListCommands();
}
void LLLandmarksPanel::onSelectionChange(LLPlacesInventoryPanel* inventory_list, const std::deque<LLFolderViewItem*> &items, BOOL user_action)
{
if (user_action && (items.size() > 0))
{
deselectOtherThan(inventory_list);
mCurrentSelectedList = inventory_list;
}
updateVerbs();
}
void LLLandmarksPanel::onSelectorButtonClicked()
{
// TODO: mantipov: update getting of selected item
// TODO: bind to "i" button
LLFolderViewItem* cur_item = mFavoritesInventoryPanel->getRootFolder()->getCurSelectedItem();
if (!cur_item) return;
LLFolderViewModelItemInventory* listenerp = static_cast<LLFolderViewModelItemInventory*>(cur_item->getViewModelItem());
if (listenerp->getInventoryType() == LLInventoryType::IT_LANDMARK)
{
LLSD key;
key["type"] = "landmark";
key["id"] = listenerp->getUUID();
// <FS:Ansariel> FIRE-817: Separate place details floater
//LLFloaterSidePanelContainer::showPanel("places", key);
if (gSavedSettings.getBOOL("FSUseStandalonePlaceDetailsFloater"))
{
LLFloaterReg::showInstance("fs_placedetails", key);
}
else
{
LLFloaterSidePanelContainer::showPanel("places", key);
}
// </FS:Ansariel>
}
}
void LLLandmarksPanel::updateShowFolderState()
{
bool show_all_folders = mLandmarksInventoryPanel->getFilterSubString().empty();
if (show_all_folders)
{
show_all_folders = category_has_descendents(mLandmarksInventoryPanel);
}
mLandmarksInventoryPanel->setShowFolderState(show_all_folders ?
LLInventoryFilter::SHOW_ALL_FOLDERS :
LLInventoryFilter::SHOW_NON_EMPTY_FOLDERS
);
}
void LLLandmarksPanel::setItemSelected(const LLUUID& obj_id, BOOL take_keyboard_focus)
{
if (selectItemInAccordionTab(mFavoritesInventoryPanel, "tab_favorites", obj_id, take_keyboard_focus))
{
return;
}
if (selectItemInAccordionTab(mLandmarksInventoryPanel, "tab_landmarks", obj_id, take_keyboard_focus))
{
return;
}
if (selectItemInAccordionTab(mMyInventoryPanel, "tab_inventory", obj_id, take_keyboard_focus))
{
return;
}
if (selectItemInAccordionTab(mLibraryInventoryPanel, "tab_library", obj_id, take_keyboard_focus))
{
return;
}
}
//////////////////////////////////////////////////////////////////////////
// PROTECTED METHODS
//////////////////////////////////////////////////////////////////////////
bool LLLandmarksPanel::isLandmarkSelected() const
{
LLFolderViewModelItemInventory* current_item = getCurSelectedViewModelItem();
return current_item && (current_item->getInventoryType() == LLInventoryType::IT_LANDMARK);
}
bool LLLandmarksPanel::isFolderSelected() const
{
LLFolderViewModelItemInventory* current_item = getCurSelectedViewModelItem();
return current_item && (current_item->getInventoryType() == LLInventoryType::IT_CATEGORY);
}
bool LLLandmarksPanel::isReceivedFolderSelected() const
{
// Received Folder can be only in Landmarks accordion
if (mCurrentSelectedList != mLandmarksInventoryPanel) return false;
// *TODO: it should be filled with logic when EXT-976 is done.
LL_WARNS() << "Not implemented yet until EXT-976 is done." << LL_ENDL;
return false;
}
void LLLandmarksPanel::doActionOnCurSelectedLandmark(LLLandmarkList::loaded_callback_t cb)
{
LLFolderViewModelItemInventory* cur_item = getCurSelectedViewModelItem();
if(cur_item && cur_item->getInventoryType() == LLInventoryType::IT_LANDMARK)
{
LLLandmark* landmark = LLLandmarkActions::getLandmark(cur_item->getUUID(), cb);
if (landmark)
{
cb(landmark);
}
}
}
LLFolderViewItem* LLLandmarksPanel::getCurSelectedItem() const
{
return mCurrentSelectedList ? mCurrentSelectedList->getRootFolder()->getCurSelectedItem() : NULL;
}
LLFolderViewModelItemInventory* LLLandmarksPanel::getCurSelectedViewModelItem() const
{
LLFolderViewItem* cur_item = getCurSelectedItem();
if (cur_item)
{
return static_cast<LLFolderViewModelItemInventory*>(cur_item->getViewModelItem());
}
return NULL;
}
LLFolderViewItem* LLLandmarksPanel::selectItemInAccordionTab(LLPlacesInventoryPanel* inventory_list,
const std::string& tab_name,
const LLUUID& obj_id,
BOOL take_keyboard_focus) const
{
if (!inventory_list)
return NULL;
LLFolderView* root = inventory_list->getRootFolder();
LLFolderViewItem* item = inventory_list->getItemByID(obj_id);
if (!item)
return NULL;
LLAccordionCtrlTab* tab = getChild<LLAccordionCtrlTab>(tab_name);
if (!tab->isExpanded())
{
tab->changeOpenClose(false);
}
root->setSelection(item, FALSE, take_keyboard_focus);
LLAccordionCtrl* accordion = getChild<LLAccordionCtrl>("landmarks_accordion");
LLRect screen_rc;
localRectToScreen(item->getRect(), &screen_rc);
accordion->notifyParent(LLSD().with("scrollToShowRect", screen_rc.getValue()));
return item;
}
void LLLandmarksPanel::updateSortOrder(LLInventoryPanel* panel, bool byDate)
{
if(!panel) return;
U32 order = panel->getSortOrder();
if (byDate)
{
panel->setSortOrder( order | LLInventoryFilter::SO_DATE );
}
else
{
panel->setSortOrder( order & ~LLInventoryFilter::SO_DATE );
}
}
// virtual
void LLLandmarksPanel::processParcelInfo(const LLParcelData& parcel_data)
{
//this function will be called after user will try to create a pick for selected landmark.
// We have to make request to sever to get parcel_id and snaption_id.
if(isLandmarkSelected())
{
LLFolderViewModelItemInventory* cur_item = getCurSelectedViewModelItem();
if (!cur_item) return;
LLUUID id = cur_item->getUUID();
LLInventoryItem* inv_item = mCurrentSelectedList->getModel()->getItem(id);
doActionOnCurSelectedLandmark(boost::bind(
&LLLandmarksPanel::doProcessParcelInfo, this, _1, getCurSelectedItem(), inv_item, parcel_data));
}
}
// virtual
void LLLandmarksPanel::setParcelID(const LLUUID& parcel_id)
{
if (!parcel_id.isNull())
{
LLRemoteParcelInfoProcessor::getInstance()->addObserver(parcel_id, this);
LLRemoteParcelInfoProcessor::getInstance()->sendParcelInfoRequest(parcel_id);
}
}
// virtual
void LLLandmarksPanel::setErrorStatus(U32 status, const std::string& reason)
{
LL_WARNS() << "Can't handle remote parcel request."<< " Http Status: "<< status << ". Reason : "<< reason<<LL_ENDL;
}
//////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
//////////////////////////////////////////////////////////////////////////
void LLLandmarksPanel::initFavoritesInventoryPanel()
{
mFavoritesInventoryPanel = getChild<LLPlacesInventoryPanel>("favorites_list");
initLandmarksPanel(mFavoritesInventoryPanel);
mFavoritesInventoryPanel->getFilter().setEmptyLookupMessage("FavoritesNoMatchingItems");
initAccordion("tab_favorites", mFavoritesInventoryPanel, true);
}
void LLLandmarksPanel::initLandmarksInventoryPanel()
{
mLandmarksInventoryPanel = getChild<LLPlacesInventoryPanel>("landmarks_list");
initLandmarksPanel(mLandmarksInventoryPanel);
mLandmarksInventoryPanel->setShowFolderState(LLInventoryFilter::SHOW_ALL_FOLDERS);
// subscribe to have auto-rename functionality while creating New Folder
mLandmarksInventoryPanel->setSelectCallback(boost::bind(&LLInventoryPanel::onSelectionChange, mLandmarksInventoryPanel, _1, _2));
mMyLandmarksAccordionTab = initAccordion("tab_landmarks", mLandmarksInventoryPanel, true);
}
void LLLandmarksPanel::initMyInventoryPanel()
{
mMyInventoryPanel= getChild<LLPlacesInventoryPanel>("my_inventory_list");
initLandmarksPanel(mMyInventoryPanel);
initAccordion("tab_inventory", mMyInventoryPanel, false);
}
void LLLandmarksPanel::initLibraryInventoryPanel()
{
mLibraryInventoryPanel = getChild<LLPlacesInventoryPanel>("library_list");
initLandmarksPanel(mLibraryInventoryPanel);
// We want to fetch only "Landmarks" category from the library.
const LLUUID &landmarks_cat = gInventory.findLibraryCategoryUUIDForType(LLFolderType::FT_LANDMARK, false);
if (landmarks_cat.notNull())
{
LLInventoryModelBackgroundFetch::instance().start(landmarks_cat);
}
// Expanding "Library" tab for new users who have no landmarks in "My Inventory".
initAccordion("tab_library", mLibraryInventoryPanel, true);
}
void LLLandmarksPanel::initLandmarksPanel(LLPlacesInventoryPanel* inventory_list)
{
inventory_list->getFilter().setEmptyLookupMessage("PlacesNoMatchingItems");
inventory_list->setFilterTypes(0x1 << LLInventoryType::IT_LANDMARK);
inventory_list->setSelectCallback(boost::bind(&LLLandmarksPanel::onSelectionChange, this, inventory_list, _1, _2));
inventory_list->setShowFolderState(LLInventoryFilter::SHOW_NON_EMPTY_FOLDERS);
bool sorting_order = gSavedSettings.getBOOL("LandmarksSortedByDate");
updateSortOrder(inventory_list, sorting_order);
LLPlacesFolderView* root_folder = dynamic_cast<LLPlacesFolderView*>(inventory_list->getRootFolder());
if (root_folder)
{
root_folder->setupMenuHandle(LLInventoryType::IT_CATEGORY, mGearFolderMenu->getHandle());
root_folder->setupMenuHandle(LLInventoryType::IT_LANDMARK, mGearLandmarkMenu->getHandle());
root_folder->setParentLandmarksPanel(this);
}
inventory_list->saveFolderState();
}
LLAccordionCtrlTab* LLLandmarksPanel::initAccordion(const std::string& accordion_tab_name, LLPlacesInventoryPanel* inventory_list, bool expand_tab)
{
LLAccordionCtrlTab* accordion_tab = getChild<LLAccordionCtrlTab>(accordion_tab_name);
mAccordionTabs.push_back(accordion_tab);
accordion_tab->setDropDownStateChangedCallback(
boost::bind(&LLLandmarksPanel::onAccordionExpandedCollapsed, this, _2, inventory_list));
accordion_tab->setDisplayChildren(expand_tab);
return accordion_tab;
}
void LLLandmarksPanel::onAccordionExpandedCollapsed(const LLSD& param, LLPlacesInventoryPanel* inventory_list)
{
bool expanded = param.asBoolean();
if(!expanded && (mCurrentSelectedList == inventory_list))
{
inventory_list->getRootFolder()->clearSelection();
mCurrentSelectedList = NULL;
updateVerbs();
}
// Start background fetch, mostly for My Inventory and Library
if (expanded)
{
const LLUUID &cat_id = inventory_list->getRootFolderID();
// Just because the category itself has been fetched, doesn't mean its child folders have.
/*
if (!gInventory.isCategoryComplete(cat_id))
*/
{
LLInventoryModelBackgroundFetch::instance().start(cat_id);
}
// Apply filter substring because it might have been changed
// while accordion was closed. See EXT-3714.
filter_list(inventory_list, sFilterSubString);
}
}
void LLLandmarksPanel::deselectOtherThan(const LLPlacesInventoryPanel* inventory_list)
{
if (inventory_list != mFavoritesInventoryPanel)
{
mFavoritesInventoryPanel->clearSelection();
}
if (inventory_list != mLandmarksInventoryPanel)
{
mLandmarksInventoryPanel->clearSelection();
}
if (inventory_list != mMyInventoryPanel)
{
mMyInventoryPanel->clearSelection();
}
if (inventory_list != mLibraryInventoryPanel)
{
mLibraryInventoryPanel->clearSelection();
}
}
// List Commands Handlers
void LLLandmarksPanel::initListCommandsHandlers()
{
mListCommands = getChild<LLPanel>("bottom_panel");
mGearButton = getChild<LLMenuButton>(OPTIONS_BUTTON_NAME);
mGearButton->setMouseDownCallback(boost::bind(&LLLandmarksPanel::onActionsButtonClick, this));
mListCommands->childSetAction(TRASH_BUTTON_NAME, boost::bind(&LLLandmarksPanel::onTrashButtonClick, this));
LLDragAndDropButton* trash_btn = mListCommands->getChild<LLDragAndDropButton>(TRASH_BUTTON_NAME);
trash_btn->setDragAndDropHandler(boost::bind(&LLLandmarksPanel::handleDragAndDropToTrash, this
, _4 // BOOL drop
, _5 // EDragAndDropType cargo_type
, _6 // void* cargo_data
, _7 // EAcceptance* accept
));
mCommitCallbackRegistrar.add("Places.LandmarksGear.Add.Action", boost::bind(&LLLandmarksPanel::onAddAction, this, _2));
mCommitCallbackRegistrar.add("Places.LandmarksGear.CopyPaste.Action", boost::bind(&LLLandmarksPanel::onClipboardAction, this, _2));
mCommitCallbackRegistrar.add("Places.LandmarksGear.Custom.Action", boost::bind(&LLLandmarksPanel::onCustomAction, this, _2));
mCommitCallbackRegistrar.add("Places.LandmarksGear.Folding.Action", boost::bind(&LLLandmarksPanel::onFoldingAction, this, _2));
mEnableCallbackRegistrar.add("Places.LandmarksGear.Check", boost::bind(&LLLandmarksPanel::isActionChecked, this, _2));
mEnableCallbackRegistrar.add("Places.LandmarksGear.Enable", boost::bind(&LLLandmarksPanel::isActionEnabled, this, _2));
mGearLandmarkMenu = LLUICtrlFactory::getInstance()->createFromFile<LLToggleableMenu>("menu_places_gear_landmark.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
mGearFolderMenu = LLUICtrlFactory::getInstance()->createFromFile<LLToggleableMenu>("menu_places_gear_folder.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
mMenuAdd = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_place_add_button.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
mGearLandmarkMenu->setVisibilityChangeCallback(boost::bind(&LLLandmarksPanel::onMenuVisibilityChange, this, _1, _2));
mGearFolderMenu->setVisibilityChangeCallback(boost::bind(&LLLandmarksPanel::onMenuVisibilityChange, this, _1, _2));
mListCommands->childSetAction(ADD_BUTTON_NAME, boost::bind(&LLLandmarksPanel::showActionMenu, this, mMenuAdd, ADD_BUTTON_NAME));
}
void LLLandmarksPanel::updateListCommands()
{
bool add_folder_enabled = isActionEnabled("category");
bool trash_enabled = isActionEnabled("delete") && (isFolderSelected() || isLandmarkSelected());
// keep Options & Add Landmark buttons always enabled
mListCommands->getChildView(ADD_FOLDER_BUTTON_NAME)->setEnabled(add_folder_enabled);
mListCommands->getChildView(TRASH_BUTTON_NAME)->setEnabled(trash_enabled);
}
void LLLandmarksPanel::updateMenuVisibility(LLUICtrl* menu)
{
onMenuVisibilityChange(menu, LLSD().with("visibility", true));
}
void LLLandmarksPanel::onActionsButtonClick()
{
LLToggleableMenu* menu = mGearFolderMenu;
if(mCurrentSelectedList)
{
LLFolderViewModelItemInventory* listenerp = getCurSelectedViewModelItem();
if(!listenerp)
return;
if (listenerp->getInventoryType() == LLInventoryType::IT_LANDMARK)
{
menu = mGearLandmarkMenu;
}
}
mGearButton->setMenu(menu);
}
void LLLandmarksPanel::showActionMenu(LLMenuGL* menu, std::string spawning_view_name)
{
if (menu)
{
menu->buildDrawLabels();
menu->updateParent(LLMenuGL::sMenuContainer);
menu->arrangeAndClear();
LLView* spawning_view = getChild<LLView>(spawning_view_name);
S32 menu_x, menu_y;
//show menu in co-ordinates of panel
spawning_view->localPointToOtherView(0, spawning_view->getRect().getHeight(), &menu_x, &menu_y, this);
menu_y += menu->getRect().getHeight();
LLMenuGL::showPopup(this, menu, menu_x, menu_y);
}
}
void LLLandmarksPanel::onTrashButtonClick() const
{
onClipboardAction("delete");
}
void LLLandmarksPanel::onAddAction(const LLSD& userdata) const
{
LLFolderViewModelItemInventory* view_model = getCurSelectedViewModelItem();
LLFolderViewItem* item = getCurSelectedItem();
std::string command_name = userdata.asString();
if("add_landmark" == command_name)
{
// [RLVa:KB] - Checked: 2012-02-08 (RLVa-1.4.5) | Added: RLVa-1.4.5
if (!gRlvHandler.hasBehaviour(RLV_BHVR_SHOWLOC))
{
// [/RLVa:KB]
LLViewerInventoryItem* landmark = LLLandmarkActions::findLandmarkForAgentPos();
if(landmark)
{
LLNotificationsUtil::add("LandmarkAlreadyExists");
}
else
{
// <FS:Ansariel> FIRE-817: Separate place details floater
//LLFloaterSidePanelContainer::showPanel("places", LLSD().with("type", "create_landmark"));
if (gSavedSettings.getBOOL("FSUseStandalonePlaceDetailsFloater"))
{
LLFloaterReg::showInstance("fs_placedetails", LLSD().with("type", "create_landmark"));
}
else
{
LLFloaterSidePanelContainer::showPanel("places", LLSD().with("type", "create_landmark"));
}
// </FS:Ansariel>
}
// [RLVa:KB] - Checked: 2012-02-08 (RLVa-1.4.5) | Added: RLVa-1.4.5
}
// [/RLVa:KB]
}
else if ("category" == command_name)
{
if (item && mCurrentSelectedList == mLandmarksInventoryPanel)
{
LLFolderViewModelItem* folder_bridge = NULL;
if (view_model->getInventoryType()
== LLInventoryType::IT_LANDMARK)
{
// for a landmark get parent folder bridge
folder_bridge = item->getParentFolder()->getViewModelItem();
}
else if (view_model->getInventoryType()
== LLInventoryType::IT_CATEGORY)
{
// for a folder get its own bridge
folder_bridge = view_model;
}
menu_create_inventory_item(mCurrentSelectedList,
dynamic_cast<LLFolderBridge*> (folder_bridge), LLSD(
"category"), gInventory.findCategoryUUIDForType(
LLFolderType::FT_LANDMARK));
}
else
{
//in case My Landmarks tab is completely empty (thus cannot be determined as being selected)
menu_create_inventory_item(mLandmarksInventoryPanel, NULL, LLSD("category"),
gInventory.findCategoryUUIDForType(LLFolderType::FT_LANDMARK));
if (mMyLandmarksAccordionTab)
{
mMyLandmarksAccordionTab->changeOpenClose(false);
}
}
}
}
void LLLandmarksPanel::onClipboardAction(const LLSD& userdata) const
{
if(!mCurrentSelectedList)
return;
std::string command_name = userdata.asString();
if("copy_slurl" == command_name)
{
LLFolderViewModelItemInventory* cur_item = getCurSelectedViewModelItem();
if(cur_item)
LLLandmarkActions::copySLURLtoClipboard(cur_item->getUUID());
}
else if ( "paste" == command_name)
{
mCurrentSelectedList->getRootFolder()->paste();
}
else if ( "cut" == command_name)
{
mCurrentSelectedList->getRootFolder()->cut();
}
else
{
mCurrentSelectedList->doToSelected(command_name);
}
}
void LLLandmarksPanel::onFoldingAction(const LLSD& userdata)
{
std::string command_name = userdata.asString();
if ("expand_all" == command_name)
{
expand_all_folders(mFavoritesInventoryPanel->getRootFolder());
expand_all_folders(mLandmarksInventoryPanel->getRootFolder());
expand_all_folders(mMyInventoryPanel->getRootFolder());
expand_all_folders(mLibraryInventoryPanel->getRootFolder());
for (accordion_tabs_t::const_iterator iter = mAccordionTabs.begin(); iter != mAccordionTabs.end(); ++iter)
{
(*iter)->changeOpenClose(false);
}
}
else if ("collapse_all" == command_name)
{
collapse_all_folders(mFavoritesInventoryPanel->getRootFolder());
collapse_all_folders(mLandmarksInventoryPanel->getRootFolder());
collapse_all_folders(mMyInventoryPanel->getRootFolder());
collapse_all_folders(mLibraryInventoryPanel->getRootFolder());
for (accordion_tabs_t::const_iterator iter = mAccordionTabs.begin(); iter != mAccordionTabs.end(); ++iter)
{
(*iter)->changeOpenClose(true);
}
}
else if ("sort_by_date" == command_name)
{
bool sorting_order = gSavedSettings.getBOOL("LandmarksSortedByDate");
sorting_order=!sorting_order;
gSavedSettings.setBOOL("LandmarksSortedByDate",sorting_order);
updateSortOrder(mLandmarksInventoryPanel, sorting_order);
updateSortOrder(mMyInventoryPanel, sorting_order);
updateSortOrder(mLibraryInventoryPanel, sorting_order);
}
else
{
if(mCurrentSelectedList)
{
mCurrentSelectedList->doToSelected(userdata);
}
}
}
bool LLLandmarksPanel::isActionChecked(const LLSD& userdata) const
{
const std::string command_name = userdata.asString();
if ( "sort_by_date" == command_name)
{
bool sorting_order = gSavedSettings.getBOOL("LandmarksSortedByDate");
return sorting_order;
}
return false;
}
bool LLLandmarksPanel::isActionEnabled(const LLSD& userdata) const
{
std::string command_name = userdata.asString();
LLFolderView* root_folder_view = mCurrentSelectedList
? mCurrentSelectedList->getRootFolder()
: NULL;
if ("collapse_all" == command_name)
{
bool disable_collapse_all = !has_expanded_folders(mFavoritesInventoryPanel->getRootFolder())
&& !has_expanded_folders(mLandmarksInventoryPanel->getRootFolder())
&& !has_expanded_folders(mMyInventoryPanel->getRootFolder())
&& !has_expanded_folders(mLibraryInventoryPanel->getRootFolder());
if (disable_collapse_all)
{
for (accordion_tabs_t::const_iterator iter = mAccordionTabs.begin(); iter != mAccordionTabs.end(); ++iter)
{
if ((*iter)->isExpanded())
{
disable_collapse_all = false;
break;
}
}
}
return !disable_collapse_all;
}
else if ("expand_all" == command_name)
{
bool disable_expand_all = !has_collapsed_folders(mFavoritesInventoryPanel->getRootFolder())
&& !has_collapsed_folders(mLandmarksInventoryPanel->getRootFolder())
&& !has_collapsed_folders(mMyInventoryPanel->getRootFolder())
&& !has_collapsed_folders(mLibraryInventoryPanel->getRootFolder());
if (disable_expand_all)
{
for (accordion_tabs_t::const_iterator iter = mAccordionTabs.begin(); iter != mAccordionTabs.end(); ++iter)
{
if (!(*iter)->isExpanded())
{
disable_expand_all = false;
break;
}
}
}
return !disable_expand_all;
}
else if ("sort_by_date" == command_name)
{
// disable "sort_by_date" for Favorites accordion because
// it has its own items order. EXT-1758
if (mCurrentSelectedList == mFavoritesInventoryPanel)
{
return false;
}
}
else if ( "paste" == command_name
|| "cut" == command_name
|| "copy" == command_name
|| "delete" == command_name
|| "collapse" == command_name
|| "expand" == command_name
)
{
if (!root_folder_view) return false;
std::set<LLFolderViewItem*> selected_uuids = root_folder_view->getSelectionList();
// Allow to execute the command only if it can be applied to all selected items.
for (std::set<LLFolderViewItem*>::const_iterator iter = selected_uuids.begin(); iter != selected_uuids.end(); ++iter)
{
LLFolderViewItem* item = *iter;
if (!item) return false;
if (!canItemBeModified(command_name, item)) return false;
}
return true;
}
else if ( "teleport" == command_name
|| "more_info" == command_name
|| "show_on_map" == command_name
|| "copy_slurl" == command_name
|| "rename" == command_name
)
{
// disable some commands for multi-selection. EXT-1757
bool is_single_selection = root_folder_view && root_folder_view->getSelectedCount() == 1;
if (!is_single_selection)
{
return false;
}
if ("show_on_map" == command_name)
{
LLFolderViewModelItemInventory* cur_item = getCurSelectedViewModelItem();
if (!cur_item) return false;
LLViewerInventoryItem* inv_item = dynamic_cast<LLViewerInventoryItem*>(cur_item->getInventoryObject());
if (!inv_item) return false;
LLUUID asset_uuid = inv_item->getAssetUUID();
if (asset_uuid.isNull()) return false;
// Disable "Show on Map" if landmark loading is in progress.
return !gLandmarkList.isAssetInLoadedCallbackMap(asset_uuid);
}
else if ("rename" == command_name)
{
LLFolderViewItem* selected_item = getCurSelectedItem();
if (!selected_item) return false;
return canItemBeModified(command_name, selected_item);
}
return true;
}
else if("category" == command_name)
{
// we can add folder only in Landmarks Accordion
if (mCurrentSelectedList == mLandmarksInventoryPanel)
{
// ... but except Received folder
return !isReceivedFolderSelected();
}
//"Add a folder" is enabled by default (case when My Landmarks is empty)
else return true;
}
else if("create_pick" == command_name)
{
if (mCurrentSelectedList)
{
std::set<LLFolderViewItem*> selection = mCurrentSelectedList->getRootFolder()->getSelectionList();
if (!selection.empty())
{
return ( 1 == selection.size() && !LLAgentPicksInfo::getInstance()->isPickLimitReached() );
}
}
return false;
}
// [RLVa:KB] - Checked: 2012-02-08 (RLVa-1.4.5) | Added: RLVa-1.4.5
else if("add_landmark" == command_name)
{
return !gRlvHandler.hasBehaviour(RLV_BHVR_SHOWLOC);
}
// [/RLVa:KB]
else
{
LL_WARNS() << "Unprocessed command has come: " << command_name << LL_ENDL;
}
return true;
}
void LLLandmarksPanel::onCustomAction(const LLSD& userdata)
{
std::string command_name = userdata.asString();
if("more_info" == command_name)
{
onShowProfile();
}
else if ("teleport" == command_name)
{
onTeleport();
}
else if ("show_on_map" == command_name)
{
onShowOnMap();
}
else if ("create_pick" == command_name)
{
doActionOnCurSelectedLandmark(boost::bind(&LLLandmarksPanel::doCreatePick, this, _1));
}
else if ("restore" == command_name && mCurrentSelectedList)
{
mCurrentSelectedList->doToSelected(userdata);
}
}
void LLLandmarksPanel::onMenuVisibilityChange(LLUICtrl* ctrl, const LLSD& param)
{
bool new_visibility = param["visibility"].asBoolean();
// We don't have to update items visibility if the menu is hiding.
if (!new_visibility) return;
BOOL are_any_items_in_trash = FALSE;
BOOL are_all_items_in_trash = TRUE;
LLFolderView* root_folder_view = mCurrentSelectedList ? mCurrentSelectedList->getRootFolder() : NULL;
if(root_folder_view)
{
const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
std::set<LLFolderViewItem*> selected_items = root_folder_view->getSelectionList();
// Iterate through selected items to find out if any of these items are in Trash
// or all the items are in Trash category.
for (std::set<LLFolderViewItem*>::const_iterator iter = selected_items.begin(); iter != selected_items.end(); ++iter)
{
LLFolderViewItem* item = *iter;
// If no item is found it might be a folder id.
if (!item) continue;
LLFolderViewModelItemInventory* listenerp = static_cast<LLFolderViewModelItemInventory*>(item->getViewModelItem());
if(!listenerp) continue;
// Trash category itself should not be included because it can't be
// actually restored from trash.
are_all_items_in_trash &= listenerp->isItemInTrash() && listenerp->getUUID() != trash_id;
// If there are any selected items in Trash including the Trash category itself
// we show "Restore Item" in context menu and hide other irrelevant items.
are_any_items_in_trash |= listenerp->isItemInTrash();
}
}
// Display "Restore Item" menu entry if at least one of the selected items
// is in Trash or the Trash category itself is among selected items.
// Hide other menu entries in this case.
// Enable this menu entry only if all selected items are in the Trash category.
toggle_restore_menu((LLMenuGL*)ctrl, are_any_items_in_trash, are_all_items_in_trash);
}
/*
Processes such actions: cut/rename/delete/paste actions
Rules:
1. We can't perform any action in Library
2. For Landmarks we can:
- cut/rename/delete in any other accordions
- paste - only in Favorites, Landmarks accordions
3. For Folders we can: perform any action in Landmarks accordion, except Received folder
4. We can paste folders from Clipboard (processed by LLFolderView::canPaste())
5. Check LLFolderView/Inventory Bridges rules
*/
bool LLLandmarksPanel::canItemBeModified(const std::string& command_name, LLFolderViewItem* item) const
{
// validate own rules first
if (!item) return false;
// nothing can be modified in Library
if (mLibraryInventoryPanel == mCurrentSelectedList) return false;
bool can_be_modified = false;
// landmarks can be modified in any other accordion...
if (static_cast<LLFolderViewModelItemInventory*>(item->getViewModelItem())->getInventoryType() == LLInventoryType::IT_LANDMARK)
{
can_be_modified = true;
// we can modify landmarks anywhere except paste to My Inventory
if ("paste" == command_name)
{
can_be_modified = (mCurrentSelectedList != mMyInventoryPanel);
}
}
else
{
// ...folders only in the Landmarks accordion...
can_be_modified = mLandmarksInventoryPanel == mCurrentSelectedList;
// ...except "Received" folder
can_be_modified &= !isReceivedFolderSelected();
}
// then ask LLFolderView permissions
LLFolderView* root_folder = mCurrentSelectedList->getRootFolder();
if ("copy" == command_name)
{
return root_folder->canCopy();
}
else if ("collapse" == command_name)
{
return item->isOpen();
}
else if ("expand" == command_name)
{
return !item->isOpen();
}
if (can_be_modified)
{
LLFolderViewModelItemInventory* listenerp = static_cast<LLFolderViewModelItemInventory*>(item->getViewModelItem());
if ("cut" == command_name)
{
can_be_modified = root_folder->canCut();
}
else if ("rename" == command_name)
{
can_be_modified = listenerp ? listenerp->isItemRenameable() : false;
}
else if ("delete" == command_name)
{
can_be_modified = listenerp ? listenerp->isItemRemovable() && !listenerp->isItemInTrash() : false;
}
else if("paste" == command_name)
{
can_be_modified = root_folder->canPaste();
}
else
{
LL_WARNS() << "Unprocessed command has come: " << command_name << LL_ENDL;
}
}
return can_be_modified;
}
void LLLandmarksPanel::onPickPanelExit( LLPanelPickEdit* pick_panel, LLView* owner, const LLSD& params)
{
pick_panel->setVisible(FALSE);
owner->removeChild(pick_panel);
//we need remove observer to avoid processParcelInfo in the future.
LLRemoteParcelInfoProcessor::getInstance()->removeObserver(params["parcel_id"].asUUID(), this);
delete pick_panel;
pick_panel = NULL;
}
bool LLLandmarksPanel::handleDragAndDropToTrash(BOOL drop, EDragAndDropType cargo_type, void* cargo_data , EAcceptance* accept)
{
*accept = ACCEPT_NO;
switch (cargo_type)
{
case DAD_LANDMARK:
case DAD_CATEGORY:
{
bool is_enabled = isActionEnabled("delete");
if (is_enabled) *accept = ACCEPT_YES_MULTI;
if (is_enabled && drop)
{
// don't call onClipboardAction("delete")
// this lead to removing (N * 2 - 1) items if drag N>1 items into trash. EXT-6757
// So, let remove items one by one.
LLInventoryItem* item = static_cast<LLInventoryItem*>(cargo_data);
if (item)
{
LLFolderViewItem* fv_item = mCurrentSelectedList
? mCurrentSelectedList->getItemByID(item->getUUID())
: NULL;
if (fv_item)
{
// is Item Removable checked inside of remove()
fv_item->remove();
}
}
}
}
break;
default:
break;
}
return true;
}
void LLLandmarksPanel::doShowOnMap(LLLandmark* landmark)
{
LLVector3d landmark_global_pos;
if (!landmark->getGlobalPos(landmark_global_pos))
return;
LLFloaterWorldMap* worldmap_instance = LLFloaterWorldMap::getInstance();
if (!landmark_global_pos.isExactlyZero() && worldmap_instance)
{
worldmap_instance->trackLocation(landmark_global_pos);
LLFloaterReg::showInstance("world_map", "center");
}
mShowOnMapBtn->setEnabled(TRUE);
mGearLandmarkMenu->setItemEnabled("show_on_map", TRUE);
}
void LLLandmarksPanel::doProcessParcelInfo(LLLandmark* landmark,
LLFolderViewItem* cur_item,
LLInventoryItem* inv_item,
const LLParcelData& parcel_data)
{
LLPanelPickEdit* panel_pick = LLPanelPickEdit::create();
LLVector3d landmark_global_pos;
landmark->getGlobalPos(landmark_global_pos);
// let's toggle pick panel into panel places
LLPanel* panel_places = NULL;
LLFloaterSidePanelContainer* floaterp = LLFloaterReg::getTypedInstance<LLFloaterSidePanelContainer>("places");
if (floaterp)
{
panel_places = floaterp->findChild<LLPanel>("main_panel");
}
if (!panel_places)
{
llassert(NULL != panel_places);
return;
}
panel_places->addChild(panel_pick);
LLRect paren_rect(panel_places->getRect());
panel_pick->reshape(paren_rect.getWidth(),paren_rect.getHeight(), TRUE);
panel_pick->setRect(paren_rect);
panel_pick->onOpen(LLSD());
LLPickData data;
data.pos_global = landmark_global_pos;
data.name = cur_item->getName();
data.desc = inv_item->getDescription();
data.snapshot_id = parcel_data.snapshot_id;
data.parcel_id = parcel_data.parcel_id;
panel_pick->setPickData(&data);
LLSD params;
params["parcel_id"] = parcel_data.parcel_id;
/* set exit callback to get back onto panel places
in callback we will make cleaning up( delete pick_panel instance,
remove landmark panel from observer list
*/
panel_pick->setExitCallback(boost::bind(&LLLandmarksPanel::onPickPanelExit,this,
panel_pick, panel_places,params));
panel_pick->setSaveCallback(boost::bind(&LLLandmarksPanel::onPickPanelExit,this,
panel_pick, panel_places,params));
panel_pick->setCancelCallback(boost::bind(&LLLandmarksPanel::onPickPanelExit,this,
panel_pick, panel_places,params));
}
void LLLandmarksPanel::doCreatePick(LLLandmark* landmark)
{
LLViewerRegion* region = gAgent.getRegion();
if (!region) return;
LLGlobalVec pos_global;
LLUUID region_id;
landmark->getGlobalPos(pos_global);
landmark->getRegionID(region_id);
LLVector3 region_pos((F32)fmod(pos_global.mdV[VX], (F64)REGION_WIDTH_METERS),
(F32)fmod(pos_global.mdV[VY], (F64)REGION_WIDTH_METERS),
(F32)pos_global.mdV[VZ]);
LLSD body;
std::string url = region->getCapability("RemoteParcelRequest");
if (!url.empty())
{
body["location"] = ll_sd_from_vector3(region_pos);
if (!region_id.isNull())
{
body["region_id"] = region_id;
}
if (!pos_global.isExactlyZero())
{
U64 region_handle = to_region_handle(pos_global);
body["region_handle"] = ll_sd_from_U64(region_handle);
}
LLHTTPClient::post(url, body, new LLRemoteParcelRequestResponder(getObserverHandle()));
}
else
{
LL_WARNS() << "Can't create pick for landmark for region" << region_id
<< ". Region: " << region->getName()
<< " does not support RemoteParcelRequest" << LL_ENDL;
}
}
//////////////////////////////////////////////////////////////////////////
// HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////
static void filter_list(LLPlacesInventoryPanel* inventory_list, const std::string& string)
{
// When search is cleared, restore the old folder state.
if (!inventory_list->getFilterSubString().empty() && string == "")
{
inventory_list->setFilterSubString(LLStringUtil::null);
// Re-open folders that were open before
inventory_list->restoreFolderState();
}
if (inventory_list->getFilterSubString().empty() && string.empty())
{
// current filter and new filter empty, do nothing
return;
}
// save current folder open state if no filter currently applied
if (inventory_list->getFilterSubString().empty())
{
inventory_list->saveFolderState();
}
// Set new filter string
inventory_list->setFilterSubString(string);
}
static bool category_has_descendents(LLPlacesInventoryPanel* inventory_list)
{
LLViewerInventoryCategory* category = gInventory.getCategory(inventory_list->getRootFolderID());
if (category)
{
return category->getDescendentCount() > 0;
}
return false;
}
static void collapse_all_folders(LLFolderView* root_folder)
{
if (!root_folder)
return;
root_folder->setOpenArrangeRecursively(FALSE, LLFolderViewFolder::RECURSE_DOWN);
// The top level folder is invisible, it must be open to
// display its sub-folders.
// <FS:Ansariel> Also collapse top level folders on Firestorm - we don't have accordions (FIRE-3961)
//root_folder->openTopLevelFolders();
root_folder->arrangeAll();
}
static void expand_all_folders(LLFolderView* root_folder)
{
if (!root_folder)
return;
root_folder->setOpenArrangeRecursively(TRUE, LLFolderViewFolder::RECURSE_DOWN);
root_folder->arrangeAll();
}
static bool has_expanded_folders(LLFolderView* root_folder)
{
LLCheckFolderState checker;
root_folder->applyFunctorRecursively(checker);
// We assume that the root folder is always expanded so we enable "collapse_all"
// command when we have at least one more expanded folder.
if (checker.getExpandedFolders() < 2)
{
return false;
}
return true;
}
static bool has_collapsed_folders(LLFolderView* root_folder)
{
LLCheckFolderState checker;
root_folder->applyFunctorRecursively(checker);
if (checker.getCollapsedFolders() < 1)
{
return false;
}
return true;
}
// Displays "Restore Item" context menu entry while hiding
// all other entries or vice versa.
// Sets "Restore Item" enabled state.
void toggle_restore_menu(LLMenuGL *menu, BOOL visible, BOOL enabled)
{
if (!menu) return;
const LLView::child_list_t *list = menu->getChildList();
for (LLView::child_list_t::const_iterator itor = list->begin();
itor != list->end();
++itor)
{
LLView *menu_item = (*itor);
std::string name = menu_item->getName();
if ("restore_item" == name)
{
menu_item->setVisible(visible);
menu_item->setEnabled(enabled);
}
else
{
menu_item->setVisible(!visible);
}
}
}
// EOF
| 30.101036 | 184 | 0.743653 | humbletim |
b80544cba266f8ae7a54e8f4be80e41852b1af37 | 7,254 | cpp | C++ | src/turtlebot_controller.cpp | DevasenaInupakutika/assn2 | e533e0560241c81fa92a25b7058187562aa9fbfc | [
"Apache-2.0"
] | 1 | 2015-03-06T05:33:39.000Z | 2015-03-06T05:33:39.000Z | src/turtlebot_controller.cpp | DevasenaInupakutika/assn2 | e533e0560241c81fa92a25b7058187562aa9fbfc | [
"Apache-2.0"
] | null | null | null | src/turtlebot_controller.cpp | DevasenaInupakutika/assn2 | e533e0560241c81fa92a25b7058187562aa9fbfc | [
"Apache-2.0"
] | null | null | null | #include <ros/ros.h>
#include <math.h>
#include <iostream>
#include "boost/thread/mutex.hpp"
#include <LinearMath/btMatrix3x3.h>
#include <sensor_msgs/LaserScan.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/PoseStamped.h>
#include <visualization_msgs/Marker.h>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
#include <geometry_msgs/PointStamped.h>
using namespace std;
// current robot pose, relative to /odom
tf::StampedTransform robotPose;
// current goal pose
// TODO: clean up these types. why are they different??
// RESPONSE: one of them is a pose and one of them is a transform
// you could replace tf::Stamped<tf::Pose> with StampedPose, which
// I think is just a typedef
tf::Stamped<tf::Pose> goalPose;
// current linear/angular velocity of the robot
// these values are used to send out the cmd_vel
// messages to the robot each iteration
double linear = -0.3;
double angular = 0;
// true if the robot's forward path is blocked
bool pathBlocked = false;
// used to get the robot unstuck
int itcount = 0;
/* Called when receiving a new laser scan message */
void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
// convenience vars
int numPts = msg->ranges.size();
//int centerIdx = numPts / 2;
// check to see if any point blocks the robot
// i.e. is the point within a rectangular window
double robotRadius = 0.16; // meters
double cutoffDist = 1.0; // meters (subtract about 0.08 to get true distance)
double cutoffAngle = atan2(robotRadius, cutoffDist);
bool foundAny = false;
bool blocked = false;
double blockAngle = 0;
// loop through scan range
for (int i = 0; i < numPts; i++) {
double distance = msg->ranges[i]-0.08;
double angle = msg->angle_min + i * msg->angle_increment;
// bounds check
if (distance < msg->range_min || distance > msg->range_max) {
continue;
}
foundAny = true;
// x-coordinate of point
double forward = distance * cos(angle);
if (abs(angle) > cutoffAngle) {
double lCutoff = abs(robotRadius / sin(angle));
if (distance < lCutoff) {
cout << "blocked at angle: " << angle << endl;
blocked = true;
blockAngle = angle;
}
} else if (forward < cutoffDist) {
cout << "forward too small: " << angle << endl;
blocked = true;
blockAngle = angle;
}
}
// TODO: move this to the controller code
// update control appropriately
if (foundAny && blocked) {
linear = 0;
itcount = 0;
pathBlocked = true;
// rotate away from obstacle
if (blockAngle >= 0) angular = -0.5;
else angular = 0.5;
} else if (pathBlocked) {
// once unblocked, try moving forward 8 times
if (itcount < 8) {
// move forward a little bit
itcount++;
linear = -0.3;
angular = 0.0;
} else {
// resume normal control
pathBlocked = false;
}
}
}
/* Called when receiving a new laser scan message */
void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
cout << "got a new goal" << endl;
// update goalPose
tf::poseStampedMsgToTF(*msg, goalPose);
}
int main(int argc, char** argv) {
// initialize ros
ros::init(argc, argv, "turtlebot_controller");
ros::NodeHandle n;
/* subscribe to laser scans */
ros::Subscriber scanSub = n.subscribe("scan", 1, scanCallback);
/* subscribe to rviz goals */
ros::Subscriber goalSub = n.subscribe("goal", 1, goalCallback);
/* publish cmd velocities */
ros::Publisher pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
/* transform listener */
tf::TransformListener listener;
// collect transforms for a while
listener.waitForTransform("/odom", "/base_link", ros::Time(), ros::Duration(1.5));
// set initial goal to be the robot's pose
try {
// lookup current robot pose wrt odom
listener.lookupTransform("/odom", "/base_link", ros::Time(), robotPose);
goalPose.setRotation(robotPose.getRotation());
goalPose.setOrigin(robotPose.getOrigin());
} catch (tf::TransformException ex) {
ROS_ERROR("%s",ex.what());
}
// publish frequency
ros::Rate loop_rate(30);
while (ros::ok()) {
try {
// update robotPose
listener.lookupTransform("/odom", "/base_footprint", ros::Time(0), robotPose);
} catch (tf::TransformException ex) {
ROS_ERROR("%s",ex.what());
}
// check for laser scans
ros::spinOnce();
// Controller, version 0
// Navigates in a series of phases:
// (0) If blocked, get unblocked
// (1) If misaligned, rotate towards goal
// (2) If facing goal, move towards goal
// (3) If at goal position, rotate into final orientation
/* --------------------------------------------------------- */
// convert goal pose to a message type
geometry_msgs::PoseStamped goalPoseMsg;
tf::poseStampedTFToMsg(goalPose, goalPoseMsg);
goalPoseMsg.header.frame_id = "/odom";
goalPoseMsg.header.stamp = ros::Time();
// get goal in base_link frame
geometry_msgs::PoseStamped relativePoseMsg;
listener.transformPose("/base_footprint", goalPoseMsg, relativePoseMsg);
// extract goal pose from the message
tf::Stamped<tf::Pose> relativePose;
tf::poseStampedMsgToTF(relativePoseMsg, relativePose);
// get the RPY and offset of the current goal
// (relative to robot's current position)
double roll, pitch, yaw;
tf::Matrix3x3(relativePose.getRotation()).getRPY(roll, pitch, yaw);
tf::Vector3 offset = relativePose.getOrigin();
// compute the 2-D angle from robot position to goal position
double angle = atan2(relativePose.getOrigin().getY(), relativePose.getOrigin().getX());
// if blocked, appropriate velocities are already set
if (!pathBlocked) {
// far away from goal?
if (sqrt(offset.getX()*offset.getX() + offset.getY()*offset.getY()) > 0.05) {
// not lined up?
if (abs(angle) > 0.3) {
cout << "rotating towards target\n";
if (abs(angle) > 0.05) {
if (angle > 0) {
angular = 1;
} else {
angular = -1;
}
}
linear = 0;
} else {
cout << "moving toward target" << endl;
if (offset.getX() > 0.05) {
linear = -0.3;
} else {
linear = 0.3;
}
// adjust course?
if (abs(angle) > 0.05) {
cout << "adjusting course\n" << endl;
if (angle > 0) {
angular = 0.2;
} else {
angular = -0.2;
}
}
}
} else {
// rotate into place?
if (abs(yaw) > 0.1) {
cout << "yaw into place\n" << endl;
if (yaw > 0) {
angular = 0.8;
} else {
angular = -0.8;
}
} else {
cout << "done!" << endl;
angular = 0;
}
linear = 0;
}
}
/* ---------------------------------------------------- */
// send out a new control message
double x = robotPose.getOrigin().x();
double y = robotPose.getOrigin().y();
double gx = goalPose.getOrigin().x();
double gy = goalPose.getOrigin().y();
cout<< "Robot is at position: "<< "( "<< x << "," << y <<") "<< endl;
cout<< "Goal coordinates are: "<<"( "<< gx << "," << gy <<") "<< endl;
geometry_msgs::Twist vel;
vel.linear.x = linear;
vel.angular.z = angular;
pub.publish(vel);
loop_rate.sleep();
}
return 0;
};
| 28.447059 | 89 | 0.621588 | DevasenaInupakutika |
b80859b2aecabe1fa51dabf8c71180d89f1db61b | 48,944 | cpp | C++ | src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp | berkansasmaz/runtime | 7626c5d8be527d6735eddcdc7c97423211d8f9e9 | [
"MIT"
] | 1 | 2021-11-21T18:25:08.000Z | 2021-11-21T18:25:08.000Z | src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp | berkansasmaz/runtime | 7626c5d8be527d6735eddcdc7c97423211d8f9e9 | [
"MIT"
] | 1 | 2021-11-19T10:42:54.000Z | 2021-11-19T10:42:54.000Z | src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp | berkansasmaz/runtime | 7626c5d8be527d6735eddcdc7c97423211d8f9e9 | [
"MIT"
] | 1 | 2020-01-31T06:16:53.000Z | 2020-01-31T06:16:53.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Derived class from CCeeGen which handles writing out
// the exe. All references to PEWriter pulled out of CCeeGen,
// and moved here
//
//
#include "stdafx.h"
#include <string.h>
#include <limits.h>
#include "corerror.h"
#include <posterror.h>
#include <shlwapi.h>
// The following block contains a template for the default entry point stubs of a COM+
// IL only program. One can emit these stubs (with some fix-ups) and make
// the code supplied the entry point value for the image. The fix-ups will
// in turn cause mscoree.dll to be loaded and the correct entry point to be
// called.
//
// Note: Although these stubs contain x86 specific code, they are used
// for all platforms
//*****************************************************************************
// This stub is designed for a x86 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// jump _CorExeMain();
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE ExeMainX86Template[] =
{
// Jump through IAT to _CorExeMain
0xFF, 0x25, // jmp [iat:_CorDllMain entry]
0x00, 0x00, 0x00, 0x00, // address to replace
};
#define ExeMainX86TemplateSize sizeof(ExeMainX86Template)
#define CorExeMainX86IATOffset 2
//*****************************************************************************
// This stub is designed for a x86 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// jump _CorDllMain
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE DllMainX86Template[] =
{
// Jump through IAT to CorDllMain
0xFF, 0x25, // jmp [iat:_CorDllMain entry]
0x00, 0x00, 0x00, 0x00, // address to replace
};
#define DllMainX86TemplateSize sizeof(DllMainX86Template)
#define CorDllMainX86IATOffset 2
//*****************************************************************************
// This stub is designed for a AMD64 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// mov rax, _CorExeMain();
// jmp [rax]
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE ExeMainAMD64Template[] =
{
// Jump through IAT to _CorExeMain
0x48, 0xA1, // rex.w rex.b mov rax,[following address]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//address of iat:_CorExeMain entry
0xFF, 0xE0 // jmp [rax]
};
#define ExeMainAMD64TemplateSize sizeof(ExeMainAMD64Template)
#define CorExeMainAMD64IATOffset 2
//*****************************************************************************
// This stub is designed for a AMD64 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// mov rax, _CorDllMain();
// jmp [rax]
//
// The code jumps to the imported function _CorDllMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE DllMainAMD64Template[] =
{
// Jump through IAT to CorDllMain
0x48, 0xA1, // rex.w rex.b mov rax,[following address]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//address of iat:_CorDllMain entry
0xFF, 0xE0 // jmp [rax]
};
#define DllMainAMD64TemplateSize sizeof(DllMainAMD64Template)
#define CorDllMainAMD64IATOffset 2
//*****************************************************************************
// This stub is designed for an ia64 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// jump _CorExeMain();
//
// The code jumps to the imported function _CorExeMain using the iat.
// We set the value of gp to point at the iat table entry for _CorExeMain
//*****************************************************************************
const BYTE ExeMainIA64Template[] =
{
// ld8 r9 = [gp] ;;
// ld8 r10 = [r9],8
// nop.i ;;
// ld8 gp = [r9]
// mov b6 = r10
// br.cond.sptk.few b6
//
0x0B, 0x48, 0x00, 0x02, 0x18, 0x10, 0xA0, 0x40,
0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50,
0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
};
#define ExeMainIA64TemplateSize sizeof(ExeMainIA64Template)
//*****************************************************************************
// This stub is designed for an ia64 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// jump _CorDllMain
//
// The code jumps to the imported function _CorExeMain using the iat.
// We set the value of gp to point at the iat table entry for _CorExeMain
//*****************************************************************************
const BYTE DllMainIA64Template[] =
{
// ld8 r9 = [gp] ;;
// ld8 r10 = [r9],8
// nop.i ;;
// ld8 gp = [r9]
// mov b6 = r10
// br.cond.sptk.few b6
//
0x0B, 0x48, 0x00, 0x02, 0x18, 0x10, 0xA0, 0x40,
0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50,
0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
};
#define DllMainIA64TemplateSize sizeof(DllMainIA64Template)
// Get the Symbol entry given the head and a 0-based index
inline IMAGE_SYMBOL* GetSymbolEntry(IMAGE_SYMBOL* pHead, SIZE_T idx)
{
return (IMAGE_SYMBOL*) (((BYTE*) pHead) + IMAGE_SIZEOF_SYMBOL * idx);
}
//*****************************************************************************
// To get a new instance, call CreateNewInstance() or CreateNewInstanceEx() instead of new
//*****************************************************************************
HRESULT CeeFileGenWriter::CreateNewInstance(CCeeGen *pCeeFileGenFrom,
CeeFileGenWriter* & pGenWriter,
DWORD createFlags)
{
return CreateNewInstanceEx(pCeeFileGenFrom, pGenWriter, createFlags);
}
//
// Seed file is used as the base file. The new file data will be "appended" to the seed file
//
HRESULT CeeFileGenWriter::CreateNewInstanceEx(CCeeGen *pCeeFileGenFrom,
CeeFileGenWriter* & pGenWriter,
DWORD createFlags,
LPCWSTR seedFileName)
{
HRESULT hr = S_OK;
ULONG preallocatedOffset = 0;
NewHolder<PEWriter> pPEWriter(NULL);
NewHolder<CeeFileGenWriter> pPrivateGenWriter;
CeeSection *corHeaderSection = NULL;
pPrivateGenWriter = new (nothrow) CeeFileGenWriter;
if (pPrivateGenWriter == NULL)
IfFailGo(E_OUTOFMEMORY);
pPEWriter = new (nothrow) PEWriter;
if (pPEWriter == NULL)
IfFailGo(E_OUTOFMEMORY);
//workaround
//What's really the correct thing to be doing here?
//HRESULT hr = pPEWriter->Init(pCeeFileGenFrom ? pCeeFileGenFrom->getPESectionMan() : NULL);
hr = pPEWriter->Init(NULL, createFlags, seedFileName);
IfFailGo(hr);
//Create the general PEWriter.
pPrivateGenWriter->m_peSectionMan = pPEWriter;
hr = pPrivateGenWriter->Init(); // base class member to finish init
IfFailGo(hr);
if (!seedFileName) // Use base file's preferred base (if present)
{
if (pPEWriter->isPE32())
{
pPrivateGenWriter->setImageBase((DWORD) CEE_IMAGE_BASE_32); // use same default as linker
}
else
{
pPrivateGenWriter->setImageBase64((ULONGLONG) CEE_IMAGE_BASE_64); // use same default as linker
}
}
pPrivateGenWriter->setSubsystem(IMAGE_SUBSYSTEM_WINDOWS_CUI, CEE_IMAGE_SUBSYSTEM_MAJOR_VERSION, CEE_IMAGE_SUBSYSTEM_MINOR_VERSION);
if (pPEWriter->createCorMainStub())
{
hr = pPrivateGenWriter->allocateIAT(); // so the IAT goes out first
IfFailGo(hr);
}
hr = pPrivateGenWriter->allocateCorHeader(); // get COR header near front
IfFailGo(hr);
//If we were passed a CCeeGen at the beginning, copy it's data now.
if (pCeeFileGenFrom) {
pCeeFileGenFrom->cloneInstance((CCeeGen*)pPrivateGenWriter);
}
hr = pPrivateGenWriter->getSectionCreate(".text0", sdExecute, &corHeaderSection);
IfFailGo(hr);
preallocatedOffset = corHeaderSection->dataLen();
// set il RVA to be after the preallocated sections
pPEWriter->setIlRva(preallocatedOffset);
pPEWriter.SuppressRelease();
pPrivateGenWriter.SuppressRelease();
pGenWriter = pPrivateGenWriter;
ErrExit:
return hr;
} // HRESULT CeeFileGenWriter::CreateNewInstance()
CeeFileGenWriter::CeeFileGenWriter() // ctor is protected
{
m_outputFileName = NULL;
m_resourceFileName = NULL;
m_dllSwitch = false;
m_entryPoint = 0;
m_comImageFlags = COMIMAGE_FLAGS_ILONLY; // ceegen PEs don't have native code
m_iatOffset = 0;
m_dllCount = 0;
m_dwManifestSize = 0;
m_dwManifestRVA = NULL;
m_dwStrongNameSize = 0;
m_dwStrongNameRVA = NULL;
m_dwVTableSize = 0;
m_dwVTableRVA = NULL;
m_iDataDlls = NULL;
m_linked = false;
m_fixed = false;
} // CeeFileGenWriter::CeeFileGenWriter()
//*****************************************************************************
// Cleanup
//*****************************************************************************
HRESULT CeeFileGenWriter::Cleanup() // virtual
{
((PEWriter *)m_peSectionMan)->Cleanup(); // call derived cleanup
delete m_peSectionMan;
m_peSectionMan = NULL; // so base class won't delete
delete[] m_outputFileName;
delete[] m_resourceFileName;
if (m_iDataDlls) {
for (int i=0; i < m_dllCount; i++) {
if (m_iDataDlls[i].m_methodName)
delete[] m_iDataDlls[i].m_methodName;
}
delete[] m_iDataDlls;
}
return CCeeGen::Cleanup();
} // HRESULT CeeFileGenWriter::Cleanup()
HRESULT CeeFileGenWriter::link()
{
HRESULT hr = checkForErrors();
if (! SUCCEEDED(hr))
return hr;
// Don't set this if SetManifestEntry was not called - zapper sets the
// resource directory explicitly
if (m_dwManifestSize != 0)
{
m_corHeader->Resources.VirtualAddress = VAL32(m_dwManifestRVA);
m_corHeader->Resources.Size = VAL32(m_dwManifestSize);
}
if (m_dwStrongNameSize != 0)
{
m_corHeader->StrongNameSignature.VirtualAddress = VAL32(m_dwStrongNameRVA);
m_corHeader->StrongNameSignature.Size = VAL32(m_dwStrongNameSize);
}
if (m_dwVTableSize != 0)
{
m_corHeader->VTableFixups.VirtualAddress = VAL32(m_dwVTableRVA);
m_corHeader->VTableFixups.Size = VAL32(m_dwVTableSize);
}
unsigned characteristicsMask = IMAGE_FILE_EXECUTABLE_IMAGE;
if (getPEWriter().isPE32())
characteristicsMask |= IMAGE_FILE_32BIT_MACHINE;
if (!getPEWriter().isPE32())
characteristicsMask |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
getPEWriter().setCharacteristics(characteristicsMask);
m_corHeader->cb = VAL32(sizeof(IMAGE_COR20_HEADER));
m_corHeader->MajorRuntimeVersion = VAL16(COR_VERSION_MAJOR);
m_corHeader->MinorRuntimeVersion = VAL16(COR_VERSION_MINOR);
if (m_dllSwitch)
getPEWriter().setCharacteristics(IMAGE_FILE_DLL);
m_corHeader->Flags = VAL32(m_comImageFlags);
IMAGE_COR20_HEADER_FIELD(*m_corHeader, EntryPointToken) = VAL32(m_entryPoint);
_ASSERTE(TypeFromToken(m_entryPoint) == mdtMethodDef || m_entryPoint == mdTokenNil ||
TypeFromToken(m_entryPoint) == mdtFile);
setDirectoryEntry(getCorHeaderSection(), IMAGE_DIRECTORY_ENTRY_COMHEADER, sizeof(IMAGE_COR20_HEADER), m_corHeaderOffset);
if ((m_comImageFlags & COMIMAGE_FLAGS_IL_LIBRARY) == 0
&& !m_linked)
{
hr = emitExeMain();
if (FAILED(hr))
return hr;
#ifndef TARGET_UNIX
hr = emitResourceSection();
if (FAILED(hr))
return hr;
#endif
}
m_linked = true;
IfFailRet(getPEWriter().link());
return S_OK;
} // HRESULT CeeFileGenWriter::link()
HRESULT CeeFileGenWriter::fixup()
{
HRESULT hr;
m_fixed = true;
if (!m_linked)
IfFailRet(link());
CeeGenTokenMapper *pMapper = getTokenMapper();
// Apply token remaps if there are any.
if (! m_fTokenMapSupported && pMapper != NULL) {
IMetaDataImport *pImport;
hr = pMapper->GetMetaData(&pImport);
_ASSERTE(SUCCEEDED(hr));
hr = MapTokens(pMapper, pImport);
pImport->Release();
}
// remap the entry point if entry point token has been moved
if (pMapper != NULL)
{
mdToken tk = m_entryPoint;
pMapper->HasTokenMoved(tk, tk);
IMAGE_COR20_HEADER_FIELD(*m_corHeader, EntryPointToken) = VAL32(tk);
}
IfFailRet(getPEWriter().fixup(pMapper));
return S_OK;
} // HRESULT CeeFileGenWriter::fixup()
HRESULT CeeFileGenWriter::generateImage(void **ppImage)
{
HRESULT hr = S_OK;
LPCWSTR outputFileName = NULL;
#ifndef TARGET_UNIX
HANDLE hThreadToken = NULL;
// Impersonation is only supported on Win2k and above.
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ | TOKEN_IMPERSONATE, TRUE, &hThreadToken))
{
if (GetLastError() != ERROR_NO_TOKEN)
{
_ASSERTE(!"Failed to get thread token!");
return HRESULT_FROM_GetLastError();
}
}
if (hThreadToken != NULL)
{
if (!RevertToSelf())
{
_ASSERTE(!"Failed to revert impersonation!");
CloseHandle(hThreadToken);
return HRESULT_FROM_GetLastError();
}
}
#endif // !TARGET_UNIX
if (!m_fixed)
IfFailGo(fixup());
outputFileName = m_outputFileName;
if (! outputFileName && ppImage == NULL) {
if (m_comImageFlags & COMIMAGE_FLAGS_IL_LIBRARY)
outputFileName = W("output.ill");
else if (m_dllSwitch)
outputFileName = W("output.dll");
else
outputFileName = W("output.exe");
}
// output file name and ppImage are mutually exclusive
_ASSERTE((NULL == outputFileName && ppImage != NULL) || (outputFileName != NULL && NULL == ppImage));
if (outputFileName != NULL)
IfFailGo(getPEWriter().write(outputFileName));
else
IfFailGo(getPEWriter().write(ppImage));
ErrExit:
#ifndef TARGET_UNIX
if (hThreadToken != NULL)
{
BOOL success = SetThreadToken(NULL, hThreadToken);
CloseHandle(hThreadToken);
if (!success)
{
_ASSERTE(!"Failed to reimpersonate!");
hr = HRESULT_FROM_GetLastError();
}
}
#endif // !TARGET_UNIX
return hr;
} // HRESULT CeeFileGenWriter::generateImage()
HRESULT CeeFileGenWriter::setOutputFileName(_In_ LPWSTR fileName)
{
if (m_outputFileName)
delete[] m_outputFileName;
size_t len = wcslen(fileName) + 1;
m_outputFileName = (LPWSTR)new (nothrow) WCHAR[len];
TESTANDRETURN(m_outputFileName!=NULL, E_OUTOFMEMORY);
wcscpy_s(m_outputFileName, len, fileName);
return S_OK;
} // HRESULT CeeFileGenWriter::setOutputFileName()
HRESULT CeeFileGenWriter::setResourceFileName(_In_ LPWSTR fileName)
{
if (m_resourceFileName)
delete[] m_resourceFileName;
size_t len = wcslen(fileName) + 1;
m_resourceFileName = (LPWSTR)new (nothrow) WCHAR[len];
TESTANDRETURN(m_resourceFileName!=NULL, E_OUTOFMEMORY);
wcscpy_s(m_resourceFileName, len, fileName);
return S_OK;
} // HRESULT CeeFileGenWriter::setResourceFileName()
HRESULT CeeFileGenWriter::setImageBase(size_t imageBase)
{
_ASSERTE(getPEWriter().isPE32());
getPEWriter().setImageBase32((DWORD)imageBase);
return S_OK;
} // HRESULT CeeFileGenWriter::setImageBase()
HRESULT CeeFileGenWriter::setImageBase64(ULONGLONG imageBase)
{
_ASSERTE(!getPEWriter().isPE32());
getPEWriter().setImageBase64(imageBase);
return S_OK;
} // HRESULT CeeFileGenWriter::setImageBase64()
HRESULT CeeFileGenWriter::setFileAlignment(ULONG fileAlignment)
{
getPEWriter().setFileAlignment(fileAlignment);
return S_OK;
} // HRESULT CeeFileGenWriter::setFileAlignment()
HRESULT CeeFileGenWriter::setSubsystem(DWORD subsystem, DWORD major, DWORD minor)
{
getPEWriter().setSubsystem(subsystem, major, minor);
return S_OK;
} // HRESULT CeeFileGenWriter::setSubsystem()
HRESULT CeeFileGenWriter::checkForErrors()
{
if (TypeFromToken(m_entryPoint) == mdtMethodDef) {
if (m_dllSwitch) {
//current spec would need to check the binary sig of the entry point method
}
return S_OK;
}
return S_OK;
} // HRESULT CeeFileGenWriter::checkForErrors()
HRESULT CeeFileGenWriter::getMethodRVA(ULONG codeOffset, ULONG *codeRVA)
{
_ASSERTE(codeRVA);
*codeRVA = getPEWriter().getIlRva() + codeOffset;
return S_OK;
} // HRESULT CeeFileGenWriter::getMethodRVA()
HRESULT CeeFileGenWriter::setDirectoryEntry(CeeSection §ion, ULONG entry, ULONG size, ULONG offset)
{
return getPEWriter().setDirectoryEntry((PEWriterSection*)(§ion.getImpl()), entry, size, offset);
} // HRESULT CeeFileGenWriter::setDirectoryEntry()
HRESULT CeeFileGenWriter::getFileTimeStamp(DWORD *pTimeStamp)
{
return getPEWriter().getFileTimeStamp(pTimeStamp);
} // HRESULT CeeFileGenWriter::getFileTimeStamp()
HRESULT CeeFileGenWriter::setAddrReloc(UCHAR *instrAddr, DWORD value)
{
*(DWORD *)instrAddr = VAL32(value);
return S_OK;
} // HRESULT CeeFileGenWriter::setAddrReloc()
HRESULT CeeFileGenWriter::addAddrReloc(CeeSection &thisSection, UCHAR *instrAddr, DWORD offset, CeeSection *targetSection)
{
if (!targetSection) {
thisSection.addBaseReloc(offset, srRelocHighLow);
} else {
thisSection.addSectReloc(offset, *targetSection, srRelocHighLow);
}
return S_OK;
} // HRESULT CeeFileGenWriter::addAddrReloc()
// create CorExeMain and import directory into .text and the .iat into .data
//
// The structure of the import directory information is as follows, but it is not contiguous in
// section. All the r/o data goes into the .text section and the iat array (which the loader
// updates with the imported addresses) goes into the .data section because WINCE needs it to be writable.
//
// struct IData {
// // one for each DLL, terminating in NULL
// IMAGE_IMPORT_DESCRIPTOR iid[];
// // import lookup table: a set of entries for the methods of each DLL,
// // terminating each set with NULL
// IMAGE_THUNK_DATA32/64 ilt[];
// // hint/name table: an set of entries for each method of each DLL wiht
// // no terminating entry
// struct {
// WORD Hint;
// // null terminated string
// BYTE Name[];
// } ibn; // Hint/name table
// // import address table: a set of entries for the methods of each DLL,
// // terminating each set with NULL
// IMAGE_THUNK_DATA32/64 iat[];
// // one for each DLL, null terminated strings
// BYTE DllName[];
// };
//
// IAT must be first in its section, so have code here to allocate it up front
// prior to knowing other info such as if dll or not. This won't work if have > 1
// function imported, but we'll burn that bridge when we get to it.
HRESULT CeeFileGenWriter::allocateIAT()
{
m_dllCount = 1;
m_iDataDlls = new (nothrow) IDataDllInfo[m_dllCount];
if (m_iDataDlls == NULL) {
return E_OUTOFMEMORY;
}
memset(m_iDataDlls, '\0', m_dllCount * sizeof(IDataDllInfo));
m_iDataDlls[0].m_name = "mscoree.dll";
m_iDataDlls[0].m_numMethods = 1;
m_iDataDlls[0].m_methodName = new (nothrow) const char*[m_iDataDlls[0].m_numMethods];
if (! m_iDataDlls[0].m_methodName) {
return E_OUTOFMEMORY;
}
m_iDataDlls[0].m_methodName[0] = NULL;
int iDataSizeIAT = 0;
for (int i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_iatOffset = iDataSizeIAT;
iDataSizeIAT += (m_iDataDlls[i].m_numMethods + 1)
* (getPEWriter().isPE32() ? sizeof(IMAGE_THUNK_DATA32)
: sizeof(IMAGE_THUNK_DATA64));
}
HRESULT hr = getSectionCreate(".text0", sdExecute, &m_iDataSectionIAT);
TESTANDRETURNHR(hr);
m_iDataOffsetIAT = m_iDataSectionIAT->dataLen();
_ASSERTE(m_iDataOffsetIAT == 0);
m_iDataIAT = m_iDataSectionIAT->getBlock(iDataSizeIAT);
if (! m_iDataIAT) {
return E_OUTOFMEMORY;
}
memset(m_iDataIAT, '\0', iDataSizeIAT);
// Don't set the IAT directory entry yet, since we may not actually end up doing
// an emitExeMain.
return S_OK;
} // HRESULT CeeFileGenWriter::allocateIAT()
HRESULT CeeFileGenWriter::emitExeMain()
{
if (m_dllCount == 0)
return S_OK;
// Note: code later on in this method assumes that mscoree.dll is at
// index m_iDataDlls[0], with CorDllMain or CorExeMain at method[0]
_ASSERTE(getPEWriter().createCorMainStub());
if (m_dllSwitch) {
m_iDataDlls[0].m_methodName[0] = "_CorDllMain";
} else {
m_iDataDlls[0].m_methodName[0] = "_CorExeMain";
}
// IMAGE_IMPORT_DESCRIPTOR on PE/PE+ must be 4-byte or 8-byte aligned
int align = (getPEWriter().isPE32()) ? 4 : 8;
int curOffset = getTextSection().dataLen();
int diff = ((curOffset + align -1) & ~(align-1)) - curOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if (NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
}
int iDataSizeRO = (m_dllCount + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
CeeSection &iDataSectionRO = getTextSection();
int iDataOffsetRO = iDataSectionRO.dataLen();
int iDataSizeIAT = 0;
int i;
for (i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_iltOffset = iDataSizeRO + iDataSizeIAT;
iDataSizeIAT += (m_iDataDlls[i].m_numMethods + 1)
* (getPEWriter().isPE32() ? sizeof(IMAGE_THUNK_DATA32)
: sizeof(IMAGE_THUNK_DATA64));
}
iDataSizeRO += iDataSizeIAT;
for (i=0; i < m_dllCount; i++) {
int delta = (iDataSizeRO + iDataOffsetRO) % 16;
// make sure is on a 16-byte offset
if (delta != 0)
iDataSizeRO += (16 - delta);
_ASSERTE((iDataSizeRO + iDataOffsetRO) % 16 == 0);
m_iDataDlls[i].m_ibnOffset = iDataSizeRO;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++) {
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
iDataSizeRO += sizeof(WORD) + nameLen + nameLen%2;
}
}
for (i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_nameOffset = iDataSizeRO;
iDataSizeRO += (int)(strlen(m_iDataDlls[i].m_name) + 2);
}
char *iDataRO = iDataSectionRO.getBlock(iDataSizeRO);
if (!iDataRO) return E_OUTOFMEMORY;
memset(iDataRO, '\0', iDataSizeRO);
setDirectoryEntry(iDataSectionRO, IMAGE_DIRECTORY_ENTRY_IMPORT, iDataSizeRO, iDataOffsetRO);
IMAGE_IMPORT_DESCRIPTOR *iid = (IMAGE_IMPORT_DESCRIPTOR *)iDataRO;
for (i=0; i < m_dllCount; i++) {
// fill in the import descriptors for each DLL
IMAGE_IMPORT_DESC_FIELD(iid[i], OriginalFirstThunk) = VAL32((ULONG)(m_iDataDlls[i].m_iltOffset + iDataOffsetRO));
iid[i].Name = VAL32(m_iDataDlls[i].m_nameOffset + iDataOffsetRO);
iid[i].FirstThunk = VAL32((ULONG)(m_iDataDlls[i].m_iatOffset + m_iDataOffsetIAT));
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&IMAGE_IMPORT_DESC_FIELD(iid[i], OriginalFirstThunk)) - iDataRO), iDataSectionRO, srRelocAbsolute);
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&iid[i].Name) - iDataRO), iDataSectionRO, srRelocAbsolute);
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&iid[i].FirstThunk) - iDataRO), *m_iDataSectionIAT, srRelocAbsolute);
if (getPEWriter().isPE32())
{
// now fill in the import lookup table for each DLL
IMAGE_THUNK_DATA32 *ilt = (IMAGE_THUNK_DATA32*) (iDataRO + m_iDataDlls[i].m_iltOffset);
IMAGE_THUNK_DATA32 *iat = (IMAGE_THUNK_DATA32*) (m_iDataIAT + m_iDataDlls[i].m_iatOffset);
int ibnOffset = m_iDataDlls[i].m_ibnOffset;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++)
{
ilt[j].u1.AddressOfData = VAL32((ULONG)(ibnOffset + iDataOffsetRO));
iat[j].u1.AddressOfData = VAL32((ULONG)(ibnOffset + iDataOffsetRO));
iDataSectionRO.addSectReloc( (unsigned)(iDataOffsetRO + (char *)(&ilt[j].u1.AddressOfData) - iDataRO),
iDataSectionRO, srRelocAbsolute);
m_iDataSectionIAT->addSectReloc( (unsigned)(m_iDataOffsetIAT + (char *)(&iat[j].u1.AddressOfData) - m_iDataIAT),
iDataSectionRO, srRelocAbsolute);
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
memcpy(iDataRO + ibnOffset + offsetof(IMAGE_IMPORT_BY_NAME, Name),
m_iDataDlls[i].m_methodName[j], nameLen);
ibnOffset += sizeof(WORD) + nameLen + nameLen%2;
}
}
else
{
// now fill in the import lookup table for each DLL
IMAGE_THUNK_DATA64 *ilt = (IMAGE_THUNK_DATA64*) (iDataRO + m_iDataDlls[i].m_iltOffset);
IMAGE_THUNK_DATA64 *iat = (IMAGE_THUNK_DATA64*) (m_iDataIAT + m_iDataDlls[i].m_iatOffset);
int ibnOffset = m_iDataDlls[i].m_ibnOffset;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++)
{
ilt[j].u1.AddressOfData = VAL64((ULONG)(ibnOffset + iDataOffsetRO));
iat[j].u1.AddressOfData = VAL64((ULONG)(ibnOffset + iDataOffsetRO));
iDataSectionRO.addSectReloc( (unsigned)(iDataOffsetRO + (char *)(&ilt[j].u1.AddressOfData) - iDataRO),
iDataSectionRO, srRelocAbsolute);
m_iDataSectionIAT->addSectReloc( (unsigned)(m_iDataOffsetIAT + (char *)(&iat[j].u1.AddressOfData) - m_iDataIAT),
iDataSectionRO, srRelocAbsolute);
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
memcpy(iDataRO + ibnOffset + offsetof(IMAGE_IMPORT_BY_NAME, Name),
m_iDataDlls[i].m_methodName[j], nameLen);
ibnOffset += sizeof(WORD) + nameLen + nameLen%2;
}
}
// now fill in the import lookup table for each DLL
strcpy_s(iDataRO + m_iDataDlls[i].m_nameOffset,
iDataSizeRO - m_iDataDlls[i].m_nameOffset,
m_iDataDlls[i].m_name);
} // end of for loop i < m_dllCount
if (getPEWriter().isI386())
{
// Put the entry point code into the PE file
unsigned entryPointOffset = getTextSection().dataLen();
int iatOffset = (int) (entryPointOffset + (m_dllSwitch ? CorDllMainX86IATOffset : CorExeMainX86IATOffset));
align = 4; // x86 fixups must be 4-byte aligned
// The IAT offset must be aligned because fixup is applied to it.
diff = ((iatOffset + align -1) & ~(align-1)) - iatOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
entryPointOffset += diff;
}
_ASSERTE((getTextSection().dataLen() + (m_dllSwitch ? CorDllMainX86IATOffset : CorExeMainX86IATOffset)) % align == 0);
getPEWriter().setEntryPointTextOffset(entryPointOffset);
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainX86Template));
if(dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainX86Template, sizeof(DllMainX86Template));
//mscoree.dll
setAddrReloc(dllMainBuf+CorDllMainX86IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), dllMainBuf, entryPointOffset+CorDllMainX86IATOffset, m_iDataSectionIAT);
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainX86Template));
if(exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainX86Template, sizeof(ExeMainX86Template));
//mscoree.dll
setAddrReloc(exeMainBuf+CorExeMainX86IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), exeMainBuf, entryPointOffset+CorExeMainX86IATOffset, m_iDataSectionIAT);
}
}
else if (getPEWriter().isAMD64())
{
// Put the entry point code into the PE file
unsigned entryPointOffset = getTextSection().dataLen();
int iatOffset = (int) (entryPointOffset + (m_dllSwitch ? CorDllMainAMD64IATOffset : CorExeMainAMD64IATOffset));
align = 16; // AMD64 fixups must be 8-byte aligned
// The IAT offset must be aligned because fixup is applied to it.
diff = ((iatOffset + align -1) & ~(align-1)) - iatOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
entryPointOffset += diff;
}
_ASSERTE((getTextSection().dataLen() + (m_dllSwitch ? CorDllMainAMD64IATOffset : CorExeMainAMD64IATOffset)) % align == 0);
getPEWriter().setEntryPointTextOffset(entryPointOffset);
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainAMD64Template));
if(dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainAMD64Template, sizeof(DllMainAMD64Template));
//mscoree.dll
setAddrReloc(dllMainBuf+CorDllMainAMD64IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), dllMainBuf, entryPointOffset+CorDllMainAMD64IATOffset, m_iDataSectionIAT);
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainAMD64Template));
if(exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainAMD64Template, sizeof(ExeMainAMD64Template));
//mscoree.dll
setAddrReloc(exeMainBuf+CorExeMainAMD64IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), exeMainBuf, entryPointOffset+CorExeMainAMD64IATOffset, m_iDataSectionIAT);
}
}
else if (getPEWriter().isIA64())
{
// Must have a PE+ PE64 file
//_ASSERTE(!getPEWriter().isPE32());
// Put the entry point code into the PE+ file
curOffset = getTextSection().dataLen();
align = 16; // instructions on ia64 must be 16-byte aligned
// The entry point address be aligned
diff = ((curOffset + align -1) & ~(align-1)) - curOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
}
unsigned entryPointOffset = getTextSection().dataLen();
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainIA64Template));
if (dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainIA64Template, sizeof(DllMainIA64Template));
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainIA64Template));
if (exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainIA64Template, sizeof(ExeMainIA64Template));
}
// Put the entry point function pointer into the PE file
unsigned entryPlabelOffset = getTextSection().dataLen();
getPEWriter().setEntryPointTextOffset(entryPlabelOffset);
UCHAR * entryPtr = (UCHAR*)getTextSection().getBlock(sizeof(ULONGLONG));
UCHAR * gpPtr = (UCHAR*)getTextSection().getBlock(sizeof(ULONGLONG));
memset(entryPtr,0,sizeof(ULONGLONG));
memset(gpPtr,0,sizeof(ULONGLONG));
setAddrReloc(entryPtr, entryPointOffset);
addAddrReloc(getTextSection(), entryPtr, entryPlabelOffset, &getTextSection());
setAddrReloc(gpPtr, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), gpPtr, entryPlabelOffset+8, m_iDataSectionIAT);
}
else
{
_ASSERTE(!"Unknown target machine");
}
// Now set our IAT entry since we're using the IAT
setDirectoryEntry(*m_iDataSectionIAT, IMAGE_DIRECTORY_ENTRY_IAT, iDataSizeIAT, m_iDataOffsetIAT);
return S_OK;
} // HRESULT CeeFileGenWriter::emitExeMain()
#ifndef TARGET_UNIX
// This function reads a resource file and emits it into the generated PE file.
// 1. We can only link resources in obj format. Must convert from .res to .obj
// with CvtRes.exe. See https://github.com/dotnet/runtime/issues/11412.
// 2. Must touch up all COFF relocs from .rsrc$01 (resource header) to .rsrc$02
// (resource raw data)
HRESULT CeeFileGenWriter::emitResourceSection()
{
if (m_resourceFileName == NULL)
return S_OK;
const WCHAR* szResFileName = m_resourceFileName;
// read the resource file and spit it out in the .rsrc section
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hMap = NULL;
IMAGE_FILE_HEADER *hMod = NULL;
HRESULT hr = S_OK;
struct Param
{
HANDLE hFile;
HANDLE hMap;
IMAGE_FILE_HEADER *hMod;
const WCHAR* szResFileName;
CeeFileGenWriter *genWriter;
HRESULT hr;
} param;
param.hFile = hFile;
param.hMap = hMap;
param.hMod = hMod;
param.szResFileName = szResFileName;
param.genWriter = this;
param.hr = S_OK;
PAL_TRY(Param *, pParam, ¶m)
{
SIZE_T cbFileSize;
const BYTE *pbStartOfMappedMem;
IMAGE_SECTION_HEADER *rsrc[2] = { NULL, NULL };
S_SIZE_T cbTotalSizeOfRawData;
char *data = NULL;
SIZE_T cReloc = 0;
IMAGE_RELOCATION *pReloc = NULL;
SIZE_T cSymbol = 0;
IMAGE_SYMBOL *pSymbolTable = NULL;
// create a mapped view of the .res file
pParam->hFile = WszCreateFile(pParam->szResFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (pParam->hFile == INVALID_HANDLE_VALUE)
{
//dbprintf("Resource file %S not found\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Grab the file size for verification checks.
{
DWORD dwFileSizeHigh;
DWORD dwFileSize = SafeGetFileSize(pParam->hFile, &dwFileSizeHigh);
if (dwFileSize == (DWORD)(-1))
{
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
// Since we intend to memory map this file, the size of the file can not need 64 bits to represent!
if (dwFileSizeHigh != 0)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
cbFileSize = static_cast<SIZE_T>(dwFileSize);
}
pParam->hMap = WszCreateFileMapping(pParam->hFile, 0, PAGE_READONLY, 0, 0, NULL);
if (pParam->hMap == NULL)
{
//dbprintf("Invalid .res file: %S\n", szResFileName);
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
pbStartOfMappedMem = reinterpret_cast<const BYTE *>(MapViewOfFile(pParam->hMap, FILE_MAP_READ, 0, 0, 0));
// test failure conditions
if (pbStartOfMappedMem == NULL)
{
//dbprintf("Invalid .res file: %S:Can't get header\n", szResFileName);
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
// Check that the file contains an IMAGE_FILE_HEADER structure.
if (IMAGE_SIZEOF_FILE_HEADER > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
pParam->hMod = (IMAGE_FILE_HEADER*)pbStartOfMappedMem;
if (VAL16(pParam->hMod->SizeOfOptionalHeader) != 0)
{
//dbprintf("Invalid .res file: %S:Illegal optional header\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND); // GetLastError() = 0 since API worked.
goto lDone;
}
// Scan all section headers and grab .rsrc$01 and .rsrc$02
{
// First section is directly after header
SIZE_T cSections = static_cast<SIZE_T>(VAL16(pParam->hMod->NumberOfSections));
SIZE_T cbStartOfSections = IMAGE_SIZEOF_FILE_HEADER;
S_SIZE_T cbEndOfSections(S_SIZE_T(cbStartOfSections) +
(S_SIZE_T(cSections) * S_SIZE_T(IMAGE_SIZEOF_SECTION_HEADER)));
// Check that all sections are within the bounds of the mapped file.
if (cbEndOfSections.IsOverflow() ||
cbEndOfSections.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
{
IMAGE_SECTION_HEADER *pSection =
(IMAGE_SECTION_HEADER *)(pbStartOfMappedMem + cbStartOfSections);
IMAGE_SECTION_HEADER *pSectionEnd = pSection + cSections;
for (; pSection < pSectionEnd; pSection++)
{
if (strcmp(".rsrc$01", (char *)pSection->Name) == 0)
{
rsrc[0] = pSection;
}
else if (strcmp(".rsrc$02", (char *)pSection->Name) == 0)
{
rsrc[1] = pSection;
}
}
}
}
// If we don't have both resources, fail.
if (!rsrc[0] || !rsrc[1])
{
//dbprintf("Invalid .res file: %S: Missing sections .rsrc$01 or .rsrc$02\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Verify the resource data starts and sizes
{
cbTotalSizeOfRawData = S_SIZE_T(0);
for (int i = 0; i < 2; i++)
{
S_SIZE_T cbStartOfResourceData(static_cast<SIZE_T>(VAL32(rsrc[i]->PointerToRawData)));
S_SIZE_T cbSizeOfResourceData(static_cast<SIZE_T>(VAL32(rsrc[i]->SizeOfRawData)));
S_SIZE_T cbEndOfResourceData(cbStartOfResourceData + cbSizeOfResourceData);
if (cbEndOfResourceData.IsOverflow() ||
cbEndOfResourceData.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
cbTotalSizeOfRawData += cbSizeOfResourceData;
}
// Check that the total raw data doesn't overflow.
if (cbTotalSizeOfRawData.IsOverflow() ||
cbTotalSizeOfRawData.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
}
PESection *rsrcSection;
pParam->hr = pParam->genWriter->getPEWriter().getSectionCreate(".rsrc", sdReadOnly, &rsrcSection);
if (FAILED(pParam->hr)) goto lDone;
rsrcSection->directoryEntry(IMAGE_DIRECTORY_ENTRY_RESOURCE);
data = rsrcSection->getBlock(static_cast<unsigned>(cbTotalSizeOfRawData.Value()), 8);
if(data == NULL)
{
pParam->hr = E_OUTOFMEMORY;
goto lDone;
}
// Copy resource header
memcpy(data, (char *)pParam->hMod + VAL32(rsrc[0]->PointerToRawData), VAL32(rsrc[0]->SizeOfRawData));
// Map all the relocs in .rsrc$01 using the reloc and symbol tables in the COFF object.,
cReloc = 0; // Total number of relocs
pReloc = NULL; // Reloc table start
cSymbol = 0; // Total number of symbols
pSymbolTable = NULL; // Symbol table start
{
// Check that the relocations and symbols lie within the resource
cReloc = VAL16(rsrc[0]->NumberOfRelocations);
SIZE_T cbStartOfRelocations = static_cast<SIZE_T>(VAL32(rsrc[0]->PointerToRelocations));
S_SIZE_T cbEndOfRelocations(S_SIZE_T(cbStartOfRelocations) +
(S_SIZE_T(cReloc) * S_SIZE_T(sizeof(IMAGE_RELOCATION))));
// Verify the number of symbols fit into the resource.
cSymbol = static_cast<SIZE_T>(VAL32(pParam->hMod->NumberOfSymbols));
SIZE_T cbStartOfSymbolTable = static_cast<SIZE_T>(VAL32(pParam->hMod->PointerToSymbolTable));
S_SIZE_T cbEndOfSymbolTable(S_SIZE_T(cbStartOfSymbolTable) +
(S_SIZE_T(cSymbol) * S_SIZE_T(IMAGE_SIZEOF_SYMBOL)));
if (cbEndOfRelocations.IsOverflow() ||
cbEndOfRelocations.Value() > cbFileSize ||
cbEndOfSymbolTable.IsOverflow() ||
cbEndOfSymbolTable.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
pReloc = (IMAGE_RELOCATION *)(pbStartOfMappedMem + cbStartOfRelocations);
pSymbolTable = (IMAGE_SYMBOL *)(pbStartOfMappedMem + cbStartOfSymbolTable);
}
_ASSERTE(pReloc != NULL && pSymbolTable != NULL);
for(SIZE_T iReloc = 0; iReloc < cReloc; iReloc++, pReloc++)
{
// Ensure this is a valid reloc
{
S_SIZE_T cbRelocEnd = S_SIZE_T(VAL32(pReloc->VirtualAddress)) + S_SIZE_T(sizeof(DWORD));
if (cbRelocEnd.IsOverflow() ||
cbRelocEnd.Value() > static_cast<SIZE_T>(VAL32(rsrc[0]->SizeOfRawData)))
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
}
// index into symbol table, provides address into $02
DWORD iSymbol = VAL32(pReloc->SymbolTableIndex);
// Make sure the index is in range
if (iSymbol >= cSymbol)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
IMAGE_SYMBOL* pSymbolEntry = GetSymbolEntry(pSymbolTable, iSymbol);
// Ensure the symbol entry is valid for a resource.
if ((pSymbolEntry->StorageClass != IMAGE_SYM_CLASS_STATIC) ||
(VAL16(pSymbolEntry->Type) != IMAGE_SYM_TYPE_NULL) ||
(VAL16(pSymbolEntry->SectionNumber) != 3)) // 3rd section is .rsrc$02
{
//dbprintf("Invalid .res file: %S:Illegal symbol entry\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Ensure that RVA is valid address (inside rsrc[1])
if (VAL32(pSymbolEntry->Value) >= VAL32(rsrc[1]->SizeOfRawData))
{
//dbprintf("Invalid .res file: %S:Illegal rva into .rsrc$02\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
DWORD dwOffsetInRsrc2 = VAL32(pSymbolEntry->Value) + VAL32(rsrc[0]->SizeOfRawData);
// Create reloc
*(DWORD*)(data + VAL32(pReloc->VirtualAddress)) = VAL32(dwOffsetInRsrc2);
rsrcSection->addSectReloc(pReloc->VirtualAddress, rsrcSection, srRelocAbsolute);
}
// Copy $02 (resource raw) data
memcpy(data+VAL32(rsrc[0]->SizeOfRawData),
(char *)pParam->hMod + VAL32(rsrc[1]->PointerToRawData),
VAL32(rsrc[1]->SizeOfRawData));
lDone: ;
}
PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
//dbprintf("Exception occurred manipulating .res file %S\n", szResFileName);
param.hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
}
PAL_ENDTRY
hMod = param.hMod;
hFile = param.hFile;
szResFileName = param.szResFileName;
hr = param.hr;
if (hMod != NULL)
UnmapViewOfFile(hMod);
if (hMap != NULL)
CloseHandle(hMap);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return hr;
} // HRESULT CeeFileGenWriter::emitResourceSection()
#endif // !TARGET_UNIX
HRESULT CeeFileGenWriter::setManifestEntry(ULONG size, ULONG offset)
{
if (offset)
m_dwManifestRVA = offset;
else {
CeeSection TextSection = getTextSection();
getMethodRVA(TextSection.dataLen() - size, &m_dwManifestRVA);
}
m_dwManifestSize = size;
return S_OK;
} // HRESULT CeeFileGenWriter::setManifestEntry()
HRESULT CeeFileGenWriter::setStrongNameEntry(ULONG size, ULONG offset)
{
m_dwStrongNameRVA = offset;
m_dwStrongNameSize = size;
return S_OK;
} // HRESULT CeeFileGenWriter::setStrongNameEntry()
HRESULT CeeFileGenWriter::setVTableEntry64(ULONG size, void* ptr)
{
if (ptr && size)
{
void * pv;
CeeSection TextSection = getTextSection();
// make it DWORD-aligned
ULONG L = TextSection.dataLen();
if((L &= ((ULONG)sizeof(DWORD)-1)))
{
L = (ULONG)sizeof(DWORD) - L;
if((pv = TextSection.getBlock(L)))
memset(pv,0,L);
else
return E_OUTOFMEMORY;
}
getMethodRVA(TextSection.dataLen(), &m_dwVTableRVA);
if((pv = TextSection.getBlock(size)))
{
memcpy(pv,ptr,size);
}
else
return E_OUTOFMEMORY;
m_dwVTableSize = size;
}
return S_OK;
} // HRESULT CeeFileGenWriter::setVTableEntry()
HRESULT CeeFileGenWriter::setVTableEntry(ULONG size, ULONG offset)
{
return setVTableEntry64(size,(void*)(ULONG_PTR)offset);
} // HRESULT CeeFileGenWriter::setVTableEntry()
HRESULT CeeFileGenWriter::computeSectionOffset(CeeSection §ion, _In_ char *ptr,
unsigned *offset)
{
*offset = section.computeOffset(ptr);
return S_OK;
} // HRESULT CeeFileGenWriter::computeSectionOffset()
HRESULT CeeFileGenWriter::computeOffset(_In_ char *ptr,
CeeSection **pSection, unsigned *offset)
{
TESTANDRETURNPOINTER(pSection);
CeeSection **s = m_sections;
CeeSection **sEnd = s + m_numSections;
while (s < sEnd)
{
if ((*s)->containsPointer(ptr))
{
*pSection = *s;
*offset = (*s)->computeOffset(ptr);
return S_OK;
}
s++;
}
return E_FAIL;
} // HRESULT CeeFileGenWriter::computeOffset()
HRESULT CeeFileGenWriter::getCorHeader(IMAGE_COR20_HEADER **ppHeader)
{
*ppHeader = m_corHeader;
return S_OK;
} // HRESULT CeeFileGenWriter::getCorHeader()
| 36.744745 | 147 | 0.616541 | berkansasmaz |
b80c8bd5dca485d9744f1e7de8264d7e87f3987a | 13,797 | cpp | C++ | test/core/crypto/crypto_store/crypto_store_test.cpp | Harrm/kagome | 22932bbbbf2f09712ca81b9e6256492f84cf2a46 | [
"Apache-2.0"
] | null | null | null | test/core/crypto/crypto_store/crypto_store_test.cpp | Harrm/kagome | 22932bbbbf2f09712ca81b9e6256492f84cf2a46 | [
"Apache-2.0"
] | null | null | null | test/core/crypto/crypto_store/crypto_store_test.cpp | Harrm/kagome | 22932bbbbf2f09712ca81b9e6256492f84cf2a46 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "crypto/crypto_store/crypto_store_impl.hpp"
#include <gmock/gmock.h>
#include "crypto/bip39/impl/bip39_provider_impl.hpp"
#include "crypto/ed25519/ed25519_provider_impl.hpp"
#include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp"
#include "crypto/random_generator/boost_generator.hpp"
#include "crypto/sr25519/sr25519_provider_impl.hpp"
#include "testutil/outcome.hpp"
#include "testutil/storage/base_fs_test.hpp"
using kagome::common::Blob;
using kagome::common::Buffer;
using kagome::crypto::Bip39Provider;
using kagome::crypto::Bip39ProviderImpl;
using kagome::crypto::BoostRandomGenerator;
using kagome::crypto::CryptoStore;
using kagome::crypto::CryptoStoreError;
using kagome::crypto::CryptoStoreImpl;
using kagome::crypto::Ed25519Keypair;
using kagome::crypto::Ed25519PrivateKey;
using kagome::crypto::Ed25519Provider;
using kagome::crypto::Ed25519ProviderImpl;
using kagome::crypto::Ed25519PublicKey;
using kagome::crypto::Ed25519Suite;
using kagome::crypto::KeyTypeId;
using kagome::crypto::KnownKeyTypeId;
using kagome::crypto::Pbkdf2Provider;
using kagome::crypto::Pbkdf2ProviderImpl;
using kagome::crypto::Sr25519Keypair;
using kagome::crypto::Sr25519Provider;
using kagome::crypto::Sr25519ProviderImpl;
using kagome::crypto::Sr25519PublicKey;
using kagome::crypto::Sr25519SecretKey;
using kagome::crypto::Sr25519Suite;
static CryptoStoreImpl::Path crypto_store_test_directory =
boost::filesystem::temp_directory_path() / "crypto_store_test";
struct CryptoStoreTest : public test::BaseFS_Test {
CryptoStoreTest() : BaseFS_Test(crypto_store_test_directory) {}
void SetUp() override {
auto csprng = std::make_shared<BoostRandomGenerator>();
auto ed25519_provider = std::make_shared<Ed25519ProviderImpl>(csprng);
auto sr25519_provider = std::make_shared<Sr25519ProviderImpl>(csprng);
auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>();
bip39_provider =
std::make_shared<Bip39ProviderImpl>(std::move(pbkdf2_provider));
crypto_store = std::make_shared<CryptoStoreImpl>(
std::make_shared<Ed25519Suite>(std::move(ed25519_provider)),
std::make_shared<Sr25519Suite>(std::move(sr25519_provider)),
bip39_provider,
kagome::crypto::KeyFileStorage::createAt(crypto_store_test_directory)
.value());
mnemonic =
"ozone drill grab fiber curtain grace pudding thank cruise elder eight "
"picnic";
EXPECT_OUTCOME_TRUE(e, Buffer::fromHex("9e885d952ad362caeb4efe34a8e91bd2"));
entropy = std::move(e);
EXPECT_OUTCOME_TRUE(s,
Blob<32>::fromHex("a4681403ba5b6a3f3bd0b0604ce439a78244"
"c7d43b127ec35cd8325602dd47fd"));
seed = s;
key_type = KnownKeyTypeId::KEY_TYPE_BABE;
EXPECT_OUTCOME_TRUE(
ed_publ,
Ed25519PublicKey::fromHex("3e765f2bde3daadd443097b3145abf1f71f99f0aa946"
"960990fe02aa26b7fc72"));
EXPECT_OUTCOME_TRUE(
ed_priv,
Ed25519PrivateKey::fromHex("a4681403ba5b6a3f3bd0b0604ce439a78244c7d43b1"
"27ec35cd8325602dd47fd"));
ed_pair = {ed_priv, ed_publ};
EXPECT_OUTCOME_TRUE(
sr_publ,
Sr25519PublicKey::fromHex("56a03c8afc0e7a3a8b1d53bcc875ba5b6364754f9045"
"16009b57ef3adf96f61f"));
EXPECT_OUTCOME_TRUE(
sr_secr,
Sr25519SecretKey::fromHex(
"ec96cb0816b67b045baae21841952a61ecb0612a109293e10c5453b950659c0a8b"
"35b6d6196f33169334e36a05d624d9996d07243f9f71e638e3bc29a5330ec9"));
sr_pair = {sr_secr, sr_publ};
}
bool isStoredOnDisk(KeyTypeId kt, const Blob<32> &public_key) {
auto file_name = kagome::crypto::decodeKeyTypeId(kt) + public_key.toHex();
auto file_path = crypto_store_test_directory / file_name;
return boost::filesystem::exists(file_path);
}
std::shared_ptr<Bip39Provider> bip39_provider;
std::shared_ptr<CryptoStoreImpl> crypto_store;
std::string mnemonic;
Buffer entropy;
Blob<32> seed;
KeyTypeId key_type;
Ed25519Keypair ed_pair;
Sr25519Keypair sr_pair;
};
/**
* @given cryptostore instance, type, mnemonic and predefined key pair
* @when generateEd25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairMnemonicSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateEd25519Keypair(key_type, mnemonic));
ASSERT_EQ(pair, ed_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, mnemonic and predefined key pair
* @when generateSr25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairMnemonicSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateSr25519Keypair(key_type, mnemonic));
ASSERT_EQ(pair, sr_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, seed and predefined key pair
* @when generateEd25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairSeedSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
auto pair = crypto_store->generateEd25519Keypair(key_type, seed);
ASSERT_EQ(pair, ed_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, seed and predefined key pair
* @when generateSr25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and key generated pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairSeedSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findSr25519Keypair(key_type, sr_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
auto &&pair = crypto_store->generateSr25519Keypair(key_type, seed);
ASSERT_EQ(pair, sr_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call generateEd25519KeypairOnDisk(key_type)
* @then a new ed25519 key pair is generated and stored on disk
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairStoreSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateEd25519KeypairOnDisk(key_type));
// check that created pair is contained in the storage on disk
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// stored on disk
ASSERT_TRUE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call generateSr25519KeypairOnDisk(key_type)
* @then a new ed25519 key pair is generated and stored on disk
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairStoreSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateSr25519KeypairOnDisk(key_type));
// check that created pair is contained in the storage on disk
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// stored on disk
ASSERT_TRUE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call getEd25519PublicKeys
* @then collection of all ed25519 public keys of provided type is returned
*/
TEST_F(CryptoStoreTest, getEd25519PublicKeysSuccess) {
EXPECT_OUTCOME_TRUE(pair1,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_TRUE(pair2,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair3,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_LP2P));
EXPECT_OUTCOME_SUCCESS(pair4,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair5,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_ACCO));
std::set<Ed25519PublicKey> ed_babe_keys_set = {pair1.public_key,
pair2.public_key};
std::vector<Ed25519PublicKey> ed_babe_keys(ed_babe_keys_set.begin(),
ed_babe_keys_set.end());
auto keys =
crypto_store->getEd25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE).value();
ASSERT_THAT(keys, testing::UnorderedElementsAreArray(ed_babe_keys));
}
/**
* @given cryptostore instance, and key type
* @when call getSr25519PublicKeys
* @then collection of all sr25519 public keys of provided type is returned
*/
TEST_F(CryptoStoreTest, getSr25519PublicKeysSuccess) {
EXPECT_OUTCOME_TRUE(pair1,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_TRUE(pair2,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair3,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_LP2P));
EXPECT_OUTCOME_SUCCESS(pair4,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair5,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_ACCO));
std::set<Sr25519PublicKey> sr_babe_keys_set = {pair1.public_key,
pair2.public_key};
std::vector<Sr25519PublicKey> sr_babe_keys(sr_babe_keys_set.begin(),
sr_babe_keys_set.end());
auto keys =
crypto_store->getSr25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE).value();
ASSERT_THAT(keys, testing::UnorderedElementsAreArray(sr_babe_keys));
}
/**
* @given an empty crypto storage
* @when having inserted keys into it
* @then session keys are initialized with inserted keys of the corresponding
* types
*/
TEST_F(CryptoStoreTest, SessionKeys) {
// GIVEN
ASSERT_FALSE(crypto_store->getGrandpaKeypair());
ASSERT_FALSE(crypto_store->getBabeKeypair());
ASSERT_FALSE(crypto_store->getLibp2pKeypair());
// WHEN
EXPECT_OUTCOME_TRUE(
pair1,
crypto_store->generateSr25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_BABE))
EXPECT_OUTCOME_TRUE(
pair2,
crypto_store->generateEd25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_GRAN))
EXPECT_OUTCOME_TRUE(
pair3,
crypto_store->generateEd25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_LP2P))
// THEN
ASSERT_TRUE(crypto_store->getGrandpaKeypair());
ASSERT_EQ(crypto_store->getGrandpaKeypair().value(), pair2);
ASSERT_TRUE(crypto_store->getBabeKeypair());
ASSERT_EQ(crypto_store->getBabeKeypair().value(), pair1);
ASSERT_TRUE(crypto_store->getLibp2pKeypair());
ASSERT_THAT(pair3.secret_key,
testing::ElementsAreArray(
crypto_store->getLibp2pKeypair().value().privateKey.data));
}
/**
* Currently incompatible with subkey because subkey doesn't append key type to
* filename
*/
TEST(CryptoStoreCompatibilityTest, DISABLED_SubkeyCompat) {
auto csprng = std::make_shared<BoostRandomGenerator>();
auto ed25519_provider = std::make_shared<Ed25519ProviderImpl>(csprng);
auto sr25519_provider = std::make_shared<Sr25519ProviderImpl>(csprng);
auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>();
auto bip39_provider =
std::make_shared<Bip39ProviderImpl>(std::move(pbkdf2_provider));
auto keystore_path = boost::filesystem::path(__FILE__).parent_path()
/ "subkey_keys" / "keystore";
auto crypto_store = std::make_shared<CryptoStoreImpl>(
std::make_shared<Ed25519Suite>(std::move(ed25519_provider)),
std::make_shared<Sr25519Suite>(std::move(sr25519_provider)),
bip39_provider,
kagome::crypto::KeyFileStorage::createAt(keystore_path).value());
EXPECT_OUTCOME_TRUE(
keys, crypto_store->getEd25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE));
ASSERT_EQ(keys.size(), 1);
}
| 38.431755 | 80 | 0.718272 | Harrm |
b80d3c82f849ab216721d0f6d7f6841f90a1f9a2 | 1,162 | hpp | C++ | dylibwrap/DylibWrap.hpp | churuxu/codesnippets | 9d01c53a5bd7be29168e3c8bfb27ebacc5164f03 | [
"MIT"
] | 4 | 2018-11-05T03:21:02.000Z | 2021-09-25T15:33:52.000Z | dylibwrap/DylibWrap.hpp | churuxu/codesnippets | 9d01c53a5bd7be29168e3c8bfb27ebacc5164f03 | [
"MIT"
] | null | null | null | dylibwrap/DylibWrap.hpp | churuxu/codesnippets | 9d01c53a5bd7be29168e3c8bfb27ebacc5164f03 | [
"MIT"
] | 2 | 2021-01-28T08:14:07.000Z | 2021-09-25T15:33:54.000Z | #pragma once
/**
用于动态加载dll/so的包装类
用法示例:
class User32DLL {
public:
DYLIB_LOAD(User32DLL, "user32");
DYLIB_IMPORT(MessageBoxA);
DYLIB_IMPORT(MessageBoxW);
};
User32DLL user32;
user32.MessageBoxA(NULL, "Hello World", "test", MB_OK);
*/
#include <stdexcept>
#include <string>
#ifdef _WIN32
#include <windows.h>
static void _DylibLoad(const char* name, void** lib, int size) {
HMODULE mod = LoadLibraryA(name);
if (!mod) {
std::string msg = "can not load library ";
msg + name;
throw std::runtime_error(msg);
}
for (int i = 0; i < size; i += 2) {
const char* name = (const char*)(lib[i]);
void* func = GetProcAddress(mod, name);
if (!func) {
std::string msg = "no function names ";
msg + name;
throw std::runtime_error(msg);
}
else {
lib[i + 1] = func;
}
}
}
#else
#error "current not support"
#endif
#define _DYLIB_NAME_CAT(a,b) a##b
/** 声明一个导入类的构造函数 */
#define DYLIB_LOAD(cls, name) \
cls() {\
_DylibLoad(name, (void**)this, sizeof(cls) / sizeof(void*));\
}
/** 声明一个导入函数 */
#define DYLIB_IMPORT(func) \
const char* _DYLIB_NAME_CAT(name_of_,func) = #func;\
decltype(::func)* func = NULL;
| 15.090909 | 65 | 0.636833 | churuxu |
b80f78c2790db3e08720b94e7233247c1f045b58 | 7,045 | cc | C++ | third_party/blink/renderer/core/paint/cull_rect_updater_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/paint/cull_rect_updater_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/core/paint/cull_rect_updater_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/cull_rect_updater.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
namespace blink {
class CullRectUpdaterTest : public RenderingTest {
protected:
void SetUp() override {
EnableCompositing();
RenderingTest::SetUp();
}
CullRect GetCullRect(const char* id) {
return GetLayoutObjectByElementId(id)->FirstFragment().GetCullRect();
}
CullRect GetContentsCullRect(const char* id) {
return GetLayoutObjectByElementId(id)
->FirstFragment()
.GetContentsCullRect();
}
};
// TODO(wangxianzhu): Move other cull rect tests from PaintLayerPainterTest
// into this file.
CullRect GetCullRect(const PaintLayer& layer) {
return layer.GetLayoutObject().FirstFragment().GetCullRect();
}
TEST_F(CullRectUpdaterTest, FixedPositionUnderClipPath) {
GetDocument().View()->Resize(800, 600);
SetBodyInnerHTML(R"HTML(
<div style="height: 100vh"></div>
<div style="width: 100px; height: 100px; clip-path: inset(0 0 0 0)">
<div id="fixed" style="position: fixed; top: 0; left: 0; width: 1000px;
height: 1000px"></div>
</div>
)HTML");
EXPECT_EQ(gfx::Rect(0, 0, 800, 600), GetCullRect("fixed").Rect());
GetDocument().GetFrame()->DomWindow()->scrollTo(0, 1000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 800, 600), GetCullRect("fixed").Rect());
GetDocument().View()->Resize(800, 1000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 800, 1000), GetCullRect("fixed").Rect());
}
TEST_F(CullRectUpdaterTest, FixedPositionUnderClipPathWillChangeTransform) {
GetDocument().View()->Resize(800, 600);
SetBodyInnerHTML(R"HTML(
<div style="height: 100vh"></div>
<div style="width: 100px; height: 100px; clip-path: inset(0 0 0 0)">
<div id="fixed" style="position: fixed; top: 0; left: 0; width: 1000px;
height: 1000px; will-change: transform"></div>
</div>
)HTML");
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 8600), GetCullRect("fixed").Rect());
GetDocument().GetFrame()->DomWindow()->scrollTo(0, 1000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 8600), GetCullRect("fixed").Rect());
GetDocument().View()->Resize(800, 2000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 10000), GetCullRect("fixed").Rect());
}
TEST_F(CullRectUpdaterTest, AbsolutePositionUnderNonContainingStackingContext) {
GetDocument().GetSettings()->SetPreferCompositingToLCDTextEnabled(false);
SetBodyInnerHTML(R"HTML(
<div id="scroller" style="width: 200px; height: 200px; overflow: auto;
position: relative">
<div style="height: 0; overflow: hidden; opacity: 0.5; margin: 250px">
<div id="absolute"
style="width: 100px; height: 100px; position: absolute;
background: green"></div>
</div>
</div>
)HTML");
EXPECT_EQ(gfx::Rect(0, 0, 200, 200), GetCullRect("absolute").Rect());
GetDocument().getElementById("scroller")->scrollTo(200, 200);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(RuntimeEnabledFeatures::LayoutNGEnabled()
? gfx::Rect(200, 200, 200, 200)
: gfx::Rect(150, 200, 200, 200),
GetCullRect("absolute").Rect());
}
TEST_F(CullRectUpdaterTest, StackedChildOfNonStackingContextScroller) {
SetBodyInnerHTML(R"HTML(
<div id="scroller" style="width: 200px; height: 200px; overflow: auto;
background: white">
<div id="child" style="height: 7000px; position: relative"></div>
</div>
)HTML");
auto* scroller = GetDocument().getElementById("scroller");
EXPECT_EQ(gfx::Rect(0, 0, 200, 4200), GetContentsCullRect("scroller").Rect());
EXPECT_EQ(gfx::Rect(0, 0, 200, 4200), GetCullRect("child").Rect());
for (int i = 1000; i < 7000; i += 1000) {
scroller->scrollTo(0, i);
UpdateAllLifecyclePhasesForTest();
}
// When scrolled to 3800, the cull rect covers the whole scrolling contents.
// Then we use this full cull rect on further scroll to avoid repaint.
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetContentsCullRect("scroller").Rect());
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetCullRect("child").Rect());
// The full cull rect still applies when the scroller scrolls to the top.
scroller->scrollTo(0, 0);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetContentsCullRect("scroller").Rect());
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetCullRect("child").Rect());
// When child needs repaint, it will recalculate its cull rect.
GetPaintLayerByElementId("child")->SetNeedsRepaint();
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetContentsCullRect("scroller").Rect());
EXPECT_EQ(gfx::Rect(0, 0, 200, 4200), GetCullRect("child").Rect());
// Then scroll to the bottom, child should recalculate it cull rect again.
scroller->scrollTo(0, 7000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 200, 7000), GetContentsCullRect("scroller").Rect());
EXPECT_EQ(gfx::Rect(0, 2800, 200, 4200), GetCullRect("child").Rect());
}
TEST_F(CullRectUpdaterTest, SVGForeignObject) {
GetDocument().GetSettings()->SetPreferCompositingToLCDTextEnabled(false);
SetBodyInnerHTML(R"HTML(
<div id="scroller" style="width: 100px; height: 100px; overflow: scroll">
<svg id="svg" style="width: 100px; height: 4000px">
<foreignObject id="foreign" style="width: 500px; height: 1000px">
<div id="child" style="position: relative">Child</div>
</foreignObject>
</svg>
</div>
)HTML");
auto* child = GetPaintLayerByElementId("child");
auto* foreign = GetPaintLayerByElementId("foreign");
auto* svg = GetPaintLayerByElementId("svg");
EXPECT_FALSE(child->NeedsCullRectUpdate());
EXPECT_FALSE(foreign->DescendantNeedsCullRectUpdate());
EXPECT_FALSE(svg->DescendantNeedsCullRectUpdate());
GetDocument().getElementById("scroller")->scrollTo(0, 500);
UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(child->NeedsCullRectUpdate());
EXPECT_FALSE(foreign->DescendantNeedsCullRectUpdate());
EXPECT_FALSE(svg->DescendantNeedsCullRectUpdate());
child->SetNeedsCullRectUpdate();
EXPECT_TRUE(child->NeedsCullRectUpdate());
EXPECT_TRUE(foreign->DescendantNeedsCullRectUpdate());
EXPECT_TRUE(svg->DescendantNeedsCullRectUpdate());
UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(child->NeedsCullRectUpdate());
EXPECT_FALSE(foreign->DescendantNeedsCullRectUpdate());
EXPECT_FALSE(svg->DescendantNeedsCullRectUpdate());
}
} // namespace blink
| 38.708791 | 80 | 0.694961 | chromium |
b810eeff62ded4e90aa3ff240516d4c2003fa9f1 | 55,677 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/diffeditor/differ.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/diffeditor/differ.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/diffeditor/differ.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
/*
The main algorithm "diffMyers()" is based on "An O(ND) Difference Algorithm
and Its Variations" by Eugene W. Myers: http://www.xmailserver.org/diff2.pdf
Preprocessing and postprocessing functions inspired by "Diff Strategies"
publication by Neil Fraser: http://neil.fraser.name/writing/diff/
*/
#include "differ.h"
#include <QList>
#include <QRegularExpression>
#include <QStringList>
#include <QMap>
#include <QPair>
#include <QCoreApplication>
#include <QFutureInterfaceBase>
namespace DiffEditor {
static int commonPrefix(const QString &text1, const QString &text2)
{
int i = 0;
const int text1Count = text1.count();
const int text2Count = text2.count();
const int maxCount = qMin(text1Count, text2Count);
while (i < maxCount) {
if (text1.at(i) != text2.at(i))
break;
i++;
}
return i;
}
static int commonSuffix(const QString &text1, const QString &text2)
{
int i = 0;
const int text1Count = text1.count();
const int text2Count = text2.count();
const int maxCount = qMin(text1Count, text2Count);
while (i < maxCount) {
if (text1.at(text1Count - i - 1) != text2.at(text2Count - i - 1))
break;
i++;
}
return i;
}
static int commonOverlap(const QString &text1, const QString &text2)
{
int i = 0;
const int text1Count = text1.count();
const int text2Count = text2.count();
const int maxCount = qMin(text1Count, text2Count);
while (i < maxCount) {
if (text1.midRef(text1Count - maxCount + i) == text2.leftRef(maxCount - i))
return maxCount - i;
i++;
}
return 0;
}
static QList<Diff> decode(const QList<Diff> &diffList, const QStringList &lines)
{
QList<Diff> newDiffList;
newDiffList.reserve(diffList.count());
for (Diff diff : diffList) {
QString text;
for (QChar c : diff.text) {
const int idx = static_cast<ushort>(c.unicode());
text += lines.value(idx);
}
diff.text = text;
newDiffList.append(diff);
}
return newDiffList;
}
static QList<Diff> squashEqualities(const QList<Diff> &diffList)
{
if (diffList.count() < 3) // we need at least 3 items
return diffList;
QList<Diff> newDiffList;
Diff prevDiff = diffList.at(0);
Diff thisDiff = diffList.at(1);
Diff nextDiff = diffList.at(2);
int i = 2;
while (i < diffList.count()) {
if (prevDiff.command == Diff::Equal
&& nextDiff.command == Diff::Equal) {
if (thisDiff.text.endsWith(prevDiff.text)) {
thisDiff.text = prevDiff.text
+ thisDiff.text.left(thisDiff.text.count()
- prevDiff.text.count());
nextDiff.text = prevDiff.text + nextDiff.text;
} else if (thisDiff.text.startsWith(nextDiff.text)) {
prevDiff.text += nextDiff.text;
thisDiff.text = thisDiff.text.mid(nextDiff.text.count())
+ nextDiff.text;
i++;
if (i < diffList.count())
nextDiff = diffList.at(i);
newDiffList.append(prevDiff);
} else {
newDiffList.append(prevDiff);
}
} else {
newDiffList.append(prevDiff);
}
prevDiff = thisDiff;
thisDiff = nextDiff;
i++;
if (i < diffList.count())
nextDiff = diffList.at(i);
}
newDiffList.append(prevDiff);
if (i == diffList.count())
newDiffList.append(thisDiff);
return newDiffList;
}
static QList<Diff> cleanupOverlaps(const QList<Diff> &diffList)
{
// Find overlaps between deletions and insetions.
// The "diffList" already contains at most one deletion and
// one insertion between two equalities, in this order.
// Eliminate overlaps, e.g.:
// DEL(ABCXXXX), INS(XXXXDEF) -> DEL(ABC), EQ(XXXX), INS(DEF)
// DEL(XXXXABC), INS(DEFXXXX) -> INS(DEF), EQ(XXXX), DEL(ABC)
QList<Diff> newDiffList;
int i = 0;
while (i < diffList.count()) {
Diff thisDiff = diffList.at(i);
Diff nextDiff = i < diffList.count() - 1
? diffList.at(i + 1)
: Diff(Diff::Equal, QString());
if (thisDiff.command == Diff::Delete
&& nextDiff.command == Diff::Insert) {
const int delInsOverlap = commonOverlap(thisDiff.text, nextDiff.text);
const int insDelOverlap = commonOverlap(nextDiff.text, thisDiff.text);
if (delInsOverlap >= insDelOverlap) {
if (delInsOverlap > thisDiff.text.count() / 2
|| delInsOverlap > nextDiff.text.count() / 2) {
thisDiff.text = thisDiff.text.left(thisDiff.text.count() - delInsOverlap);
const Diff equality(Diff::Equal, nextDiff.text.left(delInsOverlap));
nextDiff.text = nextDiff.text.mid(delInsOverlap);
newDiffList.append(thisDiff);
newDiffList.append(equality);
newDiffList.append(nextDiff);
} else {
newDiffList.append(thisDiff);
newDiffList.append(nextDiff);
}
} else {
if (insDelOverlap > thisDiff.text.count() / 2
|| insDelOverlap > nextDiff.text.count() / 2) {
nextDiff.text = nextDiff.text.left(nextDiff.text.count() - insDelOverlap);
const Diff equality(Diff::Equal, thisDiff.text.left(insDelOverlap));
thisDiff.text = thisDiff.text.mid(insDelOverlap);
newDiffList.append(nextDiff);
newDiffList.append(equality);
newDiffList.append(thisDiff);
} else {
newDiffList.append(thisDiff);
newDiffList.append(nextDiff);
}
}
i += 2;
} else {
newDiffList.append(thisDiff);
i++;
}
}
return newDiffList;
}
static int cleanupSemanticsScore(const QString &text1, const QString &text2)
{
const QRegularExpression blankLineEnd("\\n\\r?\\n$");
const QRegularExpression blankLineStart("^\\r?\\n\\r?\\n");
const QRegularExpression sentenceEnd("\\. $");
if (!text1.count() || !text2.count()) // Edges
return 6;
const QChar char1 = text1[text1.count() - 1];
const QChar char2 = text2[0];
const bool nonAlphaNumeric1 = !char1.isLetterOrNumber();
const bool nonAlphaNumeric2 = !char2.isLetterOrNumber();
const bool whitespace1 = nonAlphaNumeric1 && char1.isSpace();
const bool whitespace2 = nonAlphaNumeric2 && char2.isSpace();
const bool lineBreak1 = whitespace1 && char1.category() == QChar::Other_Control;
const bool lineBreak2 = whitespace2 && char2.category() == QChar::Other_Control;
const bool blankLine1 = lineBreak1 && blankLineEnd.match(text1).hasMatch();
const bool blankLine2 = lineBreak2 && blankLineStart.match(text2).hasMatch();
if (blankLine1 || blankLine2) // Blank lines
return 5;
if (lineBreak1 || lineBreak2) // Line breaks
return 4;
if (sentenceEnd.match(text1).hasMatch()) // End of sentence
return 3;
if (whitespace1 || whitespace2) // Whitespaces
return 2;
if (nonAlphaNumeric1 || nonAlphaNumeric2) // Non-alphanumerics
return 1;
return 0;
}
static bool isWhitespace(const QChar &c)
{
if (c == ' ' || c == '\t')
return true;
return false;
}
static bool isNewLine(const QChar &c)
{
if (c == '\n')
return true;
return false;
}
/*
* Splits the diffList into left and right diff lists.
* The left diff list contains the original (insertions removed),
* while the right diff list contains the destination (deletions removed).
*/
void Differ::splitDiffList(const QList<Diff> &diffList,
QList<Diff> *leftDiffList,
QList<Diff> *rightDiffList)
{
if (!leftDiffList || !rightDiffList)
return;
leftDiffList->clear();
rightDiffList->clear();
for (const Diff &diff : diffList) {
if (diff.command != Diff::Delete)
rightDiffList->append(diff);
if (diff.command != Diff::Insert)
leftDiffList->append(diff);
}
}
/*
* Prerequisites:
* input should be only the left or right list of diffs, not a mix of both.
*
* Moves whitespace characters from Diff::Delete or Diff::Insert into
* surrounding Diff::Equal, if possible.
* It may happen, that some Diff::Delete of Diff::Insert will disappear.
*/
QList<Diff> Differ::moveWhitespaceIntoEqualities(const QList<Diff> &input)
{
QList<Diff> output = input;
for (int i = 0; i < output.count(); i++) {
Diff diff = output[i];
if (diff.command != Diff::Equal) {
if (i > 0) { // check previous equality
Diff &previousDiff = output[i - 1];
const int previousDiffCount = previousDiff.text.count();
if (previousDiff.command == Diff::Equal
&& previousDiffCount
&& isWhitespace(previousDiff.text.at(previousDiffCount - 1))) {
// previous diff ends with whitespace
int j = 0;
while (j < diff.text.count()) {
if (!isWhitespace(diff.text.at(j)))
break;
++j;
}
if (j > 0) {
// diff starts with j whitespaces, move them to the previous diff
previousDiff.text.append(diff.text.leftRef(j));
diff.text = diff.text.mid(j);
}
}
}
if (i < output.count() - 1) { // check next equality
const int diffCount = diff.text.count();
Diff &nextDiff = output[i + 1];
const int nextDiffCount = nextDiff.text.count();
if (nextDiff.command == Diff::Equal
&& nextDiffCount
&& (isWhitespace(nextDiff.text.at(0)) || isNewLine(nextDiff.text.at(0)))) {
// next diff starts with whitespace or with newline
int j = 0;
while (j < diffCount) {
if (!isWhitespace(diff.text.at(diffCount - j - 1)))
break;
++j;
}
if (j > 0) {
// diff ends with j whitespaces, move them to the next diff
nextDiff.text.prepend(diff.text.mid(diffCount - j));
diff.text = diff.text.left(diffCount - j);
}
}
}
// remove diff if empty
if (diff.text.isEmpty()) {
output.removeAt(i);
--i;
} else {
output[i] = diff;
}
}
}
return output;
}
/*
* Encodes any sentence of whitespaces with one simple space.
*
* The mapping is returned by codeMap argument, which contains
* the position in output string of encoded whitespace character
* and it's corresponding original sequence of whitespace characters.
*
* The returned string contains encoded version of the input string.
*/
static QString encodeReducedWhitespace(const QString &input,
QMap<int, QString> *codeMap)
{
QString output;
if (!codeMap)
return output;
int inputIndex = 0;
int outputIndex = 0;
while (inputIndex < input.count()) {
QChar c = input.at(inputIndex);
if (isWhitespace(c)) {
output.append(' ');
codeMap->insert(outputIndex, QString(c));
++inputIndex;
while (inputIndex < input.count()) {
QChar reducedChar = input.at(inputIndex);
if (!isWhitespace(reducedChar))
break;
(*codeMap)[outputIndex].append(reducedChar);
++inputIndex;
}
} else {
output.append(c);
++inputIndex;
}
++outputIndex;
}
return output;
}
/*
* This is corresponding function to encodeReducedWhitespace().
*
* The input argument contains version encoded with codeMap,
* the returned value contains decoded diff list.
*/
static QList<Diff> decodeReducedWhitespace(const QList<Diff> &input,
const QMap<int, QString> &codeMap)
{
QList<Diff> output;
int counter = 0;
auto it = codeMap.constBegin();
const auto itEnd = codeMap.constEnd();
for (Diff diff : input) {
const int diffCount = diff.text.count();
while ((it != itEnd) && (it.key() < counter + diffCount)) {
const int reversePosition = diffCount + counter - it.key();
const int updatedDiffCount = diff.text.count();
diff.text.replace(updatedDiffCount - reversePosition, 1, it.value());
++it;
}
output.append(diff);
counter += diffCount;
}
return output;
}
/*
* Prerequisites:
* leftDiff is expected to be Diff::Delete and rightDiff is expected to be Diff::Insert.
*
* Encode any sentence of whitespaces with simple space (inside leftDiff and rightDiff),
* diff without cleanup,
* split diffs,
* decode.
*/
void Differ::diffWithWhitespaceReduced(const QString &leftInput,
const QString &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (!leftOutput || !rightOutput)
return;
leftOutput->clear();
rightOutput->clear();
QMap<int, QString> leftCodeMap;
QMap<int, QString> rightCodeMap;
const QString &leftString = encodeReducedWhitespace(leftInput, &leftCodeMap);
const QString &rightString = encodeReducedWhitespace(rightInput, &rightCodeMap);
Differ differ;
QList<Diff> diffList = differ.diff(leftString, rightString);
QList<Diff> leftDiffList;
QList<Diff> rightDiffList;
Differ::splitDiffList(diffList, &leftDiffList, &rightDiffList);
*leftOutput = decodeReducedWhitespace(leftDiffList, leftCodeMap);
*rightOutput = decodeReducedWhitespace(rightDiffList, rightCodeMap);
}
/*
* Prerequisites:
* leftDiff is expected to be Diff::Delete and rightDiff is expected to be Diff::Insert.
*
* Encode any sentence of whitespaces with simple space (inside leftDiff and rightDiff),
* diff without cleanup,
* split diffs,
* decode.
*/
void Differ::unifiedDiffWithWhitespaceReduced(const QString &leftInput,
const QString &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (!leftOutput || !rightOutput)
return;
leftOutput->clear();
rightOutput->clear();
QMap<int, QString> leftCodeMap;
QMap<int, QString> rightCodeMap;
const QString &leftString = encodeReducedWhitespace(leftInput, &leftCodeMap);
const QString &rightString = encodeReducedWhitespace(rightInput, &rightCodeMap);
Differ differ;
const QList<Diff> &diffList = differ.unifiedDiff(leftString, rightString);
QList<Diff> leftDiffList;
QList<Diff> rightDiffList;
Differ::splitDiffList(diffList, &leftDiffList, &rightDiffList);
*leftOutput = decodeReducedWhitespace(leftDiffList, leftCodeMap);
*rightOutput = decodeReducedWhitespace(rightDiffList, rightCodeMap);
}
/*
* Prerequisites:
* leftEquality and rightEquality needs to be equal. They may differ only with
* whitespaces character (count and kind).
*
* Replaces any corresponding sentence of whitespaces inside left and right equality
* with space characters. The number of space characters inside
* replaced sequence depends on the longest sequence of whitespace characters
* either in left or right equlity.
*
* E.g., when:
* leftEquality: "a b c" (3 whitespace characters, 5 whitespace characters)
* rightEquality: "a /tb /t c" (2 whitespace characters, 7 whitespace characters)
* then:
* returned value: "a b c" (3 space characters, 7 space characters)
*
* The returned code maps contains the info about the encoding done.
* The key on the map is the position of encoding inside the output string,
* and the value, which is a pair of int and string,
* describes how many characters were encoded in the output string
* and what was the original whitespace sequence in the original
* For the above example it would be:
*
* leftCodeMap: <1, <3, " "> >
* <5, <7, " "> >
* rightCodeMap: <1, <3, " /t"> >
* <5, <7, " /t "> >
*
*/
static QString encodeExpandedWhitespace(const QString &leftEquality,
const QString &rightEquality,
QMap<int, QPair<int, QString> > *leftCodeMap,
QMap<int, QPair<int, QString> > *rightCodeMap,
bool *ok)
{
if (ok)
*ok = false;
if (!leftCodeMap || !rightCodeMap)
return QString();
leftCodeMap->clear();
rightCodeMap->clear();
QString output;
const int leftCount = leftEquality.count();
const int rightCount = rightEquality.count();
int leftIndex = 0;
int rightIndex = 0;
while (leftIndex < leftCount && rightIndex < rightCount) {
QString leftWhitespaces;
QString rightWhitespaces;
while (leftIndex < leftCount && isWhitespace(leftEquality.at(leftIndex))) {
leftWhitespaces.append(leftEquality.at(leftIndex));
++leftIndex;
}
while (rightIndex < rightCount && isWhitespace(rightEquality.at(rightIndex))) {
rightWhitespaces.append(rightEquality.at(rightIndex));
++rightIndex;
}
if (leftIndex < leftCount && rightIndex < rightCount) {
if (leftEquality.at(leftIndex) != rightEquality.at(rightIndex))
return QString(); // equalities broken
} else if (leftIndex == leftCount && rightIndex == rightCount) {
; // do nothing, the last iteration
} else {
return QString(); // equalities broken
}
if ((leftWhitespaces.count() && !rightWhitespaces.count())
|| (!leftWhitespaces.count() && rightWhitespaces.count())) {
// there must be at least 1 corresponding whitespace, equalities broken
return QString();
}
if (leftWhitespaces.count() && rightWhitespaces.count()) {
const int replacementPosition = output.count();
const int replacementSize = qMax(leftWhitespaces.count(), rightWhitespaces.count());
const QString replacement(replacementSize, ' ');
leftCodeMap->insert(replacementPosition,
qMakePair(replacementSize, leftWhitespaces));
rightCodeMap->insert(replacementPosition,
qMakePair(replacementSize, rightWhitespaces));
output.append(replacement);
}
if (leftIndex < leftCount)
output.append(leftEquality.at(leftIndex)); // add common character
++leftIndex;
++rightIndex;
}
if (ok)
*ok = true;
return output;
}
/*
* This is corresponding function to encodeExpandedWhitespace().
*
* The input argument contains version encoded with codeMap,
* the returned value contains decoded diff list.
*/
static QList<Diff> decodeExpandedWhitespace(const QList<Diff> &input,
const QMap<int, QPair<int, QString> > &codeMap,
bool *ok)
{
if (ok)
*ok = false;
QList<Diff> output;
int counter = 0;
auto it = codeMap.constBegin();
const auto itEnd = codeMap.constEnd();
for (Diff diff : input) {
const int diffCount = diff.text.count();
while ((it != itEnd) && (it.key() < counter + diffCount)) {
const int replacementSize = it.value().first;
const int reversePosition = diffCount + counter - it.key();
if (reversePosition < replacementSize)
return QList<Diff>(); // replacement exceeds one Diff
const QString replacement = it.value().second;
const int updatedDiffCount = diff.text.count();
diff.text.replace(updatedDiffCount - reversePosition,
replacementSize, replacement);
++it;
}
output.append(diff);
counter += diffCount;
}
if (ok)
*ok = true;
return output;
}
/*
* Prerequisites:
* leftInput and rightInput should contain the same number of equalities,
* equalities should differ only in whitespaces.
*
* Encodes any sentence of whitespace characters in equalities only
* with the maximal number of corresponding whitespace characters
* (inside leftInput and rightInput), so that the leftInput and rightInput
* can be merged together again,
* diff merged sequence with cleanup,
* decode.
*/
static bool diffWithWhitespaceExpandedInEqualities(const QList<Diff> &leftInput,
const QList<Diff> &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (!leftOutput || !rightOutput)
return false;
leftOutput->clear();
rightOutput->clear();
const int leftCount = leftInput.count();
const int rightCount = rightInput.count();
int l = 0;
int r = 0;
QString leftText;
QString rightText;
QMap<int, QPair<int, QString> > commonLeftCodeMap;
QMap<int, QPair<int, QString> > commonRightCodeMap;
while (l <= leftCount && r <= rightCount) {
const Diff leftDiff = l < leftCount ? leftInput.at(l) : Diff(Diff::Equal);
const Diff rightDiff = r < rightCount ? rightInput.at(r) : Diff(Diff::Equal);
if (leftDiff.command == Diff::Equal && rightDiff.command == Diff::Equal) {
QMap<int, QPair<int, QString> > leftCodeMap;
QMap<int, QPair<int, QString> > rightCodeMap;
bool ok = false;
const QString &commonEquality = encodeExpandedWhitespace(leftDiff.text,
rightDiff.text,
&leftCodeMap,
&rightCodeMap,
&ok);
if (!ok)
return false;
// join code map positions with common maps
for (auto it = leftCodeMap.cbegin(), end = leftCodeMap.cend(); it != end; ++it)
commonLeftCodeMap.insert(leftText.count() + it.key(), it.value());
for (auto it = rightCodeMap.cbegin(), end = rightCodeMap.cend(); it != end; ++it)
commonRightCodeMap.insert(rightText.count() + it.key(), it.value());
leftText.append(commonEquality);
rightText.append(commonEquality);
++l;
++r;
}
if (leftDiff.command != Diff::Equal) {
leftText.append(leftDiff.text);
++l;
}
if (rightDiff.command != Diff::Equal) {
rightText.append(rightDiff.text);
++r;
}
}
Differ differ;
const QList<Diff> &diffList = differ.cleanupSemantics(
differ.diff(leftText, rightText));
QList<Diff> leftDiffList;
QList<Diff> rightDiffList;
Differ::splitDiffList(diffList, &leftDiffList, &rightDiffList);
leftDiffList = Differ::moveWhitespaceIntoEqualities(leftDiffList);
rightDiffList = Differ::moveWhitespaceIntoEqualities(rightDiffList);
bool ok = false;
*leftOutput = decodeExpandedWhitespace(leftDiffList,
commonLeftCodeMap, &ok);
if (!ok)
return false;
*rightOutput = decodeExpandedWhitespace(rightDiffList,
commonRightCodeMap, &ok);
if (!ok)
return false;
return true;
}
static void appendWithEqualitiesSquashed(const QList<Diff> &leftInput,
const QList<Diff> &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (leftInput.count()
&& rightInput.count()
&& leftOutput->count()
&& rightOutput->count()
&& leftInput.first().command == Diff::Equal
&& rightInput.first().command == Diff::Equal
&& leftOutput->last().command == Diff::Equal
&& rightOutput->last().command == Diff::Equal) {
leftOutput->last().text += leftInput.first().text;
rightOutput->last().text += rightInput.first().text;
leftOutput->append(leftInput.mid(1));
rightOutput->append(rightInput.mid(1));
return;
}
leftOutput->append(leftInput);
rightOutput->append(rightInput);
}
/*
* Prerequisites:
* leftInput cannot contain insertions, while right input cannot contain deletions.
* The number of equalities on leftInput and rightInput lists should be the same.
* Deletions and insertions need to be merged.
*
* For each corresponding insertion / deletion pair:
* - diffWithWhitespaceReduced(): rediff them separately with whitespace reduced
* (new equalities may appear)
* - moveWhitespaceIntoEqualities(): move whitespace into new equalities
* - diffWithWhitespaceExpandedInEqualities(): expand whitespace inside new
* equalities only and rediff with cleanup
*/
void Differ::ignoreWhitespaceBetweenEqualities(const QList<Diff> &leftInput,
const QList<Diff> &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (!leftOutput || !rightOutput)
return;
leftOutput->clear();
rightOutput->clear();
const int leftCount = leftInput.count();
const int rightCount = rightInput.count();
int l = 0;
int r = 0;
while (l <= leftCount && r <= rightCount) {
const Diff leftDiff = l < leftCount
? leftInput.at(l)
: Diff(Diff::Equal);
const Diff rightDiff = r < rightCount
? rightInput.at(r)
: Diff(Diff::Equal);
if (leftDiff.command == Diff::Equal && rightDiff.command == Diff::Equal) {
const Diff previousLeftDiff = l > 0 ? leftInput.at(l - 1) : Diff(Diff::Equal);
const Diff previousRightDiff = r > 0 ? rightInput.at(r - 1) : Diff(Diff::Equal);
if (previousLeftDiff.command == Diff::Delete
&& previousRightDiff.command == Diff::Insert) {
QList<Diff> outputLeftDiffList;
QList<Diff> outputRightDiffList;
QList<Diff> reducedLeftDiffList;
QList<Diff> reducedRightDiffList;
diffWithWhitespaceReduced(previousLeftDiff.text,
previousRightDiff.text,
&reducedLeftDiffList,
&reducedRightDiffList);
reducedLeftDiffList = moveWhitespaceIntoEqualities(reducedLeftDiffList);
reducedRightDiffList = moveWhitespaceIntoEqualities(reducedRightDiffList);
QList<Diff> cleanedLeftDiffList;
QList<Diff> cleanedRightDiffList;
if (diffWithWhitespaceExpandedInEqualities(reducedLeftDiffList,
reducedRightDiffList,
&cleanedLeftDiffList,
&cleanedRightDiffList)) {
outputLeftDiffList = cleanedLeftDiffList;
outputRightDiffList = cleanedRightDiffList;
} else {
outputLeftDiffList = reducedLeftDiffList;
outputRightDiffList = reducedRightDiffList;
}
appendWithEqualitiesSquashed(outputLeftDiffList,
outputRightDiffList,
leftOutput,
rightOutput);
} else if (previousLeftDiff.command == Diff::Delete) {
leftOutput->append(previousLeftDiff);
} else if (previousRightDiff.command == Diff::Insert) {
rightOutput->append(previousRightDiff);
}
QList<Diff> leftEquality;
QList<Diff> rightEquality;
if (l < leftCount)
leftEquality.append(leftDiff);
if (r < rightCount)
rightEquality.append(rightDiff);
appendWithEqualitiesSquashed(leftEquality,
rightEquality,
leftOutput,
rightOutput);
++l;
++r;
}
if (leftDiff.command != Diff::Equal)
++l;
if (rightDiff.command != Diff::Equal)
++r;
}
}
/*
* Prerequisites:
* leftInput cannot contain insertions, while right input cannot contain deletions.
* The number of equalities on leftInput and rightInput lists should be the same.
* Deletions and insertions need to be merged.
*
* For each corresponding insertion / deletion pair do just diff and merge equalities
*/
void Differ::diffBetweenEqualities(const QList<Diff> &leftInput,
const QList<Diff> &rightInput,
QList<Diff> *leftOutput,
QList<Diff> *rightOutput)
{
if (!leftOutput || !rightOutput)
return;
leftOutput->clear();
rightOutput->clear();
const int leftCount = leftInput.count();
const int rightCount = rightInput.count();
int l = 0;
int r = 0;
while (l <= leftCount && r <= rightCount) {
const Diff leftDiff = l < leftCount
? leftInput.at(l)
: Diff(Diff::Equal);
const Diff rightDiff = r < rightCount
? rightInput.at(r)
: Diff(Diff::Equal);
if (leftDiff.command == Diff::Equal && rightDiff.command == Diff::Equal) {
const Diff previousLeftDiff = l > 0 ? leftInput.at(l - 1) : Diff(Diff::Equal);
const Diff previousRightDiff = r > 0 ? rightInput.at(r - 1) : Diff(Diff::Equal);
if (previousLeftDiff.command == Diff::Delete
&& previousRightDiff.command == Diff::Insert) {
Differ differ;
differ.setDiffMode(Differ::CharMode);
const QList<Diff> commonOutput = differ.cleanupSemantics(
differ.diff(previousLeftDiff.text, previousRightDiff.text));
QList<Diff> outputLeftDiffList;
QList<Diff> outputRightDiffList;
Differ::splitDiffList(commonOutput, &outputLeftDiffList,
&outputRightDiffList);
appendWithEqualitiesSquashed(outputLeftDiffList,
outputRightDiffList,
leftOutput,
rightOutput);
} else if (previousLeftDiff.command == Diff::Delete) {
leftOutput->append(previousLeftDiff);
} else if (previousRightDiff.command == Diff::Insert) {
rightOutput->append(previousRightDiff);
}
QList<Diff> leftEquality;
QList<Diff> rightEquality;
if (l < leftCount)
leftEquality.append(leftDiff);
if (r < rightCount)
rightEquality.append(rightDiff);
appendWithEqualitiesSquashed(leftEquality,
rightEquality,
leftOutput,
rightOutput);
++l;
++r;
}
if (leftDiff.command != Diff::Equal)
++l;
if (rightDiff.command != Diff::Equal)
++r;
}
}
///////////////
Diff::Diff() :
command(Diff::Equal)
{
}
Diff::Diff(Command com, const QString &txt) :
command(com),
text(txt)
{
}
bool Diff::operator==(const Diff &other) const
{
return command == other.command && text == other.text;
}
bool Diff::operator!=(const Diff &other) const
{
return !(operator == (other));
}
QString Diff::commandString(Command com)
{
if (com == Delete)
return QCoreApplication::translate("Diff", "Delete");
else if (com == Insert)
return QCoreApplication::translate("Diff", "Insert");
return QCoreApplication::translate("Diff", "Equal");
}
QString Diff::toString() const
{
QString prettyText = text;
// Replace linebreaks with pretty char
prettyText.replace('\n', '\xb6');
return commandString(command) + " \"" + prettyText + "\"";
}
///////////////
Differ::Differ(QFutureInterfaceBase *jobController)
: m_jobController(jobController)
{
}
QList<Diff> Differ::diff(const QString &text1, const QString &text2)
{
m_currentDiffMode = m_diffMode;
return merge(preprocess1AndDiff(text1, text2));
}
QList<Diff> Differ::unifiedDiff(const QString &text1, const QString &text2)
{
QString encodedText1;
QString encodedText2;
QStringList subtexts = encode(text1, text2, &encodedText1, &encodedText2);
const DiffMode diffMode = m_currentDiffMode;
m_currentDiffMode = CharMode;
// Each different subtext is a separate symbol
// process these symbols as text with bigger alphabet
QList<Diff> diffList = merge(preprocess1AndDiff(encodedText1, encodedText2));
diffList = decode(diffList, subtexts);
m_currentDiffMode = diffMode;
return diffList;
}
void Differ::setDiffMode(Differ::DiffMode mode)
{
m_diffMode = mode;
}
Differ::DiffMode Differ::diffMode() const
{
return m_diffMode;
}
QList<Diff> Differ::preprocess1AndDiff(const QString &text1, const QString &text2)
{
if (text1.isNull() && text2.isNull())
return QList<Diff>();
if (text1 == text2) {
QList<Diff> diffList;
if (!text1.isEmpty())
diffList.append(Diff(Diff::Equal, text1));
return diffList;
}
QString newText1 = text1;
QString newText2 = text2;
QString prefix;
QString suffix;
const int prefixCount = commonPrefix(text1, text2);
if (prefixCount) {
prefix = text1.left(prefixCount);
newText1 = text1.mid(prefixCount);
newText2 = text2.mid(prefixCount);
}
const int suffixCount = commonSuffix(newText1, newText2);
if (suffixCount) {
suffix = newText1.right(suffixCount);
newText1 = newText1.left(newText1.count() - suffixCount);
newText2 = newText2.left(newText2.count() - suffixCount);
}
QList<Diff> diffList = preprocess2AndDiff(newText1, newText2);
if (prefixCount)
diffList.prepend(Diff(Diff::Equal, prefix));
if (suffixCount)
diffList.append(Diff(Diff::Equal, suffix));
return diffList;
}
QList<Diff> Differ::preprocess2AndDiff(const QString &text1, const QString &text2)
{
QList<Diff> diffList;
if (text1.isEmpty()) {
diffList.append(Diff(Diff::Insert, text2));
return diffList;
}
if (text2.isEmpty()) {
diffList.append(Diff(Diff::Delete, text1));
return diffList;
}
if (text1.count() != text2.count())
{
const QString longtext = text1.count() > text2.count() ? text1 : text2;
const QString shorttext = text1.count() > text2.count() ? text2 : text1;
const int i = longtext.indexOf(shorttext);
if (i != -1) {
const Diff::Command command = (text1.count() > text2.count())
? Diff::Delete : Diff::Insert;
diffList.append(Diff(command, longtext.left(i)));
diffList.append(Diff(Diff::Equal, shorttext));
diffList.append(Diff(command, longtext.mid(i + shorttext.count())));
return diffList;
}
if (shorttext.count() == 1) {
diffList.append(Diff(Diff::Delete, text1));
diffList.append(Diff(Diff::Insert, text2));
return diffList;
}
}
if (m_currentDiffMode != Differ::CharMode && text1.count() > 80 && text2.count() > 80)
return diffNonCharMode(text1, text2);
return diffMyers(text1, text2);
}
QList<Diff> Differ::diffMyers(const QString &text1, const QString &text2)
{
const int n = text1.count();
const int m = text2.count();
const bool odd = (n + m) % 2;
const int D = odd ? (n + m) / 2 + 1 : (n + m) / 2;
const int delta = n - m;
const int vShift = D;
int *forwardV = new int[2 * D + 1]; // free me
int *reverseV = new int[2 * D + 1]; // free me
for (int i = 0; i <= 2 * D; i++) {
forwardV[i] = -1;
reverseV[i] = -1;
}
forwardV[vShift + 1] = 0;
reverseV[vShift + 1] = 0;
int kMinForward = -D;
int kMaxForward = D;
int kMinReverse = -D;
int kMaxReverse = D;
for (int d = 0; d <= D; d++) {
if (m_jobController && m_jobController->isCanceled()) {
delete [] forwardV;
delete [] reverseV;
return QList<Diff>();
}
// going forward
for (int k = qMax(-d, kMinForward + qAbs(d + kMinForward) % 2);
k <= qMin(d, kMaxForward - qAbs(d + kMaxForward) % 2);
k = k + 2) {
int x;
if (k == -d || (k < d && forwardV[k + vShift - 1] < forwardV[k + vShift + 1]))
x = forwardV[k + vShift + 1]; // copy vertically from diagonal k + 1, y increases, y may exceed the graph
else
x = forwardV[k + vShift - 1] + 1; // copy horizontally from diagonal k - 1, x increases, x may exceed the graph
int y = x - k;
if (x > n) {
kMaxForward = k - 1; // we are beyond the graph (right border), don't check diagonals >= current k anymore
} else if (y > m) {
kMinForward = k + 1; // we are beyond the graph (bottom border), don't check diagonals <= current k anymore
} else {
// find snake
while (x < n && y < m) {
if (text1.at(x) != text2.at(y))
break;
x++;
y++;
}
forwardV[k + vShift] = x;
if (odd) { // check if overlap
if (k >= delta - (d - 1) && k <= delta + (d - 1)) {
if (n - reverseV[delta - k + vShift] <= x) {
delete [] forwardV;
delete [] reverseV;
return diffMyersSplit(text1, x, text2, y);
}
}
}
}
}
// in reverse direction
for (int k = qMax(-d, kMinReverse + qAbs(d + kMinReverse) % 2);
k <= qMin(d, kMaxReverse - qAbs(d + kMaxReverse) % 2);
k = k + 2) {
int x;
if (k == -d || (k < d && reverseV[k + vShift - 1] < reverseV[k + vShift + 1]))
x = reverseV[k + vShift + 1];
else
x = reverseV[k + vShift - 1] + 1;
int y = x - k;
if (x > n) {
kMaxReverse = k - 1; // we are beyond the graph (right border), don't check diagonals >= current k anymore
} else if (y > m) {
kMinReverse = k + 1; // we are beyond the graph (bottom border), don't check diagonals <= current k anymore
} else {
// find snake
while (x < n && y < m) {
if (text1.at(n - x - 1) != text2.at(m - y - 1))
break;
x++;
y++;
}
reverseV[k + vShift] = x;
if (!odd) { // check if overlap
if (k >= delta - d && k <= delta + d) {
if (n - forwardV[delta - k + vShift] <= x) {
delete [] forwardV;
delete [] reverseV;
return diffMyersSplit(text1, n - x, text2, m - x + k);
}
}
}
}
}
}
delete [] forwardV;
delete [] reverseV;
// Completely different
QList<Diff> diffList;
diffList.append(Diff(Diff::Delete, text1));
diffList.append(Diff(Diff::Insert, text2));
return diffList;
}
QList<Diff> Differ::diffMyersSplit(
const QString &text1, int x,
const QString &text2, int y)
{
const QString text11 = text1.left(x);
const QString text12 = text1.mid(x);
const QString text21 = text2.left(y);
const QString text22 = text2.mid(y);
const QList<Diff> &diffList1 = preprocess1AndDiff(text11, text21);
const QList<Diff> &diffList2 = preprocess1AndDiff(text12, text22);
return diffList1 + diffList2;
}
QList<Diff> Differ::diffNonCharMode(const QString &text1, const QString &text2)
{
QString encodedText1;
QString encodedText2;
QStringList subtexts = encode(text1, text2, &encodedText1, &encodedText2);
DiffMode diffMode = m_currentDiffMode;
m_currentDiffMode = CharMode;
// Each different subtext is a separate symbol
// process these symbols as text with bigger alphabet
QList<Diff> diffList = preprocess1AndDiff(encodedText1, encodedText2);
diffList = decode(diffList, subtexts);
QString lastDelete;
QString lastInsert;
QList<Diff> newDiffList;
if (m_jobController) {
m_jobController->setProgressRange(0, diffList.count());
m_jobController->setProgressValue(0);
}
for (int i = 0; i <= diffList.count(); i++) {
if (m_jobController) {
if (m_jobController->isCanceled()) {
m_currentDiffMode = diffMode;
return QList<Diff>();
}
m_jobController->setProgressValue(i + 1);
}
const Diff diffItem = i < diffList.count()
? diffList.at(i)
: Diff(Diff::Equal); // dummy, ensure we process to the end
// even when diffList doesn't end with equality
if (diffItem.command == Diff::Delete) {
lastDelete += diffItem.text;
} else if (diffItem.command == Diff::Insert) {
lastInsert += diffItem.text;
} else { // Diff::Equal
if (lastDelete.count() || lastInsert.count()) {
// Rediff here on char basis
newDiffList += preprocess1AndDiff(lastDelete, lastInsert);
lastDelete.clear();
lastInsert.clear();
}
newDiffList.append(diffItem);
}
}
m_currentDiffMode = diffMode;
return newDiffList;
}
QStringList Differ::encode(const QString &text1,
const QString &text2,
QString *encodedText1,
QString *encodedText2)
{
QStringList lines;
lines.append(QString()); // don't use code: 0
QMap<QString, int> lineToCode;
*encodedText1 = encode(text1, &lines, &lineToCode);
*encodedText2 = encode(text2, &lines, &lineToCode);
return lines;
}
int Differ::findSubtextEnd(const QString &text,
int subtextStart)
{
if (m_currentDiffMode == Differ::LineMode) {
int subtextEnd = text.indexOf('\n', subtextStart);
if (subtextEnd == -1)
subtextEnd = text.count() - 1;
return ++subtextEnd;
} else if (m_currentDiffMode == Differ::WordMode) {
if (!text.at(subtextStart).isLetter())
return subtextStart + 1;
int i = subtextStart + 1;
const int count = text.count();
while (i < count && text.at(i).isLetter())
i++;
return i;
}
return subtextStart + 1; // CharMode
}
QString Differ::encode(const QString &text,
QStringList *lines,
QMap<QString, int> *lineToCode)
{
int subtextStart = 0;
int subtextEnd = -1;
QString codes;
while (subtextEnd < text.count()) {
subtextEnd = findSubtextEnd(text, subtextStart);
const QString line = text.mid(subtextStart, subtextEnd - subtextStart);
subtextStart = subtextEnd;
if (lineToCode->contains(line)) {
codes += QChar(static_cast<ushort>(lineToCode->value(line)));
} else {
lines->append(line);
lineToCode->insert(line, lines->count() - 1);
codes += QChar(static_cast<ushort>(lines->count() - 1));
}
}
return codes;
}
QList<Diff> Differ::merge(const QList<Diff> &diffList)
{
QString lastDelete;
QString lastInsert;
QList<Diff> newDiffList;
for (int i = 0; i <= diffList.count(); i++) {
Diff diff = i < diffList.count()
? diffList.at(i)
: Diff(Diff::Equal); // dummy, ensure we process to the end
// even when diffList doesn't end with equality
if (diff.command == Diff::Delete) {
lastDelete += diff.text;
} else if (diff.command == Diff::Insert) {
lastInsert += diff.text;
} else { // Diff::Equal
if (lastDelete.count() || lastInsert.count()) {
// common prefix
const int prefixCount = commonPrefix(lastDelete, lastInsert);
if (prefixCount) {
const QString prefix = lastDelete.left(prefixCount);
lastDelete = lastDelete.mid(prefixCount);
lastInsert = lastInsert.mid(prefixCount);
if (newDiffList.count()
&& newDiffList.last().command == Diff::Equal) {
newDiffList.last().text += prefix;
} else {
newDiffList.append(Diff(Diff::Equal, prefix));
}
}
// common suffix
const int suffixCount = commonSuffix(lastDelete, lastInsert);
if (suffixCount) {
const QString suffix = lastDelete.right(suffixCount);
lastDelete = lastDelete.left(lastDelete.count() - suffixCount);
lastInsert = lastInsert.left(lastInsert.count() - suffixCount);
diff.text.prepend(suffix);
}
// append delete / insert / equal
if (lastDelete.count())
newDiffList.append(Diff(Diff::Delete, lastDelete));
if (lastInsert.count())
newDiffList.append(Diff(Diff::Insert, lastInsert));
if (diff.text.count())
newDiffList.append(diff);
lastDelete.clear();
lastInsert.clear();
} else { // join with last equal diff
if (newDiffList.count()
&& newDiffList.last().command == Diff::Equal) {
newDiffList.last().text += diff.text;
} else {
if (diff.text.count())
newDiffList.append(diff);
}
}
}
}
QList<Diff> squashedDiffList = squashEqualities(newDiffList);
if (squashedDiffList.count() != newDiffList.count())
return merge(squashedDiffList);
return squashedDiffList;
}
struct EqualityData
{
int equalityIndex;
int textCount;
int deletesBefore;
int insertsBefore;
int deletesAfter;
int insertsAfter;
};
QList<Diff> Differ::cleanupSemantics(const QList<Diff> &diffList)
{
int deletes = 0;
int inserts = 0;
// equality index, equality data
QList<EqualityData> equalities;
for (int i = 0; i <= diffList.count(); i++) {
const Diff diff = i < diffList.count()
? diffList.at(i)
: Diff(Diff::Equal); // dummy, ensure we process to the end
// even when diffList doesn't end with equality
if (diff.command == Diff::Equal) {
if (!equalities.isEmpty()) {
EqualityData &previousData = equalities.last();
previousData.deletesAfter = deletes;
previousData.insertsAfter = inserts;
}
if (i < diffList.count()) { // don't insert dummy
EqualityData data;
data.equalityIndex = i;
data.textCount = diff.text.count();
data.deletesBefore = deletes;
data.insertsBefore = inserts;
equalities.append(data);
deletes = 0;
inserts = 0;
}
} else {
if (diff.command == Diff::Delete)
deletes += diff.text.count();
else if (diff.command == Diff::Insert)
inserts += diff.text.count();
}
}
QMap<int, bool> equalitiesToBeSplit;
int i = 0;
while (i < equalities.count()) {
const EqualityData &data = equalities.at(i);
if (data.textCount <= qMax(data.deletesBefore, data.insertsBefore)
&& data.textCount <= qMax(data.deletesAfter, data.insertsAfter)) {
if (i > 0) {
EqualityData &previousData = equalities[i - 1];
previousData.deletesAfter += data.textCount + data.deletesAfter;
previousData.insertsAfter += data.textCount + data.insertsAfter;
}
if (i < equalities.count() - 1) {
EqualityData &nextData = equalities[i + 1];
nextData.deletesBefore += data.textCount + data.deletesBefore;
nextData.insertsBefore += data.textCount + data.insertsBefore;
}
equalitiesToBeSplit.insert(data.equalityIndex, true);
equalities.removeAt(i);
if (i > 0)
i--; // reexamine previous equality
} else {
i++;
}
}
QList<Diff> newDiffList;
for (int i = 0; i < diffList.count(); i++) {
const Diff &diff = diffList.at(i);
if (equalitiesToBeSplit.contains(i)) {
newDiffList.append(Diff(Diff::Delete, diff.text));
newDiffList.append(Diff(Diff::Insert, diff.text));
} else {
newDiffList.append(diff);
}
}
return cleanupOverlaps(merge(cleanupSemanticsLossless(merge(newDiffList))));
}
QList<Diff> Differ::cleanupSemanticsLossless(const QList<Diff> &diffList)
{
if (diffList.count() < 3) // we need at least 3 items
return diffList;
QList<Diff> newDiffList;
Diff prevDiff = diffList.at(0);
Diff thisDiff = diffList.at(1);
Diff nextDiff = diffList.at(2);
int i = 2;
while (i < diffList.count()) {
if (prevDiff.command == Diff::Equal
&& nextDiff.command == Diff::Equal) {
// Single edit surrounded by equalities
QString equality1 = prevDiff.text;
QString edit = thisDiff.text;
QString equality2 = nextDiff.text;
// Shift the edit as far left as possible
const int suffixCount = commonSuffix(equality1, edit);
if (suffixCount) {
const QString commonString = edit.mid(edit.count() - suffixCount);
equality1 = equality1.left(equality1.count() - suffixCount);
edit = commonString + edit.left(edit.count() - suffixCount);
equality2 = commonString + equality2;
}
// Step char by char right, looking for the best score
QString bestEquality1 = equality1;
QString bestEdit = edit;
QString bestEquality2 = equality2;
int bestScore = cleanupSemanticsScore(equality1, edit)
+ cleanupSemanticsScore(edit, equality2);
while (!edit.isEmpty() && !equality2.isEmpty()
&& edit[0] == equality2[0]) {
equality1 += edit[0];
edit = edit.mid(1) + equality2[0];
equality2 = equality2.mid(1);
const int score = cleanupSemanticsScore(equality1, edit)
+ cleanupSemanticsScore(edit, equality2);
if (score >= bestScore) {
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
bestScore = score;
}
}
prevDiff.text = bestEquality1;
thisDiff.text = bestEdit;
nextDiff.text = bestEquality2;
if (!bestEquality1.isEmpty())
newDiffList.append(prevDiff); // append modified equality1
if (bestEquality2.isEmpty()) {
i++;
if (i < diffList.count())
nextDiff = diffList.at(i); // omit equality2
}
} else {
newDiffList.append(prevDiff); // append prevDiff
}
prevDiff = thisDiff;
thisDiff = nextDiff;
i++;
if (i < diffList.count())
nextDiff = diffList.at(i);
}
newDiffList.append(prevDiff);
if (i == diffList.count())
newDiffList.append(thisDiff);
return newDiffList;
}
} // namespace DiffEditor
| 35.713278 | 127 | 0.554268 | kevinlq |
b81874f403f5aa58b31dd0a8fe27df2f303f13ff | 1,770 | hpp | C++ | SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_ProjMekSiegeCannon_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ProjMekSiegeCannon.ProjMekSiegeCannon_C
// 0x0090 (0x06F0 - 0x0660)
class AProjMekSiegeCannon_C : public AShooterProjectile
{
public:
float MaxStructureImpactDistance; // 0x0660(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TEnumAsByte<ENetworkModeResult> CallFunc_CanRunCosmeticEvents_OutNetworkMode; // 0x0664(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum_CmpSuccess; // 0x0665(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData00[0x2]; // 0x0666(0x0002) MISSED OFFSET
struct FHitResult K2Node_Event_Result; // 0x0668(0x0088) (OutParm, Transient, DuplicateTransient, ReferenceParm)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ProjMekSiegeCannon.ProjMekSiegeCannon_C");
return ptr;
}
void UserConstructionScript();
void OnExplode(struct FHitResult* Result);
void ExecuteUbergraph_ProjMekSiegeCannon(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 38.478261 | 208 | 0.590395 | 2bite |
b81adeaf4697f45632c66e56d383c6949584a165 | 4,737 | hh | C++ | dam/source/cc/dam/DataFragmentUnpack.hh | DUNE/dunepdsprce | 2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30 | [
"BSD-3-Clause-LBNL"
] | null | null | null | dam/source/cc/dam/DataFragmentUnpack.hh | DUNE/dunepdsprce | 2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30 | [
"BSD-3-Clause-LBNL"
] | null | null | null | dam/source/cc/dam/DataFragmentUnpack.hh | DUNE/dunepdsprce | 2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30 | [
"BSD-3-Clause-LBNL"
] | null | null | null | // -*-Mode: C++;-*-
#ifndef DATAFRAGMENTUNPACK_HH
#define DATAFRAGMENTUNPACK_HH
/* ---------------------------------------------------------------------- *//*!
*
* @file DataFragment.hh
* @brief Access methods for the RCE data fragments
* decoding a binary test file.
* @verbatim
* Copyright 2017
* by
*
* The Board of Trustees of the
* Leland Stanford Junior University.
* All rights reserved.
*
* @endverbatim
*
\* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *\
HISTORY
-------
DATE WHO WHAT
---------- --- ---------------------------------------------------------
2018.08.30 jjr Added isTpcEmpty method
2018.03.23 jjr Added isTpcDamaged method
2017.08.29 jjr Created
\* ---------------------------------------------------------------------- */
#include "dam/access/DataFragment.hh"
#include <cinttypes>
/* ====================================================================== */
/* FORWARD REFERENCES */
/* ---------------------------------------------------------------------- */
namespace pdd {
namespace fragment {
class DataFragmentHeader;
class Identifier;
class Originator;
class Data;
}
class Trailer;
}
/* ====================================================================== */
/* ====================================================================== */
/* CLASS DEFINITION */
/* ---------------------------------------------------------------------- *//*!
\class DataFragmentUnpack
\brief Provides access to a Data Fragment and its records
\par
This is more of a convenience class than anything else. Its main value
is in cacheing pointer to the records contained within a Data Fragment.
Finding thes records can also be done by the caller using the static
routines contained in this class, with no need to instantiate the
class.
*/
/* ---------------------------------------------------------------------- */
class DataFragmentUnpack
{
public:
DataFragmentUnpack (uint64_t const *buf);
// ------------------------------------------------------------
// Get the length of the Data Fragment and check its subtype
// Currently only TpcNormal streams exist, but this may change
// in the future.
// ------------------------------------------------------------
uint32_t getN64 () const;
bool isTpcNormal () const;
bool isTpcDamaged () const;
bool isTpcEmpty () const;
// ------------------------------------------------------------
// Access the records within the Data Fragment
// ------------------------------------------------------------
pdd::record::DataFragmentHeader const *getHeader () const;
pdd::record::Identifier const *getIdentifier () const;
pdd::record::Originator const *getOriginator () const;
pdd::record::Data const *getData () const;
pdd::Trailer const *getTrailer () const;
static pdd::record::DataFragmentHeader
const *getHeader (uint64_t const *buf);
static pdd::record::Identifier const *getIdentifier (uint64_t const *buf);
static pdd::record::Originator const *getOriginator (uint64_t const *buf);
static pdd::record::Data const *getData (uint64_t const *buf);
static pdd::Trailer const *getTrailer (uint64_t const *buf);
// ---------------------------------------------------------
// Crude print methods, meant only to get one off the ground
// Given the size and complexity of a Data Fragment, writing
// one-size-fits-all print routines is not feasible.
// ---------------------------------------------------------
void print () const;
void printHeader () const;
void printIdentifier () const;
void printOriginator () const;
void printData () const;
void printTrailer () const;
static void print (pdd::Header0 const *header);
static void print (pdd::Trailer const *trailer);
public:
pdd::access::DataFragment m_df;
};
/* ====================================================================== */
#endif
| 35.886364 | 80 | 0.410809 | DUNE |
b81b14fbdab9a89d7245ebe0466bb3ca7fce1725 | 8,764 | cpp | C++ | main.cpp | Bango1999/cpp-tictactoe-cli | 6add1cc62b242212b7106cf79426f674e9b654c8 | [
"MIT"
] | null | null | null | main.cpp | Bango1999/cpp-tictactoe-cli | 6add1cc62b242212b7106cf79426f674e9b654c8 | [
"MIT"
] | null | null | null | main.cpp | Bango1999/cpp-tictactoe-cli | 6add1cc62b242212b7106cf79426f674e9b654c8 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
// Program: tic tac toe cli
// Name: Bango
// Purpose: This will be an implementation of a tic-tac-toe game.
// This is a 2 player version of tic-tac-toe where 'X' goes first
// followed by 'O'. When it is player 1's turn, (s)he places an 'X'
// on a 3x3 grid; player 2 places an 'O' on the grid. The first
// player to get 3 characters ('X' or 'O') in a row wins. If
// the board fills up with no winner, the game ends in a tie.
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
// Global variables
const char BLANK = '-';
const char X = 'X';
const char O = 'O';
const char TIE = 'T';
//---------------------------------------------------------------------------
// Name: PlayX
// Parameters: game board 2d array
// Returns: void
// Purpose: Asks for a position and places an X on the grid at a position and returns true.
// Also performs error checking
//---------------------------------------------------------------------------
void PlayX(char board[3][3], string player1)
{
int row, col;
// Ask for the position to place an X.
cout << player1 << ": Enter the row followed by the column for your X (1-3), 0 to exit." << endl;
cin >> row >> col;
if (row == 0 || col == 0) {
board[0][0] = '1';
} else {
while (row < 0 || row > 3 || col < 0 || col > 3 || (row >=1 && row <=3 && col >=1 && col <=3 && board[row-1][col-1] != BLANK))
{
cout << "\nNot a valid play. \n" << player1 << ": Enter the row followed by the column for your X (1-3), 0 to exit." << endl;
cin >> row;
cin >> col;
}
// set the position on the board to X
board[row-1][col-1] = X;
}
}
//---------------------------------------------------------------------------
// Name: PlayO
// Parameters:
// Returns:
// Purpose: Similar to the PlayX function
//---------------------------------------------------------------------------
void PlayO(char board[3][3], string player2)
{
int row = 0;
int col = 0;
// Ask for the position to place an O.
cout << player2 << ": Enter the row followed by the column for your O (1-3), 0 to exit." << endl;
cin >> row >> col;
if (row == 0 || col == 0) {
board[0][0] = '2';
} else {
while (row < 0 || row > 3 || col < 0 || col > 3 || (row >=1 && row <=3 && col >=1 && col <=3 && board[row-1][col-1] != BLANK))
{
cout << "\nNot a valid play. \n" << player2 << ": Enter the row followed by the column for your O (1-3), 0 to exit." << endl;
cin >> row >> col;
}
// set the position on the board to X
board[row-1][col-1] = O;
}
}
//---------------------------------------------------------------------------
// Name: CheckWinner
// Parameters: 2d array for game board
// Returns: char
// Purpose: return 'X' if x wins, 'O' if o wins, 'T' if
// the game has ended in a tie.
//---------------------------------------------------------------------------
int CheckWinner(char board[3][3]) {
int done = 0;
int counter = 0;
//check for a full board
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] != BLANK) {
counter++;
}
}
}
//check for a winner over all possible winning combinations, check for the exit code, 0, and define the variable 'done' which will tell main what it needs to know to output the right thing.
if ((board[0][0] == X && board[0][1] == X && board[0][2] == X) || (board[1][0] == X && board[1][1] == X && board[1][2] == X) || (board[2][0] == X && board[2][1] == X && board[2][2] == X) || (board[0][0] == X && board[1][0] == X && board[2][0] == X) || (board[0][1] == X && board[1][1] == X && board[2][1] == X) || (board[0][2] == X && board[1][2] == X && board[2][2] == X) || (board[0][0] == X && board[1][1] == X && board[2][2] == X) || (board[0][2] == X && board[1][1] == X && board[2][0] == X)) {
done = 1;
} else if ((board[0][0] == O && board[0][1] == O && board[0][2] == O) || (board[1][0] == O && board[1][1] == O && board[1][2] == O) || (board[2][0] == O && board[2][1] == O && board[2][2] == O) || (board[0][0] == O && board[1][0] == O && board[2][0] == O) || (board[0][1] == O && board[1][1] == O && board[2][1] == O) || (board[0][2] == O && board[1][2] == O && board[2][2] == O) || (board[0][0] == O && board[1][1] == O && board[2][2] == O) || (board[0][2] == O && board[1][1] == O && board[2][0] == O)) {
done = 2;
} else if (board[0][0] == '1') {
done = 4;
} else if (board[0][0] == '2') {
done = 5;
} else if (counter == 9) {
done = 3;
}
return done;
}
//---------------------------------------------------------------------------
// Name: ConfirmPlayAgain
// Parameters: none
// Returns: bool
// Purpose: Once the game has ended, this function asks if the player wants to
// play again.
//---------------------------------------------------------------------------
bool ConfirmPlayAgain() {
char x;
bool again;
cout << "Would you like to play again? (y/n) ";
cin >> x;
if (x == 'y' || x == 'Y') {
again = true;
cout << "\n=======================\n\n";
} else {
again = false;
}
return again;
}
//---------------------------------------------------------------------------
// Name: PrintBoard
// Parameters: 2d array game board
// Returns: void
// Purpose: Output current tic-tac-toe game board
//---------------------------------------------------------------------------
void PrintBoard(char board[3][3]) {
for (int i = 0; i < 3; i++)
{
cout << "\n";
for (int j = 0; j < 3; j++)
{
cout << board[i][j];
}
}
}
//---------------------------------------------------------------------------
// Name: InitializeBoard
// Parameters: 2d array game board
// Returns: void
// Purpose: Sets tic-tac-toe game board to blank
//---------------------------------------------------------------------------
void InitializeBoard(char board[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = BLANK;
}
}
}
// Main should be used to call the functions above to complete the tic-tac-toe game.
int main ()
{
char board[3][3];
bool again = true;
char done = 0;
int counter = 0;
string player1;
string player2;
cout << " ________________________________" << endl;
cout << "| |" << endl;
cout << "| Logan B.A. Swango -- 010636621 |" << endl;
cout << "| Project 4: Tic Tac Toe |" << endl;
cout << "| 3/7/2013 |" << endl;
cout << "|________________________________|" << endl;
while (again) {
InitializeBoard(board);
cout << "Player 1, please enter your name: ";
getline(cin, player1);
while (!cin) {
cin.clear();
cout << "Invalid input Player 1, please enter your name: ";
getline(cin, player1);
}
cout << "Player 2, please enter your name: ";
getline(cin, player2);
while (!cin) {
cin.clear();
cout << "Invalid input Player 2, please enter your name: ";
getline(cin, player2);
}
while (done == 0) {
PrintBoard(board);
if (counter % 2 == 0) {
cout << "\n";
PlayX(board, player1);
} else {
cout << "\n";
PlayO(board, player2);
}
counter++;
done = CheckWinner(board);
if (done == 1) {
PrintBoard(board);
cout << "\n" << player1 << " wins!" << endl;
} else if (done == 2) {
PrintBoard(board);
cout << "\n" << player2 << " wins!" << endl;
} else if (done == 3) {
PrintBoard(board);
cout << "\nThe match has ended in a tie!" << endl;
} else if (done == 4) {
cout << "\n" << player1 << " has forefeited the match!" << endl;
} else if (done == 5) {
cout << "\n" << player2 << " has forefeited the match!" << endl;
}
}
if (done == 1 || done == 2 || done == 3 || done == 4 || done == 5) {
again = ConfirmPlayAgain();
}
if (again) {
done = 0;
counter = 0;
}
}
return 0;
}
| 30.430556 | 507 | 0.420812 | Bango1999 |
b81e68a74e764c0c9d2c8ccab0ffa0d53c328407 | 1,967 | cpp | C++ | main.cpp | svenpilz/gpgpu | 0c74790f3753ecafa10256745531de4e6240787d | [
"MIT"
] | 1 | 2016-04-09T00:39:04.000Z | 2016-04-09T00:39:04.000Z | main.cpp | svenpilz/gpgpu | 0c74790f3753ecafa10256745531de4e6240787d | [
"MIT"
] | null | null | null | main.cpp | svenpilz/gpgpu | 0c74790f3753ecafa10256745531de4e6240787d | [
"MIT"
] | null | null | null | #include <iostream>
#include <gpgpu/Context.hpp>
#include <gpgpu/Framebuffer.hpp>
#include <gpgpu/Program.hpp>
#include <OpenImageIO/imagebufalgo.h>
using namespace std;
int main() {
/*
* Context
*/
gpgpu::Context context;
cout << context << endl;
/*
* Shader
*/
gpgpu::Program fixed_color_shader;
auto vs = gpgpu::create_shader(gpgpu::Shader::Vertex, R"(
#version 130
uniform mat4 camera;
in vec4 vertex;
void main() {
gl_Position = camera * vertex;
})"
);
auto fs = gpgpu::create_shader(gpgpu::Shader::Fragment, R"(
#version 130
out vec4 color;
void main() {
color = vec4(1.0, 0.0, 0.0, 1.0);
})"
);
fixed_color_shader.append({vs, fs});
fixed_color_shader.link();
/*
* Framebuffer
*/
gpgpu::Framebuffer fb(800, 600, true);
auto canvas = make_shared<gpgpu::Texture2D>(800, 600);
fb.set_color_attachment(canvas, 0);
/*
* Geometry
*/
float vertices[] = {
-0.5, -0.5, 0.0,
0.0, 0.5, 0.0,
0.5, -0.5, 0.0
};
auto geometry = make_shared<gpgpu::ArrayBuffer>();
geometry->data(3, 3, vertices);
unsigned int face_vertices[] = {
0, 1, 2
};
gpgpu::ElementArrayBuffer faces;
faces.data(3, 3, face_vertices);
/*
* Camera
*/
Eigen::Matrix4f camera = Eigen::Matrix4f::Identity();
/*
* Render
*/
fb.bind();
fixed_color_shader.use();
fixed_color_shader.uniform("camera", camera);
fixed_color_shader.attribute("vertex", geometry);
fixed_color_shader.render(faces);
// Or without indirection.
//fixed_color_shader.render(geometry, "vertex", GL_TRIANGLES);
auto image = canvas->image();
OpenImageIO::ImageBuf output;
OpenImageIO::ImageBufAlgo::flip(output, *image);
output.write("canvas.png");
return 0;
} | 20.705263 | 66 | 0.571429 | svenpilz |
b82012b146208c5058594132edee7cb163f2367a | 11,745 | cc | C++ | src/devices/i2c/drivers/i2c/i2c-child-test.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/devices/i2c/drivers/i2c/i2c-child-test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/devices/i2c/drivers/i2c/i2c-child-test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "i2c-child.h"
#include <lib/fake_ddk/fake_ddk.h>
#include <ddk/binding.h>
#include <zxtest/zxtest.h>
#include "i2c-bus.h"
namespace i2c {
constexpr uint8_t kTestWrite0 = 0x99;
constexpr uint8_t kTestWrite1 = 0x88;
constexpr uint8_t kTestWrite2 = 0x77;
constexpr uint8_t kTestRead0 = 0x12;
constexpr uint8_t kTestRead1 = 0x34;
constexpr uint8_t kTestRead2 = 0x56;
class I2cChildTest : public I2cChild {
public:
I2cChildTest(zx_device_t* parent, fbl::RefPtr<I2cBus> bus, uint16_t address)
: I2cChild(parent, std::move(bus), address) {
ddk_proto_id_ = ZX_PROTOCOL_I2C;
ZX_ASSERT(DdkAdd("Test-device") == ZX_OK);
}
};
TEST(I2cChildTest, Write3BytesOnce) {
fake_ddk::Bind tester;
class I2cBusTest : public I2cBus {
public:
explicit I2cBusTest(ddk::I2cImplProtocolClient i2c, uint32_t bus_id)
: I2cBus(fake_ddk::kFakeParent, i2c, bus_id) {}
void Transact(uint16_t address, const i2c_op_t* op_list, size_t op_count,
i2c_transact_callback callback, void* cookie) override {
if (op_count != 1) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
auto p0 = static_cast<uint8_t*>(const_cast<void*>(op_list[0].data_buffer));
if (p0[0] != kTestWrite0 || p0[1] != kTestWrite1 || p0[2] != kTestWrite2 ||
op_list[0].data_size != 3 || op_list[0].is_read != false || op_list[0].stop != true) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
callback(cookie, ZX_OK, nullptr, 0);
}
};
ddk::I2cImplProtocolClient i2c = {};
I2cChildTest server(fake_ddk::kFakeParent, fbl::AdoptRef<I2cBus>(new I2cBusTest(i2c, 0)), 0);
llcpp::fuchsia::hardware::i2c::Device2::SyncClient client_wrap(std::move(tester.FidlClient()));
bool is_write[] = {true}; // 1 write segment.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 3 bytes in 1 write segment.
size_t n_write_bytes = 3;
auto write_buffer = std::make_unique<uint8_t[]>(n_write_bytes);
write_buffer[0] = kTestWrite0;
write_buffer[1] = kTestWrite1;
write_buffer[2] = kTestWrite2;
fidl::VectorView<uint8_t> write_segment(fidl::unowned_ptr(write_buffer.get()), n_write_bytes);
auto read = client_wrap.Transfer(std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(
fidl::unowned_ptr(&write_segment), 1), // 1 write segment.
fidl::VectorView<uint8_t>(nullptr, 0)); // No reads.
ASSERT_OK(read.status());
ASSERT_FALSE(read->result.is_err());
}
TEST(I2cChildTest, Read3BytesOnce) {
fake_ddk::Bind tester;
class I2cBusTest : public I2cBus {
public:
explicit I2cBusTest(ddk::I2cImplProtocolClient i2c, uint32_t bus_id)
: I2cBus(fake_ddk::kFakeParent, i2c, bus_id) {}
void Transact(uint16_t address, const i2c_op_t* op_list, size_t op_count,
i2c_transact_callback callback, void* cookie) override {
if (op_count != 1) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
if (op_list[0].data_size != 3 || op_list[0].is_read != true || op_list[0].stop != true) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
uint8_t reply0 = kTestRead0;
uint8_t reply1 = kTestRead1;
uint8_t reply2 = kTestRead2;
i2c_op_t replies[3] = {
{&reply0, 1, true, false},
{&reply1, 1, true, false},
{&reply2, 1, true, false},
};
callback(cookie, ZX_OK, replies, countof(replies));
}
};
ddk::I2cImplProtocolClient i2c = {};
I2cChildTest server(fake_ddk::kFakeParent, fbl::AdoptRef<I2cBus>(new I2cBusTest(i2c, 0)), 0);
llcpp::fuchsia::hardware::i2c::Device2::SyncClient client_wrap(std::move(tester.FidlClient()));
bool is_write[] = {false}; // 1 read segment.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 1 read segment expecting 3 bytes.
constexpr size_t n_reads = 1;
auto read_lengths = std::make_unique<uint8_t[]>(n_reads);
read_lengths[0] = 3; // 3 bytes to read in 1 segment.
auto read =
client_wrap.Transfer(std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(nullptr, 0), // No writes.
fidl::VectorView<uint8_t>(fidl::unowned_ptr(read_lengths.get()),
n_reads)); // 1 read segment.
ASSERT_OK(read.status());
ASSERT_FALSE(read->result.is_err());
auto& read_data = read->result.response().read_segments_data;
ASSERT_EQ(read_data[0].data()[0], kTestRead0);
ASSERT_EQ(read_data[1].data()[0], kTestRead1);
ASSERT_EQ(read_data[2].data()[0], kTestRead2);
}
TEST(I2cChildTest, Write1ByteOnceRead1Byte3Times) {
fake_ddk::Bind tester;
class I2cBusTest : public I2cBus {
public:
explicit I2cBusTest(ddk::I2cImplProtocolClient i2c, uint32_t bus_id)
: I2cBus(fake_ddk::kFakeParent, i2c, bus_id) {}
void Transact(uint16_t address, const i2c_op_t* op_list, size_t op_count,
i2c_transact_callback callback, void* cookie) override {
if (op_count != 4) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
auto p0 = static_cast<uint8_t*>(const_cast<void*>(op_list[0].data_buffer));
if (p0[0] != kTestWrite0 || op_list[0].data_size != 1 || op_list[0].is_read != false ||
op_list[0].stop != false || op_list[1].data_size != 1 || op_list[1].is_read != true ||
op_list[1].stop != false || op_list[2].data_size != 1 || op_list[2].is_read != true ||
op_list[2].stop != false || op_list[3].data_size != 1 || op_list[3].is_read != true ||
op_list[3].stop != true) {
callback(cookie, ZX_ERR_INTERNAL, nullptr, 0);
return;
}
uint8_t reply0 = kTestRead0;
uint8_t reply1 = kTestRead1;
uint8_t reply2 = kTestRead2;
i2c_op_t replies[3] = {
{&reply0, 1, true, false},
{&reply1, 1, true, false},
{&reply2, 1, true, false},
};
callback(cookie, ZX_OK, replies, countof(replies));
}
};
ddk::I2cImplProtocolClient i2c = {};
I2cChildTest server(fake_ddk::kFakeParent, fbl::AdoptRef<I2cBus>(new I2cBusTest(i2c, 0)), 0);
llcpp::fuchsia::hardware::i2c::Device2::SyncClient client_wrap(std::move(tester.FidlClient()));
bool is_write[] = {true, false, false, false}; // 1 write, 3 reads.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 1 byte in 1 write segment.
size_t n_write_bytes = 1;
auto write_buffer = std::make_unique<uint8_t[]>(n_write_bytes);
write_buffer[0] = kTestWrite0;
fidl::VectorView<uint8_t> write_segment(fidl::unowned_ptr(write_buffer.get()), n_write_bytes);
// 3 read segments expecting 1 byte each.
constexpr size_t n_reads = 3;
auto read_lengths = std::make_unique<uint8_t[]>(n_reads);
read_lengths[0] = 1;
read_lengths[1] = 1;
read_lengths[2] = 1;
auto read = client_wrap.Transfer(
std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(fidl::unowned_ptr(&write_segment),
1), // 1 write segment.
fidl::VectorView<uint8_t>(fidl::unowned_ptr(read_lengths.get()),
n_reads)); // 3 read segmenets.
ASSERT_OK(read.status());
ASSERT_FALSE(read->result.is_err());
auto& read_data = read->result.response().read_segments_data;
ASSERT_EQ(read_data[0].data()[0], kTestRead0);
ASSERT_EQ(read_data[1].data()[0], kTestRead1);
ASSERT_EQ(read_data[2].data()[0], kTestRead2);
}
TEST(I2cChildTest, BadTransfers) {
fake_ddk::Bind tester;
ddk::I2cImplProtocolClient i2c = {};
I2cChildTest server(fake_ddk::kFakeParent,
fbl::AdoptRef<I2cBus>(new I2cBus(fake_ddk::kFakeParent, i2c, 0)), 0);
llcpp::fuchsia::hardware::i2c::Device2::SyncClient client_wrap(std::move(tester.FidlClient()));
{
// 2 write segments, inconsistent with 1 segment write below.
bool is_write[] = {true, true};
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
size_t n_write_bytes = 1;
auto write_buffer = std::make_unique<uint8_t[]>(n_write_bytes);
write_buffer[0] = kTestWrite0;
fidl::VectorView<uint8_t> write_segment(fidl::unowned_ptr(write_buffer.get()), n_write_bytes);
auto read = client_wrap.Transfer(
std::move(segments_is_write),
// 1 segment write (incosistent with the 2 segments_is_write above).
fidl::VectorView<fidl::VectorView<uint8_t>>(fidl::unowned_ptr(&write_segment), 1),
fidl::VectorView<uint8_t>(nullptr, 0)); // No reads.
ASSERT_OK(read.status());
ASSERT_TRUE(read->result.is_err());
}
{
bool is_write[] = {true}; // 1 write segment, inconsistent with segments below.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 1 byte in 2 write segments.
size_t n_write_bytes = 1;
auto write_buffer = std::make_unique<uint8_t[]>(n_write_bytes);
write_buffer[0] = kTestWrite0;
fidl::VectorView<uint8_t> write_segments[2];
write_segments[0].set_data(fidl::unowned_ptr(write_buffer.get()));
write_segments[0].set_count(n_write_bytes);
write_segments[1].set_data(fidl::unowned_ptr(write_buffer.get()));
write_segments[1].set_count(n_write_bytes);
auto read =
client_wrap.Transfer(std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(
fidl::unowned_ptr(write_segments), 2), // 2 write segments.
fidl::VectorView<uint8_t>(nullptr, 0)); // No reads.
ASSERT_OK(read.status());
ASSERT_TRUE(read->result.is_err());
}
{
bool is_write[] = {false}; // 1 read segment, inconsistent with segments below.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 2 read segments expecting 2 bytes each.
constexpr size_t n_reads = 2;
auto read_lengths = std::make_unique<uint8_t[]>(n_reads);
read_lengths[0] = 2;
read_lengths[1] = 2;
auto read =
client_wrap.Transfer(std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(nullptr, 0), // No writes.
fidl::VectorView<uint8_t>(fidl::unowned_ptr(read_lengths.get()),
n_reads)); // 2 read segments.
ASSERT_OK(read.status());
ASSERT_TRUE(read->result.is_err());
}
{
bool is_write[] = {false, false}; // 2 read segments, inconsistent with segments below.
fidl::VectorView<bool> segments_is_write(fidl::unowned_ptr(is_write), countof(is_write));
// 1 read segment expecting 2 bytes.
constexpr size_t n_reads = 1;
auto read_lengths = std::make_unique<uint8_t[]>(n_reads);
read_lengths[0] = 2;
auto read =
client_wrap.Transfer(std::move(segments_is_write),
fidl::VectorView<fidl::VectorView<uint8_t>>(nullptr, 0), // No writes.
fidl::VectorView<uint8_t>(fidl::unowned_ptr(read_lengths.get()),
n_reads)); // 1 read segment.
ASSERT_OK(read.status());
ASSERT_TRUE(read->result.is_err());
}
}
} // namespace i2c
| 41.501767 | 100 | 0.644444 | dahlia-os |
b821505ac59988b02264175486a38ad044fd3c68 | 1,192 | cpp | C++ | Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | null | null | null | Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | 8 | 2020-03-10T23:11:09.000Z | 2020-03-14T01:19:32.000Z | Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp | TDToolbox/btdapi | b8349ef33d5bc2dacc85e96ced86dc37e972e8ee | [
"MIT"
] | null | null | null | #include "os/c-api/il2cpp-config-platforms.h"
#if !IL2CPP_DOTS_WITHOUT_DEBUGGER
#include "os/Path.h"
#include "utils/PathUtils.h"
#include "Allocator.h"
extern "C"
{
const char* UnityPalGetTempPath()
{
return Allocator::CopyToAllocatedStringBuffer(il2cpp::os::Path::GetTempPath());
}
const char* UnityPalGetExecutablePath()
{
return Allocator::CopyToAllocatedStringBuffer(il2cpp::os::Path::GetExecutablePath());
}
int32_t UnityPalIsAbsolutePath(const char* path)
{
if (path == NULL)
return 0;
std::string path_string = path;
return il2cpp::os::Path::IsAbsolute(path_string);
}
char* UnityPalBasename(const char* path)
{
if (path == NULL)
return NULL;
std::string pathString = path;
return Allocator::CopyToAllocatedStringBuffer(il2cpp::utils::PathUtils::Basename(pathString));
}
char* UnityPalDirectoryName(const char* path)
{
if (path == NULL)
return NULL;
std::string pathString = path;
return Allocator::CopyToAllocatedStringBuffer(il2cpp::utils::PathUtils::DirectoryName(pathString));
}
}
#endif
| 25.361702 | 107 | 0.647651 | TDToolbox |
b822c39b7bcda06ac3fd9e243df856767593e48b | 2,715 | cpp | C++ | buffer.cpp | alexander-sholohov/rtlmuxer | cae7fb29f4daa7df0cd74279bf8168e9645a5306 | [
"MIT"
] | 13 | 2016-05-15T08:20:43.000Z | 2021-05-19T12:53:46.000Z | buffer.cpp | US1GHQ/rtlmuxer | 9f317f9730169b074dcd96bfe4eecaeae22aa4de | [
"MIT"
] | 1 | 2018-11-21T18:19:14.000Z | 2018-11-27T12:02:03.000Z | buffer.cpp | US1GHQ/rtlmuxer | 9f317f9730169b074dcd96bfe4eecaeae22aa4de | [
"MIT"
] | 5 | 2016-10-14T19:45:56.000Z | 2020-10-04T19:31:31.000Z | //
// Author: Alexander Sholohov <ra9yer@yahoo.com>
//
// License: MIT
//
#include <memory.h>
#include "buffer.h"
//---------------------------------------------------------------------------------------------------
CBuffer::CBuffer(size_t bufferSize)
{
m_buffer.resize(bufferSize + 16);
m_head = 0;
m_tail = 0;
}
//---------------------------------------------------------------------------------------------------
void CBuffer::consume(size_t len)
{
if( bytesAvailable() < len )
{
// never happen but for some reason
m_head = 0;
m_tail = 0;
return;
}
m_tail += len;
if( m_tail >= m_buffer.size() )
{
m_tail -= m_buffer.size();
}
}
//---------------------------------------------------------------------------------------------------
void CBuffer::peek(char* buf, size_t len) const
{
if( m_tail + len < m_buffer.size() )
{
memcpy(buf, &m_buffer[m_tail], len);
}
else
{
size_t len1 = m_buffer.size() - m_tail;
size_t len2 = len - len1;
memcpy(buf, &m_buffer[m_tail], len1);
memcpy(buf+len1, &m_buffer[0], len2);
}
}
//---------------------------------------------------------------------------------------------------
void CBuffer::peek(std::vector<char> & buffer, size_t len) const
{
size_t len2 = (len > buffer.size())? buffer.size() : len; // limit length for some reason
peek(&buffer[0], len2);
}
//---------------------------------------------------------------------------------------------------
void CBuffer::put(const char* buf, size_t len)
{
// ignore huge data (should never happen)
if( len >= m_buffer.size())
return;
size_t bytesAvailableBefore = bytesAvailable();
if( m_head + len < m_buffer.size() )
{
memcpy(&m_buffer[m_head], buf, len);
m_head += len;
}
else
{
size_t len1 = m_buffer.size() - m_head;
size_t len2 = len - len1;
memcpy(&m_buffer[m_head], buf, len1);
memcpy(&m_buffer[0], buf+len1, len2);
m_head = len2;
}
// check buffer overflow
if( bytesAvailableBefore + len >= m_buffer.size() - 1 )
{
m_tail = m_head + 1;
if( m_tail == m_buffer.size() )
m_tail = 0;
}
}
//---------------------------------------------------------------------------------------------------
size_t CBuffer::bytesAvailable() const
{
int s = m_head - m_tail;
if( s < 0 )
{
s += m_buffer.size();
}
return s;
}
//---------------------------------------------------------------------------------------------------
void CBuffer::reset()
{
m_head = 0;
m_tail = 0;
}
| 23.815789 | 101 | 0.402578 | alexander-sholohov |
b82664066fbd78861a15ddb3e3cc9346ed2cc044 | 1,203 | cpp | C++ | vpi/src/copyMemory.cpp | anycore/anycore-pisa-funcsim | 122e08c7b94448ace742bc298740ec4ed1e7ec81 | [
"BSD-3-Clause"
] | null | null | null | vpi/src/copyMemory.cpp | anycore/anycore-pisa-funcsim | 122e08c7b94448ace742bc298740ec4ed1e7ec81 | [
"BSD-3-Clause"
] | null | null | null | vpi/src/copyMemory.cpp | anycore/anycore-pisa-funcsim | 122e08c7b94448ace742bc298740ec4ed1e7ec81 | [
"BSD-3-Clause"
] | 3 | 2017-10-14T00:51:39.000Z | 2021-03-25T16:37:11.000Z | #include <stdio.h>
#include <stdlib.h>
#include "vpi_user.h"
#include "Thread.h"
#include "veri_memory_macros.h"
#include "veri_memory.h"
#include "global_vars.h"
#include "VPI_global_vars.h"
int copyMemory_calltf(char *user_data)
{
vpiHandle systf_handle, arg_iterator, arg_handle, reg_handle;
s_vpi_value current_value;
s_vpi_value value_s;
/* obtain a handle to the system task instance. */
systf_handle = vpi_handle(vpiSysTfCall, 0);
/* obtain handle to system task argument. */
//arg_iterator = vpi_iterate(vpiArgument, systf_handle);
//reg_handle = vpi_scan(arg_iterator);
/* free iterator memory */
//vpi_free_object(arg_iterator);
VMEM[0]->copy_mem(THREAD[0]->get_mem_table());
vpi_printf("Memory table copied from functional simulator\n");
return(0);
}
// Associate C Function with a New System Function
void copyMemory_register() {
s_vpi_systf_data task_data_s;
task_data_s.type = vpiSysTask;
//task_data_s.sysfunctype = vpiSysFuncSized;
task_data_s.tfname = "$copyMemory";
task_data_s.calltf = copyMemory_calltf;
task_data_s.compiletf = 0;
//task_data_s.sizetf = readInst_sizetf;
vpi_register_systf(&task_data_s);
}
| 23.588235 | 64 | 0.733167 | anycore |
b82730c0e9e7b2054c2df23a197819efbbfff9f2 | 28,511 | cpp | C++ | Code/Tools/SceneAPI/SceneCore/Tests/Containers/Views/FilterIteratorTests.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Tools/SceneAPI/SceneCore/Tests/Containers/Views/FilterIteratorTests.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Tools/SceneAPI/SceneCore/Tests/Containers/Views/FilterIteratorTests.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#define _SCL_SECURE_NO_WARNINGS
#include <AzTest/AzTest.h>
#include <AzCore/std/createdestroy.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/std/iterator.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/containers/unordered_set.h>
#include <SceneAPI/SceneCore/Containers/Views/FilterIterator.h>
#include <SceneAPI/SceneCore/Tests/Containers/Views/IteratorTestsBase.h>
namespace AZ
{
namespace SceneAPI
{
namespace Containers
{
namespace Views
{
template<typename CollectionType>
class FilterIteratorBasicTests
: public IteratorTypedTestsBase<CollectionType>
{
public:
FilterIteratorBasicTests()
{
MakeComparePredicate(0);
}
~FilterIteratorBasicTests() override = default;
using BaseIteratorReference = typename IteratorTypedTestsBase<CollectionType>::BaseIteratorReference;
template<typename T>
void MakeComparePredicate(T compareValue)
{
m_testPredicate = [compareValue](const BaseIteratorReference value) -> bool
{
return value >= compareValue;
};
}
template<typename T>
void MakeNotEqualPredicate(T compareValue)
{
m_testPredicate = [compareValue](const BaseIteratorReference value) -> bool
{
return value != compareValue;
};
}
AZStd::function<bool(const BaseIteratorReference)> m_testPredicate;
};
TYPED_TEST_CASE_P(FilterIteratorBasicTests);
TYPED_TEST_P(FilterIteratorBasicTests,
Constructor_InputIsEmptyValidBaseIterator_NoCrash)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
FilterIterator<BaseIterator>
testIterator(this->m_testCollection.begin(), this->m_testCollection.end(),
this->m_testPredicate);
}
TYPED_TEST_P(FilterIteratorBasicTests,
Constructor_MovesForwardBasedOnPredicate_ExpectSkipFirstEntryAndReturnSecond)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
lhsIterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_EQ(1, *lhsIterator);
}
// Increment operator
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorPreIncrement_MoveOneUnfilteredElementUp_ReturnsTheSecondValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
iterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
++iterator;
EXPECT_EQ(1, *iterator);
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorPreIncrement_MoveOneSkippingOne_ReturnsTheThirdValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
iterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
++iterator;
EXPECT_EQ(2, *iterator);
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorPostIncrement_MoveOneUnfilteredElementUp_ReturnsTheSecondValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
iterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
iterator++;
EXPECT_EQ(1, *iterator);
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorPostIncrement_MoveOneSkippingOne_ReturnsTheThirdValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
iterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
iterator++;
EXPECT_EQ(2, *iterator);
}
// Equals equals operator
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorEqualsEquals_DifferentlyInitializedObjectsPredicatePassesAll_ReturnsFalse)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
FilterIterator<BaseIterator>
lhsIterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
FilterIterator<BaseIterator>
rhsIterator(this->GetBaseIterator(1), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_NE(lhsIterator, rhsIterator);
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorEqualsEquals_DifferentlyInitializedObjectsPredicatePassesPart_ReturnsTrue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
lhsIterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
FilterIterator<BaseIterator>
rhsIterator(this->GetBaseIterator(1), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_EQ(lhsIterator, rhsIterator);
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorEqualsEquals_SkippingAllEntriesMatchesWithEndIterator_FullySkippedIteratorIsSameAsEnd)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(3);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
FilterIterator<BaseIterator>
iterator(this->m_testCollection.begin(), this->m_testCollection.end(),
this->m_testPredicate);
FilterIterator<BaseIterator>
endIterator(this->m_testCollection.end(), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_EQ(iterator, endIterator);
}
// Not equals operator
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorNotEquals_DifferentObjects_ReturnsTrue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
FilterIterator<BaseIterator>
lhsIterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
FilterIterator<BaseIterator>
rhsIterator(this->GetBaseIterator(1), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_TRUE(lhsIterator != rhsIterator);
}
// Star operator
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorStar_GetValueByDereferencingIterator_ExpectFirstValueInArray)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
AddElement(this->m_testCollection, 0);
FilterIterator<BaseIterator>
lhsIterator(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
EXPECT_EQ(0, *lhsIterator);
}
// Decrement operator
template<typename Container, typename = typename AZStd::iterator_traits<typename Container::iterator>::iterator_category>
struct OperatorPreDecrement
{
int operator()([[maybe_unused]] FilterIteratorBasicTests<Container>& test, [[maybe_unused]] int iteratorOffset, int expectedResult)
{
return expectedResult;
}
};
template<typename Container>
struct OperatorPreDecrement<Container, AZStd::bidirectional_iterator_tag>
{
int operator()(FilterIteratorBasicTests<Container>& test, int iteratorOffset, [[maybe_unused]] int expectedResult)
{
FilterIterator<typename Container::iterator>
iterator(test.GetBaseIterator(iteratorOffset), test.m_testCollection.begin(), test.m_testCollection.end(),
test.m_testPredicate);
--iterator;
return *iterator;
};
};
template<typename Container>
struct OperatorPreDecrement<Container, AZStd::random_access_iterator_tag>
: public OperatorPreDecrement<Container, AZStd::bidirectional_iterator_tag>
{
};
template<typename Container>
struct OperatorPreDecrement<Container, AZStd::contiguous_iterator_tag>
: public OperatorPreDecrement<Container, AZStd::bidirectional_iterator_tag>
{
};
template<typename Container, typename = typename AZStd::iterator_traits<typename Container::iterator>::iterator_category>
struct OperatorPostDecrement
{
int operator()([[maybe_unused]] FilterIteratorBasicTests<Container>& test, [[maybe_unused]] int iteratorOffset, int expectedResult)
{
return expectedResult;
}
};
template<typename Container>
struct OperatorPostDecrement<Container, AZStd::bidirectional_iterator_tag>
{
int operator()(FilterIteratorBasicTests<Container>& test, int iteratorOffset, [[maybe_unused]] int expectedResult)
{
FilterIterator<typename Container::iterator>
iterator(test.GetBaseIterator(iteratorOffset), test.m_testCollection.begin(), test.m_testCollection.end(),
test.m_testPredicate);
iterator--;
return *iterator;
};
};
template<typename Container>
struct OperatorPostDecrement<Container, AZStd::random_access_iterator_tag>
: public OperatorPostDecrement<Container, AZStd::bidirectional_iterator_tag>
{
};
template<typename Container>
struct OperatorPostDecrement<Container, AZStd::contiguous_iterator_tag>
: public OperatorPostDecrement<Container, AZStd::bidirectional_iterator_tag>
{
};
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorDecrement_MoveOneUnfilteredElementDown_ReturnsTheFirstValue)
{
using CollectionType = typename IteratorTypedTestsBase<TypeParam>::CollectionType;
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
EXPECT_EQ(0, OperatorPreDecrement<CollectionType>()(*this, 1, 0));
EXPECT_EQ(0, OperatorPostDecrement<CollectionType>()(*this, 1, 0));
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorDecrement_MoveOneFilteredElementDown_ReturnsTheFirstValue)
{
using CollectionType = typename IteratorTypedTestsBase<TypeParam>::CollectionType;
this->MakeNotEqualPredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
EXPECT_EQ(0, OperatorPreDecrement<CollectionType>()(*this, 2, 0));
EXPECT_EQ(0, OperatorPostDecrement<CollectionType>()(*this, 2, 0));
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorDecrement_MoveDownToLastFilteredElement_ExpectToStayOnCurrentElement)
{
using CollectionType = typename IteratorTypedTestsBase<TypeParam>::CollectionType;
this->MakeNotEqualPredicate(0);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
EXPECT_EQ(1, OperatorPreDecrement<CollectionType>()(*this, 1, 1));
EXPECT_EQ(1, OperatorPostDecrement<CollectionType>()(*this, 1, 1));
}
TYPED_TEST_P(FilterIteratorBasicTests,
OperatorDecrement_MoveOneUnfilteredElementDownFromEnd_ReturnsTheSecondValue)
{
using CollectionType = typename IteratorTypedTestsBase<TypeParam>::CollectionType;
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
ReorderToMatchIterationWithAddition(this->m_testCollection);
EXPECT_EQ(1, OperatorPreDecrement<CollectionType>()(*this, 2, 1));
EXPECT_EQ(1, OperatorPostDecrement<CollectionType>()(*this, 2, 1));
}
// Filtered Elements
TYPED_TEST_P(FilterIteratorBasicTests,
MakeFilterView_InputIsIterator_CorrectFilteredElements)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(2);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
AddElement(this->m_testCollection, 3);
AZStd::unordered_set<int> expectedElements = {2, 3};
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->m_testCollection.begin(), this->m_testCollection.end(),
this->m_testPredicate);
for (auto it : view)
{
if (expectedElements.find(it) != expectedElements.end())
{
expectedElements.erase(it);
}
}
EXPECT_TRUE(expectedElements.empty());
}
TYPED_TEST_P(FilterIteratorBasicTests,
MakeFilterView_InputIteratorNotStartsAtBegin_CorrectFilteredElements)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(2);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
AddElement(this->m_testCollection, 3);
ReorderToMatchIterationWithAddition(this->m_testCollection);
AZStd::unordered_set<int> expectedElements = { 2, 3 };
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->GetBaseIterator(1), this->m_testCollection.end(),
this->m_testPredicate);
for (auto it : view)
{
if (expectedElements.find(it) != expectedElements.end())
{
expectedElements.erase(it);
}
}
EXPECT_TRUE(expectedElements.empty());
}
// Algorithms
TYPED_TEST_P(FilterIteratorBasicTests,
Algorithms_CopyFilteredContainer_ContainerIsCopiedWithoutFilteredValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeNotEqualPredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
AZStd::vector<int> target;
AZStd::copy(view.begin(), view.end(), AZStd::back_inserter(target));
ASSERT_EQ(2, target.size());
EXPECT_EQ(0, target[0]);
EXPECT_EQ(2, target[1]);
}
TYPED_TEST_P(FilterIteratorBasicTests,
Algorithms_FillFilteredContainer_AllValuesAreSetTo42ExceptFilteredValue)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeNotEqualPredicate(1);
AddElement(this->m_testCollection, 0);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
ReorderToMatchIterationWithAddition(this->m_testCollection);
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->GetBaseIterator(0), this->m_testCollection.end(),
this->m_testPredicate);
AZStd::generate_n(view.begin(), 2, [](){ return 42; });
EXPECT_EQ(42, *this->GetBaseIterator(0));
EXPECT_EQ(1, *this->GetBaseIterator(1));
EXPECT_EQ(42, *this->GetBaseIterator(2));
}
TYPED_TEST_P(FilterIteratorBasicTests,
Algorithms_PartialSortCopyFilteredContainer_AllValuesLargerOrEqualThan10AreCopiedAndSorted)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(10);
AddElement(this->m_testCollection, 18);
AddElement(this->m_testCollection, 42);
AddElement(this->m_testCollection, 36);
AddElement(this->m_testCollection, 9);
AddElement(this->m_testCollection, 88);
AddElement(this->m_testCollection, 3);
AZStd::vector<int> results;
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->m_testCollection.begin(), this->m_testCollection.end(), this->m_testPredicate);
AZStd::copy(view.begin(), view.end(), AZStd::back_inserter(results));
for (auto val : results)
{
EXPECT_GE(val, 10);
}
}
REGISTER_TYPED_TEST_CASE_P(FilterIteratorBasicTests,
Constructor_InputIsEmptyValidBaseIterator_NoCrash,
OperatorStar_GetValueByDereferencingIterator_ExpectFirstValueInArray,
Constructor_MovesForwardBasedOnPredicate_ExpectSkipFirstEntryAndReturnSecond,
OperatorPreIncrement_MoveOneUnfilteredElementUp_ReturnsTheSecondValue,
OperatorPreIncrement_MoveOneSkippingOne_ReturnsTheThirdValue,
OperatorPostIncrement_MoveOneUnfilteredElementUp_ReturnsTheSecondValue,
OperatorPostIncrement_MoveOneSkippingOne_ReturnsTheThirdValue,
OperatorEqualsEquals_DifferentlyInitializedObjectsPredicatePassesAll_ReturnsFalse,
OperatorEqualsEquals_DifferentlyInitializedObjectsPredicatePassesPart_ReturnsTrue,
OperatorEqualsEquals_SkippingAllEntriesMatchesWithEndIterator_FullySkippedIteratorIsSameAsEnd,
OperatorNotEquals_DifferentObjects_ReturnsTrue,
OperatorDecrement_MoveOneUnfilteredElementDown_ReturnsTheFirstValue,
OperatorDecrement_MoveOneFilteredElementDown_ReturnsTheFirstValue,
OperatorDecrement_MoveDownToLastFilteredElement_ExpectToStayOnCurrentElement,
OperatorDecrement_MoveOneUnfilteredElementDownFromEnd_ReturnsTheSecondValue,
MakeFilterView_InputIsIterator_CorrectFilteredElements,
MakeFilterView_InputIteratorNotStartsAtBegin_CorrectFilteredElements,
Algorithms_CopyFilteredContainer_ContainerIsCopiedWithoutFilteredValue,
Algorithms_FillFilteredContainer_AllValuesAreSetTo42ExceptFilteredValue,
Algorithms_PartialSortCopyFilteredContainer_AllValuesLargerOrEqualThan10AreCopiedAndSorted
);
INSTANTIATE_TYPED_TEST_CASE_P(CommonTests,
FilterIteratorBasicTests,
BasicCollectionTypes);
// Map iterator tests
template<typename CollectionType>
class FilterIteratorMapTests
: public IteratorTypedTestsBase<CollectionType>
{
public:
FilterIteratorMapTests()
{
this->MakeComparePredicate(0);
}
~FilterIteratorMapTests() override = default;
protected:
using BaseIteratorReference = typename IteratorTypedTestsBase<CollectionType>::BaseIteratorReference;
template<typename T>
void MakeComparePredicate(T compareValue)
{
m_testPredicate = [compareValue](const BaseIteratorReference value) -> bool
{
return value.first >= compareValue;
};
}
AZStd::function<bool(const BaseIteratorReference)> m_testPredicate;
};
TYPED_TEST_CASE_P(FilterIteratorMapTests);
TYPED_TEST_P(FilterIteratorMapTests,
MakeFilterView_InputIsIterator_CorrectFilteredElements)
{
using BaseIterator = typename IteratorTypedTestsBase<TypeParam>::BaseIterator;
this->MakeComparePredicate(2);
AddElement(this->m_testCollection, 1);
AddElement(this->m_testCollection, 2);
AddElement(this->m_testCollection, 3);
AZStd::unordered_set<int> expectedElements = { 2, 3 };
View<FilterIterator<BaseIterator> > view = MakeFilterView(this->m_testCollection.begin(), this->m_testCollection.end(),
this->m_testPredicate);
for (auto it : view)
{
if (expectedElements.find(it.first) != expectedElements.end())
{
expectedElements.erase(it.first);
}
}
EXPECT_TRUE(expectedElements.empty());
}
REGISTER_TYPED_TEST_CASE_P(FilterIteratorMapTests,
MakeFilterView_InputIsIterator_CorrectFilteredElements
);
INSTANTIATE_TYPED_TEST_CASE_P(CommonTests,
FilterIteratorMapTests,
MapCollectionTypes);
// Added as separate test to avoid having to write another set of specialized templates.
TEST(FilterIteratorTests, Algorithms_ReverseFilteredContainer_ValuesReversedExceptValuesLargerThan50)
{
AZStd::vector<int> values = { 18, 7, 62, 63, 14 };
View<FilterIterator<AZStd::vector<int>::iterator> > view = MakeFilterView(values.begin(), values.end(),
[](int value) -> bool
{
return value < 50;
});
AZStd::reverse(view.begin(), view.end());
EXPECT_EQ(values[0], 14);
EXPECT_EQ(values[1], 7);
EXPECT_EQ(values[2], 62);
EXPECT_EQ(values[3], 63);
EXPECT_EQ(values[4], 18);
}
}
}
}
}
#undef _SCL_SECURE_NO_WARNINGS
| 46.434853 | 163 | 0.557118 | cypherdotXd |
b82924fb36df65496b699a7d66dbbd0b683c3b69 | 5,584 | cc | C++ | src/yb/common/placement_info.cc | polarweasel/yugabyte-db | 9064eca9dc35769cf6b034e537ee42efed03c47d | [
"Apache-2.0",
"CC0-1.0"
] | 4 | 2019-07-19T12:55:40.000Z | 2021-03-25T15:59:09.000Z | src/yb/common/placement_info.cc | polarweasel/yugabyte-db | 9064eca9dc35769cf6b034e537ee42efed03c47d | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/yb/common/placement_info.cc | polarweasel/yugabyte-db | 9064eca9dc35769cf6b034e537ee42efed03c47d | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2021-08-23T10:06:40.000Z | 2021-08-23T10:06:40.000Z | //--------------------------------------------------------------------------------------------------
// Copyright (c) Yugabyte, 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 "yb/common/placement_info.h"
#include <boost/algorithm/string/predicate.hpp>
#include <rapidjson/document.h>
#include "yb/gutil/strings/split.h"
#include "yb/util/status.h"
namespace yb {
namespace {
bool IsReplicaPlacementOption(const string& option) {
return boost::starts_with(option, "replica_placement");
}
} // namespace
Result<PlacementInfoConverter::Placement> PlacementInfoConverter::FromJson(
const string& placement_str, const rapidjson::Document& placement) {
std::vector<PlacementInfo> placement_infos;
// Parse the number of replicas
if (!placement.HasMember("num_replicas") || !placement["num_replicas"].IsInt()) {
return STATUS_FORMAT(Corruption,
"Invalid value found for \"num_replicas\" field in the placement "
"policy: $0", placement_str);
}
const int num_replicas = placement["num_replicas"].GetInt();
// Parse the placement blocks.
if (!placement.HasMember("placement_blocks") ||
!placement["placement_blocks"].IsArray()) {
return STATUS_FORMAT(Corruption,
"\"placement_blocks\" field not found in the placement policy: $0",
placement_str);
}
const rapidjson::Value& pb = placement["placement_blocks"];
if (pb.Size() < 1) {
return STATUS_FORMAT(Corruption,
"\"placement_blocks\" field has empty value in the placement "
"policy: $0", placement_str);
}
int64 total_min_replicas = 0;
for (int64 i = 0; i < pb.Size(); ++i) {
const rapidjson::Value& placement = pb[i];
if (!placement.HasMember("cloud") || !placement.HasMember("region") ||
!placement.HasMember("zone") || !placement.HasMember("min_num_replicas")) {
return STATUS_FORMAT(Corruption,
"Missing keys in replica placement option: $0", placement_str);
}
if (!placement["cloud"].IsString() || !placement["region"].IsString() ||
!placement["zone"].IsString() || !placement["min_num_replicas"].IsInt()) {
return STATUS_FORMAT(Corruption,
"Invalid value for replica_placement option: $0", placement_str);
}
const int min_rf = placement["min_num_replicas"].GetInt();
placement_infos.emplace_back(PlacementInfo {
.cloud = placement["cloud"].GetString(),
.region = placement["region"].GetString(),
.zone = placement["zone"].GetString(),
.min_num_replicas = min_rf,
});
total_min_replicas += min_rf;
}
if (total_min_replicas > num_replicas) {
return STATUS_FORMAT(Corruption,
"Sum of min_num_replicas fields exceeds the total replication factor "
"in the placement policy: $0", placement_str);
}
return PlacementInfoConverter::Placement{
.placement_infos = std::move(placement_infos),
.num_replicas = num_replicas,
};
}
// TODO(#10869): improve JSON parsing
Result<PlacementInfoConverter::Placement> PlacementInfoConverter::FromString(
const std::string& placement) {
rapidjson::Document document;
// The only tablespace option supported today is "replica_placement" that allows specification
// of placement policies encoded as a JSON array. Example value:
// replica_placement=
// '{"num_replicas":3, "placement_blocks": [
// {"cloud":"c1", "region":"r1", "zone":"z1", "min_num_replicas":1},
// {"cloud":"c2", "region":"r2", "zone":"z2", "min_num_replicas":1},
// {"cloud":"c3", "region":"r3", "zone":"z3", "min_num_replicas":1}]}'
if (!IsReplicaPlacementOption(placement)) {
return STATUS(InvalidArgument, "Invalid option found in spcoptions: $0", placement);
}
// First split the string and get only the json value in a string.
vector<string> split;
split = strings::Split(placement, "replica_placement=", strings::SkipEmpty());
if (split.size() != 1) {
return STATUS_FORMAT(Corruption, "replica_placement option illformed: $0", placement);
}
auto replica_placement = split[0].c_str();
if (document.Parse(replica_placement).HasParseError() || !document.IsObject()) {
return STATUS_FORMAT(Corruption,
"Json parsing of replica placement option failed: $0", split[0]);
}
return FromJson(replica_placement, document);
}
Result<PlacementInfoConverter::Placement> PlacementInfoConverter::FromQLValue(
const vector<QLValuePB>& placement) {
// Today only one option is supported, so this array should have only one option.
if (placement.size() != 1) {
return STATUS_FORMAT(Corruption,
"Unexpected number of options: $0", placement.size());
}
const string& option = placement[0].string_value();
return FromString(option);
}
} // namespace yb
| 40.172662 | 100 | 0.643446 | polarweasel |
b82b4c3f15bb1184cac9ddee7c09be4d04bd31cd | 16,663 | cpp | C++ | Engine/Source/Runtime/Renderer/Private/MobileReflectionEnvironmentCapture.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Renderer/Private/MobileReflectionEnvironmentCapture.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Renderer/Private/MobileReflectionEnvironmentCapture.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
=============================================================================*/
#include "MobileReflectionEnvironmentCapture.h"
#include "ReflectionEnvironmentCapture.h"
#include "ShaderParameterUtils.h"
#include "RHIStaticStates.h"
#include "SceneRenderTargets.h"
#include "SceneUtils.h"
#include "ScreenRendering.h"
#include "PipelineStateCache.h"
#include "SceneFilterRendering.h"
#include "OneColorShader.h"
extern int32 GDiffuseIrradianceCubemapSize;
extern float ComputeSingleAverageBrightnessFromCubemap(FRHICommandListImmediate& RHICmdList, ERHIFeatureLevel::Type FeatureLevel, int32 TargetSize, FSceneRenderTargetItem& Cubemap);
extern void FullyResolveReflectionScratchCubes(FRHICommandListImmediate& RHICmdList);
class FMobileDownsamplePS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FMobileDownsamplePS, Global);
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsMobilePlatform(Platform);
}
FMobileDownsamplePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer) :
FGlobalShader(Initializer)
{
CubeFace.Bind(Initializer.ParameterMap, TEXT("CubeFace"));
SourceMipIndex.Bind(Initializer.ParameterMap, TEXT("SourceMipIndex"));
SourceTexture.Bind(Initializer.ParameterMap, TEXT("SourceTexture"));
SourceTextureSampler.Bind(Initializer.ParameterMap, TEXT("SourceTextureSampler"));
}
FMobileDownsamplePS() {}
void SetParameters(FRHICommandList& RHICmdList, int32 CubeFaceValue, int32 SourceMipIndexValue, FSceneRenderTargetItem& SourceTextureValue)
{
SetShaderValue(RHICmdList, GetPixelShader(), CubeFace, CubeFaceValue);
SetShaderValue(RHICmdList, GetPixelShader(), SourceMipIndex, SourceMipIndexValue);
SetTextureParameter(
RHICmdList,
GetPixelShader(),
SourceTexture,
SourceTextureSampler,
TStaticSamplerState<SF_Bilinear, AM_Clamp, AM_Clamp, AM_Clamp>::GetRHI(),
SourceTextureValue.ShaderResourceTexture);
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << CubeFace;
Ar << SourceMipIndex;
Ar << SourceTexture;
Ar << SourceTextureSampler;
return bShaderHasOutdatedParameters;
}
private:
FShaderParameter CubeFace;
FShaderParameter SourceMipIndex;
FShaderResourceParameter SourceTexture;
FShaderResourceParameter SourceTextureSampler;
};
IMPLEMENT_SHADER_TYPE(, FMobileDownsamplePS, TEXT("/Engine/Private/ReflectionEnvironmentShaders.usf"), TEXT("DownsamplePS_Mobile"), SF_Pixel);
namespace MobileReflectionEnvironmentCapture
{
/** Encapsulates render target picking logic for cubemap mip generation. */
FSceneRenderTargetItem& GetEffectiveRenderTarget(FSceneRenderTargets& SceneContext, bool bDownsamplePass, int32 TargetMipIndex)
{
int32 ScratchTextureIndex = TargetMipIndex % 2;
if (!bDownsamplePass)
{
ScratchTextureIndex = 1 - ScratchTextureIndex;
}
return SceneContext.ReflectionColorScratchCubemap[ScratchTextureIndex]->GetRenderTargetItem();
}
/** Encapsulates source texture picking logic for cubemap mip generation. */
FSceneRenderTargetItem& GetEffectiveSourceTexture(FSceneRenderTargets& SceneContext, bool bDownsamplePass, int32 TargetMipIndex)
{
int32 ScratchTextureIndex = TargetMipIndex % 2;
if (bDownsamplePass)
{
ScratchTextureIndex = 1 - ScratchTextureIndex;
}
return SceneContext.ReflectionColorScratchCubemap[ScratchTextureIndex]->GetRenderTargetItem();
}
void ComputeAverageBrightness(FRHICommandListImmediate& RHICmdList, ERHIFeatureLevel::Type FeatureLevel, int32 CubmapSize, float& OutAverageBrightness)
{
SCOPED_DRAW_EVENT(RHICmdList, ComputeAverageBrightness);
const int32 EffectiveTopMipSize = CubmapSize;
const int32 NumMips = FMath::CeilLogTwo(EffectiveTopMipSize) + 1;
// necessary to resolve the clears which touched all the mips. scene rendering only resolves mip 0.
FullyResolveReflectionScratchCubes(RHICmdList);
auto ShaderMap = GetGlobalShaderMap(FeatureLevel);
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
{
SCOPED_DRAW_EVENT(RHICmdList, DownsampleCubeMips);
// Downsample all the mips, each one reads from the mip above it
for (int32 MipIndex = 1; MipIndex < NumMips; MipIndex++)
{
const int32 SourceMipIndex = FMath::Max(MipIndex - 1, 0);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
FSceneRenderTargetItem& EffectiveRT = GetEffectiveRenderTarget(SceneContext, true, MipIndex);
FSceneRenderTargetItem& EffectiveSource = GetEffectiveSourceTexture(SceneContext, true, MipIndex);
check(EffectiveRT.TargetableTexture != EffectiveSource.ShaderResourceTexture);
for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++)
{
SetRenderTarget(RHICmdList, EffectiveRT.TargetableTexture, MipIndex, CubeFace, NULL, true);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
const FIntRect ViewRect(0, 0, MipSize, MipSize);
RHICmdList.SetViewport(0, 0, 0.0f, MipSize, MipSize, 1.0f);
TShaderMapRef<FScreenVS> VertexShader(ShaderMap);
TShaderMapRef<FMobileDownsamplePS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, CubeFace, SourceMipIndex, EffectiveSource);
DrawRectangle(
RHICmdList,
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
FIntPoint(ViewRect.Width(), ViewRect.Height()),
FIntPoint(MipSize, MipSize),
*VertexShader);
RHICmdList.CopyToResolveTarget(EffectiveRT.TargetableTexture, EffectiveRT.ShaderResourceTexture, true, FResolveParams(FResolveRect(), (ECubeFace)CubeFace, MipIndex));
}
}
}
OutAverageBrightness = ComputeSingleAverageBrightnessFromCubemap(RHICmdList, FeatureLevel, CubmapSize, GetEffectiveRenderTarget(FSceneRenderTargets::Get(RHICmdList), true, NumMips - 1));
}
void CopyToSkyTexture(FRHICommandList& RHICmdList, FScene* Scene, FTexture* ProcessedTexture)
{
SCOPED_DRAW_EVENT(RHICmdList, CopyToSkyTexture);
if (ProcessedTexture->TextureRHI)
{
const int32 EffectiveTopMipSize = ProcessedTexture->GetSizeX();
const int32 NumMips = FMath::CeilLogTwo(EffectiveTopMipSize) + 1;
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
// GPU copy back to the skylight's texture, which is not a render target
for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++)
{
// The source for this copy is the dest from the filtering pass
FSceneRenderTargetItem& EffectiveSource = GetEffectiveRenderTarget(SceneContext, false, MipIndex);
for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++)
{
RHICmdList.CopyToResolveTarget(EffectiveSource.ShaderResourceTexture, ProcessedTexture->TextureRHI, true, FResolveParams(FResolveRect(), (ECubeFace)CubeFace, MipIndex, 0, 0));
}
}
}
}
/** Generates mips for glossiness and filters the cubemap for a given reflection. */
void FilterReflectionEnvironment(FRHICommandListImmediate& RHICmdList, ERHIFeatureLevel::Type FeatureLevel, int32 CubmapSize, FSHVectorRGB3* OutIrradianceEnvironmentMap)
{
SCOPED_DRAW_EVENT(RHICmdList, FilterReflectionEnvironment);
const int32 EffectiveTopMipSize = CubmapSize;
const int32 NumMips = FMath::CeilLogTwo(EffectiveTopMipSize) + 1;
FSceneRenderTargetItem& EffectiveColorRT = FSceneRenderTargets::Get(RHICmdList).ReflectionColorScratchCubemap[0]->GetRenderTargetItem();
// Premultiply alpha in-place using alpha blending
for (uint32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++)
{
SetRenderTarget(RHICmdList, EffectiveColorRT.TargetableTexture, 0, CubeFace, NULL, true);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.BlendState = TStaticBlendState<CW_RGBA, BO_Add, BF_Zero, BF_DestAlpha, BO_Add, BF_Zero, BF_One>::GetRHI();
const FIntPoint SourceDimensions(CubmapSize, CubmapSize);
const FIntRect ViewRect(0, 0, EffectiveTopMipSize, EffectiveTopMipSize);
RHICmdList.SetViewport(0, 0, 0.0f, EffectiveTopMipSize, EffectiveTopMipSize, 1.0f);
TShaderMapRef<FScreenVS> VertexShader(GetGlobalShaderMap(FeatureLevel));
TShaderMapRef<FOneColorPS> PixelShader(GetGlobalShaderMap(FeatureLevel));
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
FLinearColor UnusedColors[1] = { FLinearColor::Black };
PixelShader->SetColors(RHICmdList, UnusedColors, ARRAY_COUNT(UnusedColors));
DrawRectangle(
RHICmdList,
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
0, 0,
SourceDimensions.X, SourceDimensions.Y,
FIntPoint(ViewRect.Width(), ViewRect.Height()),
SourceDimensions,
*VertexShader);
RHICmdList.CopyToResolveTarget(EffectiveColorRT.TargetableTexture, EffectiveColorRT.ShaderResourceTexture, true, FResolveParams(FResolveRect(), (ECubeFace)CubeFace));
}
int32 DiffuseConvolutionSourceMip = INDEX_NONE;
FSceneRenderTargetItem* DiffuseConvolutionSource = NULL;
auto ShaderMap = GetGlobalShaderMap(FeatureLevel);
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
{
SCOPED_DRAW_EVENT(RHICmdList, DownsampleCubeMips);
// Downsample all the mips, each one reads from the mip above it
for (int32 MipIndex = 1; MipIndex < NumMips; MipIndex++)
{
SCOPED_DRAW_EVENT(RHICmdList, DownsampleCubeMip);
const int32 SourceMipIndex = FMath::Max(MipIndex - 1, 0);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
FSceneRenderTargetItem& EffectiveRT = GetEffectiveRenderTarget(SceneContext, true, MipIndex);
FSceneRenderTargetItem& EffectiveSource = GetEffectiveSourceTexture(SceneContext, true, MipIndex);
check(EffectiveRT.TargetableTexture != EffectiveSource.ShaderResourceTexture);
for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++)
{
SetRenderTarget(RHICmdList, EffectiveRT.TargetableTexture, MipIndex, CubeFace, NULL, true);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
const FIntRect ViewRect(0, 0, MipSize, MipSize);
RHICmdList.SetViewport(0, 0, 0.0f, MipSize, MipSize, 1.0f);
TShaderMapRef<FScreenVS> VertexShader(ShaderMap);
TShaderMapRef<FMobileDownsamplePS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, CubeFace, SourceMipIndex, EffectiveSource);
DrawRectangle(
RHICmdList,
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
FIntPoint(ViewRect.Width(), ViewRect.Height()),
FIntPoint(MipSize, MipSize),
*VertexShader);
RHICmdList.CopyToResolveTarget(EffectiveRT.TargetableTexture, EffectiveRT.ShaderResourceTexture, true, FResolveParams(FResolveRect(), (ECubeFace)CubeFace, MipIndex));
}
if (MipSize == GDiffuseIrradianceCubemapSize)
{
DiffuseConvolutionSourceMip = MipIndex;
DiffuseConvolutionSource = &EffectiveRT;
}
}
}
if (OutIrradianceEnvironmentMap)
{
SCOPED_DRAW_EVENT(RHICmdList, ComputeDiffuseIrradiance);
check(DiffuseConvolutionSource != NULL);
ComputeDiffuseIrradiance(RHICmdList, FeatureLevel, DiffuseConvolutionSource->ShaderResourceTexture, DiffuseConvolutionSourceMip, OutIrradianceEnvironmentMap);
}
{
SCOPED_DRAW_EVENT(RHICmdList, FilterCubeMap);
// Filter all the mips, each one reads from whichever scratch render target holds the downsampled contents, and writes to the destination cubemap
for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++)
{
SCOPED_DRAW_EVENT(RHICmdList, FilterCubeMip);
FSceneRenderTargetItem& EffectiveRT = GetEffectiveRenderTarget(SceneContext, false, MipIndex);
FSceneRenderTargetItem& EffectiveSource = GetEffectiveSourceTexture(SceneContext, false, MipIndex);
check(EffectiveRT.TargetableTexture != EffectiveSource.ShaderResourceTexture);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++)
{
SetRenderTarget(RHICmdList, EffectiveRT.TargetableTexture, MipIndex, CubeFace, NULL, true);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
const FIntRect ViewRect(0, 0, MipSize, MipSize);
RHICmdList.SetViewport(0, 0, 0.0f, MipSize, MipSize, 1.0f);
TShaderMapRef<FScreenVS> VertexShader(GetGlobalShaderMap(FeatureLevel));
TShaderMapRef< TCubeFilterPS<1> > CaptureCubemapArrayPixelShader(GetGlobalShaderMap(FeatureLevel));
FCubeFilterPS* PixelShader;
PixelShader = *TShaderMapRef< TCubeFilterPS<0> >(ShaderMap);
check(PixelShader);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
{
const FPixelShaderRHIParamRef ShaderRHI = PixelShader->GetPixelShader();
SetShaderValue(RHICmdList, ShaderRHI, PixelShader->CubeFace, CubeFace);
SetShaderValue(RHICmdList, ShaderRHI, PixelShader->MipIndex, MipIndex);
SetShaderValue(RHICmdList, ShaderRHI, PixelShader->NumMips, NumMips);
SetTextureParameter(
RHICmdList,
ShaderRHI,
PixelShader->SourceTexture,
PixelShader->SourceTextureSampler,
TStaticSamplerState<SF_Trilinear, AM_Clamp, AM_Clamp, AM_Clamp>::GetRHI(),
EffectiveSource.ShaderResourceTexture);
}
//PixelShader->SetParameters(RHICmdList, NumMips, CubeFace, MipIndex, EffectiveSource);
DrawRectangle(
RHICmdList,
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
ViewRect.Min.X, ViewRect.Min.Y,
ViewRect.Width(), ViewRect.Height(),
FIntPoint(ViewRect.Width(), ViewRect.Height()),
FIntPoint(MipSize, MipSize),
*VertexShader);
RHICmdList.CopyToResolveTarget(EffectiveRT.TargetableTexture, EffectiveRT.ShaderResourceTexture, true, FResolveParams(FResolveRect(), (ECubeFace)CubeFace, MipIndex));
}
}
}
}
}
| 43.393229 | 188 | 0.77171 | windystrife |
b82e11dc7a2ace56a749d7832aa7d3bb29563874 | 1,030 | cpp | C++ | core/src/Graphics/Color.cpp | gon6109/Altseed2 | 976cd17f337575a221e9f8dab0df4063e2ded235 | [
"Apache-2.0"
] | 29 | 2019-05-26T10:12:43.000Z | 2021-06-24T03:35:03.000Z | core/src/Graphics/Color.cpp | gon6109/Altseed2 | 976cd17f337575a221e9f8dab0df4063e2ded235 | [
"Apache-2.0"
] | 448 | 2019-10-14T03:19:25.000Z | 2022-03-30T15:30:33.000Z | core/src/Graphics/Color.cpp | gon6109/Altseed2 | 976cd17f337575a221e9f8dab0df4063e2ded235 | [
"Apache-2.0"
] | 18 | 2019-06-10T11:15:17.000Z | 2022-03-27T00:49:27.000Z | #include "Color.h"
#include "Graphics.h"
namespace Altseed2 {
Color::Color() : A(TextureDefaultColor), R(TextureDefaultColor), G(TextureDefaultColor), B(TextureDefaultColor) {}
Color::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a) : A(a), R(r), G(g), B(b) {}
Color Color::operator*(const Color& right) {
return Color(
R * right.R / TextureDefaultColor,
G * right.G / TextureDefaultColor,
B * right.B / TextureDefaultColor,
A * right.A / TextureDefaultColor);
}
Color& Color::operator*=(const Color& right) {
R = R * right.R / TextureDefaultColor;
G = G * right.G / TextureDefaultColor;
B = B * right.B / TextureDefaultColor;
A = A * right.A / TextureDefaultColor;
return *this;
}
bool Color::operator==(const Color& right) { return R == right.R && G == right.G && B == right.B && A == right.A; }
Color::operator Color_C() const { return Color_C{R, G, B, A}; }
Color_C::operator Color() const { return Color(R, G, B, A); }
} // namespace Altseed2 | 33.225806 | 115 | 0.631068 | gon6109 |
b83058b31b94eb3c8d13f0dbab2514f00cf7ab38 | 251 | hpp | C++ | book/cpp_templates/tmplbook/basics/boolstring.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/basics/boolstring.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/basics/boolstring.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | class BoolString {
private:
std::string value;
public:
BoolString (std::string const& s)
: value(s) {
}
template<typename T = std::string>
T get() const { // get value (converted to T)
return value;
}
};
| 19.307692 | 57 | 0.553785 | houruixiang |
b8308bc07a36798b295c2d51b1bd93ffa8067edb | 213 | hpp | C++ | game.hpp | comprogger/Space-Opera | 2ff1d62689c31fcf4878d4255125e82136b94d5e | [
"Artistic-2.0"
] | null | null | null | game.hpp | comprogger/Space-Opera | 2ff1d62689c31fcf4878d4255125e82136b94d5e | [
"Artistic-2.0"
] | 1 | 2016-06-01T22:47:33.000Z | 2016-06-01T22:47:33.000Z | game.hpp | comprogger/Space-Opera | 2ff1d62689c31fcf4878d4255125e82136b94d5e | [
"Artistic-2.0"
] | null | null | null | #ifndef GAME_HPP_INCLUDED
#define GAME_HPP_INCLUDED
#include <SFML/Graphics.hpp>
class Game{
public:
static void Start();
private:
static sf::RenderWindow app;
sf::View view1;
};
#endif // GAME_HPP_INCLUDED
| 16.384615 | 28 | 0.755869 | comprogger |
b831ea1e4e61bbd2a76fa445087f7ab49cd35239 | 3,495 | cc | C++ | src/proof_stat_collector.cc | rcurtin/drat2er | 77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76 | [
"MIT"
] | 1 | 2019-12-24T18:37:34.000Z | 2019-12-24T18:37:34.000Z | src/proof_stat_collector.cc | rcurtin/drat2er | 77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76 | [
"MIT"
] | 4 | 2018-09-23T23:44:59.000Z | 2019-01-22T17:32:10.000Z | src/proof_stat_collector.cc | rcurtin/drat2er | 77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76 | [
"MIT"
] | 2 | 2018-12-13T22:39:55.000Z | 2021-08-09T21:06:48.000Z | // MIT License
//
// Copyright (c) 2018 Benjamin Kiesl
//
// 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 "proof_stat_collector.h"
#include <string>
#include <algorithm>
#include <memory>
#include "formula.h"
#include "clause.h"
#include "rat_clause.h"
#include "rup_clause.h"
#include "deletion.h"
#include "lrat_parser.h"
using std::string;
using std::shared_ptr;
using std::max;
namespace drat2er
{
ProofStatCollector::ProofStatCollector(shared_ptr<Formula> formula) :
formula_ {formula},
max_variable_ {0},
max_instruction_ {0},
number_of_instructions_ {0},
number_of_proper_rat_additions_ {0},
number_of_rup_additions_ {0},
number_of_deletions_ {0}
{ }
int ProofStatCollector::GetMaxVariable() const
{
return max_variable_;
}
int ProofStatCollector::GetMaxInstruction() const
{
return max_instruction_;
}
int ProofStatCollector::GetNumberOfInstructions() const
{
return number_of_instructions_;
}
int ProofStatCollector::GetNumberOfProperRatAdditions() const
{
return number_of_proper_rat_additions_;
}
int ProofStatCollector::GetNumberOfRupAdditions() const
{
return number_of_rup_additions_;
}
int ProofStatCollector::GetNumberOfDeletions() const
{
return number_of_deletions_;
}
int ProofStatCollector::GetNumberOfExtensionClauses() const
{
return number_of_extension_clauses_;
}
void ProofStatCollector::ObserveDeletion(const Deletion& deletion)
{
max_instruction_ = max(max_instruction_, deletion.GetIndex());
number_of_instructions_++;
number_of_deletions_++;
}
void ProofStatCollector::ObserveProperRatAddition(const RatClause& rat)
{
UpdateInstructionAndMaxVariableStats(rat);
number_of_proper_rat_additions_++;
}
void ProofStatCollector::ObserveRupAddition(const RupClause& rup)
{
UpdateInstructionAndMaxVariableStats(rup);
number_of_rup_additions_++;
}
void ProofStatCollector::ObserveComment(const string& comment_line)
{
// do nothing
}
void ProofStatCollector::ObserveExtension(const Clause& definition_clause)
{
UpdateInstructionAndMaxVariableStats(definition_clause);
number_of_extension_clauses_++;
}
void ProofStatCollector::UpdateInstructionAndMaxVariableStats(
const Clause& clause)
{
max_instruction_ = max(max_instruction_, clause.GetIndex());
max_variable_ = max(max_variable_, clause.GetMaxVariable());
number_of_instructions_++;
}
} // namespace drat2er
| 27.96 | 79 | 0.762232 | rcurtin |
b836de530818bb730f484311be23e725c3afda4c | 1,368 | cxx | C++ | src/internal/1m/dot.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 86 | 2016-05-30T16:08:24.000Z | 2022-03-30T22:57:35.000Z | src/internal/1m/dot.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 41 | 2017-02-02T22:28:17.000Z | 2022-02-22T16:51:14.000Z | src/internal/1m/dot.cxx | devinamatthews/tensor | 7d979b6624071879383377611cb2fa483b6a3104 | [
"BSD-3-Clause"
] | 26 | 2016-05-30T16:08:33.000Z | 2021-12-29T03:02:30.000Z | #include "dot.hpp"
namespace tblis
{
namespace internal
{
template <typename T>
void dot(const communicator& comm, const config& cfg, len_type m, len_type n,
bool conj_A, const T* A, stride_type rs_A, stride_type cs_A,
bool conj_B, const T* B, stride_type rs_B, stride_type cs_B, T& result)
{
if (rs_B > cs_B)
{
std::swap(m, n);
std::swap(rs_A, cs_A);
std::swap(rs_B, cs_B);
}
atomic_accumulator<T> local_result;
comm.distribute_over_threads(m, n,
[&](len_type m_min, len_type m_max, len_type n_min, len_type n_max)
{
T micro_result = T();
for (len_type j = n_min;j < n_max;j++)
{
cfg.dot_ukr.call<T>(m_max-m_min,
conj_A, A + m_min*rs_A + j*cs_A, rs_A,
conj_B, B + m_min*rs_B + j*cs_B, rs_B, micro_result);
}
local_result += micro_result;
});
reduce(comm, local_result);
if (comm.master()) result = local_result;
comm.barrier();
}
#define FOREACH_TYPE(T) \
template void dot(const communicator& comm, const config& cfg, len_type m, len_type n, \
bool conj_A, const T* A, stride_type rs_A, stride_type cs_A, \
bool conj_B, const T* B, stride_type rs_B, stride_type cs_B, T& result);
#include "configs/foreach_type.h"
}
}
| 26.823529 | 90 | 0.592105 | devinamatthews |
b837888b908cd351f7a3ae13c5f4470191869aba | 868 | cpp | C++ | C++/Codeforces/cf617A.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Codeforces/cf617A.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Codeforces/cf617A.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
typedef unsigned long long ul;
typedef long long ll;
using namespace std;
ll t, n;
int main(){
ios_base::sync_with_stdio(0); cin.tie(); cout.tie();
cin >> t;
while(t--)
{
cin >> n;
ll a[n];
ll even = 0;
ll odd = 0;
ll s = 0;
for (ll i = 0; i < n; i++)
{
cin >> a[i];
s += a[i];
if (a[i] % 2 == 0)
even++;
else
odd++;
}
if (s % 2 == 1)
{
cout << "YES\n";
continue;
}
else if (even == 0 || odd == 0)
{
cout << "NO\n";
continue;
}
else
cout << "YES\n";
}
return 0;
}
| 18.083333 | 56 | 0.353687 | Nicu-Ducal |
b83b9d79495d47c49ed32a1dbc8c36093d718ad6 | 1,567 | cpp | C++ | BurningGround/src/hooks/consume.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 8 | 2015-04-03T16:50:59.000Z | 2021-01-06T17:12:29.000Z | BurningGround/src/hooks/consume.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-03T18:10:56.000Z | 2016-02-18T05:04:21.000Z | BurningGround/src/hooks/consume.cpp | idmontie/gptp | 14d68e5eac84c2f3085ac25a7fff31a07ea387f6 | [
"0BSD"
] | 6 | 2015-04-04T04:37:33.000Z | 2018-04-09T09:03:50.000Z | #include "consume.h"
#include "max_unit_energy.h"
#include "../SCBW/api.h"
#include "../SCBW/scbwdata.h"
#include "../SCBW/enumerations.h"
/// Helper function: Sets death scores for [unit] owned by [player].
void incrementDeathScores(const CUnit *unit, u8 player);
/// Decides whether the given unit can be Consumed.
bool unitIsConsumable(const CUnit* unit, u8 consumingPlayer) {
using Unit::BaseProperty;
using Unit::GroupFlags;
using UnitProperty::Building;
//Default StarCraft behavior
return !(BaseProperty[unit->id] & Building) //Cannot consume buildings
&& unit->playerId == consumingPlayer //Must be owned by the current player
&& GroupFlags[unit->id].isZerg //Must be a Zerg unit
&& unit->id != UnitId::larva; //Cannot consume larvae
}
/// Is called when a unit is consumed.
void onConsumeUnit(CUnit* caster, CUnit *target) {
//Default StarCraft behavior
incrementDeathScores(target, caster->playerId);
target->remove();
if (!(target->status & UnitStatus::IsHallucination)) { //If not a hallucination
u16 energy = caster->energy + 12800; //50 energy
u16 maxEnergy = getUnitMaxEnergy(caster);
if (energy > maxEnergy)
energy = maxEnergy;
caster->energy = energy;
}
}
/**** Definitions of helper functions. Do not edit anything below this! ****/
void incrementDeathScores(const CUnit *unit, u8 player) {
__asm {
PUSHAD
MOV EDI, unit
MOVZX EDX, player
CALL offsets::Util_IncrementDeathScores
POPAD
}
}
| 31.34 | 86 | 0.668794 | idmontie |
b83cafb7bb44272086953fc5bb485628de372e86 | 3,872 | cc | C++ | backend/schema/verifiers/foreign_key_verifiers_test.cc | sgorse12/cloud-spanner-emulator | 13ebb6d42867bfbc80224b4a74a896b683ae4555 | [
"Apache-2.0"
] | 179 | 2020-03-30T20:30:49.000Z | 2022-03-31T04:47:55.000Z | backend/schema/verifiers/foreign_key_verifiers_test.cc | sgorse12/cloud-spanner-emulator | 13ebb6d42867bfbc80224b4a74a896b683ae4555 | [
"Apache-2.0"
] | 53 | 2020-08-31T15:14:30.000Z | 2022-03-30T21:28:36.000Z | backend/schema/verifiers/foreign_key_verifiers_test.cc | sgorse12/cloud-spanner-emulator | 13ebb6d42867bfbc80224b4a74a896b683ae4555 | [
"Apache-2.0"
] | 26 | 2020-04-02T04:05:58.000Z | 2022-02-22T12:05:55.000Z | //
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "backend/schema/verifiers/foreign_key_verifiers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "zetasql/base/testing/status_matchers.h"
#include "tests/common/proto_matchers.h"
#include "backend/database/database.h"
#include "backend/transaction/options.h"
#include "backend/transaction/read_write_transaction.h"
#include "common/clock.h"
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
namespace {
using zetasql::values::Int64;
using zetasql::values::NullInt64;
using zetasql_base::testing::StatusIs;
// Unit tests for the foreign key verifier. These include branch coverage of the
// verifier code. Separate conformance tests cover more detailed end-to-end
// tests for different foreign key shapes and initial data states.
class ForeignKeyVerifiersTest : public ::testing::Test {
protected:
void SetUp() override {
ZETASQL_ASSERT_OK(CreateDatabase({R"(
CREATE TABLE T (
A INT64,
B INT64,
C INT64,
) PRIMARY KEY(A))",
R"(
CREATE TABLE U (
X INT64,
Y INT64,
Z INT64,
) PRIMARY KEY(X))"}));
}
absl::Status AddForeignKey() {
return UpdateSchema({R"(
ALTER TABLE U
ADD CONSTRAINT C
FOREIGN KEY(Z, Y)
REFERENCES T(B, C))"});
}
absl::Status CreateDatabase(const std::vector<std::string>& statements) {
ZETASQL_ASSIGN_OR_RETURN(database_, Database::Create(&clock_, statements));
return absl::OkStatus();
}
absl::Status UpdateSchema(absl::Span<const std::string> statements) {
int succesful;
absl::Status status;
absl::Time timestamp;
ZETASQL_RETURN_IF_ERROR(
database_->UpdateSchema(statements, &succesful, ×tamp, &status));
return status;
}
void Insert(const std::string& table, const std::vector<std::string>& columns,
const std::vector<int>& values) {
Mutation m;
m.AddWriteOp(MutationOpType::kInsert, table, columns, {AsList(values)});
ZETASQL_ASSERT_OK_AND_ASSIGN(std::unique_ptr<ReadWriteTransaction> txn,
database_->CreateReadWriteTransaction(
ReadWriteOptions(), RetryState()));
ZETASQL_ASSERT_OK(txn->Write(m));
ZETASQL_ASSERT_OK(txn->Commit());
}
ValueList AsList(const std::vector<int>& values) {
ValueList value_list;
std::transform(
values.begin(), values.end(), std::back_inserter(value_list),
[](int value) { return value == 0 ? NullInt64() : Int64(value); });
return value_list;
}
Clock clock_;
std::unique_ptr<Database> database_;
};
TEST_F(ForeignKeyVerifiersTest, NoExistingData) { ZETASQL_EXPECT_OK(AddForeignKey()); }
TEST_F(ForeignKeyVerifiersTest, ValidExistingData) {
Insert("T", {"A", "B", "C"}, {1, 2, 3});
Insert("U", {"X", "Y", "Z"}, {4, 3, 2});
ZETASQL_EXPECT_OK(AddForeignKey());
}
TEST_F(ForeignKeyVerifiersTest, InvalidExistingData) {
Insert("T", {"A", "B", "C"}, {1, 2, 3});
Insert("U", {"X", "Y", "Z"}, {4, 2, 3});
EXPECT_THAT(AddForeignKey(), StatusIs(absl::StatusCode::kFailedPrecondition));
}
} // namespace
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
| 31.737705 | 87 | 0.668905 | sgorse12 |
b83ee13397a05776a3c1e47ad5d079b0391122d9 | 2,606 | cpp | C++ | src/xr_3da/xrGame/GameTask_script.cpp | ixray-team/ixray-b2939 | d9dc2359c0177cd3b58c310e015a1f390af2d8a1 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | src/xr_3da/xrGame/GameTask_script.cpp | ixray-team/ixray-b2939 | d9dc2359c0177cd3b58c310e015a1f390af2d8a1 | [
"Linux-OpenIB"
] | null | null | null | src/xr_3da/xrGame/GameTask_script.cpp | ixray-team/ixray-b2939 | d9dc2359c0177cd3b58c310e015a1f390af2d8a1 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | #include "stdafx.h"
#include "GameTask.h"
#include "script_space.h"
#include <luabind/adopt_policy.hpp>
using namespace luabind;
#pragma optimize("s",on)
void CGameTask::script_register(lua_State *L)
{
module(L)
[
class_<enum_exporter<ETaskState> >("task")
.enum_("task_state")
[
value("fail", int(eTaskStateFail)),
value("in_progress", int(eTaskStateInProgress)),
value("completed", int(eTaskStateCompleted)),
value("task_dummy", int(eTaskStateDummy))
],
class_<SGameTaskObjective>("SGameTaskObjective")
.def( constructor<CGameTask*, int>() )
.def("set_description", &SGameTaskObjective::SetDescription_script )
.def("get_description", &SGameTaskObjective::GetDescription_script )
.def("set_article_id", &SGameTaskObjective::SetArticleID_script )
.def("set_map_hint", &SGameTaskObjective::SetMapHint_script )
.def("set_map_location", &SGameTaskObjective::SetMapLocation_script )
.def("set_object_id", &SGameTaskObjective::SetObjectID_script )
.def("set_article_key", &SGameTaskObjective::SetArticleKey_script )
.def("add_complete_info", &SGameTaskObjective::AddCompleteInfo_script )
.def("add_fail_info", &SGameTaskObjective::AddFailInfo_script )
.def("add_on_complete_info", &SGameTaskObjective::AddOnCompleteInfo_script )
.def("add_on_fail_info", &SGameTaskObjective::AddOnFailInfo_script )
.def("add_complete_func", &SGameTaskObjective::AddCompleteFunc_script )
.def("add_fail_func", &SGameTaskObjective::AddFailFunc_script )
.def("add_on_complete_func", &SGameTaskObjective::AddOnCompleteFunc_script )
.def("add_on_fail_func", &SGameTaskObjective::AddOnFailFunc_script )
.def("get_state", &SGameTaskObjective::TaskState )
.def("get_idx", &SGameTaskObjective::GetIDX_script )
.def("get_state", &SGameTaskObjective::TaskState ),
class_<CGameTask>("CGameTask")
.def( constructor<>() )
.def("load", &CGameTask::Load_script )
.def("set_title", &CGameTask::SetTitle_script )
.def("get_title", &CGameTask::GetTitle_script )
.def("add_objective", &CGameTask::AddObjective_script, adopt(_2))
.def("get_objective", &CGameTask::GetObjective_script )
.def("get_id", &CGameTask::GetID_script )
.def("get_objectives_cnt", &CGameTask::GetObjectiveSize_script )
];
} | 46.535714 | 84 | 0.651573 | ixray-team |
b83f048dc7c3b3547b53cb378630a073b7d4552e | 1,277 | cpp | C++ | Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp | crimsonstrife/velorum-defunct | 1a6e1eab9057293da2aa045eff021d069df54c5e | [
"CC0-1.0"
] | null | null | null | /*
By Rama
*/
#include "VictoryBPLibraryPrivatePCH.h"
#include "VictoryBPHTML.h"
#if PLATFORM_HTML5_BROWSER
#include "SDL_opengl.h"
DEFINE_LOG_CATEGORY_STATIC(VictoryPluginHTML, Log, All);
#include "emscripten.h"
#include "html5.h"
#endif
bool UVictoryBPHTML::IsHTML()
{
#if PLATFORM_HTML5_BROWSER
return true;
#else
return false;
#endif //HTML
}
void UVictoryBPHTML::VictoryHTML5_SetCursorVisible(bool MakeVisible)
{
if(MakeVisible)
{
#if PLATFORM_HTML5_WIN32
{
SDL_SetRelativeMouseMode(SDL_FALSE);
SDL_ShowCursor(SDL_ENABLE);
SDL_SetWindowGrab(WindowHandle, SDL_FALSE);
UE_LOG(VictoryPluginHTML, Warning, TEXT("SDL Showing Mouse Cursor"));
}
#endif
#if PLATFORM_HTML5_BROWSER
{
emscripten_exit_pointerlock();
UE_LOG(VictoryPluginHTML, Warning, TEXT("Exiting Pointer Lock"));
}
#endif
}
else
{
#if PLATFORM_HTML5_WIN32
{
SDL_SetWindowGrab(WindowHandle, SDL_TRUE);
SDL_ShowCursor(SDL_DISABLE);
SDL_SetRelativeMouseMode(SDL_TRUE);
UE_LOG(VictoryPluginHTML, Warning, TEXT("SDL Hiding Mouse Cursor"));
}
#endif
#if PLATFORM_HTML5_BROWSER
{
emscripten_request_pointerlock ( "#canvas" , true);
UE_LOG(VictoryPluginHTML, Warning, TEXT("Entering Pointer Lock"));
}
#endif
}
} | 20.269841 | 72 | 0.729052 | crimsonstrife |
b84141fe534387171bef980fd9676c08b623280b | 1,349 | cpp | C++ | Day 25/Flood Fill - DFS Version (Better).cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | 4 | 2019-12-12T19:59:50.000Z | 2020-01-20T15:44:44.000Z | Day 25/Flood Fill - DFS Version (Better).cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | Day 25/Flood Fill - DFS Version (Better).cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | // Question Link ---> https://leetcode.com/problems/flood-fill/
// Day #25
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
// We need to consider starting pixel, if it is alrealy filled with newColor then return
if (image[sr][sc] != newColor) {
int oldColor = image[sr][sc];
dfs(image, sr, sc, newColor, oldColor);
}
return image;
}
void dfs(vector<vector<int>> &image, int x, int y, int &newColor, int &oldColor) {
if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor) {
image[x][y] = newColor;
dfs(image, x, y + 1, newColor, oldColor);
dfs(image, x, y - 1, newColor, oldColor);
dfs(image, x - 1, y, newColor, oldColor);
dfs(image, x + 1, y, newColor, oldColor);
}
}
};
int main(void) {
vector<vector<int>> res, image = { {0, 0, 0}, {0, 1, 1} };
int sr = 1, sc = 1, newColor = 1;
//vector<vector<int>> res, image = { {1, 1, 1}, {1, 1, 0}, {1, 0, 1} };
//int sr = 1, sc = 1, newColor = 2;
Solution obj;
res = obj.floodFill(image, sr, sc, newColor);
cout << "Result: \n";
for (auto row : image) {
for (auto pixel : row) {
cout << pixel << " ";
}
cout << endl;
}
} | 30.659091 | 96 | 0.570793 | shtanriverdi |
cdc7bd71d9ec72ddccba414e42a22e60c693de99 | 9,632 | cxx | C++ | modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from PoseStamped_.idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
#ifndef NDDS_STANDALONE_TYPE
#ifndef ndds_cpp_h
#include "ndds/ndds_cpp.h"
#endif
#ifndef dds_c_log_impl_h
#include "dds_c/dds_c_log_impl.h"
#endif
#ifndef cdr_type_h
#include "cdr/cdr_type.h"
#endif
#ifndef osapi_heap_h
#include "osapi/osapi_heap.h"
#endif
#else
#include "ndds_standalone_type.h"
#endif
#include "PoseStamped_.h"
#include <new>
namespace geometry_msgs {
namespace msg {
namespace dds_ {
/* ========================================================================= */
const char *PoseStamped_TYPENAME = "geometry_msgs::msg::dds_::PoseStamped_";
DDS_TypeCode* PoseStamped__get_typecode()
{
static RTIBool is_initialized = RTI_FALSE;
static DDS_TypeCode_Member PoseStamped__g_tc_members[2]=
{
{
(char *)"header_",/* Member name */
{
0,/* Representation ID */
DDS_BOOLEAN_FALSE,/* Is a pointer? */
-1, /* Bitfield bits */
NULL/* Member type code is assigned later */
},
0, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
RTI_CDR_REQUIRED_MEMBER, /* Is a key? */
DDS_PUBLIC_MEMBER,/* Member visibility */
1,
NULL/* Ignored */
},
{
(char *)"pose_",/* Member name */
{
1,/* Representation ID */
DDS_BOOLEAN_FALSE,/* Is a pointer? */
-1, /* Bitfield bits */
NULL/* Member type code is assigned later */
},
0, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
RTI_CDR_REQUIRED_MEMBER, /* Is a key? */
DDS_PUBLIC_MEMBER,/* Member visibility */
1,
NULL/* Ignored */
}
};
static DDS_TypeCode PoseStamped__g_tc =
{{
DDS_TK_STRUCT,/* Kind */
DDS_BOOLEAN_FALSE, /* Ignored */
-1, /*Ignored*/
(char *)"geometry_msgs::msg::dds_::PoseStamped_", /* Name */
NULL, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
2, /* Number of members */
PoseStamped__g_tc_members, /* Members */
DDS_VM_NONE /* Ignored */
}}; /* Type code for PoseStamped_*/
if (is_initialized) {
return &PoseStamped__g_tc;
}
PoseStamped__g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)std_msgs::msg::dds_::Header__get_typecode();
PoseStamped__g_tc_members[1]._representation._typeCode = (RTICdrTypeCode *)geometry_msgs::msg::dds_::Pose__get_typecode();
is_initialized = RTI_TRUE;
return &PoseStamped__g_tc;
}
RTIBool PoseStamped__initialize(
PoseStamped_* sample) {
return geometry_msgs::msg::dds_::PoseStamped__initialize_ex(sample,RTI_TRUE,RTI_TRUE);
}
RTIBool PoseStamped__initialize_ex(
PoseStamped_* sample,RTIBool allocatePointers, RTIBool allocateMemory)
{
struct DDS_TypeAllocationParams_t allocParams =
DDS_TYPE_ALLOCATION_PARAMS_DEFAULT;
allocParams.allocate_pointers = (DDS_Boolean)allocatePointers;
allocParams.allocate_memory = (DDS_Boolean)allocateMemory;
return geometry_msgs::msg::dds_::PoseStamped__initialize_w_params(
sample,&allocParams);
}
RTIBool PoseStamped__initialize_w_params(
PoseStamped_* sample, const struct DDS_TypeAllocationParams_t * allocParams)
{
if (sample == NULL) {
return RTI_FALSE;
}
if (allocParams == NULL) {
return RTI_FALSE;
}
if (!std_msgs::msg::dds_::Header__initialize_w_params(&sample->header_,
allocParams)) {
return RTI_FALSE;
}
if (!geometry_msgs::msg::dds_::Pose__initialize_w_params(&sample->pose_,
allocParams)) {
return RTI_FALSE;
}
return RTI_TRUE;
}
void PoseStamped__finalize(
PoseStamped_* sample)
{
geometry_msgs::msg::dds_::PoseStamped__finalize_ex(sample,RTI_TRUE);
}
void PoseStamped__finalize_ex(
PoseStamped_* sample,RTIBool deletePointers)
{
struct DDS_TypeDeallocationParams_t deallocParams =
DDS_TYPE_DEALLOCATION_PARAMS_DEFAULT;
if (sample==NULL) {
return;
}
deallocParams.delete_pointers = (DDS_Boolean)deletePointers;
geometry_msgs::msg::dds_::PoseStamped__finalize_w_params(
sample,&deallocParams);
}
void PoseStamped__finalize_w_params(
PoseStamped_* sample,const struct DDS_TypeDeallocationParams_t * deallocParams)
{
if (sample==NULL) {
return;
}
if (deallocParams == NULL) {
return;
}
std_msgs::msg::dds_::Header__finalize_w_params(&sample->header_,deallocParams);
geometry_msgs::msg::dds_::Pose__finalize_w_params(&sample->pose_,deallocParams);
}
void PoseStamped__finalize_optional_members(
PoseStamped_* sample, RTIBool deletePointers)
{
struct DDS_TypeDeallocationParams_t deallocParamsTmp =
DDS_TYPE_DEALLOCATION_PARAMS_DEFAULT;
struct DDS_TypeDeallocationParams_t * deallocParams =
&deallocParamsTmp;
if (sample==NULL) {
return;
}
if (deallocParams) {} /* To avoid warnings */
deallocParamsTmp.delete_pointers = (DDS_Boolean)deletePointers;
deallocParamsTmp.delete_optional_members = DDS_BOOLEAN_TRUE;
std_msgs::msg::dds_::Header__finalize_optional_members(&sample->header_, deallocParams->delete_pointers);
geometry_msgs::msg::dds_::Pose__finalize_optional_members(&sample->pose_, deallocParams->delete_pointers);
}
RTIBool PoseStamped__copy(
PoseStamped_* dst,
const PoseStamped_* src)
{
try {
if (dst == NULL || src == NULL) {
return RTI_FALSE;
}
if (!std_msgs::msg::dds_::Header__copy(
&dst->header_,(const std_msgs::msg::dds_::Header_*)&src->header_)) {
return RTI_FALSE;
}
if (!geometry_msgs::msg::dds_::Pose__copy(
&dst->pose_,(const geometry_msgs::msg::dds_::Pose_*)&src->pose_)) {
return RTI_FALSE;
}
return RTI_TRUE;
} catch (std::bad_alloc&) {
return RTI_FALSE;
}
}
/**
* <<IMPLEMENTATION>>
*
* Defines: TSeq, T
*
* Configure and implement 'PoseStamped_' sequence class.
*/
#define T PoseStamped_
#define TSeq PoseStamped_Seq
#define T_initialize_w_params geometry_msgs::msg::dds_::PoseStamped__initialize_w_params
#define T_finalize_w_params geometry_msgs::msg::dds_::PoseStamped__finalize_w_params
#define T_copy geometry_msgs::msg::dds_::PoseStamped__copy
#ifndef NDDS_STANDALONE_TYPE
#include "dds_c/generic/dds_c_sequence_TSeq.gen"
#include "dds_cpp/generic/dds_cpp_sequence_TSeq.gen"
#else
#include "dds_c_sequence_TSeq.gen"
#include "dds_cpp_sequence_TSeq.gen"
#endif
#undef T_copy
#undef T_finalize_w_params
#undef T_initialize_w_params
#undef TSeq
#undef T
} /* namespace dds_ */
} /* namespace msg */
} /* namespace geometry_msgs */
| 34.898551 | 138 | 0.48858 | Omnirobotic |
cdc85a8aaa84d76d1b59685fdf79359face70a9d | 3,191 | hpp | C++ | stan/math/rev/core/operator_multiplication.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/core/operator_multiplication.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/core/operator_multiplication.hpp | peterwicksstringfield/math | 5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_REV_CORE_OPERATOR_MULTIPLICATION_HPP
#define STAN_MATH_REV_CORE_OPERATOR_MULTIPLICATION_HPP
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/core/vv_vari.hpp>
#include <stan/math/rev/core/vd_vari.hpp>
#include <stan/math/prim/scal/fun/is_any_nan.hpp>
#include <limits>
namespace stan {
namespace math {
namespace internal {
class multiply_vv_vari : public op_vv_vari {
public:
multiply_vv_vari(vari* avi, vari* bvi)
: op_vv_vari(avi->val_ * bvi->val_, avi, bvi) {}
void chain() {
if (unlikely(is_any_nan(avi_->val_, bvi_->val_))) {
avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
bvi_->adj_ = std::numeric_limits<double>::quiet_NaN();
} else {
avi_->adj_ += bvi_->val_ * adj_;
bvi_->adj_ += avi_->val_ * adj_;
}
}
};
class multiply_vd_vari : public op_vd_vari {
public:
multiply_vd_vari(vari* avi, double b) : op_vd_vari(avi->val_ * b, avi, b) {}
void chain() {
if (unlikely(is_any_nan(avi_->val_, bd_))) {
avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
} else {
avi_->adj_ += adj_ * bd_;
}
}
};
} // namespace internal
/**
* Multiplication operator for two variables (C++).
*
* The partial derivatives are
*
* \f$\frac{\partial}{\partial x} (x * y) = y\f$, and
*
* \f$\frac{\partial}{\partial y} (x * y) = x\f$.
*
\f[
\mbox{operator*}(x, y) =
\begin{cases}
xy & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{operator*}(x, y)}{\partial x} =
\begin{cases}
y & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{operator*}(x, y)}{\partial y} =
\begin{cases}
x & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
*
* @param a First variable operand.
* @param b Second variable operand.
* @return Variable result of multiplying operands.
*/
inline var operator*(const var& a, const var& b) {
return var(new internal::multiply_vv_vari(a.vi_, b.vi_));
}
/**
* Multiplication operator for a variable and a scalar (C++).
*
* The partial derivative for the variable is
*
* \f$\frac{\partial}{\partial x} (x * c) = c\f$, and
*
* @param a Variable operand.
* @param b Scalar operand.
* @return Variable result of multiplying operands.
*/
inline var operator*(const var& a, double b) {
if (b == 1.0) {
return a;
}
return var(new internal::multiply_vd_vari(a.vi_, b));
}
/**
* Multiplication operator for a scalar and a variable (C++).
*
* The partial derivative for the variable is
*
* \f$\frac{\partial}{\partial y} (c * y) = c\f$.
*
* @param a Scalar operand.
* @param b Variable operand.
* @return Variable result of multiplying the operands.
*/
inline var operator*(double a, const var& b) {
if (a == 1.0) {
return b;
}
return var(new internal::multiply_vd_vari(b.vi_, a)); // by symmetry
}
} // namespace math
} // namespace stan
#endif
| 26.155738 | 78 | 0.622689 | peterwicksstringfield |
cdcb3c9d7b0ab48f58035e94362a02c755229f35 | 203 | cpp | C++ | judges/uri/iniciante/1174.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | null | null | null | judges/uri/iniciante/1174.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T11:53:02.000Z | 2018-10-17T11:54:42.000Z | judges/uri/iniciante/1174.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T12:14:04.000Z | 2018-10-17T12:14:04.000Z | #include <bits/stdc++.h>
using namespace std;
int main (){
double n[100];
for(int i = 0; i < 100; i++){
cin >> n[i];
if(n[i] <= 10){
printf("A[%d] = %.1lf\n", i, n[i]);
}
}
return 0;
} | 11.277778 | 38 | 0.472906 | eduardonunes2525 |
cdcc3ce66639c6fb6bca770b90d0c5faf738e466 | 2,725 | hpp | C++ | fw/avrlib/adc.hpp | RoboticsBrno/3piRB-shield | 974e327d0a3b5c55d5811eba48c963596f7663da | [
"MIT"
] | 1 | 2021-05-08T05:54:16.000Z | 2021-05-08T05:54:16.000Z | fw/avrlib/adc.hpp | RoboticsBrno/3piRB-shield | 974e327d0a3b5c55d5811eba48c963596f7663da | [
"MIT"
] | null | null | null | fw/avrlib/adc.hpp | RoboticsBrno/3piRB-shield | 974e327d0a3b5c55d5811eba48c963596f7663da | [
"MIT"
] | 1 | 2017-11-13T05:48:29.000Z | 2017-11-13T05:48:29.000Z | #ifndef AVRLIB_ADC_HPP
#define AVRLIB_ADC_HPP
#include <avr/io.h>
namespace avrlib {
enum adc_timer_mode
{
adc_prescaler_2 = 1,
adc_prescaler_4,
adc_prescaler_8,
adc_prescaler_16,
adc_prescaler_32,
adc_prescaler_64,
adc_prescaler_128
};
class sync_adc
{
public:
explicit sync_adc(uint8_t channel, bool reverse = false, bool left_adj = true)
: m_channel(channel), m_reverse(reverse), m_left_adj(left_adj)
{
}
static void init(adc_timer_mode t)
{
ADCSRA = (1<<ADEN) | t;
}
void start()
{
ADCSRA |= (1<<ADSC);
}
bool running() const
{
return (ADCSRA & (1<<ADSC)) != 0;
}
uint16_t value() const
{
uint16_t res = ADCL;
res |= ADCH << 8;
return res;
}
uint16_t operator()()
{
ADMUX = (m_left_adj<<ADLAR) | m_channel;
ADCSRA |= (1<<ADSC);
while ((ADCSRA & (1<<ADIF)) == 0)
{
}
/*ADCSRA |= (1<<ADSC);
while ((ADCSRA & (1<<ADIF)) == 0)
{
}*/
uint16_t res = ADCL;
res |= ADCH << 8;
if (m_reverse)
res = -res;
return res;
}
private:
uint8_t m_channel;
bool m_reverse;
bool m_left_adj;
};
class async_adc
{
public:
typedef uint16_t value_type;
explicit async_adc(uint8_t channel, bool reverse = false, bool left_adj = true)
: m_channel(channel), m_reverse(reverse), m_value(0), m_new_value(false), m_left_adj(left_adj)
{
}
static void init(adc_timer_mode t)
{
ADCSRA = (1<<ADEN) | t;
}
void start()
{
ADMUX = (m_left_adj<<ADLAR) | m_channel;
ADCSRA |= (1<<ADSC);
}
bool process()
{
if ((ADCSRA & (1<<ADSC)) != 0)
return false;
m_value = ADCL;
m_value |= ADCH << 8;
if (m_reverse)
m_value = -m_value;
m_new_value = true;
return true;
}
value_type value()
{
m_new_value = false;
return m_value;
}
bool new_value() const { return m_new_value; }
uint8_t channel() const { return m_channel; }
private:
uint8_t m_channel;
bool m_reverse;
volatile value_type m_value;
volatile bool m_new_value;
bool m_left_adj;
};
class fast_async_adc
{
public:
typedef uint16_t value_type;
explicit fast_async_adc(uint8_t channel)
: m_channel(channel | (1<<ADLAR)), m_value(0), m_new_value(0)
{
}
static void init(adc_timer_mode t) {};
void start()
{
ADMUX = m_channel;
ADCSRA = adcsra;
}
inline void process()
{
m_value = ADCL;
m_value |= ADCH << 8;
m_new_value = 1;
}
value_type value()
{
m_new_value = 0;
return m_value;
}
value_type operator()()
{
m_new_value = 0;
return m_value;
}
inline uint8_t new_value() const { return m_new_value; }
static uint8_t adcsra;
private:
uint8_t m_channel;
volatile value_type m_value;
volatile uint8_t m_new_value;
};
uint8_t fast_async_adc::adcsra = (1<<ADEN) | (1<<ADSC) | 7;
}
#endif
| 14.572193 | 96 | 0.650275 | RoboticsBrno |
cdcdda1727cad51d2b9f1d5364b44d01972f86f3 | 1,317 | cc | C++ | 洛谷/提高/P2014.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | 67 | 2019-07-14T05:38:41.000Z | 2021-12-23T11:52:51.000Z | 洛谷/提高/P2014.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | null | null | null | 洛谷/提高/P2014.cc | OFShare/Algorithm-challenger | 43336871a5e48f8804d6e737c813d9d4c0dc2731 | [
"MIT"
] | 12 | 2020-01-16T10:48:01.000Z | 2021-06-11T16:49:04.000Z | /*
* Author : OFShare
* E-mail : OFShare@outlook.com
* Created Time : 2020-07-01 13:40:58 PM
* File Name : P2014.cc
*/
#include <bits/stdc++.h>
#define ll long long
void debug() {
#ifdef Acui
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
}
const int N = 3e2 + 5;
int n, m, score[N], size[N], dp[N][N];
std::vector<int> sons[N];
// dp[u][j]表示以结点u为根, 选j门课(看成背包容量且恰好装满), 能获得的最大学分
void dfs(int u) {
dp[u][0] = 0;
size[u] = 1;
// 每个儿子看成一组背包
for (int i = 0; i < sons[u].size(); ++i) {
int v = sons[u][i];
dfs(v);
size[u] += size[v];
// 类似分组背包, k枚举第i组背包(即第i个儿子)选几门课
for (int j = m; j >= 0; --j) {
for (int k = 0; k <= size[v]; ++k) {
if (j - k >= 0)
dp[u][j] = std::max(dp[u][j], dp[u][j - k] + dp[v][k]);
}
}
}
// 根结点u本身看成一组背包, 且必须取它
for (int j = m; j >= 0; --j) {
if (j - 1 >= 0) {
// dp[u][j] = std::max(dp[u][j], dp[u][j - 1] + score[u]);
dp[u][j] = dp[u][j - 1] + score[u];
}
}
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) {
int k, s;
scanf("%d %d", &k, &s);
sons[k].push_back(i);
score[i] = s;
}
m += 1;
score[0] = 0;
std::memset(dp, -0x3f3f3f, sizeof dp);
dfs(0);
printf("%d\n", dp[0][m]);
return 0;
}
| 21.241935 | 65 | 0.459377 | OFShare |
cdcdfa70ac642fa745ec04bc6dcd146877c746ac | 3,001 | cpp | C++ | src/ldb_reader.cpp | Prime9999/liblcf | 3ea048387c36b14af48a4061a7a23d2276f35ac4 | [
"MIT"
] | null | null | null | src/ldb_reader.cpp | Prime9999/liblcf | 3ea048387c36b14af48a4061a7a23d2276f35ac4 | [
"MIT"
] | null | null | null | src/ldb_reader.cpp | Prime9999/liblcf | 3ea048387c36b14af48a4061a7a23d2276f35ac4 | [
"MIT"
] | null | null | null | /*
* This file is part of liblcf. Copyright (c) 2018 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
#include <fstream>
#include "ldb_reader.h"
#include "ldb_chunks.h"
#include "data.h"
#include "reader_util.h"
#include "reader_struct.h"
bool LDB_Reader::Load(const std::string& filename, const std::string& encoding) {
std::ifstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::Load(stream, encoding);
}
bool LDB_Reader::Save(const std::string& filename, const std::string& encoding) {
std::ofstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::Save(stream, encoding);
}
bool LDB_Reader::SaveXml(const std::string& filename) {
std::ofstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::SaveXml(stream);
}
bool LDB_Reader::LoadXml(const std::string& filename) {
std::ifstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::LoadXml(stream);
}
bool LDB_Reader::Load(std::istream& filestream, const std::string& encoding) {
LcfReader reader(filestream, encoding);
if (!reader.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
std::string header;
reader.ReadString(header, reader.ReadInt());
if (header.length() != 11) {
LcfReader::SetError("This is not a valid RPG2000 database.\n");
return false;
}
if (header != "LcfDataBase") {
fprintf(stderr, "Warning: This header is not LcfDataBase and might not be a valid RPG2000 database.\n");
}
TypeReader<RPG::Database>::ReadLcf(Data::data, reader, 0);
// Delayed initialization of some actor fields because they are engine
// dependent
std::vector<RPG::Actor>::iterator it;
for (it = Data::actors.begin(); it != Data::actors.end(); ++it) {
(*it).Setup();
}
return true;
}
bool LDB_Reader::Save(std::ostream& filestream, const std::string& encoding) {
LcfWriter writer(filestream, encoding);
if (!writer.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
const std::string header("LcfDataBase");
writer.WriteInt(header.size());
writer.Write(header);
TypeReader<RPG::Database>::WriteLcf(Data::data, writer);
return true;
}
bool LDB_Reader::SaveXml(std::ostream& filestream) {
XmlWriter writer(filestream);
if (!writer.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
writer.BeginElement("LDB");
TypeReader<RPG::Database>::WriteXml(Data::data, writer);
writer.EndElement("LDB");
return true;
}
bool LDB_Reader::LoadXml(std::istream& filestream) {
XmlReader reader(filestream);
if (!reader.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
reader.SetHandler(new RootXmlHandler<RPG::Database>(Data::data, "LDB"));
reader.Parse();
return true;
}
| 30.01 | 106 | 0.715095 | Prime9999 |
cdce7c6e95a62bd75ef115cdc5cbb46bff04970e | 1,439 | cpp | C++ | Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp | RaiaN/ue4_runtimeimageimporter | 02fec76b591fb9b5988e3355bf73f16248c244a4 | [
"MIT"
] | 1 | 2022-02-02T09:06:41.000Z | 2022-02-02T09:06:41.000Z | Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp | RaiaN/ue4_runtimeimageimporter | 02fec76b591fb9b5988e3355bf73f16248c244a4 | [
"MIT"
] | null | null | null | Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp | RaiaN/ue4_runtimeimageimporter | 02fec76b591fb9b5988e3355bf73f16248c244a4 | [
"MIT"
] | null | null | null | // Copyright 2022 Peter Leontev. All Rights Reserved.
#include "ImageReaderLocal.h"
#include "HAL/FileManager.h"
#include "Misc/FileHelper.h"
#include "Stats/Stats.h"
bool FImageReaderLocal::ReadImage(const FString& ImageURI, TArray<uint8>& OutImageData)
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_RuntimeImageUtils_ImportFileAsTexture);
// TODO:
const int64 MAX_FILESIZE_BYTES = 999999999;
IFileManager& FileManager = IFileManager::Get();
if (!FileManager.FileExists(*ImageURI))
{
OutError = FString::Printf(TEXT("Image does not exist: %s"), *ImageURI);
return false;
}
const int64 ImageFileSizeBytes = FileManager.FileSize(*ImageURI);
check(ImageFileSizeBytes != INDEX_NONE);
// check filesize
if (ImageFileSizeBytes > MAX_FILESIZE_BYTES)
{
OutError = FString::Printf(TEXT("Image filesize > %d MBs): %s"), MAX_FILESIZE_BYTES, *ImageURI);
return false;
}
QUICK_SCOPE_CYCLE_COUNTER(STAT_FImageReaderLocal_LoadFileToArray);
if (!FFileHelper::LoadFileToArray(OutImageData, *ImageURI))
{
OutError = FString::Printf(TEXT("Image loading I/O error: %s"), *ImageURI);
return false;
}
OutImageData.Add(0);
return true;
}
FString FImageReaderLocal::GetLastError() const
{
return OutError;
}
void FImageReaderLocal::Flush()
{
// do nothing as we image reader local is synchronous and does not depend on game thread
}
| 27.673077 | 104 | 0.702571 | RaiaN |
cdd31d556fdcad78e0b66559b3a5d11b71f88d97 | 261 | hpp | C++ | lib/tests/ruby/ruby_helper.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | lib/tests/ruby/ruby_helper.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | lib/tests/ruby/ruby_helper.hpp | mihaibuzgau/facter | 451ee4288c61c6185295b454339801b84b8242ef | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <facter/facts/collection.hpp>
#include <facter/facts/value.hpp>
#include <string>
bool load_custom_fact(std::string const& filename, facter::facts::collection& facts);
std::string ruby_value_to_string(facter::facts::value const* value);
| 29 | 85 | 0.777778 | mihaibuzgau |
cdd3415aacc6450af278647dd8d7980e2c101d2e | 1,460 | hpp | C++ | gearoenix/render/camera/gx-rnd-cmr-manager.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/render/camera/gx-rnd-cmr-manager.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/render/camera/gx-rnd-cmr-manager.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_RENDER_CAMERA_MANAGER_HPP
#define GEAROENIX_RENDER_CAMERA_MANAGER_HPP
#include "../../core/asset/gx-cr-asset-manager.hpp"
#include "../../core/cache/gx-cr-cache-file.hpp"
#include "../../core/sync/gx-cr-sync-end-caller.hpp"
#include "gx-rnd-cmr-camera.hpp"
namespace gearoenix {
namespace system::stream {
class Stream;
}
namespace render {
namespace engine {
class Engine;
}
namespace camera {
class Manager {
protected:
engine::Engine* const e;
core::cache::File<Camera> cache;
public:
Manager(std::unique_ptr<system::stream::Stream> s, engine::Engine* e) noexcept;
~Manager() noexcept = default;
std::shared_ptr<Camera> get_gx3d(core::Id cid, core::sync::EndCaller<Camera>& call) noexcept;
template <typename T>
typename std::enable_if<std::is_base_of<Camera, T>::value, std::shared_ptr<T>>::type create(std::string name) noexcept;
};
}
}
}
template <typename T>
typename std::enable_if<std::is_base_of<gearoenix::render::camera::Camera, T>::value, std::shared_ptr<T>>::type
gearoenix::render::camera::Manager::create(std::string name) noexcept
{
const core::Id id = core::asset::Manager::create_id();
const std::shared_ptr<T> result(new T(id, std::move(name), e));
const std::weak_ptr<Camera> w = result;
cache.get_cacher().get_cacheds()[id] = w;
return result;
}
#endif
| 33.181818 | 131 | 0.65411 | Hossein-Noroozpour |
cdd41a7a87d3aa9436324e0fac88cf48e70813b3 | 43,935 | cpp | C++ | platform/shared/db/DBAdapter.cpp | jjfraz11/rhodes | d7fc4579550e0fa7d93c7b66536d4407ca3afefc | [
"MIT"
] | null | null | null | platform/shared/db/DBAdapter.cpp | jjfraz11/rhodes | d7fc4579550e0fa7d93c7b66536d4407ca3afefc | [
"MIT"
] | null | null | null | platform/shared/db/DBAdapter.cpp | jjfraz11/rhodes | d7fc4579550e0fa7d93c7b66536d4407ca3afefc | [
"MIT"
] | 1 | 2018-02-28T23:51:04.000Z | 2018-02-28T23:51:04.000Z | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "DBAdapter.h"
#include "sync/RhoconnectClientManager.h"
#include "common/RhoFile.h"
#include "common/RhoFilePath.h"
#include "common/RhoConf.h"
#include "common/RhodesApp.h"
#include "common/RhoAppAdapter.h"
#include "common/Tokenizer.h"
#ifndef RHO_NO_RUBY
#include "ruby/ext/rho/rhoruby.h"
#endif //RHO_NO_RUBY
#include "common/app_build_configs.h"
#include "DBImportTransaction.h"
#include "DBRequestHelper.h"
#include <sstream>
int rho_sys_zip_files_with_path_array_ptr(const char* szZipFilePath, const char *base_path, const rho::Vector<rho::String>& arFiles, const char* psw);
namespace rho{
namespace db{
IMPLEMENT_LOGCLASS(CDBAdapter,"DB");
HashtablePtr<String,CDBAdapter*> CDBAdapter::m_mapDBPartitions;
using namespace rho::common;
using namespace rho;
static int onDBBusy(void* data,int nTry)
{
LOGC(ERROR,CDBAdapter::getLogCategory())+"Database BUSY";
return 0;
}
void SyncBlob_DeleteCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)
{
if ( nArgs < 3 )
return;
CDBAttrManager& attrMgr = CDBAdapter::getDBByHandle(sqlite3_context_db_handle(dbContext)).getAttrMgr();
char* szAttrName = (char*)sqlite3_value_text(*(ppArgs+2));
int nSrcID = sqlite3_value_int(*(ppArgs+1));
if ( attrMgr.isBlobAttr(nSrcID, szAttrName) )
{
String strFilePath = RHODESAPPBASE().resolveDBFilesPath((char*)sqlite3_value_text(*(ppArgs)));
CRhoFile::deleteFile(strFilePath.c_str());
}
//attrMgr.remove( nSrcID, szAttrName );
}
void SyncBlob_UpdateCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)
{
if ( nArgs < 3 )
return;
CDBAttrManager& attrMgr = CDBAdapter::getDBByHandle(sqlite3_context_db_handle(dbContext)).getAttrMgr();
char* szAttrName = (char*)sqlite3_value_text(*(ppArgs+2));
int nSrcID = sqlite3_value_int(*(ppArgs+1));
if ( attrMgr.isBlobAttr(nSrcID, szAttrName) )
{
String strFilePath = RHODESAPPBASE().resolveDBFilesPath((char*)sqlite3_value_text(*(ppArgs)));
CRhoFile::deleteFile(strFilePath.c_str());
}
}
void SyncBlob_DeleteSchemaCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)
{
//LOG(INFO) + "SyncBlob_DeleteSchemaCallback";
const char* szValue = (char*)sqlite3_value_text(*ppArgs);
if ( szValue && *szValue )
{
String strFilePath = RHODESAPPBASE().resolveDBFilesPath(szValue);
CRhoFile::deleteFile(strFilePath.c_str());
}
}
void SyncBlob_UpdateSchemaCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)
{
//LOG(INFO) + "SyncBlob_UpdateSchemaCallback";
const char* szOldValue = (char*)sqlite3_value_text(*(ppArgs+0));
const char* szNewValue = (char*)sqlite3_value_text(*(ppArgs+1));
if ( szOldValue == szNewValue || szOldValue == 0 )
return;
if ( szOldValue && szNewValue && strcmp(szOldValue, szNewValue) == 0 )
return;
if ( szOldValue && *szOldValue )
{
String strFilePath = RHODESAPPBASE().resolveDBFilesPath(szOldValue);
CRhoFile::deleteFile(strFilePath.c_str());
}
}
boolean CDBAdapter::checkDbError(int rc)
{
if ( rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE )
return true;
const char * szErrMsg = sqlite3_errmsg(m_dbHandle);
int nErrCode = sqlite3_errcode(m_dbHandle);
LOG(ERROR)+"DB query failed. Error code: " + nErrCode + "; Message: " + szErrMsg;
return false;
}
boolean CDBAdapter::checkDbErrorEx(int rc, rho::db::CDBResult& res)
{
if ( rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE )
return true;
const char * szErrMsg = sqlite3_errmsg(m_dbHandle);
int nErrCode = sqlite3_errcode(m_dbHandle);
res.getDBError().setError(nErrCode, szErrMsg);
if ( nErrCode == SQLITE_CONSTRAINT && res.getReportNonUnique() )
return true;
LOG(ERROR)+"DB query failed. rc: " + rc + "; Error code: " + nErrCode + "; Message: " + szErrMsg;
return false;
}
void CDBAdapter::open (String strDbPath, String strVer, boolean bTemp, boolean checkImportState)
{
if ( strcasecmp(strDbPath.c_str(),m_strDbPath.c_str() ) == 0 )
return;
LOG(INFO) + "Open DB: " + strDbPath;
//close();
m_mxRuby.create();
m_strDbPath = strDbPath;
if ( !bTemp )
{
m_strDbVerPath = strDbPath+".version";
m_strDbVer = strVer;
checkDBVersion(strVer);
}
if (checkImportState) {
CDBImportTransaction importTxn(*this);
if (importTxn.pending()) {
//if (!importTxn.commit()) {
importTxn.rollback();
//}
}
}
boolean bExist = CRhoFile::isFileExist(strDbPath.c_str());
int nRes = sqlite3_open(strDbPath.c_str(),&m_dbHandle);
if ( !checkDbError(nRes) )
return;
//TODO: raise exception if error
//if (RHOCONF().getBool("encrypt_database"))
const char* szEncrypt = get_app_build_config_item("encrypt_database");
if ( szEncrypt && strcmp(szEncrypt, "1") == 0 )
{
m_ptrCrypt = rho_get_RhoClassFactory()->createRhoCrypt();
if ( m_strCryptKey.length() > 0 )
m_ptrCrypt->set_db_CryptKey( m_strDbPartition.c_str(), m_strCryptKey.c_str(), !bTemp );
CDBError dbError;
String strKey = "PRAGMA key = \"";
strKey += m_strDbPartition + "\";";
executeBatch(strKey.c_str(), dbError);
}
if ( !bExist )
createSchema();
sqlite3_create_function( m_dbHandle, "rhoOnDeleteObjectRecord", 3, SQLITE_ANY, 0,
SyncBlob_DeleteCallback, 0, 0 );
sqlite3_create_function( m_dbHandle, "rhoOnUpdateObjectRecord", 3, SQLITE_ANY, 0,
SyncBlob_UpdateCallback, 0, 0 );
sqlite3_create_function( m_dbHandle, "rhoOnDeleteSchemaRecord", 1, SQLITE_ANY, 0,
SyncBlob_DeleteSchemaCallback, 0, 0 );
sqlite3_create_function( m_dbHandle, "rhoOnUpdateSchemaRecord", 2, SQLITE_ANY, 0,
SyncBlob_UpdateSchemaCallback, 0, 0 );
sqlite3_busy_handler(m_dbHandle, onDBBusy, 0 );
//getAttrMgr().load(*this);
//copy client_info table
if ( !bTemp && !bExist && CRhoFile::isFileExist((strDbPath+"_oldver").c_str()) )
{
LOG(INFO) + "Copy client_info table from old database";
CDBAdapter db(m_strDbPartition.c_str(), true);
db.open( strDbPath+"_oldver", m_strDbVer, true, false );
copyTable( "client_info", db, *this );
{
IDBResult res = executeSQL( "SELECT client_id FROM client_info" );
if ( !res.isEnd() && res.getStringByIdx(0).length() > 0 )
{
LOG(INFO) + "Set reset=1 in client_info";
executeSQL( "UPDATE client_info SET reset=1" );
}
}
// db.updateAllAttribChanges();
// db.copyTable("changed_values", db, *this );
db.close();
CRhoFile::deleteFile( (m_strDbPath+"_oldver").c_str());
CRhoFile::deleteFile( (m_strDbPath+"_oldver-journal").c_str());
}
}
void CDBAdapter::CDBVersion::fromFile(const String& strFilePath)//throws Exception
{
String strData;
CRhoFile::readStringFromFile(strFilePath.c_str(), strData);
CTokenizer oTokenizer( strData, ";" );
int nPos = 0;
while (oTokenizer.hasMoreTokens())
{
String tok = oTokenizer.nextToken();
tok = String_trim(tok);
switch(nPos)
{
case 0:
m_strRhoVer = tok;
break;
case 1:
m_strAppVer = tok;
break;
case 2:
m_bEncrypted = tok.compare("encrypted") == 0;
break;
}
nPos++;
}
}
void CDBAdapter::CDBVersion::toFile(const String& strFilePath)const//throws Exception
{
String strFullVer = m_strRhoVer + ";" + m_strAppVer +
";" + (m_bEncrypted ? "encrypted":"");
//try{
CRhoFile::deleteFile( strFilePath.c_str() );
CRhoFile::writeStringToFile(strFilePath.c_str(), strFullVer);
//}catch (Exception e) {
// LOG.ERROR("writeDBVersion failed.", e);
// throw e;
//}
}
boolean CDBAdapter::migrateDB(const CDBVersion& dbVer, const CDBVersion& dbNewVer )
{
LOG(INFO) + "Try migrate database from " + dbVer.m_strRhoVer + " to " + dbNewVer.m_strRhoVer;
if ( (dbVer.m_strRhoVer.find("1.4") == 0)&& (dbNewVer.m_strRhoVer.find("1.5")==0||dbNewVer.m_strRhoVer.find("1.4")==0) )
{
LOG(INFO) + "No migration required from " + dbVer.m_strRhoVer + " to " + dbNewVer.m_strRhoVer;
dbNewVer.toFile(m_strDbVerPath);
return true;
}
if ( (dbVer.m_strRhoVer.find("2.0") == 0||dbVer.m_strRhoVer.find("2.1") == 0||dbVer.m_strRhoVer.find("2.2") == 0)&&
(dbNewVer.m_strRhoVer.find("2.0")==0||dbNewVer.m_strRhoVer.find("2.1")==0||dbNewVer.m_strRhoVer.find("2.2")==0) )
{
LOG(INFO) + "No migration required from " + dbVer.m_strRhoVer + " to " + dbNewVer.m_strRhoVer;
dbNewVer.toFile(m_strDbVerPath);
return true;
}
//1.2.x -> 1.5.x,1.4.x
if ( (dbVer.m_strRhoVer.find("1.2") == 0)&& (dbNewVer.m_strRhoVer.find("1.5")==0||dbNewVer.m_strRhoVer.find("1.4")==0) )
{
//sources
//priority INTEGER, ADD
//backend_refresh_time int default 0, ADD
//id INTEGER PRIMARY KEY, REMOVE
//changed_values
//id INTEGER PRIMARY KEY, REMOVE
LOG(INFO) + "Migrate database from " + dbVer.m_strRhoVer + " to " + dbNewVer.m_strRhoVer;
CDBAdapter db(m_strDbPartition.c_str(), true);
db.open( m_strDbPath, m_strDbVer, true, false );
IDBResult res = db.executeSQL( "ALTER TABLE sources ADD priority INTEGER" );
IDBResult res1 = db.executeSQL( "ALTER TABLE sources ADD backend_refresh_time int default 0" );
{
Vector<int> vecSrcIds;
IDBResult res2 = db.executeSQL( "SELECT source_id FROM sources" );
for ( ; !res2.isEnd(); res2.next() )
vecSrcIds.addElement(res2.getIntByIdx(0));
for( size_t i = 0; i < vecSrcIds.size(); i++)
{
IDBResult res3 = db.executeSQL( "UPDATE sources SET priority=? where source_id=?",
vecSrcIds.elementAt(i), vecSrcIds.elementAt(i) );
}
}
db.close();
dbNewVer.toFile(m_strDbVerPath);
return true;
}
return false;
}
void CDBAdapter::checkDBVersion(String& strRhoDBVer)
{
CDBVersion dbNewVer;
dbNewVer.m_strRhoVer = strRhoDBVer;
dbNewVer.m_strAppVer = RHOCONF().getString("app_db_version");
const char* szEncrypt = get_app_build_config_item("encrypt_database");
dbNewVer.m_bEncrypted = szEncrypt && strcmp(szEncrypt, "1") == 0;
CDBVersion dbVer;
dbVer.fromFile(m_strDbVerPath);
if (dbVer.m_strRhoVer.length() == 0 )
{
dbNewVer.toFile(m_strDbVerPath);
return;
}
boolean bRhoReset = dbVer.isRhoVerChanged(dbNewVer);
boolean bAppReset = dbVer.isAppVerChanged(dbNewVer);
boolean bDbFormatChanged = dbVer.isDbFormatChanged(dbNewVer);
if ( !bDbFormatChanged && dbVer.m_bEncrypted )
{
//if (!com.rho.RhoCrypto.isKeyExist(strEncryptionInfo) )
// bDbFormatChanged = true;
}
if ( bDbFormatChanged )
LOG(INFO) + "Reset Database( format changed ):" + m_strDbPath;
if ( bRhoReset && !bAppReset && !bDbFormatChanged )
bRhoReset = !migrateDB(dbVer, dbNewVer);
if ( bRhoReset || bAppReset || bDbFormatChanged)
{
LOG(INFO) + "Reset database because version is changed.";
CRhoFile::deleteFile( (m_strDbPath+"_oldver").c_str());
CRhoFile::deleteFile( (m_strDbPath+"_oldver-journal").c_str());
if ( bDbFormatChanged )
{
CRhoFile::deleteFile( m_strDbPath.c_str() );
CRhoFile::deleteFile((m_strDbPath+"-journal").c_str());
}else
{
CRhoFile::renameFile( m_strDbPath.c_str(), (m_strDbPath+"_oldver").c_str());
CRhoFile::renameFile((m_strDbPath+"-journal").c_str(), (m_strDbPath+"_oldver-journal").c_str());
}
if ( m_strDbPartition.compare("user") == 0 ) //do it only once
CRhoFile::deleteFilesInFolder(RHODESAPPBASE().getBlobsDirPath().c_str());
dbNewVer.toFile(m_strDbVerPath);
if ( RHOCONF().isExist("bulksync_state") && RHOCONF().getInt("bulksync_state") != 0)
RHOCONF().setInt("bulksync_state", 0, true);
}
}
sqlite3_stmt* CDBAdapter::createInsertStatement(IDBResult& res, const String& tableName, CDBAdapter& db, String& strInsert)
{
sqlite3_stmt* stInsert = 0;
int nColCount = sqlite3_data_count(res.getStatement());
if ( strInsert.length() == 0 )
{
strInsert = "INSERT INTO ";
strInsert += tableName;
strInsert += "(";
String strQuest = ") VALUES(";
String strValues = "";
for (int nCol = 0; nCol < nColCount; nCol++ )
{
String strColName = sqlite3_column_name(res.getStatement(),nCol);
if ( strColName == "id")
continue;
if ( strValues.length() > 0 )
{
strValues += ",";
strQuest += ",";
}
strValues += strColName;
strQuest += "?";
}
strInsert += strValues + strQuest + ")";
}
int rc = sqlite3_prepare_v2(db.getDbHandle(), strInsert.c_str(), -1, &stInsert, NULL);
if ( !checkDbError(rc) )
return 0;
int nBindCol = 1;
for (int nCol = 0; nCol < nColCount; nCol++ )
{
int nColType = sqlite3_column_type(res.getStatement(),nCol);
String strColName = sqlite3_column_name(res.getStatement(),nCol);
if ( strColName == "id")
continue;
switch(nColType){
case SQLITE_NULL:
rc = sqlite3_bind_text(stInsert, nBindCol, null, -1, SQLITE_TRANSIENT);
break;
case SQLITE_INTEGER:
{
sqlite_int64 nValue = sqlite3_column_int64(res.getStatement(), nCol);
rc = sqlite3_bind_int64(stInsert, nBindCol, nValue);
break;
}
default:{
char* szValue = (char *)sqlite3_column_text(res.getStatement(), nCol);
rc = sqlite3_bind_text(stInsert, nBindCol, szValue, -1, SQLITE_TRANSIENT);
break;
}
}
nBindCol++;
}
return stInsert;
}
static boolean destroyTableName(String tableName, const rho::Vector<rho::String>& arIncludeTables, const rho::Vector<rho::String>& arExcludeTables )
{
int i;
for (i = 0; i < (int)arExcludeTables.size(); i++ )
{
if ( arExcludeTables.elementAt(i).compare(tableName) == 0 )
return false;
}
for (i = 0; i < (int)arIncludeTables.size(); i++ )
{
if ( arIncludeTables.elementAt(i).compare(tableName) == 0 )
return true;
}
return arIncludeTables.size()==0;
}
boolean CDBAdapter::isTableExist(String strTableName)
{
Vector<String> vecTables;
Lock();
IDBResult res = executeSQL( "SELECT name FROM sqlite_master WHERE type='table' AND name=?", strTableName.c_str() );
boolean bRes = !res.isEnd();
Unlock();
return bRes;
}
void CDBAdapter::destroy_tables(const rho::Vector<rho::String>& arIncludeTables, const rho::Vector<rho::String>& arExcludeTables)
{
//getAttrMgr().reset(*this);
CFilePath oFilePath(m_strDbPath);
String dbNewName = oFilePath.changeBaseName("resetdbtemp.sqlite");
CRhoFile::deleteFile(dbNewName.c_str());
CRhoFile::deleteFile((dbNewName+"-journal").c_str());
CRhoFile::deleteFile((dbNewName+".version").c_str());
CDBAdapter db(m_strDbPartition.c_str(), true);
db.open( dbNewName, m_strDbVer, true, false );
//Copy all tables
Vector<String> vecTables;
{
IDBResult res = executeSQL( "SELECT name FROM sqlite_master WHERE type='table' " );
for ( ; !res.isEnd(); res.next() )
vecTables.addElement(res.getStringByIdx(0));
}
db.startTransaction();
for ( int i = 0; i < (int)vecTables.size(); i++ )
{
String tableName = vecTables.elementAt(i);
if (destroyTableName(tableName, arIncludeTables, arExcludeTables) )
continue;
copyTable(tableName, *this, db );
}
db.endTransaction();
db.close();
String dbOldName = m_strDbPath;
close();
CRhoFile::deleteFilesInFolder(RHODESAPPBASE().getBlobsDirPath().c_str());
CRhoFile::deleteFile(dbOldName.c_str());
CRhoFile::renameFile(dbNewName.c_str(),dbOldName.c_str());
open( dbOldName, m_strDbVer, false, false );
}
void CDBAdapter::copyTable(String tableName, CDBAdapter& dbFrom, CDBAdapter& dbTo)
{
String strSelect = "SELECT * from " + tableName;
IDBResult res = dbFrom.executeSQL( strSelect.c_str() );
String strInsert = "";
int rc = 0;
for ( ; !res.isEnd(); res.next() )
{
sqlite3_stmt* stInsert = createInsertStatement(res, tableName, dbTo, strInsert);
if (stInsert)
{
rc = sqlite3_step(stInsert);
checkDbError(rc);
sqlite3_finalize(stInsert);
}
}
}
void CDBAdapter::updateAllAttribChanges()
{
//Check for attrib = object
IDBResult res = executeSQL("SELECT object, source_id, update_type "
"FROM changed_values where attrib = 'object' and sent=0");
if ( res.isEnd() )
return;
startTransaction();
Vector<String> arObj, arUpdateType;
Vector<int> arSrcID;
for( ; !res.isEnd(); res.next() )
{
arObj.addElement(res.getStringByIdx(0));
arSrcID.addElement(res.getIntByIdx(1));
arUpdateType.addElement(res.getStringByIdx(2));
}
for( int i = 0; i < (int)arObj.size(); i++ )
{
IDBResult resSrc = executeSQL("SELECT name, schema FROM sources where source_id=?", arSrcID.elementAt(i) );
boolean bSchemaSource = false;
String strTableName = "object_values";
if ( !resSrc.isEnd() )
{
bSchemaSource = resSrc.getStringByIdx(1).length() > 0;
if ( bSchemaSource )
strTableName = resSrc.getStringByIdx(0);
}
if (bSchemaSource)
{
IDBResult res2 = executeSQL((String("SELECT * FROM ") + strTableName + " where object=?").c_str(), arObj.elementAt(i) );
for( int j = 0; j < res2.getColCount(); j ++)
{
if ( res2.isNullByIdx(j) )
continue;
String strAttrib = res2.getColName(j);
String value = res2.getStringByIdx(j);
String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib.c_str()) ? "blob.file" : "";
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0);
}
}else
{
IDBResult res2 = executeSQL((String("SELECT attrib, value FROM ") + strTableName + " where object=? and source_id=?").c_str(),
arObj.elementAt(i), arSrcID.elementAt(i) );
for( ; !res2.isEnd(); res2.next() )
{
if ( res2.isNullByIdx(1) )
continue;
String strAttrib = res2.getStringByIdx(0);
String value = res2.getStringByIdx(1);
String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib.c_str()) ? "blob.file" : "";
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0);
}
}
}
executeSQL("DELETE FROM changed_values WHERE attrib='object'");
endTransaction();
}
void CDBAdapter::updateFullUpdateChanges(int nSrcID)
{
IDBResult res = executeSQL("SELECT object, source_id, update_type, attrib FROM changed_values where source_id=? and update_type=? and sent=0", nSrcID, "update");
if ( res.isEnd() )
return;
startTransaction();
Vector<String> arObj, arUpdateType, arAttribs;
Vector<int> arSrcID;
for( ; !res.isEnd(); res.next() )
{
arObj.addElement(res.getStringByIdx(0));
arSrcID.addElement(res.getIntByIdx(1));
arUpdateType.addElement(res.getStringByIdx(2));
arAttribs.addElement(res.getStringByIdx(3));
}
Hashtable<String, int> hashObjs;
for( int i = 0; i < (int)arObj.size(); i++ )
{
if (hashObjs.containsKey(arObj.elementAt(i)))
continue;
hashObjs.put(arObj.elementAt(i), 1);
IDBResult resSrc = executeSQL("SELECT name, schema FROM sources where source_id=?", arSrcID.elementAt(i) );
boolean bSchemaSource = false;
String strTableName = "object_values";
if ( !resSrc.isEnd() )
{
bSchemaSource = resSrc.getStringByIdx(1).length() > 0;
if ( bSchemaSource )
strTableName = resSrc.getStringByIdx(0);
}
if (bSchemaSource)
{
IDBResult res2 = executeSQL((String("SELECT * FROM ") + strTableName + " where object=?").c_str(), arObj.elementAt(i) );
for( int j = 0; j < res2.getColCount(); j ++)
{
if ( res2.isNullByIdx(j) )
continue;
String strAttrib = res2.getColName(j);
String value = res2.getStringByIdx(j);
String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib.c_str()) ? "blob.file" : "";
boolean bDuplicate = false;
for( int k = i; k < (int)arObj.size(); k++ )
{
if ( arObj.elementAt(k) == arObj.elementAt(i) && strAttrib == arAttribs.elementAt(k) )
{
bDuplicate = true;
break;
}
}
if ( bDuplicate )
continue;
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0);
}
}else
{
IDBResult res2 = executeSQL((String("SELECT attrib, value FROM ") + strTableName + " where object=? and source_id=?").c_str(),
arObj.elementAt(i), arSrcID.elementAt(i) );
for( ; !res2.isEnd(); res2.next() )
{
if ( res2.isNullByIdx(1) )
continue;
String strAttrib = res2.getStringByIdx(0);
String value = res2.getStringByIdx(1);
String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib.c_str()) ? "blob.file" : "";
boolean bDuplicate = false;
for( int k = i; k < (int)arObj.size(); k++ )
{
if ( arObj.elementAt(k) == arObj.elementAt(i) && strAttrib == arAttribs.elementAt(k) )
{
bDuplicate = true;
break;
}
}
if ( bDuplicate )
continue;
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0);
}
}
}
endTransaction();
}
void CDBAdapter::copyChangedValues(CDBAdapter& db)
{
updateAllAttribChanges();
copyTable("changed_values", *this, db );
{
Vector<int> arOldSrcs;
{
IDBResult resSrc = db.executeSQL( "SELECT DISTINCT(source_id) FROM changed_values" );
for ( ; !resSrc.isEnd(); resSrc.next() )
arOldSrcs.addElement( resSrc.getIntByIdx(0) );
}
for( int i = 0; i < (int)arOldSrcs.size(); i++)
{
int nOldSrcID = arOldSrcs.elementAt(i);
IDBResult res = executeSQL("SELECT name from sources WHERE source_id=?", nOldSrcID);
if ( !res.isEnd() )
{
String strSrcName = res.getStringByIdx(0);
IDBResult res2 = db.executeSQL("SELECT source_id from sources WHERE name=?", strSrcName);
if ( !res2.isEnd() )
{
if ( nOldSrcID != res2.getIntByIdx(0) )
db.executeSQL("UPDATE changed_values SET source_id=? WHERE source_id=?", res2.getIntByIdx(0), nOldSrcID);
continue;
}
}
//source not exist in new partition, remove this changes
db.executeSQL("DELETE FROM changed_values WHERE source_id=?", nOldSrcID);
}
}
}
void CDBAdapter::setBulkSyncDB(String fDataName, String strCryptKey)
{
if (rho::sync::RhoconnectClientManager::haveRhoconnectClientImpl()) {
CDBAdapter db(m_strDbPartition.c_str(), true);
db.setCryptKey(strCryptKey);
db.open( fDataName, m_strDbVer, true, false );
db.createTriggers();
db.startTransaction();
copyTable("client_info", *this, db );
copyChangedValues(db);
getDBPartitions().put(m_strDbPartition.c_str(), &db);
// sync::CSyncThread::getSyncEngine().applyChangedValues(db);
rho::sync::RhoconnectClientManager::syncEngineApplyChangedValues(db);
getDBPartitions().put(m_strDbPartition.c_str(), this);
db.endTransaction();
db.close();
String dbOldName = m_strDbPath;
close(false);
CRhoFile::deleteFilesInFolder(RHODESAPPBASE().getBlobsDirPath().c_str());
CRhoFile::deleteFile(dbOldName.c_str());
CRhoFile::renameFile(fDataName.c_str(),dbOldName.c_str());
setCryptKey(strCryptKey);
open( dbOldName, m_strDbVer, false, false );
}
}
void CDBAdapter::setImportDB(String fDataName, String strCryptKey)
{
CDBAdapter db(m_strDbPartition.c_str(), true);
db.setCryptKey(strCryptKey);
db.open( fDataName, m_strDbVer, true, false );
//db.createTriggers();
db.startTransaction();
copyTable("client_info", *this, db );
//copyChangedValues(db);
//getDBPartitions().put(m_strDbPartition.c_str(), &db);
//sync::CSyncThread::getSyncEngine().applyChangedValues(db);
//getDBPartitions().put(m_strDbPartition.c_str(), this);
db.endTransaction();
db.close();
String dbOldName = m_strDbPath;
close(false);
CRhoFile::deleteFilesInFolder(RHODESAPPBASE().getBlobsDirPath().c_str());
CRhoFile::deleteFile(dbOldName.c_str());
CRhoFile::renameFile(fDataName.c_str(),dbOldName.c_str());
setCryptKey(strCryptKey);
open( dbOldName, m_strDbVer, false, false );
}
void CDBAdapter::executeBatch(const char* szSql, CDBError& error)
{
char* errmsg = 0;
int rc = sqlite3_exec(m_dbHandle, szSql, NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
LOG(ERROR)+"execute batch failed. Error code: " + rc + ";Message: " + (errmsg ? errmsg : "");
error.setError(rc, errmsg);
if ( errmsg )
sqlite3_free(errmsg);
}
void CDBAdapter::createSchema()
{
#ifdef RHODES_EMULATOR
String strPath = CFilePath::join( RHOSIMCONF().getRhodesPath(), "platform/shared/db/res/db/syncdb.schema" );
#else
String strPath = CFilePath::join( RHODESAPP().getRhoRootPath(), "db/syncdb.schema" );
#endif
String strSqlScript;
CRhoFile::loadTextFile(strPath.c_str(), strSqlScript);
if ( strSqlScript.length() == 0 )
{
LOG(ERROR)+"createSchema failed. Cannot read schema file: " + strSqlScript;
return;
}
CDBError dbError;
executeBatch(strSqlScript.c_str(), dbError);
if ( dbError.isOK() )
createTriggers();
}
void CDBAdapter::createTriggers()
{
char* errmsg = 0;
#ifdef RHODES_EMULATOR
String strPath = CFilePath::join( RHOSIMCONF().getRhodesPath(), "platform/shared/db/res/db/syncdb.triggers" );
#else
String strPath = CFilePath::join( RHODESAPP().getRhoRootPath(), "db/syncdb.triggers" );
#endif
String strSqlTriggers;
CRhoFile::loadTextFile(strPath.c_str(), strSqlTriggers);
if ( strSqlTriggers.length() == 0 )
{
LOG(ERROR)+"createTriggers failed. Cannot read triggers file: " + strSqlTriggers;
return;
}
int rc = sqlite3_exec(m_dbHandle, strSqlTriggers.c_str(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
LOG(ERROR)+"createTriggers failed. Error code: " + rc + ";Message: " + (errmsg ? errmsg : "");
if ( errmsg )
sqlite3_free(errmsg);
}
void CDBAdapter::createTrigger(const String& strSQL)
{
char* errmsg = 0;
int rc = sqlite3_exec(m_dbHandle, strSQL.c_str(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
LOG(ERROR)+"createTrigger failed. Error code: " + rc + ";Message: " + (errmsg ? errmsg : "");
}
void CDBAdapter::dropTrigger(const String& strName)
{
String strSQL = "DROP TRIGGER " + strName + ";";
char* errmsg = 0;
int rc = sqlite3_exec(m_dbHandle, strSQL.c_str(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
LOG(ERROR)+"dropTrigger failed. Error code: " + rc + ";Message: " + (errmsg ? errmsg : "");
}
void CDBAdapter::close(boolean bCloseRubyMutex/* = true*/)
{
for (Hashtable<String,sqlite3_stmt*>::iterator it = m_mapStatements.begin(); it != m_mapStatements.end(); ++it )
sqlite3_finalize( it->second );
m_mapStatements.clear();
if ( m_dbHandle != 0 )
sqlite3_close(m_dbHandle);
m_dbHandle = 0;
m_strDbPath = String();
m_ptrCrypt = 0;
m_strCryptKey = "";
if ( bCloseRubyMutex )
m_mxRuby.close();
}
int CDBAdapter::prepareSqlStatement(const char* szSql, int nByte, sqlite3_stmt **ppStmt)
{
int rc = SQLITE_OK;
sqlite3_stmt* st = m_mapStatements.get(szSql);
if ( st != null )
*ppStmt = st;
else
{
rc = sqlite3_prepare_v2(m_dbHandle, szSql, nByte, ppStmt, NULL);
if ( rc == SQLITE_OK )
m_mapStatements.put(szSql, *ppStmt);
}
return rc;
}
DBResultPtr CDBAdapter::prepareStatement( const char* szSt )
{
if ( m_dbHandle == null )
return new CDBResult();
DBResultPtr res = new CDBResult(0,this);
sqlite3_stmt* st = m_mapStatements.get(szSt);
if ( st != null )
{
res->setStatement(st);
return res;
}
int rc = sqlite3_prepare_v2(m_dbHandle, szSt, -1, &st, NULL);
if ( !checkDbErrorEx(rc,*res) )
{
//TODO: raise exception
return res;
}
res->setStatement(st);
m_mapStatements.put(szSt, st);
return res;
}
DBResultPtr CDBAdapter::executeSQLReportNonUniqueEx( const char* szSt, Vector<String>& arValues )
{
DBResultPtr res = prepareStatement(szSt);
if ( res->getStatement() == null )
return res;
for (int i = 0; i < (int)arValues.size(); i++ )
bind(res->getStatement(), i+1, arValues.elementAt(i));
res->setReportNonUnique(true);
return executeStatement(res, szSt);
}
DBResultPtr CDBAdapter::executeSQLEx( const char* szSt, Vector<String>& arValues)
{
DBResultPtr res = prepareStatement(szSt);
if ( res->getStatement() == null )
return res;
for (int i = 0; i < (int)arValues.size(); i++ )
bind(res->getStatement(), i+1, arValues.elementAt(i));
return executeStatement(res, szSt);
}
DBResultPtr CDBAdapter::executeSQL( const char* szSt)
{
DBResultPtr res = prepareStatement(szSt);
if ( res->getStatement() == null )
return res;
return executeStatement(res, szSt);
}
DBResultPtr CDBAdapter::executeStatement(DBResultPtr& res, const char* szSt)
{
//LOG(INFO) + "executeStatement:" + szSt;
int rc = sqlite3_step(res->getStatement());
if ( rc != SQLITE_ROW )
{
res->setStatement(null);
if ( rc != SQLITE_OK && rc != SQLITE_ROW && rc != SQLITE_DONE )
{
checkDbErrorEx(rc, *res);
//TODO: raise exception
return res;
}
}
return res;
}
void CDBAdapter::Lock()
{
if ( m_mxRuby.isMainRubyThread() )
m_bUIWaitDB = true;
m_mxRuby.Lock();
m_mxDB.Lock();
if ( m_mxRuby.isMainRubyThread() )
m_bUIWaitDB = false;
}
void CDBAdapter::Unlock()
{
m_mxDB.Unlock();
m_mxRuby.Unlock();
}
void CDBAdapter::startTransaction()
{
Lock();
m_nTransactionCounter++;
char *zErr = 0;
int rc = 0;
if ( m_dbHandle && m_nTransactionCounter == 1)
{
rc = sqlite3_exec(m_dbHandle, "BEGIN IMMEDIATE;",0,0,&zErr);
checkDbError(rc);
}
}
void CDBAdapter::endTransaction()
{
char *zErr = 0;
int rc = 0;
m_nTransactionCounter--;
if (m_dbHandle && m_nTransactionCounter == 0)
{
//getAttrMgr().save(*this);
rc = sqlite3_exec(m_dbHandle, "END;",0,0,&zErr);
checkDbError(rc);
}
Unlock();
}
void CDBAdapter::rollback()
{
char *zErr = 0;
int rc = 0;
m_nTransactionCounter--;
if (m_dbHandle && m_nTransactionCounter == 0)
{
rc = sqlite3_exec(m_dbHandle, "ROLLBACK;",0,0,&zErr);
checkDbError(rc);
}
Unlock();
}
String CDBAdapter::exportDatabase() {
String basePath = CFilePath(m_strDbPath).getFolderName();
String zipName = m_strDbPath + ".zip";
DBLock lock(*this);
CDBRequestHelper reqHelper(*this);
Vector<String> fileList = reqHelper.requestBlobs();
for ( Vector<String>::iterator it = fileList.begin(); it != fileList.end(); ++it ) {
String rel = RHODESAPP().getRelativeDBFilesPath(*it);
if ( ((rel).find('/') == String::npos) && ((rel).find('\\') == String::npos) ) {
(*it) = common::CFilePath::join( RHODESAPP().getBlobsDirPath(),rel);
} else {
*it = common::CFilePath::join( RHODESAPP().getDBFileRoot(),rel);
}
}
fileList.push_back(m_strDbPath);
String path = m_strDbPath;
String ver = m_strDbVer;
close(false);
String ret = zipName;
if (rho_sys_zip_files_with_path_array_ptr(zipName.c_str(),basePath.c_str(),fileList,0)!=0) {
ret = "";
}
open(path,ver,false,false);
return ret;
}
bool CDBAdapter::importDatabase( const String& zipName ) {
CDBImportTransaction importTxn(*this,zipName);
if (!importTxn.commit()) {
importTxn.rollback();
return false;
}
return true;
}
/*static*/ void CDBAdapter::closeAll()
{
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
it->second->close();
}
/*static*/ void CDBAdapter::initAttrManager()
{
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
it->second->getAttrMgr().loadBlobAttrs(*(it->second));
}
/*static*/ CDBAdapter& CDBAdapter::getUserDB()
{
return *getDBPartitions().get(USER_PARTITION_NAME());
}
/*static*/ CDBAdapter& CDBAdapter::getDB(const char* szPartition)
{
return *getDBPartitions().get(szPartition);
}
/*static*/ Vector<String> CDBAdapter::getDBAllPartitionNames()
{
Vector<String> vecNames;
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
vecNames.addElement(it->first);
return vecNames;
}
/*static*/ boolean CDBAdapter::isAnyInsideTransaction()
{
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
{
if ( it->second->isInsideTransaction() )
return true;
}
return false;
}
/*static void CDBAdapter::destroy_tables_allpartitions(const rho::Vector<rho::String>& arIncludeTables, const rho::Vector<rho::String>& arExcludeTables)
{
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
{
it->second->destroy_tables(arIncludeTables, arExcludeTables);
}
}*/
/*static*/ db::CDBAdapter& CDBAdapter::getDBByHandle(sqlite3* db)
{
for (Hashtable<String,CDBAdapter*>::iterator it = m_mapDBPartitions.begin(); it != m_mapDBPartitions.end(); ++it )
{
if ( it->second->getDbHandle() == db )
return *(it->second);
}
return *getDBPartitions().get(USER_PARTITION_NAME());
}
}
}
extern "C" {
using namespace rho::db;
int rho_db_open(const char* szDBPath, const char* szDBPartition, void** ppDB)
{
CFilePath oPath(szDBPath);
CDBAdapter* pDB = CDBAdapter::getDBPartitions().get(szDBPartition);
if ( !pDB )
{
pDB = new CDBAdapter(szDBPartition, false);
CDBAdapter::getDBPartitions().put(szDBPartition, pDB);
}
rho::String strVer = RhoAppAdapter.getRhoDBVersion();
pDB->open(szDBPath,strVer, false,true);
*ppDB = pDB;
return 0;
}
int rho_db_close(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.close();
//TODO: get error code from DBException
return 0;
}
int rho_db_startTransaction(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.startTransaction();
//TODO: get error code from DBException
return 0;
}
int rho_db_commitTransaction(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.endTransaction();
//TODO: get error code from DBException
return 0;
}
int rho_db_rollbackTransaction(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.rollback();
//TODO: get error code from DBException
return 0;
}
int rho_db_is_ui_waitfordb(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return db.isUIWaitDB() ? 1 :0;
}
extern "C" void
string_iter(const char* szVal, void* par)
{
rho::Vector<rho::String>& ar = *((rho::Vector<rho::String>*)(par));
ar.addElement(szVal);
}
#ifndef RHO_NO_RUBY
int rho_db_destroy_tables(void* pDB, unsigned long arInclude, unsigned long arExclude)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
rho::Vector<rho::String> arIncludeTables;
rho_ruby_enum_strary(arInclude, string_iter, &arIncludeTables);
rho::Vector<rho::String> arExcludeTables;
rho_ruby_enum_strary(arExclude, string_iter, &arExcludeTables);
db.destroy_tables(arIncludeTables,arExcludeTables);
return 0;
}
VALUE rho_db_export(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return rho_ruby_create_string(db.exportDatabase().c_str());
}
int rho_db_import(void* pDB, const char* zipName)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return db.importDatabase(zipName)? 1 : 0;
}
unsigned long rho_sys_is_blob_attr(const char* szPartition, int nSrcID, const char* szAttrName)
{
return rho_ruby_create_boolean( CDBAdapter::getDB(szPartition).getAttrMgr().isBlobAttr(nSrcID, szAttrName) );
}
#endif //RHO_NO_RUBY
void* rho_db_get_handle(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return db.getDbHandle();
}
/*
void* rho_db_user_get_handle()
{
rho::db::CDBAdapter& db = rho::db::CDBAdapter::getUserDB();
return db.getDbHandle();
}
void* rho_db_user_get_adapter()
{
rho::db::CDBAdapter& db = rho::db::CDBAdapter::getUserDB();
return &db;
} */
int rho_db_prepare_statement(void* pDB, const char* szSql, int nByte, sqlite3_stmt **ppStmt)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return db.prepareSqlStatement(szSql, nByte, ppStmt);
}
void rho_db_lock(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.Lock();
}
void rho_db_unlock(void* pDB)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
db.Unlock();
}
int rho_db_is_table_exist(void* pDB, const char* szTableName)
{
rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)pDB);
return db.isTableExist(szTableName) ? 1 : 0;
}
void rho_db_init_attr_manager()
{
rho::db::CDBAdapter::initAttrManager();
}
void rho_sys_update_blob_attribs(const char* szPartition, int source_id)
{
rho::db::CDBAdapter& db = rho::db::CDBAdapter::getDB(szPartition);
db.getAttrMgr().loadBlobAttrs(db);
}
void rho_db_encrypt( const char* szPartition, int nPartLen, int size, unsigned char* data, unsigned char* dataOut )
{
String strPartition(szPartition, nPartLen);
rho::db::CDBAdapter& db = rho::db::CDBAdapter::getDB(strPartition.c_str());
if ( db.getCrypt() )
db.getCrypt()->db_encrypt(strPartition.c_str(), size, data, dataOut);
else
memcpy(dataOut, data, size);
}
void rho_db_decrypt( const char* szPartition, int nPartLen, int size, unsigned char* data )
{
String strPartition(szPartition, nPartLen);
rho::db::CDBAdapter& db = rho::db::CDBAdapter::getDB( strPartition.c_str() );
if ( db.getCrypt() )
db.getCrypt()->db_decrypt(strPartition.c_str(), size, data);
}
}
namespace rho{
namespace common{
#ifndef RHO_NO_RUBY
CRubyMutex::CRubyMutex(boolean bIgnore) : m_nLockCount(0), m_valThread(0), m_valMutex(null)
{
m_bIgnore = bIgnore || RHOCONF().getBool("no_ruby_threads");
}
void CRubyMutex::create()
{
if ( !m_bIgnore && !m_valMutex)
m_valMutex = rho_ruby_create_mutex();
}
CRubyMutex::~CRubyMutex()
{
close();
}
void CRubyMutex::close()
{
if ( m_valMutex )
{
rho_ruby_destroy_mutex(m_valMutex);
m_valMutex = 0;
}
}
boolean CRubyMutex::isMainRubyThread()
{
return rho_ruby_main_thread() == rho_ruby_current_thread();
}
void CRubyMutex::Lock()
{
if ( m_valMutex == null )
return;
unsigned long curThread = rho_ruby_current_thread();
if ( curThread == null )
return;
if ( m_valThread != curThread )
{
rho_ruby_lock_mutex(m_valMutex);
m_valThread = curThread;
m_nLockCount = 1;
}else
m_nLockCount += 1;
}
void CRubyMutex::Unlock()
{
if ( m_valMutex == null || m_nLockCount == 0)
return;
m_nLockCount--;
if ( m_nLockCount == 0 )
{
m_valThread = null;
rho_ruby_unlock_mutex(m_valMutex);
}
}
#else //RHO_NO_RUBY
CRubyMutex::CRubyMutex(boolean bIgnore) : m_nLockCount(0), m_valThread(0), m_valMutex(null)
{
}
CRubyMutex::~CRubyMutex()
{
}
boolean CRubyMutex::isMainRubyThread()
{
if ( (!sync::RhoconnectClientManager::haveRhoconnectClientImpl()) || (!sync::RhoconnectClientManager::haveSyncThread()))
// if ( !sync::CSyncThread::getInstance() )
return true;
//return sync::CSyncThread::getInstance()->getThreadID() != CSystem::getThreadID();
return sync::RhoconnectClientManager::syncThreadGetThreadID() != CSystem::getThreadID();
}
void CRubyMutex::Lock()
{
}
void CRubyMutex::Unlock()
{
}
void CRubyMutex::close()
{
}
void CRubyMutex::create()
{
}
#endif //RHO_NO_RUBY
}
}
| 29.645749 | 165 | 0.630613 | jjfraz11 |
cdd66f3fdd4f4cbd8a5d1bedc91b172b0727f686 | 1,824 | hpp | C++ | layout/include/nesci/layout/spike_detector.hpp | halfflat/nesci | 60f90b41d4d4c50a306fe2af28b322c1cbef943c | [
"Apache-2.0"
] | null | null | null | layout/include/nesci/layout/spike_detector.hpp | halfflat/nesci | 60f90b41d4d4c50a306fe2af28b322c1cbef943c | [
"Apache-2.0"
] | null | null | null | layout/include/nesci/layout/spike_detector.hpp | halfflat/nesci | 60f90b41d4d4c50a306fe2af28b322c1cbef943c | [
"Apache-2.0"
] | 1 | 2018-10-11T15:14:36.000Z | 2018-10-11T15:14:36.000Z | //------------------------------------------------------------------------------
// nesci -- neuronal simulator conan interface
//
// Copyright (c) 2018 RWTH Aachen University, Germany,
// Virtual Reality & Immersive Visualization Group.
//------------------------------------------------------------------------------
// License
//
// 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 LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
#define LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
#include <string>
#include "nesci/layout/device.hpp"
namespace nesci {
namespace layout {
class SpikeDetector : public Device {
public:
SpikeDetector() = delete;
explicit SpikeDetector(const std::string& name);
SpikeDetector(const SpikeDetector&) = default;
explicit SpikeDetector(const Device& device);
SpikeDetector(SpikeDetector&&) = default;
explicit SpikeDetector(Device&& device);
~SpikeDetector() override = default;
SpikeDetector& operator=(const SpikeDetector&) = default;
SpikeDetector& operator=(SpikeDetector&&) = default;
std::string GetPath() const override;
};
} // namespace layout
} // namespace nesci
#endif // LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
| 35.076923 | 80 | 0.645285 | halfflat |
cdd6d6354490997081eaa944e7bd55f72e3091fb | 6,367 | cpp | C++ | src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qsize.h>
class tst_QSize : public QObject
{
Q_OBJECT
private slots:
void getSetCheck();
void scale();
void expandedTo();
void expandedTo_data();
void boundedTo_data();
void boundedTo();
void transpose_data();
void transpose();
};
// Testing get/set functions
void tst_QSize::getSetCheck()
{
QSize obj1;
// int QSize::width()
// void QSize::setWidth(int)
obj1.setWidth(0);
QCOMPARE(0, obj1.width());
obj1.setWidth(INT_MIN);
QCOMPARE(INT_MIN, obj1.width());
obj1.setWidth(INT_MAX);
QCOMPARE(INT_MAX, obj1.width());
// int QSize::height()
// void QSize::setHeight(int)
obj1.setHeight(0);
QCOMPARE(0, obj1.height());
obj1.setHeight(INT_MIN);
QCOMPARE(INT_MIN, obj1.height());
obj1.setHeight(INT_MAX);
QCOMPARE(INT_MAX, obj1.height());
QSizeF obj2;
// qreal QSizeF::width()
// void QSizeF::setWidth(qreal)
obj2.setWidth(0.0);
QCOMPARE(0.0, obj2.width());
obj2.setWidth(1.1);
QCOMPARE(1.1, obj2.width());
// qreal QSizeF::height()
// void QSizeF::setHeight(qreal)
obj2.setHeight(0.0);
QCOMPARE(0.0, obj2.height());
obj2.setHeight(1.1);
QCOMPARE(1.1, obj2.height());
}
void tst_QSize::scale()
{
QSize t1( 10, 12 );
t1.scale( 60, 60, Qt::IgnoreAspectRatio );
QCOMPARE( t1, QSize(60, 60) );
QSize t2( 10, 12 );
t2.scale( 60, 60, Qt::KeepAspectRatio );
QCOMPARE( t2, QSize(50, 60) );
QSize t3( 10, 12 );
t3.scale( 60, 60, Qt::KeepAspectRatioByExpanding );
QCOMPARE( t3, QSize(60, 72) );
QSize t4( 12, 10 );
t4.scale( 60, 60, Qt::KeepAspectRatio );
QCOMPARE( t4, QSize(60, 50) );
QSize t5( 12, 10 );
t5.scale( 60, 60, Qt::KeepAspectRatioByExpanding );
QCOMPARE( t5, QSize(72, 60) );
// test potential int overflow
QSize t6(88473, 88473);
t6.scale(141817, 141817, Qt::KeepAspectRatio);
QCOMPARE(t6, QSize(141817, 141817));
QSize t7(800, 600);
t7.scale(400, INT_MAX, Qt::KeepAspectRatio);
QCOMPARE(t7, QSize(400, 300));
QSize t8(800, 600);
t8.scale(INT_MAX, 150, Qt::KeepAspectRatio);
QCOMPARE(t8, QSize(200, 150));
QSize t9(600, 800);
t9.scale(300, INT_MAX, Qt::KeepAspectRatio);
QCOMPARE(t9, QSize(300, 400));
QSize t10(600, 800);
t10.scale(INT_MAX, 200, Qt::KeepAspectRatio);
QCOMPARE(t10, QSize(150, 200));
QSize t11(0, 0);
t11.scale(240, 200, Qt::IgnoreAspectRatio);
QCOMPARE(t11, QSize(240, 200));
QSize t12(0, 0);
t12.scale(240, 200, Qt::KeepAspectRatio);
QCOMPARE(t12, QSize(240, 200));
QSize t13(0, 0);
t13.scale(240, 200, Qt::KeepAspectRatioByExpanding);
QCOMPARE(t13, QSize(240, 200));
}
void tst_QSize::expandedTo_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("input2");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(10,12);
QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(6,4);
// This should pick the highest of w,h components independently of each other,
// thus the results don't have to be equal to neither input1 nor input2.
QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(6,6);
}
void tst_QSize::expandedTo()
{
QFETCH( QSize, input1);
QFETCH( QSize, input2);
QFETCH( QSize, expected);
QCOMPARE( input1.expandedTo(input2), expected);
}
void tst_QSize::boundedTo_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("input2");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(6,4);
QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(0,0);
// This should pick the lowest of w,h components independently of each other,
// thus the results don't have to be equal to neither input1 nor input2.
QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(4,4);
}
void tst_QSize::boundedTo()
{
QFETCH( QSize, input1);
QFETCH( QSize, input2);
QFETCH( QSize, expected);
QCOMPARE( input1.boundedTo(input2), expected);
}
void tst_QSize::transpose_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(12,10);
QTest::newRow("data1") << QSize(0,0) << QSize(0,0);
QTest::newRow("data3") << QSize(6,4) << QSize(4,6);
}
void tst_QSize::transpose()
{
QFETCH( QSize, input1);
QFETCH( QSize, expected);
// transpose() works only inplace and does not return anything, so we must do the operation itself before the compare.
input1.transpose();
QCOMPARE(input1 , expected);
}
QTEST_APPLESS_MAIN(tst_QSize)
#include "tst_qsize.moc"
| 29.476852 | 122 | 0.641275 | power-electro |
cdd86cd37fbbfb7ed78c314cfa0208fc260b1c1f | 2,860 | hpp | C++ | lib/dmitigr/fcgi/listener_options.hpp | dmitigr/fcgi | 0d3755e87c8fe168a7325c5fb93f450375601bfc | [
"Zlib"
] | 40 | 2019-05-16T14:37:10.000Z | 2022-03-25T11:35:13.000Z | lib/dmitigr/fcgi/listener_options.hpp | dmitigr/fcgi | 0d3755e87c8fe168a7325c5fb93f450375601bfc | [
"Zlib"
] | 2 | 2019-05-30T09:41:03.000Z | 2020-05-27T18:29:38.000Z | lib/dmitigr/fcgi/listener_options.hpp | dmitigr/fcgi | 0d3755e87c8fe168a7325c5fb93f450375601bfc | [
"Zlib"
] | 6 | 2019-05-17T13:13:41.000Z | 2022-01-18T01:26:50.000Z | // -*- C++ -*-
// Copyright (C) Dmitry Igrishin
// For conditions of distribution and use, see files LICENSE.txt or fcgi.hpp
#ifndef DMITIGR_FCGI_LISTENER_OPTIONS_HPP
#define DMITIGR_FCGI_LISTENER_OPTIONS_HPP
#include "dmitigr/fcgi/dll.hpp"
#include "dmitigr/fcgi/types_fwd.hpp"
#include <dmitigr/misc/filesystem.hpp>
#include <dmitigr/net/types_fwd.hpp>
#include <memory>
#include <optional>
#include <string>
namespace dmitigr::fcgi {
/**
* @brief FastCGI Listener options.
*/
class Listener_options {
public:
/**
* @brief The destructor.
*/
virtual ~Listener_options() = default;
/// @name Constructors
/// @{
#ifdef _WIN32
/**
* @returns A new instance of the options for listeners of
* Windows Named Pipes (WNP).
*
* @param pipe_name - the pipe name.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::wnp)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string pipe_name);
#else
/**
* @returns A new instance of the options for listeners of
* Unix Domain Sockets (UDS).
*
* @param path - the path to the socket.
* @param backlog - the maximum size of the queue of pending connections.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::uds)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::filesystem::path path, int backlog);
#endif
/**
* @overload
*
* @returns A new instance of the options for listeners of network.
*
* @param address - IPv4 or IPv6 address to use for binding on.
* @param port - the port number to use for binding on.
* @param backlog - the maximum size of the queue of pending connections.
*
* @par Requires
* `(port > 0)`.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::net)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string address, int port, int backlog);
/**
* @returns A new instance of the Listener initialized with this instance.
*
* @see Listener::make().
*/
virtual std::unique_ptr<Listener> make_listener() const = 0;
/**
* @returns The copy of this instance.
*/
virtual std::unique_ptr<Listener_options> to_listener_options() const = 0;
/// @}
/**
* @returns The endpoint identifier.
*/
virtual const net::Endpoint& endpoint() const = 0;
/**
* @returns The value of backlog if the communication mode of the endpoint is
* not `Communication_mode::wnp`, or `std::nullopt` otherwise.
*/
virtual std::optional<int> backlog() const = 0;
private:
friend detail::iListener_options;
Listener_options() = default;
};
} // namespace dmitigr::fcgi
#ifdef DMITIGR_FCGI_HEADER_ONLY
#include "dmitigr/fcgi/listener_options.cpp"
#endif
#endif // DMITIGR_FCGI_LISTENER_OPTIONS_HPP
| 25.535714 | 109 | 0.682517 | dmitigr |
cdd9dfffa913dd308cd4a4856d4f5dec7a85dfc3 | 1,603 | cpp | C++ | client/ModelGenerated/checkinvitation.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 1 | 2015-08-23T11:03:58.000Z | 2015-08-23T11:03:58.000Z | client/ModelGenerated/checkinvitation.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | null | null | null | client/ModelGenerated/checkinvitation.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 3 | 2016-12-05T02:43:52.000Z | 2021-06-30T21:35:46.000Z | #include "listwrapperobjects.h"
#include "checkinvitation.h"
namespace MoodBox
{
CheckInvitationData::CheckInvitationData() : QSharedData()
{
}
CheckInvitationData::CheckInvitationData(QString code) : QSharedData()
{
this->code = code;
}
CheckInvitationData::~CheckInvitationData()
{
}
CheckInvitation::CheckInvitation() : TransportableObject()
{
}
CheckInvitation::CheckInvitation(QString code) : TransportableObject()
{
d = new CheckInvitationData(code);
}
CheckInvitation::~CheckInvitation()
{
}
QString CheckInvitation::getCode() const
{
Q_ASSERT_X(!isNull(), "CheckInvitation::getCode", "Getter call on object which isNull");
return this->d->code;
}
void CheckInvitation::setCode(QString value)
{
Q_ASSERT_X(!isNull(), "CheckInvitation::setCode", "Setter call on object which isNull");
this->d->code = value;
}
qint32 CheckInvitation::getRepresentedTypeId()
{
return 10091;
}
qint32 CheckInvitation::getTypeId() const
{
return 10091;
}
void CheckInvitation::writeProperties(PropertyWriter *writer)
{
TransportableObject::writeProperties(writer);
writer->writeProperty(this, 1, this->d->code);
}
PropertyReadResult CheckInvitation::readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader)
{
PropertyReadResult result = TransportableObject::readProperty(propertyId, typeId, reader);
if(result.getIsPropertyFound())
return result;
switch(propertyId)
{
case 1:
this->d->code = reader->readString();
return PropertyReadResult(true);
}
return PropertyReadResult(false);
}
}
| 21.662162 | 106 | 0.724267 | vorushin |
cddd2cc64e4c0b9b7997379e13f67349cbe04451 | 2,340 | cpp | C++ | test/sql/create_index_options_test.cpp | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 971 | 2020-09-13T10:24:02.000Z | 2022-03-31T07:02:51.000Z | test/sql/create_index_options_test.cpp | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 1,019 | 2018-07-20T23:11:10.000Z | 2020-09-10T06:41:42.000Z | test/sql/create_index_options_test.cpp | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 318 | 2018-07-23T16:48:16.000Z | 2020-09-07T09:46:31.000Z |
#include "execution/compiler/output_checker.h"
#include "gtest/gtest.h"
#include "spdlog/fmt/fmt.h"
#include "storage/index/bplustree_index.h"
#include "storage/index/index.h"
#include "test_util/end_to_end_test.h"
#include "test_util/test_harness.h"
namespace noisepage::test {
class CreateIndexOptionsTest : public EndToEndTest {
public:
void SetUp() override {
EndToEndTest::SetUp();
auto exec_ctx = MakeExecCtx();
GenerateTestTables(exec_ctx.get());
}
};
// NOLINTNEXTLINE
TEST_F(CreateIndexOptionsTest, BPlusTreeOptions) {
RunQuery("CREATE INDEX test_2_idx_upper ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_UPPER_THRESHOLD = 256)");
RunQuery("CREATE INDEX test_2_idx_lower ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_LOWER_THRESHOLD = 4)");
RunQuery(
"CREATE INDEX test_2_idx_both ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_UPPER_THRESHOLD = 256, "
"BPLUSTREE_INNER_NODE_LOWER_THRESHOLD = 4)");
auto test_2_idx_upper = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_upper"));
auto test_2_idx_lower = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_lower"));
auto test_2_idx_both = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_both"));
ASSERT_TRUE(test_2_idx_upper);
ASSERT_TRUE(test_2_idx_lower);
ASSERT_TRUE(test_2_idx_both);
ASSERT_EQ(test_2_idx_upper->Type(), storage::index::IndexType::BPLUSTREE);
ASSERT_EQ(test_2_idx_lower->Type(), storage::index::IndexType::BPLUSTREE);
ASSERT_EQ(test_2_idx_both->Type(), storage::index::IndexType::BPLUSTREE);
auto test_2_idx_upper_bpt_index =
test_2_idx_upper.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>();
auto test_2_idx_lower_bpt_index =
test_2_idx_lower.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>();
auto test_2_idx_both_bpt_index =
test_2_idx_both.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>();
ASSERT_EQ(test_2_idx_upper_bpt_index->GetInnerNodeSizeUpperThreshold(), 256);
ASSERT_EQ(test_2_idx_lower_bpt_index->GetInnerNodeSizeLowerThreshold(), 4);
ASSERT_EQ(test_2_idx_both_bpt_index->GetInnerNodeSizeUpperThreshold(), 256);
ASSERT_EQ(test_2_idx_both_bpt_index->GetInnerNodeSizeLowerThreshold(), 4);
}
} // namespace noisepage::test
| 43.333333 | 113 | 0.784188 | ScottLiao920 |
cdddfff7fb6d83dd203382be1fa4d2d0c3594fc7 | 3,869 | cpp | C++ | source/Plugins/Dividers/PhongDivider/PhongDivider.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | source/Plugins/Dividers/PhongDivider/PhongDivider.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | source/Plugins/Dividers/PhongDivider/PhongDivider.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | #include "PhongDivider/PhongDivider.hpp"
using namespace castor3d;
namespace Phong
{
namespace
{
castor::Point3f barycenter( float u
, float v
, castor::Point3f const & p1
, castor::Point3f const & p2
, castor::Point3f const & p3 )
{
float w = 1 - u - v;
CU_Ensure( std::abs( u + v + w - 1.0 ) < 0.0001 );
return castor::Point3f{ p1 * u + p2 * v + p3 * w };
}
}
Patch::Patch( Plane const & p1
, Plane const & p2
, Plane const & p3 )
: pi( p1 )
, pj( p2 )
, pk( p3 )
{
}
castor::String const Subdivider::Name = cuT( "Phong Divider" );
castor::String const Subdivider::Type = cuT( "phong" );
Subdivider::Subdivider()
: castor3d::MeshSubdivider()
, m_occurences( 1 )
{
}
Subdivider::~Subdivider()
{
cleanup();
}
MeshSubdividerUPtr Subdivider::create()
{
return std::make_unique< Subdivider >();
}
void Subdivider::cleanup()
{
castor3d::MeshSubdivider::cleanup();
}
void Subdivider::subdivide( SubmeshSPtr submesh
, int occurences
, bool generateBuffers
, bool threaded )
{
m_occurences = occurences;
m_submesh = submesh;
m_generateBuffers = generateBuffers;
m_submesh->computeContainers();
doInitialise();
m_threaded = threaded;
if ( threaded )
{
m_thread = std::make_shared< std::thread >( std::bind( &Subdivider::doSubdivideThreaded, this ) );
}
else
{
doSubdivide();
doAddGeneratedFaces();
doSwapBuffers();
}
}
void Subdivider::doSubdivide()
{
auto facesArray = m_indexMapping->getFaces();
m_indexMapping->clearFaces();
std::map< uint32_t, Plane > posnml;
uint32_t i = 0;
for ( auto const & point : m_submesh->getPoints() )
{
castor::Point3f position = point.pos;
castor::Point3f normal = point.nml;
posnml.emplace( i++, Plane{ castor::PlaneEquation( normal, position ), position } );
}
for ( auto face : facesArray )
{
doComputeFaces( 0.0, 0.0, 1.0, 1.0, m_occurences, Patch( posnml[face[0]], posnml[face[1]], posnml[face[2]] ) );
}
for ( auto & point : m_points )
{
m_submesh->getPoint( point->m_index ).pos = point->m_vertex.pos;
}
facesArray.clear();
}
void Subdivider::doInitialise()
{
for ( uint32_t i = 0; i < m_submesh->getPointsCount(); ++i )
{
m_points.emplace_back( std::make_unique< SubmeshVertex >( SubmeshVertex{ i, m_submesh->getPoint( i ) } ) );
}
castor3d::MeshSubdivider::doInitialise();
m_indexMapping = m_submesh->getComponent< TriFaceMapping >();
}
void Subdivider::doAddGeneratedFaces()
{
for ( auto const & face : m_arrayFaces )
{
m_indexMapping->addFace( face[0], face[1], face[2] );
}
}
void Subdivider::doComputeFaces( float u0
, float v0
, float u2
, float v2
, int occurences
, Patch const & patch )
{
float u1 = ( u0 + u2 ) / 2.0f;
float v1 = ( v0 + v2 ) / 2.0f;
if ( occurences > 1 )
{
doComputeFaces( u0, v0, u1, v1, occurences - 1, patch );
doComputeFaces( u0, v1, u1, v2, occurences - 1, patch );
doComputeFaces( u1, v0, u2, v1, occurences - 1, patch );
doComputeFaces( u1, v1, u0, v0, occurences - 1, patch );
}
else
{
auto & a = doComputePoint( u0, v0, patch );
auto & b = doComputePoint( u2, v0, patch );
auto & c = doComputePoint( u0, v2, patch );
auto & d = doComputePoint( u1, v0, patch );
auto & e = doComputePoint( u1, v1, patch );
auto & f = doComputePoint( u0, v1, patch );
doSetTextCoords( a, b, c, d, e, f );
}
}
castor3d::SubmeshVertex & Subdivider::doComputePoint( float u, float v, Patch const & patch )
{
castor::Point3f b = barycenter( u, v, patch.pi.point, patch.pj.point, patch.pk.point );
castor::Point3f pi = patch.pi.plane.project( b );
castor::Point3f pj = patch.pj.plane.project( b );
castor::Point3f pk = patch.pk.plane.project( b );
castor::Point3f point( barycenter( u, v, pi, pj, pk ) );
return doTryAddPoint( point );
}
}
| 23.591463 | 114 | 0.634014 | Mu-L |
cde33b2e843334d259f12f8a2263cd8d663b6996 | 701 | cpp | C++ | LeetCode/Tree/same-tree.cpp | vasanth9/coding-universe | 69ffcb58af0c163689ab9893e6d1e0581e0247e0 | [
"MIT"
] | null | null | null | LeetCode/Tree/same-tree.cpp | vasanth9/coding-universe | 69ffcb58af0c163689ab9893e6d1e0581e0247e0 | [
"MIT"
] | null | null | null | LeetCode/Tree/same-tree.cpp | vasanth9/coding-universe | 69ffcb58af0c163689ab9893e6d1e0581e0247e0 | [
"MIT"
] | null | null | null | /**
Definition for a binary tree node. */
//https://leetcode.com/problems/same-tree/
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL) return true;
if(p==NULL || q==NULL) return false;
return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
}
}; | 31.863636 | 92 | 0.603424 | vasanth9 |
cde3c6083a27b89f1434e2c6a83cba538f12f2fc | 11,241 | cxx | C++ | Code/Core/Applications/Common/vnsAppExtractChannels.cxx | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 57 | 2020-09-30T08:51:22.000Z | 2021-12-19T20:28:30.000Z | Code/Core/Applications/Common/vnsAppExtractChannels.cxx | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 34 | 2020-09-29T21:27:22.000Z | 2022-02-03T09:56:45.000Z | Code/Core/Applications/Common/vnsAppExtractChannels.cxx | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 14 | 2020-10-11T13:17:59.000Z | 2022-03-09T15:58:19.000Z | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
/************************************************************************************************************
* *
* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *
* o *
* o *
* o *
* o *
* o ooooooo ooooooo o o oo *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o oooo o o o o o o *
* o o o o o o o o o *
* o o o o o o o o o o *
* oo oooooooo o o o oooooo o oooo *
* o *
* o *
* o o *
* o o oooo o o oooo *
* o o o o o o *
* o o ooo o o ooo *
* o o o o o *
* ooooo oooo o ooooo oooo *
* o *
* *
************************************************************************************************************
* *
* Author: CS Systemes d'Information (France) *
* *
************************************************************************************************************
* HISTORIQUE *
* *
* VERSION : 1-0-0 : <TypeFT> : <NumFT> : 15 nov. 2017 : Creation
* *
* FIN-HISTORIQUE *
* *
* $Id$
* *
************************************************************************************************************/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMultiChannelExtractROI.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbWrapperListViewParameter.h"
#include "vnsMacro.h"
#define CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(Tin, Tout, image_base) \
{ \
Tin* img = dynamic_cast<Tin*>(image_base); \
\
if (img) \
{ \
DoExtractVector<Tin, Tout>(img); \
return; \
\
} \
} \
#define CAST_AND_EXTRACT_IMAGE_BASE(Tin, Tout, image_base) \
{ \
Tin* img = dynamic_cast<Tin*>(image_base); \
\
if (img) \
{ \
DoExtract<Tin, Tout>(img); \
return; \
\
} \
} \
namespace vns
{
namespace Wrapper
{
using namespace otb::Wrapper;
class ExtractChannels : public Application
{
public:
/** Standard class typedefs. */
typedef ExtractChannels Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ExtractChannels, otb::Application);
protected:
ExtractChannels()
{
}
private:
void DoInit() override
{
SetName("ExtractChannels");
SetDescription("Extract channels defined by the user.");
// Documentation
SetDocLongDescription(
"This application extracts a list of channels with "
"user parameters. ");
SetDocLimitations("None");
SetDocAuthors("MAJA-OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Manip);
// Set parameter input
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "Image to be processed.");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Region of interest from the input image");
SetParameterOutputImagePixelType("out",ImagePixelType_double);
// Channelist Parameters
AddParameter(ParameterType_ListView, "cl", "Output Image channels");
SetParameterDescription("cl", "Channels to write in the output image.");
AddRAMParameter();
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
if (HasValue("in"))
{
ImageBaseType* inImage = GetParameterImageBase("in",0);
unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
ListViewParameter* clParam = dynamic_cast<ListViewParameter*>(GetParameterByKey("cl"));
// Update the values of the channels to be selected if nbComponents is changed
if (clParam != nullptr && clParam->GetNbChoices() != nbComponents)
{
ClearChoices("cl");
for (unsigned int idx = 0; idx < nbComponents; ++idx)
{
std::ostringstream key, item;
key << "cl.channel" << idx + 1;
item << "Channel" << idx + 1;
AddChoice(key.str(), item.str());
}
}
}
}
template <typename TInputImage, typename TOutputImage>
void DoExtractVector(TInputImage* in)
{
//MultiChannels
typedef otb::MultiChannelExtractROI<typename TInputImage::InternalPixelType, typename TOutputImage::InternalPixelType> ExtractROIFilterType;
typename ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
extractROIFilter->SetInput(in);
for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
{
extractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1);
}
SetParameterOutputImage<TOutputImage>("out", extractROIFilter->GetOutput());
m_ExtractFilter = extractROIFilter;
}
template <typename TInputImage, typename TOutputImage>
void DoExtract(TInputImage* in)
{
//MonoChannel
typedef otb::MultiToMonoChannelExtractROI<typename TInputImage::InternalPixelType, typename TOutputImage::InternalPixelType> MonoChannelExtractROIFilterType;
typename MonoChannelExtractROIFilterType::Pointer extractROIFilter = MonoChannelExtractROIFilterType::New();
extractROIFilter->SetInput(in);
extractROIFilter->SetChannel(GetSelectedItems("cl")[0] + 1);
SetParameterOutputImage<TOutputImage>("out", extractROIFilter->GetOutput());
m_ExtractFilter = extractROIFilter;
}
void DoExecute() override
{
// Get input image pointers
ImageBaseType* l_inPtr = GetParameterImageBase("in",0);
// Guess the image type
std::string className(l_inPtr->GetNameOfClass());
vnsLogDebugMacro("Resampling needed");
if (className == "VectorImage") {
if (GetSelectedItems("cl").size() == 1)
{
vnsLogDebugMacro("SingleImage");
CAST_AND_EXTRACT_IMAGE_BASE(DoubleVectorImageType,DoubleImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_float);
CAST_AND_EXTRACT_IMAGE_BASE(FloatVectorImageType,FloatImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_uint8);
CAST_AND_EXTRACT_IMAGE_BASE(UInt8VectorImageType, UInt8ImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_uint16);
CAST_AND_EXTRACT_IMAGE_BASE(UInt16VectorImageType, UInt16ImageType,l_inPtr);
} else {
vnsLogDebugMacro("VectorImage");
CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(DoubleVectorImageType,DoubleVectorImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_float);
CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(FloatVectorImageType,FloatVectorImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_uint8);
CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(UInt8VectorImageType, UInt8VectorImageType,l_inPtr);
SetParameterOutputImagePixelType("out",ImagePixelType_uint16);
CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(UInt16VectorImageType, UInt16VectorImageType,l_inPtr);
}
} else {
vnsExceptionDataMacro("Unsuported image type : only vector supported");
}
vnsExceptionDataMacro("Unsuported image type");
}
private:
itk::ProcessObject::Pointer m_ExtractFilter;
};
}
}
OTB_APPLICATION_EXPORT(vns::Wrapper::ExtractChannels)
| 44.784861 | 160 | 0.459123 | spacebel |
cde4d0857e55da57e987111dce80ed47d38f7872 | 16,068 | cpp | C++ | dev/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp | santosh90n/lumberyard-1 | 9608bcf905bb60e9f326bd3fe8297381c22d83a6 | [
"AML"
] | null | null | null | dev/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp | santosh90n/lumberyard-1 | 9608bcf905bb60e9f326bd3fe8297381c22d83a6 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// include the required headers
#include "EMotionFXConfig.h"
#include <MCore/Source/Compare.h>
#include <MCore/Source/UnicodeString.h>
#include "AnimGraphStateCondition.h"
#include "AnimGraph.h"
#include "AnimGraphStateMachine.h"
#include "AnimGraphExitNode.h"
#include "AnimGraphInstance.h"
#include "AnimGraphManager.h"
#include <MCore/Source/AttributeSettings.h>
namespace EMotionFX
{
// constructor
AnimGraphStateCondition::AnimGraphStateCondition(AnimGraph* animGraph)
: AnimGraphTransitionCondition(animGraph, TYPE_ID)
{
mState = nullptr;
CreateAttributeValues();
InitInternalAttributesForAllInstances();
}
// destructor
AnimGraphStateCondition::~AnimGraphStateCondition()
{
}
// create
AnimGraphStateCondition* AnimGraphStateCondition::Create(AnimGraph* animGraph)
{
return new AnimGraphStateCondition(animGraph);
}
// create unique data
AnimGraphObjectData* AnimGraphStateCondition::CreateObjectData()
{
return new UniqueData(this, nullptr);
}
// register the attributes
void AnimGraphStateCondition::RegisterAttributes()
{
// register the state name
MCore::AttributeSettings* attributeInfo = RegisterAttribute("State", "stateID", "The state to watch.", ATTRIBUTE_INTERFACETYPE_STATESELECTION);
attributeInfo->SetDefaultValue(MCore::AttributeString::Create());
// create the function combobox
attributeInfo = RegisterAttribute("Test Function", "testFunction", "The type of test function or condition.", MCore::ATTRIBUTE_INTERFACETYPE_COMBOBOX);
attributeInfo->ResizeComboValues(6);
attributeInfo->SetComboValue(FUNCTION_EXITSTATES, "Trigger When Exit State Reached");
attributeInfo->SetComboValue(FUNCTION_ENTERING, "Started Transitioning Into State");
attributeInfo->SetComboValue(FUNCTION_ENTER, "State Fully Blended In");
attributeInfo->SetComboValue(FUNCTION_EXIT, "Leaving State, Transitioning Out");
attributeInfo->SetComboValue(FUNCTION_END, "State Fully Blended Out");
attributeInfo->SetComboValue(FUNCTION_PLAYTIME, "Has Reached Specified Playtime");
attributeInfo->SetDefaultValue(MCore::AttributeFloat::Create(FUNCTION_EXITSTATES));
// create the max playtime attribute
attributeInfo = RegisterAttribute("Play Time", "playtime", "The float value in seconds to test against the current playtime of the state.", MCore::ATTRIBUTE_INTERFACETYPE_FLOATSPINNER);
attributeInfo->SetDefaultValue(MCore::AttributeFloat::Create(0.0f));
attributeInfo->SetMinValue(MCore::AttributeFloat::Create(0.0f));
attributeInfo->SetMaxValue(MCore::AttributeFloat::Create(FLT_MAX));
}
// get the palette name
const char* AnimGraphStateCondition::GetPaletteName() const
{
return "State Condition";
}
// get the type string
const char* AnimGraphStateCondition::GetTypeString() const
{
return "AnimGraphStateCondition";
}
// get the category
AnimGraphObject::ECategory AnimGraphStateCondition::GetPaletteCategory() const
{
return AnimGraphObject::CATEGORY_TRANSITIONCONDITIONS;
}
// test the condition
bool AnimGraphStateCondition::TestCondition(AnimGraphInstance* animGraphInstance) const
{
// add the unique data for the condition to the anim graph
UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
// in case a event got triggered constantly fire true until the condition gets reset
if (uniqueData->mTriggered)
{
return true;
}
// update the unique data
if (uniqueData->mAnimGraphInstance != animGraphInstance ||
uniqueData->mAnimGraphInstance->FindEventHandlerIndex(uniqueData->mEventHandler) == MCORE_INVALIDINDEX32)
{
// create a new event handler for this motion condition and add it to the motion instance
uniqueData->mAnimGraphInstance = animGraphInstance;
uniqueData->mEventHandler = new AnimGraphStateCondition::EventHandler(const_cast<AnimGraphStateCondition*>(this), uniqueData);
uniqueData->mAnimGraphInstance->AddEventHandler(uniqueData->mEventHandler);
}
// get the condition test function type
const int32 functionIndex = GetAttributeFloatAsInt32(ATTRIB_FUNCTION);
// check what we want to do
switch (functionIndex)
{
// reached an exit state
case FUNCTION_EXITSTATES:
{
// check if the state is a valid state machine
if (mState && mState->GetType() == AnimGraphStateMachine::TYPE_ID)
{
// type-cast the state to a state machine
AnimGraphStateMachine* stateMachine = static_cast<AnimGraphStateMachine*>(mState);
// check if we have reached an exit state
if (stateMachine->GetExitStateReached(animGraphInstance))
{
return true;
}
}
break;
}
// reached the specified play time
case FUNCTION_PLAYTIME:
{
// get the play time to check against
// the has reached play time condition is not part of the event handler, so we have to manually handle it here
const float playTime = GetAttributeFloat(ATTRIB_PLAYTIME)->GetValue();
// reached the specified play time
if (mState)
{
const float currentLocalTime = mState->GetCurrentPlayTime(uniqueData->mAnimGraphInstance);
if (currentLocalTime > playTime)
{
return true;
}
}
}
break;
default:
{
// check if any event got triggered since we tested the condition the last time
if (functionIndex == uniqueData->mLastTriggeredType)
{
uniqueData->mLastTriggeredType = FUNCTION_NONE;
uniqueData->mTriggered = true;
return true;
}
}
}
;
// no event got triggered, continue playing the state and don't autostart the transition
return false;
}
// clonse the condition
AnimGraphObject* AnimGraphStateCondition::Clone(AnimGraph* animGraph)
{
// create the clone
AnimGraphStateCondition* clone = new AnimGraphStateCondition(animGraph);
// copy base class settings such as parameter values to the new clone
CopyBaseObjectTo(clone);
// return a pointer to the clone
return clone;
}
// update the data
void AnimGraphStateCondition::OnUpdateAttributes()
{
// get a pointer to the selected motion node
AnimGraphNode* animGraphNode = mAnimGraph->RecursiveFindNode(GetAttributeString(ATTRIB_STATE)->AsChar());
if (animGraphNode && animGraphNode->GetCanActAsState())
{
mState = animGraphNode;
}
else
{
mState = nullptr;
}
// disable GUI items that have no influence
#ifdef EMFX_EMSTUDIOBUILD
// enable all attributes
EnableAllAttributes(true);
// disable the playtime value
const int32 function = GetAttributeFloatAsInt32(ATTRIB_FUNCTION);
if (function != FUNCTION_PLAYTIME)
{
SetAttributeDisabled(ATTRIB_PLAYTIME);
}
#endif
}
// reset the motion condition
void AnimGraphStateCondition::Reset(AnimGraphInstance* animGraphInstance)
{
// find the unique data and reset it
UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
uniqueData->mTriggered = false;
uniqueData->mLastTriggeredType = FUNCTION_NONE;
}
// when attribute values change
void AnimGraphStateCondition::OnUpdateUniqueData(AnimGraphInstance* animGraphInstance)
{
// add the unique data for the condition to the anim graph
UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
if (uniqueData == nullptr)
{
uniqueData = (UniqueData*)GetEMotionFX().GetAnimGraphManager()->GetObjectDataPool().RequestNew(TYPE_ID, this, animGraphInstance);
//uniqueData = new UniqueData(this, nullptr);
animGraphInstance->RegisterUniqueObjectData(uniqueData);
}
}
// get the name of the currently used test function
const char* AnimGraphStateCondition::GetTestFunctionString() const
{
// get access to the combo values and the currently selected function
MCore::AttributeSettings* comboAttributeInfo = GetAnimGraphManager().GetAttributeInfo(this, ATTRIB_FUNCTION);
const uint32 functionIndex = GetAttributeFloatAsUint32(ATTRIB_FUNCTION);
return comboAttributeInfo->GetComboValue(functionIndex);
}
// construct and output the information summary string for this object
void AnimGraphStateCondition::GetSummary(MCore::String* outResult) const
{
outResult->Format("%s: State='%s', Test Function='%s'", GetTypeString(), GetAttributeString(ATTRIB_STATE)->AsChar(), GetTestFunctionString());
}
// construct and output the tooltip for this object
void AnimGraphStateCondition::GetTooltip(MCore::String* outResult) const
{
MCore::String columnName, columnValue;
// add the condition type
columnName = "Condition Type: ";
columnValue = GetTypeString();
outResult->Format("<table border=\"0\"><tr><td width=\"100\"><b>%s</b></td><td>%s</td>", columnName.AsChar(), columnValue.AsChar());
// add the state name
columnName = "State Name: ";
columnValue = GetAttributeString(ATTRIB_STATE)->AsChar();
outResult->FormatAdd("</tr><tr><td><b>%s</b></td><td>%s</td>", columnName.AsChar(), columnValue.AsChar());
// add the test function
columnName = "Test Function: ";
columnValue = GetTestFunctionString();
outResult->FormatAdd("</tr><tr><td><b>%s</b></td><td width=\"180\">%s</td></tr></table>", columnName.AsChar(), columnValue.AsChar());
}
//--------------------------------------------------------------------------------
// class AnimGraphStateCondition::UniqueData
//--------------------------------------------------------------------------------
// constructor
AnimGraphStateCondition::UniqueData::UniqueData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance)
: AnimGraphObjectData(object, animGraphInstance)
{
mLastTriggeredType = FUNCTION_NONE;
mAnimGraphInstance = animGraphInstance;
mEventHandler = nullptr;
mTriggered = false;
}
// destructor
AnimGraphStateCondition::UniqueData::~UniqueData()
{
// get rid of the event handler
if (mEventHandler)
{
if (mAnimGraphInstance)
{
mAnimGraphInstance->RemoveEventHandler(mEventHandler, false);
}
mEventHandler->Destroy();
mAnimGraphInstance = nullptr;
}
}
// callback for when we renamed a node
void AnimGraphStateCondition::OnRenamedNode(AnimGraph* animGraph, AnimGraphNode* node, const MCore::String& oldName)
{
MCORE_UNUSED(animGraph);
if (GetAttributeString(ATTRIB_STATE)->GetValue().CheckIfIsEqual(oldName))
{
GetAttributeString(ATTRIB_STATE)->SetValue(node->GetName());
}
}
// callback that gets called before a node gets removed
void AnimGraphStateCondition::OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove)
{
MCORE_UNUSED(animGraph);
if (GetAttributeString(ATTRIB_STATE)->GetValue().CheckIfIsEqual(nodeToRemove->GetName()))
{
GetAttributeString(ATTRIB_STATE)->SetValue("");
}
}
//--------------------------------------------------------------------------------
// class AnimGraphStateCondition::EventHandler
//--------------------------------------------------------------------------------
// constructor
AnimGraphStateCondition::EventHandler::EventHandler(AnimGraphStateCondition* condition, UniqueData* uniqueData)
: EMotionFX::AnimGraphInstanceEventHandler()
{
mCondition = condition;
mUniqueData = uniqueData;
}
// destructor
AnimGraphStateCondition::EventHandler::~EventHandler()
{
}
void AnimGraphStateCondition::EventHandler::OnStateEnter(AnimGraphInstance* animGraphInstance, AnimGraphNode* state)
{
// check if the state and the anim graph instance are valid and return directly in case one of them is not
if (state == nullptr || animGraphInstance == nullptr)
{
return;
}
const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue();
if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName()))
{
mUniqueData->mLastTriggeredType = FUNCTION_ENTER;
}
}
void AnimGraphStateCondition::EventHandler::OnStateEntering(AnimGraphInstance* animGraphInstance, AnimGraphNode* state)
{
// check if the state and the anim graph instance are valid and return directly in case one of them is not
if (state == nullptr || animGraphInstance == nullptr)
{
return;
}
// get the condition test function type
const int32 functionIndex = mCondition->GetAttributeFloatAsInt32(ATTRIB_FUNCTION);
if (functionIndex == FUNCTION_ENTERING)
{
const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue();
if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName()))
{
mUniqueData->mLastTriggeredType = FUNCTION_ENTERING;
}
}
}
void AnimGraphStateCondition::EventHandler::OnStateExit(AnimGraphInstance* animGraphInstance, AnimGraphNode* state)
{
// check if the state and the anim graph instance are valid and return directly in case one of them is not
if (state == nullptr || animGraphInstance == nullptr)
{
return;
}
const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue();
if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName()))
{
mUniqueData->mLastTriggeredType = FUNCTION_EXIT;
}
}
void AnimGraphStateCondition::EventHandler::OnStateEnd(AnimGraphInstance* animGraphInstance, AnimGraphNode* state)
{
// check if the state and the anim graph instance are valid and return directly in case one of them is not
if (state == nullptr || animGraphInstance == nullptr)
{
return;
}
const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue();
if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName()))
{
mUniqueData->mLastTriggeredType = FUNCTION_END;
}
}
} // namespace EMotionFX
| 36.768879 | 193 | 0.642457 | crazyskateface |
cde815305470ccc734b19a7718cdd93b74788053 | 607 | cpp | C++ | src/main.cpp | danbz/signsSlippyMap | 7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c | [
"MIT"
] | null | null | null | src/main.cpp | danbz/signsSlippyMap | 7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c | [
"MIT"
] | null | null | null | src/main.cpp | danbz/signsSlippyMap | 7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c | [
"MIT"
] | null | null | null | //
// slippy map elements based on example code Copyright (c) 2014 Christopher Baker <https://christopherbaker.net>
// SPDX-License-Identifier: MIT
//
/*
Project Title: Signs of Surveillance
Description:
©Daniel Buzzo 2019
dan@buzzo.com
http://buzzo.com
https://github.com/danbz
*/
#include "ofAppRunner.h"
#include "ofApp.h"
int main()
{
ofGLWindowSettings settings;
settings.setSize(1280, 768);
settings.setGLVersion(3, 2);
settings.windowMode = OF_FULLSCREEN;
auto window = ofCreateWindow(settings);
auto app = std::make_shared<ofApp>();
return ofRunApp(app);
}
| 20.931034 | 112 | 0.70346 | danbz |
cdebb80f0ab70fcd88c13f4c41657343898bfbc6 | 5,744 | cpp | C++ | src/optimizer/rule/PushFilterDownGetNbrsRule.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | 1 | 2021-08-23T05:55:55.000Z | 2021-08-23T05:55:55.000Z | src/optimizer/rule/PushFilterDownGetNbrsRule.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | null | null | null | src/optimizer/rule/PushFilterDownGetNbrsRule.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "optimizer/rule/PushFilterDownGetNbrsRule.h"
#include "common/expression/BinaryExpression.h"
#include "common/expression/ConstantExpression.h"
#include "common/expression/Expression.h"
#include "common/expression/FunctionCallExpression.h"
#include "common/expression/LogicalExpression.h"
#include "common/expression/UnaryExpression.h"
#include "optimizer/OptGroup.h"
#include "planner/PlanNode.h"
#include "planner/Query.h"
#include "visitor/ExtractFilterExprVisitor.h"
using nebula::graph::Filter;
using nebula::graph::GetNeighbors;
using nebula::graph::PlanNode;
using nebula::graph::QueryContext;
namespace nebula {
namespace opt {
std::unique_ptr<OptRule> PushFilterDownGetNbrsRule::kInstance =
std::unique_ptr<PushFilterDownGetNbrsRule>(new PushFilterDownGetNbrsRule());
PushFilterDownGetNbrsRule::PushFilterDownGetNbrsRule() {
RuleSet::queryRules().addRule(this);
}
bool PushFilterDownGetNbrsRule::match(const OptGroupExpr *groupExpr) const {
auto pair = findMatchedGroupExpr(groupExpr);
if (!pair.first) {
return false;
}
return true;
}
Status PushFilterDownGetNbrsRule::transform(QueryContext *qctx,
const OptGroupExpr *groupExpr,
TransformResult *result) const {
auto pair = findMatchedGroupExpr(groupExpr);
auto filter = static_cast<const Filter *>(groupExpr->node());
auto gn = static_cast<const GetNeighbors *>(pair.second->node());
auto condition = filter->condition()->clone();
graph::ExtractFilterExprVisitor visitor;
condition->accept(&visitor);
if (!visitor.ok()) {
result->eraseCurr = false;
result->eraseAll = false;
return Status::OK();
}
auto pool = qctx->objPool();
auto remainedExpr = std::move(visitor).remainedExpr();
OptGroupExpr *newFilterGroupExpr = nullptr;
if (remainedExpr != nullptr) {
auto newFilter = Filter::make(qctx, nullptr, pool->add(remainedExpr.release()));
newFilter->setOutputVar(filter->outputVar());
newFilter->setInputVar(filter->inputVar());
newFilterGroupExpr = OptGroupExpr::create(qctx, newFilter, groupExpr->group());
}
auto newGNFilter = condition->encode();
if (!gn->filter().empty()) {
auto filterExpr = Expression::decode(gn->filter());
LogicalExpression logicExpr(
Expression::Kind::kLogicalAnd, condition.release(), filterExpr.release());
newGNFilter = logicExpr.encode();
}
auto newGN = cloneGetNbrs(qctx, gn);
newGN->setFilter(newGNFilter);
OptGroupExpr *newGroupExpr = nullptr;
if (newFilterGroupExpr != nullptr) {
// Filter(A&&B)->GetNeighbors(C) => Filter(A)->GetNeighbors(B&&C)
auto newGroup = OptGroup::create(qctx);
newGroupExpr = OptGroupExpr::create(qctx, newGN, newGroup);
newFilterGroupExpr->dependsOn(newGroup);
} else {
// Filter(A)->GetNeighbors(C) => GetNeighbors(A&&C)
newGroupExpr = OptGroupExpr::create(qctx, newGN, groupExpr->group());
newGN->setOutputVar(filter->outputVar());
}
for (auto dep : pair.second->dependencies()) {
newGroupExpr->dependsOn(dep);
}
result->newGroupExprs.emplace_back(newFilterGroupExpr ? newFilterGroupExpr : newGroupExpr);
result->eraseAll = true;
result->eraseCurr = true;
return Status::OK();
}
std::string PushFilterDownGetNbrsRule::toString() const {
return "PushFilterDownGetNbrsRule";
}
std::pair<bool, const OptGroupExpr *> PushFilterDownGetNbrsRule::findMatchedGroupExpr(
const OptGroupExpr *groupExpr) const {
auto node = groupExpr->node();
if (node->kind() != PlanNode::Kind::kFilter) {
return std::make_pair(false, nullptr);
}
for (auto dep : groupExpr->dependencies()) {
for (auto expr : dep->groupExprs()) {
if (expr->node()->kind() == PlanNode::Kind::kGetNeighbors) {
return std::make_pair(true, expr);
}
}
}
return std::make_pair(false, nullptr);
}
GetNeighbors *PushFilterDownGetNbrsRule::cloneGetNbrs(QueryContext *qctx,
const GetNeighbors *gn) const {
auto newGN = GetNeighbors::make(qctx, nullptr, gn->space());
newGN->setSrc(gn->src());
newGN->setEdgeTypes(gn->edgeTypes());
newGN->setEdgeDirection(gn->edgeDirection());
newGN->setDedup(gn->dedup());
newGN->setRandom(gn->random());
newGN->setLimit(gn->limit());
newGN->setInputVar(gn->inputVar());
newGN->setOutputVar(gn->outputVar());
if (gn->vertexProps()) {
auto vertexProps = *gn->vertexProps();
auto vertexPropsPtr = std::make_unique<decltype(vertexProps)>(std::move(vertexProps));
newGN->setVertexProps(std::move(vertexPropsPtr));
}
if (gn->edgeProps()) {
auto edgeProps = *gn->edgeProps();
auto edgePropsPtr = std::make_unique<decltype(edgeProps)>(std::move(edgeProps));
newGN->setEdgeProps(std::move(edgePropsPtr));
}
if (gn->statProps()) {
auto statProps = *gn->statProps();
auto statPropsPtr = std::make_unique<decltype(statProps)>(std::move(statProps));
newGN->setStatProps(std::move(statPropsPtr));
}
if (gn->exprs()) {
auto exprs = *gn->exprs();
auto exprsPtr = std::make_unique<decltype(exprs)>(std::move(exprs));
newGN->setExprs(std::move(exprsPtr));
}
return newGN;
}
} // namespace opt
} // namespace nebula
| 35.02439 | 95 | 0.657904 | yixinglu |
cdec69a15f3729bf283bd45a363b4fe8f6ca7a5b | 2,007 | cc | C++ | examples/inference/cpp/bert_example.cc | onlyrico/lightseq | 2e1cf1aa184a011cb71c17acbd4139144188ce7d | [
"Apache-2.0"
] | 1 | 2022-03-27T17:16:16.000Z | 2022-03-27T17:16:16.000Z | examples/inference/cpp/bert_example.cc | onlyrico/lightseq | 2e1cf1aa184a011cb71c17acbd4139144188ce7d | [
"Apache-2.0"
] | null | null | null | examples/inference/cpp/bert_example.cc | onlyrico/lightseq | 2e1cf1aa184a011cb71c17acbd4139144188ce7d | [
"Apache-2.0"
] | null | null | null | #include "model_base.h"
#include "util.h"
/**
@file
Example of how to run Bert inference using our implementation.
*/
int main(int argc, char* argv[]) {
std::string model_weights_path = argv[1];
int max_batch_size = 128;
auto model = lightseq::cuda::LSModelFactory::GetInstance().CreateModel(
"Bert", model_weights_path, max_batch_size);
int batch_size = 1;
int batch_seq_len = 8;
std::vector<int> host_input = {101, 4931, 1010, 2129, 2024, 2017, 102, 0};
void* d_input;
lightseq::cuda::CHECK_GPU_ERROR(
cudaMalloc(&d_input, sizeof(int) * batch_size * batch_seq_len));
lightseq::cuda::CHECK_GPU_ERROR(cudaMemcpy(
d_input, host_input.data(), sizeof(int) * batch_size * batch_seq_len,
cudaMemcpyHostToDevice));
model->set_input_ptr(0, d_input);
model->set_input_shape(0, {batch_size, batch_seq_len});
for (int i = 0; i < model->get_output_size(); i++) {
void* d_output;
std::vector<int> shape = model->get_output_max_shape(i);
int total_size = 1;
for (int j = 0; j < shape.size(); j++) {
total_size *= shape[j];
}
lightseq::cuda::CHECK_GPU_ERROR(
cudaMalloc(&d_output, total_size * sizeof(int)));
model->set_output_ptr(i, d_output);
}
lightseq::cuda::CHECK_GPU_ERROR(cudaStreamSynchronize(0));
std::cout << "infer preprocessing finished" << std::endl;
/* ---step5. infer and log--- */
for (int i = 0; i < 10; i++) {
auto start = std::chrono::high_resolution_clock::now();
model->Infer();
lightseq::cuda::print_time_duration(start, "one infer time", 0);
}
for (int i = 0; i < model->get_output_size(); i++) {
const float* d_output;
d_output = static_cast<const float*>(model->get_output_ptr(i));
std::vector<int> shape = model->get_output_shape(i);
std::cout << "output shape: ";
for (int j = 0; j < shape.size(); j++) {
std::cout << shape[j] << " ";
}
std::cout << std::endl;
lightseq::cuda::print_vec(d_output, "output", 5);
}
return 0;
}
| 30.409091 | 76 | 0.642252 | onlyrico |
cdf05999595b8296f34e1e2e39939a2ca3dbb56e | 3,733 | cc | C++ | tensorflow/core/kernels/matrix_inverse_op.cc | sylviawhoa/tensorflow | 30f3cdfc420d831e2591cce62fa51164cf8a700a | [
"Apache-2.0"
] | 21 | 2016-03-10T11:55:45.000Z | 2021-02-03T02:49:11.000Z | tensorflow/core/kernels/matrix_inverse_op.cc | sylviawhoa/tensorflow | 30f3cdfc420d831e2591cce62fa51164cf8a700a | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/matrix_inverse_op.cc | sylviawhoa/tensorflow | 30f3cdfc420d831e2591cce62fa51164cf8a700a | [
"Apache-2.0"
] | 39 | 2016-03-25T05:13:09.000Z | 2020-06-16T01:30:53.000Z | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include <cmath>
#include "third_party/eigen3/Eigen/Cholesky"
#include "third_party/eigen3/Eigen/LU"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
template <class Scalar, bool SupportsBatchOperationT>
class MatrixInverseOp
: public UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> {
public:
explicit MatrixInverseOp(OpKernelConstruction* context)
: UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT>(context) {}
~MatrixInverseOp() override {}
TensorShape GetOutputMatrixShape(
const TensorShape& input_matrix_shape) override {
return input_matrix_shape;
}
int64 GetCostPerUnit(const TensorShape& input_matrix_shape) override {
const int64 rows = input_matrix_shape.dim_size(0);
if (rows > (1LL << 20)) {
// A big number to cap the cost in case overflow.
return kint64max;
} else {
return rows * rows * rows;
}
}
typedef UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> Base;
using Matrix = typename Base::Matrix;
using MatrixMap = typename Base::MatrixMap;
using ConstMatrixMap = typename Base::ConstMatrixMap;
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMap& input,
MatrixMap* output) override {
OP_REQUIRES(context, input.rows() == input.cols(),
errors::InvalidArgument("Input matrix must be square."));
if (input.rows() == 0) {
// By definition, an empty matrix's inverse is an empty matrix.
return;
}
Eigen::PartialPivLU<Matrix> lu_decomposition(input);
// TODO(rmlarsen): Add check based on condition number estimation.
// PartialPivLU cannot give strong guarantees on invertibility, but
// we can at least guard against exact zero pivots. This can occur as
// a result of basic user mistakes, such as providing integer valued
// matrices that are exactly singular, or due to underflow if this
// code is run with denormals being flushed to zero.
const Scalar min_abs_pivot =
lu_decomposition.matrixLU().diagonal().cwiseAbs().minCoeff();
OP_REQUIRES(context, min_abs_pivot > Scalar(0),
errors::InvalidArgument("Input is not invertible."));
output->noalias() = lu_decomposition.inverse();
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(MatrixInverseOp);
};
REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<float, false>), float);
REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<double, false>), double);
REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<float, true>), float);
REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<double, true>),
double);
} // namespace tensorflow
| 40.139785 | 80 | 0.723547 | sylviawhoa |