hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8df0831afadec311be21dc624b9be9b157ce96b1 | 1,551 | cpp | C++ | Robot2/Window.cpp | szedenik-adam/Robot2 | 2d4438e55fa5300f57c19e49a8b0dd8986cd05e3 | [
"MIT"
] | 1 | 2022-01-30T14:49:42.000Z | 2022-01-30T14:49:42.000Z | Robot2/Window.cpp | szedenik-adam/Robot2 | 2d4438e55fa5300f57c19e49a8b0dd8986cd05e3 | [
"MIT"
] | null | null | null | Robot2/Window.cpp | szedenik-adam/Robot2 | 2d4438e55fa5300f57c19e49a8b0dd8986cd05e3 | [
"MIT"
] | null | null | null | #include "Window.h"
#include "scrcpy/scrcpy.h"
Window::Window() :
window(Window::_CreateWindow()),
console(*window)
{
console.Init();
}
Window::~Window()
{
}
bool Window::ManageConsoleKey(SDL_Keycode keycode, SDL_Scancode scancode, uint16_t mod, bool isDown)
{
if (isDown) {
if (keycode == SDLK_TAB) {
this->console.ToggleConsole();
//printf("Console is "); printf(this->screen->console->IsOpen() ? "opened.\n" : "closed.\n");
return true;
}
else if (this->console.IsOpen())
{
if (keycode < 256) {
this->console.KeyboardFunc(keycode, mod);
}
else {
this->console.SpecialFunc(scancode, mod);
}
return true;
}
}
return false; // Keyboard event is not for the console.
}
//#include <Windows.h>
//#include <GL/glew.h>
//#include <GL/GL.h>
void Window::Render()
{
glDisable(GL_TEXTURE_2D);
this->console.RenderConsole();
}
void Window::GetClientSize(int* w, int* h)
{
SDL_GL_GetDrawableSize(this->window, w, h);
}
SDL_Window* Window::_CreateWindow()
{
Window::InitSDL();
int x = SDL_WINDOWPOS_UNDEFINED;
int y = SDL_WINDOWPOS_UNDEFINED;
SDL_Window* w = SDL_CreateWindow("Main window", x, y, 600, 800, SDL_WINDOW_OPENGL);
return w;
}
void Window::InitSDL()
{
if (Window::sdl_initialized) return;
SDL_SetMainReady();
scrcpyOptions::sdl_init_and_configure(true, nullptr, false);
Window::sdl_initialized = true;
}
| 23.5 | 105 | 0.604126 | [
"render"
] |
8df8ef344a7b741aec1d6f6f9233b4b80e41ac72 | 5,123 | hpp | C++ | libs/core/render/include/bksge/core/render/d3d11/detail/hlsl_shader.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/include/bksge/core/render/d3d11/detail/hlsl_shader.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/include/bksge/core/render/d3d11/detail/hlsl_shader.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file hlsl_shader.hpp
*
* @brief HlslShader クラスの定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_D3D11_DETAIL_HLSL_SHADER_HPP
#define BKSGE_CORE_RENDER_D3D11_DETAIL_HLSL_SHADER_HPP
#include <bksge/core/render/d3d11/detail/fwd/hlsl_shader_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/constant_buffer_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/hlsl_sampler_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/hlsl_texture_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/device_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/device_context_fwd.hpp>
#include <bksge/core/render/d3d11/detail/fwd/resource_pool_fwd.hpp>
#include <bksge/core/render/d3d_common/d3d11.hpp>
#include <bksge/core/render/d3d_common/d3dcommon.hpp>
#include <bksge/core/render/d3d_common/d3d11shader.hpp>
#include <bksge/core/render/d3d_common/com_ptr.hpp>
#include <bksge/core/render/fwd/shader_parameter_map_fwd.hpp>
#include <bksge/fnd/memory/unique_ptr.hpp>
#include <bksge/fnd/string/string.hpp>
#include <vector>
namespace bksge
{
namespace render
{
namespace d3d11
{
/**
* @brief
*/
class HlslShaderBase
{
public:
HlslShaderBase();
virtual ~HlslShaderBase() = 0;
bool Compile(Device* device, bksge::string const& source);
ComPtr<::ID3D11InputLayout> CreateInputLayout(Device* device);
void SetEnable(DeviceContext* device_context);
void LoadParameters(
ResourcePool* resource_pool,
Device* device,
DeviceContext* device_context,
bksge::ShaderParameterMap const& shader_parameter_map);
private:
void CreateConstantBuffer(Device* device);
void CreateShaderResources(Device* device);
virtual const char* VGetTargetString() = 0;
virtual void VCreateShader(Device* device, ::ID3DBlob* micro_code) = 0;
virtual void VSetEnable(DeviceContext* device_context) = 0;
virtual void VSetConstantBuffers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_buffers,
::ID3D11Buffer* const* constant_buffers) = 0;
public:
virtual void VSetSamplers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_samplers,
::ID3D11SamplerState* const* samplers) = 0;
virtual void VSetShaderResources(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_views,
::ID3D11ShaderResourceView* const* shader_resource_views) = 0;
private:
// noncopyable
HlslShaderBase(HlslShaderBase const&) = delete;
HlslShaderBase& operator=(HlslShaderBase const&) = delete;
private:
using ConstantBuffers = std::vector<bksge::unique_ptr<ConstantBuffer>>;
using HlslSamplers = std::vector<bksge::unique_ptr<HlslSampler>>;
using HlslTextures = std::vector<bksge::unique_ptr<HlslTexture>>;
ComPtr<::ID3DBlob> m_micro_code;
ComPtr<::ID3D11ShaderReflection> m_reflection;
ConstantBuffers m_constant_buffers;
HlslSamplers m_hlsl_samplers;
HlslTextures m_hlsl_textures;
};
/**
* @brief
*/
class HlslVertexShader : public HlslShaderBase
{
public:
HlslVertexShader();
virtual ~HlslVertexShader();
private:
const char* VGetTargetString() override;
void VCreateShader(Device* device, ::ID3DBlob* micro_code) override;
void VSetEnable(DeviceContext* device_context) override;
void VSetConstantBuffers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_buffers,
::ID3D11Buffer* const* constant_buffers) override;
void VSetSamplers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_samplers,
::ID3D11SamplerState* const* samplers) override;
void VSetShaderResources(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_views,
::ID3D11ShaderResourceView* const* shader_resource_views) override;
private:
ComPtr<::ID3D11VertexShader> m_shader;
};
/**
* @brief
*/
class HlslPixelShader : public HlslShaderBase
{
public:
HlslPixelShader();
virtual ~HlslPixelShader();
private:
const char* VGetTargetString() override;
void VCreateShader(Device* device, ::ID3DBlob* micro_code) override;
void VSetEnable(DeviceContext* device_context) override;
void VSetConstantBuffers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_buffers,
::ID3D11Buffer* const* constant_buffers) override;
void VSetSamplers(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_samplers,
::ID3D11SamplerState* const* samplers) override;
void VSetShaderResources(
DeviceContext* device_context,
::UINT start_slot,
::UINT num_views,
::ID3D11ShaderResourceView* const* shader_resource_views) override;
private:
ComPtr<::ID3D11PixelShader> m_shader;
};
} // namespace d3d11
} // namespace render
} // namespace bksge
#include <bksge/fnd/config.hpp>
#if defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/d3d11/detail/inl/hlsl_shader_inl.hpp>
#endif
#endif // BKSGE_CORE_RENDER_D3D11_DETAIL_HLSL_SHADER_HPP
| 28.303867 | 73 | 0.725161 | [
"render",
"vector"
] |
8dfff2f3968848fc585d31e13cd832f3f13176ba | 4,278 | cpp | C++ | nntrainer/tensor/optimized_v1_planner.cpp | SIJUN0725/nntrainer | d22eeaa6591bedeff2480fc7853ebca60ebaa80c | [
"Apache-2.0"
] | 91 | 2020-03-24T06:52:34.000Z | 2022-03-27T18:56:32.000Z | nntrainer/tensor/optimized_v1_planner.cpp | SIJUN0725/nntrainer | d22eeaa6591bedeff2480fc7853ebca60ebaa80c | [
"Apache-2.0"
] | 1,815 | 2020-03-24T08:15:43.000Z | 2022-03-31T09:14:47.000Z | nntrainer/tensor/optimized_v1_planner.cpp | SIJUN0725/nntrainer | d22eeaa6591bedeff2480fc7853ebca60ebaa80c | [
"Apache-2.0"
] | 45 | 2020-03-24T06:17:05.000Z | 2022-03-28T23:47:12.000Z | // SPDX-License-Identifier: Apache-2.0
/**
* Copyright (C) 2021 Parichay Kapoor <pk.kapoor@samsung.com>
*
* @file optimized_v1_planner.cpp
* @date 3 September 2021
* @see https://github.com/nnstreamer/nntrainer
* @author Parichay Kapoor <pk.kapoor@samsung.com>
* @bug No known bugs except for NYI items
* @brief This is Optimized V1 Memory Planner
*
*/
#include <algorithm>
#include <vector>
#include <optimized_v1_planner.h>
namespace nntrainer {
/**
* @brief Memory Request data structure clubbing all the requests
*
*/
struct MemoryRequest {
unsigned int start; /**< start of the validity (inclusive) */
unsigned int end; /**< end of the validity (exclusive) */
unsigned int loc; /**< index/location of the this request */
size_t size; /**< size of the request */
size_t offset; /**< offset for this request */
/**
* @brief Constructor for the Memory Request
*
*/
MemoryRequest(size_t s, const std::pair<unsigned int, unsigned int> &valid,
unsigned int idx) :
start(valid.first),
end(valid.second),
loc(idx),
size(s),
offset(0) {}
};
/**
* @copydoc MemoryPlanner::planLayout(
* const std::vector<size_t> &memory_size,
* const std::vector<std::pair<unsigned int, unsigned int>> &memory_validity,
* std::vector<size_t> &memory_offset);
*
* @details The optimized v1 memory planner assigns memory to the requests whose
* validity starts first.
* The requested memories are sorted based on the ascending order of the start
* timestamps, and descending order using the end timestamps. The
* sorted memories are given increasing offset based on the memory size.
* At the end of each timestamp, invalid memories are freed, and offset updated
* for reuse. This planner allocates overlapping memory for all the required
* memories.
*
*/
size_t OptimizedV1Planner::planLayout(
const std::vector<size_t> &memory_size,
const std::vector<std::pair<unsigned int, unsigned int>> &memory_validity,
std::vector<size_t> &memory_offset) const {
/** create memory requests structure array for easier management */
std::vector<MemoryRequest> requests;
requests.reserve(memory_size.size());
for (unsigned int idx = 0; idx < memory_size.size(); idx++) {
requests.emplace_back(memory_size[idx], memory_validity[idx], idx);
}
/**
* sort the memory requests with ascending order of start time first, and
* then end time
*/
std::sort(requests.begin(), requests.end(),
[](auto const &v1, auto const &v2) -> int {
if (v1.start == v2.start)
return v1.end < v2.end;
return v1.start < v2.start;
/** TODO: try this */
// if (v1.end == v2.end)
// return v1.start < v2.start;
// return v1.end > v2.end;
});
/** all the memories in use sorted by their assigned offset and size */
std::vector<MemoryRequest *> sorted_req;
/** iterate over the sorted requests and start allocation of the requests */
memory_offset.resize(memory_size.size());
size_t memory_req = 0;
for (auto &req : requests) {
/** remove expired memories and update offset */
while (!sorted_req.empty() && sorted_req.back()->end <= req.start)
sorted_req.pop_back();
/** if there exists an expired memory with same size (not at the edge),
* reuse it */
bool replace_and_fill = false;
for (int idx = sorted_req.size() - 1; idx >= 0; idx--) {
auto const &sr = sorted_req[idx];
/** TODO: reuse if memory size not exactly match */
if (sr->end <= req.start && sr->size == req.size) {
req.offset = sr->offset;
memory_offset[req.loc] = req.offset;
sorted_req[idx] = &req;
replace_and_fill = true;
break;
}
}
if (replace_and_fill) {
continue;
}
size_t offset = 0;
if (!sorted_req.empty())
offset = sorted_req.back()->offset + sorted_req.back()->size;
/** assign offset to the new request and push to queue */
req.offset = offset;
memory_offset[req.loc] = offset;
memory_req = std::max(memory_req, req.offset + req.size);
sorted_req.push_back(&req);
}
return memory_req;
}
} // namespace nntrainer
| 32.165414 | 80 | 0.645161 | [
"vector"
] |
5c00682df809a5bcc525752aedfbb2491356bdda | 7,999 | cpp | C++ | src/runtime/json/jsonml_array.cpp | jsoniq/jsoniq | f7af29417f809d64d1f0b2622d880bc4d87f2e42 | [
"Apache-2.0"
] | 94 | 2015-01-18T09:40:36.000Z | 2022-03-02T21:14:55.000Z | src/runtime/json/jsonml_array.cpp | jsoniq/jsoniq | f7af29417f809d64d1f0b2622d880bc4d87f2e42 | [
"Apache-2.0"
] | 72 | 2015-01-05T22:00:31.000Z | 2021-07-17T11:35:03.000Z | src/runtime/json/jsonml_array.cpp | jsoniq/jsoniq | f7af29417f809d64d1f0b2622d880bc4d87f2e42 | [
"Apache-2.0"
] | 27 | 2015-01-18T20:20:54.000Z | 2020-11-01T18:01:07.000Z | /*
* Copyright 2006-2011 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include <sstream>
#include <zorba/diagnostic_list.h>
#include <zorba/internal/cxx_util.h>
#include <zorba/store_consts.h>
#include "runtime/json/json.h"
#include "store/api/item_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/typeops.h"
#include "util/stl_util.h"
#include "zorbautils/store_util.h"
#include "common.h"
#include "jsonml_array.h"
#include "jsonml_common.h"
// JsonML ("array form") grammar.
// Source: http://www.jsonml.org/syntax/
//
// element
// = '[' tag-name ',' attributes ',' element-list ']'
// | '[' tag-name ',' attributes ']'
// | '[' tag-name ',' element-list ']'
// | '[' tag-name ']'
// | string
// ;
// tag-name
// = string
// ;
// attributes
// = '{' attribute-list '}'
// | '{' '}'
// ;
// attribute-list
// = attribute ',' attribute-list
// | attribute
// ;
// attribute
// = attribute-name ':' attribute-value
// ;
// attribute-name
// = string
// ;
// attribute-value
// = string
// | number
// | 'true'
// | 'false'
// | 'null'
// ;
// element-list
// = element ',' element-list
// | element
// ;
using namespace std;
namespace zorba {
namespace jsonml_array {
///////////////////////////////////////////////////////////////////////////////
static void j2x_object( store::Item_t const &object_item,
store::Item_t *parent_xml_item ) {
ZORBA_ASSERT( parent_xml_item );
store::Item_t junk_item, key_item, type_name;
store::Iterator_t k( object_item->getObjectKeys() );
k->open();
while ( k->next( key_item ) ) {
store::Item_t att_name;
GENV_ITEMFACTORY->createQName(
att_name, "", "", key_item->getStringValue()
);
store::Item_t value_item( object_item->getObjectValue( key_item ) );
zstring value_str( value_item->getStringValue() );
GENV_ITEMFACTORY->createString( value_item, value_str );
type_name = GENV_TYPESYSTEM.XS_UNTYPED_QNAME;
GENV_ITEMFACTORY->createAttributeNode(
junk_item, *parent_xml_item, att_name, type_name, value_item
);
}
k->close();
}
static store::Item_t j2x_array( store::Item_t const &array_item,
store::Item *parent_xml_item ) {
zstring base_uri;
store::NsBindings ns_bindings;
store::Item_t array_elt_item, element_name, junk_item, type_name, xml_item;
store::Iterator_t i( array_item->getArrayValues() );
i->open();
if ( !i->next( array_elt_item ) )
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_EmptyArray ) )
);
if ( !array_elt_item->isAtomic() ||
!TypeOps::is_subtype( array_elt_item->getTypeCode(), store::XS_STRING ) )
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_Bad1stElement ) )
);
GENV_ITEMFACTORY->createQName(
element_name, "", "", array_elt_item->getStringValue()
);
type_name = GENV_TYPESYSTEM.XS_UNTYPED_QNAME;
GENV_ITEMFACTORY->createElementNode(
xml_item, parent_xml_item,
element_name, type_name, false, false, ns_bindings, base_uri
);
bool did_attributes = false;
while ( i->next( array_elt_item ) ) {
switch ( array_elt_item->getKind() ) {
case store::Item::ARRAY:
j2x_array( array_elt_item, xml_item.getp() );
break;
case store::Item::ATOMIC: {
zstring value_str( array_elt_item->getStringValue() );
GENV_ITEMFACTORY->createTextNode( junk_item, xml_item, value_str );
break;
}
case store::Item::OBJECT:
if ( did_attributes )
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_UnexpectedObject ) )
);
j2x_object( array_elt_item, &xml_item );
did_attributes = true;
break;
default:
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_BadElement ), array_elt_item->getKind() )
);
} // switch
} // while
i->close();
return xml_item;
}
void json_to_xml( store::Item_t const &json_item, store::Item_t *xml_item ) {
ZORBA_ASSERT( xml_item );
switch ( json_item->getKind() ) {
case store::Item::ARRAY:
*xml_item = j2x_array( json_item, nullptr );
break;
case store::Item::OBJECT:
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_ArrayRequired ) )
);
default:
ZORBA_ASSERT( false );
}
}
///////////////////////////////////////////////////////////////////////////////
static void x2j_attributes( store::Item_t const &element,
store::Item_t *json_item ) {
ZORBA_ASSERT( json_item );
store::Item_t att_item;
vector<store::Item_t> keys, values;
store::Iterator_t i( element->getAttributes() );
i->open();
while ( i->next( att_item ) ) {
zstring const att_name( name_of( att_item ) );
if ( att_name != "xmlns" ) {
push_back( &keys, att_name );
push_back( &values, att_item->getStringValue() );
}
} // while
i->close();
if ( !keys.empty() )
GENV_ITEMFACTORY->createJSONObject( *json_item, keys, values );
}
// forward declaration
static void x2j_element( store::Item_t const &element,
store::Item_t *json_item );
static void x2j_children( store::Item_t const &parent,
vector<store::Item_t> *children ) {
ZORBA_ASSERT( children );
store::Iterator_t i( parent->getChildren() );
i->open();
store::Item_t child_item, temp_item;
while ( i->next( child_item ) ) {
if ( !x2j_map_atomic( child_item, &temp_item ) ) {
if ( !child_item->isNode() )
throw XQUERY_EXCEPTION(
zerr::ZJ2X0001_JSONML_ARRAY_BAD_JSON,
ERROR_PARAMS( ZED( ZJ2X0001_BadElement ), child_item->getKind() )
);
switch ( child_item->getNodeKind() ) {
case store::StoreConsts::elementNode:
x2j_element( child_item, &temp_item );
break;
case store::StoreConsts::textNode: {
zstring s( child_item->getStringValue() );
GENV_ITEMFACTORY->createString( temp_item, s );
break;
}
default:
continue;
} // switch
} // if
children->push_back( temp_item );
} // while
i->close();
}
static void x2j_element( store::Item_t const &element,
store::Item_t *json_item ) {
ZORBA_ASSERT( json_item );
store::Item_t attributes_item;
vector<store::Item_t> elements;
push_back( &elements, name_of( element ) );
x2j_attributes( element, &attributes_item );
if ( !!attributes_item )
elements.push_back( attributes_item );
x2j_children( element, &elements );
GENV_ITEMFACTORY->createJSONArray( *json_item, elements );
}
void xml_to_json( store::Item_t const &xml_item, store::Item_t *json_item ) {
ZORBA_ASSERT( json_item );
switch ( xml_item->getNodeKind() ) {
case store::StoreConsts::elementNode:
x2j_element( xml_item, json_item );
break;
default:
throw XQUERY_EXCEPTION( zerr::ZJSE0001_NOT_ELEMENT_NODE );
}
}
///////////////////////////////////////////////////////////////////////////////
} // namespace jsonml_array
} // namespace zorba
/* vim:set et sw=2 ts=2: */
| 29.516605 | 80 | 0.622828 | [
"object",
"vector"
] |
5c041c7e1328c57fae1ae6285fa01a756aa32ad4 | 6,647 | cpp | C++ | openfsa-sys/src/foreign/fsa.cpp | truprecht/openfsa | fda2e8632267c77f308733ead1d58411c3cfa0a9 | [
"MIT"
] | null | null | null | openfsa-sys/src/foreign/fsa.cpp | truprecht/openfsa | fda2e8632267c77f308733ead1d58411c3cfa0a9 | [
"MIT"
] | null | null | null | openfsa-sys/src/foreign/fsa.cpp | truprecht/openfsa | fda2e8632267c77f308733ead1d58411c3cfa0a9 | [
"MIT"
] | null | null | null | #include <fst/fstlib.h>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include "fsa.h"
const fst::Fst<fst::StdArc>* reinterpret(const struct fsa_t *wrapper) {
switch(wrapper->type) {
case STDVECTOR:
return static_cast<fst::StdVectorFst*>(wrapper->fsa);
case RMEPSILON:
return static_cast<fst::RmEpsilonFst<fst::StdArc>*>(wrapper->fsa);
case INTERSECTION:
return static_cast<fst::IntersectFst<fst::StdArc>*>(wrapper->fsa);
case DIFFERENCE:
return static_cast<fst::DifferenceFst<fst::StdArc>*>(wrapper->fsa);
case COMPACT:
return static_cast<fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >*>(wrapper->fsa);
case CONST:
return static_cast<fst::ConstFst<fst::StdArc>*>(wrapper->fsa);
}
return NULL;
}
extern "C" {
struct fsa_t fsa_from_string(const struct vec_t *binary){
std::istringstream stream;
std::string binary_string(static_cast<char*>(binary->first), binary->length);
stream.str(binary_string);
struct fsa_t wrapper = {
COMPACT,
fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >::Read(stream, fst::FstReadOptions())
};
return wrapper;
}
struct vec_t fsa_to_string(const struct fsa_t *f){
std::ostringstream stream;
fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> > compactfst(*reinterpret(f));
compactfst.Write(stream, fst::FstWriteOptions());
std::string binary_string(stream.str());
// move string's char array into heap with std::vector
// allocating std::string in heap would give use a const pointer
std::vector<char> *cstr = new std::vector<char>(binary_string.c_str(), binary_string.c_str() + binary_string.length());
struct vec_t list = { CHAR, cstr, &((*cstr)[0]), binary_string.length() };
return list;
}
struct fsa_t fsa_from_arc_list( int states
, const struct vec_t *final_states
, const struct vec_t *arc_list){
fst::StdVectorFst mut;
fsa_arc *arcs = static_cast<fsa_arc*>(arc_list->first);
int *finals = static_cast<int*>(final_states->first);
// add states
for (int i = 0; i < states; i++){
mut.AddState();
}
// add arcs
for (size_t i = 0; i < arc_list->length; i++){
mut.AddArc(
arcs[i].from_state, fst::StdArc(arcs[i].label, arcs[i].label, arcs[i].weight, arcs[i].to_state)
);
}
// set final states without weight
for (size_t i = 0; i < final_states->length; i++){
mut.SetFinal(finals[i], 0.0);
}
// start is always 0
mut.SetStart(0);
fst::ArcSort(&mut, fst::ILabelCompare<fst::StdArc>());
fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> > *imut = new fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >(mut);
struct fsa_t wrapper = { COMPACT, imut };
return wrapper;
}
struct vec_t fsa_to_arc_list(const struct fsa_t *wrapper){
std::vector<struct fsa_arc> *vec = new std::vector<struct fsa_arc>();
const fst::Fst<fst::StdArc> *fsa = reinterpret(wrapper);
struct fsa_arc carc;
for (fst::StateIterator<fst::StdFst> state(*fsa); !state.Done(); state.Next()){
for (fst::ArcIterator<fst::StdFst> arc(*fsa, state.Value()); !arc.Done(); arc.Next()){
carc.from_state = state.Value();
carc.to_state = arc.Value().nextstate;
carc.label = arc.Value().ilabel;
carc.weight = arc.Value().weight.Value();
vec->push_back(carc);
}
}
struct vec_t al = { ARC, vec, &(*vec)[0], vec->size() };
return al;
}
struct fsa_t fsa_n_best(const struct fsa_t *fsa, int n){
fst::StdVectorFst nbest;
fst::ShortestPath(*reinterpret(fsa), &nbest, n);
fst::RmEpsilon(&nbest);
struct fsa_t ret = {
COMPACT,
new fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >(nbest)
};
return ret;
}
struct fsa_t fsa_intersect(const struct fsa_t *a, const struct fsa_t *b){
fst::StdVectorFst inter;
fst::Intersect(*reinterpret(a), *reinterpret(b), &inter);
struct fsa_t ret = {
COMPACT,
new fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >(inter)
};
return ret;
}
struct fsa_t fsa_difference(const struct fsa_t *a, const struct fsa_t *b){
fst::ArcMapFst<fst::StdArc, fst::StdArc, fst::RmWeightMapper<fst::StdArc> > c(*reinterpret(b), fst::RmWeightMapper<fst::StdArc>());
fst::DeterminizeFst<fst::StdArc> d(c);
fst::DifferenceFst<fst::StdArc> difference(*reinterpret(a), d);
struct fsa_t ret = {
COMPACT,
new fst::CompactFst<fst::StdArc, fst::AcceptorCompactor<fst::StdArc> >(difference)
};
return ret;
}
void fsa_free(const struct fsa_t *fsa){
delete reinterpret(fsa);
}
int fsa_initial_state(const struct fsa_t *fsa){
return reinterpret(fsa)->Start();
}
struct vec_t fsa_final_states(const struct fsa_t *fsa){
// allocate vector on stack
std::vector<int> *final_states = new std::vector<int>;
const fst::Fst<fst::StdArc> *fst = reinterpret(fsa);
// iterate through states, keep those with final weight ≠ zero
for (fst::StateIterator<fst::StdFst> state(*fst); !state.Done(); state.Next()) {
if (fst->Final(state.Value()).Value() != fst::TropicalWeight::Zero()){
final_states->push_back(state.Value());
}
}
// return list as pointer × length pair
struct vec_t result = { INT, final_states, &(*final_states)[0], final_states->size() };
return result;
}
void vec_free(const struct vec_t *vec) {
switch (vec->type) {
case CHAR:
delete static_cast<std::vector<char>*>(vec->vec_obj);
return;
case INT:
delete static_cast<std::vector<int>*>(vec->vec_obj);
return;
case ARC:
delete static_cast<std::vector<fsa_arc>*>(vec->vec_obj);
return;
}
}
} | 36.322404 | 159 | 0.574394 | [
"vector"
] |
5c0b17ef3bc8a66be1135349759121dc132b1a81 | 70,486 | cpp | C++ | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebRIVAHandler.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebRIVAHandler.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_WebRIVAHandler.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCWebSrvC_WebRIVAHandler.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 05/27/2017
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the handler for the WebBrowser based RIVA client.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCWebSrvC_.hpp"
#include "CIDJPEG.hpp"
#include "CIDPNG.hpp"
// ---------------------------------------------------------------------------
// Local types and constants
// ---------------------------------------------------------------------------
namespace
{
namespace CQCWebSrvC_WebRIVAHandler
{
// Some bespoke Websocket error codes, starting at the per-application base code
constexpr tCIDLib::TCard2 c2WSockErr_LoginFailed = kCQCWebSrvC::c2WSockErr_AppBase;
//
// Some time periods that we use in the Idle callback to invoke various update cycles
// on the view.
//
constexpr tCIDLib::TEncodedTime enctActive(100 * kCIDLib::enctOneMilliSec);
constexpr tCIDLib::TEncodedTime enctValue(250 * kCIDLib::enctOneMilliSec);
constexpr tCIDLib::TEncodedTime enctEvent(2 * kCIDLib::enctOneSecond);
constexpr tCIDLib::TEncodedTime enctTOCheck(kCIDLib::enctOneSecond);
}
};
// ---------------------------------------------------------------------------
// CLASS: TWebSockRIVAThread::TGUIEvent
// PREFIX: ev
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TWebSockRIVAThread::TGUIEvent: Public, static methods
// ---------------------------------------------------------------------------
//
// Compares two events for the same type. This is used as a comparator function in evnt
// queue operations that require one. We use it to only post some event types if there's
// not already one in the queue, to avoid getting it backed up.
//
tCIDLib::TBoolean TWebSockRIVAThread::TGUIEvent::
bCompEvent( const TWebSockRIVAThread::TGUIEvent& ev1
, const TWebSockRIVAThread::TGUIEvent& ev2)
{
return ev1.m_eType == ev2.m_eType;
}
// ---------------------------------------------------------------------------
// TWebSockRIVAThread::TGUIEvent: Constructors and Destructors
// ---------------------------------------------------------------------------
TWebSockRIVAThread::TGUIEvent::TGUIEvent() :
m_c4Val1(0)
, m_c4Val2(0)
, m_eType(TWebSockRIVAThread::EGUIEvTypes::None)
, m_f8Val(0.0)
, m_i4Val1(0)
, m_i4Val2(0)
, m_i4Val3(0)
, m_i4Val4(0)
, m_pevNotify(nullptr)
, m_piceInfo(nullptr)
, m_padcbInfo(nullptr)
{
}
// A specialized one for async data callbacks
TWebSockRIVAThread::TGUIEvent::TGUIEvent(TCQCIntfADCB* const padcbInfo) :
m_c4Val1(0)
, m_c4Val2(0)
, m_eType(TWebSockRIVAThread::EGUIEvTypes::AsyncDCB)
, m_f8Val(0.0)
, m_i4Val1(0)
, m_i4Val2(0)
, m_i4Val3(0)
, m_i4Val4(0)
, m_pevNotify(nullptr)
, m_piceInfo(nullptr)
, m_padcbInfo(padcbInfo)
{
}
TWebSockRIVAThread::TGUIEvent::TGUIEvent(const EGUIEvTypes eType) :
m_c4Val1(0)
, m_c4Val2(0)
, m_eType(eType)
, m_f8Val(0.0)
, m_i4Val1(0)
, m_i4Val2(0)
, m_i4Val3(0)
, m_i4Val4(0)
, m_pevNotify(nullptr)
, m_piceInfo(nullptr)
, m_padcbInfo(nullptr)
{
}
TWebSockRIVAThread::TGUIEvent::~TGUIEvent()
{
// If it didn't get cleaned up, then destroy it
if (m_padcbInfo)
{
try
{
delete m_padcbInfo;
}
catch(...)
{
}
m_padcbInfo = nullptr;
}
}
// ---------------------------------------------------------------------------
// CLASS: TWebSockRIVAThread
// PREFIX: thr
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TWebSockRIVAThread: Constructors and destructor
// ---------------------------------------------------------------------------
TWebSockRIVAThread::TWebSockRIVAThread(const tCIDLib::TCard1 c1ThreadId) :
TWebsockThread(tCQCWebSrvC::EWSockTypes::RIVA, kCIDLib::False)
, m_bClientVisState(kCIDLib::True)
, m_bEnableCaching(kCIDLib::True)
, m_bGUIBailOut(kCIDLib::False)
, m_bLogGUIEvents(kCIDLib::False)
, m_bLogInMsgs(kCIDLib::False)
, m_bShutdownReq(kCIDLib::False)
, m_c4TimerSuspend(0)
, m_colGUIEvQ(tCIDLib::EAdoptOpts::Adopt, tCIDLib::EMTStates::Safe)
, m_enctLastMsg(0)
, m_enctNextActive(0)
, m_enctNextEvent(0)
, m_enctNextVal(0)
, m_enctNextTOCheck(0)
, m_eCurState(EStates::WaitSessState)
, m_f8ClientLat(kCQCWebRIVA::f8LocNotSet)
, m_f8ClientLong(kCQCWebRIVA::f8LocNotSet)
, m_gesthInp(this)
, m_pcivTarget(nullptr)
, m_szDevRes(800, 600)
, m_thrFauxGUIThread
(
TString(L"CQCWebRIVAGUIThread_") + TString(TCardinal(c1ThreadId))
, TMemberFunc<TWebSockRIVAThread>(this, &TWebSockRIVAThread::eFauxGUIThread)
)
{
}
TWebSockRIVAThread::~TWebSockRIVAThread()
{
}
// ---------------------------------------------------------------------------
// TWebSockRIVAThread: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TWebSockRIVAThread::AsyncCallback(const tCQCIntfEng::EAsyncCmds, TCQCIntfView&)
{
// A no-op for now. We might implement some commands later
}
//
// Queue this up. The faux GUI thread will grab it and make the call back to the
// view.
//
tCIDLib::TVoid
TWebSockRIVAThread::AsyncDataCallback(TCQCIntfADCB* const padcbInfo)
{
// Queue up a GUI event for this guy
m_colGUIEvQ.Add(new TGUIEvent(padcbInfo));
}
// If our view is set, then pass it on
tCIDLib::TBoolean
TWebSockRIVAThread::bProcessGestEv( const tCIDCtrls::EGestEvs eEv
, const TPoint& pntStart
, const TPoint& pntAt
, const TPoint& pntDelta
, const tCIDLib::TBoolean bTwoFingers)
{
tCIDLib::TBoolean bRet = kCIDLib::False;
if (m_pcivTarget)
{
bRet = m_pcivTarget->bProcessGestEv
(
eEv, pntStart, pntAt, pntDelta, bTwoFingers
);
}
return bRet;
}
// We just need to send this on to the client
tCIDLib::TVoid
TWebSockRIVAThread::CreateRemWidget(const TString& strUID
, const tCQCIntfEng::ERIVAWTypes eType
, const TArea& areaAt
, const tCIDLib::TKVPList& colParams
, const tCIDLib::TBoolean bInitVis)
{
// Turn the parameters into a raw JSON array
TString strParams;
MakeRawObject(colParams, strParams);
TWebRIVATools wrtToUse;
tCIDLib::TCard4 c4Bytes;
TMemBuf* pmbufNew = wrtToUse.pmbufFormatCreateRemWidget
(
c4Bytes, strUID, tWebRIVA::EWdgTypes(eType), areaAt, strParams, bInitVis
);
SendMsg(pmbufNew, c4Bytes);
}
// Send this on to the client
tCIDLib::TVoid
TWebSockRIVAThread::DestroyRemWidget(const TString& strUID
, const tCQCIntfEng::ERIVAWTypes eType)
{
TWebRIVATools wrtToUse;
tCIDLib::TCard4 c4Bytes;
TMemBuf* pmbufNew = wrtToUse.pmbufFormatDestroyRemWidget
(
c4Bytes, strUID, tWebRIVA::EWdgTypes(eType)
);
SendMsg(pmbufNew, c4Bytes);
}
//
// This is called by the int engine becase we register ourself as a handler
// for special actions. This one for now is just ignored in remote mode.
//
tCIDLib::TVoid TWebSockRIVAThread::DismissBlanker(TCQCIntfView&)
{
}
//
// We have to emulate the way action command processing works in the GUI scenario, so
// our view derivative calls this method any time an action command targets one of the
// widgets. We queue it up on the faux GUI thread's queue and then block till he
// finishes processesing it.
//
// This correctly serializes access to the template and allows the action engine to
// call back into the GUI message loop if a popup is done (which otherwise would happen
// from the background thread that the action runs in.
//
// WE CANNOT allow any exception to propogate out of here, since it will propogate in
// the Faux GUI thread, not back to the action thread. So we catch them and return the
// info in the passed command event object.
//
tCIDLib::TVoid
TWebSockRIVAThread::DispatchActEvent(tCQCIntfEng::TIntfCmdEv& iceToDo)
{
// Queue up a GUI event and point it at an event that we'll wait on
TEvent evWait(tCIDLib::EEventStates::Reset);
TGUIEvent* pgevDispatch = new TGUIEvent(EGUIEvTypes::DispatchActEv);
pgevDispatch->m_pevNotify = &evWait;
pgevDispatch->m_piceInfo = &iceToDo;
m_colGUIEvQ.Add(pgevDispatch);
// Now wait for the event to trigger
evWait.WaitFor();
}
//
// This is called by the int engine becase we register ourself as a handler
// for special actions. We handle the exit one ourself, and pass the others
// to the client.
//
tCIDLib::TVoid
TWebSockRIVAThread::DoSpecialAction(const tCQCIntfEng::ESpecActs eSpecAct
, const tCIDLib::TBoolean
, TCQCIntfView&)
{
//
// We handle the exit action if a popup is up, else we pass everything
// to the client to handle.
//
if ((eSpecAct == tCQCIntfEng::ESpecActs::Exit) && m_pcivTarget->bHasPopups())
{
// We need to queue an exit loop command to the GUI thread
m_colGUIEvQ.Add(new TGUIEvent(EGUIEvTypes::ExitLoop));
}
else
{
TWebRIVATools wrtToUse;
tCIDLib::TCard4 c4Bytes;
TMemBuf* pmbufNew = wrtToUse.pmbufFormatSpecialAction
(
c4Bytes, tWebRIVA::ESpecialActs(eSpecAct)
);
SendMsg(pmbufNew, c4Bytes);
}
}
// Always just report that we are in remote mode
tCQCIntfEng::EAppFlags TWebSockRIVAThread::eAppFlags() const
{
return tCQCIntfEng::EAppFlags::RemoteMode;
}
//
// We start up a secondary processing thread, which just calls this method. This loop
// simulates a GUI type event loop thread, so that things can work more like in the
// standard Window based template engine. The worker thread posts us events to service.
// This also must makes it esier for us as well, since it allows this worker thread
// to concentrate purely on servicing the client and for fully async communications
// between the two threads via queues.
//
// If one of our press/release events (which are passed to the interface engine) causes
// an action to occur, then the interface engine will start another thread to process
// the action. If any command target is a widget, then that thread will call back into
// our view, asking for the cmd to be dispatched. The view will call DispatchActEvent()
// above. The thread will queue up an item in our queue. We'll look up the target
// widget and perform the command, then trigger the event in the queued item to let the
// calling action thread go.
//
// If the command is to do a popup/popout, then the command will not return until the
// popup is closed. The engine will call back into here (on this same thread) to do what
// would be a modal loop in a real GUI. So the action thread will remain blocked until
// that popup is exited, in which case we'll get an ExitLoop command, which will unwind
// back to the previous recursion level, fall out of the action dispatch command below,
// and that will release the waiting action thread. If the action is not done, then
// it will happen more times. If it is, then the action thread will end, and we will come
// back out of the Press/Release block below that started the whole thing, and we are now
// unrecursed for that action.
//
// So, recursion happens, but it's always on this thread. The action threads don't actually
// call this method. They block above and wait for the posted action command to complete.
//
// To support unwinding the stack completely, we have the m_bGUIBailout thread. If it's
// set, that will cause all the nested loops to exit. It will also cause all waiting action
// threads to be released (and we'll pass back it back a status that tells it to stop
// processing the action. Since we could only be in a nested scenario if we were recursed
// back in from a dispatch action event command, each exit from the subsequently invoked
// modal loop will get us back out of the dispatch below which will wake up the action
// thread and tell it to stop.
//
// So the GUI bailout flag cleanly gets the whole GUI loop unwound and all nested
// actions stopped.
//
tCIDLib::TVoid TWebSockRIVAThread::FauxGUILoop(tCIDLib::TBoolean& bBreakFlag)
{
while (!bBreakFlag && !m_bGUIBailOut)
{
TGUIEvent* pgevCur = nullptr;
try
{
// TEmp debug code
m_eLastGUIEv = EGUIEvTypes::None;
// Wait for an event to process
pgevCur = m_colGUIEvQ.pobjGetNext(100, kCIDLib::False);
if (pgevCur)
{
// Temp debug code
m_eLastGUIEv = pgevCur->m_eType;
TJanitor<TGUIEvent> janEvent(pgevCur);
switch(pgevCur->m_eType)
{
case EGUIEvTypes::ActiveUpdate :
//
// Ask the view to do a active update pass. This one
// we post to ourself, it doesn't come from the client.
//
m_pcivTarget->DoActiveUpdatePass();
break;
case EGUIEvTypes::AsyncDCB :
{
//
// Get the callback object out and orphan from the event
// into a janitor to insure it gets cleaned up but the event
// doesn't try to do it again.
//
TCQCIntfADCB* padcbInfo = pgevCur->m_padcbInfo;
pgevCur->m_padcbInfo = nullptr;
if (padcbInfo)
{
TJanitor<TCQCIntfADCB> janData(padcbInfo);
if (m_bLogGUIEvents)
{
TString strMsg(L"Handling asyncCB. CBId=");
strMsg += pgevCur->m_padcbInfo->m_strCBId;
LogStatusMsg(strMsg, CID_LINE);
}
// And now do the callback
padcbInfo->m_pcivCaller->AsyncDataCallback(padcbInfo);
}
break;
}
case EGUIEvTypes::CancelInput :
{
if (m_bLogGUIEvents)
LogStatusMsg(L"Got gesture cancel", CID_LINE);
m_gesthInp.CancelGesture();
break;
}
case EGUIEvTypes::CheckTimeout :
{
// Let the view see if it's time for a timeout event
m_pcivTarget->bCheckTimeout();
break;
}
case EGUIEvTypes::DispatchActEv :
{
// Handle an action command from a background action thread
if (m_bLogGUIEvents)
{
TString strMsg(L"Handling dispatched action command. Target=");
strMsg += pgevCur->m_piceInfo->pccfgToDo->strTargetName();
strMsg += L", Cmd=";
strMsg += pgevCur->m_piceInfo->pccfgToDo->strCmdId();
LogStatusMsg(strMsg, CID_LINE);
}
HandleGUIActDispatch(*pgevCur);
break;
}
case EGUIEvTypes::ExitLoop :
if (m_bLogGUIEvents)
LogStatusMsg(L"Processing exit event", CID_LINE);
bBreakFlag = kCIDLib::True;
break;
case EGUIEvTypes::EventUpdate :
// We don't currently handle async events in RIVA
break;
case EGUIEvTypes::HotKey :
{
// Pass the hot key on to the viewer
CIDAssert(m_pcivTarget != nullptr, L"Got mouse event before view was set")
m_pcivTarget->HotKey(tCQCIntfEng::EHotKeys(pgevCur->m_c4Val1));
break;
}
case EGUIEvTypes::Move :
{
// Pass the mouse movement to the viewer
CIDAssert(m_pcivTarget != nullptr, L"Got mouse event before view was set")
TPoint pntAt(pgevCur->m_i4Val1, pgevCur->m_i4Val2);
m_gesthInp.HandleMsg(tCQCWebRIVA::EGestEvs::Move, pntAt);
break;
}
case EGUIEvTypes::Press :
case EGUIEvTypes::Release :
{
//
// Pass the mouse press/release to the viewer.
//
CIDAssert(m_pcivTarget != nullptr, L"Got mouse event before view was set")
if (m_bLogGUIEvents)
{
LogStatusMsg
(
(pgevCur->m_eType == EGUIEvTypes::Press) ? L"Processing press event"
: L"Processing release event"
, CID_LINE
);
}
TPoint pntAt(pgevCur->m_i4Val1, pgevCur->m_i4Val2);
m_gesthInp.HandleMsg
(
(pgevCur->m_eType == EGUIEvTypes::Press)
? tCQCWebRIVA::EGestEvs::Press
: tCQCWebRIVA::EGestEvs::Release
, pntAt
);
break;
}
case EGUIEvTypes::Redraw :
{
// Force a redraw of the whole view
m_pcivTarget->Redraw();
break;
}
case EGUIEvTypes::SetVisState :
{
//
// The client has changed bgn/fgn state. Set a flag to remember
// this state. If it's not visible, we'll stop dispatching graphics
// commands. If he came back, then force a redraw.
//
const tCIDLib::TBoolean bNewState(pgevCur->m_c4Val1 != 0);
if (m_bClientVisState != bNewState)
if (m_bLogGUIEvents)
{
if (bNewState)
LogStatusMsg(L"Client has moved to fgn state", CID_LINE);
else
LogStatusMsg(L"Client has moved to bgn state", CID_LINE);
}
{
m_bClientVisState = bNewState;
if (m_bClientVisState)
m_pcivTarget->Redraw();
}
break;
}
case EGUIEvTypes::SizeChange :
{
if (m_bLogGUIEvents)
LogStatusMsg(L"Procesing display size change event", CID_LINE);
// Tell the view that the view area changed
TSize szNew(pgevCur->m_c4Val1, pgevCur->m_c4Val2);
m_pcivTarget->NewSize(szNew);
break;
}
case EGUIEvTypes::ValueUpdate :
//
// Ask the view to do a value based update pass. This
// one we post to ourself, it doesn't come from the
// client.
//
m_pcivTarget->DoUpdatePass();
break;
default :
break;
};
}
}
catch(TError& errToCatch)
{
// Just in case, so we don't go crazy in a worst case scenario
TThread::Sleep(100);
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadError
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, m_strSessionName
);
}
catch(...)
{
// Just in case, so we don't go crazy in a worst case scenario
TThread::Sleep(100);
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadError
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, m_strSessionName
);
}
}
}
// If our view is set, just pass it on
tCIDLib::TVoid TWebSockRIVAThread::GestClick(const TPoint& pntAt)
{
if (m_pcivTarget)
m_pcivTarget->Clicked(pntAt);
}
// If our view is set, just pass it on
tCIDLib::TVoid
TWebSockRIVAThread::GestFlick(const tCIDLib::EDirs eDirection
, const TPoint& pntStartPos)
{
if (m_pcivTarget)
m_pcivTarget->ProcessFlick(eDirection, pntStartPos);
}
// A no-op for us
tCIDLib::TVoid
TWebSockRIVAThread::GestInertiaIdle( const tCIDLib::TEncodedTime
, const tCIDLib::TCard4
, const tCIDLib::EDirs)
{
}
// A no-op for us
tCIDLib::TVoid TWebSockRIVAThread::GestReset(const tCIDCtrls::EGestReset)
{
}
//
// Let the client know a new template was loaded and it's size, and we pass the border
// color that's currently set.
//
tCIDLib::TVoid
TWebSockRIVAThread::NewTemplate(const TCQCIntfTemplate& iwdgNew
, TCQCIntfView&
, const tCIDLib::TCard4 c4StackPos)
{
TWebRIVATools wrtToUse;
//
// If it's a new base template, we need to update our virtual device res. In the
// RIVA scenario there's no actual screen so we keep it set to the size of the
// base template. Only do this if the view is already created since it will also
// get called on initial startup before the view exists, and all of this kind
// of stuff will be getting taken care of differently.
//
if ((c4StackPos == 0) && m_pcivTarget)
{
m_szDevRes = iwdgNew.areaActual().szArea();
TWebRIVAGraphDev* pgdevNew = new TWebRIVAGraphDev(m_szDevRes, this);
m_cptrRemDev.SetPointer(pgdevNew);
// Let the view update itself
m_pcivTarget->NewSize(m_szDevRes);
}
tCIDLib::TCard4 c4Size;
TMemBuf* pmbufMsg = wrtToUse.pmbufFormatNewTemplate
(
c4Size, iwdgNew.strTemplateName(), iwdgNew.areaActual().szArea()
);
SendMsg(pmbufMsg, c4Size);
}
MCQCCmdTracer* TWebSockRIVAThread::pmcmdtTrace()
{
// A No-op for us
return nullptr;
}
tCIDLib::TVoid
TWebSockRIVAThread::PauseTimers(const tCIDLib::TBoolean bPauseState)
{
if (bPauseState)
{
m_c4TimerSuspend++;
}
else
{
CIDAssert(m_c4TimerSuspend > 0, L"Timer supsension counter underflow");
if (m_c4TimerSuspend)
m_c4TimerSuspend--;
}
}
// If our view is set, just pass it on
tCIDLib::TVoid
TWebSockRIVAThread::PerGestOpts(const TPoint& pntAt
, const tCIDLib::EDirs eDir
, const tCIDLib::TBoolean bTwoFingers
, tCIDCtrls::EGestOpts& eOpts
, tCIDLib::TFloat4& f4VScale)
{
if (m_pcivTarget)
m_pcivTarget->PerGestOpts(pntAt, eDir, bTwoFingers, eOpts, f4VScale);
}
//
// Any messages sent from the RIVA stuff will go through these methods. Partly because the
// underlying message queuing methods in our base class are protected so that other code
// needs us to provide access to them, and also partly so that we can intercept them and
// do any necessary magic along the way.
//
//
// This one is called by the redirecting graphics device. It could call SendMsg directly,
// but we need to be able to suppress drawing commands when the client is not in the fgn,
// so they call this. If the client is visible, we queue the msg, else we just eat it.
//
tCIDLib::TVoid
TWebSockRIVAThread::SendGraphicsMsg(TMemBuf* const pmbufToAdopt, const tCIDLib::TCard4 c4Size)
{
if (m_bClientVisState)
QueueTextMsg(pmbufToAdopt, c4Size);
else
delete pmbufToAdopt;
}
//
// This one is used to send any image related messages. We see if the image is in the client's
// image map. If not, then we send it. That way, he has the image before he needs to draw it.
//
// Because we can get various types of images, but we don't want to have to worry about going
// to find the original image data. We know we have the image, because we are drawing it
// right now. So we just convert it to PNG or JPG and send that. This avoids all kinds of
// complications that would otherwise occur, and also allows us to deal with images that the
// IV builds on the fly, such as color palettes.
//
// If the image is a CQC image repo image or an on the fly image, we send it as PNG, else we
// send it as JPEG.
//
// If the client is not visible, in a bgn tab, we just eat the message. When it comes forward
// again a full redraw will be done, and this will drawn again and it still won't be in the
// client's cache (if its not now) and so we will send it then.
//
tCIDLib::TVoid
TWebSockRIVAThread::SendImgMsg( const TString& strFullPath
, const TBitmap& bmpToSend
, TMemBuf* const pmbufToAdopt
, const tCIDLib::TCard4 c4Size)
{
// Just in case...
TJanitor<TMemBuf> janBuf(pmbufToAdopt);
// If the client isn't visible we just return, and eat the msg
if (!m_bClientVisState)
return;
// Get out the path and serial number
const tCIDLib::TCard4 c4SerialNum = bmpToSend.c4SerialNum();
const TRIVAImgItem* pimiTar = m_rimapClient.pimiFind(strFullPath);
if (!pimiTar || (pimiTar->objValue() != c4SerialNum))
{
try
{
//
// Log the paths of the messages we are sending, to correlate with the browser
// console output
//
#if CID_DEBUG_ON
//facCQCWebSrvC().LogMsg
//(
// CID_FILE
// , CID_LINE
// , strFullPath
// , tCIDLib::ESeverities::Status
//);
#endif
//
// Let's convert this guy to a PNG first. Though in some cases we can get direct
// access to the pixel data, we also need to potentially get the palette if it is
// palette based. So we just query the pixel and palette info.
//
TPixelArray pixaData;
TClrPalette palData;
bmpToSend.QueryImgData(m_pcivTarget->gdevCompat(), pixaData, palData);
// Generate an image from this
tCIDLib::TBoolean bIsPNG;
TCIDImage* pimgToSend = nullptr;
if (strFullPath.bStartsWith(kCQCKit::strWRIVA_RepoPref)
|| strFullPath.bStartsWith(kCQCKit::strWRIVA_IVOTFPref))
{
bIsPNG = kCIDLib::True;
pimgToSend = new TPNGImage(pixaData, palData);
}
else
{
bIsPNG = kCIDLib::False;
pimgToSend = new TJPEGImage(pixaData, palData);
}
TJanitor<TCIDImage> janImg(pimgToSend);
// Convert it to Base64 in a string
tCIDLib::TCard4 c4BinImgBytes = 0;
TString strEncoded(pimgToSend->c4ImageSz() + (pimgToSend->c4ImageSz() / 4));
{
// Create a buffer to hold the raw flattened PNG and stream it out
TBinMBufOutStream strmRaw(strEncoded.c4BufChars());
strmRaw << *pimgToSend << kCIDLib::FlushIt;
c4BinImgBytes = strmRaw.c4CurSize();
//
// Create a linked input stream over the output stream so we can stream from
// it directly and avoid any copying.
//
TBinMBufInStream strmRawIn(strmRaw);
// Now create one over the target string and encode to that
TTextStringOutStream strmTar(&strEncoded);
TBase64 b64Encode;
// Disable line breaks by setting the line width to max card
b64Encode.c4LineWidth(kCIDLib::c4MaxCard);
b64Encode.Encode(strmRawIn, strmTar);
strmTar.Flush();
}
//
// Now we send the image data in chunks. We have to send a first image
// msg first. If that covers the whole image, then fine, else we continue
// until the last one.
//
TWebRIVATools wrtToUse;
TMemBuf* pmbufCur = nullptr;
//
// The max images bytes we send per round has to leave room for the other msg
// overhead. Normally it would have to also include space for possible UTF-8
// expansion of chars to bytes, but we know this is base64 encoded.
//
const tCIDLib::TCard4 c4MaxChunkImgChars(kCQCWebSrvC::c4MaxWebsockMsgSz - 4192);
//
// Optimize if the whole thing can be sent in one chunk since we don't have
// to copy the image data, we can just send from the original.
//
const tCIDLib::TCard4 c4ImgChars = strEncoded.c4Length();
tCIDLib::TCard4 c4MsgBytes;
if (c4ImgChars < c4MaxChunkImgChars)
{
// Indicate this is the last block
pmbufCur = wrtToUse.pmbufFormatImgDataFirst
(
c4MsgBytes
, strFullPath
, c4SerialNum
, c4BinImgBytes
, bmpToSend.szBitmap()
, bIsPNG
, kCIDLib::True
, strEncoded
);
SendMsg(pmbufCur, c4MsgBytes);
}
else
{
tCIDLib::TCard4 c4SoFar = 0;
tCIDLib::TCard4 c4AvailChars = c4ImgChars;
tCIDLib::TCard4 c4ChunkChars = 0;
TString strChunkStr;
// We have to send at least one max img bytes chunk so fully allocate
THeapBuf mbufChunk(c4MaxChunkImgChars, c4MaxChunkImgChars);
while (c4AvailChars > 0)
{
//
// Get up to a chunk's worth of bytes. We have to leave room for the other
// msg data values.
//
if (c4AvailChars >= c4MaxChunkImgChars)
c4ChunkChars = c4MaxChunkImgChars;
else
c4ChunkChars = c4AvailChars;
// Reduce the available chars now, so we can know if this is the last one
c4AvailChars -= c4ChunkChars;
strChunkStr.CopyInSubStr(strEncoded, c4SoFar, c4ChunkChars);
if (c4SoFar)
{
//
// It's not the first chunk. If available bytes is zero, then it
// is the last block for this image.
//
pmbufCur = wrtToUse.pmbufFormatImgDataNext
(
c4MsgBytes, strFullPath, c4AvailChars == 0, strChunkStr
);
}
else
{
// It's the first chunk
pmbufCur = wrtToUse.pmbufFormatImgDataFirst
(
c4MsgBytes
, strFullPath
, c4SerialNum
, c4BinImgBytes
, bmpToSend.szBitmap()
, bIsPNG
, kCIDLib::False
, strChunkStr
);
}
SendMsg(pmbufCur, c4MsgBytes);
// Move our working index forward by this chunk size
c4SoFar += c4ChunkChars;
}
}
//
// Assume at this point that he has this image in his cache. He will send
// us a message that he added it, but we could see this image drawn a number
// of times before that got to us.
//
m_rimapClient.bAddUpdate(strFullPath, c4SerialNum);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
//
// Fall through and at least still send the message. The client won't have the
// image.
//
}
}
// Now send the original msg that references this image
SendMsg(janBuf.pobjOrphan(), c4Size);
}
//
// This one ultimately gets called for all RIVA messages. Our other helpers here will
// call this one. Here we can do any stuff we need to do based on number of messages sent
// or tracking the time of the last message sent or anything like that.
//
tCIDLib::TVoid
TWebSockRIVAThread::SendMsg(TMemBuf* const pmbufToAdopt, const tCIDLib::TCard4 c4Size)
{
// Pass it on to the web socket parent class to be queued up for transmission
QueueTextMsg(pmbufToAdopt, c4Size);
}
// Send a message to the client
tCIDLib::TVoid
TWebSockRIVAThread::SetRemWidgetVis(const TString& strUID
, const tCQCIntfEng::ERIVAWTypes eType
, const tCIDLib::TBoolean bNewState)
{
TWebRIVATools wrtToUse;
tCIDLib::TCard4 c4Size;
TMemBuf* pmbufMsg = wrtToUse.pmbufFormatSetRemWidgetVis
(
c4Size, strUID, tWebRIVA::EWdgTypes(eType), bNewState
);
SendMsg(pmbufMsg, c4Size);
}
// Send a message to the client
tCIDLib::TVoid
TWebSockRIVAThread::SetRemWidgetURL(const TString& strUID
, const tCQCIntfEng::ERIVAWTypes eType
, const TString& strURL
, const tCIDLib::TKVPList& colParams)
{
// Turn the parameters into a raw JSON object
TString strParams;
MakeRawObject(colParams, strParams);
TWebRIVATools wrtToUse;
tCIDLib::TCard4 c4Size;
TMemBuf* pmbufMsg = wrtToUse.pmbufFormatSetRemWidgetURL
(
c4Size, strUID, tWebRIVA::EWdgTypes(eType), strURL, strParams
);
SendMsg(pmbufMsg, c4Size);
}
// ---------------------------------------------------------------------------
// TWebSockRIVAThread: Protected, inherited methods
// ---------------------------------------------------------------------------
//
// Prep any data members for a new connection. Check any query parms that we support
// in order to get set up any options for us. We don't yet trust the client, so we don't
// do anything yet that requires trust.
//
// Since these threads are reused, we must be sure that we initialize all data that
// is per-connection.
//
// To be extra safe, we make sure that the GUI thread got stopped, and try to stop it
// if not.
//
tCIDLib::TCard4
TWebSockRIVAThread::c4WSInitialize( const TURL& urlReq
, TString& strRepText
, TString& strErrText)
{
if (m_thrFauxGUIThread.bIsRunning())
{
try
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIStillRunning
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::Internal
, TInteger(tCIDLib::TInt4(m_eLastGUIEv))
);
m_bGUIBailOut = kCIDLib::True;
m_thrFauxGUIThread.eWaitForDeath(5000);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
return kCIDNet::c4HTTPStatus_SrvError;
}
}
strRepText = L"OK";
return kCIDNet::c4HTTPStatus_OK;
}
tCIDLib::TVoid TWebSockRIVAThread::CheckShutdownReq() const
{
}
//
// We have a conneced client now and the client has gone through any secure socket
// negotiations and such. So now we need to try to log in. They provide the login info
// via URL parameters.
//
tCIDLib::TVoid TWebSockRIVAThread::Connected()
{
// We have to have gotten name/password query parameters
TString strUserName, strPassword;
if (!bFindQParam(L"user", strUserName) || !bFindQParam(L"pw", strPassword))
{
// Send a failure back and shutdown
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_NoCreds);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
// We can get a session name that we'll use in some log messages
if (!bFindQParam(L"sessname", m_strSessionName))
m_strSessionName = L"Unknown";
//
// Default the optional flags that the clients can set to known defaults, so
// that we and the client always start in sync. He can send us messages to set
// these as desired after connection.
//
m_bEnableCaching = kCIDLib::True;
m_bLogInMsgs = kCIDLib::False;
m_bLogGUIEvents = kCIDLib::False;
// They can provide the lat/long info
m_f8ClientLat = kCQCWebRIVA::f8LocNotSet;
m_f8ClientLong = kCQCWebRIVA::f8LocNotSet;
// Reset stuff that is per-connection
m_enctNextActive = 0;
m_enctNextEvent = 0;
m_enctNextVal = 0;
// We got the values so try the actual login
try
{
// Get a reference to the security server
tCQCKit::TSecuritySrvProxy orbcSS = facCQCKit().orbcSecuritySrvProxy();
// And ask it to give us a challenge
TCQCSecChallenge seccLogon;
if (orbcSS->bLoginReq(strUserName, seccLogon))
{
// Lets do a hash of the user's password
TMD5Hash mhashPW;
TMessageDigest5 mdigTmp;
mdigTmp.StartNew();
mdigTmp.DigestStr(strPassword);
mdigTmp.Complete(mhashPW);
// And use that to validate the challenge
seccLogon.Validate(mhashPW);
// And send that back to get a security token, assuming its legal
TCQCUserAccount uaccToFill;
TCQCSecToken sectToFill;
tCQCKit::ELoginRes eRes;
if (orbcSS->bGetSToken(seccLogon, sectToFill, uaccToFill, eRes)
&& (eRes == tCQCKit::ELoginRes::Ok))
{
// Make sure this guy has a default template
if (uaccToFill.strDefInterfaceName().bIsEmpty())
{
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_NoDefTmpl);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
// It worked so store the info away
m_cuctxClient.Set(uaccToFill, sectToFill);
m_uaccClient = uaccToFill;
//
// They can send environmental variables for this session. So search
// for those and set them if found.
//
TString strVarVal;
TString strExpVal;
TString strVarName(L"env");
for (tCIDLib::TCard4 c4Index = 1; c4Index <= 9; c4Index++)
{
strVarName.CapAt(3);
strVarName.AppendFormatted(c4Index);
if (bFindQParam(strVarName, strVarVal))
{
// Expand it out
TURL::ExpandTo
(
strVarVal
, strExpVal
, TURL::EExpTypes::Query
, tCIDLib::EAppendOver::Overwrite
);
m_cuctxClient.SetEnvRTVAt(c4Index - 1, strExpVal);
}
}
// Tell the client we logged in and provide user info
SendLoginRes(kCIDLib::True, kCQCWSCMsgs::midWRIVA_LoginSucceeded);
}
else
{
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_BadCreds);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
}
else
{
// It has to be an unknown name/password
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_BadCreds);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_LoginExcept);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
catch(...)
{
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_LoginExcept);
StartShutdown(CQCWebSrvC_WebRIVAHandler::c2WSockErr_LoginFailed);
return;
}
// Now we need to wait to get the session state from the client
m_eCurState = EStates::WaitSessState;
}
//
// Indicate we are done
//
tCIDLib::TVoid TWebSockRIVAThread::Disconnected()
{
// Stop the 'GUI' thread
if (m_thrFauxGUIThread.bIsRunning())
{
try
{
//
// We stop this guy by setting the GUI bailout flag, not via the
// usual means, because the it can actually have been called back
// into by other threads from the action engine. This will cause
// all nested calls to it to unwind.
//
m_bGUIBailOut = kCIDLib::True;
m_thrFauxGUIThread.eWaitForDeath(10000);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadNotStopped
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::Term
, TInteger(tCIDLib::TInt4(m_eLastGUIEv))
);
}
catch(...)
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadNotStopped
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::Term
, TInteger(tCIDLib::TInt4(m_eLastGUIEv))
);
}
}
// Clear the event queue which will shut down any actions
ClearGUIEventQ();
// Clean up the view if we created it
if (m_pcivTarget)
{
try
{
delete m_pcivTarget;
m_pcivTarget = nullptr;
}
catch(TError& errToCatch)
{
if (facCQCWebSrvC().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
m_pcivTarget = nullptr;
}
}
// Clean up the graphics device if we created it
if (m_cptrRemDev.pobjData())
{
try
{
m_cptrRemDev.DropRef();
}
catch(TError& errToCatch)
{
if (facCQCWebSrvC().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
}
// Make sure we don't leave credentials around
m_cuctxClient.Reset();
}
//
// We don't use this and never register any fields. We are hosting an interface engine
// and it uses the polling engine directly.
//
tCIDLib::TVoid
TWebSockRIVAThread::FieldChanged(const TString&
, const TString&
, const tCIDLib::TBoolean
, const TCQCFldValue&)
{
}
tCIDLib::TVoid TWebSockRIVAThread::Idle()
{
// If not in ready state, do nothing
if (!bIsReady())
return;
//
// Check the time against our next update time stamps and post GUI events for any
// that are ready.
//
try
{
const tCIDLib::TEncodedTime enctNow = TTime::enctNow();
if (enctNow >= m_enctNextActive)
{
m_enctNextActive = enctNow + CQCWebSrvC_WebRIVAHandler::enctActive;
if (!m_c4TimerSuspend)
{
m_colGUIEvQ.bPutIfNew
(
new TGUIEvent(EGUIEvTypes::ActiveUpdate), TGUIEvent::bCompEvent
);
}
}
if (enctNow >= m_enctNextEvent)
{
m_enctNextEvent = enctNow + CQCWebSrvC_WebRIVAHandler::enctEvent;
if (!m_c4TimerSuspend)
{
m_colGUIEvQ.bPutIfNew
(
new TGUIEvent(EGUIEvTypes::EventUpdate), TGUIEvent::bCompEvent
);
}
}
if (enctNow >= m_enctNextVal)
{
m_enctNextVal = enctNow + CQCWebSrvC_WebRIVAHandler::enctValue;
if (!m_c4TimerSuspend)
{
m_colGUIEvQ.bPutIfNew
(
new TGUIEvent(EGUIEvTypes::ValueUpdate), TGUIEvent::bCompEvent
);
}
}
//
// And we want to give the view a chance to timeout events
// for any popups that enable timeouts.
//
if (enctNow >= m_enctNextTOCheck)
{
m_enctNextTOCheck = enctNow + CQCWebSrvC_WebRIVAHandler::enctTOCheck;
m_colGUIEvQ.bPutIfNew
(
new TGUIEvent(EGUIEvTypes::CheckTimeout), TGUIEvent::bCompEvent
);
}
}
catch(TError& errToCatch)
{
if (facCQCWebSrvC().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
}
tCIDLib::TVoid TWebSockRIVAThread::ProcessMsg(const TString& strMsg)
{
// Parse out the message as a JSON object
try
{
TTextStringInStream strmSrc(&strMsg);
TJSONValue* pjprsnRep = m_jprsIn.pjprsnParse(strmSrc);
// The reply is actually an object so cast it
TJSONObject* pjprsnMsg = static_cast<TJSONObject*>(pjprsnRep);
// Get the opcode out so we know what the rest is
const tWebRIVA::EOpCodes eOpCode = tWebRIVA::EOpCodes
(
pjprsnMsg->strValByName(kWebRIVA::strAttr_OpCode).i4Val()
);
TWebRIVATools wrtToUse;
//
// If in wait image map, we have to see an image map. Anything else is
// an error. The client has to send this immediately upon connection. If
// so, we can store that info away and then load the initial template and
// complete the connection process.
//
// If in Ready mode, we can process other types of messages.
//
// We allow proxy log server requests from the client event before the
// image map, to help debug startup issues.
//
if (eOpCode == tWebRIVA::EOpCodes::LogMsg)
{
// The client wants us to log a message on his behalf
TString strMsg;
tCIDLib::TBoolean bError;
wrtToUse.ExtractLogMsg(*pjprsnMsg, strMsg, bError);
facCQCWebSrvC().LogMsg
(
L"RIVA Client"
, 0
, kCQCWSCMsgs::midWRIVA_ClientMsg
, bError ? tCIDLib::ESeverities::Failed : tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
, m_strSessionName
, strMsg
);
}
else if (m_eCurState == EStates::WaitSessState)
{
if (eOpCode == tWebRIVA::EOpCodes::SessionState)
{
CompleteConnection(wrtToUse, *pjprsnMsg);
// We can move to ready state now
m_eCurState = EStates::Ready;
}
else
{
// Can't be right, so drop the connection
SendLoginRes(kCIDLib::False, kCQCWSCErrs::errcWRIVA_NoSessState);
StartShutdown(kCQCWebSrvC::c2WSockErr_Proto);
}
}
else
{
switch(eOpCode)
{
case tWebRIVA::EOpCodes::CancelInput :
{
TGUIEvent* pevToQ(new TGUIEvent(EGUIEvTypes::CancelInput));
m_colGUIEvQ.Add(pevToQ);
if (m_bLogInMsgs)
LogStatusMsg(L"Got cancel input", CID_LINE);
break;
}
case tWebRIVA::EOpCodes::Move :
{
TPoint pntAt;
wrtToUse.ExtractMove(*pjprsnMsg, pntAt);
TGUIEvent* pevToQ(new TGUIEvent(EGUIEvTypes::Move));
pevToQ->m_i4Val1 = pntAt.i4X();
pevToQ->m_i4Val2 = pntAt.i4Y();
m_colGUIEvQ.Add(pevToQ);
break;
}
case tWebRIVA::EOpCodes::Ping :
{
//
// Just eat it. This will update the last msg time stamp which
// is all it needs to do.
//
break;
}
case tWebRIVA::EOpCodes::Press :
{
TPoint pntAt;
wrtToUse.ExtractPress(*pjprsnMsg, pntAt);
TGUIEvent* pevToQ(new TGUIEvent(EGUIEvTypes::Press));
pevToQ->m_i4Val1 = pntAt.i4X();
pevToQ->m_i4Val2 = pntAt.i4Y();
m_colGUIEvQ.Add(pevToQ);
if (m_bLogInMsgs)
{
TString strMsg(L"Got press msg at %(1)", pntAt);
LogStatusMsg(strMsg, CID_LINE);
}
break;
}
case tWebRIVA::EOpCodes::Release :
{
TPoint pntAt;
wrtToUse.ExtractRelease(*pjprsnMsg, pntAt);
TGUIEvent* pevToQ(new TGUIEvent(EGUIEvTypes::Release));
pevToQ->m_i4Val1 = pntAt.i4X();
pevToQ->m_i4Val2 = pntAt.i4Y();
m_colGUIEvQ.Add(pevToQ);
if (m_bLogInMsgs)
{
TString strMsg(L"Got release msg at %(1)", pntAt);
LogStatusMsg(strMsg, CID_LINE);
}
break;
}
case tWebRIVA::EOpCodes::SetServerFlags :
{
tCIDLib::TCard4 c4Flags, c4Mask;
wrtToUse.ExtractSetServerFlags(*pjprsnMsg, c4Flags, c4Mask);
StoreServerFlags(c4Flags, c4Mask);
break;
}
case tWebRIVA::EOpCodes::SetVisState :
{
//
// The client has changed fgn/bgn state. Post this to the GUI
// thread to handler.
//
tCIDLib::TBoolean bState;
wrtToUse.ExtractSetVisState(*pjprsnMsg, bState);
TGUIEvent* pevToQ(new TGUIEvent(EGUIEvTypes::SetVisState));
pevToQ->m_c4Val1 = bState ? 1 : 0;
m_colGUIEvQ.Add(pevToQ);
break;
}
default :
if (m_bLogInMsgs)
{
TString strMsg(L"Unknown RIVA message: ", 10);
strMsg.AppendFormatted(TInteger(tCIDLib::i4EnumOrd(eOpCode)));
LogStatusMsg(strMsg, CID_LINE);
}
break;
};
}
}
catch(TError& errToCatch)
{
if (facCQCWebSrvC().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
catch(...)
{
}
}
tCIDLib::TVoid TWebSockRIVAThread::WSTerminate()
{
}
// ---------------------------------------------------------------------------
// TWebSockRIVAThread: Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// We clean up any entries in the GUI event queue. Any action threads
// should have already been stopped.
//
tCIDLib::TVoid TWebSockRIVAThread::ClearGUIEventQ()
{
while (!m_colGUIEvQ.bIsEmpty())
{
try
{
TGUIEvent* pgevCur = m_colGUIEvQ.pobjGetNext(0, kCIDLib::False);
if (pgevCur->m_pevNotify)
{
pgevCur->m_piceInfo->eRes = tCQCKit::ECmdRes::Stop;
pgevCur->m_pevNotify->Trigger();
}
delete pgevCur;
}
catch(...)
{
if (facCQCWebSrvC().bLogFailures())
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_CleanupErr
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, TString(L"GUI event")
, m_strSessionName
);
}
}
}
}
//
// This is called after the client connects, and we get the expected session state
// msg. At that point we can continue with the connection process. We need to set
// our image map to match his and store the passed server flags.
//
// Then we can load his default template, which will start us spitting out messages to
// him.
//
// We wil also be told if he is in a background tab. If so, we will set the background
// state flag, and that will suppress graphics/images msgs being sent until he comes
// forward. This can happen if we lose connection while he is in the background and he
// then reconnects.
//
tCIDLib::TVoid
TWebSockRIVAThread::CompleteConnection(TWebRIVATools& wrtToUse, const TJSONObject& jprsnMsg)
{
//
// First process the received image map message. If this fails, we'll log something
// but we won't give up. We'll just reset our map to empty and resend the images that
// are necessary.
//
try
{
m_rimapClient.Reset();
// There is an array named imgList. We need to get that and iterate its elements
const TJSONArray& jprsnList = *jprsnMsg.pjprsnFindArray(kWebRIVA::strAttr_List);
const tCIDLib::TCard4 c4Count = jprsnList.c4ValCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TJSONObject& jprsnImg = *jprsnList.pjprsnObjAt(c4Index);
m_rimapClient.bAddUpdate
(
jprsnImg.strValByName(kWebRIVA::strAttr_Path)
, jprsnImg.c4FindVal(kWebRIVA::strAttr_SerialNum)
);
}
// Get the server flags and mask and set those flags appropriately
const tCIDLib::TCard4 c4Flags = jprsnMsg.c4FindVal(kWebRIVA::strAttr_ToSet);
const tCIDLib::TCard4 c4Mask = jprsnMsg.c4FindVal(kWebRIVA::strAttr_Mask);
StoreServerFlags(c4Flags, c4Mask);
//
// Store the visibility state (fgn/bgn tab state), which we piggyback on the
// flags in this msg.
//
m_bClientVisState = (c4Flags & kWebRIVA::c4SrvFlag_InBgnTab) == 0;
}
catch(TError& errToCatch)
{
// Oh well, log it and reset the map
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
m_rimapClient.Reset();
}
// OK, now we can try to load the default template for our user
try
{
tCIDLib::TFloat8 f8SrvLat;
tCIDLib::TFloat8 f8SrvLong;
TCQCIntfTemplate iwdgInit;
TDataSrvClient dsclTmpl;
//
// Download the template and stream it in. For this initial query we pass
// in the caching enablement flag we got. We haven't created the view yet
// so we can't set the flag on it until we do.
//
facCQCIntfEng().QueryTemplate
(
m_uaccClient.strDefInterfaceName()
, dsclTmpl
, iwdgInit
, m_cuctxClient
, m_bEnableCaching
);
// Get the server side location info
facCQCKit().bGetLocationInfo
(
tCIDLib::ECSSides::Server, f8SrvLat, f8SrvLong, kCIDLib::True, m_cuctxClient.sectUser()
);
// For us the 'screen res' is the size of the base template
m_szDevRes = iwdgInit.areaRelative().szArea();
//
// Now create our shadow device, the size of the base template in our
// case.
//
TWebRIVAGraphDev* pgdevNew = new TWebRIVAGraphDev(m_szDevRes, this);
m_cptrRemDev.SetPointer(pgdevNew);
//
// And create our view. He gets a copy of our remote graphics device, but we
// still own it since the ref count will stay non-zero because of our counted
// pointer that we store it in.
//
m_pcivTarget = new TCQCWebRIVAView
(
iwdgInit
, L"CQC Remote Viewer"
, f8SrvLat
, f8SrvLong
, m_szDevRes
, m_cptrRemDev
, pgdevNew
, this
, this
, m_cuctxClient
, m_f8ClientLat
, m_f8ClientLong
);
// Start up the faux GUI thread, making sure the bailout flag is cleared first
m_bGUIBailOut = kCIDLib::False;
m_thrFauxGUIThread.Start();
//
// Set the caching option on it. DO this before we initialize it below, since
// that will kick off any recursive loading of overlays, so we need to have
// this set before that happens.
//
m_pcivTarget->bEnableTmplCaching(m_bEnableCaching);
// And initialize it
tCQCIntfEng::TErrList colErrs;
if (!m_pcivTarget->bInitialize(dsclTmpl, colErrs))
{
if (facCQCWebSrvC().bLogFailures())
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_FailedTmplInit
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, m_uaccClient.strDefInterfaceName()
, m_strSessionName
);
}
#if 0
facCQCRemVSrv.SendStatusReply
(
*m_psockTarget
, m_c2NextOutSeqId
, kCIDLib::False
, L"The template could not be initialized"
);
#endif
// Reset the the template so they end up with an empty window
m_pcivTarget->iwdgBaseTmpl().ResetWidget();
}
m_pcivTarget->NewSize(m_szDevRes);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
}
//
// This is the thread that simulates the GUI thread. It's started up by
// this (worker) thread after initialization is done. It simulates the
// GUI thread that would normally handle user input, and that the interface
// engine would use to implement modals loops and whatnot.
//
// So the worker thread is the 'background' thread, and this faux GUI
// thread is the 'foreground' thread, though in this case the background
// thread is really running things (acting like the OS in the real GUI
// scenario.)
//
tCIDLib::EExitCodes
TWebSockRIVAThread::eFauxGUIThread(TThread& thrThis, tCIDLib::TVoid*)
{
// Let the calling thread go
thrThis.Sync();
// TEmp debug code
m_eLastGUIEv = EGUIEvTypes::None;
try
{
//
// Now call the service loop. We'll stay there until the client
// drops the connection (in which case the worker thread that owns
// us will post us a message to that effect and we'll unwind and
// exit.
//
tCIDLib::TBoolean bBreakFlag = kCIDLib::False;
FauxGUILoop(bBreakFlag);
}
catch(TError& errToCatch)
{
if (facCQCWebSrvC().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
if (facCQCWebSrvC().bLogFailures())
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadError
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, m_strSessionName
);
}
}
catch(...)
{
if (facCQCWebSrvC().bLogFailures())
{
facCQCWebSrvC().LogMsg
(
CID_FILE
, CID_LINE
, kCQCWSCErrs::errcWRIVA_GUIThreadError
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppStatus
, m_strSessionName
);
}
}
return tCIDLib::EExitCodes::Normal;
}
//
// This is called when our faux GUI thread gets a command dispatch from the
// action engine thread. We just moved it out here to keep that method from
// getting bloated.
//
// The action engine thread will dispatch us commands if they are either
// non-standard targets (which means a widget) or standard targets that are
// marked as GUI targets (such as the interface viewer.)
//
//
// >>>>>>>>
// WE CANNOT allow any exception to propogate here, since it will propogate
// in this thread, not back to the waiting action thread.
// <<<<<<<<
//
tCIDLib::TVoid TWebSockRIVAThread::HandleGUIActDispatch(const TGUIEvent& gevCur)
{
tCQCIntfEng::TIntfCmdEv& iceToDo = *gevCur.m_piceInfo;
iceToDo.eRes = tCQCKit::ECmdRes::Ok;
try
{
// Get a ref ot he command we are to do and the target template
const TCQCCmdCfg& ccfgToDo = *iceToDo.pccfgToDo;
TCQCIntfTemplate& iwdgTmpl = m_pcivTarget->iwdgAt(iceToDo.c4HandlerId);
// Find the target widget by the id in the command
TCQCIntfWidget* piwdgTar(iwdgTmpl.piwdgFindByUID(ccfgToDo.c4TargetId(), kCIDLib::True));
// If we didn't find it, it could be the view itself
MCQCCmdTarIntf* pmctarCur = nullptr;
if (piwdgTar)
pmctarCur = dynamic_cast<MCQCCmdTarIntf*>(piwdgTar);
else if (m_pcivTarget->c4UniqueId() == ccfgToDo.c4TargetId())
pmctarCur = m_pcivTarget;
if (pmctarCur)
{
iceToDo.eRes = pmctarCur->eDoCmd
(
ccfgToDo
, iceToDo.c4StepInd
, *iceToDo.pstrUserId
, *iceToDo.pstrEventId
, *iceToDo.pctarGlobals
, iceToDo.bResult
, *iceToDo.pacteOwner
);
}
else
{
iceToDo.bTarNotFound = kCIDLib::True;
}
}
catch(const TError& errToCatch)
{
iceToDo.eRes = tCQCKit::ECmdRes::Except;
iceToDo.errFailure = errToCatch;
}
catch(...)
{
iceToDo.eRes = tCQCKit::ECmdRes::UnknownExcept;
}
//
// If we got out because of a bailout, tell the action
// thread to stop processing and exit.
//
if (m_bGUIBailOut)
iceToDo.eRes = tCQCKit::ECmdRes::Stop;
// Now wake up the background action thread what's waiting
gevCur.m_pevNotify->Trigger();
}
//
// A convenience method to log status messages. We automatically include the file name
// and the session name.
//
tCIDLib::TVoid
TWebSockRIVAThread::LogStatusMsg(const TString& strMsg, const tCIDLib::TCard4 c4Line)
{
TString strToLog(L"[", strMsg.c4Length() + m_strSessionName.c4Length() + 16);
strToLog.Append(m_strSessionName);
strToLog.Append(L"] ");
strToLog.Append(strMsg);
facCQCWebSrvC().LogMsg(CID_FILE, c4Line, strToLog, tCIDLib::ESeverities::Status);
}
tCIDLib::TVoid
TWebSockRIVAThread::LogStatusMsg(const tCIDLib::TCh* const pszMsg, const tCIDLib::TCard4 c4Line)
{
TString strToLog(L"[", TRawStr::c4StrLen(pszMsg) + m_strSessionName.c4Length() + 16);
strToLog.Append(m_strSessionName);
strToLog.Append(L"] ");
strToLog.Append(pszMsg);
facCQCWebSrvC().LogMsg(CID_FILE, c4Line, strToLog, tCIDLib::ESeverities::Status);
}
// Formats a list of key/value string pairs into a JSON object
tCIDLib::TVoid
TWebSockRIVAThread::MakeRawObject(const tCIDLib::TKVPList& colValues, TString& strToFill)
{
strToFill.Clear();
strToFill += kCIDLib::chOpenBrace;
const tCIDLib::TCard4 c4Count = colValues.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
if (c4Index)
strToFill += kCIDLib::chComma;
strToFill += kCIDLib::chQuotation;
strToFill += colValues[c4Index].strKey();
strToFill += kCIDLib::chQuotation;
strToFill += kCIDLib::chColon;
strToFill += kCIDLib::chQuotation;
strToFill += colValues[c4Index].strValue();
strToFill += kCIDLib::chQuotation;
}
strToFill += kCIDLib::chCloseBrace;
}
//
// This is called to send a login result msg to the client. The caller provides the success
// or failure indicator and a message to send with it. If successful, we also send the
// login name and user role back.
//
tCIDLib::TVoid
TWebSockRIVAThread::SendLoginRes(const tCIDLib::TBoolean bRes, tCIDLib::TMsgId midText)
{
//
// To avoid any sync requirements, we just create our own tools object. The overhead
// is not high for a very seldom sent message like this.
//
TWebRIVATools wrtToUse;
TString strName;
tWebRIVA::EUserRoles eRole = tWebRIVA::EUserRoles::Limited;
// If it was successful, get the real name and user role
if (bRes)
{
// The user role values are the same between ours and the protocol's
eRole = tWebRIVA::EUserRoles(m_uaccClient.eRole());
strName = m_uaccClient.strLoginName();
}
tCIDLib::TCard4 c4Size;
TMemBuf* pmbufMsg = wrtToUse.pmbufFormatLoginRes
(
c4Size, bRes, facCQCWebSrvC().strMsg(midText), strName, eRole
);
SendMsg(pmbufMsg, c4Size);
}
// Store away the passed server flags
tCIDLib::TVoid
TWebSockRIVAThread::StoreServerFlags(const tCIDLib::TCard4 c4Flags
, const tCIDLib::TCard4 c4Mask)
{
if (c4Mask & kWebRIVA::c4SrvFlag_NoCache)
{
// Note the reverse meanings here!
m_bEnableCaching = (c4Flags & kWebRIVA::c4SrvFlag_NoCache) == 0;
// If the view is already created, set it on that
if (m_pcivTarget)
m_pcivTarget->bEnableTmplCaching(m_bEnableCaching);
}
if (c4Mask & kWebRIVA::c4SrvFlag_LogGUIEvents)
m_bLogGUIEvents = (c4Flags & kWebRIVA::c4SrvFlag_LogGUIEvents) != 0;
if (c4Mask & kWebRIVA::c4SrvFlag_LogSrvMsgs)
m_bLogInMsgs = (c4Flags & kWebRIVA::c4SrvFlag_LogSrvMsgs) != 0;
}
| 34.034766 | 102 | 0.544378 | [
"object"
] |
5c1536dec22460b749ffebe9f81e7b86f21433ce | 15,523 | cpp | C++ | test/main.cpp | windoze/cxxstuff | 14a416ea320a6aab2d2b247630492bb01f855d81 | [
"WTFPL"
] | null | null | null | test/main.cpp | windoze/cxxstuff | 14a416ea320a6aab2d2b247630492bb01f855d81 | [
"WTFPL"
] | null | null | null | test/main.cpp | windoze/cxxstuff | 14a416ea320a6aab2d2b247630492bb01f855d81 | [
"WTFPL"
] | null | null | null | #include <assert.h>
#include <iostream>
#include <sstream>
#include <fcntl.h>
#include <vector>
#include <cxl/variant.hpp>
#include <cxl/type_traits.hpp>
#include <cxl/stdio_filebuf.hpp>
#include <cxl/str_lit.hpp>
#include <cxl/reflection.hpp>
#include <cxl/reflection/csv.hpp>
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)
#define POS __FILE__ ":" LINE_STRING
using namespace cxl;
// is_same
#if __cplusplus > 201103L
// C++14 features
static_assert(is_same<int, int>, POS);
static_assert(!is_same<int, double>, POS);
static_assert(is_same<int, int, int, int>, POS);
static_assert(!is_same<int, int, int, double>, POS);
static_assert(!is_same<int, int, double, int>, POS);
static_assert(!is_same<double, int, int, int>, POS);
// unref
static_assert(is_same<unref<int &>, int>, POS);
static_assert(is_same<unref<const int &>, int const>, POS);
static_assert(is_same<unref<int>, int>, POS);
static_assert(!is_same<unref<int *>, int>, POS);
// uncv
static_assert(is_same<uncv<int const>, int>, POS);
static_assert(is_same<uncv<const int &>, const int &>, POS);
static_assert(is_same<uncv<int>, int>, POS);
static_assert(is_same<uncv<int &>, int &>, POS);
static_assert(is_same<uncv<const int *>, const int *>, POS);
static_assert(is_same<uncv<int *const>, int *>, POS);
static_assert(is_same<uncv<const int *const>, const int *>, POS);
// unrefcv
static_assert(is_same<unrefcv<int const>, int>, POS);
static_assert(is_same<unrefcv<const int &>, int>, POS);
static_assert(is_same<unrefcv<int>, int>, POS);
static_assert(is_same<unrefcv<int>, int>, POS);
static_assert(is_same<unrefcv<const int *>, const int *>, POS);
static_assert(is_same<unrefcv<int *const>, int *>, POS);
static_assert(is_same<unrefcv<const int *const>, const int *>, POS);
// add_lref
static_assert(is_same<add_lref<int>, int &>, POS);
static_assert(is_same<add_lref<int &>, int &>, POS);
static_assert(is_same<add_lref<const int>, int const &>, POS);
static_assert(is_same<add_lref<const int *>, int const *&>, POS);
// add_rref
static_assert(is_same<add_rref<int>, int &&>, POS);
static_assert(is_same<add_rref<int &>, int &>, POS); // (int&)&& = int&
static_assert(is_same<add_rref<const int>, int const &&>, POS);
static_assert(is_same<add_rref<const int *>, int const *&&>, POS);
// add_const
static_assert(is_same<add_const<int>, int const>, POS);
static_assert(is_same<add_const<const int>, int const>, POS);
// add_volatile
static_assert(is_same<add_volatile<int>, int volatile>, POS);
static_assert(is_same<add_volatile<volatile int>, int volatile>, POS);
// is_ref
static_assert(is_ref<int &>, POS);
static_assert(is_ref<int &&>, POS);
static_assert(is_ref<const int &>, POS);
static_assert(!is_ref<int>, POS);
static_assert(!is_ref<int *>, POS);
// contained
static_assert(contained<int, int, double>, POS);
static_assert(!contained<char, int, double>, POS);
// dedup tuple
typedef std::tuple<int, int, double> t3;
static_assert(is_same<dedup<t3>::type, std::tuple<int, double>>, POS);
// dedup variant
static_assert(is_same<deduped_variant<int, int, double>, variant<int, double>>, POS);
static_assert(is_same<deduped_variant<int, double>, variant<int, double>>, POS);
static_assert(is_same<deduped_variant<int, int, double, double>, variant<int, double>>, POS);
static_assert(is_same<deduped_variant<int, int, double, double, int, int>, variant<double, int>>,
POS);
// type_index
static_assert(is_same<std::tuple_element<typeindex<int, std::tuple<char, int, double>>,
std::tuple<char, int, double>>::type,
int>,
POS);
#else
// C++11 version
static_assert(is_same_t<int, int>::value, POS);
static_assert(!is_same_t<int, double>::value, POS);
static_assert(is_same_t<int, int, int, int>::value, POS);
static_assert(!is_same_t<int, int, int, double>::value, POS);
static_assert(!is_same_t<int, int, double, int>::value, POS);
static_assert(!is_same_t<double, int, int, int>::value, POS);
// unref
static_assert(is_same_t<unref<int&>, int>::value, POS);
static_assert(is_same_t<unref<const int&>, int const>::value, POS);
static_assert(is_same_t<unref<int>, int>::value, POS);
static_assert(!is_same_t<unref<int*>, int>::value, POS);
// uncv
static_assert(is_same_t<uncv<int const>, int>::value, POS);
static_assert(is_same_t<uncv<const int&>, const int&>::value, POS);
static_assert(is_same_t<uncv<int>, int>::value, POS);
static_assert(is_same_t<uncv<int&>, int&>::value, POS);
static_assert(is_same_t<uncv<const int*>, const int*>::value, POS);
static_assert(is_same_t<uncv<int* const>, int*>::value, POS);
static_assert(is_same_t<uncv<const int* const>, const int*>::value, POS);
// unrefcv
static_assert(is_same_t<unrefcv<int const>, int>::value, POS);
static_assert(is_same_t<unrefcv<const int&>, int>::value, POS);
static_assert(is_same_t<unrefcv<int>, int>::value, POS);
static_assert(is_same_t<unrefcv<int>, int>::value, POS);
static_assert(is_same_t<unrefcv<const int*>, const int*>::value, POS);
static_assert(is_same_t<unrefcv<int* const>, int*>::value, POS);
static_assert(is_same_t<unrefcv<const int* const>, const int*>::value, POS);
// add_lref
static_assert(is_same_t<add_lref<int>, int&>::value, POS);
static_assert(is_same_t<add_lref<int&>, int&>::value, POS);
static_assert(is_same_t<add_lref<const int>, int const&>::value, POS);
static_assert(is_same_t<add_lref<const int*>, int const*&>::value, POS);
// add_rref
static_assert(is_same_t<add_rref<int>, int&&>::value, POS);
static_assert(is_same_t<add_rref<int&>, int&>::value, POS); // (int&)&& = int&
static_assert(is_same_t<add_rref<const int>, int const&&>::value, POS);
static_assert(is_same_t<add_rref<const int*>, int const*&&>::value, POS);
// add_const
static_assert(is_same_t<add_const<int>, int const>::value, POS);
static_assert(is_same_t<add_const<const int>, int const>::value, POS);
// add_volatile
static_assert(is_same_t<add_volatile<int>, int volatile>::value, POS);
static_assert(is_same_t<add_volatile<volatile int>, int volatile>::value, POS);
// contained
static_assert(contained_t<int, int, double>::value, POS);
static_assert(!contained_t<char, int, double>::value, POS);
// dedup tuple
typedef std::tuple<int, int, double> t3;
static_assert(is_same_t<dedup<t3>::type, std::tuple<int, double>>::value, POS);
// dedup variant
static_assert(is_same_t<deduped_variant<int, int, double>, variant<int, double>>::value, POS);
static_assert(is_same_t<deduped_variant<int, double>, variant<int, double>>::value, POS);
static_assert(is_same_t<deduped_variant<int, int, double, double>, variant<int, double>>::value,
POS);
static_assert(
is_same_t<deduped_variant<int, int, double, double, int, int>, variant<double, int>>::value,
POS);
// type_index
static_assert(is_same_t<std::tuple_element<type_index<int, std::tuple<char, int, double>>::value,
std::tuple<char, int, double>>::type,
int>::value,
POS);
#endif
void test_variant()
{
variant<int, std::string> v(10);
int n = get<int>(v);
assert(n == 10);
try {
variant<int, std::string> v1("xyz");
get<int>(v1); // bad_get
assert(false);
} catch (bad_get &) {
assert(true);
}
}
void test_recursive_variant()
{
struct node;
typedef variant<std::nullptr_t, int, recursive_wrapper<node>> node_data;
struct node
{
node_data left;
node_data right;
} t;
t.left = 5;
t.right = node{10, 20};
assert(t.left.get<int>() == 5);
assert(t.right.get<node>().right.get<int>() == 20);
}
void test_move()
{
typedef variant<std::string, int> vt;
vt v("hello");
vt v1 = std::move(v);
assert(v1.get<std::string>() == "hello");
assert(v1.which() == 0);
assert(v.which() == 0);
// std::move clears std::string
assert(v.get<std::string>().empty());
vt v2 = 100;
vt v3 = std::move(v2);
assert(v3.get<int>() == 100);
assert(v2.which() == 1);
// std::move doesn't clear int
assert(v2.get<int>() == 100);
}
void test_visitor()
{
typedef variant<int, double> vt;
struct visitor
{
std::string operator()(int x) && { return "int"; }
std::string operator()(double x) && { return "double"; }
};
vt v(5.5);
assert(v.apply_visitor(visitor()) == "double");
}
void test_print()
{
typedef variant<int, std::string> vt;
{
vt v(100);
std::stringstream ss;
ss << v;
assert(ss.str() == "100");
}
{
vt v("hello");
std::stringstream ss;
ss << v;
assert(ss.str() == "hello");
}
}
struct iarchive
{
iarchive(std::istream &is) : is_(is) { }
template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value, iarchive &>::type operator>>(T &n)
{
is_.read((char *) (&n), sizeof(n));
return *this;
}
std::istream &is_;
};
struct oarchive
{
oarchive(std::ostream &os) : os_(os) { }
template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value, oarchive &>::type operator<<(const T &n)
{
os_.write((const char *) (&n), sizeof(n));
return *this;
}
std::ostream &os_;
};
void test_io()
{
typedef variant<int, double> vt;
vt v(5.5);
std::stringstream ss;
oarchive oa(ss);
write(oa, v);
vt v1;
iarchive ia(ss);
read(ia, v1);
assert(v == v1);
assert(v1.get<double>() == 5.5);
}
void test_filebuf()
{
int fd = open("/tmp/x", O_CREAT | O_RDWR, 0644);
stdio_filebuf<char> *fb = new stdio_filebuf<char>;
fb->open(fd, std::ios::in | std::ios::out);
std::iostream s(fb);
s << "abc" << std::endl;
}
#include "main.hpp"
struct visitor
{
visitor(std::ostream &s) : os(s) { }
template<typename T>
void operator()(const T &t) const
{
os << t << std::endl;
}
std::ostream &os;
};
void test_reflected()
{
S s{420, 4.2, "hello", {4200}};
static_assert(cxl::tuple_size<S>::value == 4, POS);
static_assert(std::is_same<double, cxl::tuple_element<1, S>::type>::value, POS);
static_assert(
std::is_same<const double, cxl::reflection::reflected_element<1, const S>::type>::value,
POS);
static_assert(std::is_same<const double, cxl::tuple_element<1, const S>::type>::value,
POS);
static_assert(!std::is_const<cxl::reflection::reflected_element_type<1, S>>::value, POS);
// Test cxl::reflection::set
try {
// This will succeed
cxl::set("m1", s, 210);
// This will fail, incompatible type, double and string literal
cxl::set(1, s, "210");
assert(false);
} catch (cxl::bad_get &) {
}
assert(s.m1 == 210);
try {
// This will fail, index out of range
cxl::reflection::set(10, s, 55);
assert(false);
} catch (std::out_of_range &) {
}
try {
// This will succeed
cxl::set("MM3", s, std::string("world"));
// This will fail, unknown key
cxl::set("unknown key", s, 55);
assert(false);
} catch (std::out_of_range &) {
}
assert(s.m3 == std::string("world"));
// Custom attribute
assert(std::string(cxl::get_element_sql_field<S>(0)) == "m1"); // Fallback to name()
assert(std::string(cxl::get_element_sql_field<S>(1)) == "field2");
assert(std::string(cxl::get_element_xml_namespace<S>(0)).empty());
assert(std::string(cxl::get_element_xml_namespace<S>(1)) == "somens");
assert(std::string(cxl::get_element_json_key<S>(2)) == "MM3"); // Fallback to key()
assert(std::string(cxl::get_element_xml_node<S>(3)) == "m4");
// Test std::get
std::get<2>(s) = "hello, world";
assert(s.m3 == std::string("hello, world"));
// Test cxl::get
assert(cxl::get<std::string>(2, s) == std::string("hello, world"));
// Access field names
std::string names;
for (size_t i = 0; i < cxl::tuple_size<S>::value; i++) {
if (!names.empty()) names += ",";
names += get_element_name<S>(i);
}
assert(names == "m1,m2,m3,m4");
// Toy SQL generator
std::string keys;
for (size_t i = 0; i < cxl::tuple_size<S>::value; i++) {
if (!keys.empty()) keys += ", ";
keys += get_element_sql_field<S>(i);
}
keys = "SELECT " + keys + " FROM " + cxl::get_sql_table<S>() + " WHERE "
+ cxl::get_element_sql_field<S>(0) + "=?";
assert(keys == "SELECT m1, field2, MM3, m4 FROM some_table WHERE m1=?");
// Test with std::tuple
auto st = std::make_tuple(10, 5.4, 100, 200);
static_assert(std::is_same<cxl::tuple_element<0, decltype(st)>::type, int>::value, POS);
assert(cxl::get<int>(0, st) == 10);
// Test with std::pair
auto p = std::make_pair("xyz", 74);
static_assert(std::is_same<cxl::tuple_element<1, decltype(p)>::type, int>::value, POS);
assert(cxl::get<int>(1, p) == 74);
assert(cxl::get<int>("second", p) == 74);
assert(std::string(cxl::get<const char *>("first", p)) == "xyz");
cxl::set(1, p, 5);
assert(std::get<1>(p) == 5);
assert(cxl::get<int>("second", p) == 5);
// Test with std::pair with const member
typedef std::pair<const int, int> cp_t;
typedef cxl::to_variant_t<cp_t> vcp_t;
static_assert(std::is_same<cxl::variant<int>, vcp_t>::value, POS);
typedef std::pair<const int, int> cp_t;
cp_t cp(42, 420);
assert(cxl::get<int>(0, cp) == 42);
try {
// Should fail, cannot set a const field
cxl::set(0, cp, 21);
assert(false);
} catch (std::bad_cast &) {
}
assert(cxl::get<int>(1, cp) == 420);
cxl::set(1, cp, 100);
static_assert(cxl::reflectable<cp_t>, POS);
static_assert(
std::is_same<const int, cxl::reflection::reflected_element<0, cp_t>::type>::value, POS);
static_assert(std::is_same<const int, std::tuple_element<0, cp_t>::type>::value, POS);
assert(cxl::get<int>(0, cp) == 42);
assert(cxl::get<int>(1, cp) == 100);
assert(std::get<1>(cp) == 100);
std::get<1>(cp) = 1420;
assert(std::get<1>(cp) == 1420);
// struct with const field
SC sc{10, 5.5, 84};
cxl::set(0, sc, 42);
assert(sc.m1 == 42);
try {
// Should fail, cannot set a const field
cxl::set(1, sc, 7.5);
assert(false);
} catch (std::bad_cast &) {
}
cxl::set("m3", sc, 168);
assert(cxl::get<int>(2, sc) == 168);
assert(cxl::get<int>(3, sc) == 100);
assert(std::get<3>(sc) == 100);
std::stringstream ss;
visitor v(ss);
cxl::for_each_element(sc, v);
assert(ss.str() == "42\n"
"5.5\n"
"168\n"
"100\n");
}
void test_csv()
{
std::vector<SC> vsc;
vsc.push_back(SC{10, 5.5, 84});
vsc.push_back(SC{20, 15.5, 284});
vsc.push_back(SC{30, 25.5, 384});
vsc.push_back(SC{40, 35.5, 484});
std::stringstream ss;
std::ostream_iterator<char> oi(ss);
cxl::reflection::csv::write_csv(vsc.begin(), vsc.end(), oi);
assert(ss.str() == "\"m1\",\"m2\",\"m3\",\"m4\"\n"
"10,5.500000,84,100\n"
"20,15.500000,284,100\n"
"30,25.500000,384,100\n"
"40,35.500000,484,100\n");
}
int main()
{
test_variant();
test_recursive_variant();
test_move();
test_visitor();
test_print();
test_io();
test_filebuf();
test_reflected();
test_csv();
return 0;
}
| 31.679592 | 100 | 0.624042 | [
"vector"
] |
5c1a757254cc1b232d3c7ea8d04ccde530ca854d | 5,639 | hpp | C++ | src/parser.hpp | bsurmanski/wlc | e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629 | [
"MIT"
] | 4 | 2015-02-13T01:14:23.000Z | 2019-06-29T19:25:49.000Z | src/parser.hpp | bsurmanski/wlc | e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629 | [
"MIT"
] | null | null | null | src/parser.hpp | bsurmanski/wlc | e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629 | [
"MIT"
] | null | null | null |
#ifndef _PARSER_HPP
#define _PARSER_HPP
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Module.h>
#include "lexer.hpp"
#include "ast.hpp"
#include "astScope.hpp"
#include "sourceLocation.hpp"
#include "file.hpp"
#include <deque>
#include <vector>
#include <map>
#include <stack>
// wait, this doesn't really do anything anymore. all the parsing in ParseContext
class Parser
{
AST *ast;
public:
Parser() { ast = new AST(); }
void parseFile(ModuleDeclaration *mod, File *file, SourceLocation l = SourceLocation());
void parseString(const char *str);
AST *getAST() { return ast; }
protected:
};
/**
* parsing is pretty strange in WLC. The strangest parts revolve around identifiers.
* identifiers are user defined names, used as variable names, function names, and
* struct names. In WL, global variables need not be defined before use. So, for example
* a function can be declared below it's usage. This has some strange side effects for parsing.
* When encountering an identifier, we often don't know whether it is a variable, function,
* struct, or simply undefined. This complicates determining expressions from declarations.
* The way I have solved it, is to treat unknown identifiers as declarations, and traceback
* if it turns out I am wrong
*/
class ParseContext
{
Lexer *lexer;
Parser *parser;
PackageDeclaration *package;
ModuleDeclaration *module;
std::stack<ASTScope*> scope;
//std::stack<Lexer*> lexers;
public:
ParseContext(Lexer *lex, Parser *parse, PackageDeclaration *p) : lexer(lex), parser(parse),
package(p) {}
~ParseContext() { }
AST *getAST() { return parser->getAST(); }
protected:
std::deque<int> recoveryState; // tokens left over in rqueue after current recover
std::deque<Token> rqueue; // recovery queue
std::deque<Token> tqueue; // token lookahead queue
void ignoreComments() {
while(lexer->peek().is(tok::comment))
lexer->ignore();
}
//void push() { tqueue.push(getBuffer()); }
Token get() {
Token t;
if(!tqueue.empty()){
t = tqueue.front();
tqueue.pop_front();
} else {
ignoreComments();
t = lexer->get();
}
if(recoveryState.size()) rqueue.push_back(t);
return t;
}
Token linePeek() { Token t = peek(); if(!t.followsNewline()) return t; return Token(tok::semicolon); }
Token peek() {
if(!tqueue.empty()) return tqueue.front();
ignoreComments();
return lexer->peek();
}
void ignore() { get(); }
void dropLine() { // dumps entire line of input given an error (if line ends in binop, dump that too)
//bool binOp = false;
//while(!peek().followsNewline() && !binOp) {
// binOp = peek().isBinaryOp();
// ignore();
//}
}
Token lookAhead(int i = 0) { // lookAhead(0) is equivilent to peek()
while(tqueue.size() < i+1) {
ignoreComments();
tqueue.push_back(lexer->get());
}
return tqueue.at(i);
}
//Token getBuffer() { ignoreComments(); return lexer->get(); }
//Token peekBuffer() { ignoreComments(); return lexer->peek(); }
//void ignoreBuffer() { ignoreComments(); lexer->ignore(); }
//void unGet(Token tok) { lexer->unGet(tok); }
bool eof() { return tqueue.empty() && lexer->eof(); }
PackageDeclaration *currentPackage() { return package; }
ModuleDeclaration *getModule() { return module; }
void pushScope(ASTScope* tbl) { scope.push(tbl); }
ASTScope *popScope() { ASTScope *tbl = scope.top(); scope.pop(); return tbl;}
ASTScope *getScope() { if(!scope.empty()) return scope.top(); return NULL; }
//void pushLexer(Lexer *l) { lexers.push(l); }
//Lexer *popLexer() { Lexer *lx = lexers.top(); lexers.pop(); return lx; }
//Lexer *getLexer() { if(!lexers.empty()) return lexer.top(); return NULL; }
public:
void parseModule(ModuleDeclaration *u);
void parseTopLevel(ModuleDeclaration *unit);
void pushRecover();
void popRecover();
void recover();
ASTType *parseBasicType();
ASTType *parseScalarType(); //scalar type is anything but pointer/array. this includes struct and tuples
ASTType *parsePointerModifiedType(ASTType *base);
ASTType *parseArrayModifiedType(ASTType *base);
ASTType *parseFunctionModifiedType(ASTType *base); //where base is the return-type
ASTType *parseModifiedType(ASTType *base);
ASTType *parseType();
void parseInclude();
ImportExpression *parseImport();
Statement *parseStatement();
CaseStatement *parseCaseStatement();
Statement *parseIfStatement();
Statement *parseSwitchStatement();
Statement *parseWhileStatement();
Statement *parseForStatement();
Statement *parseCompoundStatement();
DeclarationQualifier parseDeclarationQualifier();
Declaration *parseDeclaration();
TopLevelExpression *parseTopLevelExpression();
UseExpression *parseUseExpression();
Expression *parseCastExpression(int prec = 0);
Expression *parseExpression(int prec = 0);
Expression *parseNewExpression();
Expression *parseIdOpExpression();
Expression *parseIdentifierExpression();
Expression *parsePrimaryExpression();
void parseArgumentList(std::list<Expression*> &args);
Expression *parsePostfixExpression(int prec = 0);
Expression *parseUnaryExpression(int prec = 0);
Expression *parseBinaryExpression(int prec = 0);
Expression *parseTupleExpression();
};
#endif
| 34.384146 | 108 | 0.656322 | [
"vector"
] |
5c234cc04ef11f5998e1108d177775cef09c0fe5 | 1,863 | inl | C++ | include/impl/Game.inl | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | null | null | null | include/impl/Game.inl | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | null | null | null | include/impl/Game.inl | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | 1 | 2021-10-13T14:25:11.000Z | 2021-10-13T14:25:11.000Z |
template<typename Impl>
void Game::run(const char* parentObject)
{
auto initInstance = []()
{
m_instance->onStart();
m_instance->initUpdate();
if(Config.UseSimpleInput)
{
event::Keyboard::Down::subscribe(std::bind(&IGame::onKey, m_instance->m_impl, std::placeholders::_1));
event::Touch::Begin::subscribe(std::bind(&IGame::onTouch, m_instance->m_impl, std::placeholders::_1));
}
};
if(!m_instance)
{
using namespace std::placeholders;
m_instance = sptr<Game>(new Game(sptr<IGame>(new Impl()), parentObject));
event::Resize::subscribe([](auto& evt)
{
m_instance->m_impl->onResize(evt.size);
Render::resize(evt.size);
});
utils::InitW4Lib();
core::Timer::init();
m_instance->onConfig();
Render::init(Config.RSettings);
Config.log();
if (Config.UseDefaultRenderPass)
{
W4_LOG_INFO("Using default render pass, create default root node ...");
auto id = Render::addPass();
Render::getPass(id)->setEnabled(true);
Render::getPass(id)->setRoot(make::sptr<render::RootNode>());
}
event::Resize::fire(platform::Platform::getSize());
event::Event::performEmitAll();
platform::Platform::showLoader();
if(Config.VFSInit)
{
W4_LOG_INFO("Init VFS ...");
auto& vfs = filesystem::VFS::instance();
auto vfsInit = [&]
{
auto vfsInitCb = [&]
{
initInstance();
};
vfs.init(vfsInitCb);
};
Config.VFSClean ? vfs.clean(vfsInit) : vfsInit();
}
else
{
initInstance();
}
}
}
| 26.614286 | 114 | 0.513151 | [
"render"
] |
5c366d4277030335b0ec6b28de153c49d55dd94c | 1,264 | hpp | C++ | src/ordered_bounded_queue.hpp | whackashoe/kar | 71ab11cd4774e3aa3abeb1df019c4a7994994814 | [
"MIT"
] | null | null | null | src/ordered_bounded_queue.hpp | whackashoe/kar | 71ab11cd4774e3aa3abeb1df019c4a7994994814 | [
"MIT"
] | null | null | null | src/ordered_bounded_queue.hpp | whackashoe/kar | 71ab11cd4774e3aa3abeb1df019c4a7994994814 | [
"MIT"
] | null | null | null | #ifndef KAR_ORDERED_BOUNDED_QUEUE_HPP
#define KAR_ORDERED_BOUNDED_QUEUE_HPP
#include <vector>
#include <limits>
#include <utility>
namespace kar
{
template <typename Comp, typename T>
struct ordered_bounded_queue
{
std::vector<std::pair<Comp, T>> data;
Comp min;
Comp max;
Comp size;
ordered_bounded_queue(Comp size)
: min(std::numeric_limits<Comp>::max())
, max(std::numeric_limits<Comp>::max())
, size(size)
{}
void push(const Comp distance, const T & s)
{
if(data.size() < size || distance < max) {
if(data.size() == 0) {
data.push_back(std::make_pair(distance, s));
min = distance;
max = distance;
} else {
for(auto it = data.begin(); it != data.end(); ++it) {
if(distance <= (*it).first) {
data.insert(it, std::make_pair(distance, T(std::begin(s) + 1, std::end(s))));
break;
}
}
if(data.size() > size) {
data.pop_back();
}
min = data[0].first;
max = data[data.size() - 1].first;
}
}
}
};
}
#endif
| 22.981818 | 101 | 0.482595 | [
"vector"
] |
5c4560b15300ba17be9f35f74ac23e98a1ab6f9d | 2,581 | cpp | C++ | src/RotateObjectRelativeAction.cpp | rGovers/KurveM | 9b59093d91701e6f721facca75e350e62500b246 | [
"MIT"
] | null | null | null | src/RotateObjectRelativeAction.cpp | rGovers/KurveM | 9b59093d91701e6f721facca75e350e62500b246 | [
"MIT"
] | null | null | null | src/RotateObjectRelativeAction.cpp | rGovers/KurveM | 9b59093d91701e6f721facca75e350e62500b246 | [
"MIT"
] | null | null | null | #include "Actions/RotateObjectRelativeAction.h"
#include <glm/gtx/quaternion.hpp>
#include "Object.h"
#include "Transform.h"
RotateObjectRelativeAction::RotateObjectRelativeAction(const glm::vec3& a_startPos, const glm::vec3& a_axis, Object* a_object) :
RotateObjectRelativeAction(a_startPos, a_axis, &a_object, 1U)
{
}
RotateObjectRelativeAction::RotateObjectRelativeAction(const glm::vec3& a_startPos, const glm::vec3& a_axis, Object* const* a_object, unsigned int a_objectCount)
{
m_objectCount = a_objectCount;
m_axis = a_axis;
m_objects = new Object*[m_objectCount];
m_oldRotations = new glm::quat[m_objectCount];
m_oldPositions = new glm::vec3[m_objectCount];
m_centre = glm::vec3(0);
m_startPos = a_startPos;
m_endPos = a_startPos;
for (unsigned int i = 0; i < m_objectCount; ++i)
{
Object* obj = a_object[i];
m_objects[i] = obj;
const Transform* transform = obj->GetTransform();
const glm::vec3 pos = transform->Translation();
m_oldRotations[i] = transform->Quaternion();
m_oldPositions[i] = pos;
m_centre += pos;
}
m_centre /= m_objectCount;
}
RotateObjectRelativeAction::~RotateObjectRelativeAction()
{
delete[] m_oldRotations;
delete[] m_oldPositions;
delete[] m_objects;
}
e_ActionType RotateObjectRelativeAction::GetActionType()
{
return ActionType_RotateObjectRelative;
}
bool RotateObjectRelativeAction::Redo()
{
return Execute();
}
bool RotateObjectRelativeAction::Execute()
{
const glm::vec3 endAxis = m_endPos - m_startPos;
const float len = glm::length(endAxis);
if (len > 0)
{
const glm::vec3 inv = glm::vec3(1) - m_axis;
const glm::vec3 scaledAxis = inv * len;
const float scale = glm::dot(scaledAxis, endAxis) * 10;
const glm::quat q = glm::angleAxis(scale, m_axis);
for (unsigned int i = 0; i < m_objectCount; ++i)
{
const glm::vec3 diff = m_oldPositions[i] - m_centre;
Transform* transform = m_objects[i]->GetTransform();
// transform->Translation() = m_centre + (q * diff);
transform->Quaternion() = q * m_oldRotations[i];
}
}
return true;
}
bool RotateObjectRelativeAction::Revert()
{
for (unsigned int i = 0; i < m_objectCount; ++i)
{
Transform* transform = m_objects[i]->GetTransform();
transform->Quaternion() = m_oldRotations[i];
transform->Translation() = m_oldPositions[i];
}
return true;
} | 25.058252 | 161 | 0.645099 | [
"object",
"transform"
] |
5c51b2798c56b30fd46a54147402ca27627820c8 | 689 | cpp | C++ | Recursion & Backtracking/GetSubsequence.cpp | kashika0112/DataStructuresProblems | 85ee6e4ed19ce6e3fcc7d9246561fe7580f5c1fe | [
"MIT"
] | null | null | null | Recursion & Backtracking/GetSubsequence.cpp | kashika0112/DataStructuresProblems | 85ee6e4ed19ce6e3fcc7d9246561fe7580f5c1fe | [
"MIT"
] | null | null | null | Recursion & Backtracking/GetSubsequence.cpp | kashika0112/DataStructuresProblems | 85ee6e4ed19ce6e3fcc7d9246561fe7580f5c1fe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<string> getSubsequence(string str)
{
if(str.length()==0)
{
vector<string> res;
res.push_back("");
return res;
}
char ch = str.at(0);
string ros = str.substr(1);
vector<string> rres = getSubsequence(ros);
vector<string> myres;
for(string rstr : rres)
{
myres.push_back("" + rstr);
}
for(string rstr : rres)
{
myres.push_back(ch + rstr);
}
return myres;
}
int main()
{
string s = "abc";
vector<string> result=getSubsequence(s);
cout<<"[";
for(int i=0;i<result.size();i++)
{
cout<<result[i];
if(i!=result.size()-1)
cout<<",";
}
cout<<"]"<<endl;
return 0;
}
//Output
// [,c,b,bc,a,ac,ab,abc]
| 13.78 | 43 | 0.603774 | [
"vector"
] |
5c576ffce915e92a050afe4b9b98b5c4fec4a113 | 12,035 | cpp | C++ | src/LanguageBase/Variable_float.cpp | karlkrissian/amilab_engine | a361884e30bf3a92343319e70395fcaccb7abdde | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/LanguageBase/Variable_float.cpp | karlkrissian/amilab_engine | a361884e30bf3a92343319e70395fcaccb7abdde | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2016-08-11T09:50:37.000Z | 2016-08-11T14:02:46.000Z | src/LanguageBase/Variable_float.cpp | karlkrissian/amilab_engine | a361884e30bf3a92343319e70395fcaccb7abdde | [
"BSD-2-Clause-FreeBSD"
] | null | null | null |
#include <iomanip>
#include <cassert>
#include "boost/format.hpp"
#include "amilab_messages.h"
#include "DefineClass.hpp"
#include "Variable.hpp"
#include <math.h>
#include <iostream>
#define NEW_SMARTPTR(type, var, value) \
boost::shared_ptr<type> var(new type(value));
#define RETURN_VARPTR(type, value) \
boost::shared_ptr<type> newval(new type(value)); \
return Variable<type>::ptr( new Variable<type>(newval));
#include <boost/numeric/conversion/cast.hpp>
std::vector<std::string> AMILabType<float>::conversion_types =
{ "bool", "double",
"long", "int", "short",
"unsigned long", "unsigned short",
"unsigned char" };
//------------------------------------------------------
//------- Variable<float>
//------------------------------------------------------
/// Copy contents to new variable
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::NewCopy() const
{
float_ptr newval( new float(Value()));
Variable<float>::ptr newvar(new Variable<float>(newval));
return newvar;
}
// Arithmetic operators
/// +a
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +()
{ RETURN_VARPTR(float,Value());}
/// prefix ++ operator ++a
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ++()
{
//std::cout << "**" << std::endl;
RETURN_VARPTR(float,++RefValue());
}
/// postfix ++ operator a++
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ++(int)
{
//std::cout << "**" << std::endl;
RETURN_VARPTR(float,RefValue()++);
}
/// -a
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -()
{ RETURN_VARPTR(float,-Value());}
/// prefix -- operator --a
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator --()
{ RETURN_VARPTR(float,--RefValue()); }
/// postfix -- operator a--
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator --(int)
{ RETURN_VARPTR(float,RefValue()--); }
/// a+b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(float,Value()+b->GetValueAsDouble());
}
else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a+=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator +=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() += b->GetValueAsDouble();
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a-b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(float,Value()-b->GetValueAsDouble());
}
else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a-=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator -=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() -= b->GetValueAsDouble();
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a*b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator *(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(float,Value()*b->GetValueAsDouble());
}
else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a*=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator *=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() *= b->GetValueAsDouble();
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a/b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator /(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(float,Value()/b->GetValueAsDouble());
}
else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a/=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator /=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() /= b->GetValueAsDouble();
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a%b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator %(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(float, ((int) round(Value())) % ((int) round(b->GetValueAsDouble())));
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a%=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator %=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() = ((int) round(Value())) % ((int) round(b->GetValueAsDouble()));
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
// Comparison Operators
/// a<b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator <(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()<b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a<=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator <=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()<=b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a>b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator >(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()>b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a>=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator >=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()>=b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a!=b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator !=(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()!=b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
/// a==b
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ==(const BasicVariable::ptr& b)
{
//std::cout << __func__ << std::endl;
if (b->IsNumeric()) {
RETURN_VARPTR(bool,Value()==b->GetValueAsDouble());
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
// Logical operators
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator !()
{
RETURN_VARPTR(bool,!(Value()>0.5));
}
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator &&(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,(Value()>0.5)&& (bool) (b->GetValueAsDouble()>0.5));
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::operator ||(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RETURN_VARPTR(bool,(Value()>0.5) || (bool) (b->GetValueAsDouble()>0.5));
} else
CLASS_ERROR("operation not defined");
return this->NewReference();
}
// Mathematical functions
#define VAR_IMPL_FUNC(type,fname,func) \
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<type>::m_##fname() \
{ \
RETURN_VARPTR(float, func(Value())); \
}
VAR_IMPL_FUNC(float, sin, sin)
VAR_IMPL_FUNC(float, cos, cos)
VAR_IMPL_FUNC(float, tan, tan)
VAR_IMPL_FUNC(float, asin, asin)
VAR_IMPL_FUNC(float, acos, acos)
VAR_IMPL_FUNC(float, atan, atan)
VAR_IMPL_FUNC(float, fabs, fabs)
VAR_IMPL_FUNC(float, round,round)
VAR_IMPL_FUNC(float, floor,floor)
VAR_IMPL_FUNC(float, exp, exp)
VAR_IMPL_FUNC(float, log, 1.0/log(10.0)*log)
VAR_IMPL_FUNC(float, ln, log)
VAR_IMPL_FUNC(float, norm, fabs)
VAR_IMPL_FUNC(float, sqrt, sqrt)
//VAR_IMPL_FUNC(float, pow, pow)
//---------------------------------------------------
template<> AMI_DLLEXPORT
BasicVariable::ptr Variable<float>::TryCast(
const std::string& type_string) const
{
try
{
// cast to double
if (type_string==AMILabType<double>::name_as_string()) {
RETURN_VARPTR(double, boost::numeric_cast<double>(Value()));
} else
// cast to int
if (type_string==AMILabType<int>::name_as_string()) {
RETURN_VARPTR(int, boost::numeric_cast<int>(Value()));
} else
// cast to long
if (type_string==AMILabType<long>::name_as_string()) {
RETURN_VARPTR(long, boost::numeric_cast<long>(Value()));
} else
// cast to unsigned long
if (type_string==AMILabType<unsigned long>::name_as_string()) {
RETURN_VARPTR(unsigned long, boost::numeric_cast<unsigned long>(Value()));
} else
// cast to short
if (type_string==AMILabType<short>::name_as_string()) {
RETURN_VARPTR(short, boost::numeric_cast<short>(Value()));
} else
// cast to unsigned short
if (type_string==AMILabType<unsigned short>::name_as_string()) {
RETURN_VARPTR(unsigned short, boost::numeric_cast<unsigned short>(Value()));
} else
// cast to unsigned char
if (type_string==AMILabType<unsigned char>::name_as_string()) {
RETURN_VARPTR(unsigned char, boost::numeric_cast<unsigned char>(Value()));
} else
// cast to bool
if (type_string==AMILabType<bool>::name_as_string()) {
RETURN_VARPTR(bool, boost::numeric_cast<bool>(Value()));
} else
{
// make default conversion to double??
CLASS_ERROR((boost::format("No conversion available for variable %1% from float to %2%") % _name % type_string).str().c_str());
}
} catch (std::bad_cast &e)
{
CLASS_ERROR((boost::format("%1%, for variable %2% from float to %3%") % e.what() % _name % type_string).str().c_str());
return BasicVariable::ptr();
}
return BasicVariable::ptr();
}
//
template<> AMI_DLLEXPORT BasicVariable::ptr Variable<float>::BasicCast(const int& type)
{
#define NUMCAST(amitype,type) \
case amitype: { RETURN_VARPTR(type, boost::numeric_cast<type>(Value())); }
try
{
switch((WORDTYPE)type) {
NUMCAST( WT_UNSIGNED_CHAR, unsigned char )
NUMCAST( WT_SIGNED_SHORT, short )
NUMCAST( WT_UNSIGNED_SHORT, unsigned short)
NUMCAST( WT_SIGNED_INT, int )
NUMCAST( WT_SIGNED_LONG, long )
NUMCAST( WT_FLOAT, float )
NUMCAST( WT_DOUBLE, double )
case WT_UNSIGNED_INT: { RETURN_VARPTR(float, (unsigned int) Value()); }
default:
CLASS_ERROR(( boost::format("Conversion to type %1% not available")%((WORDTYPE)type)).str().c_str());
}
} catch (std::bad_cast &e)
{
CLASS_ERROR((boost::format("%1%, for variable %2% from float to WORDTYPE %3%") % e.what() % _name % (WORDTYPE)type ).str().c_str());
return BasicVariable::ptr();
}
RETURN_VARPTR(float, Value());
}
//
template<> AMI_DLLEXPORT
BasicVariable::ptr Variable<float>::TernaryCondition(const BasicVariable::ptr& v1, const BasicVariable::ptr&v2)
{
if (Value()>0.5) {
return v1->NewReference();
} else {
return v2->NewReference();
}
return NewReference();
}
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif
template<> AMI_DLLEXPORT
BasicVariable::ptr Variable<float>::operator[](const BasicVariable::ptr& v)
{
if (v->IsNumeric()) {
float* pointer = this->Pointer().get();
//std::cout << "Size of array " << ARRAY_SIZE(pointer) << std::endl;
// at the user own risk
float res = pointer[(int)(v->GetValueAsDouble()+0.5)];
return AMILabType<float>::CreateVar(res);
} else
CLASS_ERROR("operator[] only takes a numerical parameter");
return NewReference();
}
template<> AMI_DLLEXPORT
BasicVariable::ptr Variable<float>::operator =(const BasicVariable::ptr& b)
{
if (b->IsNumeric()) {
RefValue() = b->GetValueAsDouble();
} else
CLASS_ERROR("operation not defined");
return NewReference();
}
| 29 | 136 | 0.656336 | [
"vector"
] |
5c5b4a5af04618e2091c3e038167318cec3fc26f | 932 | cpp | C++ | uva.onlinejudge.org/OneLittleTwoLittleThreeLittleEndians.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | uva.onlinejudge.org/OneLittleTwoLittleThreeLittleEndians.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | uva.onlinejudge.org/OneLittleTwoLittleThreeLittleEndians.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=535
Name: One Little, Two Little, Three Little Endians
Date: 12/02/2015
*/
#include <bits/stdc++.h>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 1000005
using namespace std;
typedef long long ll;
typedef pair<int, int> ii; typedef pair<int, ii> iii;
typedef vector<int> vi; typedef vector<ii> vii;
int n, aux, ans;
int main () {
ios_base::sync_with_stdio(0);
int TC, i, j;
while (cin>>n) {
ans = 0; aux = n;
for (i=0; i<4; i++) {
ans = (ans << 8) + (aux & ((1 << 8) - 1));
aux >>= 8;
}
cout<<n<<" converts to "<<ans<<endl;
}
return 0;
}
| 22.731707 | 113 | 0.614807 | [
"vector"
] |
5c5ffe61f2bb8385bacf5e113a57943fe102cf58 | 503 | cpp | C++ | cpp/beginner_contest_147/b.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | 1 | 2020-03-31T05:53:38.000Z | 2020-03-31T05:53:38.000Z | cpp/beginner_contest_147/b.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | cpp/beginner_contest_147/b.cpp | kitoko552/atcoder | a1e18b6d855baefb90ae6df010bcf1ffa8ff5562 | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep1(i, n) for (int i = 1; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1001001001;
int main() {
string S;
cin >> S;
string r = S;
reverse(r.begin(), r.end());
int ans = 0;
rep(i,S.size()) {
if (S[i] != r[i]) {
ans++;
}
}
cout << ans/2 << endl;
return 0;
}
| 17.344828 | 48 | 0.554672 | [
"vector"
] |
5c6019f8c24cfe477fe84488c4bed1a1a40b7889 | 3,379 | hpp | C++ | starter_kits/C++/hlt/game_map.hpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 2 | 2018-11-15T14:04:26.000Z | 2018-11-19T01:54:01.000Z | starter_kits/C++/hlt/game_map.hpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 5 | 2021-02-08T20:26:47.000Z | 2022-02-26T04:28:33.000Z | starter_kits/C++/hlt/game_map.hpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 1 | 2018-11-22T14:58:12.000Z | 2018-11-22T14:58:12.000Z | #pragma once
#include "types.hpp"
#include "map_cell.hpp"
#include <vector>
namespace hlt {
struct GameMap {
int width;
int height;
std::vector<std::vector<MapCell>> cells;
MapCell* at(const Position& position) {
Position normalized = normalize(position);
return &cells[normalized.y][normalized.x];
}
MapCell* at(const Entity& entity) {
return at(entity.position);
}
MapCell* at(const Entity* entity) {
return at(entity->position);
}
MapCell* at(const std::shared_ptr<Entity>& entity) {
return at(entity->position);
}
int calculate_distance(const Position& source, const Position& target) {
const auto& normalized_source = normalize(source);
const auto& normalized_target = normalize(target);
const int dx = std::abs(normalized_source.x - normalized_target.x);
const int dy = std::abs(normalized_source.y - normalized_target.y);
const int toroidal_dx = std::min(dx, width - dx);
const int toroidal_dy = std::min(dy, height - dy);
return toroidal_dx + toroidal_dy;
}
Position normalize(const Position& position) {
const int x = ((position.x % width) + width) % width;
const int y = ((position.y % height) + height) % height;
return { x, y };
}
std::vector<Direction> get_unsafe_moves(const Position& source, const Position& destination) {
const auto& normalized_source = normalize(source);
const auto& normalized_destination = normalize(destination);
const int dx = std::abs(normalized_source.x - normalized_destination.x);
const int dy = std::abs(normalized_source.y - normalized_destination.y);
const int wrapped_dx = width - dx;
const int wrapped_dy = height - dy;
std::vector<Direction> possible_moves;
if (normalized_source.x < normalized_destination.x) {
possible_moves.push_back(dx > wrapped_dx ? Direction::WEST : Direction::EAST);
} else if (normalized_source.x > normalized_destination.x) {
possible_moves.push_back(dx < wrapped_dx ? Direction::WEST : Direction::EAST);
}
if (normalized_source.y < normalized_destination.y) {
possible_moves.push_back(dy > wrapped_dy ? Direction::NORTH : Direction::SOUTH);
} else if (normalized_source.y > normalized_destination.y) {
possible_moves.push_back(dy < wrapped_dy ? Direction::NORTH : Direction::SOUTH);
}
return possible_moves;
}
Direction naive_navigate(std::shared_ptr<Ship> ship, const Position& destination) {
// get_unsafe_moves normalizes for us
for (auto direction : get_unsafe_moves(ship->position, destination)) {
Position target_pos = ship->position.directional_offset(direction);
if (!at(target_pos)->is_occupied()) {
at(target_pos)->mark_unsafe(ship);
return direction;
}
}
return Direction::STILL;
}
void _update();
static std::unique_ptr<GameMap> _generate();
};
}
| 36.333333 | 102 | 0.591299 | [
"vector"
] |
5c619d4cbaddfbd5aa36370593a7ba11ee240d25 | 163,269 | cpp | C++ | Samples/Win7Samples/multimedia/windowsmediaformat/wmgenprofile/exe/GenProfileDlg.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/multimedia/windowsmediaformat/wmgenprofile/exe/GenProfileDlg.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/multimedia/windowsmediaformat/wmgenprofile/exe/GenProfileDlg.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | //*****************************************************************************
//
// Microsoft Windows Media
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// FileName: GenProfileDlg.cpp
//
// Abstract: The implementation for the MFC dialog. This file
// contains most of the interesting functionality for the
// dialog, including the message handlers and the code
// that calls into the GenProfile static library.
//
// The OnBTNSaveProfile method shows the creation of a
// profile using the CreateProfile method and the saving
// of a profile to a PRX file.
//
//*****************************************************************************
#include "stdafx.h"
#include "GenProfile.h"
#include "GenProfileDlg.h"
#include "Macros.h"
#include "ControlPositionTable.h"
#include <strsafe.h>
#include <intsafe.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define VBR_OFFSET 5000 // The offset used to tell if a particular format is VBR and how many passes it is
#define MAX_FILENAME_LENGTH 50
///////////////////////////////////////////////////////////////////////////////
CGenProfileDlg::CGenProfileDlg( CWnd* pParent )
: CDialog(CGenProfileDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CGenProfileDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon( IDR_MAINFRAME );
m_dwNextCProfileObjectNumber = 1;
m_pDisplayedProfileObject = NULL;
m_pCodecInfo = NULL;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::DoDataExchange( CDataExchange* pDX )
{
CDialog::DoDataExchange( pDX );
//{{AFX_DATA_MAP(CGenProfileDlg)
DDX_Control(pDX, IDC_TXTProfileName, m_txtProfileName);
DDX_Control(pDX, IDC_CBLanguage, m_cbLanguage);
DDX_Control(pDX, IDC_CBPixelFormat, m_cbPixelFormat);
DDX_Control(pDX, IDC_CHKUncompressed, m_chkStreamIsUncompressed);
DDX_Control(pDX, IDC_TXTBandwidthBufferWindow, m_txtBandwidthBufferWindow);
DDX_Control(pDX, IDC_TXTStreamVideoVBRQuality, m_txtStreamVideoVBRQuality);
DDX_Control(pDX, IDC_CHKSMPTE, m_chkSMPTE);
DDX_Control(pDX, IDC_TXTStreamVideoMaxBufferWindow, m_txtStreamVideoMaxBufferWindow);
DDX_Control(pDX, IDC_TXTStreamVideoMaxBitrate, m_txtStreamVideoMaxBitrate);
DDX_Control(pDX, IDC_CHKStreamVideoMaxBufferWindow, m_chkStreamVideoMaxBufferWindow);
DDX_Control(pDX, IDC_CBStreamVideoVBRMode, m_cbStreamVideoVBRMode);
DDX_Control(pDX, IDC_CHKStreamVideoVBR, m_chkStreamVideoIsVBR);
DDX_Control(pDX, IDC_TXTStreamVideoQuality, m_txtStreamVideoQuality);
DDX_Control(pDX, IDC_TXTStreamVideoSecondsPerKeyframe, m_txtStreamVideoSecondsPerKeyframe);
DDX_Control(pDX, IDC_TXTStreamVideoFPS, m_txtStreamVideoFPS);
DDX_Control(pDX, IDC_TXTStreamBitrate, m_txtStreamBitrate);
DDX_Control(pDX, IDC_TXTStreamVideoWidth, m_txtStreamVideoWidth);
DDX_Control(pDX, IDC_TXTStreamVideoHeight, m_txtStreamVideoHeight);
DDX_Control(pDX, IDC_TXTStreamBufferWindow, m_txtStreamBufferWindow);
DDX_Control(pDX, IDC_CBStreamFormat, m_cbStreamFormat);
DDX_Control(pDX, IDC_CBStreamType, m_cbStreamType);
DDX_Control(pDX, IDC_CBStreamCodec, m_cbStreamCodec);
DDX_Control(pDX, IDC_LSTMandatoryStreams, m_lstMandatoryStreams);
DDX_Control(pDX, IDC_TXTSharedBitrate, m_txtSharedBitrate);
DDX_Control(pDX, IDC_LSTPrioritizationStreams, m_lstPrioritizationStreams);
DDX_Control(pDX, IDC_LSTSharingStreams, m_lstSharingStreams);
DDX_Control(pDX, IDC_FRAMutexType, m_fraMutexType);
DDX_Control(pDX, IDC_TXTHELP, m_txtHelp);
DDX_Control(pDX, IDC_FRAMutexStreams, m_fraMutexStreams);
DDX_Control(pDX, IDC_RBMutexTypeBitrate, m_rbMutexTypeBitrate);
DDX_Control(pDX, IDC_RBMutexTypeLanguage, m_rbMutexTypeLanguage);
DDX_Control(pDX, IDC_RBMutexTypePresentation, m_rbMutexTypePresentation);
DDX_Control(pDX, IDC_RBBandwidthTypeExclusive, m_rbBandwidthSharingTypeExclusive);
DDX_Control(pDX, IDC_RBBandwidthTypePartial, m_rbBandwidthSharingTypePartial);
DDX_Control(pDX, IDC_LSTMutexStreams, m_lstMutexStreams);
DDX_Control(pDX, IDC_LSTObjects, m_lstProfileObjects);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CGenProfileDlg, CDialog)
//{{AFX_MSG_MAP(CGenProfileDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BTNAddObject, OnBTNAddObject)
ON_COMMAND(IDM_AddStream, OnMNUAddStream)
ON_COMMAND(IDM_AddPrioritization, OnMNUAddPrioritization)
ON_COMMAND(IDM_AddMutex, OnMNUAddMutex)
ON_COMMAND(IDM_AddBandwidthSharing, OnMNUAddBandwidthSharing)
ON_LBN_SELCHANGE(IDC_LSTObjects, OnSelchangeLSTObjects)
ON_BN_CLICKED(IDC_BTNDeleteObject, OnBTNDeleteObject)
ON_BN_CLICKED(IDC_BTNSaveProfile, OnBTNSaveProfile)
ON_LBN_SELCHANGE(IDC_LSTMutexStreams, OnSelchangeLSTMutexStreams)
ON_BN_CLICKED(IDC_RBMutexTypeBitrate, OnRBMutexTypeBitrate)
ON_BN_CLICKED(IDC_RBMutexTypeLanguage, OnRBMutexTypeLanguage)
ON_BN_CLICKED(IDC_RBMutexTypePresentation, OnRBMutexTypePresentation)
ON_LBN_SELCHANGE(IDC_LSTSharingStreams, OnSelchangeLSTSharingStreams)
ON_BN_CLICKED(IDC_BTNPrioritizationUp, OnBTNPrioritizationUp)
ON_BN_CLICKED(IDC_BTNPrioritizationDown, OnBTNPrioritizationDown)
ON_EN_KILLFOCUS(IDC_TXTSharedBitrate, OnKillfocusTXTSharedBitrate)
ON_LBN_SELCHANGE(IDC_LSTMandatoryStreams, OnSelchangeLSTMandatoryStreams)
ON_CBN_SELCHANGE(IDC_CBStreamType, OnSelchangeCBStreamType)
ON_CBN_SELCHANGE(IDC_CBStreamCodec, OnSelchangeCBStreamCodec)
ON_CBN_SELCHANGE(IDC_CBStreamFormat, OnSelchangeCBStreamFormat)
ON_EN_KILLFOCUS(IDC_TXTStreamBitrate, OnKillfocusTXTStreamBitrate)
ON_EN_KILLFOCUS(IDC_TXTStreamBufferWindow, OnKillfocusTXTStreamBufferWindow)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoWidth, OnKillfocusTXTStreamVideoWidth)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoHeight, OnKillfocusTXTStreamVideoHeight)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoFPS, OnKillfocusTXTStreamVideoFPS)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoSecondsPerKeyframe, OnKillfocusTXTStreamVideoSecondsPerKeyframe)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoQuality, OnKillfocusTXTStreamVideoQuality)
ON_BN_CLICKED(IDC_CHKStreamVideoVBR, OnCHKStreamVideoVBR)
ON_CBN_SELCHANGE(IDC_CBStreamVideoVBRMode, OnSelchangeCBStreamVideoVBRMode)
ON_BN_CLICKED(IDC_CHKStreamVideoMaxBufferWindow, OnCHKStreamVideoMaxBufferWindow)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoMaxBufferWindow, OnKillfocusTXTStreamVideoMaxBufferWindow)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoMaxBitrate, OnKillfocusTXTStreamVideoMaxBitrate)
ON_BN_CLICKED(IDC_CHKSMPTE, OnChkSMPTE)
ON_BN_CLICKED(IDC_RBBandwidthTypeExclusive, OnRBBandwidthTypeExclusive)
ON_BN_CLICKED(IDC_RBBandwidthTypePartial, OnRBBandwidthTypePartial)
ON_EN_KILLFOCUS(IDC_TXTStreamVideoVBRQuality, OnKillfocusTXTStreamVideoVBRQuality)
ON_EN_KILLFOCUS(IDC_TXTBandwidthBufferWindow, OnKillfocusTXTBandwidthBufferWindow)
ON_BN_CLICKED(IDC_CHKUncompressed, OnCHKStreamUncompressed)
ON_CBN_SELCHANGE(IDC_CBPixelFormat, OnSelchangeCBPixelFormat)
ON_CBN_SELCHANGE(IDC_CBLanguage, OnSelchangeCBLanguage)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
///////////////////////////////////////////////////////////////////////////////
BOOL CGenProfileDlg::DestroyWindow()
{
//
// Free up any resources pointed to by the profile object list
//
while ( m_lstProfileObjects.GetCount() > 0 )
{
DeleteProfileObjectByIndex( 0 );
}
SAFE_RELEASE( m_pCodecInfo );
return CDialog::DestroyWindow();
}
/*
** Start of message handlers
*/
///////////////////////////////////////////////////////////////////////////////
BOOL CGenProfileDlg::OnInitDialog()
{
HRESULT hr = S_OK;
INT nNewStringIndex;
DWORD dwCodecCount;
CString strStreamType;
CString strError;
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon( m_hIcon, TRUE ); // Set big icon
SetIcon( m_hIcon, FALSE ); // Set small icon
hr = EnsureIWMCodecInfo3( &m_pCodecInfo );
if ( FAILED( hr ) )
{
strError.LoadString( IDS_No_IWMCodecInfo3_error );
DisplayMessageAndTerminate( strError );
return FALSE;
}
assert( m_pCodecInfo );
//
// Setup the stream type combo box
//
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Audio, &dwCodecCount );
if ( SUCCEEDED( hr ) && ( dwCodecCount > 0 ) ) // Only add option if an audio codec exists
{
strStreamType.LoadString( IDS_Audio );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_Audio );
m_bIsAudioCodec = TRUE;
}
else
{
m_bIsAudioCodec = FALSE;
}
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Video, &dwCodecCount );
if ( SUCCEEDED( hr ) && ( dwCodecCount > 0 ) ) // Only add option if a video codec exists
{
strStreamType.LoadString( IDS_Video );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_Video );
m_bIsVideoCodec = TRUE;
}
else
{
m_bIsVideoCodec = FALSE;
}
strStreamType.LoadString( IDS_Script );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_Script );
strStreamType.LoadString( IDS_Image );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_Image );
strStreamType.LoadString( IDS_Web );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_Web );
strStreamType.LoadString( IDS_File );
nNewStringIndex = m_cbStreamType.AddString( strStreamType );
m_cbStreamType.SetItemData( nNewStringIndex, ST_File );
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnPaint()
{
if ( IsIconic() )
{
CPaintDC dc( this ); // device context for painting
SendMessage( WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0 );
// Center icon in client rectangle
int cxIcon = GetSystemMetrics( SM_CXICON );
int cyIcon = GetSystemMetrics( SM_CYICON );
CRect rect;
GetClientRect( &rect );
int x = ( rect.Width() - cxIcon + 1 ) / 2;
int y = ( rect.Height() - cyIcon + 1 ) / 2;
// Draw the icon
dc.DrawIcon( x, y, m_hIcon );
}
else
{
CDialog::OnPaint();
}
}
///////////////////////////////////////////////////////////////////////////////
HCURSOR CGenProfileDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnBTNAddObject()
{
CMenu mnuParent;
CMenu* pmnuContext;
POINT pntMouseCursor;
//
// Load the menu resource
//
mnuParent.LoadMenu( MAKEINTRESOURCE( IDR_MNUAddObjectContext ) );
pmnuContext = mnuParent.GetSubMenu( 0 );
//
// Get the current mouse position
//
ZeroMemory( &pntMouseCursor, sizeof( pntMouseCursor ) );
GetCursorPos( &pntMouseCursor );
//
// Disable the stream prioritization option if a prioritization object already exists
//
if ( StreamPrioritizationObjectExists() )
{
pmnuContext->EnableMenuItem( IDM_AddPrioritization, MF_GRAYED );
}
else
{
pmnuContext->EnableMenuItem( IDM_AddPrioritization, MF_ENABLED );
}
//
// Pop up a context menu to allow the user to select the type of object
//
if ( !pmnuContext->TrackPopupMenu( TPM_LEFTALIGN | TPM_RIGHTBUTTON, pntMouseCursor.x, pntMouseCursor.y, this ) )
{
return;
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnMNUAddStream()
{
HRESULT hr = S_OK;
CStream* pNewStream = NULL;
INT nNewItemIndex;
CString strObjectName;
INT nObjectIndex;
CProfileObject* pProfileObject;
do
{
//
// Create stream data for the new stream
//
pNewStream = new CStream();
if ( !pNewStream )
{
hr = E_OUTOFMEMORY;
break;
}
//
// Setup the stream so that it points to a valid, existing codec / format
//
if ( m_bIsAudioCodec )
{
hr = SetDefaultsForAudioStream( pNewStream ); // Prints its own error
}
else if ( m_bIsVideoCodec )
{
hr = SetDefaultsForVideoStream( pNewStream ); // Prints its own error
}
else
{
hr = SetDefaultsForScriptStream( pNewStream );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
if ( FAILED( hr ) )
{
break;
}
//
// Add the new stream to the bottom of all stream prioritization objects
//
for ( nObjectIndex = 0; nObjectIndex < m_lstProfileObjects.GetCount(); nObjectIndex++ )
{
pProfileObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nObjectIndex );
assert( pProfileObject );
if ( (CProfileObject*) -1 == pProfileObject )
{
hr = E_UNEXPECTED;
DisplayMessage( IDS_Fatal_error );
break;
}
if ( OT_StreamPrioritization == pProfileObject->Type() )
{
((CStreamPrioritizationObject*) pProfileObject)->AddStream( pNewStream );
}
}
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
break;
}
//
// Create a new list entry for the new stream
//
strObjectName.Format( _T("Stream %d"), m_dwNextCProfileObjectNumber++ );
pNewStream->SetName( strObjectName );
nNewItemIndex = m_lstProfileObjects.AddString( strObjectName );
if ( ( LB_ERR == nNewItemIndex ) || ( LB_ERRSPACE == nNewItemIndex ) )
{
hr = E_UNEXPECTED;
DisplayMessage( IDS_Fatal_error );
break;
}
SAFE_ADDREF( pNewStream );
m_lstProfileObjects.SetItemDataPtr( nNewItemIndex, pNewStream );
//
// Redraw the controls, since there might've been a change that affects the current object
//
hr = DisplayProfileObject( m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_RELEASE( pNewStream );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnMNUAddPrioritization()
{
HRESULT hr = S_OK;
CStreamPrioritizationObject *pNewStreamPrioritizationObject = NULL;
INT nNewItemIndex;
CString strObjectName;
INT nProfileObjectIndex;
CProfileObject* pCurrentObject;
do
{
//
// Create bandwidth sharing data
//
pNewStreamPrioritizationObject = new CStreamPrioritizationObject();
if ( !pNewStreamPrioritizationObject )
{
hr = E_OUTOFMEMORY;
break;
}
//
// Add all the existing streams, for prioritization
//
for ( nProfileObjectIndex = 0; nProfileObjectIndex < m_lstProfileObjects.GetCount(); nProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nProfileObjectIndex );
assert( pCurrentObject );
if ( (CProfileObject*) -1 == pCurrentObject )
{
hr = E_UNEXPECTED;
break;
}
if ( OT_Stream == pCurrentObject->Type() )
{
pNewStreamPrioritizationObject->AddStream( (CStream*) pCurrentObject );
}
}
if ( FAILED( hr ) )
{
break;
}
//
// Create a new list entry for the new stream
//
strObjectName.Format( _T("Prioritization %d"), m_dwNextCProfileObjectNumber++ );
nNewItemIndex = m_lstProfileObjects.AddString( strObjectName );
if ( ( LB_ERR == nNewItemIndex ) || ( LB_ERRSPACE == nNewItemIndex ) )
{
hr = E_UNEXPECTED;
break;
}
SAFE_ADDREF( pNewStreamPrioritizationObject );
m_lstProfileObjects.SetItemDataPtr( nNewItemIndex, pNewStreamPrioritizationObject );
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_RELEASE( pNewStreamPrioritizationObject );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnMNUAddMutex()
{
HRESULT hr = S_OK;
CMutex* pNewMutex = NULL;
INT nNewItemIndex;
CString strObjectName;
do
{
//
// Create mutex data for the new stream
//
pNewMutex = new CMutex();
if ( !pNewMutex )
{
hr = E_OUTOFMEMORY;
break;
}
//
// Set the defaults for the mutex
//
pNewMutex->SetMutexType( MT_Bitrate );
//
// Create a new list entry for the new stream
//
strObjectName.Format( _T("Mutex %d"), m_dwNextCProfileObjectNumber++ );
nNewItemIndex = m_lstProfileObjects.AddString( strObjectName );
if ( ( LB_ERR == nNewItemIndex ) || ( LB_ERRSPACE == nNewItemIndex ) )
{
hr = E_UNEXPECTED;
break;
}
SAFE_ADDREF( pNewMutex );
m_lstProfileObjects.SetItemDataPtr( nNewItemIndex, pNewMutex );
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_RELEASE( pNewMutex );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnMNUAddBandwidthSharing()
{
HRESULT hr = S_OK;
CBandwidthSharingObject* pNewBandwidthSharingObject = NULL;
INT nNewItemIndex;
CString strObjectName;
do
{
//
// Create bandwidth sharing data
//
pNewBandwidthSharingObject = new CBandwidthSharingObject();
if ( !pNewBandwidthSharingObject )
{
hr = E_OUTOFMEMORY;
break;
}
//
// Set defaults for object
//
pNewBandwidthSharingObject->SetBandwidthSharingType( CLSID_WMBandwidthSharing_Exclusive );
pNewBandwidthSharingObject->SetSharedBitrate( 100000 );
//
// Create a new list entry for the new stream
//
strObjectName.Format( _T("Bandwidth sharing %d"), m_dwNextCProfileObjectNumber++ );
nNewItemIndex = m_lstProfileObjects.AddString( strObjectName );
if ( ( LB_ERR == nNewItemIndex ) || ( LB_ERRSPACE == nNewItemIndex ) )
{
hr = E_UNEXPECTED;
break;
}
SAFE_ADDREF( pNewBandwidthSharingObject );
m_lstProfileObjects.SetItemDataPtr( nNewItemIndex, pNewBandwidthSharingObject );
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_RELEASE( pNewBandwidthSharingObject );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeLSTObjects()
{
HRESULT hr = S_OK;
INT nSelectedProfileObjectIndex;
CProfileObject *pSelectedProfileObject;
do
{
//
// Get the item that has been selected
//
nSelectedProfileObjectIndex = m_lstProfileObjects.GetCurSel();
if ( LB_ERR == nSelectedProfileObjectIndex )
{
pSelectedProfileObject = NULL;
}
else
{
pSelectedProfileObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nSelectedProfileObjectIndex );
if ( (CProfileObject*) -1 == pSelectedProfileObject )
{
DisplayMessage( IDS_Fatal_error );
pSelectedProfileObject = NULL;
}
}
hr = DisplayProfileObject( pSelectedProfileObject );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnBTNDeleteObject()
{
HRESULT hr = S_OK;
INT nSelectedProfileObjectIndex;
do
{
//
// Get the selected object
//
nSelectedProfileObjectIndex = m_lstProfileObjects.GetCurSel();
if ( LB_ERR == nSelectedProfileObjectIndex ) // Nothing selected
{
break;
}
//
// Delete the profile object
//
hr = DeleteProfileObjectByIndex( nSelectedProfileObjectIndex );
if ( FAILED( hr ) )
{
break;
}
//
// Update the display
//
hr = DisplayProfileObject( NULL );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnBTNSaveProfile()
{
HRESULT hr = S_OK;
IWMProfileManager* pProfileManager = NULL;
IWMProfile* pProfile = NULL;
LPWSTR wszProfileData = NULL;
DWORD dwProfileDataLength;
CFileDialog cSaveDialog( FALSE, _T(".prx"), NULL, OFN_OVERWRITEPROMPT, _T("Profiles (*.prx)|*.prx||"), this );
CString strMessage;
do
{
//
// Get the filename from a common dialog box
//
if ( IDOK != cSaveDialog.DoModal() )
{
break;
}
//
// Create the profile manager
//
hr = WMCreateProfileManager( &pProfileManager );
if ( FAILED( hr ) )
{
break;
}
//
// Create the profile based off the data in the dialog
//
hr = CreateProfile( &pProfile );
if ( FAILED( hr ) )
{
break;
}
assert( pProfile );
//
// Convert the profile to XML
//
dwProfileDataLength = 0;
hr = pProfileManager->SaveProfile( pProfile, NULL, &dwProfileDataLength );
if ( FAILED( hr ) )
{
break;
}
wszProfileData = new WCHAR[ dwProfileDataLength + 1 ];
if ( !wszProfileData )
{
hr = E_OUTOFMEMORY;
break;
}
hr = pProfileManager->SaveProfile( pProfile, wszProfileData, &dwProfileDataLength );
if ( FAILED( hr ) )
{
break;
}
//
// Write the profile to a file
//
hr = WriteProfileAsPRX( cSaveDialog.GetPathName(), wszProfileData, dwProfileDataLength * sizeof( WCHAR ) );
if ( FAILED( hr ) )
{
break;
}
DisplayMessage( IDS_Profile_saved );
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Cant_create_profile_error );
}
SAFE_RELEASE( pProfile );
SAFE_RELEASE( pProfileManager );
SAFE_ARRAYDELETE( wszProfileData );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeLSTMutexStreams()
{
CMutex* pSelectedMutex;
assert( m_pDisplayedProfileObject );
assert( OT_Mutex == m_pDisplayedProfileObject->Type() );
do
{
pSelectedMutex = (CMutex*) m_pDisplayedProfileObject;
ValidateMutexStreamsAgainstControl( pSelectedMutex );
}
while ( FALSE );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnRBMutexTypeBitrate()
{
assert( m_pDisplayedProfileObject );
assert( OT_Mutex == m_pDisplayedProfileObject->Type() );
((CMutex*) m_pDisplayedProfileObject)->SetMutexType( MT_Bitrate );
//
// Validate that the streams in the mutex are allowed
//
ValidateMutexStreamsAgainstControl( (CMutex*) m_pDisplayedProfileObject );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnRBMutexTypeLanguage()
{
assert( m_pDisplayedProfileObject );
assert( OT_Mutex == m_pDisplayedProfileObject->Type() );
((CMutex*) m_pDisplayedProfileObject)->SetMutexType( MT_Language );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnRBMutexTypePresentation()
{
assert( m_pDisplayedProfileObject );
assert( OT_Mutex == m_pDisplayedProfileObject->Type() );
((CMutex*) m_pDisplayedProfileObject)->SetMutexType( MT_Presentation );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnCHKStreamUncompressed()
{
BOOL fIsChecked;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
fIsChecked = ( m_chkStreamIsUncompressed.GetCheck() == BST_CHECKED );
((CStream*) m_pDisplayedProfileObject)->SetIsUncompressed( fIsChecked );
//
// Turn off VBR
//
((CStream*) m_pDisplayedProfileObject)->SetVideoIsVBR( FALSE );
//
// Update the display, since changing this will affect the other controls
//
ShowStream( (CStream*) m_pDisplayedProfileObject );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeLSTSharingStreams()
{
HRESULT hr = S_OK;
INT nSelectedStreamsCount;
INT* aSelectedStreams = NULL;
INT nSelectedStreamIndex;
CStream* pHighlightedStream;
CBandwidthSharingObject* pSelectedBandwidthSharingObject;
assert( m_pDisplayedProfileObject );
assert( OT_BandwidthSharing == m_pDisplayedProfileObject->Type() );
do
{
pSelectedBandwidthSharingObject = (CBandwidthSharingObject*) m_pDisplayedProfileObject;
pSelectedBandwidthSharingObject->RemoveAllStreams();
//
// Get the list of selected items
//
nSelectedStreamsCount = m_lstSharingStreams.GetSelCount();
aSelectedStreams = new INT[ nSelectedStreamsCount ];
if ( !aSelectedStreams )
{
hr = E_OUTOFMEMORY;
break;
}
if ( LB_ERR == m_lstSharingStreams.GetSelItems( nSelectedStreamsCount, aSelectedStreams ) )
{
hr = E_UNEXPECTED;
break;
}
//
// Select all the streams which should be selected
//
for( nSelectedStreamIndex = 0; nSelectedStreamIndex < nSelectedStreamsCount; nSelectedStreamIndex++ )
{
pHighlightedStream = (CStream*) m_lstSharingStreams.GetItemDataPtr( aSelectedStreams[ nSelectedStreamIndex ] );
assert( pHighlightedStream );
if ( (CStream*) -1 == pHighlightedStream )
{
hr = E_UNEXPECTED;
break;
}
pSelectedBandwidthSharingObject->AddStream( pHighlightedStream );
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_ARRAYDELETE( aSelectedStreams );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnBTNPrioritizationUp()
{
HRESULT hr = S_OK;
CStreamPrioritizationObject* pDisplayedObject;
CStream* pSelectedStream;
INT nSelectedIndex;
assert( m_pDisplayedProfileObject );
assert( OT_StreamPrioritization == m_pDisplayedProfileObject->Type() );
do
{
//
// Get the stream selected in the listbox
//
pDisplayedObject = (CStreamPrioritizationObject*) m_pDisplayedProfileObject;
nSelectedIndex = m_lstPrioritizationStreams.GetCurSel();
if ( 0 != nSelectedIndex )
{
pSelectedStream = (CStream*) m_lstPrioritizationStreams.GetItemDataPtr( nSelectedIndex );
assert( pSelectedStream );
if ( (CStream*) -1 == pSelectedStream )
{
hr = E_UNEXPECTED;
break;
}
hr = pDisplayedObject->IncreasePriority( pSelectedStream );
if ( FAILED( hr ) )
{
break;
}
hr = RefreshStreamPriorityList( pDisplayedObject );
if ( FAILED( hr ) )
{
break;
}
if ( LB_ERR == m_lstPrioritizationStreams.SetCurSel( nSelectedIndex - 1 ) )
{
break;
}
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnBTNPrioritizationDown()
{
HRESULT hr = S_OK;
CStreamPrioritizationObject* pDisplayedObject;
CStream* pSelectedStream;
INT nSelectedIndex;
assert( m_pDisplayedProfileObject );
assert( OT_StreamPrioritization == m_pDisplayedProfileObject->Type() );
do
{
//
// Get the stream selected in the listbox
//
pDisplayedObject = (CStreamPrioritizationObject*) m_pDisplayedProfileObject;
nSelectedIndex = m_lstPrioritizationStreams.GetCurSel();
if ( nSelectedIndex != m_lstPrioritizationStreams.GetCount() - 1 )
{
pSelectedStream = (CStream*) m_lstPrioritizationStreams.GetItemDataPtr( nSelectedIndex );
assert( pSelectedStream );
if ( (CStream*) -1 == pSelectedStream )
{
break;
}
hr = pDisplayedObject->DecreasePriority( pSelectedStream );
if ( FAILED( hr ) )
{
break;
}
hr = RefreshStreamPriorityList( pDisplayedObject );
if ( FAILED( hr ) )
{
break;
}
if ( LB_ERR == m_lstPrioritizationStreams.SetCurSel( nSelectedIndex + 1 ) )
{
break;
}
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTSharedBitrate()
{
CString strSharedBitrate;
DWORD dwSharedBitrate;
assert( m_pDisplayedProfileObject );
assert( OT_BandwidthSharing == m_pDisplayedProfileObject->Type() );
m_txtSharedBitrate.GetWindowText( strSharedBitrate );
dwSharedBitrate = _ttol( strSharedBitrate );
((CBandwidthSharingObject*) m_pDisplayedProfileObject)->SetSharedBitrate( dwSharedBitrate );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeLSTMandatoryStreams()
{
HRESULT hr = S_OK;
INT nSelectedStreamsCount;
INT* aSelectedStreams = NULL;
INT nSelectedStreamIndex;
CStream* pHighlightedStream;
CStreamPrioritizationObject* pSelectedObject;
assert( m_pDisplayedProfileObject );
assert( OT_StreamPrioritization == m_pDisplayedProfileObject->Type() );
do
{
pSelectedObject = (CStreamPrioritizationObject*) m_pDisplayedProfileObject;
hr = pSelectedObject->ClearMandatoryStreams();
if ( FAILED( hr ) )
{
break;
}
//
// Get the list of selected items
//
nSelectedStreamsCount = m_lstMandatoryStreams.GetSelCount();
aSelectedStreams = new INT[ nSelectedStreamsCount ];
if ( !aSelectedStreams )
{
hr = E_OUTOFMEMORY;
break;
}
if ( LB_ERR == m_lstMandatoryStreams.GetSelItems( nSelectedStreamsCount, aSelectedStreams ) )
{
hr = E_UNEXPECTED;
break;
}
//
// Select all the streams which should be selected
//
for( nSelectedStreamIndex = 0; nSelectedStreamIndex < nSelectedStreamsCount; nSelectedStreamIndex++ )
{
pHighlightedStream = (CStream*) m_lstMandatoryStreams.GetItemDataPtr( aSelectedStreams[ nSelectedStreamIndex ] );
assert( pHighlightedStream );
if ( (CStream*) -1 == pHighlightedStream )
{
hr = E_UNEXPECTED;
break;
}
pSelectedObject->SetStreamMandatory( pHighlightedStream, TRUE );
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_ARRAYDELETE( aSelectedStreams );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBStreamType()
{
HRESULT hr = S_OK;
CString strSelectedStreamType;
INT nSelectedIndex;
DWORD nSelectedType;
StreamType stOriginalType;
CString strMessage;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
do
{
nSelectedIndex = m_cbStreamType.GetCurSel();
if ( CB_ERR == nSelectedIndex )
{
return;
}
nSelectedType = ( DWORD )( m_cbStreamType.GetItemData( nSelectedIndex ) );
if ( CB_ERR == nSelectedType )
{
return;
}
//
// If the stream type changed, then remove it from any mutexes, since it won't be valid anymore
//
stOriginalType = ((CStream*) m_pDisplayedProfileObject)->GetStreamType();
if ( (StreamType) nSelectedType != stOriginalType )
{
hr = RemoveStreamFromAllMutexes( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
else
{
DisplayMessage( IDS_Stream_remove_from_mutexes );
}
}
//
// Set the defaults for the new stream type
//
switch ( nSelectedType )
{
case ST_Audio:
assert( m_bIsAudioCodec );
hr = SetDefaultsForAudioStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowAudioStream( (CStream*) m_pDisplayedProfileObject );
break;
case ST_Video:
assert( m_bIsVideoCodec );
hr = SetDefaultsForVideoStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowVideoStream( (CStream*) m_pDisplayedProfileObject );
break;
case ST_Script:
hr = SetDefaultsForScriptStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowScriptStream( (CStream*) m_pDisplayedProfileObject );
break;
case ST_Image:
hr = SetDefaultsForImageStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowImageStream( (CStream*) m_pDisplayedProfileObject );
break;
case ST_Web:
hr = SetDefaultsForWebStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowWebStream( (CStream*) m_pDisplayedProfileObject );
break;
case ST_File:
hr = SetDefaultsForFileStream( (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
hr = ShowFileStream( (CStream*) m_pDisplayedProfileObject );
break;
default:
assert( "Unknown stream type selected!" );
m_cbStreamType.SetCurSel( ST_Script );
hr = SetDefaultsForScriptStream( (CStream*) m_pDisplayedProfileObject );
DisplayMessage( IDS_Fatal_error );
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
ShowStreamWindowPlacement( nSelectedType );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBStreamCodec()
{
HRESULT hr = S_OK;
CString strSelectedFormat;
INT nSelectedIndex;
DWORD dwCodecIndex;
DWORD dwStreamFormatIndex;
DWORD dwStreamFormatStringIndex;
CStream* pStream;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Audio ) ||
( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video ) );
//
// Get the selected codec from the control
//
m_cbStreamCodec.GetWindowText( strSelectedFormat );
nSelectedIndex = m_cbStreamCodec.GetCurSel();
assert( CB_ERR != nSelectedIndex );
pStream = (CStream*) m_pDisplayedProfileObject;
//
// Depending on the type of the stream, adjust the stream settings / window configuration
//
switch ( pStream->GetStreamType() )
{
case ST_Audio:
pStream->SetStreamCodecIndex( nSelectedIndex );
dwCodecIndex = ( DWORD )( m_cbStreamCodec.GetItemData( nSelectedIndex ) );
assert( CB_ERR != dwCodecIndex );
hr = PopulateAudioFormatCB( dwCodecIndex );
if ( FAILED( hr ) )
{
break;
}
dwStreamFormatStringIndex = 0; // Default to the first format in the combo box
assert( dwStreamFormatStringIndex < (DWORD) m_cbStreamFormat.GetCount() );
dwStreamFormatIndex = ( DWORD )( m_cbStreamFormat.GetItemData( dwStreamFormatStringIndex ) );
pStream->SetStreamFormatIndex( dwStreamFormatIndex );
pStream->SetStreamFormatStringIndex( dwStreamFormatStringIndex );
m_cbStreamFormat.SetCurSel( dwStreamFormatStringIndex );
break;
case ST_Video:
pStream->SetStreamCodecIndex( nSelectedIndex );
dwCodecIndex = ( DWORD )( m_cbStreamCodec.GetItemData( nSelectedIndex ) );
assert( CB_ERR != dwCodecIndex );
pStream->SetVideoIsVBR( FALSE );
pStream->SetVideoVBRMode( VBR_QUALITYBASED );
hr = DisplayVBRControlsForCodec( dwCodecIndex, (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
break;
default:
assert( !"Invalid stream type from which to be switching codec!" );
hr = E_UNEXPECTED;
}
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBStreamFormat()
{
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Audio );
if ( !((CStream*) m_pDisplayedProfileObject)->GetIsUncompressed() )
{
INT nSelectedIndex;
DWORD dwFormatIndex;
nSelectedIndex = m_cbStreamFormat.GetCurSel();
assert( CB_ERR != nSelectedIndex );
dwFormatIndex = ( DWORD )( m_cbStreamFormat.GetItemData( nSelectedIndex ) );
assert( CB_ERR != dwFormatIndex );
((CStream*) m_pDisplayedProfileObject)->SetStreamFormatIndex( dwFormatIndex );
((CStream*) m_pDisplayedProfileObject)->SetStreamFormatStringIndex( nSelectedIndex );
}
else
{
DWORD dwStringIndex = m_cbStreamFormat.GetCurSel();
DWORD dwIndex = ( DWORD )( m_cbStreamFormat.GetItemData( dwStringIndex ) );
((CStream*) m_pDisplayedProfileObject)->SetWaveFormatStringIndex( dwStringIndex );
((CStream*) m_pDisplayedProfileObject)->SetWaveFormatIndex( dwIndex );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamBitrate()
{
CString strBitrate;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) ||
( ST_Script == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) ||
( ST_Image == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) ||
( ST_Web == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) ||
( ST_File == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) ||
( ST_Arbitrary == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() ) );
//
// Set the bitrate on the stream
//
m_txtStreamBitrate.GetWindowText( strBitrate );
((CStream*) m_pDisplayedProfileObject)->SetStreamBitrate( _ttol( strBitrate ) );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamBufferWindow()
{
CString strBufferWindow;
DWORD dwBufferWindow;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
m_txtStreamBufferWindow.GetWindowText( strBufferWindow );
dwBufferWindow = _ttol( strBufferWindow );
((CStream*) m_pDisplayedProfileObject)->SetStreamBufferWindow( dwBufferWindow );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoWidth()
{
CString strWidth;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
//
// Set the width on the video stream
//
m_txtStreamVideoWidth.GetWindowText( strWidth );
((CStream*) m_pDisplayedProfileObject)->SetVideoWidth( _ttol( strWidth ) );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoHeight()
{
CString strHeight;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
//
// Set the height on the video stream
//
m_txtStreamVideoWidth.GetWindowText( strHeight );
((CStream*) m_pDisplayedProfileObject)->SetVideoHeight( _ttol( strHeight ) );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoFPS()
{
CString strFPS;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
//
// Set the FPS on the video stream
//
m_txtStreamVideoFPS.GetWindowText( strFPS );
((CStream*) m_pDisplayedProfileObject)->SetVideoFPS( _ttol( strFPS ) );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoSecondsPerKeyframe()
{
CString strSecondsPerKeyframe;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
//
// Set the number of seconds between key frames on the video stream
//
m_txtStreamVideoSecondsPerKeyframe.GetWindowText( strSecondsPerKeyframe );
((CStream*) m_pDisplayedProfileObject)->SetVideoSecondsPerKeyframe( _ttol( strSecondsPerKeyframe ) );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoQuality()
{
CString strQuality;
DWORD dwQuality;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
//
// Set the quality on the video stream
//
m_txtStreamVideoQuality.GetWindowText( strQuality );
dwQuality = _ttol( strQuality );
if ( dwQuality > 100 )
{
dwQuality = 100;
strQuality.Format( _T("%ld"), dwQuality );
m_txtStreamVideoQuality.SetWindowText( strQuality );
}
((CStream*) m_pDisplayedProfileObject)->SetVideoQuality( dwQuality );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnCHKStreamVideoVBR()
{
HRESULT hr = S_OK;
BOOL fIsChecked;
CStream* pStream;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video );
do
{
pStream = (CStream*) m_pDisplayedProfileObject;
fIsChecked = ( m_chkStreamVideoIsVBR.GetCheck() == BST_CHECKED );
if ( !fIsChecked )
{
m_cbStreamVideoVBRMode.EnableWindow( FALSE );
m_txtStreamVideoVBRQuality.EnableWindow( FALSE );
pStream->SetVideoIsVBR( FALSE );
}
else
{
m_cbStreamVideoVBRMode.EnableWindow( TRUE );
m_txtStreamVideoVBRQuality.EnableWindow( TRUE );
pStream->SetVideoIsVBR( TRUE );
pStream->SetVideoVBRMode( VBR_QUALITYBASED );
pStream->SetVideoVBRQuality( 0 );
hr = SelectItemWithData( &m_cbStreamVideoVBRMode, VBR_QUALITYBASED );
if ( FAILED( hr ) )
{
break;
}
}
hr = DisplayVBRControlsForCodec( pStream->GetStreamCodecIndex(), pStream );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBStreamVideoVBRMode()
{
HRESULT hr = S_OK;
INT nSelectedIndex;
DWORD dwCodecIndex;
DWORD dwSelectedCodec;
VIDEO_VBR_MODE vbrMode;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video );
assert( BST_CHECKED == m_chkStreamVideoIsVBR.GetCheck() );
do
{
nSelectedIndex = m_cbStreamVideoVBRMode.GetCurSel();
assert( CB_ERR != nSelectedIndex );
dwSelectedCodec = m_cbStreamCodec.GetCurSel();
if ( CB_ERR == dwSelectedCodec )
{
hr = E_UNEXPECTED;
break;
}
dwCodecIndex = ( DWORD )( m_cbStreamCodec.GetItemData( dwSelectedCodec ) );
if ( CB_ERR == dwCodecIndex )
{
hr = E_UNEXPECTED;
break;
}
vbrMode = (VIDEO_VBR_MODE) m_cbStreamVideoVBRMode.GetItemData( nSelectedIndex );
assert( CB_ERR != vbrMode );
((CStream*)m_pDisplayedProfileObject)->SetVideoVBRMode( vbrMode );
((CStream*)m_pDisplayedProfileObject)->SetVideoMaxBufferWindow( 0 );
hr = DisplayVBRControlsForCodec( dwCodecIndex, (CStream*) m_pDisplayedProfileObject );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnCHKStreamVideoMaxBufferWindow()
{
BOOL fIsChecked;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video );
fIsChecked = ( m_chkStreamVideoMaxBufferWindow.GetCheck() == BST_CHECKED );
if ( !fIsChecked )
{
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
((CStream*) m_pDisplayedProfileObject)->SetVideoMaxBufferWindow( 0 );
}
else
{
m_txtStreamVideoMaxBufferWindow.EnableWindow( TRUE );
m_txtStreamVideoMaxBufferWindow.SetWindowText( _T("10000") );
((CStream*) m_pDisplayedProfileObject)->SetVideoMaxBufferWindow( 10000 );
}
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoMaxBufferWindow()
{
CString strMaxBufferWindow;
DWORD dwMaxBufferWindow;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video );
assert( BST_CHECKED == m_chkStreamVideoIsVBR.GetCheck() );
m_txtStreamVideoMaxBufferWindow.GetWindowText( strMaxBufferWindow );
dwMaxBufferWindow = _ttol( strMaxBufferWindow );
//
// Make the minimum 1
//
if ( 0 == dwMaxBufferWindow )
{
dwMaxBufferWindow = 1;
strMaxBufferWindow.Format( _T("%ld"), dwMaxBufferWindow );
m_txtStreamVideoMaxBufferWindow.SetWindowText( strMaxBufferWindow );
}
((CStream*) m_pDisplayedProfileObject)->SetVideoMaxBufferWindow( dwMaxBufferWindow );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoMaxBitrate()
{
CString strMaxBitrate;
DWORD dwMaxBitrate;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ((CStream*)m_pDisplayedProfileObject)->GetStreamType() == ST_Video );
assert( BST_CHECKED == m_chkStreamVideoIsVBR.GetCheck() );
m_txtStreamVideoMaxBitrate.GetWindowText( strMaxBitrate );
dwMaxBitrate = _ttol( strMaxBitrate );
((CStream*) m_pDisplayedProfileObject)->SetVideoMaxBitrate( dwMaxBitrate );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnChkSMPTE()
{
BOOL fIsChecked;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
fIsChecked = ( m_chkSMPTE.GetCheck() == BST_CHECKED );
((CStream*) m_pDisplayedProfileObject)->SetIsSMPTE( fIsChecked );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnRBBandwidthTypeExclusive()
{
assert( m_pDisplayedProfileObject );
assert( OT_BandwidthSharing == m_pDisplayedProfileObject->Type() );
((CBandwidthSharingObject*)m_pDisplayedProfileObject)->SetBandwidthSharingType( CLSID_WMBandwidthSharing_Exclusive );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnRBBandwidthTypePartial()
{
assert( m_pDisplayedProfileObject );
assert( OT_BandwidthSharing == m_pDisplayedProfileObject->Type() );
((CBandwidthSharingObject*)m_pDisplayedProfileObject)->SetBandwidthSharingType( CLSID_WMBandwidthSharing_Partial );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTStreamVideoVBRQuality()
{
CString strVBRQuality;
DWORD dwVBRQuality;
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
assert( ST_Video == ((CStream*) m_pDisplayedProfileObject)->GetStreamType() );
assert( BST_CHECKED == m_chkStreamVideoIsVBR.GetCheck() );
assert( VBR_QUALITYBASED == m_cbStreamVideoVBRMode.GetItemData( m_cbStreamVideoVBRMode.GetCurSel() ) );
//
// Set the VBR quality on the video stream
//
m_txtStreamVideoVBRQuality.GetWindowText( strVBRQuality );
dwVBRQuality = _ttol( strVBRQuality );
if ( dwVBRQuality > 100 )
{
dwVBRQuality = 100;
strVBRQuality.Format( _T("%ld"), dwVBRQuality );
m_txtStreamVideoVBRQuality.SetWindowText( strVBRQuality );
}
((CStream*) m_pDisplayedProfileObject)->SetVideoVBRQuality( dwVBRQuality );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnKillfocusTXTBandwidthBufferWindow()
{
CString strBufferWindow;
DWORD dwBufferWindow;
assert( m_pDisplayedProfileObject );
assert( OT_BandwidthSharing == m_pDisplayedProfileObject->Type() );
m_txtBandwidthBufferWindow.GetWindowText( strBufferWindow );
dwBufferWindow = _ttol( strBufferWindow );
((CBandwidthSharingObject*) m_pDisplayedProfileObject)->SetBufferWindow( dwBufferWindow );
}
/*
** Start of helper member functions
*/
///////////////////////////////////////////////////////////////////////////////
BOOL CGenProfileDlg::InBitrateMutex( CStream *pStream )
{
HRESULT hr;
ULONG nDependantCount;
ULONG nDependantIndex;
CProfileObject* pDependant = NULL;
assert( pStream );
//
// Get the number of dependants for the stream
//
nDependantCount = pStream->DependentCount();
//
// Loop through all dependants, looking for a bitrate mutex
//
for ( nDependantIndex = 0; nDependantIndex < nDependantCount; nDependantIndex++ )
{
SAFE_RELEASE( pDependant );
hr = pStream->GetDependent( nDependantIndex, &pDependant );
if ( FAILED( hr ) )
{
return TRUE; // Default to true, because it's safer
}
assert( pDependant );
if ( !pDependant )
{
return TRUE; // Default to true, because it's safer
}
if ( ( OT_Mutex == pDependant->Type() ) && ( ((CMutex*) pDependant)->GetMutexType() == MT_Bitrate ) )
{
return TRUE;
}
}
SAFE_RELEASE( pDependant );
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::DeleteProfileObjectByIndex( INT nCProfileObjectIndex )
{
HRESULT hr = S_OK;
CProfileObject* pProfileObjectToDelete;
do
{
//
// Delete the item's data
//
pProfileObjectToDelete = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nCProfileObjectIndex );
if ( (CProfileObject*) -1 == pProfileObjectToDelete )
{
hr = E_UNEXPECTED;
break;
}
assert( pProfileObjectToDelete );
pProfileObjectToDelete->PrepareForDeletion();
SAFE_RELEASE( pProfileObjectToDelete );
//
// Remove the string from the list
//
m_lstProfileObjects.DeleteString( nCProfileObjectIndex );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::DisplayProfileObject( CProfileObject *pProfileObject )
{
HRESULT hr = S_OK;
do
{
if ( NULL == pProfileObject )
{
ShowStreamWindowPlacement( WINSTREAMCONFIG_NONE );
ShowWindowConfiguration( WINCONFIG_NONE );
}
if ( NULL != pProfileObject )
{
switch ( pProfileObject->Type() )
{
case OT_Stream:
//
// Show the help string
//
DisplayMessage( IDS_Stream_directions );
hr = ShowStream( (CStream*) pProfileObject );
break;
case OT_Mutex:
//
// Show the help string
//
DisplayMessage( IDS_Mutex_directions );
ShowStreamWindowPlacement( WINSTREAMCONFIG_NONE );
hr = ShowMutex( (CMutex*) pProfileObject );
break;
case OT_StreamPrioritization:
//
// Show the help string
//
DisplayMessage( IDS_Prioritization_directions );
ShowStreamWindowPlacement( WINSTREAMCONFIG_NONE );
hr = ShowStreamPrioritizationObject( (CStreamPrioritizationObject*) pProfileObject );
break;
case OT_BandwidthSharing:
//
// Show the help string
//
DisplayMessage( IDS_Bandwidth_directions );
ShowStreamWindowPlacement( WINSTREAMCONFIG_NONE );
hr = ShowBandwidthSharingObject( (CBandwidthSharingObject*) pProfileObject );
break;
default:
assert( !"Unknown object type" );
hr = E_UNEXPECTED;
}
if ( FAILED( hr ) )
{
break;
}
}
m_pDisplayedProfileObject = pProfileObject;
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowStream( CStream *pStream )
{
HRESULT hr = S_OK;
StreamType stStreamType;
assert( pStream );
do
{
//
// Configure the dialog based on stream type
//
stStreamType = pStream->GetStreamType( );
switch ( stStreamType )
{
case ST_Audio:
hr = ShowAudioStream( pStream );
break;
case ST_Video:
hr = ShowVideoStream( pStream );
break;
case ST_Script:
hr = ShowScriptStream( pStream );
break;
case ST_Image:
hr = ShowImageStream( pStream );
break;
case ST_Web:
hr = ShowWebStream( pStream );
break;
case ST_File:
hr = ShowFileStream( pStream );
break;
default:
assert( !"Unknown stream type!" );
hr = E_UNEXPECTED;
break;
}
if ( FAILED( hr ) )
{
break;
}
//
// Show all the stream controls
//
ShowWindowConfiguration( WINCONFIG_STREAM );
ShowStreamWindowPlacement( (DWORD) stStreamType );
//
// Set the controls common to all streams
//
m_chkSMPTE.SetCheck( pStream->GetIsSMPTE() ? BST_CHECKED : BST_UNCHECKED );
hr = PopulateLanguageCB();
if ( FAILED( hr ) )
{
break;
}
SelectLanguage( pStream->GetLanguageLCID() );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowMutex( CMutex *pMutex )
{
HRESULT hr = S_OK;
MUTEX_TYPE mtMutexType;
assert( pMutex );
do
{
//
// Add all the stream objects to the mutex list
//
hr = PopulateListbox( &m_lstMutexStreams, OT_Stream );
if ( FAILED( hr ) )
{
break;
}
hr = SelectDependanciesInListMutex( &m_lstMutexStreams, pMutex );
if ( FAILED( hr ) )
{
break;
}
//
// Select the correct radio button for mutex type
//
mtMutexType = pMutex->GetMutexType( );
switch ( mtMutexType )
{
case MT_Bitrate:
m_rbMutexTypeBitrate.SetCheck( TRUE );
m_rbMutexTypeLanguage.SetCheck( FALSE );
m_rbMutexTypePresentation.SetCheck( FALSE );
break;
case MT_Language:
m_rbMutexTypeBitrate.SetCheck( FALSE );
m_rbMutexTypeLanguage.SetCheck( TRUE );
m_rbMutexTypePresentation.SetCheck( FALSE );
break;
case MT_Presentation:
m_rbMutexTypeBitrate.SetCheck( FALSE );
m_rbMutexTypeLanguage.SetCheck( FALSE );
m_rbMutexTypePresentation.SetCheck( TRUE );
break;
default:
assert( !"Unknown mutex type!" );
hr = E_UNEXPECTED;
}
if ( FAILED( hr ) )
{
break;
}
//
// Show all the mutex controls
//
ShowWindowConfiguration( WINCONFIG_MUTEX );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::ShowDialogItem( DWORD dwResourceID, int nCmdShow )
{
HWND hwndSubItem = NULL;
hwndSubItem = ::GetDlgItem( this->m_hWnd, dwResourceID );
if ( hwndSubItem )
{
::ShowWindow( hwndSubItem, nCmdShow );
}
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowBandwidthSharingObject( CBandwidthSharingObject *pBandwidthSharingObject )
{
HRESULT hr = S_OK;
CString strSharedBitrate;
DWORD dwSharedBitrate;
CString strBufferWindow;
DWORD dwBufferWindow;
if ( !pBandwidthSharingObject )
{
return E_INVALIDARG;
}
do
{
//
// Add all the stream objects to the mutex list
//
hr = PopulateListbox( &m_lstSharingStreams, OT_Stream );
if ( FAILED( hr ) )
{
break;
}
hr = SelectDependanciesInListBandwidth( &m_lstSharingStreams, pBandwidthSharingObject );
if ( FAILED( hr ) )
{
break;
}
dwBufferWindow = pBandwidthSharingObject->GetBufferWindow( );
strBufferWindow.Format( _T("%d"), dwBufferWindow );
m_txtBandwidthBufferWindow.SetWindowText( strBufferWindow );
dwSharedBitrate = pBandwidthSharingObject->GetSharedBitrate( );
strSharedBitrate.Format( _T("%d"), dwSharedBitrate );
m_txtSharedBitrate.SetWindowText( strSharedBitrate );
if ( pBandwidthSharingObject->GetBandwidthSharingType() == CLSID_WMBandwidthSharing_Exclusive )
{
m_rbBandwidthSharingTypeExclusive.SetCheck( TRUE );
m_rbBandwidthSharingTypePartial.SetCheck( FALSE );
}
else
{
m_rbBandwidthSharingTypeExclusive.SetCheck( FALSE );
m_rbBandwidthSharingTypePartial.SetCheck( TRUE );
}
ShowWindowConfiguration( WINCONFIG_BANDWIDTHSHARING );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::ShowWindowConfiguration( DWORD dwConfigurationIndex )
{
int nControlIndex;
HWND hwndControl;
assert( dwConfigurationIndex < NUM_CONFIGS );
do
{
for ( nControlIndex = 0; nControlIndex < NUM_MOVABLE_CONTROLS; nControlIndex++ )
{
hwndControl = ::GetDlgItem( this->m_hWnd, WINDOW_POSITION[dwConfigurationIndex][nControlIndex].dwControl );
if ( hwndControl )
{
::MoveWindow( hwndControl,
WINDOW_POSITION[dwConfigurationIndex][nControlIndex].nX,
WINDOW_POSITION[dwConfigurationIndex][nControlIndex].nY,
WINDOW_POSITION[dwConfigurationIndex][nControlIndex].nWidth,
WINDOW_POSITION[dwConfigurationIndex][nControlIndex].nHeight,
TRUE );
::ShowWindow( hwndControl, WINDOW_POSITION[dwConfigurationIndex][nControlIndex].fVisible ? SW_SHOW : SW_HIDE );
}
}
}
while ( FALSE );
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::PopulateListbox( CListBox *pListBox, ProfileObjectType potRequestedType )
{
HRESULT hr = S_OK;
INT nProfileObjectIndex;
INT nObjectIndex;
CProfileObject* pCurrentObject;
CString strObjectName;
assert( pListBox );
do
{
pListBox->ResetContent();
for ( nProfileObjectIndex = 0; nProfileObjectIndex < m_lstProfileObjects.GetCount(); nProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nProfileObjectIndex );
assert( pCurrentObject );
if ( (CProfileObject*) -1 == pCurrentObject )
{
hr = E_UNEXPECTED;
break;
}
if ( potRequestedType == pCurrentObject->Type() )
{
m_lstProfileObjects.GetText( nProfileObjectIndex, strObjectName );
nObjectIndex = pListBox->AddString( strObjectName );
pListBox->SetItemDataPtr( nObjectIndex, pCurrentObject );
}
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SelectDependanciesInListMutex( CListBox *pListBox, CMutex *pMutex )
{
INT nDependacyCount;
INT nDependancyIndex;
HRESULT hr = S_OK;
CStream* pCurrentObject;
CStream* pPotentialMatch;
INT nMatchingItemIndex;
INT nProfileObjectIndex;
assert( pListBox );
assert( pMutex );
do
{
//
// Select the list box elements that the profile object depends on
//
nDependacyCount = pMutex->StreamCount();
for ( nDependancyIndex = 0; nDependancyIndex < nDependacyCount; nDependancyIndex++ )
{
hr = pMutex->GetStream( nDependancyIndex, &pCurrentObject );
if ( FAILED( hr ) )
{
break;
}
assert( pCurrentObject );
//
// Find the stream on the control that matches the stream in the mutex
//
nMatchingItemIndex = -1;
for ( nProfileObjectIndex = 0; nProfileObjectIndex < pListBox->GetCount(); nProfileObjectIndex++ )
{
pPotentialMatch = (CStream*) pListBox->GetItemDataPtr( nProfileObjectIndex );
assert( pPotentialMatch );
if ( (CStream*) -1 == pPotentialMatch )
{
hr = E_UNEXPECTED;
break;
}
if ( pPotentialMatch == pCurrentObject )
{
nMatchingItemIndex = nProfileObjectIndex;
break;
}
}
if ( FAILED( hr ) )
{
break;
}
if ( -1 != nMatchingItemIndex )
{
if ( LB_ERR == pListBox->SetSel( nMatchingItemIndex, TRUE ) )
{
hr = E_UNEXPECTED;
break;
}
}
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SelectDependanciesInListBandwidth( CListBox *pListBox, CBandwidthSharingObject* pBandwidthSharingObject )
{
INT nDependacyCount;
INT nDependancyIndex;
HRESULT hr = S_OK;
CStream* pCurrentObject;
CStream* pPotentialMatch;
INT nMatchingItemIndex;
INT nProfileObjectIndex;
assert( pListBox );
assert( pBandwidthSharingObject );
do
{
//
// Select the list box elements that the profile object depends on
//
nDependacyCount = pBandwidthSharingObject->StreamCount();
for ( nDependancyIndex = 0; nDependancyIndex < nDependacyCount; nDependancyIndex++ )
{
hr = pBandwidthSharingObject->GetStream( nDependancyIndex, &pCurrentObject );
if ( FAILED( hr ) )
{
break;
}
assert( pCurrentObject );
//
// Find the stream on the control that matches the stream in the mutex
//
nMatchingItemIndex = -1;
for ( nProfileObjectIndex = 0; nProfileObjectIndex < pListBox->GetCount(); nProfileObjectIndex++ )
{
pPotentialMatch = (CStream*) pListBox->GetItemDataPtr( nProfileObjectIndex );
assert( pPotentialMatch );
if ( (CStream*) -1 == pPotentialMatch )
{
hr = E_UNEXPECTED;
break;
}
if ( pPotentialMatch == pCurrentObject )
{
nMatchingItemIndex = nProfileObjectIndex;
break;
}
}
if ( FAILED( hr ) )
{
break;
}
if ( -1 != nMatchingItemIndex )
{
if ( LB_ERR == pListBox->SetSel( nMatchingItemIndex, TRUE ) )
{
hr = E_UNEXPECTED;
break;
}
}
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowStreamPrioritizationObject( CStreamPrioritizationObject *pStreamPrioritizationObject )
{
HRESULT hr = S_OK;
INT nStreamIndex;
CStream* pStream;
BOOL fStreamIsMandatory;
if ( !pStreamPrioritizationObject )
{
return E_INVALIDARG;
}
do
{
hr = RefreshStreamPriorityList( pStreamPrioritizationObject );
if ( FAILED( hr ) )
{
break;
}
//
// Show mandatory streams, then select the ones that are mandatory
//
hr = PopulateListbox( &m_lstMandatoryStreams, OT_Stream );
if ( FAILED( hr ) )
{
break;
}
for ( nStreamIndex = 0; nStreamIndex < m_lstMandatoryStreams.GetCount(); nStreamIndex++ )
{
pStream = (CStream*) m_lstMandatoryStreams.GetItemDataPtr( nStreamIndex );
assert( pStream );
if ( (CStream*) -1 == pStream )
{
hr = E_UNEXPECTED;
break;
}
hr = pStreamPrioritizationObject->GetStreamMandatory( pStream, &fStreamIsMandatory );
if ( FAILED( hr ) )
{
break;
}
if ( fStreamIsMandatory )
{
if ( LB_ERR == m_lstMandatoryStreams.SetSel( nStreamIndex, TRUE ) )
{
hr = E_UNEXPECTED;
break;
}
}
}
if ( FAILED( hr ) )
{
break;
}
ShowWindowConfiguration( WINCONFIG_STREAMPRIORITIZATION );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::RefreshStreamPriorityList( CStreamPrioritizationObject *pPriorityObject )
{
HRESULT hr = S_OK;
CStream* pStream = NULL;
INT nStreamIndex;
INT nStreamCount;
CString strStreamName;
INT nNewItemIndex;
do
{
//
// Add all the stream objects to the mutex list
//
nStreamCount = pPriorityObject->StreamCount();
m_lstPrioritizationStreams.ResetContent();
for ( nStreamIndex = 0; nStreamIndex < nStreamCount; nStreamIndex++ )
{
SAFE_RELEASE( pStream );
hr = pPriorityObject->GetStreamWithPriority( nStreamIndex, &pStream );
if ( FAILED( hr ) )
{
break;
}
assert( pStream );
if( NULL == pStream )
{
hr = E_UNEXPECTED;
break;
}
strStreamName = pStream->GetName();
nNewItemIndex = m_lstPrioritizationStreams.AddString( strStreamName );
if ( LB_ERR != nNewItemIndex )
{
m_lstPrioritizationStreams.SetItemDataPtr( nNewItemIndex, pStream );
}
else
{
hr = E_UNEXPECTED;
break;
}
}
}
while ( FALSE );
SAFE_RELEASE( pStream );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
bool CGenProfileDlg::StreamPrioritizationObjectExists()
{
INT nProfileObjectIndex;
CProfileObject* pCurrentObject;
CString strObjectName;
do
{
for ( nProfileObjectIndex = 0; nProfileObjectIndex < m_lstProfileObjects.GetCount(); nProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nProfileObjectIndex );
assert( pCurrentObject );
if ( (CProfileObject*) -1 == pCurrentObject )
{
DisplayMessage( IDS_Fatal_error );
break;
}
if ( OT_StreamPrioritization == pCurrentObject->Type() )
{
return true;
}
}
}
while ( FALSE );
return false;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowStreamWindowPlacement( DWORD dwStreamType )
{
int nControlIndex;
HWND hwndControl;
assert( dwStreamType < NUM_STREAMTYPES );
do
{
for ( nControlIndex = 0; nControlIndex < NUM_STREAM_CONTROLS; nControlIndex++ )
{
hwndControl = ::GetDlgItem( this->m_hWnd, STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].dwControl );
if ( hwndControl )
{
::MoveWindow( hwndControl,
STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].nX,
STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].nY,
STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].nWidth,
STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].nHeight,
TRUE );
::ShowWindow( hwndControl, STREAM_WINDOW_POSITION[dwStreamType][nControlIndex].fVisible ? SW_SHOW : SW_HIDE );
}
}
}
while ( FALSE );
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowAudioStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
DWORD dwCodecCount;
DWORD dwCodecIndex;
LPWSTR wszCodecName = NULL;
CString strCodecName;
DWORD dwCodecNameLength;
INT nCodecStringIndex;
DWORD dwStreamFormatIndex;
CString strBufferWindow;
CString strStreamType;
BOOL fIsUncompressedStream;
assert( pStream );
assert( ST_Audio == pStream->GetStreamType() );
assert( m_pCodecInfo );
assert( m_bIsAudioCodec );
do
{
//
// Select "audio" in the stream type combo box
//
strStreamType.LoadString( IDS_Audio );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
if ( CB_ERR == nStreamTypeIndex )
{
hr = E_UNEXPECTED;
break;
}
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// If the stream is uncompressed, then show it appropriately
//
m_chkStreamIsUncompressed.EnableWindow( TRUE );
fIsUncompressedStream = pStream->GetIsUncompressed();
m_chkStreamIsUncompressed.SetCheck( pStream->GetIsUncompressed() ? BST_CHECKED : BST_UNCHECKED );
if ( !fIsUncompressedStream )
{
//
// Enable controls that are relevant to compressed streams
//
m_cbStreamCodec.EnableWindow( TRUE );
m_txtStreamBitrate.EnableWindow( TRUE );
m_txtStreamBufferWindow.EnableWindow( TRUE );
//
// Get number of audio codecs installed on machine
//
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Audio, &dwCodecCount );
if ( FAILED( hr ) )
{
break;
}
assert( dwCodecCount > 0 );
//
// Populate the codec type with the installed audio codecs
//
m_cbStreamCodec.ResetContent();
for ( dwCodecIndex = 0; dwCodecIndex < dwCodecCount; dwCodecIndex++ )
{
//
// Get the name for the codec
//
dwCodecNameLength = 0;
hr = m_pCodecInfo->GetCodecName( WMMEDIATYPE_Audio, dwCodecIndex, NULL, &dwCodecNameLength );
if ( FAILED( hr ) )
{
break;
}
SAFE_ARRAYDELETE( wszCodecName );
wszCodecName = new WCHAR[ dwCodecNameLength + 1 ];
if ( !wszCodecName )
{
hr = E_OUTOFMEMORY;
break;
}
hr = m_pCodecInfo->GetCodecName( WMMEDIATYPE_Audio, dwCodecIndex, wszCodecName, &dwCodecNameLength );
if ( FAILED( hr ) )
{
break;
}
wszCodecName[ dwCodecNameLength ] = L'\0'; // terminate the codec name, just in case
strCodecName.Format( _T( "%ls" ), wszCodecName );
nCodecStringIndex = m_cbStreamCodec.AddString( strCodecName );
if ( CB_ERR == nCodecStringIndex )
{
hr = E_UNEXPECTED;
break;
}
m_cbStreamCodec.SetItemData( nCodecStringIndex, dwCodecIndex );
}
if ( FAILED( hr ) )
{
break;
}
//
// Select the appropriate audio format in the format type combo box
//
nCodecStringIndex = pStream->GetStreamCodecIndex();
assert( (DWORD) nCodecStringIndex < dwCodecCount );
m_cbStreamCodec.SetCurSel( nCodecStringIndex );
//
// Populate the format combo box based on the selected codec
//
dwCodecIndex = ( DWORD )( m_cbStreamCodec.GetItemData( nCodecStringIndex ) );
assert( CB_ERR != dwCodecIndex );
if ( CB_ERR == dwCodecIndex )
{
dwCodecIndex = 0;
pStream->SetStreamCodecIndex( dwCodecIndex );
}
hr = PopulateAudioFormatCB( dwCodecIndex );
if ( FAILED( hr ) )
{
break;
}
//
// Select the format matching the stream
//
dwStreamFormatIndex = pStream->GetStreamFormatStringIndex();
assert( dwStreamFormatIndex < (DWORD) m_cbStreamFormat.GetCount() );
m_cbStreamFormat.SetCurSel( dwStreamFormatIndex );
}
else
{
//
// Disable controls that are irrelevant to uncompressed streams
//
m_cbStreamCodec.EnableWindow( FALSE );
m_txtStreamBitrate.EnableWindow( FALSE );
m_txtStreamBufferWindow.EnableWindow( FALSE );
hr = PopulateWaveFormatCB();
if ( FAILED( hr ) )
{
break;
}
DWORD dwWaveFormatIndex = pStream->GetWaveFormatStringIndex();
assert( dwWaveFormatIndex < (DWORD) m_cbStreamFormat.GetCount() );
m_cbStreamFormat.SetCurSel( dwWaveFormatIndex );
pStream->SetWaveFormatIndex( ( DWORD )( m_cbStreamFormat.GetItemData( dwWaveFormatIndex ) ) );
}
//
// Make all the controls reflect the values in pStream
//
strBufferWindow.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strBufferWindow );
}
while ( FALSE );
SAFE_ARRAYDELETE( wszCodecName );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::PopulatePixleFormatCB()
{
HRESULT hr = S_OK;
DWORD dwFormatCount;
if ( m_cbPixelFormat.GetCount() > 0 )
{
// Pixel format list has been initialized.
return hr;
}
hr = GetUncompressedPixelFormatCount( &dwFormatCount );
if ( FAILED( hr ) )
{
return hr;
}
for ( DWORD i = 0; i < dwFormatCount; i ++ )
{
GUID guidFormat;
DWORD dwFourCC;
WORD wBitsPerPixel;
hr = GetUncompressedPixelFormat( i, &guidFormat, &dwFourCC, &wBitsPerPixel );
if ( FAILED( hr ) )
{
break;
}
if ( wBitsPerPixel > 8 )
{
TCHAR tszName[16];
if ( dwFourCC == BI_RGB )
{
(void)StringCchPrintf( tszName, ARRAYSIZE(tszName), _T("RGB%d"), (DWORD)wBitsPerPixel );
}
else if ( dwFourCC == BI_BITFIELDS )
{
assert( FALSE );
}
else
{
(void)StringCchPrintf( tszName, ARRAYSIZE(tszName), _T("%c%c%c%c"),
(char)(dwFourCC & 0xFF),
(char)( (dwFourCC>>8) & 0xFF),
(char)( (dwFourCC>>16) & 0xFF),
(char)( (dwFourCC>>24) & 0xFF) );
}
int nIndex = m_cbPixelFormat.AddString( tszName );
m_cbPixelFormat.SetItemData( nIndex, i );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::PopulateAudioFormatCB( DWORD dwCodecIndex )
{
HRESULT hr = S_OK;
CString strFormatName;
assert( m_bIsAudioCodec );
do
{
m_cbStreamFormat.ResetContent();
hr = AddAudioFormatsToCB( FALSE, 0, dwCodecIndex );
if ( FAILED( hr ) )
{
break;
}
hr = AddAudioFormatsToCB( TRUE, 1, dwCodecIndex );
if ( FAILED( hr ) )
{
break;
}
hr = AddAudioFormatsToCB( TRUE, 2, dwCodecIndex );
if ( FAILED( hr ) )
{
break;
}
assert( m_cbStreamFormat.GetCount() > 0 );
}
while ( FALSE );
return hr;
}
HRESULT CGenProfileDlg::PopulateWaveFormatCB()
{
HRESULT hr = S_OK;
DWORD dwFormatCount;
m_cbStreamFormat.ResetContent();
hr = GetUncompressedWaveFormatCount( &dwFormatCount );
if ( FAILED( hr ) )
{
return hr;
}
for ( DWORD i = 0; i < dwFormatCount; i ++ )
{
DWORD dwSamplesPerSecond;
WORD wNumChannels;
WORD wBitsPerSample;
hr = GetUncompressedWaveFormat( i,
&dwSamplesPerSecond,
&wNumChannels,
&wBitsPerSample );
if ( FAILED( hr ) )
{
break;
}
CString csFormat;
if ( wNumChannels == 1 )
{
csFormat.Format( _T("%d Hz, %d Bits, Mono"),
dwSamplesPerSecond, (DWORD)wBitsPerSample );
}
else if ( wNumChannels == 2 )
{
csFormat.Format( _T("%d Hz, %d Bits, Stereo"),
dwSamplesPerSecond, (DWORD)wBitsPerSample );
}
else
{
csFormat.Format( _T("%d Hz, %d Bits, %d Channels"),
dwSamplesPerSecond, (DWORD)wBitsPerSample, (DWORD)wNumChannels );
}
int nIndex = m_cbStreamFormat.AddString( csFormat );
m_cbStreamFormat.SetItemData( nIndex, i );
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddAudioFormatsToCB( BOOL fIsVBR, DWORD dwNumVBRPasses, DWORD dwCodecIndex )
{
HRESULT hr = S_OK;
DWORD dwFormatCount;
DWORD dwFormatIndex;
CString strFormatName;
DWORD nFormatStringIndex;
LPWSTR wszFormatName = NULL;
DWORD dwFormatNameLength;
DWORD dwVBROffset;
assert( m_pCodecInfo );
assert( m_bIsAudioCodec );
do
{
//
// Turn on the VBR formats, and get the format count
//
dwFormatCount = GetNumberOfFormatsSupported( WMMEDIATYPE_Audio, dwCodecIndex, fIsVBR, dwNumVBRPasses );
//
// Loop through all formats using given VBR settings, and add them to the combo box
//
for ( dwFormatIndex = 0; dwFormatIndex < dwFormatCount; dwFormatIndex++ )
{
//
// Calculate a dwVBROffset, which is used to keep track if the format is VBR and how many passes
//
dwVBROffset = fIsVBR ? VBR_OFFSET * dwNumVBRPasses : 0;
//
// Get the name for the given format from the codec
//
hr = m_pCodecInfo->GetCodecFormatDesc( WMMEDIATYPE_Audio, dwCodecIndex, dwFormatIndex, NULL, NULL, &dwFormatNameLength );
if ( FAILED( hr ) )
{
break;
}
SAFE_ARRAYDELETE( wszFormatName );
hr = ULongAdd( dwFormatNameLength, 1, &dwFormatNameLength );
if ( FAILED( hr ) )
{
break;
}
wszFormatName = new WCHAR[ dwFormatNameLength ];
if ( !wszFormatName )
{
hr = E_OUTOFMEMORY;
break;
}
hr = m_pCodecInfo->GetCodecFormatDesc( WMMEDIATYPE_Audio, dwCodecIndex, dwFormatIndex, NULL, wszFormatName, &dwFormatNameLength );
if ( FAILED( hr ) )
{
break;
}
//
// Add the format to the combo box
//
strFormatName.Format( _T("%ls"), wszFormatName );
nFormatStringIndex = m_cbStreamFormat.AddString( strFormatName );
if ( CB_ERR == nFormatStringIndex )
{
continue;
}
m_cbStreamFormat.SetItemData( nFormatStringIndex, dwFormatIndex + dwVBROffset );
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_ARRAYDELETE( wszFormatName );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForAudioStream( CStream *pStream )
{
HRESULT hr = S_OK;
DWORD dwCodecIndex;
DWORD dwCodecCount;
BOOL fFormatFound;
CString strMessage;
assert( pStream );
assert( m_bIsAudioCodec );
do
{
//
// Set type to audio
//
pStream->SetStreamType( ST_Audio );
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Audio, &dwCodecCount );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
break;
}
assert( dwCodecCount > 0 );
pStream->SetStreamFormatStringIndex( 0 );
fFormatFound = FALSE;
for ( dwCodecIndex = 0; dwCodecIndex < dwCodecCount; dwCodecIndex++ )
{
//
// Set the codec
//
pStream->SetStreamCodecIndex( dwCodecIndex );
//
// Set format to an existing value
//
if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Audio, dwCodecIndex, FALSE, 0 ) > 0 )
{
pStream->SetStreamFormatIndex( 0 );
fFormatFound = TRUE;
break;
}
else if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Audio, dwCodecIndex, TRUE, 1 ) > 0 )
{
pStream->SetStreamFormatIndex( VBR_OFFSET );
fFormatFound = TRUE;
break;
}
else if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Audio, dwCodecIndex, TRUE, 2 ) > 0 )
{
pStream->SetStreamFormatIndex( 2 * VBR_OFFSET );
fFormatFound = TRUE;
break;
}
}
if ( !fFormatFound )
{
hr = E_FAIL;
DisplayMessage( IDS_No_audio_formats_error );
break;
}
//
// Set other values to defaults
//
pStream->SetStreamBufferWindow( 3000 );
pStream->SetIsSMPTE( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForVideoStream( CStream *pStream )
{
HRESULT hr = S_OK;
DWORD dwCodecIndex;
DWORD dwCodecCount;
BOOL fFormatFound;
CString strMessage;
assert( pStream );
assert( m_pCodecInfo );
assert( m_bIsVideoCodec );
do
{
//
// Set type to video
//
pStream->SetStreamType( ST_Video );
//
// Get the number of video codecs
//
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Video, &dwCodecCount );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
break;
}
assert( dwCodecCount > 0 );
fFormatFound = FALSE;
for ( dwCodecIndex = 0; dwCodecIndex < dwCodecCount; dwCodecIndex++ )
{
//
// Set the codec
//
pStream->SetStreamCodecIndex( dwCodecIndex );
//
// Set format to an existing value
//
if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Video, dwCodecIndex, FALSE, 0 ) > 0 )
{
pStream->SetVideoIsVBR( FALSE );
pStream->SetVideoVBRMode( VBR_QUALITYBASED );
fFormatFound = TRUE;
break;
}
else if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Video, dwCodecIndex, TRUE, 1 ) > 0 )
{
pStream->SetVideoIsVBR( TRUE );
pStream->SetVideoVBRMode( VBR_QUALITYBASED );
fFormatFound = TRUE;
break;
}
else if ( GetNumberOfFormatsSupported( WMMEDIATYPE_Video, dwCodecIndex, TRUE, 2 ) > 0 )
{
pStream->SetVideoIsVBR( TRUE );
pStream->SetVideoVBRMode( VBR_UNCONSTRAINED );
fFormatFound = TRUE;
break;
}
}
if ( !fFormatFound )
{
hr = E_FAIL;
DisplayMessage( IDS_No_video_formats_error );
break;
}
//
// Set other values to defaults
//
pStream->SetStreamBitrate( 100000 );
pStream->SetStreamBufferWindow( 3000 );
pStream->SetVideoWidth( 320 );
pStream->SetVideoHeight( 240 );
pStream->SetVideoFPS( 30 );
pStream->SetVideoSecondsPerKeyframe( 8 );
pStream->SetVideoQuality( 100 );
pStream->SetVideoMaxBitrate( 1000000 );
pStream->SetVideoMaxBufferWindow( 0 );
pStream->SetIsSMPTE( FALSE );
pStream->SetVideoVBRQuality( 0 );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowVideoStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
DWORD dwCodecCount;
DWORD dwCodecIndex;
LPWSTR wszCodecName = NULL;
CString strCodecName;
DWORD dwCodecNameLength;
INT nCodecStringIndex;
CString strBufferWindow;
CString strVideoValue;
CString strStreamType;
BOOL fIsUncompressedStream;
assert( pStream );
assert( ST_Video == pStream->GetStreamType() );
assert( m_pCodecInfo );
assert( m_bIsVideoCodec );
do
{
//
// Select "video" in the stream type combo box
//
strStreamType.LoadString( IDS_Video );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// If the stream is uncompressed, then show it appropriately
//
m_chkStreamIsUncompressed.EnableWindow( TRUE );
fIsUncompressedStream = pStream->GetIsUncompressed();
m_chkStreamIsUncompressed.SetCheck( fIsUncompressedStream ? BST_CHECKED : BST_UNCHECKED );
if ( !fIsUncompressedStream )
{
//
// Enable controls that are relevant to compressed streams
//
m_cbStreamCodec.EnableWindow( TRUE );
m_txtStreamBitrate.EnableWindow( TRUE );
m_txtStreamVideoQuality.EnableWindow( TRUE );
m_txtStreamVideoSecondsPerKeyframe.EnableWindow( TRUE );
m_txtStreamBufferWindow.EnableWindow( TRUE );
//
// Get the number of video codecs installed on machine
//
hr = m_pCodecInfo->GetCodecInfoCount( WMMEDIATYPE_Video, &dwCodecCount );
if ( FAILED( hr ) )
{
break;
}
assert( dwCodecCount > 0 );
//
// Populate the codec type with the installed video codecs
//
m_cbStreamCodec.ResetContent();
for ( dwCodecIndex = 0; dwCodecIndex < dwCodecCount; dwCodecIndex++ )
{
dwCodecNameLength = 4;
hr = m_pCodecInfo->GetCodecName( WMMEDIATYPE_Video, dwCodecIndex, NULL, &dwCodecNameLength );
if ( FAILED( hr ) )
{
break;
}
SAFE_ARRAYDELETE( wszCodecName );
wszCodecName = new WCHAR[ dwCodecNameLength + 1 ];
if ( !wszCodecName )
{
hr = E_OUTOFMEMORY;
break;
}
hr = m_pCodecInfo->GetCodecName( WMMEDIATYPE_Video, dwCodecIndex, wszCodecName, &dwCodecNameLength );
if ( FAILED( hr ) )
{
break;
}
wszCodecName[ dwCodecNameLength ] = L'\0'; // terminate the codec name, just in case
strCodecName.Format( _T( "%ls" ), wszCodecName );
nCodecStringIndex = m_cbStreamCodec.AddString( strCodecName );
if ( CB_ERR == nCodecStringIndex )
{
continue;
}
m_cbStreamCodec.SetItemData( nCodecStringIndex, dwCodecIndex );
}
if ( FAILED( hr ) )
{
break;
}
//
// Set the values of the controls that are relvant to compressd video
//
dwCodecIndex = pStream->GetStreamCodecIndex();
m_cbStreamCodec.SetCurSel( dwCodecIndex );
hr = DisplayVBRControlsForCodec( dwCodecIndex, pStream );
if ( FAILED( hr ) )
{
break;
}
strVideoValue.Format( _T("%ld"), pStream->GetStreamBitrate() );
m_txtStreamBitrate.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoQuality() );
m_txtStreamVideoQuality.SetWindowText( strVideoValue );
m_cbPixelFormat.EnableWindow( FALSE );
}
else
{
//
// Disable controls that are irrelevant to uncompressed streams
//
m_cbStreamCodec.EnableWindow( FALSE );
m_txtStreamBitrate.EnableWindow( FALSE );
m_txtStreamVideoQuality.EnableWindow( FALSE );
m_txtStreamVideoSecondsPerKeyframe.EnableWindow( FALSE );
m_txtStreamBufferWindow.EnableWindow( FALSE );
DisableVideoVBRControls();
hr = PopulatePixleFormatCB();
if ( FAILED( hr ) )
{
break;
}
m_cbPixelFormat.EnableWindow( TRUE );
DWORD dwPixelFormatStringIndex = pStream->GetPixelFormatStringIndex();
m_cbPixelFormat.SetCurSel( dwPixelFormatStringIndex );
pStream->SetPixelFormatIndex( ( DWORD )( m_cbPixelFormat.GetItemData( dwPixelFormatStringIndex ) ) );
}
//
// Make all the controls reflect the values in pStream
//
strBufferWindow.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strBufferWindow );
strVideoValue.Format( _T("%ld"), pStream->GetVideoWidth() );
m_txtStreamVideoWidth.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoHeight() );
m_txtStreamVideoHeight.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoFPS() );
m_txtStreamVideoFPS.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoSecondsPerKeyframe() );
m_txtStreamVideoSecondsPerKeyframe.SetWindowText( strVideoValue );
}
while ( FALSE );
SAFE_ARRAYDELETE( wszCodecName );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::DisplayMessage( UINT nStringResourceIndex )
{
CString strMessage;
if ( !strMessage.LoadString( nStringResourceIndex ) )
{
if ( !strMessage.LoadString( IDS_String_load_error ) )
{
MessageBox( _T("Error loading string resources!"), _T("An error occured!") );
}
}
m_txtHelp.SetWindowText( strMessage );
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForScriptStream( CStream *pStream )
{
HRESULT hr = S_OK;
assert( pStream );
do
{
//
// Set stream type
//
pStream->SetStreamType( ST_Script );
//
// Set other values to defaults
//
pStream->SetStreamBitrate( 1000 );
pStream->SetStreamBufferWindow( 3000 );
pStream->SetIsSMPTE( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowScriptStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
CString strVideoValue;
CString strStreamType;
assert( pStream );
assert( ST_Script == pStream->GetStreamType() );
do
{
//
// Select "script" in the stream type combo box
//
strStreamType.LoadString( IDS_Script );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// Make all the controls reflect the values in pStream
//
strVideoValue.Format( _T("%ld"), pStream->GetStreamBitrate() );
m_txtStreamBitrate.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strVideoValue );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForImageStream( CStream *pStream )
{
HRESULT hr = S_OK;
assert( pStream );
do
{
//
// Set stream type
//
pStream->SetStreamType( ST_Image );
//
// Set other values to defaults
//
pStream->SetStreamBitrate( 1000 );
pStream->SetStreamBufferWindow( 3000 );
pStream->SetVideoWidth( 320 );
pStream->SetVideoHeight( 200 );
pStream->SetIsSMPTE( FALSE );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowImageStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
CString strVideoValue;
CString strStreamType;
assert( pStream );
assert( ST_Image == pStream->GetStreamType() );
do
{
//
// Select "Image" in the stream type combo box
//
strStreamType.LoadString( IDS_Image );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// Make all the controls reflect the values in pStream
//
strVideoValue.Format( _T("%ld"), pStream->GetStreamBitrate() );
m_txtStreamBitrate.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoWidth() );
m_txtStreamVideoWidth.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetVideoHeight() );
m_txtStreamVideoHeight.SetWindowText( strVideoValue );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForWebStream( CStream *pStream )
{
HRESULT hr = S_OK;
assert( pStream );
do
{
//
// Set stream type
//
pStream->SetStreamType( ST_Web );
//
// Set other values to defaults
//
pStream->SetStreamBitrate( 50000 );
pStream->SetStreamBufferWindow( 3000 );
pStream->SetIsSMPTE( FALSE );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowWebStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
CString strVideoValue;
CString strStreamType;
assert( pStream );
assert( ST_Web == pStream->GetStreamType() );
do
{
//
// Select "web" in the stream type combo box
//
strStreamType.LoadString( IDS_Web );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// Make all the controls reflect the values in pStream
//
strVideoValue.Format( _T("%ld"), pStream->GetStreamBitrate() );
m_txtStreamBitrate.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strVideoValue );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetDefaultsForFileStream( CStream *pStream )
{
HRESULT hr = S_OK;
assert( pStream );
do
{
//
// Set stream type
//
pStream->SetStreamType( ST_File );
//
// Set other values to defaults
//
pStream->SetStreamBitrate( 50000 );
pStream->SetStreamBufferWindow( 3000 );
pStream->SetIsSMPTE( FALSE );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::ShowFileStream( CStream *pStream )
{
HRESULT hr = S_OK;
INT nStreamTypeIndex;
CString strVideoValue;
CString strStreamType;
assert( pStream );
assert( ST_File == pStream->GetStreamType() );
do
{
//
// Select "File" in the stream type combo box
//
strStreamType.LoadString( IDS_File );
nStreamTypeIndex = m_cbStreamType.FindStringExact( -1, strStreamType );
assert( CB_ERR != nStreamTypeIndex );
m_cbStreamType.SetCurSel( nStreamTypeIndex );
//
// Make all the controls reflect the values in pStream
//
strVideoValue.Format( _T("%ld"), pStream->GetStreamBitrate() );
m_txtStreamBitrate.SetWindowText( strVideoValue );
strVideoValue.Format( _T("%ld"), pStream->GetStreamBufferWindow() );
m_txtStreamBufferWindow.SetWindowText( strVideoValue );
m_chkStreamIsUncompressed.SetCheck( BST_CHECKED );
m_chkStreamIsUncompressed.EnableWindow( FALSE );
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::CodecSupportsVBRSetting( GUID guidType, DWORD dwCodecIndex, DWORD dwPasses, BOOL* pbIsSupported )
{
HRESULT hr = S_OK;
assert( pbIsSupported );
assert( m_pCodecInfo );
do
{
*pbIsSupported = FALSE; // default to "no"
//
// Try setting the requested settings
//
hr = SetCodecVBRSettings( m_pCodecInfo, guidType, dwCodecIndex, TRUE, dwPasses );
if ( FAILED( hr ) )
{
hr = S_OK;
break;
}
//
// If it worked, then the codec should support it
//
*pbIsSupported = TRUE;
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::RemoveStreamFromAllMutexes( CStream *pStream )
{
HRESULT hr = S_OK;
INT nObjectCount;
INT nObjectIndex;
CProfileObject* pCurrentObject;
assert( pStream );
do
{
nObjectCount = m_lstProfileObjects.GetCount();
if ( LB_ERR == nObjectCount )
{
hr = E_UNEXPECTED;
break;
}
//
// Loop through all the objects in the object list and remove the stream from each mutex
//
for ( nObjectIndex = 0; nObjectIndex < nObjectCount; nObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( nObjectIndex );
assert( pCurrentObject );
if ( (CProfileObject*) -1 == pCurrentObject )
{
hr = E_UNEXPECTED;
break;
}
if ( OT_Mutex == pCurrentObject->Type() )
{
hr = ((CMutex*) pCurrentObject)->RemoveStream( pStream );
if ( FAILED( hr ) )
{
break;
}
}
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::DisplayVBRControlsForCodec( DWORD dwCodecIndex, CStream* pStream )
{
HRESULT hr = S_OK;
BOOL fSupportsVBR;
BOOL fSupports2Pass;
BOOL fIsVBR;
INT nVBRModeIndex;
DWORD dwMaxBitrate;
DWORD dwMaxBufferWindow;
CString strValue;
INT nNewStringIndex;
CString strVBRType;
assert( pStream );
do
{
hr = CodecSupportsVBRSetting( WMMEDIATYPE_Video, dwCodecIndex, 1, &fSupportsVBR );
if ( FAILED( hr ) )
{
break;
}
if ( fSupportsVBR )
{
//
// Check for 2 pass VBR
//
hr = CodecSupportsVBRSetting( WMMEDIATYPE_Video, dwCodecIndex, 2, &fSupports2Pass );
if ( FAILED( hr ) )
{
break;
}
//
// Setup the combo box to display the correct results
//
m_cbStreamVideoVBRMode.ResetContent();
strVBRType.LoadString( IDS_Quality_based_VBR );
nNewStringIndex = m_cbStreamVideoVBRMode.AddString( strVBRType );
m_cbStreamVideoVBRMode.SetItemData( nNewStringIndex, VBR_QUALITYBASED );
if ( fSupports2Pass )
{
strVBRType.LoadString( IDS_Constrained_VBR );
nNewStringIndex = m_cbStreamVideoVBRMode.AddString( strVBRType );
m_cbStreamVideoVBRMode.SetItemData( nNewStringIndex, VBR_CONSTRAINED );
strVBRType.LoadString( IDS_Unconstrained_VBR );
nNewStringIndex = m_cbStreamVideoVBRMode.AddString( strVBRType );
m_cbStreamVideoVBRMode.SetItemData( nNewStringIndex, VBR_UNCONSTRAINED );
}
fIsVBR = pStream->GetVideoIsVBR();
nVBRModeIndex = pStream->GetVideoVBRMode();
m_chkStreamVideoIsVBR.EnableWindow( TRUE );
m_chkStreamVideoIsVBR.SetCheck( fIsVBR ? BST_CHECKED : BST_UNCHECKED );
m_cbStreamVideoVBRMode.EnableWindow( fIsVBR );
hr = SelectItemWithData( &m_cbStreamVideoVBRMode, nVBRModeIndex );
if ( FAILED( hr ) )
{
break;
}
if ( fIsVBR )
{
switch ( nVBRModeIndex )
{
case VBR_QUALITYBASED:
m_chkStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoMaxBitrate.EnableWindow( FALSE );
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoVBRQuality.EnableWindow( TRUE );
strValue.Format( _T("%ld"), pStream->GetVideoVBRQuality() );
m_txtStreamVideoVBRQuality.SetWindowText( strValue );
break;
case VBR_CONSTRAINED:
assert( fSupports2Pass );
dwMaxBitrate = pStream->GetVideoMaxBitrate();
strValue.Format( _T("%ld"), dwMaxBitrate );
m_txtStreamVideoMaxBitrate.SetWindowText( strValue );
m_txtStreamVideoMaxBitrate.EnableWindow( TRUE );
m_txtStreamVideoVBRQuality.EnableWindow( FALSE );
dwMaxBufferWindow = pStream->GetVideoMaxBufferWindow();
if ( dwMaxBufferWindow != 0 )
{
strValue.Format( _T("%ld"), dwMaxBufferWindow );
m_txtStreamVideoMaxBufferWindow.SetWindowText( strValue );
m_txtStreamVideoMaxBufferWindow.EnableWindow( TRUE );
m_chkStreamVideoMaxBufferWindow.SetCheck( BST_CHECKED );
}
else
{
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_chkStreamVideoMaxBufferWindow.SetCheck( BST_UNCHECKED );
}
m_chkStreamVideoMaxBufferWindow.EnableWindow( TRUE );
break;
case VBR_UNCONSTRAINED:
assert( fSupports2Pass );
m_chkStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoMaxBitrate.EnableWindow( FALSE );
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoVBRQuality.EnableWindow( FALSE );
break;
default:
assert( !"Unknown VBR index!");
hr = E_UNEXPECTED;
break;
}
if ( FAILED( hr ) )
{
break;
}
}
else
{
m_chkStreamVideoIsVBR.SetCheck( BST_UNCHECKED );
m_cbStreamVideoVBRMode.EnableWindow( FALSE );
m_chkStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoMaxBitrate.EnableWindow( FALSE );
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoVBRQuality.EnableWindow( FALSE );
}
}
else
{
assert( !pStream->GetVideoIsVBR() );
DisableVideoVBRControls();
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::CreateProfile( IWMProfile **ppProfile )
{
HRESULT hr = S_OK;
IWMProfile* pProfile = NULL;
IWMProfile3* pProfile3 = NULL;
IWMProfileManager* pProfileManager = NULL;
CProfileObject* pCurrentObject;
WORD wStreamCount;
WORD wStreamIndex;
WORD wMutexCount;
WORD wPrioritizationRecordCount;
WORD wBandwidthSharingCount;
DWORD dwProfileObjectIndex;
DWORD dwProfileObjectCount;
WM_STREAM_PRIORITY_RECORD* aStreamPriorityRecords = NULL;
IWMStreamPrioritization* pStreamPrioritization = NULL;
CString strProfileName;
LPWSTR wszProfileName = NULL;
DWORD dwProfileNameLength;
assert( ppProfile );
do
{
//
// Give each stream a number, and count the number of each object type
//
dwProfileObjectCount = m_lstProfileObjects.GetCount();
wStreamIndex = 0;
wMutexCount = 0;
wPrioritizationRecordCount = 0;
wBandwidthSharingCount = 0;
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
switch ( pCurrentObject->Type() )
{
case OT_Stream:
wStreamIndex++;
((CStream*) pCurrentObject)->SetStreamNumber( wStreamIndex );
break;
case OT_Mutex:
wMutexCount++;
break;
case OT_StreamPrioritization:
wPrioritizationRecordCount++;
break;
case OT_BandwidthSharing:
wBandwidthSharingCount++;
break;
default:
assert( !"Unknown profile object type!" );
hr = E_UNEXPECTED;
break;
}
if ( FAILED( hr ) )
{
break;
}
}
if ( FAILED( hr ) )
{
break;
}
wStreamCount = wStreamIndex;
//
// Create the profile manager and a new profile
//
hr = WMCreateProfileManager( &pProfileManager );
if ( FAILED( hr ) )
{
break;
}
assert( pProfileManager );
hr = pProfileManager->CreateEmptyProfile( WMT_VER_9_0, &pProfile );
if ( FAILED( hr ) )
{
break;
}
assert( pProfile );
hr = pProfile->QueryInterface( IID_IWMProfile3, (void**) &pProfile3 );
if ( FAILED( hr ) )
{
break;
}
assert( pProfile3 );
//
// Add the streams to the profile
//
hr = AddStreamsToProfile( pProfile );
if ( FAILED( hr ) )
{
break;
}
//
// Add the mutexes to the profile
//
hr = AddMutexesToProfile( pProfile );
if ( FAILED( hr ) )
{
break;
}
if ( wPrioritizationRecordCount > 0 )
{
assert( 1 == wPrioritizationRecordCount );
//
// Create and configure the stream prioritization object
//
aStreamPriorityRecords = new WM_STREAM_PRIORITY_RECORD[ wStreamCount ];
if ( !aStreamPriorityRecords )
{
hr = E_OUTOFMEMORY;
break;
}
hr = CreateStreamPrioritizationArray( aStreamPriorityRecords, wStreamCount );
if ( FAILED( hr ) )
{
break;
}
//
// Add the stream prioritization to the profile
//
hr = pProfile3->CreateNewStreamPrioritization( &pStreamPrioritization );
if ( FAILED( hr ) )
{
break;
}
assert( pStreamPrioritization );
hr = pStreamPrioritization->SetPriorityRecords( aStreamPriorityRecords, wPrioritizationRecordCount );
if ( FAILED( hr ) )
{
break;
}
hr = pProfile3->SetStreamPrioritization( pStreamPrioritization );
if ( FAILED( hr ) )
{
break;
}
}
//
// Add bandwidth sharing objects
//
hr = AddBandwidthSharingObjectsToProfile( pProfile3 );
if ( FAILED( hr ) )
{
break;
}
//
// Set the profile name
//
m_txtProfileName.GetWindowText( strProfileName );
dwProfileNameLength = strProfileName.GetLength();
wszProfileName = new WCHAR[ dwProfileNameLength + 1 ];
if ( !wszProfileName )
{
hr = E_OUTOFMEMORY;
break;
}
#ifdef UNICODE
wcscpy_s(wszProfileName, dwProfileNameLength + 1, strProfileName);
#else // UNICODE
size_t szCount;
mbstowcs_s(&szCount, wszProfileName, dwProfileNameLength + 1, strProfileName, dwProfileNameLength);
#endif // UNICODE
hr = pProfile->SetName( wszProfileName );
if ( FAILED( hr ) )
{
break;
}
//
// Set the profile description
//
hr = SetProfileDescription( pProfile );
if ( FAILED( hr ) )
{
break;
}
SAFE_ADDREF( pProfile );
*ppProfile = pProfile;
}
while ( FALSE );
SAFE_ARRAYDELETE( wszProfileName );
SAFE_RELEASE( pProfile );
SAFE_RELEASE( pProfile3 );
SAFE_RELEASE( pProfileManager );
SAFE_ARRAYDELETE( aStreamPriorityRecords );
SAFE_RELEASE( pStreamPrioritization );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetProfileDescription( IWMProfile *pProfile )
{
HRESULT hr = S_OK;
DWORD dwProfileObjectCount;
DWORD dwProfileObjectIndex;
CString strStreamsDescription;
CString strProfileDescription;
CString strNewDescription;
DWORD dwAudioStreams;
DWORD dwVideoStreams;
DWORD dwScriptStreams;
DWORD dwImageStreams;
DWORD dwFileStreams;
DWORD dwWebStreams;
DWORD dwMutexCount;
LPWSTR wszProfileDescription = NULL;
DWORD dwProfileDescriptionLength;
CProfileObject* pCurrentObject;
if ( !pProfile )
{
return E_INVALIDARG;
}
do
{
//
// Count the number of streams and mutexes
//
dwAudioStreams = 0;
dwVideoStreams = 0;
dwScriptStreams = 0;
dwImageStreams = 0;
dwFileStreams = 0;
dwWebStreams = 0;
dwMutexCount = 0;
dwProfileObjectCount = m_lstProfileObjects.GetCount();
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
if ( OT_Stream == pCurrentObject->Type() )
{
switch ( ((CStream*) pCurrentObject)->GetStreamType() )
{
case ST_Audio: // Audio stream
dwAudioStreams++;
break;
case ST_Video: // Video stream
dwVideoStreams++;
break;
case ST_Script: // Script stream
dwScriptStreams++;
break;
case ST_Image: // Image stream
dwImageStreams++;
break;
case ST_Web: // Web stream
dwWebStreams++;
break;
case ST_File: // File stream
dwFileStreams++;
break;
default:
assert( !"Unknown stream type!" );
hr = E_UNEXPECTED;
break;
}
if ( FAILED( hr ) )
{
break;
}
}
else if ( OT_Mutex == pCurrentObject->Type() )
{
dwMutexCount++;
}
}
//
// Create simple description based on the objects in the profile
//
strStreamsDescription = _T("Streams: ");
if ( dwAudioStreams > 0 )
{
strNewDescription.Format( _T("%d audio "), dwAudioStreams );
strStreamsDescription += strNewDescription;
}
if ( dwVideoStreams > 0 )
{
strNewDescription.Format( _T("%d video "), dwVideoStreams );
strStreamsDescription += strNewDescription;
}
if ( dwScriptStreams > 0 )
{
strNewDescription.Format( _T("%d script "), dwScriptStreams );
strStreamsDescription += strNewDescription;
}
if ( dwImageStreams > 0 )
{
strNewDescription.Format( _T("%d image "), dwImageStreams );
strStreamsDescription += strNewDescription;
}
if ( dwWebStreams > 0 )
{
strNewDescription.Format( _T("%d web "), dwWebStreams );
strStreamsDescription += strNewDescription;
}
if ( dwFileStreams > 0 )
{
strNewDescription.Format( _T("%d file "), dwFileStreams );
strStreamsDescription += strNewDescription;
}
if ( dwMutexCount > 0 )
{
strProfileDescription.Format( _T("%s Mutexes: %d"), strStreamsDescription, dwMutexCount );
}
else
{
strProfileDescription.Format( _T("%s"), strStreamsDescription );
}
strProfileDescription.TrimRight();
//
// Copy the string into a LPWSTR
//
dwProfileDescriptionLength = strProfileDescription.GetLength();
wszProfileDescription = new WCHAR[ dwProfileDescriptionLength + 1 ];
if ( !wszProfileDescription )
{
hr = E_OUTOFMEMORY;
break;
}
#ifdef UNICODE
wcscpy_s( wszProfileDescription, dwProfileDescriptionLength + 1, (LPCTSTR) strProfileDescription );
#else // UNICODE
size_t szCount;
mbstowcs_s(&szCount, wszProfileDescription, dwProfileDescriptionLength + 1, strProfileDescription, dwProfileDescriptionLength);
#endif // UNICODE
hr = pProfile->SetDescription( wszProfileDescription );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_ARRAYDELETE( wszProfileDescription );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddStreamsToProfile( IWMProfile* pProfile )
{
HRESULT hr = S_OK;
WORD wStreamIndex;
CStream* pStream;
DWORD dwProfileObjectIndex;
DWORD dwProfileObjectCount;
CProfileObject* pCurrentObject;
IWMStreamConfig* pNewStreamConfig = NULL;
WORD wStreamNumber;
CString strStreamType;
CString strStreamName;
LPWSTR wszStreamName = NULL;
int nStreamNameLength;
assert( pProfile );
do
{
dwProfileObjectCount = m_lstProfileObjects.GetCount();
wStreamIndex = 0;
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
if ( OT_Stream == pCurrentObject->Type() )
{
pStream = (CStream*) pCurrentObject;
SAFE_RELEASE( pNewStreamConfig );
switch ( pStream->GetStreamType() )
{
case ST_Audio: // Audio stream
strStreamType = _T("Audio");
if ( !pStream->GetIsUncompressed() )
{
hr = CreateAudioStream( &pNewStreamConfig,
m_pCodecInfo,
pProfile,
pStream->GetStreamBufferWindow(),
pStream->GetStreamCodecIndex(),
pStream->GetStreamFormatIndex() % VBR_OFFSET,
pStream->GetStreamFormatIndex() / VBR_OFFSET > 0,
pStream->GetStreamFormatIndex() / VBR_OFFSET,
pStream->GetLanguageLCID() );
}
else
{
DWORD dwWaveFormatIndex;
DWORD dwSamplesPerSec;
WORD wNumChannels;
WORD wBitsPerSample;
dwWaveFormatIndex = pStream->GetWaveFormatIndex();
hr = GetUncompressedWaveFormat( dwWaveFormatIndex,
&dwSamplesPerSec,
&wNumChannels,
&wBitsPerSample );
if ( SUCCEEDED( hr ) )
{
hr = CreateUncompressedAudioStream( &pNewStreamConfig,
pProfile,
dwSamplesPerSec,
wNumChannels,
wBitsPerSample,
pStream->GetLanguageLCID() );
}
}
break;
case ST_Video: // Video stream
strStreamType = _T("Video");
if ( !pStream->GetIsUncompressed() )
{
hr = CreateVideoStream( &pNewStreamConfig,
m_pCodecInfo,
pProfile,
pStream->GetStreamCodecIndex(),
pStream->GetStreamBitrate(),
pStream->GetStreamBufferWindow(),
pStream->GetVideoWidth(),
pStream->GetVideoHeight(),
pStream->GetVideoFPS(),
pStream->GetVideoQuality(),
pStream->GetVideoSecondsPerKeyframe(),
pStream->GetVideoIsVBR(),
pStream->GetVideoVBRMode(),
pStream->GetVideoVBRQuality(),
pStream->GetVideoMaxBitrate(),
pStream->GetVideoMaxBufferWindow(),
pStream->GetLanguageLCID() );
}
else
{
DWORD dwPixelFormatIndex;
GUID guidFormat;
DWORD dwFourCC;
WORD wBitsPerPixel;
dwPixelFormatIndex = pStream->GetPixelFormatIndex();
hr = GetUncompressedPixelFormat( dwPixelFormatIndex, &guidFormat, &dwFourCC, &wBitsPerPixel );
if ( SUCCEEDED( hr ) )
{
hr = CreateUncompressedVideoStream( &pNewStreamConfig,
pProfile,
guidFormat,
dwFourCC,
wBitsPerPixel,
NULL,
0,
pStream->GetVideoWidth(),
pStream->GetVideoHeight(),
pStream->GetVideoFPS(),
pStream->GetLanguageLCID() );
}
}
break;
case ST_Script: // Script stream
strStreamType = _T("Script");
hr = CreateScriptStream( &pNewStreamConfig,
pProfile,
pStream->GetStreamBitrate(),
pStream->GetStreamBufferWindow(),
pStream->GetLanguageLCID() );
break;
case ST_Image: // Image stream
strStreamType = _T("Image");
hr = CreateImageStream( &pNewStreamConfig,
pProfile,
pStream->GetStreamBitrate(),
pStream->GetStreamBufferWindow(),
pStream->GetVideoWidth(),
pStream->GetVideoHeight(),
pStream->GetLanguageLCID() );
break;
case ST_Web: // Web stream
strStreamType = _T("Web");
hr = CreateWebStream( &pNewStreamConfig,
pProfile,
pStream->GetStreamBitrate(),
pStream->GetStreamBufferWindow(),
pStream->GetLanguageLCID() );
break;
case ST_File: // File stream
strStreamType = _T("File");
hr = CreateFileStream( &pNewStreamConfig,
pProfile,
pStream->GetStreamBitrate(),
pStream->GetStreamBufferWindow(),
MAX_FILENAME_LENGTH,
pStream->GetLanguageLCID() );
break;
default:
assert( !"Unknown stream type!" );
hr = E_UNEXPECTED;
break;
}
if ( FAILED( hr ) )
{
break;
}
assert( pNewStreamConfig );
//
// Set the stream number for the new stream
//
wStreamNumber = (WORD) pStream->GetStreamNumber();
hr = pNewStreamConfig->SetStreamNumber( wStreamNumber );
if ( FAILED( hr ) )
{
break;
}
//
// Set the stream name
//
strStreamName.Format( _T( "%s%d" ), strStreamType, wStreamNumber );
#ifdef UNICODE
hr = pNewStreamConfig->SetStreamName( (LPWSTR) strStreamName );
#else
nStreamNameLength = strStreamName.GetLength();
wszStreamName = new WCHAR[ nStreamNameLength + 1];
if ( !wszStreamName )
{
hr = E_OUTOFMEMORY;
break;
}
size_t szCount;
mbstowcs_s(&szCount, wszStreamName, nStreamNameLength + 1, strStreamName, nStreamNameLength);
hr = pNewStreamConfig->SetStreamName( wszStreamName );
#endif
if ( FAILED( hr ) )
{
break;
}
//
// Add the stream to the profile
//
hr = pProfile->AddStream( pNewStreamConfig );
if ( FAILED( hr ) )
{
break;
}
wStreamIndex++;
}
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_ARRAYDELETE( wszStreamName );
SAFE_RELEASE( pNewStreamConfig );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddMutexesToProfile( IWMProfile* pProfile )
{
HRESULT hr = S_OK;
WORD wMutexIndex;
CMutex* pMutex;
DWORD dwProfileObjectIndex;
DWORD dwProfileObjectCount;
CProfileObject* pCurrentObject;
assert( pProfile );
do
{
//
// Loop through all the objects, creating a mutex for each
//
dwProfileObjectCount = m_lstProfileObjects.GetCount();
wMutexIndex = 0;
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
if ( OT_Mutex == pCurrentObject->Type() )
{
pMutex = (CMutex*) pCurrentObject;
hr = AddMutexToProfile( pProfile, pMutex );
if ( FAILED( hr ) )
{
break;
}
wMutexIndex++;
}
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddMutexToProfile( IWMProfile* pProfile, CMutex *pMutex )
{
HRESULT hr = S_OK;
INT nDependacyCount;
INT nDependancyIndex;
CStream* pCurrentStream;
WORD wStreamNumber;
INT nStreamIndex;
IWMMutualExclusion* pNewMutex = NULL;
LPWSTR wszConnectionName = NULL;
WORD wConnectionNameLength;
IWMStreamConfig* pStreamConfig = NULL;
assert( pProfile );
assert( pMutex );
do
{
//
// Create a new mutual exclusion object and get the interface used to add streams to it
//
hr = pProfile->CreateNewMutualExclusion( &pNewMutex );
if ( FAILED( hr ) )
{
break;
}
assert( pNewMutex );
//
// Copy the list of streams from the CMutex to the IWMMutualExclusion
//
nStreamIndex = 0;
nDependacyCount = pMutex->StreamCount();
for ( nDependancyIndex = 0; nDependancyIndex < nDependacyCount; nDependancyIndex++ )
{
hr = pMutex->GetStream( nDependancyIndex, &pCurrentStream );
if ( FAILED( hr ) )
{
break;
}
assert( pCurrentStream );
if ( !pCurrentStream )
{
hr = E_UNEXPECTED;
break;
}
wStreamNumber = pCurrentStream->GetStreamNumber();
//
// Set the connection name for each stream to the same value
//
SAFE_RELEASE( pStreamConfig );
hr = pProfile->GetStreamByNumber( wStreamNumber, &pStreamConfig );
if ( FAILED( hr ) )
{
break;
}
if ( 0 == nDependancyIndex )
{
//
// Use the stream name of the first stream in the mutex as
// the connection name
//
SAFE_ARRAYDELETE( wszConnectionName );
hr = pStreamConfig->GetStreamName( NULL, &wConnectionNameLength );
if ( FAILED( hr ) )
{
break;
}
wszConnectionName = new WCHAR[ wConnectionNameLength ];
if ( !wszConnectionName )
{
hr = E_OUTOFMEMORY;
break;
}
hr = pStreamConfig->GetStreamName( wszConnectionName, &wConnectionNameLength );
if ( FAILED( hr ) )
{
break;
}
}
//
// The connection name only has to match for bitrate mutexes
//
if ( MT_Bitrate == pMutex->GetMutexType( ) )
{
hr = pStreamConfig->SetConnectionName( wszConnectionName );
if ( FAILED( hr ) )
{
break;
}
hr = pProfile->ReconfigStream( pStreamConfig );
if ( FAILED( hr ) )
{
break;
}
}
hr = pNewMutex->AddStream( wStreamNumber );
if ( FAILED( hr ) )
{
break;
}
nStreamIndex++;
}
if ( FAILED( hr ) )
{
break;
}
assert( nStreamIndex == nDependacyCount );
//
// Set the other members of the mutual exclusion
//
switch ( pMutex->GetMutexType( ) )
{
case MT_Bitrate:
hr = pNewMutex->SetType( CLSID_WMMUTEX_Bitrate );
break;
case MT_Language:
hr = pNewMutex->SetType( CLSID_WMMUTEX_Language );
break;
case MT_Presentation:
hr = pNewMutex->SetType( CLSID_WMMUTEX_Presentation );
break;
default:
assert( !"Unknown mutex type!" );
hr = E_UNEXPECTED;
}
if ( FAILED( hr ) )
{
break;
}
//
// Add the mutex to the profile
//
hr = pProfile->AddMutualExclusion( pNewMutex );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_RELEASE( pNewMutex );
SAFE_ARRAYDELETE( wszConnectionName );
SAFE_RELEASE( pStreamConfig );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::CreateStreamPrioritizationArray( WM_STREAM_PRIORITY_RECORD *pPrioritizationInfo, WORD wStreamCount )
{
HRESULT hr = S_OK;
CStreamPrioritizationObject* pPrioritizationObject;
DWORD dwProfileObjectIndex;
DWORD dwProfileObjectCount;
CProfileObject* pCurrentObject;
assert( pPrioritizationInfo );
do
{
//
// Loop through all the objects to find the stream prioritization object
//
dwProfileObjectCount = m_lstProfileObjects.GetCount();
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
if ( OT_StreamPrioritization == pCurrentObject->Type() )
{
pPrioritizationObject = (CStreamPrioritizationObject*) pCurrentObject;
//
// Set the values
//
hr = SetStreamPrioritizationInfo( pPrioritizationInfo, pPrioritizationObject, wStreamCount );
if ( FAILED( hr ) )
{
break;
}
break; // There is only 1 stream prioritization object
}
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SetStreamPrioritizationInfo( WM_STREAM_PRIORITY_RECORD *pPrioritizationInfo, CStreamPrioritizationObject *pStreamPrioritizationObject, WORD wStreamCount )
{
HRESULT hr = S_OK;
INT nStreamsInPrioritizationObject;
INT nStreamIndex;
WORD wStreamNumber;
CStream* pStream = NULL;
BOOL fStreamIsManatory;
assert( pPrioritizationInfo );
assert( pStreamPrioritizationObject );
do
{
//
// Copy the list of streams from the CStreamPrioritizationObject to the WM_STREAM_PRIORITY_RECORD
//
nStreamsInPrioritizationObject = pStreamPrioritizationObject->StreamCount();
assert( nStreamsInPrioritizationObject == wStreamCount );
for ( nStreamIndex = 0; nStreamIndex < nStreamsInPrioritizationObject; nStreamIndex++ )
{
//
// Get the stream by priority
//
SAFE_RELEASE( pStream );
hr = pStreamPrioritizationObject->GetStreamWithPriority( nStreamIndex, &pStream );
if ( FAILED( hr ) )
{
break;
}
assert( pStream );
if ( !pStream )
{
hr = E_UNEXPECTED;
break;
}
wStreamNumber = pStream->GetStreamNumber();
//
// Find out if the stream is mandatory
//
hr = pStreamPrioritizationObject->GetStreamMandatory( pStream, &fStreamIsManatory );
if ( FAILED( hr ) )
{
break;
}
//
// Set the values in the WM_STREAM_PRIORITY_RECORD structure
//
pPrioritizationInfo[nStreamIndex].wStreamNumber = wStreamNumber;
pPrioritizationInfo[nStreamIndex].fMandatory = fStreamIsManatory;
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_RELEASE( pStream );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddBandwidthSharingObjectsToProfile( IWMProfile3* pProfile3 )
{
HRESULT hr = S_OK;
WORD wBandwidthSharingIndex;
CBandwidthSharingObject* pBandwidthSharingObject;
DWORD dwProfileObjectIndex;
DWORD dwProfileObjectCount;
CProfileObject* pCurrentObject;
assert( pProfile3 );
do
{
//
// Loop through all the objects, creating a mutex for each
//
dwProfileObjectCount = m_lstProfileObjects.GetCount();
wBandwidthSharingIndex = 0;
for ( dwProfileObjectIndex = 0; dwProfileObjectIndex < dwProfileObjectCount; dwProfileObjectIndex++ )
{
pCurrentObject = (CProfileObject*) m_lstProfileObjects.GetItemDataPtr( dwProfileObjectIndex );
assert( pCurrentObject );
if ( OT_BandwidthSharing == pCurrentObject->Type() )
{
pBandwidthSharingObject = (CBandwidthSharingObject*) pCurrentObject;
hr = AddBandwidthSharingObjectToProfile( pProfile3, pBandwidthSharingObject );
if ( FAILED( hr ) )
{
break;
}
wBandwidthSharingIndex++;
}
}
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::AddBandwidthSharingObjectToProfile( IWMProfile3* pProfile3, CBandwidthSharingObject *pBandwidthSharingObject )
{
HRESULT hr = S_OK;
INT nDependacyCount;
INT nDependancyIndex;
CStream* pCurrentStream;
WORD wStreamNumber;
INT nStreamIndex;
IWMBandwidthSharing* pBSO = NULL;
assert( pProfile3 );
assert( pBandwidthSharingObject );
do
{
hr = pProfile3->CreateNewBandwidthSharing( &pBSO );
if ( FAILED( hr ) )
{
break;
}
//
// Don't try to add BSOs with 0 streams - they are not allowed
//
nDependacyCount = pBandwidthSharingObject->StreamCount();
if ( 0 == nDependacyCount )
{
break;
}
//
// Copy the list of streams from the CBandwidthSharingObject to the IWMBandwidthSharing
//
nStreamIndex = 0;
for ( nDependancyIndex = 0; nDependancyIndex < nDependacyCount; nDependancyIndex++ )
{
hr = pBandwidthSharingObject->GetStream( nDependancyIndex, &pCurrentStream );
if ( FAILED( hr ) )
{
break;
}
assert( pCurrentStream );
if ( !pCurrentStream )
{
hr = E_UNEXPECTED;
break;
}
wStreamNumber = pCurrentStream->GetStreamNumber();
hr = pBSO->AddStream( wStreamNumber );
if ( FAILED( hr ) )
{
break;
}
nStreamIndex++;
}
if ( FAILED( hr ) )
{
break;
}
assert( nStreamIndex == nDependacyCount );
//
// Set the other members of the BSO
//
hr = pBSO->SetType( pBandwidthSharingObject->GetBandwidthSharingType() );
if ( FAILED( hr ) )
{
break;
}
hr = pBSO->SetBandwidth( pBandwidthSharingObject->GetSharedBitrate(), pBandwidthSharingObject->GetBufferWindow() );
if ( FAILED( hr ) )
{
break;
}
//
// Add the BSO to the profile
//
hr = pProfile3->AddBandwidthSharing( pBSO );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
SAFE_RELEASE( pBSO );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::ValidateMutexStreamsAgainstControl( CMutex *pMutex )
{
HRESULT hr = S_OK;
INT nSelectedStreamsCount;
INT nActualStreamCount;
INT* aSelectedStreams = NULL;
INT nSelectedStreamIndex;
CStream* pHighlightedStream;
StreamType stExpectedStreamType;
BOOL fStreamIsAllowed;
CString strMessage;
assert( m_pDisplayedProfileObject );
assert( OT_Mutex == m_pDisplayedProfileObject->Type() );
assert( pMutex );
do
{
pMutex->RemoveAllStreams();
//
// Get the list of selected items from control
//
nSelectedStreamsCount = m_lstMutexStreams.GetSelCount();
aSelectedStreams = new INT[ nSelectedStreamsCount ];
if ( !aSelectedStreams )
{
hr = E_OUTOFMEMORY;
break;
}
if ( LB_ERR == m_lstMutexStreams.GetSelItems( nSelectedStreamsCount, aSelectedStreams ) )
{
hr = E_OUTOFMEMORY;
break;
}
//
// Select all the streams which should be selected
//
nActualStreamCount = nSelectedStreamsCount;
for( nSelectedStreamIndex = 0; nSelectedStreamIndex < nActualStreamCount; nSelectedStreamIndex++ )
{
fStreamIsAllowed = TRUE;
pHighlightedStream = (CStream*) m_lstMutexStreams.GetItemDataPtr( aSelectedStreams[ nSelectedStreamIndex ] );
assert( pHighlightedStream );
if ( (CStream*) -1 == pHighlightedStream )
{
hr = E_UNEXPECTED;
break;
}
//
// Use the first stream as the expected types for all the streams.
// If a stream doesn't match it, it isn't added to the mutex
//
if ( 0 == nSelectedStreamIndex )
{
stExpectedStreamType = pHighlightedStream->GetStreamType();
}
else if ( stExpectedStreamType == pHighlightedStream->GetStreamType() )
{
}
else
{
fStreamIsAllowed = FALSE;
//
// Print a message saying the stream types didn't match
//
DisplayMessage( IDS_Multiple_stream_types_in_mutex_error );
//
// Remove the stream from the array of selected streams
//
nActualStreamCount--;
if ( 0 != nActualStreamCount && nActualStreamCount != nSelectedStreamIndex )
{
aSelectedStreams[nSelectedStreamIndex] = aSelectedStreams[nActualStreamCount];
nSelectedStreamIndex--; // Loop through this index again
}
}
//
// Check the stream to see if it's in any other mutexes
//
if ( ( pMutex->GetMutexType() == MT_Bitrate ) && ( InBitrateMutex( pHighlightedStream ) ) )
{
fStreamIsAllowed = FALSE;
//
// Print a message saying the stream types didn't match
//
DisplayMessage( IDS_Stream_in_multiple_mutexes_error );
//
// Remove the stream from the array of selected streams
//
nActualStreamCount--;
if ( 0 != nActualStreamCount && nActualStreamCount != nSelectedStreamIndex )
{
aSelectedStreams[nSelectedStreamIndex] = aSelectedStreams[nActualStreamCount];
nSelectedStreamIndex--; // Loop through this index again
}
}
//
// Add the stream to the mutex
//
if ( fStreamIsAllowed )
{
pMutex->AddStream( pHighlightedStream );
}
}
//
// Re-select the streams in the mutex, since streams may have been removed
//
if ( nActualStreamCount != nSelectedStreamsCount )
{
if ( LB_ERR == m_lstMutexStreams.SelItemRange( FALSE, 0, m_lstMutexStreams.GetCount() - 1 ) )
{
hr = E_OUTOFMEMORY;
break;
}
for( nSelectedStreamIndex = 0; nSelectedStreamIndex < nActualStreamCount; nSelectedStreamIndex++ )
{
if ( LB_ERR == m_lstMutexStreams.SetSel( aSelectedStreams[ nSelectedStreamIndex ], TRUE ) )
{
hr = E_OUTOFMEMORY;
break;
}
}
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
DisplayMessage( IDS_Fatal_error );
}
SAFE_ARRAYDELETE( aSelectedStreams );
}
///////////////////////////////////////////////////////////////////////////////
DWORD CGenProfileDlg::GetNumberOfFormatsSupported( GUID guidStreamType,
DWORD dwCodecIndex,
BOOL fIsVBR,
DWORD dwNumPasses )
{
HRESULT hr;
DWORD dwCodecFormatCount;
do
{
hr = SetCodecVBRSettings( m_pCodecInfo, guidStreamType, dwCodecIndex, fIsVBR, dwNumPasses );
if ( FAILED( hr ) )
{
break;
}
//
// Get the number of formats the current setting supports
//
hr = m_pCodecInfo->GetCodecFormatCount( guidStreamType, dwCodecIndex, &dwCodecFormatCount );
if ( FAILED( hr ) )
{
break;
}
}
while ( FALSE );
if ( FAILED( hr ) )
{
return 0;
}
return dwCodecFormatCount;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::DisplayMessageAndTerminate( LPCTSTR tszMessage )
{
MessageBox( tszMessage, _T("Unrecoverable error occured!") );
ExitProcess( -1 );
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::SelectItemWithData( CComboBox *pcbComboBox, DWORD dwRequestedItemData )
{
INT nItemCount;
INT nItemIndex;
DWORD_PTR dwItemData;
assert( pcbComboBox );
nItemCount = pcbComboBox->GetCount();
for ( nItemIndex = 0; nItemIndex < nItemCount; nItemIndex++ )
{
dwItemData = pcbComboBox->GetItemData( nItemIndex );
if ( CB_ERR == dwItemData )
{
return E_UNEXPECTED;
}
if ( dwItemData == dwRequestedItemData )
{
pcbComboBox->SetCurSel( nItemIndex );
return S_OK;
}
}
return E_FAIL;
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::DisableVideoVBRControls()
{
m_chkStreamVideoIsVBR.EnableWindow( FALSE );
m_chkStreamVideoIsVBR.SetCheck( BST_UNCHECKED );
m_cbStreamVideoVBRMode.EnableWindow( FALSE );
m_chkStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoMaxBitrate.EnableWindow( FALSE );
m_txtStreamVideoMaxBufferWindow.EnableWindow( FALSE );
m_txtStreamVideoVBRQuality.EnableWindow( FALSE );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBPixelFormat()
{
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
DWORD dwStringIndex = m_cbPixelFormat.GetCurSel();
DWORD dwIndex = ( DWORD )( m_cbPixelFormat.GetItemData( dwStringIndex ) );
((CStream*) m_pDisplayedProfileObject)->SetPixelFormatStringIndex( dwStringIndex );
((CStream*) m_pDisplayedProfileObject)->SetPixelFormatIndex( dwIndex );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::OnSelchangeCBLanguage()
{
assert( m_pDisplayedProfileObject );
assert( OT_Stream == m_pDisplayedProfileObject->Type() );
DWORD dwStringIndex = m_cbLanguage.GetCurSel();
LCID lcid = ( DWORD )( m_cbLanguage.GetItemData( dwStringIndex ) );
((CStream*) m_pDisplayedProfileObject)->SetLanguageLCID( lcid );
}
///////////////////////////////////////////////////////////////////////////////
void CGenProfileDlg::SelectLanguage( LCID lcid )
{
DWORD dwLanguageCount = m_cbLanguage.GetCount();
for ( DWORD i = 0; i < dwLanguageCount; i ++ )
{
if ( m_cbLanguage.GetItemData( i ) == lcid )
{
m_cbLanguage.SetCurSel( i );
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
HRESULT CGenProfileDlg::PopulateLanguageCB()
{
HRESULT hr = S_OK;
if ( m_cbLanguage.GetCount() > 0 )
{
// Langauge list has been initialized.
return hr;
}
IMultiLanguage * pMLang = NULL;
IEnumRfc1766 * pEnumRfc1766 = NULL;
do
{
hr = CoCreateInstance( CLSID_CMultiLanguage,
NULL,
CLSCTX_ALL,
IID_IMultiLanguage,
(VOID **) &pMLang );
if( FAILED( hr ) )
{
break;
}
hr = pMLang->EnumRfc1766( &pEnumRfc1766 );
if( FAILED( hr ) )
{
break;
}
while( SUCCEEDED( hr ) )
{
RFC1766INFO rfcinfo = {0};
ULONG ulFetched = 0;
hr = pEnumRfc1766->Next( 1, &rfcinfo, &ulFetched );
if( FAILED( hr ) || ( S_FALSE == hr ) )
{
break;
}
if( 0 == ulFetched )
{
continue;
}
//
// Check to see if the item dup with the added item, if it is, don't add it.
//
BOOL fDup = FALSE;
for( int i = 0; i < m_cbLanguage.GetCount(); i++ )
{
if( ( (LCID)m_cbLanguage.GetItemData(i) ) == rfcinfo.lcid )
{
fDup = TRUE;
break;
}
}
if( fDup )
{
continue;
}
TCHAR szLanguageName[256];
#ifdef UNICODE
_sntprintf_s( szLanguageName, ARRAY_SIZE(szLanguageName), ARRAY_SIZE(szLanguageName) - 1, _T("%s [%s]"), rfcinfo.wszLocaleName, rfcinfo.wszRfc1766);
#else //UNICODE
CHAR szLocaleName[128];
CHAR szRfc1766[128];
if( 0 == WideCharToMultiByte( CP_ACP, 0, rfcinfo.wszLocaleName, -1, szLocaleName, 128, NULL, NULL )
|| 0 == WideCharToMultiByte( CP_ACP, 0, rfcinfo.wszRfc1766, -1, szRfc1766, 128, NULL, NULL ) )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
break;
}
(void)StringCchPrintf( szLanguageName, ARRAYSIZE(szLanguageName), _T("%s [%s]"), szLocaleName, szRfc1766 );
// prefast fix #140662 - _sntprintf may not null terminate result string
szLanguageName[ sizeof( szLanguageName ) - 1 ] = '\0';
#endif // UNICODE
int nIndex = m_cbLanguage.AddString( szLanguageName );
m_cbLanguage.SetItemData( nIndex, rfcinfo.lcid );
}
}
while( FALSE );
SAFE_RELEASE( pMLang );
SAFE_RELEASE( pEnumRfc1766 );
return( hr );
}
| 31.051541 | 179 | 0.521501 | [
"object"
] |
5c638beb8f99ffd84ea8b86612d1dd408db1b6ee | 9,226 | hpp | C++ | Source/TitaniumKit/include/Titanium/UI/Picker.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/include/Titanium/UI/Picker.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/include/Titanium/UI/Picker.hpp | garymathews/titanium_mobile_windows | ff2a02d096984c6cad08f498e1227adf496f84df | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* TitaniumKit Titanium.UI.Picker
*
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TITANIUM_UI_PICKER_HPP_
#define _TITANIUM_UI_PICKER_HPP_
#include "Titanium/detail/TiBase.hpp"
#include "Titanium/UI/View.hpp"
#include "Titanium/UI/Constants.hpp"
#include "Titanium/UI/Font.hpp"
#include <chrono>
#include <boost/optional.hpp>
namespace Titanium
{
namespace UI
{
using namespace HAL;
class PickerColumn;
class PickerRow;
/*!
@struct
@discussion An abstract datatype for specifying a properties for showPickerDateDialog
This is an abstract type. Any object meeting this description can be used where this type is used.
See http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.Picker-method-showDatePickerDialog
*/
struct PickerDialogOption
{
std::string title;
std::string okButtonTitle;
bool format24;
std::chrono::system_clock::time_point value;
JSValue callback; // need to keep these references to prevent from GC
std::function<void(const bool& cancel, const std::chrono::system_clock::time_point& value)> oncallback;
};
TITANIUMKIT_EXPORT PickerDialogOption js_to_PickerDialogOption(const JSObject& object);
/*!
@class
@discussion This is the Titanium Picker Module.
See http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.UI.Picker
*/
class TITANIUMKIT_EXPORT Picker : public View, public JSExport<Picker>
{
public:
/*!
@property
@abstract columns
@discussion Columns used for this picker, as an array of <Titanium.UI.PickerColumn> objects.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::vector<std::shared_ptr<PickerColumn>>, columns);
/*!
@property
@abstract countDownDuration
@discussion Duration in milliseconds used for a Countdown Timer picker.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::chrono::milliseconds, countDownDuration);
/*!
@property
@abstract format24
@discussion Determines whether the Time pickers display in 24-hour or 12-hour clock format.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, format24);
/*!
@property
@abstract locale
@discussion Locale used when displaying Date and Time picker values.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::string, locale);
/*!
@property
@abstract maxDate
@discussion Maximum date displayed when a Date picker is in use.
*/
TITANIUM_PROPERTY_IMPL_DEF(boost::optional<std::chrono::system_clock::time_point>, maxDate);
/*!
@property
@abstract minDate
@discussion Minimum date displayed when a Date picker is in use.
*/
TITANIUM_PROPERTY_IMPL_DEF(boost::optional<std::chrono::system_clock::time_point>, minDate);
/*!
@property
@abstract minuteInterval
@discussion Interval in minutes displayed when one of the Time types of pickers is in use.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::chrono::minutes, minuteInterval);
/*!
@property
@abstract selectionIndicator
@discussion Determines whether the visual selection indicator is shown.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, selectionIndicator);
/*!
@property
@abstract selectionOpens
@discussion Determines whether calling the method setSelectedRow opens when called.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, selectionOpens);
/*!
@property
@abstract useSpinner
@discussion Determines whether the non-native Android control, with a spinning wheel that looks and behaves like the iOS picker, is invoked rather than the default native "dropdown" style.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, useSpinner);
/*!
@property
@abstract value
@discussion Date and time value for Date and Time pickers.
*/
TITANIUM_PROPERTY_IMPL_DEF(boost::optional<std::chrono::system_clock::time_point>, value);
/*!
@property
@abstract visibleItems
@discussion Number of visible rows to display. This is only applicable to a plain picker and when the `useSpinner` is `true`.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::uint32_t, visibleItems);
/*!
@property
@abstract calendarViewShown
@discussion Determines whether the calenderView is visible.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, calendarViewShown);
/*!
@property
@abstract font
@discussion Font to use for text.
*/
TITANIUM_PROPERTY_IMPL_DEF(Font, font);
/*!
@property
@abstract type
@discussion Determines the type of picker displayed
*/
TITANIUM_PROPERTY_IMPL_DEF(PICKER_TYPE, type);
/*!
@method
@abstract add
@discussion Adds rows or columns to the picker.
*/
virtual void add_rows(const std::vector<std::shared_ptr<PickerRow>>& rows) TITANIUM_NOEXCEPT;
virtual void add_columns(const std::vector<std::shared_ptr<PickerColumn>>& columns) TITANIUM_NOEXCEPT;
/*!
@method
@abstract reloadColumn
@discussion Repopulates values for a column.
*/
virtual void reloadColumn(const std::shared_ptr<PickerColumn>& column) TITANIUM_NOEXCEPT;
/*!
@method
@abstract getSelectedRow
@discussion Gets the selected row for a column, or `null` if none exists.
*/
virtual std::shared_ptr<PickerRow> getSelectedRow(const std::uint32_t& columnIndex) TITANIUM_NOEXCEPT;
/*!
@method
@abstract setSelectedRow
@discussion Selects a column's row.
*/
virtual void setSelectedRow(const std::uint32_t& column, const std::uint32_t& row, const bool& animated) TITANIUM_NOEXCEPT;
/*!
@method
@abstract showDatePickerDialog
@discussion Shows Date picker as a modal dialog.
*/
virtual void showDatePickerDialog(const PickerDialogOption& option);
/*!
@method
@abstract showTimePickerDialog
@discussion Shows Time picker as a modal dialog.
*/
virtual void showTimePickerDialog(const PickerDialogOption& option);
Picker(const JSContext&) TITANIUM_NOEXCEPT;
virtual ~Picker() = default;
Picker(const Picker&) = default;
Picker& operator=(const Picker&) = default;
#ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE
Picker(Picker&&) = default;
Picker& operator=(Picker&&) = default;
#endif
static void JSExportInitialize();
TITANIUM_PROPERTY_DEF(columns);
TITANIUM_PROPERTY_DEF(countDownDuration);
TITANIUM_PROPERTY_DEF(format24);
TITANIUM_PROPERTY_DEF(locale);
TITANIUM_PROPERTY_DEF(maxDate);
TITANIUM_PROPERTY_DEF(minDate);
TITANIUM_PROPERTY_DEF(minuteInterval);
TITANIUM_PROPERTY_DEF(selectionIndicator);
TITANIUM_PROPERTY_DEF(selectionOpens);
TITANIUM_PROPERTY_DEF(useSpinner);
TITANIUM_PROPERTY_DEF(value);
TITANIUM_PROPERTY_DEF(visibleItems);
TITANIUM_PROPERTY_DEF(calendarViewShown);
TITANIUM_PROPERTY_DEF(font);
TITANIUM_PROPERTY_DEF(type);
TITANIUM_FUNCTION_DEF(add);
TITANIUM_FUNCTION_DEF(reloadColumn);
TITANIUM_FUNCTION_DEF(showDatePickerDialog);
TITANIUM_FUNCTION_DEF(showTimePickerDialog);
TITANIUM_FUNCTION_DEF(getSelectedRow);
TITANIUM_FUNCTION_DEF(setSelectedRow);
TITANIUM_FUNCTION_DEF(getColumns);
TITANIUM_FUNCTION_DEF(setColumns);
TITANIUM_FUNCTION_DEF(getCountDownDuration);
TITANIUM_FUNCTION_DEF(setCountDownDuration);
TITANIUM_FUNCTION_DEF(getFormat24);
TITANIUM_FUNCTION_DEF(setFormat24);
TITANIUM_FUNCTION_DEF(getLocale);
TITANIUM_FUNCTION_DEF(setLocale);
TITANIUM_FUNCTION_DEF(getMaxDate);
TITANIUM_FUNCTION_DEF(setMaxDate);
TITANIUM_FUNCTION_DEF(getMinDate);
TITANIUM_FUNCTION_DEF(setMinDate);
TITANIUM_FUNCTION_DEF(getMinuteInterval);
TITANIUM_FUNCTION_DEF(setMinuteInterval);
TITANIUM_FUNCTION_DEF(getSelectionIndicator);
TITANIUM_FUNCTION_DEF(setSelectionIndicator);
TITANIUM_FUNCTION_DEF(getSelectionOpens);
TITANIUM_FUNCTION_DEF(setSelectionOpens);
TITANIUM_FUNCTION_DEF(getUseSpinner);
TITANIUM_FUNCTION_DEF(setUseSpinner);
TITANIUM_FUNCTION_DEF(getValue);
TITANIUM_FUNCTION_DEF(setValue);
TITANIUM_FUNCTION_DEF(getVisibleItems);
TITANIUM_FUNCTION_DEF(setVisibleItems);
TITANIUM_FUNCTION_DEF(getCalendarViewShown);
TITANIUM_FUNCTION_DEF(setCalendarViewShown);
TITANIUM_FUNCTION_DEF(getFont);
TITANIUM_FUNCTION_DEF(setFont);
TITANIUM_FUNCTION_DEF(getType);
TITANIUM_FUNCTION_DEF(setType);
protected:
#pragma warning(push)
#pragma warning(disable : 4251)
std::vector<std::shared_ptr<PickerColumn>> columns__;
std::chrono::milliseconds countDownDuration__;
bool format24__;
std::string locale__;
boost::optional<std::chrono::system_clock::time_point> maxDate__;
boost::optional<std::chrono::system_clock::time_point> minDate__;
boost::optional<std::chrono::system_clock::time_point> value__;
std::chrono::minutes minuteInterval__;
bool selectionIndicator__;
bool selectionOpens__;
bool useSpinner__;
std::uint32_t visibleItems__;
bool calendarViewShown__;
Font font__;
PICKER_TYPE type__;
#pragma warning(pop)
};
} // namespace UI
} // namespace Titanium
#endif // _TITANIUM_UI_PICKER_HPP_ | 31.704467 | 193 | 0.739215 | [
"object",
"vector"
] |
5c63f7e33176caa74b8bb0ec7b9e70ae9da719d2 | 22,224 | cpp | C++ | applis/OLD-Digeo-OLD/Digeo_GaussFilter.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 451 | 2016-11-25T09:40:28.000Z | 2022-03-30T04:20:42.000Z | applis/OLD-Digeo-OLD/Digeo_GaussFilter.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 143 | 2016-11-25T20:35:57.000Z | 2022-03-01T11:58:02.000Z | applis/OLD-Digeo-OLD/Digeo_GaussFilter.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 139 | 2016-12-02T10:26:21.000Z | 2022-03-10T19:40:29.000Z | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : Marc Pierrot Deseilligny
Contributors : Gregoire Maillet, Didier Boldo.
[1] M. Pierrot-Deseilligny, N. Paparoditis.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "general/all.h"
#include "private/all.h"
#include "Digeo.h"
namespace NS_ParamDigeo
{
/****************************************/
/* */
/* :: */
/* */
/****************************************/
Im1D_REAL8 MakeSom1(Im1D_REAL8 aIm);
// K3-C3 = K1-C1 + K2-C2
Im1D_REAL8 DeConvol(int aC2,int aSz2,Im1D_REAL8 aI1,int aC1,Im1D_REAL8 aI3,int aC3)
{
L2SysSurResol aSys(aSz2);
int aSz1 = aI1.tx();
int aSz3 = aI3.tx();
for (int aK3 =0 ; aK3 < aSz3 ; aK3++)
{
std::vector<int> aVInd;
std::vector<double> aVCoef;
for (int aK=0; aK < aSz1 ; aK++)
{
int aK1 = aK;
int aK2 = aC2 + (aK3-aC3) - (aK1-aC1);
if ((aK1>=0)&&(aK1<aSz1)&&(aK2>=0)&&(aK2<aSz2))
{
aVInd.push_back(aK2);
aVCoef.push_back(aI1.data()[aK1]);
}
}
if (aVInd.size())
aSys.GSSR_AddNewEquation_Indexe(aVInd,1.0,&(aVCoef.data()[0]),aI3.data()[aK3]);
}
Im1D_REAL8 aRes = aSys.GSSR_Solve(0);
ELISE_COPY(aRes.all_pts(),Max(aRes.in(),0.0),aRes.out());
return MakeSom1(aRes);
}
Im1D_REAL8 DeConvol(int aDemISz2,Im1D_REAL8 aI1,Im1D_REAL8 aI3)
{
ELISE_ASSERT((aI1.tx()%2)&&(aI3.tx()%2),"Parity error in DeConvol");
return DeConvol(aDemISz2,1+2*aDemISz2,aI1,aI1.tx()/2,aI3,aI3.tx()/2);
}
Im1D_REAL8 Convol(Im1D_REAL8 aI1,int aC1,Im1D_REAL8 aI2,int aC2)
{
Im1D_REAL8 aRes(aI1.tx()+aI2.tx()-1,0.0);
ELISE_COPY
(
rectangle(Pt2di(0,0),Pt2di(aRes.tx(),aRes.tx())),
aI1.in(0)[FX]*aI2.in(0)[FY-FX],
aRes.histo(true).chc(FY)
);
return aRes;
}
Im1D_REAL8 Convol(Im1D_REAL8 aI1,Im1D_REAL8 aI2)
{
ELISE_ASSERT((aI1.tx()%2)&&(aI2.tx()%2),"Parity error in Convol");
return Convol(aI1,aI1.tx()/2,aI2,aI2.tx()/2);
}
Im1D_REAL8 MakeSom(Im1D_REAL8 aIm,double aSomCible)
{
double aSomActuelle;
Im1D_REAL8 aRes(aIm.tx());
ELISE_COPY(aIm.all_pts(),aIm.in(),sigma(aSomActuelle));
ELISE_COPY(aIm.all_pts(),aIm.in()*(aSomCible/aSomActuelle),aRes.out());
return aRes;
}
Im1D_REAL8 MakeSom1(Im1D_REAL8 aIm)
{
return MakeSom(aIm,1.0);
}
Im1D_REAL8 GaussianKernel(double aSigma,int aNb,int aSurEch)
{
Im1D_REAL8 aRes(2*aNb+1);
for (int aK=0 ; aK<=aNb ; aK++)
{
double aSom = 0;
for (int aKE =-aSurEch ; aKE<=aSurEch ; aKE++)
{
double aX = aK-aNb + aKE/double(2*aSurEch+1);
double aG = exp(-ElSquare(aX/aSigma)/2.0);
aSom += aG;
}
aRes.data()[aK] = aRes.data()[2*aNb-aK] = aSom;
}
return MakeSom1(aRes);
}
int NbElemForGausKern(double aSigma,double aResidu)
{
return round_up( sqrt(-2*log(aResidu))*aSigma);
}
Im1D_REAL8 GaussianKernelFromResidu(double aSigma,double aResidu,int aSurEch)
{
return GaussianKernel(aSigma,NbElemForGausKern( aSigma,aResidu),aSurEch);
}
// Methode pour avoir la "meilleure" approximation entiere d'une image reelle
// avec somme imposee. Tres sous optimal, mais a priori utilise uniquement sur de
// toute petites images
Im1D_INT4 ToIntegerKernel(Im1D_REAL8 aRK,int aMul,bool aForceSym)
{
aRK = MakeSom1(aRK);
int aSz=aRK.tx();
Im1D_INT4 aIK(aSz);
int aSom;
ELISE_COPY(aIK.all_pts(),round_ni(aRK.in()*aMul),aIK.out()|sigma(aSom));
int * aDI = aIK.data();
double * aDR = aRK.data();
while (aSom != aMul)
{
int toAdd = aMul-aSom;
int aSign = (toAdd>0) ? 1 : -1;
int aKBest=-1;
double aDeltaMin = 1e20;
if (aForceSym && (ElAbs(toAdd)==1) )
{
ELISE_ASSERT((aSz%2),"ToIntegerKernel Sym");
aKBest= aSz/2;
}
else
{
for (int aK=0 ; aK<aSz ; aK++)
{
double aDelta = ((aDI[aK]/double(aMul)) -aDR[aK]) * aSign;
if ((aDelta < aDeltaMin) && (aDI[aK]+aSign >=0))
{
aDeltaMin = aDelta;
aKBest= aK;
}
}
}
ELISE_ASSERT(aKBest!=-1,"Inco(1) in ToIntegerKernel");
aDI[aKBest] += aSign;
aSom += aSign;
if (aForceSym && (aSom!=aMul))
{
int aKSym = aSz - aKBest-1;
if (aKSym!=aKBest)
{
aDI[aKSym] += aSign;
aSom += aSign;
}
}
}
return aIK;
}
Im1D_INT4 ToOwnKernel(Im1D_REAL8 aRK,int & aShift,bool aForceSym,int *)
{
return ToIntegerKernel(aRK,1<<aShift,aForceSym);
}
Im1D_REAL8 ToOwnKernel(Im1D_REAL8 aRK,int & aShift,bool aForceSym,double *)
{
return aRK;
}
Im1D_REAL8 ToRealKernel(Im1D_INT4 aIK)
{
Im1D_REAL8 aRK(aIK.tx());
ELISE_COPY(aIK.all_pts(),aIK.in(),aRK.out());
return MakeSom1(aRK);
}
Im1D_REAL8 ToRealKernel(Im1D_REAL8 aRK)
{
return aRK;
}
// Permt de shifter les entiers (+ rapide que la div) sans rien faire pour
// les flottants
inline double ShiftDr(const double & aD,const int &) { return aD; }
inline double ShiftG(const double & aD,const int &) { return aD; }
inline double InitFromDiv(double ,double *) { return 0; }
inline int ShiftDr(const int & aD,const int & aShift) { return aD >> aShift; }
inline int ShiftG(const int & aD,const int & aShift) { return aD << aShift; }
inline int InitFromDiv(int aDiv,int *) { return aDiv/2; }
/*
// Pour utiliser un filtre sur les bord, clip les intervalle
// pour ne pas deborder et renvoie la somme partielle
template <class tBase> tBase ClipForConvol(int aSz,int aKXY,tBase * aData,int & aDeb,int & aFin)
{
ElSetMax(aDeb,-aKXY);
ElSetMin(aFin,aSz-1-aKXY);
*/
// Pour utiliser un filtre sur les bord, clip les intervalle
// pour ne pas deborder et renvoie la somme partielle
template <class tBase> tBase ClipForConvol(int aSz,int aKXY,tBase * aData,int & aDeb,int & aFin)
{
ElSetMax(aDeb,-aKXY);
ElSetMin(aFin,aSz-1-aKXY);
tBase aSom = 0;
for (int aK= aDeb ; aK<=aFin ; aK++)
aSom += aData[aK];
return aSom;
}
// Produit scalaire basique d'un filtre lineaire avec une ligne
// et une colonne image
template <class Type,class tBase>
inline tBase CorrelLine(tBase aSom,const Type * aData1,const tBase * aData2,const int & aDeb,const int & aFin)
{
for (int aK= aDeb ; aK<=aFin ; aK++)
aSom += aData1[aK]*aData2[aK];
return aSom;
}
/****************************************/
/* */
/* cTplImInMem */
/* */
/****************************************/
template <class Type>
void cTplImInMem<Type>::SetConvolBordX
(
Im2D<Type,tBase> aImOut,
Im2D<Type,tBase> aImIn,
int anX,
tBase * aDFilter,int aDebX,int aFinX
)
{
tBase aDiv = ClipForConvol(aImOut.tx(),anX,aDFilter,aDebX,aFinX);
Type ** aDOut = aImOut.data();
Type ** aDIn = aImIn.data();
const tBase aSom = InitFromDiv(aDiv,(tBase*)0);
int aSzY = aImOut.ty();
for (int anY=0 ; anY<aSzY ; anY++)
{
aDOut[anY][anX] = CorrelLine(aSom,aDIn[anY]+anX,aDFilter,aDebX,aFinX) / aDiv;
}
}
// SetConvolSepX(aImIn,aData,-aSzKer,aSzKer,aNbShitXY,aCS);
template <class Type>
void cTplImInMem<Type>::SetConvolSepX
(
Im2D<Type,tBase> aImOut,
Im2D<Type,tBase> aImIn,
tBase * aDFilter,int aDebX,int aFinX,
int aNbShitX,
cConvolSpec<Type> * aCS
)
{
ELISE_ASSERT(aImOut.sz()==aImIn.sz(),"Sz in SetConvolSepX");
int aSzX = aImOut.tx();
int aSzY = aImOut.ty();
int aX0 = -aDebX;
int aX1 = aSzX-aFinX;
for (int anX = 0 ; anX <aX0 ; anX++)
{
SetConvolBordX(aImOut,aImIn,anX,aDFilter,aDebX,aFinX);
}
for (int anX =aX1 ; anX <aSzX ; anX++)
{
SetConvolBordX(aImOut,aImIn,anX,aDFilter,aDebX,aFinX);
}
const tBase aSom = InitFromDiv(ShiftG(tBase(1),aNbShitX),(tBase*)0);
for (int anY=0 ; anY<aSzY ; anY++)
{
Type * aDOut = aImOut.data()[anY];
Type * aDIn = aImIn.data()[anY];
if (aCS)
{
aCS->Convol(aDOut,aDIn,aX0,aX1);
}
else
{
for (int anX = aX0; anX<aX1 ; anX++)
{
aDOut[anX] = ShiftDr(CorrelLine(aSom,aDIn+anX,aDFilter,aDebX,aFinX),aNbShitX);
}
}
}
}
template <class Type>
void cTplImInMem<Type>::SetConvolSepX
(
const cTplImInMem<Type> & aImIn,
tBase * aDFilter,int aDebX,int aFinX,
int aNbShitX,
cConvolSpec<Type> * aCS
)
{
SetConvolSepX
(
mIm,aImIn.mIm,
aDFilter,aDebX,aFinX,aNbShitX,
aCS
);
}
template <class Type>
void cTplImInMem<Type>::SelfSetConvolSepY
(
tBase * aDFilter,int aDebY,int aFinY,
int aNbShitY,
cConvolSpec<Type> * aCS
)
{
Im2D<Type,tBase> aBufIn(mSz.y,PackTranspo);
Im2D<Type,tBase> aBufOut(mSz.y,PackTranspo);
Type ** aData = mIm.data();
for (int anX = 0; anX<mSz.x ; anX+=PackTranspo)
{
ELISE_ASSERT(false,"::SelfSetConvolSepY NOT FINISH (bord ...)");
/*
int aDelta = mSz.x-anX;
int aDebord = ElMax(0,PackTranspo-anX);
anX = ElMin(anX,mSz.x-PackTranspo); POUR EVITER LES DEBORDEMENTS - MARCHE PAS NON PLUS
*/
Type * aL0 = aBufIn.data()[0];
Type * aL1 = aBufIn.data()[1];
Type * aL2 = aBufIn.data()[2];
Type * aL3 = aBufIn.data()[3];
for (int aY=0 ; aY<mSz.y ; aY++)
{
Type * aL = aData[aY]+anX;
*(aL0)++ = *(aL++);
*(aL1)++ = *(aL++);
*(aL2)++ = *(aL++);
*(aL3)++ = *(aL++);
}
SetConvolSepX
(
aBufOut,aBufIn,
aDFilter,aDebY,aFinY,aNbShitY,
aCS
);
aL0 = aBufOut.data()[0];
aL1 = aBufOut.data()[1];
aL2 = aBufOut.data()[2];
aL3 = aBufOut.data()[3];
for (int aY=0 ; aY<mSz.y ; aY++)
{
Type * aL = aData[aY]+anX;
*(aL)++ = *(aL0++);
*(aL)++ = *(aL1++);
*(aL)++ = *(aL2++);
*(aL)++ = *(aL3++);
}
}
}
template <class Type>
void cTplImInMem<Type>::SetConvolSepXY
(
const cTplImInMem<Type> & aImIn,
Im1D<tBase,tBase> aKerXY,
int aNbShitXY
)
{
ELISE_ASSERT(mSz==aImIn.mSz,"Size im diff in ::SetConvolSepXY");
int aSzKer = aKerXY.tx();
ELISE_ASSERT(aSzKer%2,"Taille paire pour ::SetConvolSepXY");
aSzKer /= 2;
tBase * aData = aKerXY.data() + aSzKer;
// Parfois il y a "betement" des 0 en fin de ligne ...
while (aSzKer && (aData[aSzKer]==0) && (aData[-aSzKer]==0))
aSzKer--;
if (mAppli.GenereCodeConvol().IsInit())
{
MakeClassConvolSpec
(
mAppli.FileGGC_H(),
mAppli.FileGGC_Cpp(),
aData,
-aSzKer,
aSzKer,
aNbShitXY
);
// return;
}
if ((mAppli.ShowTimes().Val() > 100) && (mResolGlob==1))
{
std::cout << "Nb = " << aSzKer << " ;; " ;
for (int aK=-aSzKer ; aK<=aSzKer ; aK++)
std::cout << aData[aK] << " ";
std::cout << "\n";
}
cConvolSpec<Type> * aCS= mAppli.UseConvolSpec().Val() ?
cConvolSpec<Type>::Get(aData,-aSzKer,aSzKer,aNbShitXY,false) :
0 ;
if (mAppli.ShowConvolSpec().Val())
std::cout << "CS = " << aCS << "\n";
if (mAppli.ExigeCodeCompile().Val() && (aCS==0))
{
ELISE_ASSERT(false,"cannot find code compiled\n");
}
ElTimer aChrono;
SetConvolSepX(aImIn,aData,-aSzKer,aSzKer,aNbShitXY,aCS);
double aTX = aChrono.uval();
aChrono.reinit();
SelfSetConvolSepY(aData,-aSzKer,aSzKer,aNbShitXY,aCS);
double aTY = aChrono.uval();
aChrono.reinit();
if (mAppli.ShowTimes().Val() > 100)
{
std::cout << "Time convol , X : " << aTX << " , Y : " << aTY << " SzK " << aKerXY.tx() << "\n";
}
}
void TestConvol()
{
int aT1 = 5;
int aT2 = 3;
Im1D_REAL8 aI1 = GaussianKernel(2.0,aT1,10);
Im1D_REAL8 aI2 = GaussianKernel(1.0,aT2,10);
// ELISE_COPY(aI1.all_pts(),FX==aT1,aI1.out());
// ELISE_COPY(aI2.all_pts(),FX==aT2,aI2.out());
Im1D_REAL8 aI3 = Convol(aI1,aI2);
Im1D_REAL8 aI2B = DeConvol(2,aI1,aI3);
Im1D_REAL8 aI4 = Convol(aI1,aI2B);
for (int aK=0 ; aK<ElMax(aI3.tx(),aI4.tx()) ; aK++)
{
std::cout
<< aK << ":"
<< " " << (aK<aI3.tx() ? ToString(aI3.data()[aK]) : " XXXXXX " )
<< " " << (aK<aI1.tx() ? ToString(aI1.data()[aK]) : " XXXXXX " )
<< " " << (aK<aI2.tx() ? ToString(aI2.data()[aK]) : " XXXXXX " )
<< " " << (aK<aI2B.tx() ? ToString(aI2B.data()[aK]) : " XXXXXX " )
<< " " << (aK<aI4.tx() ? ToString(aI4.data()[aK]) : " XXXXXX " )
<< "\n";
}
}
/*
template <class Type>
void cTplImInMem<Type>::MakeConvolInit(double aV)
{
// TestConvol();
const cPyramideGaussienne aPG = mAppli.TypePyramide().PyramideGaussienne().Val();
mNbShift = aPG.NbShift().Val();
mTFille->mNbShift = mNbShift;
mKernelTot = GaussianKernelFromResidu
(
mResolOctaveBase,
aPG.EpsilonGauss().Val(),
aPG.SurEchIntegralGauss().Val()
);
if (aV==0) return;
if (aV==-1) aV = mResolOctaveBase;
ELISE_ASSERT(aV>0,"Bad value in ConvolFirstImage");
ElTimer aChrono;
Im1D_REAL8 aKR = GaussianKernelFromResidu
(
aV,
aPG.EpsilonGauss().Val(),
aPG.SurEchIntegralGauss().Val()
);
int aShift = aPG.NbShift().Val();
Im1D<tBase,tBase> aOwnK = ToOwnKernel(aKR,aShift,true,(tBase *)0);
if (mAppli.ShowTimes().Val() > 100)
{
std::cout << "NB KER GAUSS " << aKR.tx() << "\n";
for (int aK=0 ; aK<aKR.tx() ; aK++)
{
std::cout << " G[" << aK << "]=" << aKR.data()[aK] << " " << aOwnK.data()[aK] << "\n";
}
}
int aKInOct = mTFille->mKInOct;
mTFille->mKInOct = mKInOct;
mTFille->SetConvolSepXY(*this,aOwnK,aShift);
mTFille->mKInOct = aKInOct;
for (int anY=0;anY<mSz.y; anY++)
{
memcpy
(
mIm.data()[anY],
mTFille->mIm.data()[anY],
mSz.x*sizeof(Type)
);
}
if (mAppli.ShowTimes().Val() > 100)
{
std::cout << "Time Convol Init " << aChrono.uval() << "\n";
}
}
*/
template <class Type>
void cTplImInMem<Type>::ReduceGaussienne()
{
const cPyramideGaussienne aPG = mAppli.TypePyramide().PyramideGaussienne().Val();
int aSurEch = aPG.SurEchIntegralGauss().Val();
double anEpsilon = aPG.EpsilonGauss().Val();
mNbShift = aPG.NbShift().Val();
if (mMere && (RGlob()!=mMere->RGlob()))
{
mOrigOct->MakeReduce(*(mMere->Oct().ImBase()),mAppli.PyramideImage().ReducDemiImage().Val());
}
Resize(mOrigOct->Sz());
// Valeur a priori du sigma en delta / au prec
double aSigTot = mResolOctaveBase;;
int aNbCTot = NbElemForGausKern(aSigTot,aPG.EpsilonGauss().Val()/10) +1 ;
Im1D_REAL8 aKerTot=GaussianKernel(aSigTot,aNbCTot,aSurEch);
bool isIncrem = aPG.ConvolIncrem().Val();
if (mAppli.ModifGCC())
isIncrem = mAppli.ModifGCC()->ConvolIncrem();
if (InitRandom())
{
return;
}
if (! isIncrem)
{
Im1D<tBase,tBase> aIKerTotD = ToOwnKernel(aKerTot,mNbShift,true,(tBase *)0);
if (0)
{
for (int aK=0 ; aK<aIKerTotD.tx() ; aK++)
{
std::cout << " " << aIKerTotD.data()[aK] ;
}
std::cout << "\n";
}
SetConvolSepXY(*mOrigOct,aIKerTotD,mNbShift);
return;
}
// ELISE_ASSERT(false,"Pb with convol incrementale\n");
double aSigmD = sqrt(ElSquare(aSigTot) - ElSquare(mTMere->mResolOctaveBase));
int aNbCD= NbElemForGausKern(aSigmD,anEpsilon);
Im1D_REAL8 aKerD = DeConvol(aNbCD,mTMere->mKernelTot,aKerTot);
// Bug ou incoherence dans la deconvol, donne pb
aKerD = GaussianKernelFromResidu(aSigmD,anEpsilon,aSurEch);
// Im1D_REAL8 GaussianKernelFromResidu(double aSigma,double aResidu,int aSurEch)
Im1D<tBase,tBase> aIKerD = ToOwnKernel(aKerD,mNbShift,true,(tBase *)0);
SetConvolSepXY(*mTMere,aIKerD,mNbShift);
Im1D_REAL8 aRealKerD = ToRealKernel(aIKerD);
mKernelTot = Convol(aRealKerD,mTMere->mKernelTot);
if ((mAppli.ShowTimes().Val() > 100) && (mResolGlob<=2))
{
/*
std::cout << " + + + CONVOL + + \n";
for (int aK=0 ; aK< mKernelTot.tx() ; aK++)
{
std::cout << mKernelTot.data()[aK] << ((aK==mKernelTot.tx()/2)? " @@@@@" : "")<< "\n";
}
std::cout << " + + + GLOB + + \n";
for (int aK=0 ; aK< aKerTot.tx() ; aK++)
{
std::cout << aKerTot.data()[aK] << ((aK==aKerTot.tx()/2)? " @@@@@" : "")<< "\n";
}
*/
Im1D_REAL8 aSigKer = GaussianKernel(aSigmD,aNbCD,aSurEch);
std::cout << "---------------------------------------------------------\n";
std::cout << " DZ " << mResolGlob << " ; "
<< " K " << mKInOct
<< " Sig-Delta " << aSigmD << " ; "
<< " NbC-Delta " << aNbCD << " ; "
<< " NbC-Tot " << aNbCTot << " ; "
<< "\n";
for (int aK=0 ; aK<aKerD.tx() ; aK++)
{
std::cout << " " << aIKerD.data()[aK] ;
}
std::cout << "\n";
// if (mAppli.ShowTimes().Val() > 100)
if (0)
{
for (int aK=0 ; aK<aKerD.tx() ; aK++)
{
if (aK<aKerD.tx()) std::cout << " Cur= " << aKerD.data()[aK] << " ";
if (aK<aKerD.tx()) std::cout << " ICur= " << aRealKerD.data()[aK] << " ";
if (aK<aKerD.tx()) std::cout << " SCur= " << aSigKer.data()[aK] << " ";
std::cout << "\n";
}
}
//getchar();
}
}
InstantiateClassTplDigeo(cTplImInMem)
/*
template class cTplImInMem<U_INT1>;
template class cTplImInMem<U_INT2>;
template class cTplImInMem<INT>;
template class cTplImInMem<float>;
*/
/****************************************/
/* */
/* cImInMem */
/* */
/****************************************/
/*
void cImInMem::MakeReduce()
{
VMakeReduce(*mMere);
}
*/
};
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| 27.884567 | 111 | 0.555571 | [
"vector"
] |
5c6766538913dfedd30af7fee80bbe44959007a2 | 8,738 | cpp | C++ | release/examples/C++ Hello World/generated/snb_api.cpp | rohitmaurya-png/SHARP-PROGRAMING-LANGUAGE | 17a792d54765468116fd6bfdec62969a77d4d809 | [
"MIT"
] | null | null | null | release/examples/C++ Hello World/generated/snb_api.cpp | rohitmaurya-png/SHARP-PROGRAMING-LANGUAGE | 17a792d54765468116fd6bfdec62969a77d4d809 | [
"MIT"
] | null | null | null | release/examples/C++ Hello World/generated/snb_api.cpp | rohitmaurya-png/SHARP-PROGRAMING-LANGUAGE | 17a792d54765468116fd6bfdec62969a77d4d809 | [
"MIT"
] | null | null | null | #include "snb_api.h"
namespace snb_api {
// private fields
namespace internal {
_inc_ref inc_ref;
_dec_ref dec_ref;
_getfpNumAt getfpNumAt;
_getField getField;
_getVarPtr getVarPtr;
_getfpLocalAt getfpLocalAt;
_getSize getSize;
_setObject setObject;
_staticClassInstance staticClassInstance;
_inc_sp inc_sp;
_getspNumAt getSpNumAt;
_getspObjAt getSpObjAt;
_newVarArray newVarArray;
_newClass newClass;
_newObjArray newObjArray;
_newClassArray newClassArray;
_decSp decSp;
_pushNum pushNum;
_pushObj pushObj;
_call call;
_exceptionCheck exceptionCheck;
_getExceptionObject getExceptionObject;
_className className;
_prepareException prepareException;
_clearException clearExcept;
_getItem getDataItem;
int handshake(void *lib_funcs[], int size) {
if (size == 26) {
inc_ref = (_inc_ref) lib_funcs[0];
dec_ref = (_dec_ref) lib_funcs[1];
getfpNumAt = (_getfpNumAt) lib_funcs[2];
getField = (_getField) lib_funcs[3];
getVarPtr = (_getVarPtr) lib_funcs[4];
getfpLocalAt = (_getfpLocalAt) lib_funcs[5];
getSize = (_getSize) lib_funcs[6];
setObject = (_setObject) lib_funcs[7];
staticClassInstance = (_staticClassInstance) lib_funcs[8];
inc_sp = (_inc_sp) lib_funcs[9];
getSpNumAt = (_getspNumAt) lib_funcs[10];
getSpObjAt = (_getspObjAt) lib_funcs[11];
newVarArray = (_newVarArray) lib_funcs[12];
newClass = (_newClass) lib_funcs[13];
newObjArray = (_newObjArray) lib_funcs[14];
newClassArray = (_newClassArray) lib_funcs[15];
decSp = (_decSp) lib_funcs[16];
pushNum = (_pushNum) lib_funcs[17];
pushObj = (_pushObj) lib_funcs[18];
call = (_call) lib_funcs[19];
exceptionCheck = (_exceptionCheck) lib_funcs[20];
getExceptionObject = (_getExceptionObject) lib_funcs[21];
className = (_className) lib_funcs[22];
prepareException = (_prepareException) lib_funcs[23];
clearExcept = (_clearException) lib_funcs[24];
getDataItem = (_getItem) lib_funcs[25];
return inc_ref && dec_ref && getfpNumAt && getField
&& getVarPtr && getfpLocalAt && getSize && setObject
&& staticClassInstance && inc_sp && getSpNumAt
&& getSpObjAt && decSp && pushNum && pushObj
&& call && newVarArray && newClass && newObjArray
&& newClassArray && exceptionCheck && getExceptionObject
&& className && prepareException && clearExcept
&& getDataItem;
} else return false;
}
}
using namespace internal;
object getItem(object obj, int32_t index) {
return getDataItem(obj, index);
}
void clearException() {
clearExcept();
}
const char* getClassName(object klazz) {
return className(klazz);
}
void throwException(object exceptionClass) {
throw Exception(exceptionClass, "");
}
template<class T> T cast_to(object obj) {
if(obj) {
T val(getVarPtr(obj), obj);
return val;
} else {
T val(NULL);
return val;
}
}
template<class T> T get(object obj, string field) {
object fieldObj = getField(obj, field.c_str());
if(fieldObj) {
T val(getVarPtr(fieldObj), fieldObj);
return val;
} else {
T val(NULL);
return val;
}
}
template<> var_array get<var_array>(object obj, string field) {
object fieldObj = getField(obj, field.c_str());
if(fieldObj) {
var_array val(getVarPtr(fieldObj), getSize(fieldObj), fieldObj);
return val;
} else {
var_array val(NULL);
return val;
}
}
template<> object get<object>(object obj, string field) {
return getField(obj, field.c_str());
}
template<> var_array cast_to<var_array>(object obj) {
if(obj) {
var_array val(getVarPtr(obj), getSize(obj), obj);
return val;
} else {
var_array val(NULL);
return val;
}
}
int set(object dest, var_array &arry) {
return set(dest, arry.handle);
}
int set(object dest, object src) {
return setObject(dest, src);
}
void incRef(object obj){
inc_ref(obj);
}
void decRef(object obj){
dec_ref(obj);
}
object getStaticClassInstance(const string& name) {
return staticClassInstance(name.c_str());
}
string stringFrom(const var_array &arry) {
stringstream ss;
for(int32_t i = 0; i < arry.size; i++) {
ss << (char)arry.at(i);
}
return ss.str();
}
template <class T>
T createLocalField() {
inc_sp();
T val(getSpNumAt(0));
val = 0;
return val;
}
template<> object createLocalField<object>() {
inc_sp();
object field = getSpObjAt(0);
set(field, NULL);
return field;
}
template<> var_array createLocalField<var_array>() {
inc_sp();
object handle = getSpObjAt(0);
set(handle, NULL);
var_array field(NULL, 0, handle);
return field;
}
void createVarArray(var_array &field, int32_t size) {
object newObj = newVarArray(size);
if(exceptionCheck()) {
throw Exception(getExceptionObject(), "");
}
field.num = getVarPtr(newObj);
field.size = size;
set(field.handle, newObj);
}
void createClassArray(object field, const string &name, int32_t size) {
set(field, newClassArray(name.c_str(), size));
if(exceptionCheck()) {
throw Exception(getExceptionObject(), "");
}
}
void createClass(object field, const string &name) {
set(field, newClass(name.c_str()));
if(exceptionCheck()) {
throw Exception(getExceptionObject(), "");
}
}
void createObjectArray(object field, int32_t size) {
set(field, newObjArray(size));
if(exceptionCheck()) {
throw Exception(getExceptionObject(), "");
}
}
void unTrack(int32_t amount) {
decSp(amount);
if(exceptionCheck()) {
throw Exception(getExceptionObject(), "");
}
}
void set(var_array &arry, const char *str) {
if(arry.handle) {
if(str == NULL) {
createVarArray(arry, 0);
return;
}
long len = strlen(str);
if(arry.size != len)
createVarArray(arry, len);
for(long i = 0; i < len; i++) {
arry[i] = str[i];
}
}
}
void set(var_array &arry, string& str) {
set(arry, str.c_str());
}
};
#pragma GCC push_options
#pragma GCC optimize ("O0")
/*
* This allow the compiler to properly link each template function
*/
void dead_func() {
using namespace snb_api;
createLocalField<var>();
createLocalField<_int8>();
createLocalField<_int16>();
createLocalField<_int16>();
createLocalField<_int32>();
createLocalField<_int64>();
createLocalField<_uint8>();
createLocalField<_uint16>();
createLocalField<_uint32>();
createLocalField<_uint64>();
createLocalField<var_array>();
object obj;
cast_to<var>(obj);
cast_to<_int8>(obj);
cast_to<_int16>(obj);
cast_to<_int16>(obj);
cast_to<_int32>(obj);
cast_to<_int64>(obj);
cast_to<_uint8>(obj);
cast_to<_uint16>(obj);
cast_to<_uint32>(obj);
cast_to<_uint64>(obj);
cast_to<var_array>(obj);
get<var>(obj, "");
get<_int8>(obj, "");
get<_int16>(obj, "");
get<_int16>(obj, "");
get<_int32>(obj, "");
get<_int64>(obj, "");
get<_uint8>(obj, "");
get<_uint16>(obj, "");
get<_uint32>(obj, "");
get<_uint64>(obj, "");
get<var_array>(obj, "");
}
#pragma pop_options
#ifdef __cplusplus
extern "C" {
#endif
EXPORTED short snb_handshake(void* lib_funcs[], int size) {
return snb_api::internal::handshake(lib_funcs, size);
}
#ifdef __cplusplus
}
#endif
| 27.052632 | 79 | 0.554017 | [
"object"
] |
5c6e5c424600a1c330dbd42881153c5ad3876a1b | 5,131 | cpp | C++ | adapters-stk/test/local_mesh/PanzerSTK_UnitTest_BuildMesh.cpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T03:49:50.000Z | 2022-03-22T03:49:50.000Z | adapters-stk/test/local_mesh/PanzerSTK_UnitTest_BuildMesh.cpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | adapters-stk/test/local_mesh/PanzerSTK_UnitTest_BuildMesh.cpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | #include "PanzerSTK_UnitTest_BuildMesh.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_Assert.hpp"
#include "Panzer_STK_Interface.hpp"
#include "PanzerSTK_UnitTest_STKInterfaceGenerator.hpp"
namespace panzer_stk
{
Teuchos::RCP<panzer_stk::STK_Interface>
buildMesh(const std::vector<int> & N,
const std::vector<int> & B,
const std::vector<double> & L)
{
const int num_dims = N.size();
TEUCHOS_ASSERT(L.size() == static_cast<std::size_t>(num_dims));
Teuchos::ParameterList mesh_parameters("Mesh");
mesh_parameters.set<double>("X0",-L[0]/2.);
mesh_parameters.set<double>("Xf", L[0]/2.);
mesh_parameters.set<int>("X Elements", N[0]);
mesh_parameters.set<int>("X Blocks", B[0]);
if(num_dims>1){
mesh_parameters.set<double>("Y0",-L[1]/2.);
mesh_parameters.set<double>("Yf", L[1]/2.);
mesh_parameters.set<int>("Y Elements", N[1]);
mesh_parameters.set<int>("Y Blocks", B[1]);
}
if(num_dims>2){
mesh_parameters.set<double>("Z0",-L[2]/2.);
mesh_parameters.set<double>("Zf", L[2]/2.);
mesh_parameters.set<int>("Z Elements", N[2]);
mesh_parameters.set<int>("Z Blocks", B[2]);
}
if(num_dims == 1){
mesh_parameters.set<std::string>("Mesh Type","Line");
} else if(num_dims == 2){
mesh_parameters.set<std::string>("Mesh Type","Quad");
} else if(num_dims == 3){
mesh_parameters.set<std::string>("Mesh Type","Hex");
} else {
TEUCHOS_ASSERT(false);
}
return generateMesh(mesh_parameters);
}
Teuchos::RCP<panzer_stk::STK_Interface>
buildParallelMesh(const std::vector<int> & N,
const std::vector<int> & B,
const std::vector<int> & P,
const std::vector<double> & L,
const std::vector<int> & periodic_dims)
{
const size_t num_dims = N.size();
TEUCHOS_ASSERT(L.size() == num_dims);
TEUCHOS_ASSERT(P.size() == num_dims);
Teuchos::ParameterList mesh_parameters("Mesh");
mesh_parameters.set<double>("X0",-L[0]/2.);
mesh_parameters.set<double>("Xf", L[0]/2.);
mesh_parameters.set<int>("X Elements", N[0]);
mesh_parameters.set<int>("X Blocks", B[0]);
// The line mesh factory doesn't allow this
if(num_dims>1)
mesh_parameters.set<int>("X Procs", P[0]);
if(num_dims>1){
mesh_parameters.set<double>("Y0",-L[1]/2.);
mesh_parameters.set<double>("Yf", L[1]/2.);
mesh_parameters.set<int>("Y Elements", N[1]);
mesh_parameters.set<int>("Y Blocks", B[1]);
mesh_parameters.set<int>("Y Procs", P[1]);
}
if(num_dims>2){
mesh_parameters.set<double>("Z0",-L[2]/2.);
mesh_parameters.set<double>("Zf", L[2]/2.);
mesh_parameters.set<int>("Z Elements", N[2]);
mesh_parameters.set<int>("Z Blocks", B[2]);
mesh_parameters.set<int>("Z Procs", P[2]);
}
if(num_dims == 1){
mesh_parameters.set<std::string>("Mesh Type","Line");
} else if(num_dims == 2){
mesh_parameters.set<std::string>("Mesh Type","Quad");
} else if(num_dims == 3){
mesh_parameters.set<std::string>("Mesh Type","Hex");
} else {
TEUCHOS_ASSERT(false);
}
if(periodic_dims.size() > 0){
auto & periodic_params = mesh_parameters.sublist("Periodic BCs");
int arg=1;
for(const auto & periodic_dim : periodic_dims){
if(periodic_dim == 0){
if(num_dims==1)
periodic_params.set("Periodic Condition " +std::to_string(arg++), "y-coord 1.e-8: left;right");
else if(num_dims==2){
periodic_params.set("Periodic Condition " +std::to_string(arg++), "y-coord 1.e-8: left;right");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "y-edge 1.e-8: left;right");
} else if(num_dims==3){
periodic_params.set("Periodic Condition " +std::to_string(arg++), "yz-coord 1.e-8: left;right");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "yz-edge 1.e-8: left;right");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "yz-face 1.e-8: left;right");
}
} else if(periodic_dim == 1){
if(num_dims==2){
periodic_params.set("Periodic Condition " +std::to_string(arg++), "x-coord 1.e-8: top;bottom");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "x-edge 1.e-8: top;bottom");
} else if(num_dims==3){
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xz-coord 1.e-8: top;bottom");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xz-edge 1.e-8: top;bottom");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xz-face 1.e-8: top;bottom");
}
} else if(periodic_dim == 2){
if(num_dims==3){
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xy-coord 1.e-8: front;back");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xy-edge 1.e-8: front;back");
periodic_params.set("Periodic Condition " +std::to_string(arg++), "xy-face 1.e-8: front;back");
}
}
}
periodic_params.set("Count",arg-1);
}
return generateMesh(mesh_parameters);
}
}
| 35.631944 | 106 | 0.627168 | [
"mesh",
"vector"
] |
5c6ffa257e874c52ebf65f83d841898918b05654 | 1,058 | cc | C++ | tests/test_similarity_mean.cc | xuzhezhaozhao/fastText_dnn | 3c6f56b5dce49982777e9d5707da3af0f4d96af6 | [
"BSD-3-Clause"
] | 1 | 2020-12-21T14:56:52.000Z | 2020-12-21T14:56:52.000Z | tests/test_similarity_mean.cc | xuzhezhaozhao/fastText_dnn | 3c6f56b5dce49982777e9d5707da3af0f4d96af6 | [
"BSD-3-Clause"
] | null | null | null | tests/test_similarity_mean.cc | xuzhezhaozhao/fastText_dnn | 3c6f56b5dce49982777e9d5707da3af0f4d96af6 | [
"BSD-3-Clause"
] | 1 | 2020-12-21T14:57:09.000Z | 2020-12-21T14:57:09.000Z |
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "../src/fasttext_api.h"
namespace {
void printUsage() {
std::cerr
<< "Usage: ./test <model> <ntarget> <nquery> <target ...> <query ...>"
<< std::endl;
}
}
int main(int argc, char *argv[]) {
if (argc < 6) {
printUsage();
exit(1);
}
fasttext::FastTextApi fapi;
fapi.LoadModel(argv[1]);
fapi.PrecomputeWordVectors(true);
int ntarget = std::stoi(argv[2]);
int nquery = std::stoi(argv[3]);
if (argc < 4 + ntarget + nquery) {
printUsage();
exit(1);
}
std::vector<std::string> targets;
for (int i = 0; i < ntarget; ++i) {
targets.push_back(argv[4 + i]);
}
std::vector<std::string> queries;
for (int i = 0; i < nquery; ++i) {
queries.push_back(argv[4 + ntarget + i]);
}
std::vector<std::vector<std::string>> Q_list;
Q_list.push_back(queries);
auto similarity = fapi.ComputeSimilarityMean(targets, Q_list);
for (auto f : similarity) {
std::cout << f << std::endl;
}
return 0;
}
| 19.592593 | 78 | 0.591682 | [
"vector",
"model"
] |
5c70f7428567562ff84ade4e4b537fef5bd5bacf | 5,734 | cpp | C++ | src/Meta/NameRetrieverVisitor.cpp | NativeScript/ios-metadata-generator | a7284c1e74e56335aa35988b17c3672ef5d63fa4 | [
"Apache-2.0"
] | 14 | 2015-03-28T18:02:45.000Z | 2020-11-12T04:33:55.000Z | src/Meta/NameRetrieverVisitor.cpp | NativeScript/ios-metadata-generator | a7284c1e74e56335aa35988b17c3672ef5d63fa4 | [
"Apache-2.0"
] | 32 | 2015-04-15T10:11:06.000Z | 2016-09-02T14:23:47.000Z | src/Meta/NameRetrieverVisitor.cpp | NativeScript/ios-metadata-generator | a7284c1e74e56335aa35988b17c3672ef5d63fa4 | [
"Apache-2.0"
] | 6 | 2015-03-12T16:23:41.000Z | 2020-03-05T20:58:48.000Z | //
// NameRetrieverVisitor.cpp
// objc-metadata-generator
//
// Created by Martin Bekchiev on 3.09.18.
//
#include "NameRetrieverVisitor.h"
#include "MetaEntities.h"
#include <sstream>
NameRetrieverVisitor NameRetrieverVisitor::instanceObjC(false);
NameRetrieverVisitor NameRetrieverVisitor::instanceTs(true);
std::string NameRetrieverVisitor::visitVoid() {
return "void";
}
std::string NameRetrieverVisitor::visitBool() {
return this->tsNames ? "boolean" : "bool";
}
std::string NameRetrieverVisitor::visitShort() {
return this->tsNames ? "number" : "short";
}
std::string NameRetrieverVisitor::visitUShort() {
return this->tsNames ? "number" : "unsigned short";
}
std::string NameRetrieverVisitor::visitInt() {
return this->tsNames ? "number" : "int";
}
std::string NameRetrieverVisitor::visitUInt() {
return this->tsNames ? "number" : "unsigned int";
}
std::string NameRetrieverVisitor::visitLong() {
return this->tsNames ? "number" : "long";
}
std::string NameRetrieverVisitor::visitUlong() {
return this->tsNames ? "number" : "unsigned long";
}
std::string NameRetrieverVisitor::visitLongLong() {
return this->tsNames ? "number" : "long long";
}
std::string NameRetrieverVisitor::visitULongLong() {
return this->tsNames ? "number" : "unsigned long long";
}
std::string NameRetrieverVisitor::visitSignedChar() {
return this->tsNames ? "number" : "signed char";
}
std::string NameRetrieverVisitor::visitUnsignedChar() {
return this->tsNames ? "number" : "unsigned char";
}
std::string NameRetrieverVisitor::visitUnichar() {
return this->tsNames ? "number" : "wchar_t";
}
std::string NameRetrieverVisitor::visitCString() {
return this->tsNames ? "string" : "char*";
}
std::string NameRetrieverVisitor::visitFloat() {
return this->tsNames ? "number" : "float";
}
std::string NameRetrieverVisitor::visitDouble() {
return this->tsNames ? "number" : "double";
}
std::string NameRetrieverVisitor::visitVaList() {
return "";
}
std::string NameRetrieverVisitor::visitSelector() {
return this->tsNames ? "string" : "SEL";
}
std::string NameRetrieverVisitor::visitInstancetype() {
return this->tsNames ? "any" : "instancetype";
}
std::string NameRetrieverVisitor::visitClass(const ClassType& typeDetails) {
return this->tsNames ? "any" : "Class";
}
std::string NameRetrieverVisitor::visitProtocol() {
return this->tsNames ? "any" : "Protocol";
}
std::string NameRetrieverVisitor::visitId(const IdType& typeDetails) {
return this->tsNames ? "any" : "id";
}
std::string NameRetrieverVisitor::visitConstantArray(const ConstantArrayType& typeDetails) {
return this->generateFixedArray(typeDetails.innerType, typeDetails.size);
}
std::string NameRetrieverVisitor::visitExtVector(const ExtVectorType& typeDetails) {
return this->generateFixedArray(typeDetails.innerType, typeDetails.size);
}
std::string NameRetrieverVisitor::visitIncompleteArray(const IncompleteArrayType& typeDetails) {
return typeDetails.innerType->visit(*this).append("[]");
}
std::string NameRetrieverVisitor::visitInterface(const InterfaceType& typeDetails) {
return this->tsNames ? typeDetails.interface->jsName : typeDetails.interface->name;
}
std::string NameRetrieverVisitor::visitBridgedInterface(const BridgedInterfaceType& typeDetails) {
return typeDetails.name;
}
std::string NameRetrieverVisitor::visitPointer(const PointerType& typeDetails) {
return this->tsNames ? "any" : typeDetails.innerType->visit(*this).append("*");
}
std::string NameRetrieverVisitor::visitBlock(const BlockType& typeDetails) {
return this->tsNames ? this->getFunctionTypeScriptName(typeDetails.signature) : "void*" /*TODO: construct objective-c full block definition*/;
}
std::string NameRetrieverVisitor::visitFunctionPointer(const FunctionPointerType& typeDetails) {
return this->tsNames ? this->getFunctionTypeScriptName(typeDetails.signature) : "void*"/*TODO: construct objective-c full function pointer definition*/;
}
std::string NameRetrieverVisitor::visitStruct(const StructType& typeDetails) {
return this->tsNames ? typeDetails.structMeta->jsName : typeDetails.structMeta->name;
}
std::string NameRetrieverVisitor::visitUnion(const UnionType& typeDetails) {
return this->tsNames ? typeDetails.unionMeta->jsName : typeDetails.unionMeta->name;
}
std::string NameRetrieverVisitor::visitAnonymousStruct(const AnonymousStructType& typeDetails) {
return "";
}
std::string NameRetrieverVisitor::visitAnonymousUnion(const AnonymousUnionType& typeDetails) {
return "";
}
std::string NameRetrieverVisitor::visitEnum(const EnumType& typeDetails) {
return this->tsNames ? typeDetails.enumMeta->jsName : typeDetails.enumMeta->name;
}
std::string NameRetrieverVisitor::visitTypeArgument(const ::Meta::TypeArgumentType& type) {
return type.name;
}
std::string NameRetrieverVisitor::generateFixedArray(const Type *el_type, size_t size) {
std::stringstream ss(el_type->visit(*this));
ss << "[";
if (!this->tsNames) {
ss << size;
}
ss << "]";
return ss.str();
}
std::string NameRetrieverVisitor::getFunctionTypeScriptName(const std::vector<Type*> &signature) {
// (p1: t1,...) => ret_type
assert(signature.size() > 0);
std::stringstream ss;
ss << "(";
for (size_t i = 1; i < signature.size(); i++) {
if (i > 1) {
ss << ", ";
}
ss << "p" << i << ": " << signature[i]->visit(*this);
}
ss << ")";
ss << " => ";
ss << signature[0]->visit(*this);
return ss.str();
}
| 30.178947 | 156 | 0.693059 | [
"vector"
] |
f076772454679d36464b5a919dbcc2d778a9c46e | 8,650 | cpp | C++ | src/caffe/blob.cpp | kranthisai/apollocaffe-pi | 415ff96e9825f39ad33fa7d4686c9560d9b359f8 | [
"BSD-2-Clause"
] | 3 | 2017-03-27T17:07:36.000Z | 2022-01-31T18:18:44.000Z | src/caffe/blob.cpp | LihangLiu93/apollocaffe | df44c36295b6ec6db9a336508a2b378e04e5be0b | [
"BSD-2-Clause"
] | 1 | 2019-01-26T19:15:04.000Z | 2019-01-26T19:15:04.000Z | src/caffe/blob.cpp | LihangLiu93/apollocaffe | df44c36295b6ec6db9a336508a2b378e04e5be0b | [
"BSD-2-Clause"
] | 6 | 2016-08-01T18:19:13.000Z | 2020-02-19T04:51:52.000Z | #include <climits>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void Blob<Dtype>::Init() {
data_.reset(new Tensor<Dtype>());
diff_.reset(new Tensor<Dtype>());
}
template <typename Dtype>
void Blob<Dtype>::Reshape(const int num, const int channels, const int height,
const int width) {
vector<int> shape(4);
shape[0] = num;
shape[1] = channels;
shape[2] = height;
shape[3] = width;
Reshape(shape);
}
template <typename Dtype>
void Blob<Dtype>::Reshape(const vector<int>& shape) {
data_->Reshape(shape);
diff_->Reshape(shape);
}
template <typename Dtype>
void Blob<Dtype>::Reshape(const BlobShape& shape) {
ASSERT(shape.dim_size() <= kMaxBlobAxes, "");
vector<int> shape_vec(shape.dim_size());
for (int i = 0; i < shape.dim_size(); ++i) {
shape_vec[i] = shape.dim(i);
}
Reshape(shape_vec);
}
template <typename Dtype>
void Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other) {
Reshape(other.shape());
}
template <typename Dtype>
Blob<Dtype>::Blob(const int num, const int channels, const int height,
const int width) {
Init();
Reshape(num, channels, height, width);
}
template <typename Dtype>
Blob<Dtype>::Blob(const vector<int>& shape) {
Init();
Reshape(shape);
}
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_data() const {
ASSERT(data_, "");
return (const Dtype*)data_->cpu_mem();
}
template <typename Dtype>
void Blob<Dtype>::set_cpu_data(Dtype* data) {
ASSERT(data, "");
data_->set_cpu_mem(data);
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_data() const {
ASSERT(data_, "");
return (const Dtype*)data_->gpu_mem();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_diff() const {
ASSERT(diff_, "");
return (const Dtype*)diff_->cpu_mem();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_diff() const {
ASSERT(diff_, "");
return (const Dtype*)diff_->gpu_mem();
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_data() {
ASSERT(data_, "");
return static_cast<Dtype*>(data_->mutable_cpu_mem());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_data() {
ASSERT(data_, "");
return static_cast<Dtype*>(data_->mutable_gpu_mem());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_diff() {
ASSERT(diff_, "");
return static_cast<Dtype*>(diff_->mutable_cpu_mem());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_diff() {
ASSERT(diff_, "");
return static_cast<Dtype*>(diff_->mutable_gpu_mem());
}
template <typename Dtype>
void Blob<Dtype>::ShareData(const Blob& other) {
ASSERT(count() == other.count(), "");
data_->ShareMem(*other.data());
}
template <typename Dtype>
void Blob<Dtype>::ShareDiff(const Blob& other) {
ASSERT(count() == other.count(), "");
diff_->ShareMem(*other.diff());
}
// The "update" method is used for parameter blobs in a Net, which are stored
// as Blob<float> or Blob<double> -- hence we do not define it for
// Blob<int> or Blob<unsigned int>.
template <typename Dtype>
void Blob<Dtype>::Update() {
Update(Dtype(1));
}
template <typename Dtype>
void Blob<Dtype>::Update(Dtype lr) {
data_->AddMulFromDynamicMode(*diff_, Dtype(-lr));
}
template <typename Dtype>
Dtype Blob<Dtype>::asum_data() const {
if (!data_) { return 0; }
return data_->asum();
}
template <typename Dtype>
Dtype Blob<Dtype>::asum_diff() const {
if (!diff_) { return 0; }
return diff_->asum();
}
template <typename Dtype>
Dtype Blob<Dtype>::sumsq_data() const {
if (!data_) { return 0; }
return data_->sumsq();
}
template <typename Dtype>
Dtype Blob<Dtype>::sumsq_diff() const {
if (!diff_) { return 0; }
return diff_->sumsq();
}
template <typename Dtype>
void Blob<Dtype>::scale_data(Dtype scale_factor) {
if (!data_) { return; }
data_->scale(scale_factor);
}
template <typename Dtype>
void Blob<Dtype>::scale_diff(Dtype scale_factor) {
if (!diff_) { return; }
diff_->scale(scale_factor);
}
template <typename Dtype>
bool Blob<Dtype>::ShapeEquals(const BlobProto& other) {
if (other.has_num() || other.has_channels() ||
other.has_height() || other.has_width()) {
// Using deprecated 4D Blob dimensions --
// shape is (num, channels, height, width).
// Note: we do not use the normal Blob::num(), Blob::channels(), etc.
// methods as these index from the beginning of the blob shape, where legacy
// parameter blobs were indexed from the end of the blob shape (e.g., bias
// Blob shape (1 x 1 x 1 x N), IP layer weight Blob shape (1 x 1 x M x N)).
return shape().size() <= 4 &&
LegacyShape(-4) == other.num() &&
LegacyShape(-3) == other.channels() &&
LegacyShape(-2) == other.height() &&
LegacyShape(-1) == other.width();
}
vector<int> other_shape(other.shape().dim_size());
for (int i = 0; i < other.shape().dim_size(); ++i) {
other_shape[i] = other.shape().dim(i);
}
return shape() == other_shape;
}
template <typename Dtype>
void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) {
if (source.count() != count() || source.shape() != shape()) {
if (reshape) {
ReshapeLike(source);
} else {
ASSERT(false, "Trying to copy blobs of different sizes.");
}
}
if (copy_diff) {
diff_->CopyFrom(*source.diff());
} else {
data_->CopyFrom(*source.data());
}
}
template <typename Dtype>
void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) {
if (reshape) {
vector<int> shape;
if (proto.has_num() || proto.has_channels() ||
proto.has_height() || proto.has_width()) {
// Using deprecated 4D Blob dimensions --
// shape is (num, channels, height, width).
shape.resize(4);
shape[0] = proto.num();
shape[1] = proto.channels();
shape[2] = proto.height();
shape[3] = proto.width();
} else {
shape.resize(proto.shape().dim_size());
for (int i = 0; i < proto.shape().dim_size(); ++i) {
shape[i] = proto.shape().dim(i);
}
}
Reshape(shape);
} else {
CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)";
}
// copy data
Dtype* data_vec = mutable_cpu_data();
if (proto.double_data_size() > 0) {
CHECK_EQ(count(), proto.double_data_size());
for (int i = 0; i < count(); ++i) {
data_vec[i] = proto.double_data(i);
}
} else {
CHECK_EQ(count(), proto.data_size());
for (int i = 0; i < count(); ++i) {
data_vec[i] = proto.data(i);
}
}
if (proto.double_diff_size() > 0) {
CHECK_EQ(count(), proto.double_diff_size());
Dtype* diff_vec = mutable_cpu_diff();
for (int i = 0; i < count(); ++i) {
diff_vec[i] = proto.double_diff(i);
}
} else if (proto.diff_size() > 0) {
CHECK_EQ(count(), proto.diff_size());
Dtype* diff_vec = mutable_cpu_diff();
for (int i = 0; i < count(); ++i) {
diff_vec[i] = proto.diff(i);
}
}
}
template <>
void Blob<double>::ToProto(BlobProto* proto, bool write_diff) const {
proto->clear_shape();
for (int i = 0; i < shape().size(); ++i) {
proto->mutable_shape()->add_dim(shape()[i]);
}
proto->clear_double_data();
proto->clear_double_diff();
const double* data_vec = cpu_data();
for (int i = 0; i < count(); ++i) {
proto->add_double_data(data_vec[i]);
}
if (write_diff) {
const double* diff_vec = cpu_diff();
for (int i = 0; i < count(); ++i) {
proto->add_double_diff(diff_vec[i]);
}
}
}
template <>
void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const {
proto->clear_shape();
for (int i = 0; i < shape().size(); ++i) {
proto->mutable_shape()->add_dim(shape()[i]);
}
proto->clear_data();
proto->clear_diff();
const float* data_vec = cpu_data();
for (int i = 0; i < count(); ++i) {
proto->add_data(data_vec[i]);
}
if (write_diff) {
const float* diff_vec = cpu_diff();
for (int i = 0; i < count(); ++i) {
proto->add_diff(diff_vec[i]);
}
}
}
template <typename Dtype>
void Blob<Dtype>::SetDataValues(const Dtype value) {
data_->SetValues(value);
}
template <typename Dtype>
void Blob<Dtype>::SetDiffValues(const Dtype value) {
diff_->SetValues(value);
}
template <typename Dtype>
void Blob<Dtype>::AddDataFrom(const Blob& source) {
data_->AddFrom(*source.data());
}
template <typename Dtype>
void Blob<Dtype>::AddDiffFrom(const Blob& source) {
diff_->AddFrom(*source.diff());
}
INSTANTIATE_CLASS(Blob);
template class Blob<int>;
template class Blob<unsigned int>;
} // namespace caffe
| 26.054217 | 80 | 0.641156 | [
"shape",
"vector"
] |
f0772e621696d2bf0ace9aa15b1dd09c42841e91 | 1,922 | cpp | C++ | Codingame/CPP/SinglePlayer/Medium/Scrabble.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null | Codingame/CPP/SinglePlayer/Medium/Scrabble.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null | Codingame/CPP/SinglePlayer/Medium/Scrabble.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int charVal(char c)
{
switch (c)
{
case 'e':
case 'a':
case 'i':
case 'o':
case 'n':
case 'r':
case 't':
case 'l':
case 's':
case 'u':
return 1;
case 'd':
case 'g':
return 2;
case 'b':
case 'c':
case 'm':
case 'p':
return 3;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
return 4;
case 'k':
return 5;
case 'j':
case 'x':
return 8;
case 'q':
case 'z':
return 10;
};
}
int main()
{
vector<string> words;
int N;
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) {
string W;
getline(cin, W);
if (W.length() <= 7)
words.push_back(W);
}
string LETTERS;
getline(cin, LETTERS);
// Find all possible words that can be made with the 7 letters
vector<string> possibleWords;
for (const string& word : words)
{
string sortedWord = word;
sort(LETTERS.begin(), LETTERS.end());
sort(sortedWord.begin(), sortedWord.end());
if (includes(LETTERS.begin(), LETTERS.end(), sortedWord.begin(), sortedWord.end()))
possibleWords.push_back(word);
}
// Find the word that gives us the most letters
int maxVal = 0;
string bestWord;
for (const string& word : possibleWords)
{
int val = 0;
for (char c : word)
val += charVal(c);
if (val > maxVal)
{
maxVal = val;
bestWord = word;
}
}
cout << bestWord << endl;
}
| 19.22 | 91 | 0.431842 | [
"vector"
] |
f07bae9a2804333f0ae62fbcddb4568d5b6532b7 | 7,719 | cpp | C++ | src/subtile/subui.cpp | dream-owl/Subtile | f77eb14c2c8b4810af954d7ba1f81cb31e8eda2c | [
"MIT"
] | null | null | null | src/subtile/subui.cpp | dream-owl/Subtile | f77eb14c2c8b4810af954d7ba1f81cb31e8eda2c | [
"MIT"
] | null | null | null | src/subtile/subui.cpp | dream-owl/Subtile | f77eb14c2c8b4810af954d7ba1f81cb31e8eda2c | [
"MIT"
] | null | null | null | #include "subui.h"
#include "subtile.h"
#include <glad/glad.h>
#include <glad/glad.c>
#include <glfw/glfw3.h>
class stGraphics
{
public:
stGraphics(stGraphics const&) = delete;
stGraphics()
{
static char const* const VertexSource = {
"#version 330\n"
"uniform mat4 uProjection;"
"in vec2 iPosition;"
"in vec2 iTexCoord;"
"out vec2 vTexCoord;"
"void main() {"
" vTexCoord = iTexCoord;"
" gl_Position = uProjection * vec4(iPosition.xy, 0.0, 1.0);"
"}"
};
static char const* const FragmentSource = {
"#version 330\n"
"in vec2 vTexCoord;"
"out vec4 oColor;"
"void main() {"
" oColor = vec4(1.0, 0.0, 0.0, 1.0);"
"}"
};
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glGenBuffers(1, &m_ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBindVertexArray(0);
m_vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(m_vertex, 1, &VertexSource, nullptr);
glCompileShader(m_vertex);
m_fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(m_fragment, 1, &FragmentSource, nullptr);
glCompileShader(m_fragment);
m_program = glCreateProgram();
glAttachShader(m_program, m_vertex);
glAttachShader(m_program, m_fragment);
glBindAttribLocation(m_program, 0, "iPosition");
glBindAttribLocation(m_program, 1, "iTexCoord");
glBindFragDataLocation(m_program, 0, "oColor");
glLinkProgram(m_program);
glUseProgram(m_program);
m_projectionUniform = glGetUniformLocation(m_program, "uProjection");
glUseProgram(0);
}
void draw(stMesh const& mesh)
{
glUseProgram(m_program);
glUniformMatrix4fv(m_projectionUniform, 1, GL_FALSE, m_projectionMatrix);
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(stVector) * mesh.vertices().size(), mesh.vertices().data(), GL_STREAM_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(stVector), reinterpret_cast<void const*>(0));
glEnableVertexAttribArray(0);
glVertexAttrib2f(1, 1.0f, 1.0f);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32_t) * mesh.indices().size(), mesh.indices().data(), GL_STREAM_DRAW);
glDrawElements(GL_LINES, mesh.indices().size(), GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glUseProgram(0);
}
void ortho(stVector const& center, stVector radius, float aspect)
{
float const left = center.x - radius.x * aspect;
float const right = center.x + radius.x * aspect;
float const top = center.y + radius.y;
float const bottom = center.y - radius.y;
std::fill(&m_projectionMatrix[0], &m_projectionMatrix[15], 0.0f);
m_projectionMatrix[0] = 2.0f / (right - left);
m_projectionMatrix[5] = 2.0f / (top - bottom);
m_projectionMatrix[10] = -1.0f;
m_projectionMatrix[12] = (right + left) / (left - right);
m_projectionMatrix[13] = (top + bottom) / (bottom - top);
m_projectionMatrix[15] = 1.0f;
}
private:
uint32_t m_vao;
uint32_t m_vbo;
uint32_t m_ibo;
uint32_t m_program;
uint32_t m_vertex;
uint32_t m_fragment;
int32_t m_projectionUniform;
float m_projectionMatrix[16];
};
class stSubtileMesh : public stMesh , public stVisitor
{
public:
void onTile(stLocation const& location, stMaterial const& material, stBehavior const& behavior) override
{
line(location.position, stVector(location.position.x + 0.5f, location.position.y + 0.5f));
}
};
void stMesh::reset()
{
m_vertices.clear();
m_indices.clear();
}
void stMesh::line(stVector const& origin, stVector const& target)
{
m_indices.push_back(m_vertices.size()+0);
m_indices.push_back(m_vertices.size()+1);
m_vertices.push_back(origin);
m_vertices.push_back(target);
}
void stMesh::rect(stVector const& center, stVector const& radius)
{
stVector const lower = center - radius;
stVector const upper = center + radius;
}
stUI::stUI() : m_screen(1024.0f, 768.0f) , m_cursor(0.0f) , m_delta(0.0f) , m_stamp(0.0f)
{
if(glfwInit() != GLFW_TRUE)
throw stException("Couldn't initialize GLFW libary.");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_RESIZABLE, 0);
m_window = glfwCreateWindow(m_screen.x, m_screen.y, "Subtile Project", nullptr, nullptr);
if(!m_window)
throw stException("Couldn't create system.");
glfwMakeContextCurrent(static_cast<GLFWwindow*>(m_window));
glfwSwapInterval(1);
std::fill(m_keys.begin(), m_keys.end(), false);
std::fill(m_buttons.begin(), m_buttons.end(), false);
if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
throw stException("Couldn't initialize OpenGL extensions libary.");
glClearDepth(1.0f);
glClearColor(0.25f, 0.25f, 0.25f, 1.0f);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
m_graphics.reset(new stGraphics());
m_graphics->ortho(stVector(0.0f), stVector(5.0f), m_screen.x / m_screen.y);
m_stamp = static_cast<float>(glfwGetTime());
}
stUI::~stUI()
{
if(m_window)
{
glfwDestroyWindow(static_cast<GLFWwindow*>(m_window));
glfwTerminate();
}
}
bool stUI::step()
{
GLFWwindow* system = static_cast<GLFWwindow*>(m_window);
float timestamp = static_cast<float>(glfwGetTime());
m_delta = timestamp - m_stamp;
m_stamp = timestamp;
glfwSwapBuffers(system);
glClear(GL_COLOR_BUFFER_BIT);
double mx = 0.0f, my = 0.0f;
glfwPollEvents();
glfwGetCursorPos(system, &mx, &my);
m_cursor.x = mx;
m_cursor.y = my;
return !glfwWindowShouldClose(system);
}
bool stUI::draw(stMesh const& mesh)
{
m_graphics->draw(mesh);
}
bool stUI::press(char code, bool repeat)
{
code = std::toupper(code);
bool state = glfwGetKey(static_cast<GLFWwindow*>(m_window), code);
bool first = state && !m_keys[code];
m_keys[code] = state;
return repeat ? state : first;
}
bool stUI::click(char code, bool repeat)
{
code = std::toupper(code);
switch(code)
{
case 'L': code = 0; break;
case 'M': code = 2; break;
case 'R': code = 1; break;
default: return false;
}
bool state = glfwGetMouseButton(static_cast<GLFWwindow*>(m_window), static_cast<int>(code));
bool first = state && !m_buttons[code];
m_buttons[code] = state;
return repeat ? state : first;
}
int main()
{
try
{
stUI ui;
stSubtile os("universe");
os.parse(stRequest(0, 2.0f, -1.0f));
while(ui.step())
{
stSubtileMesh mesh;
os.visit(mesh, stBounds(stLocation(0, -2.0f, -2.0f), stLocation(0, 2.0f, 2.0f)));
ui.draw(mesh);
}
}
catch(std::exception const& catched)
{
std::cerr << catched.what() << "\n";
}
}
| 27.37234 | 128 | 0.606037 | [
"mesh"
] |
f08b412c3e40dc5be01a787bb1847afc0daff4b8 | 2,064 | hh | C++ | src/pks/transport/MultiscaleTransportPorosity_GDPM.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/transport/MultiscaleTransportPorosity_GDPM.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/transport/MultiscaleTransportPorosity_GDPM.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Transport PK
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
A generalized dual porosity model, fracture + multiple matrix nodes.
Current naming convention is that the fields used in the single-porosity
model correspond now to the fracture continuum.
Example: tcc = total component concentration in the fracture continuum;
tcc_matrix = total component concentration in the matrix continuum.
*/
#ifndef MULTISCALE_TRANSPORT_POROSITY_GDPM_HH_
#define MULTISCALE_TRANSPORT_POROSITY_GDPM_HH_
#include <string>
#include <vector>
#include "Teuchos_ParameterList.hpp"
#include "Factory.hh"
#include "Mini_Diffusion1D.hh"
#include "MultiscaleTransportPorosity.hh"
namespace Amanzi {
namespace Transport {
class MultiscaleTransportPorosity_GDPM : public MultiscaleTransportPorosity {
public:
MultiscaleTransportPorosity_GDPM(Teuchos::ParameterList& plist);
~MultiscaleTransportPorosity_GDPM() {};
// Compute solute flux: icomp - component id, phi - matrix porosity,
// tcc_m_aux - vector of concentration values in secondary nodes,
// wfm[0|1] - fracture water content at initial and final time moments,
// wcm[0|1] - water content at initial and final time moments
virtual double ComputeSoluteFlux(
double flux_liquid, double& tcc_f, WhetStone::DenseVector& tcc_m, int icomp,
double dt, double wcf0, double wcf1, double wcm0, double wcm1, double phi) override;
// Number of matrix nodes
virtual int NumberMatrixNodes() override { return matrix_nodes_; }
private:
static Utils::RegisteredFactory<MultiscaleTransportPorosity, MultiscaleTransportPorosity_GDPM> factory_;
std::vector<Operators::Mini_Diffusion1D> op_diff_;
int matrix_nodes_;
double depth_, tau_;
std::vector<double> mol_diff_;
};
} // namespace Transport
} // namespace Amanzi
#endif
| 32.25 | 106 | 0.767926 | [
"vector",
"model"
] |
f08bb237de51e222160c5d42c571a5574a6a3c1a | 13,542 | cpp | C++ | tools/render/AudioFifo.cpp | wangrl2016/Skia | 494a5018428b6beec5a20885782bef1620e3a821 | [
"BSD-3-Clause"
] | 3 | 2019-10-14T06:36:32.000Z | 2021-02-20T10:55:14.000Z | tools/render/AudioFifo.cpp | wangrl2016/Skia | 494a5018428b6beec5a20885782bef1620e3a821 | [
"BSD-3-Clause"
] | null | null | null | tools/render/AudioFifo.cpp | wangrl2016/Skia | 494a5018428b6beec5a20885782bef1620e3a821 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by wangrl on 2020/11/24.
//
#include <cstdio>
#include "tools/render/Logger.h"
#include "tools/render/AudioFifo.h"
namespace render {
void AudioFifo::initPacket(AVPacket* packet) {
av_init_packet(packet);
// set the packet data and size so that it is recognized as being empty
packet->data = nullptr;
packet->size = 0;
}
int AudioFifo::initInputFrame(AVFrame** frame) {
if (!(*frame = av_frame_alloc())) {
printf("Could not allocate input frame");
return AVERROR(ENOMEM);
}
return 0;
}
int
AudioFifo::decodeAudioFrame(AVFrame* frame, AVFormatContext* inputFormatContext, AVCodecContext* inputCodecContext,
int* dataPresent, int* finished) {
// packet used for temporary storage
AVPacket inputPacket;
int error;
char errBuf[AV_ERROR_MAX_STRING_SIZE];
initPacket(&inputPacket);
// read one audio frame from the input file into a temporary packet
if ((error = av_read_frame(inputFormatContext, &inputPacket)) < 0) {
// if we are at the end of the file, flush the decoder below
if (error == AVERROR_EOF)
*finished = 1;
else {
printf("Could not read frame (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
return error;
}
}
// Send the audio frame stored in the temporary packet to the decoder.
// The input audio stream decoder is used to do this.
if ((error = avcodec_send_packet(inputCodecContext, &inputPacket)) < 0) {
printf("Could not send packet for decoding (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
return error;
}
// receive one frame from the decoder
error = avcodec_receive_frame(inputCodecContext, frame);
// If the decoder asks for more data to be able to decode a frame,
// return indicating that no data is present
if (error == AVERROR(EAGAIN)) {
error = 0;
goto cleanup;
// if the end of the input file is reached, stop decoding
} else if (error == AVERROR_EOF) {
*finished = 1;
error = 0;
goto cleanup;
} else if (error < 0) {
printf("Could not decode frame (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
goto cleanup;
// default case: Return decoded data
} else {
*dataPresent = 1;
goto cleanup;
}
cleanup:
av_packet_unref(&inputPacket);
return error;
}
int AudioFifo::initConvertedSamples(uint8_t*** convertedInputSamples, AVCodecContext* outputCodecContext,
int frameSize) {
int error;
char errBuf[AV_ERROR_MAX_STRING_SIZE];
// Allocate as many pointers as there are audio channels.
// Each pointer will later point to the audio samples of the corresponding
// channels (although it may be NULL for interleaved formats).
if (!(*convertedInputSamples = (unsigned char**) calloc(outputCodecContext->channels,
sizeof(**convertedInputSamples)))) {
printf("Could not allocate converted input sample pointers");
return AVERROR(ENOMEM);
}
// Allocate memory for the samples of all channels in one consecutive
// block for convenience.
if ((error = av_samples_alloc(*convertedInputSamples, nullptr,
outputCodecContext->channels,
frameSize,
outputCodecContext->sample_fmt, 0)) < 0) {
printf("Could not allocate converted input samples (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
av_freep(&(*convertedInputSamples)[0]);
free(*convertedInputSamples);
return error;
}
return 0;
}
int AudioFifo::convertSamples(const uint8_t** inputData, uint8_t** convertedData, const int frameSize,
SwrContext* resampleContext) {
int error;
char errBuf[AV_ERROR_MAX_STRING_SIZE];
// convert the samples using the resampler
if ((error = swr_convert(resampleContext,
convertedData, frameSize,
inputData, frameSize)) < 0) {
printf("Could not convert input samples (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
return error;
}
return 0;
}
int AudioFifo::addSamplesToFifo(AVAudioFifo* fifo, uint8_t** convertedInputSamples, const int frameSize) {
int error;
// Make the FIFO as large as it needs to be to hold both,
// the old and the new samples.
if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frameSize)) < 0) {
printf("Could not reallocate FIFO");
return error;
}
// store the new samples in the FIFO buffer
if (av_audio_fifo_write(fifo, (void**) convertedInputSamples,
frameSize) < frameSize) {
printf("Could not write data to FIFO");
return AVERROR_EXIT;
}
return 0;
}
int AudioFifo::readDecodeConvertAndStore(AVAudioFifo* fifo, AVFormatContext* inputFormatContext,
AVCodecContext* inputCodecContext, AVCodecContext* outputCodecContext,
SwrContext* resamplerContext, int* finished) {
// temporary storage of the input samples of the frame read from the file
AVFrame* inputFrame = nullptr;
// temporary storage for the converted input samples
uint8_t** convertedInputSamples = nullptr;
int dataPresent = 0;
int ret = AVERROR_EXIT;
// initialize temporary storage for one input frame
if (initInputFrame(&inputFrame))
goto cleanup;
// decode one frame worth of audio samples
if (decodeAudioFrame(inputFrame, inputFormatContext,
inputCodecContext, &dataPresent, finished))
goto cleanup;
// If we are at the end of the file and there are no more samples
// in the decoder which are delayed, we are actually finished.
// This must not be treated as an error.
if (*finished) {
ret = 0;
goto cleanup;
}
// if there is decoded data, convert and store it
if (dataPresent) {
// initialize the temporary storage for the converted input samples
if (initConvertedSamples(&convertedInputSamples, outputCodecContext,
inputFrame->nb_samples))
goto cleanup;
// Convert the input samples to the desired output sample format.
// This requires a temporary storage provided by convertedInputSamples
if (convertSamples((const uint8_t**) inputFrame->extended_data, convertedInputSamples,
inputFrame->nb_samples, resamplerContext))
goto cleanup;
// add the converted input samples to the FIFO buffer for later processing
if (addSamplesToFifo(fifo, convertedInputSamples,
inputFrame->nb_samples))
goto cleanup;
}
ret = 0;
cleanup:
if (convertedInputSamples) {
av_freep(&convertedInputSamples[0]);
free(convertedInputSamples);
}
av_frame_free(&inputFrame);
return ret;
}
int AudioFifo::initOutputFrame(AVFrame** frame, AVCodecContext* outputCodecContext, int frameSize) {
int error;
char errBuf[AV_ERROR_MAX_STRING_SIZE];
// create a new frame to store the audio samples
if (!(*frame = av_frame_alloc())) {
printf("Could not allocate output frame");
return AVERROR_EXIT;
}
// Set the frame's parameters, especially its size and format.
// av_frame_get_buffer needs this to allocate memory for the
// audio samples of the frame.
// Default channel layouts based on the number of channels
// are assumed for simplicity.
(*frame)->nb_samples = frameSize;
(*frame)->channel_layout = outputCodecContext->channel_layout;
(*frame)->format = outputCodecContext->sample_fmt;
(*frame)->sample_rate = outputCodecContext->sample_rate;
// Allocate the samples of the created frame. This call will make
// sure that the audio frame can hold as many samples as specified.
if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
printf("Could not allocate output frame samples (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
av_frame_free(frame);
return error;
}
return 0;
}
int AudioFifo::encodeAudioFrame(AVFrame* frame, AVFormatContext* outputFormatContext,
AVCodecContext* outputCodecContext, int64_t* audioPts, int* dataPresent) {
// packet used for temporary storage
AVPacket outputPacket;
int error;
char errBuf[AV_ERROR_MAX_STRING_SIZE];
initPacket(&outputPacket);
// set a timestamp based on the sample rate for the container
if (frame) {
frame->pts = *audioPts;
(*audioPts) += frame->nb_samples;
}
// Send the audio frame stored in the temporary packet to the encoder.
// The output audio stream encoder is used to do this.
error = avcodec_send_frame(outputCodecContext, frame);
// the encoder signals that it has nothing more to encode
if (error == AVERROR_EOF) {
error = 0;
goto cleanup;
} else if (error < 0) {
printf("Could not send packet for encoding (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
return error;
}
// receive one encoded frame from the encoder
error = avcodec_receive_packet(outputCodecContext, &outputPacket);
// If the encoder asks for more data to be able to provide an
// encoded frame, return indicating that no data is present.
if (error == AVERROR(EAGAIN)) {
error = 0;
goto cleanup;
// If the last frame has been encoded, stop encoding
} else if (error == AVERROR_EOF) {
error = 0;
goto cleanup;
} else if (error < 0) {
printf("Could not encode frame (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
goto cleanup;
// default case: Return encoded data
} else {
*dataPresent = 1;
}
outputPacket.stream_index = 1;
logPacket(outputFormatContext, &outputPacket);
// write one audio frame from the temporary packet to the output file
if (*dataPresent &&
(error = av_interleaved_write_frame(outputFormatContext, &outputPacket)) < 0) {
printf("Could not write frame (error '%s')",
av_make_error_string(errBuf, AV_ERROR_MAX_STRING_SIZE, error));
goto cleanup;
}
cleanup:
av_packet_unref(&outputPacket);
return error;
}
int AudioFifo::loadEncodeAndWrite(AVAudioFifo* fifo, AVFormatContext* outputFormatContext,
AVCodecContext* outputCodecContext, int64_t* audioPts) {
// temporary storage of the output samples of the frame written to the file
AVFrame* outputFrame;
// Use the maximum number of possible samples per frame.
// If there is less than the maximum possible frame size in the FIFO
// buffer use this number. Otherwise, use the maximum possible frame size.
const int frameSize = FFMIN(av_audio_fifo_size(fifo),
outputCodecContext->frame_size);
int data_written;
// initialize temporary storage for one output frame
if (initOutputFrame(&outputFrame, outputCodecContext, frameSize))
return AVERROR_EXIT;
// Read as many samples from the FIFO buffer as required to fill the frame.
// The samples are stored in the frame temporarily
if (av_audio_fifo_read(fifo, (void**) outputFrame->data, frameSize) < frameSize) {
printf("Could not read data from FIFO");
av_frame_free(&outputFrame);
return AVERROR_EXIT;
}
// encode one frame worth of audio samples
if (encodeAudioFrame(outputFrame, outputFormatContext,
outputCodecContext, audioPts, &data_written)) {
av_frame_free(&outputFrame);
return AVERROR_EXIT;
}
av_frame_free(&outputFrame);
return 0;
}
} // namespace render
| 43.967532 | 119 | 0.590459 | [
"render"
] |
f09b5ee1af5d729d7e776a573f1854e1c454c26c | 24,637 | cpp | C++ | src/dispatcher.cpp | SlausB/fos | 75c647da335925fd5e0bb956acc4db895004fc79 | [
"MIT"
] | null | null | null | src/dispatcher.cpp | SlausB/fos | 75c647da335925fd5e0bb956acc4db895004fc79 | [
"MIT"
] | null | null | null | src/dispatcher.cpp | SlausB/fos | 75c647da335925fd5e0bb956acc4db895004fc79 | [
"MIT"
] | null | null | null |
#include "dispatcher.h"
#include "externs.h"
#include "clients_conn_iface.h"
#include <boost/asio.hpp>
#include "handlers/clients_handler.h"
#include "batch_factory.h"
#include "times/starting_time_imp.h"
#include "times/tick_time_imp.h"
#include "times/exiting_time_imp.h"
#include "timer.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include "memdbg_start.h"
#include "boost/interprocess/sync/scoped_lock.hpp"
#include <exception>
#ifdef FOS_HANDLER_TYPE
#if (FOS_HANDLER_TYPE == FOS_HANDLER_REALTIME)
#include "handlers/clients_handler_realtime.h"
#elif (FOS_HANDLER_TYPE == FOS_HANDLER_AIO)
#include "handlers/aio/clients_handler_aio.h"
#else
#define FOS_DEFAULT_HANDLER
#endif
#else//#ifdef FOS_HANDLER_TYPE
#define FOS_DEFAULT_HANDLER
#endif//#ifdef FOS_HANDLER_TYPE
#ifdef FOS_DEFAULT_HANDLER
#include "handlers/asio/clients_handler_asio.h"
#undef FOS_DEFAULT_HANDLER
#endif//#ifdef FOS_DEFAULT_HANDLER
namespace fos
{
Dispatcher::Dispatcher(
#ifndef FOS_NO_DB
const char* dbName,
const char* dbLogin,
const char* dbPassword,
#endif
MetersFactory* metersFactory,
BatchFactory* batchFactory,
StartingHandler startingHandler,
TickHandler tickHandler,
const double tickPeriod,
ConnectionHandler connectionHandler,
MessageHandler messageHandler,
DisconnectionHandler disconnectionHandler,
ExitingHandler exitingHandler,
const int clientsPort,
void* clientData):
batchFactory(batchFactory),
messageHandler(messageHandler),
connectionHandler(connectionHandler),
disconnectionHandler(disconnectionHandler),
exitingHandler(exitingHandler),
handlersPool(50),
immortalClient(Client::IMMORTAL, 1, false, NULL, "n/a"),
lastSessionId(1),
stoppingServer(false),
tickRunnerExited(false),
batchesCount(0)
{
#ifndef FOS_NO_DB
//подключаемся к базе данных:
pqlDbConn = new pq_db::PqlDbConn(Globals::messenger);
pqlDbConn->Connect(dbName, dbLogin, dbPassword);
#endif
Construct(metersFactory, startingHandler, tickHandler, tickPeriod, clientsPort, clientData);
}
/** Way to find exception source (root - place from which it was thrown).*/
#if defined(LINUX)
#include <execinfo.h>
#include <string.h>
#include <iostream>
#include <cstdlib>
#include <exception>
void my_terminate()
{
void * array[50];
int size = backtrace(array, 50);
std::cerr << __FUNCTION__ << " backtrace returned " << size << " frames\n\n";
char ** messages = backtrace_symbols(array, size);
for (int i = 0; i < size && messages != NULL; ++i)
{
std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
}
std::cerr << std::endl;
free(messages);
//set debugging to this (next) line to watch callstack on unhandled exception:
abort();
}
//#if defined(LINUX)
#else
void my_terminate()
{
//set debugging to this (next) line to watch callstack on unhandled exception:
abort();
}
#endif//#if defined(LINUX)
void Dispatcher::Construct( MetersFactory* metersFactory, StartingHandler startingHandler, TickHandler tickHandler, const double tickPeriod, const int clientsPort, void* clientData )
{
std::set_terminate( my_terminate );
clientsConnIFace = new ClientsConnIFace( this );
batchTime_Imp = new BatchTime_Imp( this );
//вызываем StartingHandler:
StartingTime_Imp startingTime_Imp( this, &immortalClient );
startingHandler( &startingTime_Imp, clientData );
#ifdef FOS_HANDLER_TYPE
#if (FOS_HANDLER_TYPE == FOS_HANDLER_REALTIME)
Globals::messenger->write(boost::format("I: Dispatcher::Construct(): choosing \"Realtime\" as clients handler.\n"));
clientsHandler = new ClientsHandler_Realtime(clientsPort, clientsConnIFace);
#elif (FOS_HANDLER_TYPE == FOS_HANDLER_AIO)
Globals::messenger->write(boost::format("I: Dispatcher::Construct(): choosing \"Aio\" as clients handler.\n"));
clientsHandler = new ClientsHandler_Aio(clientsPort, clientsConnIFace);
#else
#define FOS_DEFAULT_HANDLER
#endif
#else//#ifdef FOS_HANDLER_TYPE
#define FOS_DEFAULT_HANDLER
#endif//#ifdef FOS_HANDLER_TYPE
#ifdef FOS_DEFAULT_HANDLER
Globals::messenger->write(boost::format("I: Dispatcher::Construct(): choosing \"Asio\" as clients handler.\n"));
clientsHandler = new ClientsHandler_Asio(metersFactory, clientsPort, clientsConnIFace);
#undef FOS_DEFAULT_HANDLER
#endif//#ifdef FOS_DEFAULT_HANDLER
boost::thread tickThread(&Dispatcher::TickRunner, this, tickHandler, tickPeriod);
}
Dispatcher::~Dispatcher()
{
Globals::messenger->write(boost::format("I: Dispathcer::~Dispatcher(): exiting...\n"));
stoppingServer = true;
//останавливаем поток вызова функции по таймеру:
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): waiting for tick runner to stop...\n"));
while(!tickRunnerExited)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): tick runner successfully stopped.\n"));
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): cancelling accepting connections...\n"));
clientsConnIFace->CancelAcceptingConnections();
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): accepting connections canceled.\n"));
Globals::messenger->write(boost::format("I: Dispatcher::~Dispathcer(): calling ExitingHandler()...\n"));
{
ExitingTime_Imp exitingTime_Imp(this, &immortalClient);
exitingHandler(&exitingTime_Imp);
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispathcer(): ExitingHandler() called.\n"));
clientsConnIFace->DisconnectClients();
Globals::messenger->write(boost::format("I: Dispatcher::~Dispathcer(): waiting for all clients to handle all events...\n"));
for(;;)
{
clientsMutex.lock();
const bool empty = clients.empty();
clientsMutex.unlock();
if(empty)
{
break;
}
else
{
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): all events successfully handled.\n"));
delete clientsConnIFace;
Globals::messenger->write(boost::format("I: Dispathcer::~Dispatcher(): removing immortal client...\n"));
ReleaseBatches(&immortalClient);
immortalClient.batchesUnderUsage.batches.clear();
Globals::messenger->write(boost::format("I: Dispathcer::~Dispatcher(): immortal client successfully removed.\n"));
if(!clients.empty())
{
Globals::messenger->write(boost::format("E: Dispatcher::~Dispatcher(): left some clients.\n"));
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): waiting for all clients threads to end...\n"));
for(;;)
{
batchesMutex.lock();
const size_t size = batchUsageMap.batches.size();
batchesMutex.unlock();
if(size > 0)
{
Globals::messenger->write(boost::format("W: Dispatcher::~Dispatcher(): left %u batches:\n") % size);
batchesMutex.lock();
for(BatchUsageMap::Iterator it = batchUsageMap.batches.begin(); it != batchUsageMap.batches.end(); it++)
{
BatchId* batchId = it->first.batchId;
switch(batchId->GetType())
{
case BatchId::INTEGRAL:
{
IntegralBatchId* integralBatchId = (IntegralBatchId*)batchId;
Globals::messenger->write(boost::format(" INTEGRAL: %llu\n") % integralBatchId->GetValue());
}
break;
case BatchId::LITERAL:
{
LiteralBatchId* literalBatchId = (LiteralBatchId*)batchId;
Globals::messenger->write(boost::format(" LITERAL: %s\n") % literalBatchId->GetValue());
}
break;
}
}
batchesMutex.unlock();
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}
else
{
break;
}
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): all clients threads successfully ended.\n"));
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): waiting for all batches to be destructed...\n"));
for(;;)
{
batchesMutex.lock();
const int leftBatches = batchesCount;
batchesMutex.unlock();
if(leftBatches > 0)
{
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): left %d batches...\n") % leftBatches);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
else
{
break;
}
}
Globals::messenger->write(boost::format("I: Dispatcher::~Dispatcher(): all batches successfully destructed.\n"));
delete batchTime_Imp;
#ifndef FOS_NO_DB
delete pqlDbConn;
#endif
Globals::messenger->write(boost::format("I: Dispathcer::~Dispatcher(): exited.\n"));
}
int ToInt(const double value)
{
if(value >= 0.0f) return (int)(value + 0.5f);
else return (int)(value - 0.5f);
}
void Dispatcher::TickRunner(TickHandler tickHandler, const double period)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(ToInt(period * 1000.0f)));
Timer waitingTimer;
Timer realTimer;
TickTime_Imp tickTime_Imp(this, &immortalClient);
for( ;; )
{
if ( stoppingServer )
break;
const double real = realTimer.getElapsedSeconds();
waitingTimer.drop();
tickHandler( real, &tickTime_Imp );
if ( stoppingServer )
break;
const double consumed = waitingTimer.getElapsedSeconds();
if ( consumed < period )
boost::this_thread::sleep( boost::posix_time::milliseconds( ToInt( ( period - consumed ) * 1000.0f ) ) );
}
tickRunnerExited = true;
}
/** Batches.*/
/** Используется при удалении ссылки на данные (освобождение данных после их использования).*/
class BatchRefOpaqueData
{
public:
BatchRefOpaqueData( Dispatcher* dispatcher, BatchUsageMap::Usage* usage ): dispatcher( dispatcher ), usage( usage )
{
}
/** Чтобы вызвать Dispatcher::ReleaseBatch().*/
Dispatcher* dispatcher;
BatchUsageMap::Usage* usage;
};
void OnBatchDestruction( void* opaqueData )
{
BatchRefOpaqueData* batchRefOpaqueData = ( BatchRefOpaqueData* ) opaqueData;
batchRefOpaqueData->dispatcher->ReleaseBatch( batchRefOpaqueData->usage );
delete batchRefOpaqueData;
}
void Dispatcher::ReleaseBatch_ThreadUnsafe( BatchUsageMap::Usage* usage )
{
//если данные больше никто не использует, то их нужно удалить:
if ( usage->requesters.empty() )
{
//если не зарегистрировано ни одно пользователя эти данных, то освобождаем их:
if ( usage->users.empty() )
{
usage->batch->OnDestruction( batchTime_Imp );
batchesCount--;
BatchUsageMap::Key key( usage->batchId, BatchUsageMap::Key::SHARED );
if ( batchUsageMap.batches.erase( key ) != 1 )
Globals::messenger->write( "E: Dispatcher::ReleaseBatch_ThreadUnsafe(): usage was NOT erased.\n" );
delete usage;
}
else
{
usage->underUsage = false;
}
}
//если кто-то ожидает эти данные:
else
{
usage->requesters.front()->Resume();
usage->requesters.pop_front();
}
}
void Dispatcher::ReleaseBatch( BatchUsageMap::Usage* usage )
{
batchesMutex.lock();
ReleaseBatch_ThreadUnsafe( usage );
batchesMutex.unlock();
}
void Dispatcher::DropBatch( Client* client, const BatchId* batchId )
{
//мьютекс нужно использовать только для неординарного клиента - для остальных сообщения обрабатываются поочерёдно:
if ( client->type == Client::IMMORTAL )
immortalClientMutex.lock();
ReleaseClientsBatch_TU( client, batchId );
if ( client->type == Client::IMMORTAL )
immortalClientMutex.unlock();
}
void Dispatcher::DropBatch( const uint64_t sessionId, const BatchId* batchId )
{
Client::Event* event = new Client::Event( Client::Event::DROP_BATCH );
event->batchId = batchId->MakeCopy();
HandleEvent( sessionId, event );
}
void Dispatcher::Disconnect( const uint64_t& id )
{
clientsConnIFace->Disconnect( id );
}
void Dispatcher::Disconnect(const std::vector<uint64_t>& ids)
{
clientsConnIFace->Disconnect(ids);
}
boost::shared_ptr<std::vector<uint64_t> > Dispatcher::GetIds()
{
return clientsConnIFace->GetIds();
}
CommonTime* Dispatcher::AllocateCommonTime()
{
return new CommonTime_Imp(this, &immortalClient);
}
BatchRef Dispatcher::GetBatch( Client* client, const BatchId* batchId )
{
//ищем данные с указанным идентификатором:
batchesMutex.lock();
BatchUsageMap::Key key( batchId, BatchUsageMap::Key::SHARED );
BatchUsageMap::Iterator it = batchUsageMap.batches.find( key );
//данные найдены:
if ( it != batchUsageMap.batches.end() )
{
BatchUsageMap::Usage* usage = it->second.usage;
if ( usage == NULL )
{
batchesMutex.unlock();
Globals::messenger->write( "E: Dispatcher::RequestBatch(): found data is NULL. Do nothing.\n" );
return BatchRef( NULL, NULL, NULL );
}
else
{
//указываем что данные используются текущим клиентом (это нормально что использование добавляется без проверки - в итоге будет лишь один экземпляр):
{
usage->users.insert( client->sessionId );
//мьютекс использования клиентов можно не блокировать - сообщения для каждого отдельно взятого клиента обрабатываются по-очереди:
if ( client->type == Client::IMMORTAL )
immortalClientMutex.lock();
client->batchesUnderUsage.batches.insert( std::pair< BatchUsageMap::Key, BatchUsageMap::Holder >( key, BatchUsageMap::Holder( usage ) ) );
if ( client->type == Client::IMMORTAL )
immortalClientMutex.unlock();
}
//уже используются:
if ( usage->underUsage )
{
//добавляем ещё одного пользователя:
ContextLock* contextLock = new ContextLock;
usage->requesters.push_back( contextLock );
//ожижадение получения данных - да ещё и из очереди - может быть очень долгим:
batchesMutex.unlock();
contextLock->Stop();
return BatchRef( usage->batch, OnBatchDestruction, new BatchRefOpaqueData( this, usage ) );
}
//ещё не используются:
else
{
//теперь используются:
usage->underUsage = true;
batchesMutex.unlock();
return BatchRef( usage->batch, OnBatchDestruction, new BatchRefOpaqueData( this, usage ) );
}
}
}
//запрашиваемых данных ещё не существует - их нужно создать:
else
{
//создаём новые локальные данные:
BatchUsageMap::Usage* usage = new BatchUsageMap::Usage( NULL, true, batchId );
BatchUsageMap::Holder holder( usage );
batchUsageMap.batches.insert( std::pair< BatchUsageMap::Key, BatchUsageMap::Holder >( key, holder ) );
//указываем что данные используются текущим клиентом (это нормально что использование добавляется без проверки - в итоге будет лишь один экземпляр):
{
usage->users.insert( client->sessionId );
//мьютекс использования клиентов можно не блокировать - сообщения для каждого отдельно взятого клиента обрабатываются по-очереди:
if ( client->type == Client::IMMORTAL )
immortalClientMutex.lock();
client->batchesUnderUsage.batches.insert( std::pair< BatchUsageMap::Key, BatchUsageMap::Holder >( key, BatchUsageMap::Holder( usage ) ) );
if ( client->type == Client::IMMORTAL )
immortalClientMutex.unlock();
}
batchesCount++;
//процесс создания данных может быть очень долгим - освобождаем возможность использования остальных данных на это время:
batchesMutex.unlock();
//создаём сами данные:
usage->batch = batchFactory->CreateCustomBatch( batchId );
usage->batch->OnCreation( batchId, batchTime_Imp );
return BatchRef( usage->batch, OnBatchDestruction, new BatchRefOpaqueData( this, usage ) );
}
}
#ifndef FOS_NO_DB
/** DB interface.*/
/** Багажные данные для запроса в базу данных. Например при создании данных или вызове StartingHandler.*/
class DBRequestOpaqueData
{
public:
DBRequestOpaqueData( ContextLock* contextLock ): contextLock( contextLock )
{
}
/** Поток, ожидающий получения данных.*/
ContextLock* contextLock;
/** Куда будут помещены полученные данные.*/
db::ResponseRef responseRef;
};
void DBRequestCallback( const db::ResponseRef& responseRef, void* opaqueData )
{
DBRequestOpaqueData* dbRequestOpaqueData = ( DBRequestOpaqueData* ) opaqueData;
dbRequestOpaqueData->responseRef = responseRef;
dbRequestOpaqueData->contextLock->Resume();
}
db::ResponseRef Dispatcher::DBRequest( char* query, const bool use, uint32_t size )
{
char* usingQuery = query;
if ( !use )
{
if ( size == 0 )
size = strlen( query );
usingQuery = ( char* ) ( char* ) ( char* ) ( char* ) ( char* ) ( char* ) ( char* ) ( char* ) ( char* ) malloc( size + 1 );
if ( usingQuery == NULL )
{
Globals::messenger->write( boost::format( "E: Dispatcher::DBRequest(): memory allocation failed. Request cannot be fulfilled.\n" ) );
return db::ResponseRef( NULL );
}
memcpy( usingQuery, query, size );
usingQuery[ size ] = '\0';
}
ContextLock* contextLock = new ContextLock;
DBRequestOpaqueData dbRequestOpaqueData( contextLock );
pqlDbConn->SendQuery( usingQuery, DBRequestCallback, &dbRequestOpaqueData );
//ждём пока придёт ответ из базы данных:
contextLock->Stop();
return dbRequestOpaqueData.responseRef;
}
db::ResponseRef Dispatcher::DBRequest( const char* query )
{
return DBRequest( ( char* ) query, false, 0 );
}
db::ResponseRef Dispatcher::DBRequest( const std::string& query )
{
return DBRequest( ( char* ) query.c_str(), false, ( uint32_t ) query.size() );
}
db::ResponseRef Dispatcher::DBRequest( const boost::format& query )
{
return DBRequest( str( query ) );
}
void Dispatcher::DBRequestA( char* query, const bool use, uint32_t size )
{
char* usingQuery = query;
if ( !use )
{
if ( size == 0 )
size = strlen( query );
usingQuery = ( char* ) malloc( size + 1 );
if ( usingQuery == NULL )
{
Globals::messenger->write( boost::format( "E: Dispatcher::DBRequestA(): memory allocation failed. Request cannot be fullfilled.\n" ) );
return;
}
memcpy( usingQuery, query, size );
usingQuery[ size ] = '\0';
}
pqlDbConn->SendQuery( usingQuery );
}
void Dispatcher::DBRequestA( const char* query )
{
DBRequestA( ( char* ) query, false );
}
void Dispatcher::DBRequestA( const std::string& query )
{
DBRequestA( ( char* ) query.c_str(), false, query.size() );
}
void Dispatcher::DBRequestA( const boost::format& query )
{
DBRequestA( str( query ) );
}
void Dispatcher::DBAddFilter( const char* msg )
{
pqlDbConn->AddFilter(msg);
}
#endif//#ifndef FOS_NO_DB
/** Clients events.*/
void Dispatcher::Send(const Outcoming& outcoming)
{
clientsConnIFace->Send(outcoming);
}
void Dispatcher::Send(const uint64_t& sessionId, const OutStream& outStream)
{
clientsConnIFace->Send(sessionId, outStream);
}
void Dispatcher::Send(const std::vector<uint64_t>& ids, const OutStream& outStream)
{
clientsConnIFace->Send(ids, outStream);
}
void Dispatcher::Send(const uint64_t& sessionId, const std::string& data)
{
clientsConnIFace->Send(sessionId, data);
}
void Dispatcher::Send(const uint64_t& sessionId, const void* data, const size_t length)
{
clientsConnIFace->Send(sessionId, data, length);
}
const uint64_t& Dispatcher::HandleConnection(const std::string& ipAddress)
{
lastSessionId++;
Client::Event* event = new Client::Event(Client::Event::CONNECTION);
event->ipAddress = new std::string(ipAddress);
HandleEvent(lastSessionId, event);
return lastSessionId;
}
const uint64_t& Dispatcher::HandleConnection(const char* ipAddress)
{
lastSessionId++;
Client::Event* event = new Client::Event(Client::Event::CONNECTION);
event->ipAddress = new std::string(ipAddress);
HandleEvent(lastSessionId, event);
return lastSessionId;
}
void Dispatcher::HandleMessage(const uint64_t& sessionId, const size_t dataLength, const char* messageData)
{
Client::Event* event = new Client::Event(Client::Event::MESSAGE);
event->messageData = (char*)malloc(dataLength);
event->messageLength = dataLength;
memcpy(event->messageData, messageData, dataLength);
HandleEvent(sessionId, event);
}
void Dispatcher::HandleDisconnection(const uint64_t& sessionId)
{
HandleEvent(sessionId, new Client::Event(Client::Event::DISCONNECTION));
}
void Dispatcher::HandleEvent( const uint64_t& sessionId, Client::Event* event )
{
clientsMutex.lock();
std::map< uint64_t, Client* >::iterator it = clients.find( sessionId );
if ( it != clients.end() )
{
if ( event->type == Client::Event::CONNECTION )
Globals::messenger->write(boost::format("E: Dispatcher::HandleEvent(): CONNECTION: client %lld already exists.\n") % sessionId);
Client* client = it->second;
//для "встроенных" клиентов сообщения обрабатываться не должны (хотя могут поступать по инициативе клиентского кода):
if ( client->type == Client::IMMORTAL && event->type != Client::Event::DROP_BATCH )
{
delete event;
clientsMutex.unlock();
return;
}
//если какое-либо событие, связанное с этим клиентом, уже обрабатывается в отдельном потоке, то текущее событие обработается из очереди там же:
if ( client->isOnHandle )
{
client->events.push_back(event);
}
else
{
client->isOnHandle = true;
handlersPoolMutex.lock();
handlersPool.schedule( boost::bind( &Dispatcher::HandlerRunner, this, client, event ) );
handlersPoolMutex.unlock();
}
}
//первое событие от клиента:
else
{
//события могут быть получены и после отключения клиента (или даже без его предыдущего подключения), поэтому для несуществующего клиента обрабатываем только событие подключения:
if ( event->type == Client::Event::CONNECTION )
{
Client* client = new Client( Client::ORDINARY, sessionId, true, NULL, *( event->ipAddress ) );
clients.insert( std::pair< uint64_t, Client* >( client->sessionId, client ) );
handlersPoolMutex.lock();
handlersPool.schedule( boost::bind( &Dispatcher::HandlerRunner, this, client, event ) );
handlersPoolMutex.unlock();
}
else
{
//событие удаляния данных может для несуществующих клиентов можент существляться как по неосторожности клиентского кода, так и по race-condition'у (клиент может успеть уже удалиться):
if ( event->type != Client::Event::DROP_BATCH )
Globals::messenger->write( boost::format( "W: Dispatcher::HandleEvent(): message of type %d for inexistent client under session id = %llu.\n" ) % ( int ) event->type % sessionId );
delete event;
}
}
clientsMutex.unlock();
}
void Dispatcher::HandlerRunner(Client* client, Client::Event* event)
{
//если это первое событие от клиента:
if ( client->luggage == NULL )
{
client->luggage = batchFactory->CreateLuggageBatch( client->sessionId );
IntegralBatchId integralBatchId( client->sessionId );
client->luggage->OnCreation( &integralBatchId, batchTime_Imp );
}
HandleEventSync( client, event );
//если было сообщение DISCONNECT:
if ( client == NULL )
return;
//выполнение ожидающих событий:
for( ;; )
{
clientsMutex.lock();
if( client->events.empty() )
{
client->isOnHandle = false;
clientsMutex.unlock();
break;
}
else
{
Client::Event* event = client->events.front();
client->events.pop_front();
//обработка события может быть очень долгой (синхронные запросы в базу данных, получение данных...), поэтому освобождаем возможность добавления новых событий:
clientsMutex.unlock();
HandleEventSync( client, event );
//после сообщения DISCONNECT не должно быть никаких сообщений, но, на-всякий случай, проверяем:
if ( client == NULL )
break;
}
}
}
#ifndef FOS_NO_DB
std::string Dispatcher::GetDBStats()
{
boost::interprocess::scoped_lock<boost::mutex> lock(pqlDbConn->statsMutex);
return str(boost::format("gross requests: %llu;\ngross seconds: %.6f;\nseconds/requests: %10.6f;\nlongest request: %10.6f seconds, text: \"%s\";\nfastest request: %10.6f seconds, text: \"%s\".\n") % pqlDbConn->requestsCount % pqlDbConn->grossSeconds % (pqlDbConn->grossSeconds / (double)pqlDbConn->requestsCount) % pqlDbConn->longestRequestSeconds % pqlDbConn->longestRequest % pqlDbConn->fastestRequestSeconds % pqlDbConn->fastestRequest);
}
#endif//#ifndef FOS_NO_DB
size_t Dispatcher::GetCurrentConnectionsCount()
{
boost::interprocess::scoped_lock<boost::mutex> lock(clientsMutex);
return clients.size();
}
}//namespace fos
#include "memdbg_end.h"
| 30.266585 | 442 | 0.692536 | [
"vector"
] |
f0a03cfc97bff7ea2f793db12f0ff18a4b79547d | 1,445 | hpp | C++ | src/code/Library/CoherenceNeighborhood.hpp | 1iyiwei/texture | eaa78c00666060ca0a51c69920031b367c265e7d | [
"MIT"
] | 33 | 2017-04-13T18:32:42.000Z | 2021-12-21T07:53:59.000Z | src/code/Library/CoherenceNeighborhood.hpp | 1iyiwei/texture | eaa78c00666060ca0a51c69920031b367c265e7d | [
"MIT"
] | 1 | 2021-09-24T07:21:03.000Z | 2021-09-29T23:39:41.000Z | src/code/Library/CoherenceNeighborhood.hpp | 1iyiwei/texture | eaa78c00666060ca0a51c69920031b367c265e7d | [
"MIT"
] | 5 | 2017-04-12T17:46:03.000Z | 2021-03-31T00:50:12.000Z | /*
CoherenceNeighborhood.hpp
collect coherent neighbors
Li-Yi Wei
June 8, 2017
*/
#ifndef _COHERENCE_HEIGHBORHOOD_HPP
#define _COHERENCE_HEIGHBORHOOD_HPP
#include "Neighborhood.hpp"
#include "PyramidNeighborhood.hpp"
class CoherenceNeighborhood : public Neighborhood
{
public:
CoherenceNeighborhood(const Texture & source, const Neighborhood & input_neighborhood, const Neighborhood & output_neighborhood, const Neighborhood & coherence_neighborhood);
CoherenceNeighborhood(const Texture & source, const PyramidNeighborhood & input_neighborhood, const PyramidNeighborhood & output_neighborhood, const PyramidNeighborhood & coherence_neighborhood);
virtual ~CoherenceNeighborhood(void);
protected:
virtual vector<Neighbor> Neighbors(const Texture & texture, const Position & query) const;
public:
virtual vector<Position> Candidates(const Texture & texture, const Position & query) const;
protected:
set<Position> & PositionSet(const vector<Position> & input, set<Position> & output) const;
protected:
const Texture & _source_texture;
const Neighborhood & _input_neighborhood;
const Neighborhood & _output_neighborhood;
const Neighborhood & _coherence_neighborhood;
const PyramidNeighborhood * _input_pyramid_neighborhood_ptr;
const PyramidNeighborhood * _output_pyramid_neighborhood_ptr;
const PyramidNeighborhood * _coherence_pyramid_neighborhood_ptr;
};
#endif
| 30.744681 | 199 | 0.791003 | [
"vector"
] |
f0a14a01789e7d899efafcee69ebaf9216c0a06d | 5,137 | cc | C++ | 2021/day16/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | 1 | 2017-12-11T07:08:52.000Z | 2017-12-11T07:08:52.000Z | 2021/day16/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | 2 | 2020-12-01T08:16:42.000Z | 2021-05-12T04:54:34.000Z | 2021/day16/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | null | null | null | #include "lib.h"
#include <limits>
#include <numeric>
#include <tuple>
#include <vector>
namespace
{
struct bitstream
{
size_t offset;
std::vector<uint8_t> bits;
bitstream() : offset(0)
{
}
static bitstream from_hex(const std::string &input)
{
bitstream bs;
for (size_t i = 0; i < input.size(); i += 2)
{
auto bytestr = input.substr(i, 2);
auto byteval = static_cast<uint8_t>(std::stoul(bytestr, nullptr, 16));
bs.bits.emplace_back(byteval);
}
return bs;
}
uint64_t get_bits(size_t count)
{
size_t upper_bound = offset + count;
uint64_t bit_value = 0;
for (; offset < upper_bound; ++offset)
{
bit_value <<= 1;
auto byte_index = offset / 8;
auto shift_amount = 8 - (offset % 8) - 1;
bit_value += (bits[byte_index] >> shift_amount) & 1;
}
return bit_value;
}
};
std::tuple<int64_t, int64_t> parse_packet(bitstream &bs)
{
int64_t version_sum = 0;
auto version = bs.get_bits(3);
version_sum += version;
auto type_id = bs.get_bits(3);
if (type_id == 4)
{
// literal value
uint64_t current_group = 0;
int64_t value = 0;
do
{
value <<= 4;
current_group = bs.get_bits(5);
value += current_group & 0x0F;
} while ((current_group & 0x10) != 0);
return std::tuple<int64_t, int64_t>(version_sum, value);
}
else
{
std::vector<int64_t> subpacket_results;
// operators
auto length_type_id = bs.get_bits(1);
if (length_type_id == 0)
{
// length in bits
auto total_length = bs.get_bits(15);
auto end_offset = bs.offset + total_length;
while (bs.offset < end_offset)
{
auto sub_result = parse_packet(bs);
version_sum += std::get<0>(sub_result);
subpacket_results.emplace_back(std::get<1>(sub_result));
}
}
else
{
// number of sub-packets
auto packet_count = bs.get_bits(11);
for (uint64_t i = 0; i < packet_count; ++i)
{
auto sub_result = parse_packet(bs);
version_sum += std::get<0>(sub_result);
subpacket_results.emplace_back(std::get<1>(sub_result));
}
}
int64_t result = 0;
switch (type_id)
{
case 0:
// sum
result = std::accumulate(
begin(subpacket_results),
end(subpacket_results),
0LL,
[](int64_t total, int64_t current)
{ return total + current; });
break;
case 1:
// product
result = std::accumulate(
begin(subpacket_results),
end(subpacket_results),
1LL,
[](int64_t total, int64_t current)
{ return total * current; });
break;
case 2:
// minimum
result = std::accumulate(
begin(subpacket_results),
end(subpacket_results),
std::numeric_limits<int64_t>::max(),
[](int64_t total, int64_t current)
{ return std::min(total, current); });
break;
case 3:
// maximum
result = std::accumulate(
begin(subpacket_results),
end(subpacket_results),
std::numeric_limits<int64_t>::min(),
[](int64_t total, int64_t current)
{ return std::max(total, current); });
break;
case 5:
// greater than
result = subpacket_results[0] > subpacket_results[1] ? 1 : 0;
break;
case 6:
// less than
result = subpacket_results[0] < subpacket_results[1] ? 1 : 0;
break;
case 7:
// equal to
result = subpacket_results[0] == subpacket_results[1] ? 1 : 0;
break;
}
return std::tuple<int64_t, int64_t>(version_sum, result);
}
}
}
int64_t day16::run_part1(const std::string &input)
{
auto bs = bitstream::from_hex(input);
return std::get<0>(parse_packet(bs));
}
int64_t day16::run_part2(const std::string &input)
{
auto bs = bitstream::from_hex(input);
return std::get<1>(parse_packet(bs));
}
| 29.022599 | 86 | 0.449095 | [
"vector"
] |
f0ad118728e3da0ace8b459dbf4565a027531751 | 3,071 | cpp | C++ | src/group.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | null | null | null | src/group.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | 1 | 2019-03-09T14:43:49.000Z | 2019-03-09T14:43:49.000Z | src/group.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | 2 | 2019-03-07T14:27:51.000Z | 2020-04-14T08:04:54.000Z | #include "group.h"
#include <nlohmann/json.hpp>
#include <Eigen/Geometry>
#include "aux/eigensupport.h"
namespace Faunus {
template <class T> Group<T>::Group(Group<T> &o) : base(o.begin(), o.trueend()) { *this = operator=(o); }
template <class T> Group<T>::Group(const Group<T> &o) : base(o.begin(), o.trueend()) { *this = operator=(o); }
template <class T> Group<T>::Group(Group<T>::iter begin, Group<T>::iter end) : base(begin,end) {}
template <class T> Group<T> &Group<T>::operator=(const Group<T> &o) {
if (&o == this)
return *this;
shallowcopy(o);
if (o.begin()!=begin())
std::copy(o.begin(), o.trueend(), begin()); // copy all particle data
return *this;
}
template <class T> Group<T> &Group<T>::shallowcopy(const Group<T> &o) {
if (&o != this) {
if (this->capacity() != o.capacity())
throw std::runtime_error("Group::shallowcopy: capacity mismatch");
this->resize(o.size());
id = o.id;
atomic = o.atomic;
compressible = o.compressible;
cm = o.cm;
confid = o.confid;
}
return *this;
}
template <class T> bool Group<T>::contains(const T &a, bool include_inactive) const {
if (not this->empty()) {
int size = (include_inactive ? this->capacity() : this->size());
int d = &a - &(*(this->begin()));
if (d>=0 and d<size)
return true;
}
return false;
}
template <class T> double Group<T>::mass() const {
double m=0;
for (auto &i : *this)
m += atoms[i.id].mw;
return m;
}
template <class T> std::vector<std::reference_wrapper<Point>> Group<T>::positions() const {
return Faunus::member_view(begin(), end(), &Particle::pos);
//return ranges::view::transform(*this, [](auto &i) -> Point& {return i.pos;});
}
template <class T> void Group<T>::wrap(Geometry::BoundaryFunction boundary) {
boundary(cm);
for (auto &i : *this)
boundary(i.pos);
}
template <class T> void Group<T>::rotate(const Eigen::Quaterniond &Q, Geometry::BoundaryFunction boundary) {
Geometry::rotate(begin(), end(), Q, boundary, -cm);
}
template <class T> void Group<T>::translate(const Point &d, Geometry::BoundaryFunction boundary) {
cm += d;
boundary(cm);
for (auto &i : *this) {
i.pos += d;
boundary(i.pos);
}
}
template struct Group<Particle>;
void to_json(json &j, const Group<Particle> &g) {
j = {
{"id", g.id}, {"cm", g.cm}, {"atomic", g.atomic}, {"compressible", g.compressible}, {"size", g.size()}
};
if (g.capacity()>g.size())
j["capacity"] = g.capacity();
if (g.confid!=0)
j["confid"] = g.confid;
}
void from_json(const json &j, Group<Particle> &g) {
g.resize( j.at("size").get<int>() );
g.trueend() = g.begin() + j.value("capacity", g.size());
g.id = j.at("id").get<unsigned int>();
g.cm = j.at("cm").get<Point>();
g.atomic = j.at("atomic").template get<bool>();
g.compressible = j.value("compressible", false);
g.confid = j.value("confid", 0);
}
} // namespace Faunus
| 30.405941 | 111 | 0.581895 | [
"geometry",
"vector",
"transform"
] |
f0ad53ee64876754360c09aa8ce7c532535e855f | 6,765 | cpp | C++ | Gems/GradientSignal/Code/Tests/GradientSignalGetValuesTests.cpp | whywhywhyw/o3de | 8e09f66799d4c8f188d45861d821e8656a554cb1 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-01-21T03:51:42.000Z | 2022-01-21T03:51:42.000Z | Gems/GradientSignal/Code/Tests/GradientSignalGetValuesTests.cpp | whywhywhyw/o3de | 8e09f66799d4c8f188d45861d821e8656a554cb1 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/GradientSignal/Code/Tests/GradientSignalGetValuesTests.cpp | whywhywhyw/o3de | 8e09f66799d4c8f188d45861d821e8656a554cb1 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* 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
*
*/
#include <Tests/GradientSignalTestFixtures.h>
#include <Tests/GradientSignalTestHelpers.h>
#include <AzTest/AzTest.h>
namespace UnitTest
{
struct GradientSignalGetValuesTestsFixture
: public GradientSignalTest
{
// Create an arbitrary size shape for comparing values within. It should be large enough that we detect any value anomalies
// but small enough that the tests run quickly.
const float TestShapeHalfBounds = 128.0f;
};
TEST_F(GradientSignalGetValuesTestsFixture, ImageGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto entity = BuildTestImageGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, PerlinGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto entity = BuildTestPerlinGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, RandomGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto entity = BuildTestRandomGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, ConstantGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto entity = BuildTestConstantGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, ShapeAreaFalloffGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto entity = BuildTestShapeAreaFalloffGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, DitherGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestDitherGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, InvertGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestInvertGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, LevelsGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestLevelsGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, MixedGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto mixedEntity = BuildTestConstantGradient(TestShapeHalfBounds);
auto entity = BuildTestMixedGradient(TestShapeHalfBounds, baseEntity->GetId(), mixedEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, PosterizeGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestPosterizeGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, ReferenceGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestReferenceGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, SmoothStepGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestSmoothStepGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, ThresholdGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto baseEntity = BuildTestRandomGradient(TestShapeHalfBounds);
auto entity = BuildTestThresholdGradient(TestShapeHalfBounds, baseEntity->GetId());
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, SurfaceAltitudeGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto mockSurfaceDataSystem =
CreateMockSurfaceDataSystem(AZ::Aabb::CreateFromMinMax(AZ::Vector3(-TestShapeHalfBounds), AZ::Vector3(TestShapeHalfBounds)));
auto entity = BuildTestSurfaceAltitudeGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, SurfaceMaskGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto mockSurfaceDataSystem =
CreateMockSurfaceDataSystem(AZ::Aabb::CreateFromMinMax(AZ::Vector3(-TestShapeHalfBounds), AZ::Vector3(TestShapeHalfBounds)));
auto entity = BuildTestSurfaceMaskGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
TEST_F(GradientSignalGetValuesTestsFixture, SurfaceSlopeGradientComponent_VerifyGetValueAndGetValuesMatch)
{
auto mockSurfaceDataSystem =
CreateMockSurfaceDataSystem(AZ::Aabb::CreateFromMinMax(AZ::Vector3(-TestShapeHalfBounds), AZ::Vector3(TestShapeHalfBounds)));
auto entity = BuildTestSurfaceSlopeGradient(TestShapeHalfBounds);
GradientSignalTestHelpers::CompareGetValueAndGetValues(entity->GetId(), TestShapeHalfBounds);
}
}
| 47.978723 | 137 | 0.784775 | [
"shape",
"3d"
] |
f0bce67bca006fe5859311ebecfa795521e7fdcb | 3,208 | cc | C++ | src/geometry/Domain.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/geometry/Domain.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/geometry/Domain.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Geometry
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Rao Garimella (rao@lanl.gov)
*/
#include "Domain.hh"
namespace Amanzi {
namespace AmanziGeometry {
// -------------------------------------------------------------
// class Domain
// -------------------------------------------------------------
// -------------------------------------------------------------
// Domain:: constructors / destructor
// -------------------------------------------------------------
// Constructor
Domain::Domain(const unsigned int dim): spatial_dimension_(dim)
{
if (dim < 2u || dim > 3u) {
std::cerr << "Only 2D and 3D domains are supported" << std::endl;
throw std::exception();
}
GeometricModels.clear();
FreeRegions.clear();
}
// Copy constructor
Domain::Domain(const Domain& old)
{
int i, ng, nr;
spatial_dimension_ = old.spatial_dimension();
ng = old.Num_Geometric_Models();
for (i = 0; i < ng; i++) {
Teuchos::RCP<GeometricModel> g = old.Geometric_Model_i(i);
GeometricModels.push_back(g);
}
nr = old.Num_Free_Regions();
for (i = 0; i < nr; i++) {
Teuchos::RCP<Region> r = old.Free_Region_i(i);
FreeRegions.push_back(r);
}
}
// Destructor
Domain::~Domain(void)
{
GeometricModels.clear();
FreeRegions.clear();
}
// Constructor with lists of geometric models and free regions
Domain::Domain(const unsigned int dim,
const std::vector<Teuchos::RCP<GeometricModel> >& in_geometric_models,
const std::vector<Teuchos::RCP<Region> >& in_Regions) :
spatial_dimension_(dim), GeometricModels(in_geometric_models),
FreeRegions(in_Regions)
{
if (dim != 2 || dim != 3) {
std::cerr << "Only 2D and 3D domains are supported" << std::endl;
throw std::exception();
}
}
// Add a geometric model
void Domain::Add_Geometric_Model(const Teuchos::RCP<GeometricModel>& gm)
{
// // Make sure spatial dimension of domain and geometric model are the same
// if (spatial_dimension_ != gm->dimension()) {
// std::cerr << "Spatial dimension of domain and geometric model mismatch" << std::endl;
// throw std::exception();
// }
GeometricModels.push_back(gm);
}
// Add a Free Region
void Domain::Add_Free_Region(const Teuchos::RCP<Region>& regptr)
{
if (spatial_dimension_ < regptr->manifold_dimension()) {
std::cerr << "Spatial dimension of domain is less than that of the free region" << std::endl;
throw std::exception();
}
FreeRegions.push_back(regptr);
}
// Number of geometric models
int Domain::Num_Geometric_Models(void) const
{
return GeometricModels.size();
}
// Get the i'th Decomposition
Teuchos::RCP<GeometricModel> Domain::Geometric_Model_i(const int i) const
{
return GeometricModels[i];
}
// Number of Free Regions
int Domain::Num_Free_Regions(void) const
{
return FreeRegions.size();
}
// Get the i'th Free Region
Teuchos::RCP<Region> Domain::Free_Region_i(const int i) const
{
return FreeRegions[i];
}
} // namespace AmanziGeometry
} // namespace Amanzi
| 23.588235 | 97 | 0.630611 | [
"geometry",
"vector",
"model",
"3d"
] |
f0bfebbb7f1e78c9e94fdaddea1eea7505d40b80 | 8,801 | cpp | C++ | indra/newview/llfloatertos.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/newview/llfloatertos.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/newview/llfloatertos.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | /**
* @file llfloatertos.cpp
* @brief Terms of Service Agreement dialog
*
* $LicenseInfo:firstyear=2003&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 "llfloatertos.h"
// viewer includes
#include "llviewerstats.h"
#include "llviewerwindow.h"
// linden library includes
#include "llbutton.h"
#include "llevents.h"
#include "llhttpclient.h"
#include "llhttpstatuscodes.h" // for HTTP_FOUND
#include "llnotificationsutil.h"
#include "llradiogroup.h"
#include "lltextbox.h"
#include "llui.h"
#include "lluictrlfactory.h"
#include "llvfile.h"
#include "message.h"
#include "llstartup.h" // login_alert_done
#include "llviewernetwork.h" // FIX FIRE 3143 SJ
LLFloaterTOS::LLFloaterTOS(const LLSD& data)
: LLModalDialog( data["message"].asString() ),
mMessage(data["message"].asString()),
mWebBrowserWindowId( 0 ),
mLoadingScreenLoaded(false),
mSiteAlive(false),
mRealNavigateBegun(false),
mReplyPumpName(data["reply_pump"].asString())
{
}
// helper class that trys to download a URL from a web site and calls a method
// on parent class indicating if the web server is working or not
class LLIamHere : public LLHTTPClient::Responder
{
private:
LLIamHere( LLFloaterTOS* parent ) :
mParent( parent )
{}
LLFloaterTOS* mParent;
public:
static LLIamHere* build( LLFloaterTOS* parent )
{
return new LLIamHere( parent );
};
virtual void setParent( LLFloaterTOS* parentIn )
{
mParent = parentIn;
};
virtual void result( const LLSD& content )
{
if ( mParent )
mParent->setSiteIsAlive( true );
};
virtual void error( U32 status, const std::string& reason )
{
if ( mParent )
{
// *HACK: For purposes of this alive check, 302 Found
// (aka Moved Temporarily) is considered alive. The web site
// redirects this link to a "cache busting" temporary URL. JC
bool alive = (status == HTTP_FOUND);
mParent->setSiteIsAlive( alive );
}
};
};
// this is global and not a class member to keep crud out of the header file
namespace {
LLPointer< LLIamHere > gResponsePtr = 0;
};
BOOL LLFloaterTOS::postBuild()
{
childSetAction("Continue", onContinue, this);
childSetAction("Cancel", onCancel, this);
childSetCommitCallback("agree_chk", updateAgree, this);
if (hasChild("tos_text"))
{
// this displays the critical message
LLUICtrl *tos_text = getChild<LLUICtrl>("tos_text");
tos_text->setEnabled( FALSE );
tos_text->setFocus(TRUE);
tos_text->setValue(LLSD(mMessage));
return TRUE;
}
// disable Agree to TOS radio button until the page has fully loaded
LLCheckBoxCtrl* tos_agreement = getChild<LLCheckBoxCtrl>("agree_chk");
tos_agreement->setEnabled( false );
// hide the SL text widget if we're displaying TOS with using a browser widget.
LLUICtrl *editor = getChild<LLUICtrl>("tos_text");
editor->setVisible( FALSE );
LLMediaCtrl* web_browser = getChild<LLMediaCtrl>("tos_html");
// <FS:CR> FIRE-8063 - Aurora and OpenSim TOS
bool use_web_browser = false;
#ifdef OPENSIM
if (LLGridManager::getInstance()->isInOpenSim())
{
//Check to see if the message is a link to display
std::string token = "http://";
std::string::size_type iIndex = mMessage.rfind(token);
//IF it has http:// in it, we use the web browser
if(iIndex != std::string::npos && mMessage.length() >= 2)
{
// it exists
use_web_browser = true;
}
}
else
#endif // OPENSIM
{
use_web_browser = true;
}
//if ( web_browser )
if (web_browser && use_web_browser)
// </FS:CR>
{
web_browser->addObserver(this);
// <FS:CR> FIRE-8063 - Aurora and OpenSim TOS
// Next line moved into logic below...
//web_browser->navigateTo( getString( "loading_url" ) );
#ifdef OPENSIM
if (LLGridManager::getInstance()->isInOpenSim())
{
mRealNavigateBegun = true;
tos_agreement->setEnabled(true);
web_browser->navigateTo(mMessage);
}
else
#endif // OPENSIM
{
// Don't use the start_url parameter for this browser instance -- it may finish loading before we get to add our observer.
// Store the URL separately and navigate here instead.
web_browser->navigateTo( getString( "loading_url" ) );
}
}
#ifdef OPENSIM
else if (LLGridManager::getInstance()->isInOpenSim())
{
std::string showTos = "data:text/html,%3Chtml%3E%3Chead%3E"
"%3Cstyle%3E%0A"
"body%20%7B%0A"
"background-color%3Argb%2831%2C%2031%2C%2031%29%3B%0A"
"margin%3A5px%2020px%205px%2030px%3B%0A"
"padding%3A0%3B%0A%7D%0A"
"pre%20%7B%0Afont-size%3A12px%3B%0A"
"font-family%3A%22Deja%20Vu%20Sans%22%2C%20Helvetica%2C%20Arial%2C%20sans-serif%3B%0A"
"color%3A%23fff%3B%0A%7D%0A"
"%3C/style%3E"
"%3C/head%3E%3Cbody%3E%3Cpre%3E" + mMessage + "%3C/pre%3E%3C/body%3E%3C/html%3E";
mRealNavigateBegun = true;
tos_agreement->setEnabled(true);
web_browser->navigateTo(showTos);
}
#endif // OPENSIM
// </FS:CR>
return TRUE;
}
void LLFloaterTOS::setSiteIsAlive( bool alive )
{
mSiteAlive = alive;
// only do this for TOS pages
if (hasChild("tos_html"))
{
// if the contents of the site was retrieved
if ( alive )
{
// navigate to the "real" page
if(!mRealNavigateBegun && mSiteAlive)
{
LLMediaCtrl* web_browser = getChild<LLMediaCtrl>("tos_html");
if(web_browser)
{
mRealNavigateBegun = true;
web_browser->navigateTo( getString( "real_url" ) );
}
}
}
else
{
LL_INFOS("TOS") << "ToS page: ToS page unavailable!" << LL_ENDL;
// normally this is set when navigation to TOS page navigation completes (so you can't accept before TOS loads)
// but if the page is unavailable, we need to do this now
LLCheckBoxCtrl* tos_agreement = getChild<LLCheckBoxCtrl>("agree_chk");
tos_agreement->setEnabled( true );
}
}
}
LLFloaterTOS::~LLFloaterTOS()
{
// tell the responder we're not here anymore
if ( gResponsePtr )
gResponsePtr->setParent( 0 );
}
// virtual
void LLFloaterTOS::draw()
{
// draw children
LLModalDialog::draw();
}
// static
void LLFloaterTOS::updateAgree(LLUICtrl*, void* userdata )
{
LLFloaterTOS* self = (LLFloaterTOS*) userdata;
bool agree = self->getChild<LLUICtrl>("agree_chk")->getValue().asBoolean();
self->getChildView("Continue")->setEnabled(agree);
}
// static
void LLFloaterTOS::onContinue( void* userdata )
{
LLFloaterTOS* self = (LLFloaterTOS*) userdata;
LL_INFOS("TOS") << "User agrees with TOS." << LL_ENDL;
if(self->mReplyPumpName != "")
{
LLEventPumps::instance().obtain(self->mReplyPumpName).post(LLSD(true));
}
self->closeFloater(); // destroys this object
}
// static
void LLFloaterTOS::onCancel( void* userdata )
{
LLSD args;
LLFloaterTOS* self = (LLFloaterTOS*) userdata;
LL_INFOS("TOS") << "User disagrees with TOS." << LL_ENDL;
//[FIX FIRE-3143 SJ] Making sure Current_grid has the right value
args["[CURRENT_GRID]"] = LLGridManager::getInstance()->getGridLabel();
LLNotificationsUtil::add("MustAgreeToLogIn", args, LLSD(), login_alert_done);
if(self->mReplyPumpName != "")
{
LLEventPumps::instance().obtain(self->mReplyPumpName).post(LLSD(false));
}
// reset state for next time we come to TOS
self->mLoadingScreenLoaded = false;
self->mSiteAlive = false;
self->mRealNavigateBegun = false;
// destroys this object
self->closeFloater();
}
//virtual
void LLFloaterTOS::handleMediaEvent(LLPluginClassMedia* /*self*/, EMediaEvent event)
{
if(event == MEDIA_EVENT_NAVIGATE_COMPLETE)
{
if(!mLoadingScreenLoaded)
{
mLoadingScreenLoaded = true;
gResponsePtr = LLIamHere::build( this );
LLHTTPClient::get( getString( "real_url" ), gResponsePtr );
}
else if(mRealNavigateBegun)
{
LL_INFOS("TOS") << "TOS: NAVIGATE COMPLETE" << LL_ENDL;
// enable Agree to TOS radio button now that page has loaded
LLCheckBoxCtrl * tos_agreement = getChild<LLCheckBoxCtrl>("agree_chk");
tos_agreement->setEnabled( true );
}
}
}
| 27.589342 | 125 | 0.695262 | [
"object"
] |
f0c4eba4bb74b6dc27c046eb85e42093f3b4a9c5 | 4,253 | hpp | C++ | include/moost/logging/detail/highlightlevelpatternconverter.hpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | 37 | 2015-02-22T17:15:44.000Z | 2022-02-24T02:24:41.000Z | include/moost/logging/detail/highlightlevelpatternconverter.hpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | null | null | null | include/moost/logging/detail/highlightlevelpatternconverter.hpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | 11 | 2015-02-12T04:35:06.000Z | 2022-01-19T12:46:32.000Z | /* vim:set ts=3 sw=3 sts=3 et: */
/**
* Copyright © 2008-2013 Last.fm Limited
*
* This file is part of libmoost.
*
* 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 MOOST_LOGGING_DETAIL_HIGHLIGHT_LEVEL_PATTERN_CONVERTER_HPP__
#define MOOST_LOGGING_DETAIL_HIGHLIGHT_LEVEL_PATTERN_CONVERTER_HPP__
#include <log4cxx/pattern/loggingeventpatternconverter.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/spi/loggingevent.h>
#include "../../terminal_format.hpp"
#if defined(_MSC_VER)
#pragma warning (push)
#pragma warning ( disable: 4231 4251 4275 4786 )
#endif
namespace log4cxx { namespace pattern {
class HighlightLevelPatternConverter : public LoggingEventPatternConverter
{
HighlightLevelPatternConverter()
: LoggingEventPatternConverter( LOG4CXX_STR("Level"),
LOG4CXX_STR("level")) {}
public:
/**
* Obtains an instance of pattern converter.
* @param options options, may be null.
* @return instance of pattern converter.
*/
static PatternConverterPtr newInstance(const std::vector<LogString>& /*options*/)
{
static PatternConverterPtr def(new HighlightLevelPatternConverter());
return def;
}
void format( const log4cxx::spi::LoggingEventPtr& event,
LogString& toAppendTo,
log4cxx::helpers::Pool& /*p*/) const
{
LevelPtr level = event->getLevel();
switch ( level->toInt() )
{
case Level::FATAL_INT:
case Level::ERROR_INT:
{
std::string lvl;
level->toString(lvl);
lvl = moost::terminal_format::getError(lvl);
LogString wlvl;
helpers::Transcoder::decode(lvl, wlvl);
toAppendTo.append(wlvl);
}
break;
case Level::WARN_INT:
{
std::string lvl;
level->toString(lvl);
lvl = moost::terminal_format::getWarning(lvl);
LogString wlvl;
helpers::Transcoder::decode(lvl, wlvl);
toAppendTo.append(wlvl);
}
break;
default:
toAppendTo.append(event->getLevel()->toString());
break;
}
}
LogString getStyleClass(const log4cxx::helpers::ObjectPtr& obj) const
{
log4cxx::spi::LoggingEventPtr e(obj);
if (e != NULL) {
int lint = e->getLevel()->toInt();
switch (lint) {
case Level::TRACE_INT:
return LOG4CXX_STR("level trace");
case Level::DEBUG_INT:
return LOG4CXX_STR("level debug");
case Level::INFO_INT:
return LOG4CXX_STR("level info");
case Level::WARN_INT:
return LOG4CXX_STR("level warn");
case Level::ERROR_INT:
return LOG4CXX_STR("level error");
case Level::FATAL_INT:
return LOG4CXX_STR("level fatal");
default:
return LogString(LOG4CXX_STR("level ")) + e->getLevel()->toString();
}
}
return LOG4CXX_STR("level");
}
};
}}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#if defined(_MSC_VER)
#pragma warning ( pop )
#endif
#endif // MOOST_LOGGING_CUSTOM_PATTERN_LAYOUT
| 29.130137 | 83 | 0.637197 | [
"vector"
] |
f0d42a15c86b141c4d3c5b1f96fdf663af4c0a0f | 10,210 | cpp | C++ | CS100 Project RPG/CS100 Project RPG/projectmain.cpp | faaiqbilal/CS-100-Project | 3d8e1d1e0a86e3ec263b0f9fd6a123d48a9621cd | [
"MIT"
] | 1 | 2019-12-07T18:04:24.000Z | 2019-12-07T18:04:24.000Z | CS100 Project RPG/CS100 Project RPG/projectmain.cpp | faaiqbilal/CS-100-Project | 3d8e1d1e0a86e3ec263b0f9fd6a123d48a9621cd | [
"MIT"
] | null | null | null | CS100 Project RPG/CS100 Project RPG/projectmain.cpp | faaiqbilal/CS-100-Project | 3d8e1d1e0a86e3ec263b0f9fd6a123d48a9621cd | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
#include <stdlib.h>
#include "SFML\Graphics.hpp"
#include "SFML\Window.hpp"
#include "SFML\System.hpp"
#include <vector>
using namespace sf;
class Bullet
{
public:
Sprite shape;
Bullet(Texture *texture, Vector2f pos)
{
this->shape.setTexture(*texture);
this->shape.setScale(0.1f,0.1f);
this->shape.setPosition(pos.x + 30, pos.y);
}
~Bullet()
{}
};
class Player
{
public:
Sprite shape;
Texture* texture;
std::vector<Bullet> bullets;
Player(Texture *texture, Vector2u windowSize)
{
this->texture = texture;
this->shape.setTexture(*texture);
this->shape.setScale(0.1f, 0.1f);
this->shape.setPosition(windowSize.x/2, windowSize.y);
}
~Player()
{}
};
class Enemy
{
public:
Sprite shape;
Texture* texture;
Enemy(Texture *texture, Vector2u windowSize)
{
this->texture = texture;
this->shape.setTexture(*texture);
this->shape.setScale(0.03f, 0.03f);
// Bug: stuff still spawning at the edges of window. For reference check part 3 of video series
this->shape.setPosition(rand()%(int)(windowSize.x - this->shape.getGlobalBounds().width), shape.getGlobalBounds().height);
this->shape.setRotation(180.f);
}
~Enemy()
{}
};
class Asteroid
{
public:
Sprite shape;
Texture* texture;
Asteroid(Texture *texture, Vector2f pos)
{
this->texture = texture;
this->shape.setTexture(*texture);
this->shape.setScale(0.1f,0.1f);
this->shape.setPosition(pos);
}
~Asteroid()
{}
};
int main()
{
//Score Counter
int Score_Count=0;
// For everything random
srand(time(NULL));
// create window with framerate stuff
RenderWindow window(VideoMode(800,1000),"Space Shooter",Style::Default);
window.setFramerateLimit(60);
//Firing rate for bullet
int fireRate = 50;
//Spawn timer for Enemies
int SpawnTimerEnemies = 80;
//Initializing text fonts after window is created
Font font;
font.loadFromFile("Fonts/Roboto-Light.ttf");
//font.loadFromFile("Fonts/Roboto-Medium.ttf");
//loading textures
Texture playerTexture;
playerTexture.loadFromFile("Textures/player-spaceship.png");
Texture bulletTexture;
bulletTexture.loadFromFile("Textures/bullet.png");
Texture asteroidTexture;
asteroidTexture.loadFromFile("Textures/asteroid.png");
Texture enemyTexture;
enemyTexture.loadFromFile("Textures/enemy-spacecraft.png");
//Loading player
Player player(&playerTexture, window.getSize());
//Loading text
Text Score_Display;
Text Health_Display;
Text Game_Over_Display;
Text Final_Score_Display;
Text Enter_Display;
Text Space_Bar_Display;
Text Right_Ctrl_Display;
Text Left_Ctrl_Display;
Text Up_Ctrl_Display;
Text Down_Ctrl_Display;
Text Title_Display;
//TitleDisplay text
Title_Display.setFillColor(Color::White);
Title_Display.setFont(font);
Title_Display.setPosition(180.f,50.f);
Title_Display.setCharacterSize(60);
Title_Display.setString("SPACE SHOOTER");
//Downctrl display
Down_Ctrl_Display.setFillColor(Color::White);
Down_Ctrl_Display.setFont(font);
Down_Ctrl_Display.setPosition(100.f, 250.f);
Down_Ctrl_Display.setCharacterSize(40);
Down_Ctrl_Display.setString("Press 'S' to move down");
//Upctrl display
Up_Ctrl_Display.setFillColor(Color::White);
Up_Ctrl_Display.setFont(font);
Up_Ctrl_Display.setPosition(100.f, 200.f);
Up_Ctrl_Display.setCharacterSize(40);
Up_Ctrl_Display.setString("Press 'W' to move up");
//Leftctrl display
Left_Ctrl_Display.setFillColor(Color::White);
Left_Ctrl_Display.setFont(font);
Left_Ctrl_Display.setPosition(100.f, 300.f);
Left_Ctrl_Display.setCharacterSize(40);
Left_Ctrl_Display.setString("Press 'A' to move left");
//Rightctrl display
Right_Ctrl_Display.setFillColor(Color::White);
Right_Ctrl_Display.setFont(font);
Right_Ctrl_Display.setPosition(100.f, 350.f);
Right_Ctrl_Display.setCharacterSize(40);
Right_Ctrl_Display.setString("Press 'D' to move right");
//EnterDisplay Text
Enter_Display.setFillColor(Color::White);
Enter_Display.setFont(font);
Enter_Display.setPosition(150.f, 550.f);
Enter_Display.setCharacterSize(50);
Enter_Display.setString("Press 'Enter' to start!");
//SpaceBar Text
Space_Bar_Display.setFillColor(Color::White);
Space_Bar_Display.setFont(font);
Space_Bar_Display.setPosition(100.f,400.f);
Space_Bar_Display.setCharacterSize(40);
Space_Bar_Display.setString("Press 'Space' to shoot");
//Score text
Score_Display.setFillColor(Color::White);
Score_Display.setFont(font);
//Player health
int player_health=5;
Health_Display.setFillColor(Color::White);
Health_Display.setFont(font);
//Game Over Text
Game_Over_Display.setFillColor(Color::White);
Game_Over_Display.setFont(font);
Game_Over_Display.setPosition(230.f, 200.f);
Game_Over_Display.setCharacterSize(60);
Game_Over_Display.setString("GAME OVER!");
//FinalScoreDisplay Text
Final_Score_Display.setFillColor(Color::White);
Final_Score_Display.setFont(font);
Final_Score_Display.setPosition(220.f, 400.f);
Final_Score_Display.setCharacterSize(60);
//Loading enemy
std::vector<Enemy> enemies;
//UPDATES
bool Start_Screen = true;
bool Game_Over = false;
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}
window.clear(sf::Color::Black);
window.display();
while( Start_Screen==true && Game_Over==false && player_health>0)
{
window.draw(Title_Display);
window.draw(Enter_Display);
window.draw(Space_Bar_Display);
window.draw(Up_Ctrl_Display);
window.draw(Down_Ctrl_Display);
window.draw(Left_Ctrl_Display);
window.draw(Right_Ctrl_Display);
window.display();
if (Keyboard::isKeyPressed(Keyboard::Enter))
{
Start_Screen = false;
}
}
while (player_health > 0 && Start_Screen==false && Game_Over==false)
{
//Update counter for bullet time
if (fireRate < 20)
fireRate++;
//Score text display
Score_Display.setPosition(650.f, 20.f);
Score_Display.setString("Score: " + std::to_string(Score_Count));
//Score text display
Health_Display.setPosition(player.shape.getPosition().x , player.shape.getPosition().y - Health_Display.getGlobalBounds().height);
Health_Display.setString( std::to_string(player_health) + " / 5" );
// Updating values
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && (fireRate >= 20))
{
//Spacebar is pressed: shoot
player.bullets.push_back(Bullet(&bulletTexture, player.shape.getPosition()));
fireRate = 0;
}
//Player movement
if (Keyboard::isKeyPressed(Keyboard::W))
player.shape.move(0.f, -10.f);
if (Keyboard::isKeyPressed(Keyboard::A))
player.shape.move(-10.f, 0.f);
if (Keyboard::isKeyPressed(Keyboard::S))
player.shape.move(0.f, 10.f);
if (Keyboard::isKeyPressed(Keyboard::D))
player.shape.move(10.f, 0.f);
//Collision of player with window
if (player.shape.getPosition().x <= 0) // Left side
{
player.shape.setPosition(0.f, player.shape.getPosition().y);
}
if (player.shape.getPosition().x >= window.getSize().x - player.shape.getGlobalBounds().width) //Right side
{
player.shape.setPosition(window.getSize().x - player.shape.getGlobalBounds().width, player.shape.getPosition().y);
}
if (player.shape.getPosition().y <= 0) //Top side
{
player.shape.setPosition(player.shape.getPosition().x, 0.f);
}
if (player.shape.getPosition().y >= window.getSize().y - player.shape.getGlobalBounds().height) //Bottom side
{
player.shape.setPosition(player.shape.getPosition().x, window.getSize().y - player.shape.getGlobalBounds().height);
}
for (size_t i = 0; i < player.bullets.size(); i++)
{
//Bullet movement with bullet speed defined
player.bullets[i].shape.move(0.f, -30.f);
//Reaching end of window
if (player.bullets[i].shape.getPosition().y > window.getSize().y)
{
player.bullets.erase(player.bullets.begin() + i);
break;
}
//Collision of bullet with enemies
for (size_t k = 0; k < enemies.size(); k++)
{
if (player.bullets[i].shape.getGlobalBounds().intersects(enemies[k].shape.getGlobalBounds()))
{
enemies.erase(enemies.begin() + k);
player.bullets.erase(player.bullets.begin() + i);
Score_Count++;
break;
}
}
}
//Enemy Spawner timer update
if (SpawnTimerEnemies < 80)
{
SpawnTimerEnemies++;
}
if (SpawnTimerEnemies >= 50)
{
enemies.push_back(Enemy(&enemyTexture, window.getSize()));
SpawnTimerEnemies = 0;
}
//Update Enemy position
for (size_t i = 0; i < enemies.size(); i++)
{
//Enemy Speed defined
enemies[i].shape.move(0, 5);
//Enemy collision with walls
if (enemies[i].shape.getPosition().y <= enemies[i].shape.getGlobalBounds().height)
{
enemies.erase(enemies.begin() + i);
}
//bool player_interacting_enemy=false;
//Enemy collision with player
if (enemies[i].shape.getGlobalBounds().intersects(player.shape.getGlobalBounds()))
{
enemies.erase(enemies.begin() + i);
player_health--;
}
}
// Draw
window.clear();
//Player
window.draw(player.shape);
//Using size_t everywhere because it is unsigned size of value. Question raised: Why doesn't it work if int is used instead of size_t?
//Bullets
for (size_t i = 0; i < player.bullets.size(); i++)
{
window.draw(player.bullets[i].shape);
}
//Enemy
for (size_t i = 0; i < enemies.size(); i++)
{
window.draw(enemies[i].shape);
}
window.draw(Health_Display);
window.draw(Score_Display);
window.display();
}
Game_Over = true;
while(player_health <= 0 && Start_Screen == false && Game_Over == true)
{
for (int i = 0; i < 100; i++)
{
window.clear(sf::Color::Black);
window.draw(Game_Over_Display);
Final_Score_Display.setString("Final Score: " + std::to_string(Score_Count));
window.draw(Final_Score_Display);
window.display();
}
window.close();
}
}
return 0;
}
| 24.543269 | 138 | 0.68619 | [
"shape",
"vector"
] |
f0d491ca3dcf8466f55d335fac72e68d8356a014 | 5,000 | cpp | C++ | MergeFV/MergeFV.cpp | ak110/MergeFV | 597b64464877a1ca0c5e6609286c0244cfaf80fa | [
"MIT"
] | null | null | null | MergeFV/MergeFV.cpp | ak110/MergeFV | 597b64464877a1ca0c5e6609286c0244cfaf80fa | [
"MIT"
] | null | null | null | MergeFV/MergeFV.cpp | ak110/MergeFV | 597b64464877a1ca0c5e6609286c0244cfaf80fa | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include <boost/algorithm/string.hpp>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <cmath>
using namespace std;
bool MergeFV(const vector<string>& inFiles, const vector<double>& inWeights_, const string& outFile) {
vector<double> inWeights = inWeights_;
if (inWeights.empty())
for (size_t i = 0; i < inFiles.size(); i++)
inWeights.push_back(1.0 / inFiles.size());
vector<unique_ptr<ifstream>> ifsList;
for (const auto& path : inFiles)
ifsList.emplace_back(new ifstream(path, ios_base::binary));
if (!all_of(ifsList.begin(), ifsList.end(), bind(&ifstream::good, placeholders::_1))) {
cerr << "エラー: 入力ファイルの読み込みに失敗: " << strerror(errno) << endl;
return false;
}
ofstream ofs(outFile, ios_base::binary);
if (!ofs) {
cerr << "エラー: 出力ファイルの読み込みに失敗: " << strerror(errno) << endl;
return false;
}
cout << "マージ中 . . ." << endl;
struct Stat
{
double sumDiff = 0, sumAbsDiff = 0, sumSqDiff = 0;
int diffMin = +65536, diffMax = -65536;
};
vector<Stat> stats(inFiles.size());
vector<int16_t> values(inFiles.size());
size_t elementCount = 0;
for (; ; elementCount++) {
for (size_t i = 0; i < inFiles.size(); i++)
ifsList[i]->read((char*)&values[i], sizeof values[i]);
if (all_of(ifsList.begin(), ifsList.end(), bind(&ifstream::eof, placeholders::_1)))
break;
if (any_of(ifsList.begin(), ifsList.end(), bind(&ifstream::eof, placeholders::_1))) {
cerr << "エラー: 入力ファイルのサイズ不一致" << endl;
return false;
}
if (!all_of(ifsList.begin(), ifsList.end(), bind(&ifstream::good, placeholders::_1))) {
cerr << "エラー: 読み込み失敗: " << strerror(errno) << endl;
return false;
}
double result = 0;
for (size_t i = 0; i < values.size(); i++)
result += values[i] * inWeights[i];
int16_t result16 =
INT16_MAX <= result ? INT16_MAX :
result <= -INT16_MAX ? INT16_MAX :
(int16_t)round(result);
// 入力と結果の差異について色々統計情報を算出する
for (size_t i = 0; i < values.size(); i++) {
auto d = (int)result16 - (int)values[i];
stats[i].sumDiff += d;
stats[i].sumAbsDiff += abs(d);
stats[i].sumSqDiff += d * d;
if (d < stats[i].diffMin) stats[i].diffMin = d;
if (stats[i].diffMax < d) stats[i].diffMax = d;
}
// 出力
ofs.write((const char*)&result16, sizeof result16);
}
cout << fixed;
cout << "入力ファイル:" << endl;
for (auto& path : inFiles)
cout << " " << path << endl;
cout << "出力ファイル: " << outFile << endl;
cout << "要素数: " << elementCount << endl;
cout << "差の平均: ";
for (auto& stat : stats)
cout << " " << setw(10) << setprecision(3) << stat.sumDiff / elementCount;
cout << endl;
cout << "差の絶対値の平均: ";
for (auto& stat : stats)
cout << " " << setw(10) << setprecision(1) << stat.sumAbsDiff / elementCount;
cout << endl;
cout << "差の二乗平均平方根: ";
for (auto& stat : stats)
cout << " " << setw(10) << setprecision(1) << sqrt(stat.sumSqDiff / elementCount);
cout << endl;
cout << "差の最大値: ";
for (auto& stat : stats)
cout << " " << setw(10) << stat.diffMin;
cout << endl;
cout << "差の最小値: ";
for (auto& stat : stats)
cout << " " << setw(10) << stat.diffMax;
cout << endl;
cout << "マージ完了" << endl;
return true;
}
void Usage() {
cerr << "usage: MergeFV [options] InFile1 [InFile2 ...] OutFile" << endl;
cerr << endl;
cerr << "複数の重みファイル(Bonanzaのfv.binのような2バイト符号付整数値が" << endl;
cerr << "連続で記録されたバイナリファイル)の重み付き加算を行います。" << endl;
cerr << endl;
cerr << " InFile 入力元のファイルパス" << endl;
cerr << " OutFile 出力先のファイルパス" << endl;
cerr << endl;
cerr << " -w 重み 各入力の重みを実数のカンマ区切りで指定する。省略時は1.0/入力ファイル数になる。(通常の算術平均)" << endl;
cerr << endl;
cerr << " 例:MergeFV -w 0.3,0.7 FV1.bin FV2.bin result.bin" << endl;
cerr << " ⇒ FV1.binの各要素の値に0.3を掛けたものと" << endl;
cerr << " FV2.binの各要素の値に0.7を掛けたものの和(端数は四捨五入)を、" << endl;
cerr << " result.binに出力。" << endl;
}
int main(int argc, char* argv[]) {
vector<string> files;
vector<double> inWeights;
bool hasInWeights = false;
{
vector<string> args(argv + 1, argv + argc);
for (size_t i = 0; i < args.size(); i++) {
if (args[i] == "-w") {
i++;
if (args.size() <= i) {
cerr << "不正なオプション: " << args[i - 1] << endl;
Usage();
return 1;
}
hasInWeights = true;
vector<string> sp;
boost::split(sp, args[i], boost::is_any_of(","));
for (auto s : sp)
inWeights.push_back(stod(s));
} else {
files.push_back(args[i]);
}
}
if (files.size() < 2) {
cerr << "不正なオプション: 入力ファイルと出力ファイルが未指定" << endl;
Usage();
return 1;
}
if (hasInWeights && inWeights.size() != files.size() - 1) {
cerr << "不正なオプション: 入力ファイル数と重み(-w)の数が不一致" << endl;
Usage();
return 1;
}
}
string outFile = files.back();
files.pop_back();
// 処理
return MergeFV(files, inWeights, outFile) ? 0 : 2;
}
| 30.30303 | 103 | 0.5782 | [
"vector"
] |
f0da7ec5e8c5a9125e8b43af4c9a3f1e63445884 | 21,269 | cxx | C++ | Filters/Core/vtkMultiObjectMassProperties.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | Filters/Core/vtkMultiObjectMassProperties.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | Filters/Core/vtkMultiObjectMassProperties.cxx | LongerVisionUSA/VTK | 1170774b6611c71b95c28bb821d51c2c18ff091f | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMultiObjectMassProperties.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkMultiObjectMassProperties.h"
#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkDataObject.h"
#include "vtkDoubleArray.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolygon.h"
#include "vtkSMPThreadLocalObject.h"
#include "vtkSMPTools.h"
#include "vtkTriangle.h"
#include "vtkUnsignedCharArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
vtkStandardNewMacro(vtkMultiObjectMassProperties);
//------------------------------------------------------------------------------
// Helper classes to support efficient computing, and threaded execution.
namespace
{
class ComputeProperties
{
private:
vtkPolyData* Mesh;
vtkPoints* Points;
double Center[3];
unsigned char* Orient;
double* Areas;
double* Volumes;
vtkIdType NumberOfObjects;
vtkIdType* ObjectIds;
double* ObjectAreas;
double* ObjectVolumes;
double* ObjectCentroids;
vtkSMPThreadLocalObject<vtkPolygon> Polygon;
vtkSMPThreadLocalObject<vtkIdList> Triangles;
vtkSMPThreadLocal<std::vector<double>> TLObjectAreas;
vtkSMPThreadLocal<std::vector<double>> TLObjectVolumes;
vtkSMPThreadLocal<std::vector<double>> TLObjectCentroids;
public:
ComputeProperties(vtkPolyData* mesh, double center[3], unsigned char* orient, double* areas,
double* volumes, vtkIdType numberOfObjects, vtkIdType* objectIds, double* objectAreas,
double* objectVolumes, double* objectCentroids)
: Mesh(mesh)
, Points(Mesh->GetPoints())
, Orient(orient)
, Areas(areas)
, Volumes(volumes)
, NumberOfObjects(numberOfObjects)
, ObjectIds(objectIds)
, ObjectAreas(objectAreas)
, ObjectVolumes(objectVolumes)
, ObjectCentroids(objectCentroids)
{
this->Center[0] = center[0];
this->Center[1] = center[1];
this->Center[2] = center[2];
}
void Initialize()
{
// allocate some memory
auto& polygon = this->Polygon.Local();
polygon->PointIds->Allocate(128);
polygon->Points->Allocate(128);
// allocate some memory
auto& tris = this->Triangles.Local();
tris->Allocate(128);
// initialize thread local object-related results;
auto& objectAreas = this->TLObjectAreas.Local();
objectAreas.resize(this->NumberOfObjects);
std::fill_n(objectAreas.begin(), this->NumberOfObjects, 0.0);
auto& objectVolumes = this->TLObjectVolumes.Local();
objectVolumes.resize(this->NumberOfObjects);
std::fill_n(objectVolumes.begin(), this->NumberOfObjects, 0.0);
auto& objectCentroids = this->TLObjectCentroids.Local();
objectCentroids.resize(this->NumberOfObjects * 3);
std::fill_n(objectCentroids.begin(), this->NumberOfObjects * 3, 0.0);
}
// There is a lot of data shuffling between the dataset and the cells going
// on. This could be optimized if it ever comes to that.
void operator()(vtkIdType beginPolyId, vtkIdType endPolyId)
{
auto& objectAreas = this->TLObjectAreas.Local();
auto& objectVolumes = this->TLObjectVolumes.Local();
auto& objectCentroids = this->TLObjectCentroids.Local();
vtkPoints* inPts = this->Points;
double x[3], n[3], centroid[3];
double* areas = this->Areas + beginPolyId;
double* volumes = this->Volumes + beginPolyId;
const unsigned char* orient = this->Orient + beginPolyId;
const double* c = this->Center;
vtkIdType npts;
const vtkIdType* pts;
vtkIdType numTris;
vtkPolygon*& poly = this->Polygon.Local();
vtkIdList*& tris = this->Triangles.Local();
int i;
double x0[3], x1[3], x2[3], tetVol;
double v210, v120, v201, v021, v102, v012;
for (vtkIdType polyId = beginPolyId; polyId < endPolyId; ++polyId)
{
vtkIdType& objectId = this->ObjectIds[polyId];
this->Mesh->GetCellPoints(polyId, npts, pts);
// Compute area of polygon.
*areas = vtkPolygon::ComputeArea(inPts, npts, pts, n);
objectAreas[objectId] += *areas++;
// Now need to compute volume contribution of polygon.
poly->PointIds->SetNumberOfIds(npts);
poly->Points->SetNumberOfPoints(npts);
for (i = 0; i < npts; i++)
{
poly->PointIds->SetId(i, pts[i]);
inPts->GetPoint(pts[i], x);
poly->Points->SetPoint(i, x);
}
// The volume computation implemented using signed tetrahedra from
// generating triangles. Thus, polygons may need to be triangulated.
poly->Triangulate(tris);
numTris = tris->GetNumberOfIds() / 3;
// Loop over each triangle from the tessellation
for (*volumes = 0.0, i = 0; i < numTris; i++)
{
poly->Points->GetPoint(tris->GetId(3 * i), x0);
poly->Points->GetPoint(tris->GetId(3 * i + 1), x1);
poly->Points->GetPoint(tris->GetId(3 * i + 2), x2);
// Better numerics if the volume is computed with respect to
// a nearby point... here we use the center point of the data.
v210 = (x2[0] - c[0]) * (x1[1] - c[1]) * (x0[2] - c[2]);
v120 = (x1[0] - c[0]) * (x2[1] - c[1]) * (x0[2] - c[2]);
v201 = (x2[0] - c[0]) * (x0[1] - c[1]) * (x1[2] - c[2]);
v021 = (x0[0] - c[0]) * (x2[1] - c[1]) * (x1[2] - c[2]);
v102 = (x1[0] - c[0]) * (x0[1] - c[1]) * (x2[2] - c[2]);
v012 = (x0[0] - c[0]) * (x1[1] - c[1]) * (x2[2] - c[2]);
// Find volume contribution of tetrahedron
// Note: Ordering consistency affects sign of volume contribution
tetVol =
(*orient != 0 ? 1.0 : -1.0) * (-v210 + v120 + v201 - v021 - v102 + v012) * (1.0 / 6.0);
// Find centroid of tetrahedron
centroid[0] = (x0[0] + x1[0] + x2[0] + c[0]) / 4.0;
centroid[1] = (x0[1] + x1[1] + x2[1] + c[1]) / 4.0;
centroid[2] = (x0[2] + x1[2] + x2[2] + c[2]) / 4.0;
objectCentroids[3 * objectId + 0] += (tetVol * centroid[0]);
objectCentroids[3 * objectId + 1] += (tetVol * centroid[1]);
objectCentroids[3 * objectId + 2] += (tetVol * centroid[2]);
*volumes += tetVol;
} // for each triangle in this polygon
orient++;
objectVolumes[objectId] += *volumes++;
} // for this polygon
}
void Reduce()
{
// calculate the area of each object using the thread results
std::fill_n(this->ObjectAreas, this->NumberOfObjects, 0.0);
for (auto& tlObjectAreas : this->TLObjectAreas)
{
for (vtkIdType i = 0; i < this->NumberOfObjects; ++i)
{
this->ObjectAreas[i] += tlObjectAreas[i];
}
}
// calculate the volume of each object using the thread results
std::fill_n(this->ObjectVolumes, this->NumberOfObjects, 0.0);
for (auto& tlObjectVolumes : this->TLObjectVolumes)
{
for (vtkIdType i = 0; i < this->NumberOfObjects; ++i)
{
this->ObjectVolumes[i] += tlObjectVolumes[i];
}
}
// calculate the weighted centroid of each object using the thread results
std::fill_n(this->ObjectCentroids, this->NumberOfObjects * 3, 0.0);
for (auto& tlObjectCentroids : this->TLObjectCentroids)
{
for (vtkIdType i = 0; i < this->NumberOfObjects; ++i)
{
this->ObjectCentroids[3 * i + 0] += tlObjectCentroids[3 * i + 0];
this->ObjectCentroids[3 * i + 1] += tlObjectCentroids[3 * i + 1];
this->ObjectCentroids[3 * i + 2] += tlObjectCentroids[3 * i + 2];
}
}
for (vtkIdType i = 0; i < this->NumberOfObjects; ++i)
{
this->ObjectCentroids[3 * i + 0] /= this->ObjectVolumes[i];
this->ObjectCentroids[3 * i + 1] /= this->ObjectVolumes[i];
this->ObjectCentroids[3 * i + 2] /= this->ObjectVolumes[i];
}
}
static void Execute(vtkIdType numPolys, vtkPolyData* output, double center[3],
unsigned char* orient, double* areas, double* volumes, vtkIdType numberOfObjects,
vtkIdType* objectIds, double* objectAreas, double* objectVolumes, double* objectCentroids)
{
ComputeProperties compute(output, center, orient, areas, volumes, numberOfObjects, objectIds,
objectAreas, objectVolumes, objectCentroids);
vtkSMPTools::For(0, numPolys, compute);
}
};
} // anonymous namespace
//================= Begin VTK class proper =======================================
//------------------------------------------------------------------------------
// Constructs with initial 0 values.
vtkMultiObjectMassProperties::vtkMultiObjectMassProperties()
{
this->SkipValidityCheck = 0;
this->AllValid = 0;
this->TotalVolume = 0.0;
this->TotalArea = 0.0;
// The labeling (e.g., ids) of objects. The ObjectValidity is a 0/1 flag
// indicating whether the object is manifold (i.e., valid) meaning every
// edge is used exactly two times.
this->SetObjectIdsArrayName("ObjectIds");
this->NumberOfObjects = 0;
this->ObjectIds = nullptr;
this->ObjectValidity = nullptr;
this->ObjectVolumes = nullptr;
this->ObjectAreas = nullptr;
// Processing waves for performing connected traversal
this->CellNeighbors = vtkIdList::New();
this->Wave = nullptr;
this->Wave2 = nullptr;
}
//------------------------------------------------------------------------------
// Destroy any allocated memory.
vtkMultiObjectMassProperties::~vtkMultiObjectMassProperties()
{
this->CellNeighbors->Delete();
}
//------------------------------------------------------------------------------
// This method measures volume and surface area.
// The input is a PolyData which consists of polygons.
int vtkMultiObjectMassProperties::RequestData(vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
// Get the input and output. Check to make sure data is available.
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType numPolys = input->GetPolys()->GetNumberOfCells();
vtkIdType numPts = input->GetNumberOfPoints();
this->AllValid = 1; // assumed valid until proven otherwise
this->TotalArea = 0.0;
this->TotalVolume = 0.0;
if (numPolys < 1 || numPts < 1)
{
vtkErrorMacro(<< "No data!");
return 1;
}
// Attribute data
vtkPointData *inputPD = input->GetPointData(), *outputPD = output->GetPointData();
vtkCellData *inputCD = input->GetCellData(), *outputCD = output->GetCellData();
// Determine if some data is being skipped over and either shallow copy out
// or copy the cell attribute data and prune the extra cells. Points are
// always passed through.
vtkIdType numCells = input->GetNumberOfCells();
if (numCells == numPolys)
{
// Just copy stuff through and we'll add arrays
output->CopyStructure(input);
outputPD->PassData(inputPD);
outputCD->PassData(inputCD);
}
else
{
vtkWarningMacro(<< "Skipping some non-poly cells");
// Pass points through, can always use vtkCleanPolyData to eliminate
// unused points.
output->SetPoints(input->GetPoints());
outputPD->PassData(inputPD);
// Just process polys and copy over associated cell data
input->BuildCells();
output->SetPolys(input->GetPolys());
outputCD->CopyAllocate(inputCD);
unsigned char cellType;
for (vtkIdType cellId = 0, polyId = 0; cellId < numCells; ++cellId)
{
cellType = input->GetCellType(cellId);
if (cellType == VTK_TRIANGLE || cellType == VTK_QUAD || cellType == VTK_POLYGON)
{
outputCD->CopyData(inputCD, cellId, polyId);
polyId++;
}
}
}
// Okay to identify objects, perform connected traversal. Requires
// neighborhood information (traverse via shared edges). All edges in an
// object must be used exactly twice if the object is considered valid.
this->NumberOfObjects = 0;
output->BuildLinks();
bool performValidityCheck = false;
int idx;
vtkIdType* objectIds;
vtkIdTypeArray* objectIdsArray = vtkIdTypeArray::FastDownCast(
output->GetCellData()->GetAbstractArray(this->ObjectIdsArrayName.c_str(), idx));
if (!this->SkipValidityCheck || objectIdsArray == nullptr ||
objectIdsArray->GetDataType() != VTK_ID_TYPE)
{
performValidityCheck = true;
this->ObjectIds = objectIdsArray = vtkIdTypeArray::New();
this->ObjectIds->SetName(this->ObjectIdsArrayName.c_str());
this->ObjectIds->SetNumberOfTuples(numPolys);
outputCD->AddArray(objectIdsArray);
objectIds = objectIdsArray->GetPointer(0);
std::fill_n(objectIds, numPolys, (-1));
}
else
{
objectIds = objectIdsArray->GetPointer(0);
}
this->ObjectValidity = vtkUnsignedCharArray::New();
this->ObjectValidity->SetName("ObjectValidity");
output->GetFieldData()->AddArray(this->ObjectValidity);
unsigned char* valid;
// All polygons initially assumed oriented properly
std::vector<unsigned char> orient(numPolys, 1);
// This traversal identifies the number of objects in the mesh, and whether
// they are valid (closed, manifold).
if (performValidityCheck)
{
// Loop over all polys and traverse unmarked, edge connected polygons. Make sure
// the objects are valid, and label polygons with object ids.
this->Wave = vtkIdList::New();
this->Wave->Allocate(numPolys / 4 + 1, numPolys);
this->Wave2 = vtkIdList::New();
this->Wave2->Allocate(numPolys / 4 + 1, numPolys);
for (vtkIdType polyId = 0; polyId < numPolys; ++polyId)
{
// check if value is less than 0, because the initial value is -1
if (objectIds[polyId] < 0)
{
// found another object
this->Wave->InsertNextId(polyId);
objectIds[polyId] = this->NumberOfObjects;
this->ObjectValidity->InsertValue(this->NumberOfObjects, 1);
this->TraverseAndMark(output, objectIds, this->ObjectValidity, orient.data());
this->NumberOfObjects++;
// Wave & Wave2 need to be reset since they are populated in TraverseAndMark()
this->Wave->Reset();
this->Wave2->Reset();
}
}
// Clean up
this->Wave->Delete();
this->Wave2->Delete();
valid = this->ObjectValidity->GetPointer(0);
// Roll up the valid flag
for (idx = 0; idx < this->NumberOfObjects; ++idx)
{
this->AllValid &= valid[idx];
}
} // if validity check required
// Here we assume that the object ids provided are associated with valid
// objects. However, we need to traverse provided array to determine number
// of objects.
else
{
this->NumberOfObjects = 0;
for (vtkIdType polyId = 0; polyId < numPolys; ++polyId)
{
if (this->NumberOfObjects < (objectIds[polyId] + 1))
{
this->NumberOfObjects = (objectIds[polyId] + 1);
}
}
this->ObjectValidity->SetNumberOfTuples(this->NumberOfObjects);
valid = this->ObjectValidity->GetPointer(0);
std::fill_n(valid, this->NumberOfObjects, 1);
this->AllValid = 1;
}
// Now compute the areas and volumes. This can be done in parallel. We
// compute on a per-polygon basis and sum the results later. Note that the
// polygon volumes, which can be negative or positive, are the contribution
// that the polygon makes to the total object volume.
vtkDoubleArray* polyAreas = vtkDoubleArray::New();
polyAreas->SetName("Areas");
polyAreas->SetNumberOfTuples(numPolys);
outputCD->AddArray(polyAreas);
double* pAreas = polyAreas->GetPointer(0);
vtkDoubleArray* polyVolumes = vtkDoubleArray::New();
polyVolumes->SetName("Volumes");
polyVolumes->SetNumberOfTuples(numPolys);
outputCD->AddArray(polyVolumes);
double* pVolumes = polyVolumes->GetPointer(0);
// Roll up the results into total results on a per-object basis.
this->ObjectAreas = vtkDoubleArray::New();
this->ObjectAreas->SetName("ObjectAreas");
this->ObjectAreas->SetNumberOfTuples(this->NumberOfObjects);
output->GetFieldData()->AddArray(this->ObjectAreas);
double* objectAreas = this->ObjectAreas->GetPointer(0);
this->ObjectVolumes = vtkDoubleArray::New();
this->ObjectVolumes->SetName("ObjectVolumes");
this->ObjectVolumes->SetNumberOfTuples(this->NumberOfObjects);
output->GetFieldData()->AddArray(this->ObjectVolumes);
double* objectVolumes = this->ObjectVolumes->GetPointer(0);
this->ObjectCentroids = vtkDoubleArray::New();
this->ObjectCentroids->SetName("ObjectCentroids");
this->ObjectCentroids->SetNumberOfComponents(3);
this->ObjectCentroids->SetNumberOfTuples(this->NumberOfObjects);
output->GetFieldData()->AddArray(this->ObjectCentroids);
double* objectCentroids = this->ObjectCentroids->GetPointer(0);
// Need reference origin to compute volumes
double center[3];
output->GetCenter(center);
// Compute areas and volumes in parallel
ComputeProperties::Execute(numPolys, output, center, orient.data(), pAreas, pVolumes,
this->NumberOfObjects, objectIds, objectAreas, objectVolumes, objectCentroids);
// Volumes are always positive
for (idx = 0; idx < this->NumberOfObjects; ++idx)
{
this->TotalArea += objectAreas[idx];
if (valid[idx])
{
objectVolumes[idx] = std::abs(objectVolumes[idx]);
this->TotalVolume += objectVolumes[idx];
}
}
// Clean up and get out
if (performValidityCheck)
{
this->ObjectIds->Delete();
}
this->ObjectValidity->Delete();
this->ObjectVolumes->Delete();
this->ObjectAreas->Delete();
this->ObjectCentroids->Delete();
polyAreas->Delete();
polyVolumes->Delete();
return 1;
}
//------------------------------------------------------------------------------
// This method not only identified connected objects, it ensures that they
// are manifold (i.e., valid) and polygons are oriented in a consistent manner.
// Consistent normal orientation is necessary to correctly compute volumes.
void vtkMultiObjectMassProperties::TraverseAndMark(
vtkPolyData* output, vtkIdType* objectIds, vtkDataArray* valid, unsigned char* orient)
{
vtkIdType i, j, k, numIds, polyId, npts, p0, p1, numNei, neiId;
const vtkIdType* pts;
vtkIdType numNeiPts;
const vtkIdType* neiPts;
vtkIdList* wave = this->Wave;
vtkIdList* wave2 = this->Wave2;
vtkIdList* tmpWave;
// Process all cells in this connected wave
while ((numIds = wave->GetNumberOfIds()) > 0)
{
for (i = 0; i < numIds; i++)
{
polyId = wave->GetId(i);
output->GetCellPoints(polyId, npts, pts);
for (j = 0; j < npts; ++j)
{
p0 = pts[j];
p1 = pts[(j + 1) % npts];
output->GetCellEdgeNeighbors(polyId, p0, p1, this->CellNeighbors);
// Manifold requires exactly one edge neighbor. Don't worry about
// consistency check with invalid objects.
numNei = this->CellNeighbors->GetNumberOfIds();
if (numNei != 1)
{ // mark invalid
valid->InsertTuple1(this->NumberOfObjects, 0);
}
// Determine whether neighbor is consistent with the current
// cell. The neighbor ordering of the edge (p0,p1) should be reversed
// (p1,p0). Otherwise, it is inconsistent and is marked as such. For
// non-valid objects we don't care about consistency.
else // have one neighbor.
{
neiId = this->CellNeighbors->GetId(0);
output->GetCellPoints(neiId, numNeiPts, neiPts);
for (k = 0; k < numNeiPts; ++k)
{
if (neiPts[k] == p1)
{
break;
}
}
if (neiPts[(k + 1) % numNeiPts] != p0)
{
orient[neiId] = (orient[polyId] == 1 ? 0 : 1);
}
}
for (k = 0; k < numNei; ++k)
{
neiId = this->CellNeighbors->GetId(k);
if (objectIds[neiId] < 0)
{
objectIds[neiId] = this->NumberOfObjects;
wave2->InsertNextId(neiId);
}
} // for all edge neighbors
} // for all edges
} // for all cells in this wave
tmpWave = wave;
wave = wave2;
wave2 = tmpWave;
tmpWave->Reset();
} // while wave is not empty
}
//------------------------------------------------------------------------------
void vtkMultiObjectMassProperties::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Skip Validity Check: " << this->SkipValidityCheck << "\n";
os << indent << "Number of Objects: " << this->NumberOfObjects << "\n";
os << indent << "All Valid: " << this->AllValid << "\n";
os << indent << "Total Volume: " << this->TotalVolume << "\n";
os << indent << "Total Area: " << this->TotalArea << "\n";
}
| 35.866779 | 97 | 0.638441 | [
"mesh",
"object",
"vector"
] |
f0deee41a3ecc97fa16de4851ccc220b3df4bf51 | 9,359 | cpp | C++ | c++ext/maskrcnn/csrc/cpu/crop_cpu.cpp | blyucs/MaskRCNN | 493730f1987886913ce059e934e9a720ee85bb20 | [
"MIT"
] | 4 | 2019-11-24T12:48:21.000Z | 2021-07-29T23:20:22.000Z | c++ext/maskrcnn/csrc/cpu/crop_cpu.cpp | blyucs/MaskRCNN | 493730f1987886913ce059e934e9a720ee85bb20 | [
"MIT"
] | 3 | 2019-07-30T09:48:09.000Z | 2022-01-08T09:47:26.000Z | c++ext/maskrcnn/csrc/cpu/crop_cpu.cpp | blyucs/MaskRCNN | 493730f1987886913ce059e934e9a720ee85bb20 | [
"MIT"
] | 2 | 2019-07-19T15:51:12.000Z | 2019-12-27T09:45:40.000Z | /************************************************************************************
***
*** File Author: Dell, 2018-11-06 17:11:09
***
************************************************************************************/
#include "cpu/vision.h"
#include <stdio.h>
#include <math.h>
void crop_per_box(
const float * image_data,
const int batch_size,
const int depth,
const int image_height,
const int image_width,
const float * boxes_data,
const int32_t * box_index_data,
const int start_box,
const int limit_box,
float * corps_data,
const int crop_height,
const int crop_width,
const float extrapolation_value
)
{
const int image_channel_elements = image_height * image_width;
const int image_elements = depth * image_channel_elements;
const int crop_channel_elements = crop_height * crop_width;
const int crop_elements = depth * crop_channel_elements;
int b;
for (b = start_box; b < limit_box; ++b) {
const float * box = boxes_data + b * 4;
const float y1 = box[0];
const float x1 = box[1];
const float y2 = box[2];
const float x2 = box[3];
const int b_in = box_index_data[b];
if (b_in < 0 || b_in >= batch_size) {
printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size);
exit(-1);
}
const float height_scale = (crop_height > 1)
? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0;
const float width_scale = (crop_width > 1)
? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0;
for (int y = 0; y < crop_height; ++y)
{
const float in_y = (crop_height > 1)
? y1 * (image_height - 1) + y * height_scale
: 0.5 * (y1 + y2) * (image_height - 1);
if (in_y < 0 || in_y > image_height - 1)
{
for (int x = 0; x < crop_width; ++x)
{
for (int d = 0; d < depth; ++d)
{
// crops(b, y, x, d) = extrapolation_value;
corps_data[crop_elements * b + crop_channel_elements * d + y * crop_width + x] = extrapolation_value;
}
}
continue;
}
const int top_y_index = floorf(in_y);
const int bottom_y_index = ceilf(in_y);
const float y_lerp = in_y - top_y_index;
for (int x = 0; x < crop_width; ++x)
{
const float in_x = (crop_width > 1)
? x1 * (image_width - 1) + x * width_scale
: 0.5 * (x1 + x2) * (image_width - 1);
if (in_x < 0 || in_x > image_width - 1)
{
for (int d = 0; d < depth; ++d)
{
corps_data[crop_elements * b + crop_channel_elements * d + y * crop_width + x] = extrapolation_value;
}
continue;
}
const int left_x_index = floorf(in_x);
const int right_x_index = ceilf(in_x);
const float x_lerp = in_x - left_x_index;
for (int d = 0; d < depth; ++d)
{
const float *pimage = image_data + b_in * image_elements + d * image_channel_elements;
const float top_left = pimage[top_y_index * image_width + left_x_index];
const float top_right = pimage[top_y_index * image_width + right_x_index];
const float bottom_left = pimage[bottom_y_index * image_width + left_x_index];
const float bottom_right = pimage[bottom_y_index * image_width + right_x_index];
const float top = top_left + (top_right - top_left) * x_lerp;
const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp;
corps_data[crop_elements * b + crop_channel_elements * d + y * crop_width + x] = top + (bottom - top) * y_lerp;
}
} // end for x
} // end for y
} // end for b
}
void crop_cpu_forward(
const at::Tensor& image,
const at::Tensor& boxes, // [y1, x1, y2, x2]
const at::Tensor& box_index, // range in [0, batch_size)
const float extrapolation_value,
const int crop_height,
const int crop_width,
at::Tensor& crops
)
{
image.contiguous();
boxes.contiguous();
box_index.contiguous();
const int batch_size = image.size(0);
const int depth = image.size(1);
const int image_height = image.size(2);
const int image_width = image.size(3);
const int num_boxes = boxes.size(0);
// init output space
crops.resize_({num_boxes, depth, crop_height, crop_width});
crops.contiguous();
crops.zero_();
// crop_and_resize for each box
crop_per_box(
image.data<float>(),
batch_size,
depth,
image_height,
image_width,
boxes.data<float>(),
box_index.data<int32_t>(),
0,
num_boxes,
crops.data<float>(),
crop_height,
crop_width,
extrapolation_value
);
printf("crop_cpu_forward ...4 \n");
}
void crop_cpu_backward(
const at::Tensor& grads,
const at::Tensor& boxes, // [y1, x1, y2, x2]
const at::Tensor& box_index, // range in [0, batch_size)
at::Tensor& grads_image // resize to [bsize, c, hc, wc]
)
{
grads.contiguous();
boxes.contiguous();
box_index.contiguous();
grads_image.contiguous();
// shape
const int batch_size = grads_image.size(0);
const int depth = grads_image.size(1);
const int image_height = grads_image.size(2);
const int image_width = grads_image.size(3);
const int num_boxes = grads.size(0);
const int crop_height = grads.size(2);
const int crop_width = grads.size(3);
// n_elements
const int image_channel_elements = image_height * image_width;
const int image_elements = depth * image_channel_elements;
const int crop_channel_elements = crop_height * crop_width;
const int crop_elements = depth * crop_channel_elements;
// init output space
grads_image.zero_();
// data pointer
auto grads_data = grads.data<float>();
auto boxes_data = boxes.data<float>();
auto box_index_data = box_index.data<int32_t>();
auto grads_image_data = grads_image.data<float>();
for (int b = 0; b < num_boxes; ++b) {
const float * box = boxes_data + b * 4;
const float y1 = box[0];
const float x1 = box[1];
const float y2 = box[2];
const float x2 = box[3];
const int32_t b_in = box_index_data[b];
if (b_in < 0 || b_in >= batch_size) {
printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size);
exit(-1);
}
const float height_scale =
(crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0;
const float width_scale =
(crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0;
for (int y = 0; y < crop_height; ++y)
{
const float in_y = (crop_height > 1)
? y1 * (image_height - 1) + y * height_scale
: 0.5 * (y1 + y2) * (image_height - 1);
if (in_y < 0 || in_y > image_height - 1)
{
continue;
}
const int top_y_index = floorf(in_y);
const int bottom_y_index = ceilf(in_y);
const float y_lerp = in_y - top_y_index;
for (int x = 0; x < crop_width; ++x)
{
const float in_x = (crop_width > 1)
? x1 * (image_width - 1) + x * width_scale
: 0.5 * (x1 + x2) * (image_width - 1);
if (in_x < 0 || in_x > image_width - 1)
{
continue;
}
const int left_x_index = floorf(in_x);
const int right_x_index = ceilf(in_x);
const float x_lerp = in_x - left_x_index;
for (int d = 0; d < depth; ++d)
{
float *pimage = grads_image_data + b_in * image_elements + d * image_channel_elements;
const float grad_val = grads_data[crop_elements * b + crop_channel_elements * d + y * crop_width + x];
const float dtop = (1 - y_lerp) * grad_val;
pimage[top_y_index * image_width + left_x_index] += (1 - x_lerp) * dtop;
pimage[top_y_index * image_width + right_x_index] += x_lerp * dtop;
const float dbottom = y_lerp * grad_val;
pimage[bottom_y_index * image_width + left_x_index] += (1 - x_lerp) * dbottom;
pimage[bottom_y_index * image_width + right_x_index] += x_lerp * dbottom;
} // end d
} // end x
} // end y
} // end b
}
| 35.184211 | 131 | 0.510097 | [
"shape"
] |
f0e15f347b722da50f6a3d443a5aa1944c34788a | 2,611 | cpp | C++ | src/Step9.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | 45 | 2018-01-14T17:58:51.000Z | 2022-03-16T23:47:48.000Z | src/Step9.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | null | null | null | src/Step9.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | 8 | 2018-07-02T00:34:48.000Z | 2021-05-12T09:33:04.000Z | #include <vector>
#include <SDL.h>
#include "Core.h"
#include "Vector2d.h"
#include "GraphMetrics.h"
#include "FiniteDifference.h"
#include "Render.h"
#include "Step9.h"
Step9LaplaceEquation2D::Step9LaplaceEquation2D(const int windowWidth, const int windowHeight)
{
title = "Step 9: Laplace Equation";
fixedTimeStep = 1.0 / 60;
graphMetrics.width = windowWidth - 20;
graphMetrics.height = windowHeight - 20;
graphMetrics.pos = Vector2d(10, 10);
graphMetrics.minX = 0;
graphMetrics.maxX = 2;
graphMetrics.minY = 0;
graphMetrics.maxY = 1;
dx = (graphMetrics.maxX - graphMetrics.minX) / (numX - 1);
dy = (graphMetrics.maxY - graphMetrics.minY) / (numY - 1);
applyInitialConditions();
heightMap = NULL;
}
void Step9LaplaceEquation2D::applyInitialConditions()
{
p = std::vector<std::vector<double>>(numX, std::vector<double>(numY));
// apply initial condition
for(size_t i = 0; i < numX; i++)
{
for(size_t j = 0; j < numY; j++)
{
p[i][j] = 0;
}
}
}
void Step9LaplaceEquation2D::applyBoundaryConditions(std::vector<std::vector<double>>& p)
{
const double bCVal = 1;
for(size_t i = 0; i < numY; i++)
{
p[0][i] = 0; // p = 0 at x = 0
const auto y = graphMetrics.minY + (i * dy);
p[numX - 1][i] = y; // p = y at x = 2
}
for(size_t i = 0; i < numX; i++)
{
p[i][0] = p[i][1]; // dp/dy = 0 at y = 0
p[i][numY - 1] = p[i][numY - 2]; // dp/dy = 0 at y = 1
}
}
void Step9LaplaceEquation2D::update(const double dt)
{
const auto dx2 = dx * dx;
const auto dy2 = dy * dy;
auto newP = p;
for(size_t i = 1; i < (p.size() - 1); i++)
{
for(size_t j = 1; j < (p[i].size() - 1); j++)
{
const auto numerator = (dy2 * (p[i + 1][j] + p[i - 1][j])) + (dx2 * (p[i][j + 1] + p[i][j - 1]));
const auto denominator = 2 * (dx2 + dy2);
newP[i][j] = numerator / denominator;
}
}
applyBoundaryConditions(newP);
p = newP;
}
void Step9LaplaceEquation2D::draw(SDL_Renderer* renderer)
{
if(heightMap == NULL)
{
heightMap = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, numX, numY);
}
updateHeightmap(heightMap, numX, numY, p, 0, graphMaxHeight);
SDL_Rect uGraphRect;
uGraphRect.w = (int)graphMetrics.width;
uGraphRect.h = (int)graphMetrics.height;
uGraphRect.x = (int)graphMetrics.pos.x;
uGraphRect.y = (int)graphMetrics.pos.y;
SDL_RenderCopy(renderer, heightMap, NULL, &uGraphRect);
} | 27.197917 | 115 | 0.586365 | [
"render",
"vector"
] |
f0e1dcc83dbd5e77f1486987e08de0b9e91520c6 | 10,919 | cpp | C++ | components/render/opengl_driver/sources/output_stage/gl_output_depth_stencil_state.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/render/opengl_driver/sources/output_stage/gl_output_depth_stencil_state.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/render/opengl_driver/sources/output_stage/gl_output_depth_stencil_state.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace render::low_level;
using namespace render::low_level::opengl;
using namespace common;
/*
Конструктор / деструктор
*/
DepthStencilState::DepthStencilState (const ContextManager& manager, const DepthStencilDesc& in_desc)
: ContextObject (manager),
desc_hash (0)
{
SetDesc (in_desc);
}
DepthStencilState::~DepthStencilState ()
{
}
/*
Установка / изменение дескриптора
*/
namespace
{
/*
Преобразование констант
*/
GLenum get_gl_compare_mode (CompareMode mode, const char* source, const char* param)
{
switch (mode)
{
case CompareMode_AlwaysFail: return GL_NEVER;
case CompareMode_AlwaysPass: return GL_ALWAYS;
case CompareMode_Equal: return GL_EQUAL;
case CompareMode_NotEqual: return GL_NOTEQUAL;
case CompareMode_Less: return GL_LESS;
case CompareMode_LessEqual: return GL_LEQUAL;
case CompareMode_Greater: return GL_GREATER;
case CompareMode_GreaterEqual: return GL_GEQUAL;
default:
throw xtl::make_argument_exception (source, param, mode);
}
}
GLenum get_gl_stencil_operation (StencilOperation operation, const char* source, const char* param)
{
switch (operation)
{
case StencilOperation_Keep: return GL_KEEP;
case StencilOperation_Zero: return GL_ZERO;
case StencilOperation_Replace: return GL_REPLACE;
case StencilOperation_Increment: return GL_INCR;
case StencilOperation_Decrement: return GL_DECR;
case StencilOperation_Invert: return GL_INVERT;
default:
throw xtl::make_argument_exception (source, param, operation);
}
}
}
void DepthStencilState::SetDesc (const DepthStencilDesc& in_desc)
{
static const char* METHOD_NAME = "render::low_level::opengl::DepthStencilState::SetDesc";
//выбор контекста
MakeContextCurrent ();
//получение информации о доступных расширениях
const ContextCaps& caps = GetCaps ();
bool has_two_side_stencil = caps.has_ext_stencil_two_side || caps.has_ati_separate_stencil;
//преобразование данных дескриптора
GLenum gl_depth_compare_mode = get_gl_compare_mode (in_desc.depth_compare_mode, METHOD_NAME, "desc.depth_compare_mode");
bool need_two_side_stencil = false;
const StencilDesc &front_stencil = in_desc.stencil_desc [FaceMode_Front],
&back_stencil = in_desc.stencil_desc [FaceMode_Back];
if (front_stencil.stencil_compare_mode != back_stencil.stencil_compare_mode)
need_two_side_stencil = true;
if (front_stencil.stencil_fail_operation != back_stencil.stencil_fail_operation)
need_two_side_stencil = true;
if (front_stencil.depth_fail_operation != back_stencil.depth_fail_operation)
need_two_side_stencil = true;
if (front_stencil.stencil_pass_operation != back_stencil.stencil_pass_operation)
need_two_side_stencil = true;
GLenum gl_stencil_func [2] = {
get_gl_compare_mode (front_stencil.stencil_compare_mode, METHOD_NAME, "desc.stencil_desc [FaceMode_Front].stencil_compare_mode"),
get_gl_compare_mode (back_stencil.stencil_compare_mode, METHOD_NAME, "desc.stencil_desc [FaceMode_Back].stencil_compare_mode")
};
enum StencilOperationType
{
StencilOperationType_Fail,
StencilOperationType_ZFail,
StencilOperationType_ZPass,
StencilOperationType_Num
};
GLenum gl_stencil_operation [2][StencilOperationType_Num] = {
{
get_gl_stencil_operation (front_stencil.stencil_fail_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Front].stencil_fail_operation"),
get_gl_stencil_operation (front_stencil.depth_fail_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Front].depth_fail_operation"),
get_gl_stencil_operation (front_stencil.stencil_pass_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Front].stencil_pass_operation")
},
{
get_gl_stencil_operation (back_stencil.stencil_fail_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Back].stencil_fail_operation"),
get_gl_stencil_operation (back_stencil.depth_fail_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Back].depth_fail_operation"),
get_gl_stencil_operation (back_stencil.stencil_pass_operation, METHOD_NAME, "desc.stencil_desc [FaceMode_Back].stencil_pass_operation")
}
};
//проверка наличия расширений
if (in_desc.stencil_test_enable && need_two_side_stencil && !has_two_side_stencil)
throw xtl::format_not_supported_exception (METHOD_NAME, "Unsupported configuration: desc.stencil_desc [FaceMode_Front] != desc.stencil_desc [FaceMode_Back] "
"(GL_EXT_stencil_two_side and GL_ATI_separate_stencil not supported)");
//запись команд в контексте OpenGL
CommandListBuilder cmd_list;
if (in_desc.depth_test_enable)
{
cmd_list.Add (glEnable, GL_DEPTH_TEST);
cmd_list.Add (glDepthFunc, gl_depth_compare_mode);
}
else
{
cmd_list.Add (glDisable, GL_DEPTH_TEST);
}
cmd_list.Add (glDepthMask, in_desc.depth_write_enable);
if (in_desc.stencil_test_enable)
{
cmd_list.Add (glEnable, GL_STENCIL_TEST);
#ifndef OPENGL_ES_SUPPORT
if (need_two_side_stencil)
{
if (caps.has_ati_separate_stencil)
{
if (glStencilOpSeparate)
{
cmd_list.Add (glStencilOpSeparate, GL_FRONT, gl_stencil_operation [FaceMode_Front][0], gl_stencil_operation [FaceMode_Front][1],
gl_stencil_operation [FaceMode_Front][2]);
cmd_list.Add (glStencilOpSeparate, GL_BACK, gl_stencil_operation [FaceMode_Back][0], gl_stencil_operation [FaceMode_Back][1],
gl_stencil_operation [FaceMode_Back][2]);
}
else if (glStencilOpSeparateATI)
{
cmd_list.Add (glStencilOpSeparateATI, GL_FRONT, gl_stencil_operation [FaceMode_Front][0], gl_stencil_operation [FaceMode_Front][1],
gl_stencil_operation [FaceMode_Front][2]);
cmd_list.Add (glStencilOpSeparateATI, GL_BACK, gl_stencil_operation [FaceMode_Back][0], gl_stencil_operation [FaceMode_Back][1],
gl_stencil_operation [FaceMode_Back][2]);
}
}
#ifndef OPENGL_ES2_SUPPORT
else if (caps.has_ext_stencil_two_side)
{
cmd_list.Add (glEnable, GL_STENCIL_TEST_TWO_SIDE_EXT);
cmd_list.Add (glActiveStencilFaceEXT, GL_FRONT);
cmd_list.Add (glStencilOp, gl_stencil_operation [0][0], gl_stencil_operation [0][1], gl_stencil_operation [0][2]);
cmd_list.Add (glActiveStencilFaceEXT, GL_BACK);
cmd_list.Add (glStencilOp, gl_stencil_operation [1][0], gl_stencil_operation [1][1], gl_stencil_operation [1][2]);
}
#endif
}
else
{
#ifndef OPENGL_ES2_SUPPORT
if (caps.has_ext_stencil_two_side)
cmd_list.Add (glDisable, GL_STENCIL_TEST_TWO_SIDE_EXT);
#endif
cmd_list.Add (glStencilOp, gl_stencil_operation [0][0], gl_stencil_operation [0][1], gl_stencil_operation [0][2]);
}
#else
cmd_list.Add (glStencilOp, gl_stencil_operation [0][0], gl_stencil_operation [0][1], gl_stencil_operation [0][2]);
#endif
}
else
{
cmd_list.Add (glDisable, GL_STENCIL_TEST);
}
cmd_list.Add (glStencilMask, in_desc.stencil_write_mask);
//создание нового исполнителя команд
ExecuterPtr new_executer = cmd_list.Finish ();
//проверка ошибок
CheckErrors (METHOD_NAME);
//сохранение параметров
desc = in_desc;
desc_hash = crc32 (&desc, sizeof desc);
executer = new_executer;
for (int i=0; i<FaceMode_Num; i++)
this->gl_stencil_func [i] = gl_stencil_func [i];
this->need_two_side_stencil = need_two_side_stencil;
}
void DepthStencilState::GetDesc (DepthStencilDesc& out_desc)
{
out_desc = desc;
}
/*
Установка состояния в контекст OpenGL
*/
void DepthStencilState::Bind (unsigned int reference)
{
static const char* METHOD_NAME = "render::low_level::opengl::DepthStencilState::Bind";
//проверка необходимости биндинга (кэширование состояния)
const size_t current_desc_hash = GetContextCacheValue (CacheEntry_DepthStencilStateHash),
current_reference = GetContextCacheValue (CacheEntry_StencilReference),
current_depth_write_enable = GetContextCacheValue (CacheEntry_DepthWriteEnable),
current_stencil_write_mask = GetContextCacheValue (CacheEntry_StencilWriteMask);
if (desc_hash == current_desc_hash && reference == current_reference && current_depth_write_enable == size_t (desc.depth_write_enable) &&
current_stencil_write_mask == size_t (desc.stencil_write_mask))
return;
//установка текущего контекста
MakeContextCurrent ();
//установка состояния в контекст OpenGL
if (desc_hash != current_desc_hash)
executer->ExecuteCommands ();
if (desc.stencil_test_enable)
{
#ifndef OPENGL_ES_SUPPORT
if (need_two_side_stencil)
{
//получение информации о доступных расширениях
const ContextCaps& caps = GetCaps ();
//настройка функции трафарета
if (caps.has_ati_separate_stencil)
{
if (glStencilFuncSeparate)
{
glStencilFuncSeparate (GL_FRONT, gl_stencil_func [0], reference, desc.stencil_read_mask);
glStencilFuncSeparate (GL_BACK, gl_stencil_func [1], reference, desc.stencil_read_mask);
}
else if (glStencilFuncSeparateATI)
{
glStencilFuncSeparateATI (GL_FRONT, gl_stencil_func [0], reference, desc.stencil_read_mask);
glStencilFuncSeparateATI (GL_BACK, gl_stencil_func [1], reference, desc.stencil_read_mask);
}
}
#ifndef OPENGL_ES2_SUPPORT
else if (caps.has_ext_stencil_two_side)
{
glActiveStencilFaceEXT (GL_FRONT);
glStencilFunc (gl_stencil_func [0], reference, desc.stencil_read_mask);
glActiveStencilFaceEXT (GL_BACK);
glStencilFunc (gl_stencil_func [1], reference, desc.stencil_read_mask);
}
#endif
}
else
#endif
{
glStencilFunc (gl_stencil_func [0], reference, desc.stencil_read_mask);
}
}
//проверка ошибок
CheckErrors (METHOD_NAME);
//установка кэш-переменных
SetContextCacheValue (CacheEntry_DepthStencilStateHash, desc_hash);
SetContextCacheValue (CacheEntry_StencilReference, reference);
SetContextCacheValue (CacheEntry_DepthWriteEnable, desc.depth_write_enable);
SetContextCacheValue (CacheEntry_StencilWriteMask, desc.stencil_write_mask);
//оповещение о необходимости ребиндинга уровня
StageRebindNotify (Stage_Output);
}
| 34.444795 | 162 | 0.704552 | [
"render"
] |
f0e29f3efee9a322883ca60fb8555b6d2709c329 | 2,932 | hpp | C++ | std/cpp/generator.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 2 | 2018-03-19T20:19:01.000Z | 2018-10-22T23:41:12.000Z | std/cpp/generator.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | 1 | 2017-01-18T20:45:33.000Z | 2017-01-21T20:57:37.000Z | std/cpp/generator.hpp | LSaldyt/CTF | cd11caa5a57b69e43a3a02a89e0a05b1d19e7f01 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cstddef>
#include <iostream>
#include <limits>
#include <functional>
#include <assert.h>
#include <vector>
#include "io.hpp"
template <typename value_type>
class Sequence
: public std::iterator<std::input_iterator_tag, value_type>
{
public:
using transformation = std::function<value_type(value_type)>;
Sequence(value_type initial,
value_type set_last,
transformation set_t)
: done (false),
value (initial),
last (set_last),
t (set_t)
{
}
explicit operator bool() const { return !done; }
value_type const& operator*() const { return value; }
value_type const* operator->() const { return &value; }
Sequence& operator++()
{
assert(!done);
if (value != last)
{
value = t(value);
return *this;
}
done = true;
return *this;
}
Sequence operator++(int)
{
Sequence const tmp(*this);
++*this;
return tmp;
}
Sequence begin()
{
return Sequence(value, last, t);
}
Sequence end()
{
return Sequence(last, last, t);
}
bool operator!=(Sequence other)
{
return value != other.value;
}
explicit operator std::vector<value_type>()
{
std::cout << "Explicitly converted generator to vector" << std::endl;
return std::vector<value_type>(begin(), end());
}
private:
bool done;
value_type value;
value_type last;
std::function<value_type(value_type)> t;
};
template <typename value_type>
Sequence<value_type> begin(Sequence<value_type>& s)
{
return s.begin();
}
template <typename value_type>
Sequence<value_type> end(Sequence<value_type>& s)
{
return s.end();
}
/*
template <typename value_type>
class ForSequence
: public std::iterator<std::input_iterator_tag, value_type>
{
public:
using transformation = std::function<value_type(value_type)>;
ForSequence(value_type initial,
transformation set_t)
: value (initial),
t (set_t)
{
}
explicit operator bool() const { return !done; }
value_type const& operator*() const { return value; }
value_type const* operator->() const { return &value; }
ForSequence& operator++()
{
value = t(value);
return *this;
}
ForSequence operator++(int)
{
Sequence const tmp(*this);
++*this;
return tmp;
}
private:
value_type value;
std::function<value_type(value_type)> t;
};
#include <iostream>
#include <algorithm>
namespace foo{
int i=0;
struct A
{
A()
{
std::generate(&v[0], &v[10], [&i](){ return ++i;} );
}
int v[10];
};
int *begin( A &v )
{
return &v.v[0];
}
int *last( A &v )
{
return &v.v[10];
}
} // namespace foo
*/
| 18.556962 | 77 | 0.569236 | [
"vector"
] |
f0e4d5ff9b9336ff3b5d4616fd119bed57ba396d | 20,737 | cpp | C++ | src/dclass/dcPackerInterface.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | 1 | 2022-01-18T17:17:43.000Z | 2022-01-18T17:17:43.000Z | src/dclass/dcPackerInterface.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | null | null | null | src/dclass/dcPackerInterface.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | 1 | 2022-01-31T22:07:19.000Z | 2022-01-31T22:07:19.000Z | // Filename: dcPackerInterface.cpp
// Created by: drose (15Jun04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "dcPackerInterface.h"
#include "dcPackerCatalog.h"
#include "dcField.h"
#include "dcParserDefs.h"
#include "dcLexerDefs.h"
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
DCPackerInterface::
DCPackerInterface(const string &name) :
_name(name)
{
_has_fixed_byte_size = false;
_fixed_byte_size = 0;
_has_fixed_structure = false;
_has_range_limits = false;
_num_length_bytes = 0;
_has_nested_fields = false;
_num_nested_fields = -1;
_pack_type = PT_invalid;
_catalog = NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::Copy Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
DCPackerInterface::
DCPackerInterface(const DCPackerInterface ©) :
_name(copy._name),
_has_fixed_byte_size(copy._has_fixed_byte_size),
_fixed_byte_size(copy._fixed_byte_size),
_has_fixed_structure(copy._has_fixed_structure),
_has_range_limits(copy._has_range_limits),
_num_length_bytes(copy._num_length_bytes),
_has_nested_fields(copy._has_nested_fields),
_num_nested_fields(copy._num_nested_fields),
_pack_type(copy._pack_type)
{
_catalog = NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
DCPackerInterface::
~DCPackerInterface() {
if (_catalog != (DCPackerCatalog *)NULL) {
delete _catalog;
}
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::find_seek_index
// Access: Published
// Description: Returns the index number to be passed to a future
// call to DCPacker::seek() to seek directly to the
// named field without having to look up the field name
// in a table later, or -1 if the named field cannot be
// found.
//
// If the named field is nested within a switch or some
// similar dynamic structure that reveals different
// fields based on the contents of the data, this
// mechanism cannot be used to pre-fetch the field index
// number--you must seek for the field by name.
////////////////////////////////////////////////////////////////////
int DCPackerInterface::
find_seek_index(const string &name) const {
return get_catalog()->find_entry_by_name(name);
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_field
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
DCField *DCPackerInterface::
as_field() {
return (DCField *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_field
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
const DCField *DCPackerInterface::
as_field() const {
return (DCField *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_switch_parameter
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
DCSwitchParameter *DCPackerInterface::
as_switch_parameter() {
return (DCSwitchParameter *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_switch_parameter
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
const DCSwitchParameter *DCPackerInterface::
as_switch_parameter() const {
return (DCSwitchParameter *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_class_parameter
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
DCClassParameter *DCPackerInterface::
as_class_parameter() {
return (DCClassParameter *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::as_class_parameter
// Access: Published, Virtual
// Description:
////////////////////////////////////////////////////////////////////
const DCClassParameter *DCPackerInterface::
as_class_parameter() const {
return (DCClassParameter *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::check_match
// Access: Published
// Description: Returns true if this interface is bitwise the same as
// the interface described with the indicated formatted
// string, e.g. "(uint8, uint8, int16)", or false
// otherwise.
//
// If DCFile is not NULL, it specifies the DCFile that
// was previously loaded, from which some predefined
// structs and typedefs may be referenced in the
// description string.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
check_match(const string &description, DCFile *dcfile) const {
bool match = false;
istringstream strm(description);
dc_init_parser_parameter_description(strm, "check_match", dcfile);
dcyyparse();
dc_cleanup_parser();
DCField *field = dc_get_parameter_description();
if (field != NULL) {
match = check_match(field);
delete field;
}
if (dc_error_count() == 0) {
return match;
}
// Parse error: no match is allowed.
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::set_name
// Access: Public, Virtual
// Description: Sets the name of this field.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
set_name(const string &name) {
_name = name;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::calc_num_nested_fields
// Access: Public, Virtual
// Description: This flavor of get_num_nested_fields is used during
// unpacking. It returns the number of nested fields to
// expect, given a certain length in bytes (as read from
// the _num_length_bytes stored in the stream on the
// push). This will only be called if _num_length_bytes
// is nonzero.
////////////////////////////////////////////////////////////////////
int DCPackerInterface::
calc_num_nested_fields(size_t) const {
return 0;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::get_nested_field
// Access: Public, Virtual
// Description: Returns the DCPackerInterface object that represents
// the nth nested field. This may return NULL if there
// is no such field (but it shouldn't do this if n is in
// the range 0 <= n < get_num_nested_fields()).
////////////////////////////////////////////////////////////////////
DCPackerInterface *DCPackerInterface::
get_nested_field(int) const {
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::validate_num_nested_fields
// Access: Public, Virtual
// Description: After a number of fields have been packed via push()
// .. pack_*() .. pop(), this is called to confirm that
// the number of nested fields that were added is valid
// for this type. This is primarily useful for array
// types with dynamic ranges that can't validate the
// number of fields any other way.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
validate_num_nested_fields(int) const {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_double
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_double(DCPackData &, double, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_int
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_int(DCPackData &, int, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_uint
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_uint(DCPackData &, unsigned int, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_int64
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_int64(DCPackData &, int64_t, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_uint64
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_uint64(DCPackData &, uint64_t, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_string
// Access: Public, Virtual
// Description: Packs the indicated numeric or string value into the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
pack_string(DCPackData &, const string &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::pack_default_value
// Access: Public, Virtual
// Description: Packs the field's specified default value (or a
// sensible default if no value is specified) into the
// stream. Returns true if the default value is packed,
// false if the field doesn't know how to pack its
// default value.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
pack_default_value(DCPackData &, bool &) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_double
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_double(const char *, size_t, size_t &, double &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_int
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_int(const char *, size_t, size_t &, int &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_uint
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_uint(const char *, size_t, size_t &, unsigned int &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_int64
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_int64(const char *, size_t, size_t &, int64_t &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_uint64
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_uint64(const char *, size_t, size_t &, uint64_t &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_string
// Access: Public, Virtual
// Description: Unpacks the current numeric or string value from the
// stream.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
unpack_string(const char *, size_t, size_t &, string &, bool &pack_error, bool &) const {
pack_error = true;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_validate
// Access: Public, Virtual
// Description: Internally unpacks the current numeric or string
// value and validates it against the type range limits,
// but does not return the value. Returns true on
// success, false on failure (e.g. we don't know how to
// validate this field).
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
unpack_validate(const char *data, size_t length, size_t &p,
bool &pack_error, bool &) const {
if (!_has_range_limits) {
return unpack_skip(data, length, p, pack_error);
}
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::unpack_skip
// Access: Public, Virtual
// Description: Increments p to the end of the current field without
// actually unpacking any data or performing any range
// validation. Returns true on success, false on
// failure (e.g. we don't know how to skip this field).
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
unpack_skip(const char *data, size_t length, size_t &p,
bool &pack_error) const {
if (_has_fixed_byte_size) {
// If this field has a fixed byte size, it's easy to skip.
p += _fixed_byte_size;
if (p > length) {
pack_error = true;
}
return true;
}
if (_has_nested_fields && _num_length_bytes != 0) {
// If we have a length prefix, use that for skipping.
if (p + _num_length_bytes > length) {
pack_error = true;
} else {
if (_num_length_bytes == 4) {
size_t this_length = do_unpack_uint32(data + p);
p += this_length + 4;
} else {
size_t this_length = do_unpack_uint16(data + p);
p += this_length + 2;
}
if (p > length) {
pack_error = true;
}
}
return true;
}
// Otherwise, we don't know how to skip this field (presumably it
// can be skipped by skipping over its nested fields individually).
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::get_catalog
// Access: Public
// Description: Returns the DCPackerCatalog associated with this
// field, listing all of the nested fields by name.
////////////////////////////////////////////////////////////////////
const DCPackerCatalog *DCPackerInterface::
get_catalog() const {
if (_catalog == (DCPackerCatalog *)NULL) {
((DCPackerInterface *)this)->make_catalog();
}
return _catalog;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_simple_parameter
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// simple parameter, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_simple_parameter(const DCSimpleParameter *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_class_parameter
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// class parameter, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_class_parameter(const DCClassParameter *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_switch_parameter
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// switch parameter, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_switch_parameter(const DCSwitchParameter *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_array_parameter
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// array parameter, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_array_parameter(const DCArrayParameter *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_atomic_field
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// atomic field, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_atomic_field(const DCAtomicField *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::do_check_match_molecular_field
// Access: Protected, Virtual
// Description: Returns true if this field matches the indicated
// molecular field, false otherwise.
////////////////////////////////////////////////////////////////////
bool DCPackerInterface::
do_check_match_molecular_field(const DCMolecularField *) const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: DCPackerInterface::make_catalog
// Access: Private
// Description: Called internally to create a new DCPackerCatalog
// object.
////////////////////////////////////////////////////////////////////
void DCPackerInterface::
make_catalog() {
nassertv(_catalog == (DCPackerCatalog *)NULL);
_catalog = new DCPackerCatalog(this);
_catalog->r_fill_catalog("", this, NULL, 0);
}
| 38.119485 | 93 | 0.506197 | [
"object",
"3d"
] |
f0e706a6f6d634cdc69d4a792f1c53724df299be | 568 | cpp | C++ | Solutions/1-50/37/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | 2 | 2021-07-16T13:30:10.000Z | 2021-07-16T18:17:40.000Z | Solutions/1-50/37/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | null | null | null | Solutions/1-50/37/Solution.cpp | kitegi/Edmonton | 774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d | [
"Unlicense"
] | 1 | 2021-04-16T22:56:07.000Z | 2021-04-16T22:56:07.000Z | #include "../../Headers/Edmonton.hpp"
#include <iostream>
#include <vector>
using namespace std;
constexpr bool isTrunctable(int n, vector<int> &primes) {
for(int i = 10; i < n; i *= 10) {
if(!primes[n % i]) {
return false;
}
}
for(; n; n /= 10) {
if(!primes[n]) {
return false;
}
}
return true;
}
int main() {
vector<int> primes = Edmonton::generatePrimes(1'000'000, false);
int sum = 0;
for(int n = 11; n < primes.size(); n += 2) {
if(isTrunctable(n, primes)) {
sum += n;
}
}
std::cout << sum << "\n";
} | 18.933333 | 66 | 0.540493 | [
"vector"
] |
f0f02d34f2c48b58a19179b56b9902ee8bb2d8c9 | 1,682 | hpp | C++ | Plutonium/Include/pu/ui/elm/elm_ProgressBar.hpp | Pysis868/Plutonium | f789a58ec8c6d435ceda6c40509d1905865dd440 | [
"MIT"
] | 185 | 2018-11-12T10:55:32.000Z | 2022-03-28T16:01:21.000Z | Plutonium/Include/pu/ui/elm/elm_ProgressBar.hpp | matheesha-pathirana/Plutonium | fe5a9b96e52b70eceea493def38418fe021d2e74 | [
"MIT"
] | 39 | 2019-03-10T03:24:41.000Z | 2021-12-26T14:36:18.000Z | Plutonium/Include/pu/ui/elm/elm_ProgressBar.hpp | matheesha-pathirana/Plutonium | fe5a9b96e52b70eceea493def38418fe021d2e74 | [
"MIT"
] | 50 | 2018-11-28T07:01:56.000Z | 2022-02-25T17:01:24.000Z |
/*
Plutonium library
@file ProgressBar.hpp
@brief A ProgressBar is an Element which represents a progress (a percentage) by filling a bar.
@author XorTroll
@copyright Plutonium project - an easy-to-use UI framework for Nintendo Switch homebrew
*/
#pragma once
#include <pu/ui/elm/elm_Element.hpp>
namespace pu::ui::elm
{
class ProgressBar : public Element
{
public:
ProgressBar(i32 X, i32 Y, i32 Width, i32 Height, double MaxValue);
PU_SMART_CTOR(ProgressBar)
i32 GetX();
void SetX(i32 X);
i32 GetY();
void SetY(i32 Y);
i32 GetWidth();
void SetWidth(i32 Width);
i32 GetHeight();
void SetHeight(i32 Height);
Color GetColor();
void SetColor(Color Color);
Color GetProgressColor();
void SetProgressColor(Color Color);
double GetProgress();
void SetProgress(double Progress);
void IncrementProgress(double Progress);
void DecrementProgress(double Progress);
void SetMaxValue(double Max);
double GetMaxValue();
void FillProgress();
void ClearProgress();
bool IsCompleted();
void OnRender(render::Renderer::Ref &Drawer, i32 X, i32 Y);
void OnInput(u64 Down, u64 Up, u64 Held, Touch Pos);
private:
i32 x;
i32 y;
i32 w;
i32 h;
double val;
double maxval;
Color clr;
Color oclr;
};
} | 29 | 100 | 0.532105 | [
"render"
] |
f0f24427903feec5ee831fc7a81a2ad6de5788cb | 1,219 | cpp | C++ | test/meta/model_of.cpp | attugit/archie | af89fe2d89af3b9d764837853ae9fb42d18cdeac | [
"MIT"
] | 3 | 2015-02-18T22:58:23.000Z | 2016-06-07T17:43:09.000Z | test/meta/model_of.cpp | attugit/archie | af89fe2d89af3b9d764837853ae9fb42d18cdeac | [
"MIT"
] | null | null | null | test/meta/model_of.cpp | attugit/archie | af89fe2d89af3b9d764837853ae9fb42d18cdeac | [
"MIT"
] | null | null | null | #include <archie/traits/model_of.hpp>
#include <archie/meta/requires.hpp>
#include <archie/ignore.hpp>
#include <archie/models.hpp>
#include <vector>
#include <gtest/gtest.h>
namespace
{
using archie::meta::requires;
using archie::traits::model_of;
using archie::models::Callable;
using archie::models::Iterable;
namespace fused = archie::fused;
struct foo {
template <typename Tp>
int func(Tp, requires<model_of<Callable(Tp)>> = fused::ignore) const
{
return 0;
}
template <typename Tp>
int func(Tp, requires<model_of<Callable(Tp, int)>> = fused::ignore) const
{
return 1;
}
};
struct goo {
int operator()() { return 3; }
};
struct hoo {
int operator()(int) { return 4; }
};
TEST(model_of, canUseModelOf)
{
foo f;
goo g;
hoo h;
EXPECT_EQ(0, f.func(g));
EXPECT_EQ(1, f.func(h));
}
template <typename Tp>
struct is_iterable : model_of<Iterable(Tp)> {
};
struct no_iter {
};
struct iter {
no_iter* begin();
no_iter* end();
};
static_assert(!is_iterable<no_iter>::value, "");
static_assert(is_iterable<std::vector<no_iter>>::value, "");
static_assert(is_iterable<iter>::value, "");
}
| 19.349206 | 77 | 0.629204 | [
"vector"
] |
f0f3d5db4d888d45aafa9bffdc9d688943129382 | 3,469 | cpp | C++ | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfFontTTFSubset.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 30 | 2018-03-05T17:35:29.000Z | 2022-03-17T18:59:34.000Z | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfFontTTFSubset.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 2 | 2016-05-26T04:47:13.000Z | 2019-02-15T05:17:43.000Z | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfFontTTFSubset.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 5 | 2019-02-15T05:09:22.000Z | 2021-04-14T12:10:16.000Z | #include "podofo/base/PdfInputDevice.h"
#include "podofo/base/PdfOutputDevice.h"
#include "podofo/base/PdfRefCountedBuffer.h"
#include "podofo/doc/PdfFontMetrics.h"
#include "podofo/doc/PdfFontTTFSubset.h"
#include <vector>
#include "__zz_cib_CibPoDoFo-class-down-cast.h"
#include "__zz_cib_CibPoDoFo-delegate-helper.h"
#include "__zz_cib_CibPoDoFo-generic.h"
#include "__zz_cib_CibPoDoFo-ids.h"
#include "__zz_cib_CibPoDoFo-type-converters.h"
#include "__zz_cib_CibPoDoFo-mtable-helper.h"
#include "__zz_cib_CibPoDoFo-proxy-mgr.h"
namespace __zz_cib_ {
using namespace ::PoDoFo;
template <>
struct __zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset> : public ::PoDoFo::PdfFontTTFSubset {
using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset>;
using __zz_cib_AbiType = __zz_cib_Delegatee*;
using ::PoDoFo::PdfFontTTFSubset::PdfFontTTFSubset;
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_0(__zz_cib_AbiType_t<const char*> pszFontFileName, __zz_cib_AbiType_t<::PoDoFo::PdfFontMetrics*> pMetrics, __zz_cib_AbiType_t<unsigned short> nFaceIndex) {
return new __zz_cib_Delegatee( __zz_cib_::__zz_cib_FromAbiType<const char*>(pszFontFileName),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfFontMetrics*>(pMetrics),
__zz_cib_::__zz_cib_FromAbiType<unsigned short>(nFaceIndex));
}
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_1(__zz_cib_AbiType_t<::PoDoFo::PdfInputDevice*> pDevice, __zz_cib_AbiType_t<::PoDoFo::PdfFontMetrics*> pMetrics, __zz_cib_AbiType_t<::PoDoFo::PdfFontTTFSubset::EFontFileType> eType, __zz_cib_AbiType_t<unsigned short> nFaceIndex) {
return new __zz_cib_Delegatee( __zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfInputDevice*>(pDevice),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfFontMetrics*>(pMetrics),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfFontTTFSubset::EFontFileType>(eType),
__zz_cib_::__zz_cib_FromAbiType<unsigned short>(nFaceIndex));
}
static void __zz_cib_decl __zz_cib_Delete_2(__zz_cib_Delegatee* __zz_cib_obj) {
delete __zz_cib_obj;
}
static __zz_cib_AbiType_t<void> __zz_cib_decl BuildFont_3(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfRefCountedBuffer&> outputBuffer, __zz_cib_AbiType_t<const std::set<pdf_utf16be>&> usedChars, __zz_cib_AbiType_t<::std::vector<unsigned char>&> cidSet) {
__zz_cib_obj->::PoDoFo::PdfFontTTFSubset::BuildFont(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfRefCountedBuffer&>(outputBuffer),
__zz_cib_::__zz_cib_FromAbiType<const std::set<pdf_utf16be>&>(usedChars),
__zz_cib_::__zz_cib_FromAbiType<::std::vector<unsigned char>&>(cidSet)
);
}
};
}
namespace __zz_cib_ {
namespace __zz_cib_Class333 {
using namespace ::PoDoFo;
namespace __zz_cib_Class442 {
const __zz_cib_MethodTable* __zz_cib_GetMethodTable() {
static const __zz_cib_MTableEntry methodArray[] = {
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset>::__zz_cib_New_0),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset>::__zz_cib_New_1),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset>::__zz_cib_Delete_2),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfFontTTFSubset>::BuildFont_3)
};
static const __zz_cib_MethodTable methodTable = { methodArray, 4 };
return &methodTable;
}
}}}
| 54.203125 | 283 | 0.796771 | [
"vector"
] |
e7c4cf2a15bfa55a135892e07d16717dbf6a144b | 2,749 | cpp | C++ | evelight/mesh.cpp | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | 6 | 2018-04-29T23:25:06.000Z | 2021-01-24T02:11:23.000Z | evelight/mesh.cpp | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | null | null | null | evelight/mesh.cpp | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | 2 | 2020-04-18T15:09:01.000Z | 2020-08-24T06:44:41.000Z | // DOC: http://sunandblackcat.com/tipFullView.php?l=eng&topicid=18&topic=OpenGL-VAO-VBO-EBO
// somehow deprecated, use renderer.
#include "mesh.h"
#include <iostream>
namespace evl {
Mesh::Mesh()
{
mDirty = false;
mVertexArray = mVertexBuffer = mIndexBuffer = 0;
mDrawType = GL_LINES;
}
Mesh::~Mesh()
{
glDeleteBuffers(1, &mVertexBuffer);
glDeleteBuffers(1, &mVertexArray);
glDeleteBuffers(1, &mIndexBuffer);
}
void Mesh::SetVertices(const std::vector<Vertex>& vertices)
{
mVertices = vertices;
mDirty = true;
}
void Mesh::SetIndexes(const std::vector<int>& indexes)
{
mIndexes = indexes;
mDirty = true;
}
void Mesh::SetDrawType(GLenum drawType)
{
mDrawType = drawType;
}
void Mesh::SetProgramId(GLuint programId)
{
mProgramId = programId;
}
void Mesh::AddVertex(const Vertex& vertex)
{
mVertices.push_back(vertex);
mDirty = true;
}
void Mesh::AddIndex(const int index)
{
mIndexes.push_back(index);
mDirty = true;
}
void Mesh::Update()
{
enum shader_attrs {
POSITION,
COLOR,
UV,
SHADER_NUM_ATTRS
};
if (!mVertexArray) {
glGenVertexArrays(1, &mVertexArray);
glGenBuffers(1, &mVertexBuffer);
glGenBuffers(1, &mIndexBuffer);
}
glBindVertexArray(mVertexArray);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, mVertices.size() * sizeof(mVertices[0]), &mVertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndexes.size() * sizeof(mIndexes[0]), &mIndexes[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(POSITION);
glEnableVertexAttribArray(COLOR);
glEnableVertexAttribArray(UV);
/* attribute index, number of "coordinates" per vertex (size), type of "coordinate",
* normalized, stride, pointer */
glVertexAttribPointer(
POSITION, sizeof(mVertices[0].pos) / sizeof(float), GL_FLOAT, GL_FALSE,
sizeof(mVertices[0]), (void*)offsetof(Vertex, pos));
glVertexAttribPointer(
COLOR, sizeof(mVertices[0].color) / sizeof(uint8_t), GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(mVertices[0]), (void*)offsetof(Vertex, color));
glVertexAttribPointer(
UV, sizeof(mVertices[0].uv) / sizeof(float), GL_FLOAT, GL_FALSE,
sizeof(mVertices[0]), (void*)offsetof(Vertex, uv));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
mDirty = false;
}
void Mesh::Draw()
{
if (mDirty)
Update();
glBindVertexArray(mVertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glDrawElements(mDrawType, mIndexes.size(), GL_UNSIGNED_INT, nullptr);
}
}
| 24.544643 | 111 | 0.684249 | [
"mesh",
"vector"
] |
e7d7c7f7276fd58716829323a42d8d94631bc786 | 2,705 | cpp | C++ | tc 160+/BridgeSort.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/BridgeSort.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/BridgeSort.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
struct Card {
int suite, val;
Card(char s, char v) {
switch (s) {
case 'C': suite = 0; break;
case 'D': suite = 1; break;
case 'H': suite = 2; break;
case 'S': suite = 3; break;
}
switch (v) {
case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
val = v-'1'; break;
case 'T': val = 9; break;
case 'J': val = 10; break;
case 'Q': val = 11; break;
case 'K': val = 12; break;
case 'A': val = 13; break;
}
}
string print() const {
ostringstream os;
switch (suite) {
case 0: os << 'C'; break;
case 1: os << 'D'; break;
case 2: os << 'H'; break;
case 3: os << 'S'; break;
}
if (val < 9)
os << char(val + '1');
else
switch (val) {
case 9: os << 'T'; break;
case 10: os << 'J'; break;
case 11: os << 'Q'; break;
case 12: os << 'K'; break;
case 13: os << 'A'; break;
}
return os.str();
}
};
bool operator<(const Card &a, const Card &b) {
if (a.suite != b.suite)
return a.suite < b.suite;
else
return a.val < b.val;
}
class BridgeSort {
public:
string sortedHand(string hand) {
vector<Card> A;
for (int i=0; i<(int)hand.size(); i += 2)
A.push_back(Card(hand[i], hand[i+1]));
sort(A.begin(), A.end());
string sol;
for (int i=0; i<(int)A.size(); ++i)
sol += A[i].print();
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "HAH2H3C4D5ST" ; string Arg1 = "C4D5H2H3HAST"; verify_case(0, Arg1, sortedHand(Arg0)); }
void test_case_1() { string Arg0 = "H3SAHA"; string Arg1 = "H3HASA"; verify_case(1, Arg1, sortedHand(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
BridgeSort ___test;
___test.run_test(-1);
}
// END CUT HERE
| 27.05 | 315 | 0.540481 | [
"vector"
] |
e7db713769ddf2d6f02d12b31847b596305030a2 | 23,971 | cpp | C++ | src/CCodeCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | 12 | 2015-06-08T16:19:33.000Z | 2020-02-11T13:40:58.000Z | src/CCodeCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | null | null | null | src/CCodeCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | 6 | 2016-09-09T11:55:19.000Z | 2020-07-08T16:04:04.000Z | //! Common code counter methods for sub-classing individual languages.
/*!
* \file CCodeCounter.h
*
* This contains the base class code counter methods for inherited classes individual languages.
*
* Changed from UCC 2013_04 release by Randy Maxwell
* Changes started on 2015_06_06
* Changes ended on 2015_06_06
*/
#include <time.h>
#include "CCodeCounter.h"
#include "UCCGlobals.h"
/*!
* Constructs a CCodeCounter object.
*/
CCodeCounter::CCodeCounter()
{
print_cmplx = false;
lsloc_truncate = DEFAULT_TRUNCATE;
QuoteStart = "";
QuoteEnd = "";
QuoteEscapeFront = 0;
QuoteEscapeRear = 0;
ContinueLine = "";
classtype = UNKNOWN;
language_name = DEF_LANG_NAME;
casesensitive = true;
total_filesA = 0;
total_filesB = 0;
total_dupFilesA = 0;
total_dupFilesB = 0;
}
/*!
* Destroys a CCodeCounter object.
*/
CCodeCounter::~CCodeCounter()
{
}
/*!
* Initializes the count vectors.
* This method removes the existing content of the vectors and assigns them all zeros
*/
void CCodeCounter::InitializeCounts()
{
unsigned int i = 0;
counted_files = 0;
counted_dupFiles = 0;
directive_count.assign(directive.size(), make_pair(i, i));
data_name_count.assign(data_name_list.size(), make_pair(i, i));
exec_name_count.assign(exec_name_list.size(), make_pair(i, i));
math_func_count.assign(math_func_list.size(), make_pair(i, i));
trig_func_count.assign(trig_func_list.size(), make_pair(i, i));
log_func_count.assign(log_func_list.size(), make_pair(i, i));
cmplx_calc_count.assign(cmplx_calc_list.size(), make_pair(i, i));
cmplx_cond_count.assign(cmplx_cond_list.size(), make_pair(i, i));
cmplx_logic_count.assign(cmplx_logic_list.size(), make_pair(i, i));
cmplx_preproc_count.assign(cmplx_preproc_list.size(), make_pair(i, i));
cmplx_assign_count.assign(cmplx_assign_list.size(), make_pair(i, i));
cmplx_pointer_count.assign(cmplx_pointer_list.size(), make_pair(i, i));
}
/*!
* Initializes the count vectors for a result.
* This method removes the existing content of the vectors and assigns them all zeros
*/
void CCodeCounter::InitializeResultsCounts(results* result)
{
result->directive_count.assign(directive.size(), 0);
result->data_name_count.assign(data_name_list.size(), 0);
result->exec_name_count.assign(exec_name_list.size(), 0);
result->math_func_count.assign(math_func_list.size(), 0);
result->trig_func_count.assign(trig_func_list.size(), 0);
result->log_func_count.assign(log_func_list.size(), 0);
result->cmplx_calc_count.assign(cmplx_calc_list.size(), 0);
result->cmplx_cond_count.assign(cmplx_cond_list.size(), 0);
result->cmplx_logic_count.assign(cmplx_logic_list.size(), 0);
result->cmplx_preproc_count.assign(cmplx_preproc_list.size(), 0);
result->cmplx_assign_count.assign(cmplx_assign_list.size(), 0);
result->cmplx_pointer_count.assign(cmplx_pointer_list.size(), 0);
}
/*!
* Processes and counts the source file.
*
* \param fmap list of file lines
* \param result counter results
*
* \return method status
*/
int CCodeCounter::CountSLOC(filemap* fmap, results* result)
{
// backup file content before modifying it (comments and directive lines are cleared)
// fmapBak is same as fmap except that it stores unmodified quoted strings
// fmap has quoted strings replaced with '$'
filemap fmapMod = *fmap;
filemap fmapModBak = *fmap;
InitializeResultsCounts(result);
PreCountProcess(&fmapMod);
CountBlankSLOC(&fmapMod, result);
CountCommentsSLOC(&fmapMod, result, &fmapModBak);
if (print_cmplx)
CountComplexity(&fmapMod, result);
CountDirectiveSLOC(&fmapMod, result, &fmapModBak);
LanguageSpecificProcess(&fmapMod, result, &fmapModBak);
return 0;
}
/*!
* Checks whether the file extension is supported by the language counter.
*
* \param file_name file name
*
* \return whether file extension is supported
*/
bool CCodeCounter::IsSupportedFileExtension(const string &file_name)
{
// if Makefile, check whether name equals MAKEFILE since no extension exists
if (classtype == MAKEFILE && file_name.size() >= 8)
{
if (CUtil::ToLower(file_name.substr(file_name.size() - 8)) == "makefile")
return true;
}
size_t idx = file_name.find_last_of(".");
if (idx == string::npos)
return false;
string file_ext = file_name.substr(idx);
file_ext = CUtil::ToLower(file_ext);
if (find(file_extension.begin(), file_extension.end(), file_ext) != file_extension.end())
{
// if X-Midas/NeXtMidas, parse file to check for startmacro or endmacro (needed since Midas can use .txt or .mm)
if (classtype == XMIDAS || classtype == NEXTMIDAS)
{
string oneline;
ifstream fr(file_name.c_str(), ios::in);
if (!fr.is_open())
return false;
// search for "startmacro" (optional) or "endmacro" (required)
while (fr.good() || fr.eof())
{
getline(fr, oneline);
if ((!fr.good() && !fr.eof()) || (fr.eof() && oneline.empty()))
break;
oneline = CUtil::ToLower(CUtil::TrimString(oneline));
if (oneline.compare(0, 10, "startmacro") == 0 || oneline.compare(0, 8, "endmacro") == 0)
{
fr.clear();
fr.close();
return true;
}
if (!fr.good())
break;
}
fr.clear();
fr.close();
}
else
return true;
}
return false;
}
/*!
* Retrieves the language output file stream.
* Opens a new stream if it has not been opened already.
*
* \param outputFileNamePrePend name to prepend to the output file
* \param cmd current command line string
* \param csvOutput CSV file stream? (otherwise ASCII text file)
* \param legacyOutput legacy format file stream? (otherwise standard text file)
*
* \return output file stream
*/
ofstream* CCodeCounter::GetOutputStream(const string &outputFileNamePrePend, const string &cmd, bool csvOutput, bool legacyOutput)
{
if (csvOutput)
{
if (!output_file_csv.is_open())
{
string fname = outputFileNamePrePend + language_name + OUTPUT_FILE_NAME_CSV;
output_file_csv.open(fname.c_str(), ofstream::out);
if (!output_file_csv.is_open()) return NULL;
CUtil::PrintFileHeader(output_file_csv, "SLOC COUNT RESULTS", cmd);
CUtil::PrintFileHeaderLine(output_file_csv, "RESULTS FOR " + language_name + " FILES");
output_file_csv << endl;
output_file_csv << "Total,Blank,Comments,,Compiler,Data,Exec.,Logical,Physical,File,Module" << endl;
output_file_csv << "Lines,Lines,Whole,Embedded,Direct.,Decl.,Instr.,SLOC,SLOC,Type,Name" << endl;
}
return &output_file_csv;
}
else
{
if (!output_file.is_open())
{
string fname = outputFileNamePrePend + language_name + OUTPUT_FILE_NAME;
output_file.open(fname.c_str(), ofstream::out);
if (!output_file.is_open()) return NULL;
CUtil::PrintFileHeader(output_file, "SLOC COUNT RESULTS", cmd);
CUtil::PrintFileHeaderLine(output_file, "RESULTS FOR " + language_name + " FILES");
output_file << endl;
if (legacyOutput)
{
output_file << " Total Blank | Comments | Compiler Data Exec. | Logical | File Module" << endl;
output_file << " Lines Lines | Whole Embedded | Direct. Decl. Instr. | SLOC | Type Name" << endl;
output_file << "-----------------+------------------+-------------------------+---------+---------------------------" << endl;
}
else
{
output_file << " Total Blank | Comments | Compiler Data Exec. | Logical Physical | File Module" << endl;
output_file << " Lines Lines | Whole Embedded | Direct. Decl. Instr. | SLOC SLOC | Type Name" << endl;
output_file << "-----------------+------------------+-------------------------+------------------+---------------------------" << endl;
}
}
return &output_file;
}
}
/*!
* Closes the language output file stream.
*/
void CCodeCounter::CloseOutputStream()
{
if (output_file.is_open())
output_file.close();
if (output_file_csv.is_open())
output_file_csv.close();
}
/*!
* Finds the first index of one of the characters of strQuote in strline.
*
* \param strline string line
* \param strQuote string of character(s) to find in strline
* \param idx_start index of line character to start search
* \param QuoteEscapeFront quote escape character
*
* \return index of strQuote character in strline
*/
size_t CCodeCounter::FindQuote(string const &strline, string const &strQuote, size_t idx_start, char QuoteEscapeFront)
{
size_t min_idx, idx;
min_idx = strline.length();
for (size_t i = 0; i < strQuote.length(); i++)
{
idx = CUtil::FindCharAvoidEscape(strline, strQuote[i], idx_start, QuoteEscapeFront);
if (idx != string::npos && idx < min_idx)
min_idx = idx;
}
if (min_idx < strline.length())
return min_idx;
return string::npos;
}
/*!
* Replaces up to ONE quoted string inside a string starting at idx_start.
*
* \param strline string to be processed
* \param idx_start index of line character to start search
* \param contd specifies the quote string is continued from the previous line
* \param CurrentQuoteEnd end quote character of the current status
*
* \return method status
*/
int CCodeCounter::ReplaceQuote(string &strline, size_t &idx_start, bool &contd, char &CurrentQuoteEnd)
{
size_t idx_end, idx_quote;
if (contd)
{
idx_start = 0;
if (strline[0] == CurrentQuoteEnd)
{
idx_start = 1;
contd = false;
return 1;
}
strline[0] = '$';
}
else
{
// handle two quote chars in some languages, both " and ' may be accepted
idx_start = FindQuote(strline, QuoteStart, idx_start, QuoteEscapeFront);
if (idx_start != string::npos)
{
idx_quote = QuoteStart.find_first_of(strline[idx_start]);
CurrentQuoteEnd = QuoteEnd[idx_quote];
}
else
{
idx_start = strline.length();
return 0;
}
}
idx_end = CUtil::FindCharAvoidEscape(strline, CurrentQuoteEnd, idx_start + 1, QuoteEscapeFront);
if (idx_end == string::npos)
{
idx_end = strline.length() - 1;
strline.replace(idx_start + 1, idx_end - idx_start, idx_end - idx_start, '$');
contd = true;
idx_start = idx_end + 1;
}
else
{
if ((QuoteEscapeRear) && (strline.length() > idx_end + 1) && (strline[idx_end+1] == QuoteEscapeRear))
{
strline[idx_end] = '$';
strline[idx_end+1] = '$';
}
else
{
contd = false;
strline.replace(idx_start + 1, idx_end - idx_start - 1, idx_end - idx_start - 1, '$');
idx_start = idx_end + 1;
}
}
return 1;
}
/*!
* Counts blank lines in a file.
*
* \param fmap list of file lines
* \param result counter results
*
* \return method status
*/
int CCodeCounter::CountBlankSLOC(filemap* fmap, results* result)
{
for (filemap::iterator i = fmap->begin(); i != fmap->end(); i++)
{
if (CUtil::CheckBlank(i->line))
result->blank_lines++;
}
return 1;
}
/*!
* Counts the number of comment lines, removes comments, and
* replaces quoted strings by special chars, e.g., $
* All arguments are modified by the method.
*
* \param fmap list of processed file lines
* \param result counter results
* \param fmapBak list of original file lines (same as fmap except it contains unmodified quoted strings)
*
* \return method status
*/
int CCodeCounter::CountCommentsSLOC(filemap* fmap, results* result, filemap *fmapBak)
{
if (BlockCommentStart.empty() && LineCommentStart.empty())
return 0;
if (classtype == UNKNOWN || classtype == DATAFILE)
return 0;
bool contd = false;
bool contd_nextline;
int comment_type = 0;
/*
comment_type:
0 : not a comment
1 : line comment, whole line
2 : line comment, embedded
3 : block comment, undecided
4 : block comment, embedded
*/
size_t idx_start, idx_end, comment_start;
size_t quote_idx_start;
string curBlckCmtStart, curBlckCmtEnd;
char CurrentQuoteEnd = 0;
bool quote_contd = false;
filemap::iterator itfmBak = fmapBak->begin();
quote_idx_start = 0;
for (filemap::iterator iter = fmap->begin(); iter != fmap->end(); iter++, itfmBak++)
{
contd_nextline = false;
quote_idx_start = 0;
idx_start = 0;
if (CUtil::CheckBlank(iter->line))
continue;
if (quote_contd)
{
// Replace quote until next character
ReplaceQuote(iter->line, quote_idx_start, quote_contd, CurrentQuoteEnd);
if (quote_contd)
continue;
}
if (contd)
comment_type = 3;
while (!contd_nextline && idx_start < iter->line.length())
{
// need to handle multiple quote chars in some languages, both " and ' may be accepted
quote_idx_start = FindQuote(iter->line, QuoteStart, quote_idx_start, QuoteEscapeFront);
comment_start = idx_start;
if (!contd)
FindCommentStart(iter->line, comment_start, comment_type, curBlckCmtStart, curBlckCmtEnd);
if (comment_start == string::npos && quote_idx_start == string::npos)
break;
if (comment_start != string::npos)
idx_start = comment_start;
// if found quote before comment, e.g., "this is quote");//comment
if (quote_idx_start != string::npos && (comment_start == string::npos || quote_idx_start < comment_start))
{
ReplaceQuote(iter->line, quote_idx_start, quote_contd, CurrentQuoteEnd);
if (quote_idx_start > idx_start && quote_idx_start != iter->line.length())
{
// comment delimiter inside quote
idx_start = quote_idx_start;
continue;
}
}
else if (comment_start != string::npos)
{
// comment delimiter starts first
switch (comment_type)
{
case 1: // line comment, definitely whole line
iter->line = "";
itfmBak->line = "";
result->comment_lines++;
contd_nextline = true;
break;
case 2: // line comment, possibly embedded
iter->line = iter->line.substr(0, idx_start);
itfmBak->line = itfmBak->line.substr(0, idx_start);
// trim trailing space
iter->line = CUtil::TrimString(iter->line, 1);
itfmBak->line = CUtil::TrimString(itfmBak->line, 1);
if (iter->line.empty())
result->comment_lines++; // whole line
else
result->e_comm_lines++; // embedded
contd_nextline = true;
break;
case 3: // block comment
case 4:
if (contd)
idx_end = iter->line.find(curBlckCmtEnd);
else
idx_end = iter->line.find(curBlckCmtEnd, idx_start + curBlckCmtStart.length());
if (idx_end == string::npos)
{
if (comment_type == 3)
{
iter->line = "";
itfmBak->line = "";
result->comment_lines++;
}
else if (comment_type == 4)
{
iter->line = iter->line.substr(0, idx_start);
itfmBak->line = itfmBak->line.substr(0, idx_start);
// trim trailing space
iter->line = CUtil::TrimString(iter->line, 1);
itfmBak->line = CUtil::TrimString(itfmBak->line, 1);
if (iter->line.empty())
result->comment_lines++; // whole line
else
result->e_comm_lines++; // embedded
}
contd = true;
contd_nextline = true;
break;
}
else
{
contd = false;
iter->line.erase(idx_start, idx_end - idx_start + curBlckCmtEnd.length());
itfmBak->line.erase(idx_start, idx_end - idx_start + curBlckCmtEnd.length());
if (iter->line.empty())
result->comment_lines++;
else
{
// trim trailing space
iter->line = CUtil::TrimString(iter->line, 1);
itfmBak->line = CUtil::TrimString(itfmBak->line, 1);
if (iter->line.empty())
result->comment_lines++; // whole line
else
result->e_comm_lines++; // embedded
}
// quote chars found may be erased as it is inside comment
quote_idx_start = idx_start;
}
break;
default:
cout << "Error in CountCommentsSLOC()" << endl;
break;
}
}
}
}
return 1;
}
/*!
* Finds a starting position of a comment in a string starting at idx_start.
*
* \param strline string to be processed
* \param idx_start index of line character to start search
* \param comment_type comment type (0=not a comment, 1=whole line, 2=embedded line, 3=whole line block, 4=embedded block)
* \param curBlckCmtStart current block comment start string
* \param curBlckCmtEnd current block comment end string
*
* \return method status
*/
int CCodeCounter::FindCommentStart(string strline, size_t &idx_start, int &comment_type,
string &curBlckCmtStart, string &curBlckCmtEnd)
{
size_t idx_line, idx_tmp, idx_block;
string line = strline;
comment_type = 0;
if (!casesensitive)
line = CUtil::ToLower(line);
// searching for starting of line comment
idx_line = string::npos;
for (StringVector::iterator i = LineCommentStart.begin(); i != LineCommentStart.end(); i++)
{
idx_tmp = line.find((casesensitive ? (*i) : CUtil::ToLower(*i)), idx_start);
if (idx_tmp < idx_line) idx_line = idx_tmp;
}
// searching for starting of block comment
idx_block = string::npos;
for (StringVector::iterator i = BlockCommentStart.begin(); i != BlockCommentStart.end(); i++)
{
idx_tmp = strline.find(*i, idx_start);
if (idx_tmp < idx_block)
{
idx_block = idx_tmp;
curBlckCmtStart = *i;
curBlckCmtEnd = *(BlockCommentEnd.begin() + (i - BlockCommentStart.begin()));
}
}
// see what kind of comment appears first
if (idx_line == string::npos && idx_block == string::npos)
{
comment_type = 0;
idx_start = idx_line;
}
else if (idx_block > idx_line)
{
idx_start = idx_line;
comment_type = idx_start == 0 ? 1 : 2;
}
else
{
idx_start = idx_block;
comment_type = idx_start == 0 ? 3 : 4;
}
return 1;
}
/*!
* Counts file language complexity based on specified language keywords/characters.
*
* \param fmap list of processed file lines
* \param result counter results
*
* \return method status
*/
int CCodeCounter::CountComplexity(filemap* fmap, results* result)
{
if (classtype == UNKNOWN || classtype == DATAFILE)
return 0;
filemap::iterator fit;
size_t idx;
unsigned int cnt, ret, cyclomatic_cnt = 0, ignore_cyclomatic_cnt = 0, main_cyclomatic_cnt = 0, function_count = 0;
string line, lastline, file_ext, function_name = "";
string exclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$";
filemap function_stack;
stack<unsigned int> cyclomatic_stack;
map<unsigned int, lineElement> function_map;
bool process_cyclomatic_complexity = false;
// check whether to process cyclomatic complexity
if (cmplx_cyclomatic_list.size() > 0)
{
process_cyclomatic_complexity = true;
if (skip_cmplx_cyclomatic_file_extension_list.size() > 0)
{
idx = result->file_name.find_last_of(".");
if (idx != string::npos)
{
file_ext = result->file_name.substr(idx);
file_ext = CUtil::ToLower(file_ext);
if (find(skip_cmplx_cyclomatic_file_extension_list.begin(), skip_cmplx_cyclomatic_file_extension_list.end(), file_ext) != skip_cmplx_cyclomatic_file_extension_list.end())
process_cyclomatic_complexity = false;
}
}
}
// process each line
for (fit = fmap->begin(); fit != fmap->end(); fit++)
{
line = fit->line;
if (CUtil::CheckBlank(line))
continue;
line = " " + line;
// mathematical functions
cnt = 0;
CUtil::CountTally(line, math_func_list, cnt, 1, exclude, "", "", &result->math_func_count, casesensitive);
result->cmplx_math_lines += cnt;
// trigonometric functions
cnt = 0;
CUtil::CountTally(line, trig_func_list, cnt, 1, exclude, "", "", &result->trig_func_count, casesensitive);
result->cmplx_trig_lines += cnt;
// logarithmic functions
cnt = 0;
CUtil::CountTally(line, log_func_list, cnt, 1, exclude, "", "", &result->log_func_count, casesensitive);
result->cmplx_logarithm_lines += cnt;
// calculations
cnt = 0;
CUtil::CountTally(line, cmplx_calc_list, cnt, 1, exclude, "", "", &result->cmplx_calc_count, casesensitive);
result->cmplx_calc_lines += cnt;
// conditionals
cnt = 0;
CUtil::CountTally(line, cmplx_cond_list, cnt, 1, exclude, "", "", &result->cmplx_cond_count, casesensitive);
result->cmplx_cond_lines += cnt;
// logical operators
cnt = 0;
CUtil::CountTally(line, cmplx_logic_list, cnt, 1, exclude, "", "", &result->cmplx_logic_count, casesensitive);
result->cmplx_logic_lines += cnt;
// preprocessor directives
cnt = 0;
CUtil::CountTally(line, cmplx_preproc_list, cnt, 1, exclude, "", "", &result->cmplx_preproc_count, casesensitive);
result->cmplx_preproc_lines += cnt;
// assignments
cnt = 0;
CUtil::CountTally(line, cmplx_assign_list, cnt, 1, exclude, "", "", &result->cmplx_assign_count, casesensitive);
result->cmplx_assign_lines += cnt;
// pointers
cnt = 0;
CUtil::CountTally(line, cmplx_pointer_list, cnt, 1, exclude, "", "", &result->cmplx_pointer_count, casesensitive);
result->cmplx_pointer_lines += cnt;
// cyclomatic complexity
if (process_cyclomatic_complexity)
{
// search for cyclomatic complexity keywords
CUtil::CountTally(line, cmplx_cyclomatic_list, cyclomatic_cnt, 1, exclude, "", "", 0, casesensitive);
// search for keywords to exclude
if (ignore_cmplx_cyclomatic_list.size() > 0)
CUtil::CountTally(line, ignore_cmplx_cyclomatic_list, ignore_cyclomatic_cnt, 1, exclude, "", "", 0, casesensitive);
// parse function name if found
ret = ParseFunctionName(line, lastline, function_stack, function_name, function_count);
if (ret != 1 && !cyclomatic_stack.empty() && cyclomatic_stack.size() == function_stack.size())
{
// remove count stack entry for non-function names
cyclomatic_cnt += cyclomatic_stack.top();
ignore_cyclomatic_cnt = 0;
cyclomatic_stack.pop();
}
if (ret == 1)
{
// capture count at end of function
lineElement element(cyclomatic_cnt - ignore_cyclomatic_cnt + 1, function_name);
function_map[function_count] = element;
if (!function_stack.empty())
{
// grab previous function from stack to continue
if (!cyclomatic_stack.empty())
{
cyclomatic_cnt = cyclomatic_stack.top();
cyclomatic_stack.pop();
}
}
else
cyclomatic_cnt = 0;
function_name = "";
ignore_cyclomatic_cnt = 0;
}
else if (ret == 2)
{
// some code doesn't belong to any function
main_cyclomatic_cnt += cyclomatic_cnt - ignore_cyclomatic_cnt;
if (main_cyclomatic_cnt < 1)
main_cyclomatic_cnt = 1; // add 1 for main function here in case no other decision points are found in main
cyclomatic_cnt = ignore_cyclomatic_cnt = 0;
}
else if (!function_stack.empty() && (function_stack.size() > cyclomatic_stack.size() + 1 || (cyclomatic_stack.empty() && function_stack.size() > 1)))
{
// capture previous complexity count from open function
cyclomatic_stack.push(cyclomatic_cnt - ignore_cyclomatic_cnt);
cyclomatic_cnt = ignore_cyclomatic_cnt = 0;
}
}
}
// done with a file
if (main_cyclomatic_cnt > 0)
{
// add "main" code
lineElement element(main_cyclomatic_cnt, "main");
function_map[0] = element;
}
else
{
// finish the first function if not closed
while (!function_stack.empty())
{
function_name = function_stack.back().line;
function_count = function_stack.back().lineNumber;
function_stack.pop_back();
if (!function_stack.empty())
{
// grab previous function from stack to continue
if (!cyclomatic_stack.empty())
{
cyclomatic_cnt = cyclomatic_stack.top();
cyclomatic_stack.pop();
}
}
else
{
// capture count at end of function
lineElement element(cyclomatic_cnt + 1, function_name);
function_map[0] = element;
}
}
}
// process ordered functions
for (map<unsigned int, lineElement>::iterator it = function_map.begin(); it != function_map.end(); ++it)
result->cmplx_cycfunct_count.push_back(it->second);
return 1;
}
/*!
* Processes physical and logical lines.
* This method is typically implemented in the specific language sub-class.
*
* \param fmap list of processed file lines
* \param result counter results
* \param fmapBak list of original file lines (same as fmap except it contains unmodified quoted strings)
*
* \return method status
*/
int CCodeCounter::LanguageSpecificProcess(filemap* fmap, results* result, filemap* /*fmapBak*/)
{
for (filemap::iterator iter = fmap->begin(); iter != fmap->end(); iter++)
{
if (!CUtil::CheckBlank(iter->line))
result->exec_lines[PHY]++;
}
return 1;
}
| 29.889027 | 174 | 0.683868 | [
"object"
] |
e7deb9b5140a0d379e634b666647d02239d04f2a | 2,277 | cpp | C++ | DungeonClient/DG_Sprite.cpp | meowqwe/Dungeon | 3dbf52ea420ee0a67c936ee8e298fac9e002235b | [
"MIT"
] | 5 | 2021-11-30T13:35:04.000Z | 2021-12-28T03:08:41.000Z | DungeonClient/DG_Sprite.cpp | VoidmatrixHeathcliff/Dungeon | 8ac0a793c82cbe76a4313fc115e1330fb08db694 | [
"MIT"
] | 1 | 2022-01-14T10:45:31.000Z | 2022-01-14T10:45:31.000Z | DungeonClient/DG_Sprite.cpp | meowqwe/Dungeon | 3dbf52ea420ee0a67c936ee8e298fac9e002235b | [
"MIT"
] | 2 | 2022-01-13T09:41:07.000Z | 2022-01-14T10:38:29.000Z | #include "DG_Sprite.h"
DG_Sprite::DG_Sprite(std::string file_path, bool lean)
{
if (__m_pSurface = IMG_Load(file_path.c_str()))
{
m_nWidth = __m_pSurface->w, m_nHeight = __m_pSurface->h;
if (!lean) __m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
}
}
DG_Sprite::DG_Sprite(void* mem, int size, bool lean)
{
if (__m_pSurface = IMG_Load_RW(SDL_RWFromMem(mem, size), 1))
{
m_nWidth = __m_pSurface->w, m_nHeight = __m_pSurface->h;
if (!lean) __m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
}
}
DG_Sprite::~DG_Sprite()
{
if (__m_pSurface)
{
SDL_FreeSurface(__m_pSurface);
__m_pSurface = nullptr;
}
if (__m_pTexture)
{
SDL_DestroyTexture(__m_pTexture);
__m_pTexture = nullptr;
}
}
void DG_Sprite::Slim(SlimType type)
{
if (type == SlimType::SURFACE && __m_pSurface)
{
SDL_FreeSurface(__m_pSurface);
__m_pSurface = nullptr;
}
else if (type == SlimType::TEXTURE && __m_pTexture)
{
SDL_DestroyTexture(__m_pTexture);
__m_pTexture = nullptr;
}
}
void DG_Sprite::SetColorKey(const SDL_Color& color, bool enable)
{
if (__m_pSurface)
SDL_SetColorKey(__m_pSurface, enable,
SDL_MapRGBA(__m_pSurface->format, color.r, color.g, color.b, color.a));
if (__m_pTexture)
{
SDL_DestroyTexture(__m_pTexture);
__m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
}
}
void DG_Sprite::SetAlpha(Uint8 value)
{
if (!__m_pTexture && !__m_pSurface) return;
if (!__m_pTexture)
__m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
SDL_SetTextureBlendMode(__m_pTexture, SDL_BLENDMODE_BLEND);
SDL_SetTextureAlphaMod(__m_pTexture, value);
}
void DG_Sprite::Render(const SDL_Rect* src, const SDL_Rect* dst)
{
if (!__m_pTexture && !__m_pSurface) return;
if (!__m_pTexture)
__m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
SDL_RenderCopy(g_pRenderer, __m_pTexture, src, dst);
}
void DG_Sprite::RenderEx(const SDL_Rect* src, const SDL_Rect* dst, double angle, const SDL_Point& center, SDL_RendererFlip flip)
{
if (!__m_pTexture && !__m_pSurface) return;
if (!__m_pTexture)
__m_pTexture = SDL_CreateTextureFromSurface(g_pRenderer, __m_pSurface);
SDL_RenderCopyEx(g_pRenderer, __m_pTexture, src, dst, angle, ¢er, flip);
} | 24.75 | 128 | 0.751427 | [
"render"
] |
e7e044342f0b0e99661382c5f12c45c36ce8875a | 3,501 | hpp | C++ | include/fluidity/setting/simulator_parameter.hpp | robclu/fluidity | 22069dc3b0280f843494913a2371f940531d1744 | [
"MIT"
] | 1 | 2018-04-21T09:24:36.000Z | 2018-04-21T09:24:36.000Z | include/fluidity/setting/simulator_parameter.hpp | robclu/fluidity | 22069dc3b0280f843494913a2371f940531d1744 | [
"MIT"
] | 4 | 2018-08-05T12:14:41.000Z | 2021-09-20T14:38:50.000Z | include/fluidity/setting/simulator_parameter.hpp | robclu/fluidity | 22069dc3b0280f843494913a2371f940531d1744 | [
"MIT"
] | null | null | null | //==--- fluidity/setting/simulator_parameter.hpp ----------- -*- C++ -*- ---==//
//
// Fluidity
//
// Copyright (c) 2018 Rob Clucas.
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//==------------------------------------------------------------------------==//
//
/// \file simulator_parameter.hpp
/// \brief This file defines a class which implements the Parameter interface
/// to allow paramters for the simulator to be set.
//
//==------------------------------------------------------------------------==//
#ifndef FLUIDITY_SETTING_SIMULATOR_PARAMETER_HPP
#define FLUIDITY_SETTING_SIMULATOR_PARAMETER_HPP
#include "parameter.hpp"
#include "settings.hpp"
#include <fluidity/utility/string.hpp>
namespace fluid {
namespace setting {
/// The SimualtorParameter class allows parameters of the simulator to be
/// specified.
struct SimulatorParameter : public Parameter {
private:
/// Defines the format for a domain parameter.
static constexpr const char* format =
"simulator : {\n"
" [data_type : value][,]\n"
" [limit_form : value][,]\n"
" [limiter : value][,]\n"
" [reconstructor : value][,]\n"
" [flux_method : value][,]\n"
" [solve_method : value][,]\n"
" [execution : value][,]\n"
"}\n";
public:
/// Defines the type of the container for the dimension information.
using container_t = std::vector<Setting>;
/// Returns the string identifier which defines the name of the setting.
std::string type() const final override
{
return "simulator";
}
/// Returns a vector of identifiers for the names of settings for the domain.
std::vector<std::string> param_options() const final override
{
return std::vector<std::string>{
"data_type" ,
"limit_form" ,
"limiter" ,
"material" ,
"reconstructor",
"flux_method" ,
"solve_method" ,
"execution"
};
}
/// Returns a string which defines the format for the parameter.
std::string format_info() const final override
{
return format;
}
/// Returns a string with the information for the parameter.
std::string display_string() const final override
{
std::ostringstream stream;
util::format_name_value(stream, "name", type(), 0, 4);
for (const auto& setting : _settings)
{
util::format_name_value(stream, setting.name, setting.value, 2, 13);
}
return stream.str();
}
/// Sets the dimension information for a dimension.
/// \param[in] sim_setting The setting whose value contains the information
/// to use to set the simulator parameters.
bool try_set(const Setting& sim_setting) final override
{
auto settings = Settings::from_string(sim_setting.value);
for (auto& setting : settings)
{
if (setting.complex || !this->valid_param(setting.name))
{
std::cout << "Failed to parse simulator setting : " << setting.name
<< ". Simulator settings must all be { name : value }, with "
<< "format:\n" << format;
return false;
}
util::remove(setting.value, ',', '}','\n');
_settings.push_back(setting);
}
return true;
}
private:
container_t _settings; //!< Information for the siulator.
};
}} // namespace fluid::setting
#endif // FLUIDITY_SETTING_SIMULATOR_PARAMETER_HPP | 30.982301 | 80 | 0.592402 | [
"vector"
] |
e7e325cbee88fcef3c9c0f4d0b3fa2010084cfa0 | 11,039 | cpp | C++ | src/lzma-stream.cpp | earlyorbit/lzma-native | 39f18e9a5d1e6d65966e22c06b85f77594c6550f | [
"MIT"
] | 99 | 2015-03-18T13:54:04.000Z | 2022-03-31T17:43:11.000Z | src/lzma-stream.cpp | earlyorbit/lzma-native | 39f18e9a5d1e6d65966e22c06b85f77594c6550f | [
"MIT"
] | 116 | 2015-06-03T10:10:16.000Z | 2022-02-28T10:29:27.000Z | src/lzma-stream.cpp | earlyorbit/lzma-native | 39f18e9a5d1e6d65966e22c06b85f77594c6550f | [
"MIT"
] | 43 | 2015-04-13T05:21:05.000Z | 2022-03-31T17:43:13.000Z | #include "liblzma-node.hpp"
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <climits>
namespace lzma {
namespace {
extern "C" void* LZMA_API_CALL
alloc_for_lzma(void *opaque, size_t nmemb, size_t size) {
LZMAStream* strm = static_cast<LZMAStream*>(opaque);
return strm->alloc(nmemb, size);
}
extern "C" void LZMA_API_CALL
free_for_lzma(void *opaque, void *ptr) {
LZMAStream* strm = static_cast<LZMAStream*>(opaque);
return strm->free(ptr);
}
}
LZMAStream::LZMAStream(const CallbackInfo& info) :
ObjectWrap(info),
async_context(info.Env(), "LZMAStream"),
bufsize(65536),
shouldFinish(false),
processedChunks(0),
lastCodeResult(LZMA_OK)
{
std::memset(&_, 0, sizeof(lzma_stream));
allocator.alloc = alloc_for_lzma;
allocator.free = free_for_lzma;
allocator.opaque = static_cast<void*>(this);
_.allocator = &allocator;
nonAdjustedExternalMemory = 0;
MemoryManagement::AdjustExternalMemory(info.Env(), sizeof(LZMAStream));
}
void LZMAStream::resetUnderlying() {
if (_.internal != nullptr)
lzma_end(&_);
reportAdjustedExternalMemoryToV8();
std::memset(&_, 0, sizeof(lzma_stream));
_.allocator = &allocator;
lastCodeResult = LZMA_OK;
processedChunks = 0;
}
LZMAStream::~LZMAStream() {
resetUnderlying();
MemoryManagement::AdjustExternalMemory(Env(), -int64_t(sizeof(LZMAStream)));
}
void* LZMAStream::alloc(size_t nmemb, size_t size) {
size_t nBytes = nmemb * size + sizeof(size_t);
size_t* result = static_cast<size_t*>(::malloc(nBytes));
if (!result)
return result;
*result = nBytes;
adjustExternalMemory(static_cast<int64_t>(nBytes));
return static_cast<void*>(result + 1);
}
void LZMAStream::free(void* ptr) {
if (!ptr)
return;
size_t* orig = static_cast<size_t*>(ptr) - 1;
adjustExternalMemory(-static_cast<int64_t>(*orig));
return ::free(static_cast<void*>(orig));
}
void LZMAStream::reportAdjustedExternalMemoryToV8() {
int64_t to_be_reported = nonAdjustedExternalMemory.exchange(0);
if (to_be_reported == 0)
return;
MemoryManagement::AdjustExternalMemory(Env(), nonAdjustedExternalMemory);
}
void LZMAStream::adjustExternalMemory(int64_t bytesChange) {
nonAdjustedExternalMemory += bytesChange;
}
void LZMAStream::ResetUnderlying(const CallbackInfo& info) {
MemScope mem_scope(this);
std::lock_guard<std::mutex> lock(mutex);
resetUnderlying();
}
Value LZMAStream::SetBufsize(const CallbackInfo& info) {
size_t oldBufsize, newBufsize = NumberToUint64ClampNullMax(info[0]);
{
std::lock_guard<std::mutex> lock(mutex);
oldBufsize = bufsize;
if (newBufsize && newBufsize != UINT_MAX)
bufsize = newBufsize;
}
return Number::New(Env(), oldBufsize);
}
void LZMAStream::Code(const CallbackInfo& info) {
MemScope mem_scope(this);
std::lock_guard<std::mutex> lock(mutex);
std::vector<uint8_t> inputData;
if (info[0].IsUndefined() || info[0].IsNull()) {
shouldFinish = true;
} else {
if (!readBufferFromObj(info[0], &inputData))
return;
if (inputData.empty())
shouldFinish = true;
}
inbufs.push(std::move(inputData));
bool async = info[1].ToBoolean();
if (async) {
(new LZMAStreamCodingWorker(this))->Queue();
} else {
doLZMACode();
invokeBufferHandlers(true);
}
}
template <typename T>
struct Maybe {
};
void LZMAStream::invokeBufferHandlers(bool hasLock) {
Napi::Env env = Env();
HandleScope scope(env);
MemScope mem_scope(this);
std::unique_lock<std::mutex> lock;
if (!hasLock)
lock = std::unique_lock<std::mutex>(mutex);
Function bufferHandler = Napi::Value(Value()["bufferHandler"]).As<Function>();
std::vector<uint8_t> outbuf;
auto CallBufferHandlerWithArgv = [&](size_t argc, const napi_value* argv) {
if (!hasLock) lock.unlock();
bufferHandler.MakeCallback(Value(), 5, argv, async_context);
if (!hasLock) lock.lock();
};
uint64_t in = UINT64_MAX, out = UINT64_MAX;
if (_.internal)
lzma_get_progress(&_, &in, &out);
Napi::Value in_ = Uint64ToNumberMaxNull(env, in);
Napi::Value out_ = Uint64ToNumberMaxNull(env, out);
while (outbufs.size() > 0) {
outbuf = std::move(outbufs.front());
outbufs.pop();
napi_value argv[5] = {
Buffer<char>::Copy(env, reinterpret_cast<const char*>(outbuf.data()), outbuf.size()),
env.Undefined(), env.Undefined(), in_, out_
};
CallBufferHandlerWithArgv(5, argv);
}
bool reset = false;
if (lastCodeResult != LZMA_OK) {
Napi::Value errorArg = env.Null();
if (lastCodeResult != LZMA_STREAM_END)
errorArg = lzmaRetError(env, lastCodeResult).Value();
reset = true;
napi_value argv[5] = { env.Null(), env.Undefined(), errorArg, in_, out_ };
CallBufferHandlerWithArgv(5, argv);
}
if (processedChunks) {
size_t pc = processedChunks;
processedChunks = 0;
napi_value argv[5] = {
env.Undefined(), Number::New(env, static_cast<uint32_t>(pc)),
env.Undefined(), in_, out_
};
CallBufferHandlerWithArgv(5, argv);
}
if (reset)
resetUnderlying(); // resets lastCodeResult!
}
void LZMAStream::doLZMACodeFromAsync() {
std::lock_guard<std::mutex> lock(mutex);
doLZMACode();
}
void LZMAStream::doLZMACode() {
std::vector<uint8_t> outbuf(bufsize), inbuf;
_.next_out = outbuf.data();
_.avail_out = outbuf.size();
_.avail_in = 0;
lzma_action action = LZMA_RUN;
size_t readChunks = 0;
// _.internal is set to nullptr when lzma_end() is called via resetUnderlying()
while (_.internal) {
if (_.avail_in == 0) { // more input neccessary?
while (_.avail_in == 0 && !inbufs.empty()) {
inbuf = std::move(inbufs.front());
inbufs.pop();
readChunks++;
_.next_in = inbuf.data();
_.avail_in = inbuf.size();
}
}
if (shouldFinish && inbufs.empty())
action = LZMA_FINISH;
_.next_out = outbuf.data();
_.avail_out = outbuf.size();
lastCodeResult = lzma_code(&_, action);
if (lastCodeResult != LZMA_OK && lastCodeResult != LZMA_STREAM_END) {
processedChunks += readChunks;
readChunks = 0;
break;
}
if (_.avail_out == 0 || _.avail_in == 0 || lastCodeResult == LZMA_STREAM_END) {
size_t outsz = outbuf.size() - _.avail_out;
if (outsz > 0) {
#ifndef LZMA_NO_CXX11_RVALUE_REFERENCES // C++11
outbufs.emplace(outbuf.data(), outbuf.data() + outsz);
#else
outbufs.push(std::vector<uint8_t>(outbuf.data(), outbuf.data() + outsz));
#endif
}
if (lastCodeResult == LZMA_STREAM_END) {
processedChunks += readChunks;
readChunks = 0;
break;
}
}
if (_.avail_out == outbuf.size()) { // no progress was made
if (!shouldFinish) {
processedChunks += readChunks;
readChunks = 0;
}
if (!shouldFinish)
break;
}
}
}
void LZMAStream::InitializeExports(Object exports) {
exports["Stream"] = DefineClass(exports.Env(), "LZMAStream", {
InstanceMethod("setBufsize", &LZMAStream::SetBufsize),
InstanceMethod("resetUnderlying", &LZMAStream::ResetUnderlying),
InstanceMethod("code", &LZMAStream::Code),
InstanceMethod("memusage", &LZMAStream::Memusage),
InstanceMethod("memlimitGet", &LZMAStream::MemlimitGet),
InstanceMethod("memlimitSet", &LZMAStream::MemlimitSet),
InstanceMethod("rawEncoder_", &LZMAStream::RawEncoder),
InstanceMethod("rawDecoder_", &LZMAStream::RawDecoder),
InstanceMethod("filtersUpdate", &LZMAStream::FiltersUpdate),
InstanceMethod("easyEncoder_", &LZMAStream::EasyEncoder),
InstanceMethod("streamEncoder_", &LZMAStream::StreamEncoder),
InstanceMethod("aloneEncoder", &LZMAStream::AloneEncoder),
InstanceMethod("mtEncoder_", &LZMAStream::MTEncoder),
InstanceMethod("streamDecoder_", &LZMAStream::StreamDecoder),
InstanceMethod("autoDecoder_", &LZMAStream::AutoDecoder),
InstanceMethod("aloneDecoder_", &LZMAStream::AloneDecoder),
});
}
Value LZMAStream::Memusage(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
return Uint64ToNumber0Null(Env(), lzma_memusage(&_));
}
Value LZMAStream::MemlimitGet(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
return Uint64ToNumber0Null(Env(), lzma_memlimit_get(&_));
}
Value LZMAStream::MemlimitSet(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
if (!info[0].IsNumber())
throw TypeError::New(Env(), "memlimitSet() needs a numerical argument");
Number arg = info[0].As<Number>();
return lzmaRet(Env(), lzma_memlimit_set(&_, NumberToUint64ClampNullMax(arg)));
}
Value LZMAStream::RawEncoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
const FilterArray filters(info[0]);
return lzmaRet(Env(), lzma_raw_encoder(&_, filters.array()));
}
Value LZMAStream::RawDecoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
const FilterArray filters(info[0]);
return lzmaRet(Env(), lzma_raw_decoder(&_, filters.array()));
}
Value LZMAStream::FiltersUpdate(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
const FilterArray filters(info[0]);
return lzmaRet(Env(), lzma_filters_update(&_, filters.array()));
}
Value LZMAStream::EasyEncoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
int64_t preset = info[0].ToNumber().Int64Value();
int64_t check = info[1].ToNumber().Int64Value();
return lzmaRet(Env(), lzma_easy_encoder(&_, preset, (lzma_check) check));
}
Value LZMAStream::StreamEncoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
const FilterArray filters(info[0]);
int64_t check = info[1].ToNumber().Int64Value();
return lzmaRet(Env(), lzma_stream_encoder(&_, filters.array(), (lzma_check) check));
}
Value LZMAStream::MTEncoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
const MTOptions mt(info[0]);
return lzmaRet(Env(), lzma_stream_encoder_mt(&_, mt.opts()));
}
Value LZMAStream::AloneEncoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
lzma_options_lzma o = parseOptionsLZMA(info[0]);
return lzmaRet(Env(), lzma_alone_encoder(&_, &o));
}
Value LZMAStream::StreamDecoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
uint64_t memlimit = NumberToUint64ClampNullMax(info[0]);
int64_t flags = info[1].ToNumber().Int64Value();
return lzmaRet(Env(), lzma_stream_decoder(&_, memlimit, flags));
}
Value LZMAStream::AutoDecoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
uint64_t memlimit = NumberToUint64ClampNullMax(info[0]);
int64_t flags = info[1].ToNumber().Int64Value();
return lzmaRet(Env(), lzma_auto_decoder(&_, memlimit, flags));
}
Value LZMAStream::AloneDecoder(const CallbackInfo& info) {
std::lock_guard<std::mutex> lock(mutex);
uint64_t memlimit = NumberToUint64ClampNullMax(info[0]);
return lzmaRet(Env(), lzma_alone_decoder(&_, memlimit));
}
}
| 26.472422 | 91 | 0.686656 | [
"object",
"vector"
] |
e7f3cbae7bfb15c0353f0975ed5d30aaf36aeaaa | 5,790 | cpp | C++ | src/ui/TiledFloor.cpp | equilibr/turtle | 3aeee2cd5a16ce861a1b492e3948a87e7e2e315a | [
"MIT"
] | null | null | null | src/ui/TiledFloor.cpp | equilibr/turtle | 3aeee2cd5a16ce861a1b492e3948a87e7e2e315a | [
"MIT"
] | null | null | null | src/ui/TiledFloor.cpp | equilibr/turtle | 3aeee2cd5a16ce861a1b492e3948a87e7e2e315a | [
"MIT"
] | null | null | null | #include "TiledFloor.h"
#include <osg/Geometry>
using namespace Turtle;
TiledFloor::TiledFloor(
const Index2D & size,
const QColor & clearColor,
const Position2D & tileSize)
{
m_texture = new osg::Texture2D;
//Create default members to avoid dereferencing null pointers
m_textureImage = new osg::Image;
m_floor = new osg::Geode;
m_root = new osg::Group;
setClearColor(clearColor);
reset(size, tileSize);
}
void TiledFloor::setImage(const QImage & image)
{
m_image = image.convertToFormat(QImage::Format_ARGB32, Qt::ColorOnly);
//Copy image data to texture
for (int s = 0; s < m_image.width(); ++s)
for (int t = 0; t < m_image.height(); ++t)
{
QColor color = m_image.pixelColor(s,t);
m_textureImage->setColor(
fromQColor(color),
static_cast<unsigned>(s),
static_cast<unsigned>(m_textureImage->t() - 1 - t));
}
}
void TiledFloor::reset(const Index2D & size, const Position2D & tileSize)
{
m_tileSize = tileSize;
m_halfIndexSize = size;
m_halfPositionSize = tileSize * size + tileSize / 2;
m_Base = -size;
const TilePosition2D dimentions = size * 2 + 1;
//Create the image
m_image = QImage(dimentions.x(), dimentions.y(), QImage::Format_ARGB32);
//Create the texture image
m_textureImage->allocateImage(dimentions.x(),dimentions.y(),1, GL_RGB, GL_UNSIGNED_BYTE);
m_texture->setImage(m_textureImage);
clear();
//Remove the old floor
m_root->removeChild(m_floor);
createQuad();
//Add the new floor
m_root->addChild(m_floor);
}
void TiledFloor::clear()
{
m_image.fill(m_clearColor);
OsgColor color = fromQColor(m_clearColor);
for (int s = 0; s < m_textureImage->s(); ++s)
for (int t = 0; t < m_textureImage->t(); ++t)
m_textureImage->setColor(color, static_cast<unsigned int>(s), static_cast<unsigned int>(t));
m_textureImage->dirty();
}
TilePosition2D TiledFloor::clamp(const TilePosition2D & position, const TilePosition2D & margin)
{
return position.max(-m_halfIndexSize + margin).min(m_halfIndexSize - margin);
}
TileSensor TiledFloor::getTiles(const TilePosition2D position, size_t size) const
{
//Adjust the position to be inside our bounds
const TilePosition2D::value_type margin = static_cast<TilePosition2D::value_type>(size);
TilePosition2D target = position.min(m_halfIndexSize - margin).max(-m_halfIndexSize + margin);
auto pixel = [this, target] (int x, int y)
{
const Index2D index = toIndex(target + TilePosition2D{x,y});
//Note that the Y axis is inverted
return m_image.pixelColor(
static_cast<int>(index.x()),
m_image.height() -1 - (static_cast<int>(index.y())));
};
TileSensor::Data data;
//Stride 1 is along the X axis
for (int y = -margin; y <= margin; ++y)
for (int x = -margin; x <= margin; ++x)
data.push_back(pixel(x,y));
return TileSensor(data, margin);
}
TilePosition2D TiledFloor::toTileIndex(const Position2D & position) const
{
using T = Position2D::value_type;
auto toTile = [](T coord, T size) -> TilePosition2D::value_type
{
if (fabs(coord) < size/2)
return 0;
T shifted = std::floor(fabs(coord) + size / 2);
T unwrapped = shifted * (coord / fabs(coord));
return static_cast<TilePosition2D::value_type>(unwrapped);
};
return TilePosition2D
{
toTile(position.x(), m_tileSize.x()),
toTile(position.y(), m_tileSize.y())
};
}
Position2D TiledFloor::toPosition(const TilePosition2D & index) const
{
return m_tileSize * index.min(m_halfIndexSize).max(-m_halfIndexSize);
}
Index2D TiledFloor::toIndex(const Position2D & position) const
{
return toIndex(toTileIndex(position));
}
Index2D TiledFloor::toIndex(const TilePosition2D & position) const
{
//Make sure the position is not out of bounds
TilePosition2D bounded = position.min(m_halfIndexSize).max(-m_halfIndexSize);
return bounded - m_Base;
}
void TiledFloor::setColor(const Index2D & position, const QColor & color)
{
//Note that the Y axis is inverted
m_image.setPixelColor(
static_cast<int>(position.x()),
m_image.height() -1 - static_cast<int>(position.y()),
color);
m_textureImage->setColor(
fromQColor(color),
static_cast<unsigned int>(position.x()),
static_cast<unsigned>(position.y()));
m_textureImage->dirty();
}
QColor TiledFloor::getColor(const Index2D & position) const
{
return m_image.pixelColor(
static_cast<int>(position.x()),
m_image.height() -1 - static_cast<int>(position.y()));
}
void TiledFloor::createQuad()
{
auto toVec3 = [](Position2D pos) -> osg::Vec3
{
return osg::Vec3
{
static_cast<osg::Vec3::value_type>(pos.x()),
static_cast<osg::Vec3::value_type>(pos.y()),
0
};
};
Position2D a;
a = a * Position2D{1,-1};
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
vertices->push_back( toVec3(m_halfPositionSize * Position2D{-1,-1}) );
vertices->push_back( toVec3(m_halfPositionSize * Position2D{1,-1}) );
vertices->push_back( toVec3(m_halfPositionSize * Position2D{1,1}) );
vertices->push_back( toVec3(m_halfPositionSize * Position2D{-1,1}) );
osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array;
normals->push_back( osg::Vec3(0.0f,0.0f, 1.0f) );
osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array;
texcoords->push_back( osg::Vec2(0.0f, 0.0f) );
texcoords->push_back( osg::Vec2(1.0f, 0.0f) );
texcoords->push_back( osg::Vec2(1.0f, 1.0f) );
texcoords->push_back( osg::Vec2(0.0f, 1.0f) );
osg::ref_ptr<osg::Geometry> quad = new osg::Geometry;
quad->setVertexArray( vertices );
quad->setNormalArray( normals );
quad->setNormalBinding( osg::Geometry::BIND_OVERALL );
quad->setTexCoordArray( 0, texcoords );
quad->addPrimitiveSet( new osg::DrawArrays(osg::DrawArrays::QUADS, 0, 4) );
m_floor = new osg::Geode;
m_floor->addDrawable( quad );
m_floor->getOrCreateStateSet()->setTextureAttributeAndModes(0, m_texture );
}
| 27.183099 | 96 | 0.706908 | [
"geometry"
] |
e7fdbf1e83fb264b614221798a258afd9308cc8b | 6,395 | cpp | C++ | server.cpp | arao2023/liars-dice | 5a83cc55460f8c872fe4f1dd17978a25f125f63d | [
"BSD-3-Clause"
] | null | null | null | server.cpp | arao2023/liars-dice | 5a83cc55460f8c872fe4f1dd17978a25f125f63d | [
"BSD-3-Clause"
] | null | null | null | server.cpp | arao2023/liars-dice | 5a83cc55460f8c872fe4f1dd17978a25f125f63d | [
"BSD-3-Clause"
] | null | null | null | #include <atomic>
#include <cstddef>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include "debug.hpp"
namespace beast = boost::beast;
namespace asio = boost::asio;
class Server {
private:
struct PlayerStream {
beast::websocket::stream<beast::ssl_stream<
beast::tcp_stream>> socket;
beast::flat_buffer message {};
};
asio::io_context ioContext {};
asio::ip::tcp::acceptor tcpAcceptor {ioContext};
asio::ip::tcp::endpoint tcpEndpoint {asio::ip::tcp::v4(), 443};
asio::ssl::context sslContext {asio::ssl::context::tlsv12};
std::atomic<bool> accepting {false};
std::vector<PlayerStream> playerStreams;
public:
Server(const bool shouldStartAccepting = true) {
sslContext.set_options(
asio::ssl::context::default_workarounds
| asio::ssl::context::no_sslv2
| asio::ssl::context::single_dh_use);
sslContext.use_certificate_chain_file("assets/pem/cert.pem");
sslContext.use_rsa_private_key_file(
"assets/pem/key.pem",
asio::ssl::context::pem);
sslContext.use_tmp_dh_file("assets/pem/dh.pem");
tcpAcceptor.open(tcpEndpoint.protocol());
tcpAcceptor.set_option(asio::socket_base::reuse_address(true));
tcpAcceptor.bind(tcpEndpoint);
tcpAcceptor.listen();
}
static void playerStreamOnHandshake(
PlayerStream& playerStream,
const boost::system::error_code& error) {
Debug::log("handshake error, if any: %s\n", error.category().message(error.value()).c_str());
playerStream.socket.set_option(
beast::websocket::stream_base::decorator(
[](beast::websocket::response_type& response) {
response.set(
beast::http::field::server,
"Liar's Dice Server");
}));
playerStream.socket.async_accept(std::bind(
&Server::playerStreamOnAccept,
std::ref(playerStream),
std::placeholders::_1));
}
static void playerStreamOnAccept(
PlayerStream& playerStream,
const boost::system::error_code& error) {
Debug::log("socket accept error, if any: %s\n", error.category().message(error.value()).c_str());
{
playerStream.socket.async_read(
playerStream.message,
std::bind(
&Server::playerStreamOnRead,
std::ref(playerStream),
std::placeholders::_1,
std::placeholders::_2));
}
}
static void playerStreamOnRead(
PlayerStream& playerStream,
const boost::system::error_code& error,
std::size_t transferSize) {
Debug::log("socket read error, if any: %s\n", error.category().message(error.value()).c_str());
Debug::log("got %d bytes, are text: %d\n", transferSize, playerStream.socket.got_text());
reinterpret_cast<char*>(
playerStream.message.data().data())[
transferSize - 1] = '\0';
Debug::log(
"received message: %s\n",
playerStream.message.cdata().data());
{
std::string message {"hello, world!"};
playerStream.socket.text(true);
playerStream.socket.async_write(
asio::dynamic_buffer(message).data(),
std::bind(
&Server::playerStreamOnWrite,
std::ref(playerStream),
std::placeholders::_1,
std::placeholders::_2));
}
}
static void playerStreamOnWrite(
PlayerStream& playerStream,
const boost::system::error_code& error,
std::size_t transferSize) {
playerStream.message.clear();
Debug::log("socket write error, if any: %s\n", error.category().message(error.value()).c_str());
}
void serverOnAccept(
const boost::system::error_code& error,
asio::ip::tcp::socket socket) {
Debug::log(
"%s%s%s%s",
"accepting connection",
(error ? " with error message " : ""),
(error ? error.category().message(
error.value()).c_str() : ""),
"\n");
playerStreams.push_back({.socket{std::move(socket), sslContext}});
playerStreams.back().socket.next_layer().async_handshake(
asio::ssl::stream_base::server,
std::bind(
&Server::playerStreamOnHandshake,
std::ref(playerStreams.back()),
std::placeholders::_1));
Debug::log("%s", "finished accepting connection\n");
if (accepting) {
Debug::log("%s", "queueing accept\n");
tcpAcceptor.async_accept(ioContext, std::bind(
&Server::serverOnAccept,
this,
std::placeholders::_1,
std::placeholders::_2));
}
}
void startAccepting() {
ioContext.stop();
accepting = true;
Debug::log("%s", "queueing accept\n");
tcpAcceptor.async_accept(ioContext, std::bind(
&Server::serverOnAccept,
this,
std::placeholders::_1,
std::placeholders::_2));
ioContext.restart();
ioContext.run();
}
void stopAccepting() {
accepting = false;
}
};
int main(int argc, char* argv[]) {
Server server {};
server.startAccepting();
return 0;
}
| 39.475309 | 109 | 0.495543 | [
"vector"
] |
f003ab1f08fe8b9a53cb9c5a504e43007f164288 | 851 | cpp | C++ | _includes/leet215/leet215_2.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | _includes/leet215/leet215_2.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | 8 | 2019-12-19T04:46:05.000Z | 2022-02-26T03:45:22.000Z | _includes/leet215/leet215_2.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | class Solution {
public:
int partition(vector<int>& nums, int l, int r) {
int mid = (r - l)/2 + l;
swap(nums[mid], nums[r]);
int pivot = nums[r];
int i = l;
for (int k = l; k < r; k++) {
if (nums[k] > pivot) {
swap(nums[k], nums[i++]);
}
}
swap(nums[i], nums[r]);
return i;
}
int findKthLargest(vector<int>& nums, int k) {
if (!nums.size()) return -1;
k--;
int i = 0, j = nums.size() - 1;
while (i < j) {
int idx = partition(nums, i, j);
if (idx == k)
return nums[idx];
else if (idx < k) {
i = idx + 1;
}
else {
j = idx;
}
}
return nums[i];
}
}; | 24.314286 | 52 | 0.354877 | [
"vector"
] |
f00402445cf9fb03b8f03ab470960926336dc22d | 326 | hpp | C++ | CtCI-6th-Edition-cpp/01_Arrays_And_Strings/08_Zero_Matrix/zeroMatrix.hpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/01_Arrays_And_Strings/08_Zero_Matrix/zeroMatrix.hpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/01_Arrays_And_Strings/08_Zero_Matrix/zeroMatrix.hpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | #ifndef CTCI_6TH_EDITION_CPP_01_ARRAYS_AND_STRINGS_08_ZERO_MATRIX_ZEROMATRIX_HPP_
#define CTCI_6TH_EDITION_CPP_01_ARRAYS_AND_STRINGS_08_ZERO_MATRIX_ZEROMATRIX_HPP_
#include <vector>
void zeroMatrix(std::vector<std::vector<int>>& matrix);
#endif // CTCI_6TH_EDITION_CPP_01_ARRAYS_AND_STRINGS_08_ZERO_MATRIX_ZEROMATRIX_HPP_
| 36.222222 | 84 | 0.889571 | [
"vector"
] |
f005dd430450e403ee0d6778f90a200011eacca7 | 3,054 | hpp | C++ | include/fdeep/layers/prelu_layer.hpp | mhs-achyut/frugally-deep | 49e1843c5e2583b6d2619547c3e1f039c3c75f19 | [
"MIT"
] | 1 | 2021-01-25T04:29:25.000Z | 2021-01-25T04:29:25.000Z | include/fdeep/layers/prelu_layer.hpp | mhs-achyut/frugally-deep | 49e1843c5e2583b6d2619547c3e1f039c3c75f19 | [
"MIT"
] | 1 | 2021-07-26T22:09:49.000Z | 2021-07-26T22:09:49.000Z | include/fdeep/layers/prelu_layer.hpp | mhs-achyut/frugally-deep | 49e1843c5e2583b6d2619547c3e1f039c3c75f19 | [
"MIT"
] | 2 | 2021-07-26T14:46:51.000Z | 2021-11-09T11:32:09.000Z | // Copyright 2016, Tobias Hermann.
// https://github.com/Dobiasd/frugally-deep
// Distributed under the MIT License.
// (See accompanying LICENSE file or at
// https://opensource.org/licenses/MIT)
#pragma once
#include "fdeep/layers/layer.hpp"
#include <string>
namespace fdeep { namespace internal
{
class prelu_layer : public layer
{
public:
explicit prelu_layer(const std::string& name, const float_vec& alpha,
std::vector<std::size_t> shared_axes)
: layer(name),
alpha_(fplus::make_shared_ref<float_vec>(alpha)),
shared_axes_(shared_axes)
{
}
protected:
fdeep::shared_float_vec alpha_;
std::vector<std::size_t> shared_axes_;
tensor5s apply_impl(const tensor5s& input) const override
{
// We need to shift shared_axes if the original Keras tensor
// was one or two dimensional.
// We detect this by checking if the axes indicated in shared_axes
// has length 1.
// For this to work we need to remove axes with length 1
// from shared axes in Python.
std::vector<std::size_t> shared_axes_shifted;
std::size_t shift = 0;
for (std::size_t i = 0; i < shared_axes_.size(); ++i)
{
if ((shared_axes_[i] == 1 && input[0].shape().height_ == 1) ||
(shared_axes_[i] == 2 && input[0].shape().width_ == 1))
{
shift++;
}
shared_axes_shifted.push_back(shared_axes_[i] + shift);
}
const bool height_shared = fplus::is_elem_of(1, shared_axes_shifted);
const bool width_shared = fplus::is_elem_of(2, shared_axes_shifted);
const bool channels_shared = fplus::is_elem_of(3, shared_axes_shifted);
const size_t width = width_shared ? 1 : input[0].shape().width_;
const size_t depth = channels_shared ? 1 : input[0].shape().depth_;
fdeep::tensor5 out(input[0].shape(), 1.0f);
for (std::size_t y = 0; y < out.shape().height_; ++y)
{
for (std::size_t x = 0; x < out.shape().width_; ++x)
{
for (std::size_t z = 0; z < out.shape().depth_; ++z)
{
if (input[0].get(0, 0, y, x, z) > 0)
{
out.set(0, 0, y, x, z, input[0].get(0, 0, y, x, z));
}
else
{
const size_t y_temp = height_shared ? 0 : y;
const size_t x_temp = width_shared ? 0 : x;
const size_t z_temp = channels_shared ? 0 : z;
const size_t pos =
y_temp * width * depth +
x_temp * depth +
z_temp;
out.set(0, 0, y, x, z, (*alpha_)[pos] *
input[0].get(0, 0, y, x, z));
}
}
}
}
return { out };
}
};
} } // namespace fdeep, namespace internal | 35.929412 | 79 | 0.518009 | [
"shape",
"vector"
] |
f01073e63d75c445b4b31e4f7919db1277425c4e | 3,686 | cpp | C++ | src/ge/renderer/opengl/shader.cpp | hogletgames/game-engine | 1356d8b9f364dfe13d5b9db4f4aedd7a3fd360fc | [
"BSD-3-Clause"
] | null | null | null | src/ge/renderer/opengl/shader.cpp | hogletgames/game-engine | 1356d8b9f364dfe13d5b9db4f4aedd7a3fd360fc | [
"BSD-3-Clause"
] | 1 | 2020-05-31T21:17:41.000Z | 2020-05-31T21:17:41.000Z | src/ge/renderer/opengl/shader.cpp | hogletgames/game-engine | 1356d8b9f364dfe13d5b9db4f4aedd7a3fd360fc | [
"BSD-3-Clause"
] | null | null | null | /*
* BSD 3-Clause License
*
* Copyright (c) 2020, Dmitry Shilnenkov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "shader.h"
#include "opengl_utils.h"
#include "ge/core/asserts.h"
#include "ge/core/log.h"
#include "ge/debug/profile.h"
#include <glad/glad.h>
#include <fstream>
namespace {
GLenum toGlType(::GE::Shader::Type type)
{
switch (type) {
case GE_VERTEX_SHADER: return GL_VERTEX_SHADER;
case GE_FRAGMENT_SHADER: return GL_FRAGMENT_SHADER;
default: break;
}
GE_CORE_ASSERT_MSG(false, "Unknown shader type: {}", static_cast<int>(type));
return 0;
}
std::string loadShader(const std::string& filepath)
{
GE_PROFILE_FUNC();
std::ifstream fin(filepath, std::ios_base::binary);
if (!fin.is_open()) {
GE_CORE_ERR("Failed to open shader: '{}'\n", filepath);
return {};
}
fin >> std::noskipws;
return std::string{std::istreambuf_iterator<char>(fin),
std::istreambuf_iterator<char>()};
}
} // namespace
namespace GE::OpenGL {
Shader::Shader(Type type)
: m_type{toGlType(type)}
{
GE_PROFILE_FUNC();
GLCall(m_id = glCreateShader(m_type));
}
Shader::~Shader()
{
GE_PROFILE_FUNC();
GLCall(glDeleteShader(m_id));
}
bool Shader::compileFromFile(const std::string& filepath)
{
GE_PROFILE_FUNC();
std::string source_code = loadShader(filepath);
return !source_code.empty() ? compileFromSource(source_code) : false;
}
bool Shader::compileFromSource(const std::string& source_code)
{
GE_PROFILE_FUNC();
const GLchar* source = source_code.c_str();
GLint status{GL_FALSE};
GLCall(glShaderSource(m_id, 1, &source, nullptr));
GLCall(glCompileShader(m_id));
GLCall(glGetShaderiv(m_id, GL_COMPILE_STATUS, &status));
#ifndef GE_DEBUG
if (status == GL_FALSE) {
GLint msg_len{};
GLCall(glGetShaderiv(m_id, GL_INFO_LOG_LENGTH, &msg_len));
std::vector<GLchar> msg(msg_len);
GLCall(glGetShaderInfoLog(m_id, msg_len, nullptr, msg.data()));
GE_CORE_ERR("Failed to compile shader: {}", msg.data());
}
#endif // GE_DEBUG
return status != GL_FALSE;
}
} // namespace GE::OpenGL
| 29.023622 | 81 | 0.705372 | [
"vector"
] |
f010827cd150a6480c7d89e2f26a829baebcb43f | 382 | cc | C++ | Problem_10/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | Problem_10/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | Problem_10/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | #include "common.hh"
int main()
{
const long N = 50;
std::vector<long> primes;
for (long i = 2; i < N; i++)
{
bool isPrime = true;
for (auto prime : primes)
{
if (i%prime==0) {isPrime = false; break;}
}
if (isPrime) primes.push_back(i);
}
long sum = 0;
for (auto prime : primes) sum += prime;
std::cout << sum << std::endl;
}
| 15.916667 | 47 | 0.52356 | [
"vector"
] |
f013f2451b8d3f3f74226dc946c56b180721800a | 5,811 | cpp | C++ | src/raymath/test/intersection_tests.cpp | Michionlion/rayterm-cpu | 29820aac88b64cdc44117f23cfcb46cd74b6f7ad | [
"MIT"
] | 1 | 2019-05-14T05:33:53.000Z | 2019-05-14T05:33:53.000Z | src/raymath/test/intersection_tests.cpp | Michionlion/rayterm-cpu | 29820aac88b64cdc44117f23cfcb46cd74b6f7ad | [
"MIT"
] | null | null | null | src/raymath/test/intersection_tests.cpp | Michionlion/rayterm-cpu | 29820aac88b64cdc44117f23cfcb46cd74b6f7ad | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "intersection.h"
#include "sphere.h"
TEST(Intersection, BoolEvaluation) {
intersection hit;
hit.hit = true;
if (hit) {
SUCCEED();
} else {
ADD_FAILURE() << "intersection did not evaluate to true when hit was true";
}
hit.hit = false;
if (hit) {
ADD_FAILURE() << "intersection did not evaluate to false when hit was false";
} else {
SUCCEED();
}
hit.hit = false;
if (!hit) {
SUCCEED();
} else {
ADD_FAILURE() << "!intersection did not evaluate to true when hit was false";
}
hit.hit = true;
if (!hit) {
ADD_FAILURE() << "!intersection did not evaluate to false when hit was true";
} else {
SUCCEED();
}
}
TEST(Intersection, SphereRayIntersectionBehind) {
intersection hit;
hit = sphere(vector(0, 0, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, 0, -1)));
EXPECT_FALSE(hit);
hit = sphere(vector(0, 3, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, -1, -0.5)));
EXPECT_FALSE(hit);
}
TEST(Intersection, SphereRayIntersectionPosition) {
intersection hit;
vector expected;
hit = sphere(vector(0, 0, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, 0, 1)));
expected = vector(0, 0, -2);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.position.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.position[0] << ", " << hit.position[1] << ", " << hit.position[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
hit = sphere(vector(0, 3, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, 1, 0.5)));
expected = vector(0, 2.27335, -1.863325);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.position.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.position[0] << ", " << hit.position[1] << ", " << hit.position[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
}
TEST(Intersection, SphereRayIntersectionNormal) {
intersection hit;
vector expected;
hit = sphere(vector(0, 0, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, 0, 1)));
expected = vector(0, 0, -1);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.normal.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
hit = sphere(vector(0, 3, 0), 2).intersects(ray(vector(0, 0, -3), vector(0, 1, 0.5)));
expected = vector(0, -0.363325, -0.931662);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.normal.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
}
TEST(Intersection, SphereRayIntersectionInternal) {
intersection hit;
hit = sphere(vector(0, 0, 0), 2).intersects(ray(vector(0, 0, 1), vector(0, 0, 1)));
vector expected_normal = vector(0, 0, 1);
vector expected_position = vector(0, 0, 2);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.position.isApprox(expected_position, 0.0001))
<< " Actual: "
<< "{" << hit.position[0] << ", " << hit.position[1] << ", " << hit.position[2] << "}"
<< "\nExpected: "
<< "{" << expected_position[0] << ", " << expected_position[1] << ", "
<< expected_position[2] << "}";
EXPECT_TRUE(hit.normal.isApprox(expected_normal, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected_normal[0] << ", " << expected_normal[1] << ", " << expected_normal[2]
<< "}";
hit = sphere(vector(0, 3, 0), 2).intersects(ray(vector(0, 3, 1), vector(0, 1, 1.5)));
expected_normal = vector(0, 0.302169, 0.953254);
expected_position = vector(0, 3.604339, 1.906508);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.position.isApprox(expected_position, 0.0001))
<< " Actual: "
<< "{" << hit.position[0] << ", " << hit.position[1] << ", " << hit.position[2] << "}"
<< "\nExpected: "
<< "{" << expected_position[0] << ", " << expected_position[1] << ", "
<< expected_position[2] << "}";
EXPECT_TRUE(hit.normal.isApprox(expected_normal, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected_normal[0] << ", " << expected_normal[1] << ", " << expected_normal[2]
<< "}";
}
TEST(Intersection, SphereRayIntersectionNormalNegativeRadius) {
intersection hit;
vector expected;
hit = sphere(vector(0, 0, 0), -2).intersects(ray(vector(0, 0, -3), vector(0, 0, 1)));
expected = vector(0, 0, 1);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.normal.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
hit = sphere(vector(0, 3, 0), -2).intersects(ray(vector(0, 0, -3), vector(0, 1, 0.5)));
expected = vector(0, 0.363325, 0.931662);
EXPECT_TRUE(hit);
EXPECT_TRUE(hit.normal.isApprox(expected, 0.0001))
<< " Actual: "
<< "{" << hit.normal[0] << ", " << hit.normal[1] << ", " << hit.normal[2] << "}"
<< "\nExpected: "
<< "{" << expected[0] << ", " << expected[1] << ", " << expected[2] << "}";
}
| 38.230263 | 96 | 0.515402 | [
"vector"
] |
f0261539a3cc440c3eea2446337fd75b189d5e8c | 36,789 | cpp | C++ | src/mexopencv_videostab.cpp | rokm/mexopencv | 22d459cd28df8a5e77fd7f2c8572b16723f60a1d | [
"BSD-3-Clause"
] | 1 | 2021-05-12T21:33:44.000Z | 2021-05-12T21:33:44.000Z | src/mexopencv_videostab.cpp | rokm/mexopencv | 22d459cd28df8a5e77fd7f2c8572b16723f60a1d | [
"BSD-3-Clause"
] | null | null | null | src/mexopencv_videostab.cpp | rokm/mexopencv | 22d459cd28df8a5e77fd7f2c8572b16723f60a1d | [
"BSD-3-Clause"
] | 1 | 2016-05-22T10:15:08.000Z | 2016-05-22T10:15:08.000Z | /** Implementation of mexopencv_videostab.
* @file mexopencv_videostab.cpp
* @ingroup videostab
* @author Amro
* @date 2016
*/
#include "mexopencv_videostab.hpp"
#include <typeinfo>
#include <cstdio>
#include <cstdarg>
using std::vector;
using std::string;
using std::const_mem_fun_ref_t;
using namespace cv;
using namespace cv::videostab;
// ==================== XXX ====================
/// inpainting algorithm types for option processing
const ConstMap<string,int> InpaintingAlgMap = ConstMap<string,int>
("NS", cv::INPAINT_NS)
("Telea", cv::INPAINT_TELEA);
// HACK: mexPrintf doesn't correctly handle "%s" formatted messages when
// directly passing variadic to it. So we use vsnprintf first with a buffer,
// then pass the buffer to mexPrintf.
void LogToMATLAB::print(const char *format, ...)
{
// buffer
const int BUFSIZE = 255;
char buffer[BUFSIZE+1];
// print formatted message to buffer
va_list args;
va_start(args, format);
vsnprintf(buffer, BUFSIZE, format, args);
va_end(args);
// print buffered message in MATLAB
buffer[BUFSIZE] = '\0';
mexPrintf(buffer);
//TODO: flush
}
RansacParams toRansacParams(const MxArray &arr)
{
return RansacParams(
arr.at("Size").toInt(),
arr.at("Thresh").toFloat(),
arr.at("Eps").toFloat(),
arr.at("Prob").toFloat());
}
MxArray toStruct(const RansacParams ¶ms)
{
MxArray s(MxArray::Struct());
s.set("Size", params.size);
s.set("Thresh", params.thresh);
s.set("Eps", params.eps);
s.set("Prob", params.prob);
return s;
}
// ==================== XXX ====================
MxArray toStruct(Ptr<ILog> p)
{
MxArray s(MxArray::Struct());
if (!p.empty())
s.set("TypeId", string(typeid(*p).name()));
return s;
}
MxArray toStruct(Ptr<IFrameSource> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
Ptr<VideoFileSource> pp = p.dynamicCast<VideoFileSource>();
if (!pp.empty()) {
s.set("Width", pp->width());
s.set("Height", pp->height());
s.set("FPS", pp->fps());
s.set("Count", pp->count());
}
}
return s;
}
MxArray toStruct(Ptr<DeblurerBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("Radius", p->radius());
// Frames, Motions, BlurrinessRates: data from stabilizer
Ptr<WeightingDeblurer> pp = p.dynamicCast<WeightingDeblurer>();
if (!pp.empty()) {
s.set("Sensitivity", pp->sensitivity());
}
}
return s;
}
MxArray toStruct(Ptr<MotionEstimatorBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("MotionModel", MotionModelInvMap[p->motionModel()]);
{
Ptr<MotionEstimatorRansacL2> pp = p.dynamicCast<MotionEstimatorRansacL2>();
if (!pp.empty()) {
s.set("RansacParams", toStruct(pp->ransacParams()));
s.set("MinInlierRatio", pp->minInlierRatio());
}
}
}
return s;
}
MxArray toStruct(Ptr<FeatureDetector> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
//TODO: check each derived FeatureDetector, and return its props
}
return s;
}
MxArray toStruct(Ptr<ISparseOptFlowEstimator> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
Ptr<SparsePyrLkOptFlowEstimator> pp = p.dynamicCast<SparsePyrLkOptFlowEstimator>();
if (!pp.empty()) {
s.set("WinSize", pp->winSize());
s.set("MaxLevel", pp->maxLevel());
}
}
return s;
}
MxArray toStruct(Ptr<IDenseOptFlowEstimator> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
//TODO: no CPU version, only CUDA
/*
Ptr<DensePyrLkOptFlowEstimatorGpu> pp = p.dynamicCast<DensePyrLkOptFlowEstimatorGpu>();
if (!pp.empty()) {
s.set("WinSize", pp->winSize());
s.set("MaxLevel", pp->maxLevel());
}
*/
}
return s;
}
MxArray toStruct(Ptr<IOutlierRejector> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
Ptr<TranslationBasedLocalOutlierRejector> pp = p.dynamicCast<TranslationBasedLocalOutlierRejector>();
if (!pp.empty()) {
s.set("CellSize", pp->cellSize());
s.set("RansacParams", toStruct(pp->ransacParams()));
}
}
return s;
}
MxArray toStruct(Ptr<ImageMotionEstimatorBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("MotionModel", MotionModelInvMap[p->motionModel()]);
Ptr<KeypointBasedMotionEstimator> pp = p.dynamicCast<KeypointBasedMotionEstimator>();
if (!pp.empty()) {
s.set("Detector", toStruct(pp->detector())); // Ptr<FeatureDetector>
s.set("OpticalFlowEstimator", toStruct(pp->opticalFlowEstimator())); // Ptr<ISparseOptFlowEstimator>
s.set("OutlierRejector", toStruct(pp->outlierRejector())); // Ptr<IOutlierRejector>
}
}
return s;
}
MxArray toStruct(Ptr<InpainterBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("MotionModel", MotionModelInvMap[p->motionModel()]);
s.set("Radius", p->radius());
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
{
Ptr<ConsistentMosaicInpainter> pp = p.dynamicCast<ConsistentMosaicInpainter>();
if (!pp.empty())
s.set("StdevThresh", pp->stdevThresh());
}
{
Ptr<MotionInpainter> pp = p.dynamicCast<MotionInpainter>();
if (!pp.empty()) {
s.set("FlowErrorThreshold", pp->flowErrorThreshold());
s.set("DistThresh", pp->distThresh());
s.set("BorderMode", BorderTypeInv[pp->borderMode()]);
s.set("OptFlowEstimator", toStruct(pp->optFlowEstimator())); // Ptr<IDenseOptFlowEstimator>
}
}
{
Ptr<InpaintingPipeline> pp = p.dynamicCast<InpaintingPipeline>();
if (!pp.empty())
s.set("Empty", pp->empty());
}
}
return s;
}
MxArray toStruct(Ptr<MotionFilterBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
Ptr<GaussianMotionFilter> pp = p.dynamicCast<GaussianMotionFilter>();
if (!pp.empty()) {
s.set("Radius", pp->radius());
s.set("Stdev", pp->stdev());
}
}
return s;
}
MxArray toStruct(Ptr<IMotionStabilizer> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
{
Ptr<LpMotionStabilizer> pp = p.dynamicCast<LpMotionStabilizer>();
if (!pp.empty()) {
s.set("MotionModel", MotionModelInvMap[pp->motionModel()]);
s.set("FrameSize", pp->frameSize());
s.set("TrimRatio", pp->trimRatio());
s.set("Weight1", pp->weight1());
s.set("Weight2", pp->weight2());
s.set("Weight3", pp->weight3());
s.set("Weight4", pp->weight4());
}
}
{
Ptr<GaussianMotionFilter> pp = p.dynamicCast<GaussianMotionFilter>();
if (!pp.empty()) {
s.set("Radius", pp->radius());
s.set("Stdev", pp->stdev());
}
}
{
Ptr<MotionStabilizationPipeline> pp = p.dynamicCast<MotionStabilizationPipeline>();
if (!pp.empty())
s.set("Empty", pp->empty());
}
}
return s;
}
MxArray toStruct(Ptr<WobbleSuppressorBase> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("MotionEstimator", toStruct(p->motionEstimator())); // Ptr<ImageMotionEstimatorBase>
// FrameCount, Motions, Motions2, StabilizationMotions: data from stabilizer
Ptr<MoreAccurateMotionWobbleSuppressorBase> pp = p.dynamicCast<MoreAccurateMotionWobbleSuppressorBase>();
if (!pp.empty())
s.set("Period", pp->period());
}
return s;
}
// ==================== XXX ====================
Ptr<ILog> createILog(const string& type)
{
Ptr<ILog> p;
if (type == "LogToMATLAB")
p = makePtr<LogToMATLAB>();
else if (type == "LogToStdout")
p = makePtr<LogToStdout>();
else if (type == "NullLog")
p = makePtr<NullLog>();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized logger type %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ILog");
return p;
}
Ptr<VideoFileSource> createVideoFileSource(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len>=1 && (len%2)==1);
string path(first->toString()); ++first;
bool volatileFrame = false;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "VolatileFrame")
volatileFrame = val.toBool();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return makePtr<VideoFileSource>(path, volatileFrame);
}
Ptr<IFrameSource> createIFrameSource(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
Ptr<IFrameSource> p;
if (type == "VideoFileSource")
p = createVideoFileSource(first, last);
else if (type == "NullFrameSource") {
nargchk(len==0);
p = makePtr<NullFrameSource>();
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized frame source %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create IFrameSource");
return p;
}
Ptr<WeightingDeblurer> createWeightingDeblurer(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<WeightingDeblurer> p = makePtr<WeightingDeblurer>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create WeightingDeblurer");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, BlurrinessRates: data from stabilizer
if (key == "Radius")
p->setRadius(val.toInt());
else if (key == "Sensitivity")
p->setSensitivity(val.toFloat());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<DeblurerBase> createDeblurerBase(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
Ptr<DeblurerBase> p;
if (type == "WeightingDeblurer")
p = createWeightingDeblurer(first, last);
else if (type == "NullDeblurer") {
nargchk(len==3);
p = makePtr<NullDeblurer>();
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized deblurer %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create DeblurerBase");
return p;
}
Ptr<MotionEstimatorL1> createMotionEstimatorL1(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
MotionModel model = cv::videostab::MM_AFFINE;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
model = MotionModelMap[val.toString()];
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return makePtr<MotionEstimatorL1>(model);
}
Ptr<MotionEstimatorRansacL2> createMotionEstimatorRansacL2(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
MotionModel model = cv::videostab::MM_AFFINE;
RansacParams ransacParams = RansacParams::default2dMotion(model);
float minInlierRatio = 0.1f;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
model = MotionModelMap[val.toString()];
else if (key == "RansacParams")
ransacParams = (val.isStruct() ? toRansacParams(val) :
RansacParams::default2dMotion(MotionModelMap[val.toString()]));
else if (key == "MinInlierRatio")
minInlierRatio = val.toFloat();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Ptr<MotionEstimatorRansacL2> p = makePtr<MotionEstimatorRansacL2>(model);
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MotionEstimatorRansacL2");
p->setRansacParams(ransacParams);
p->setMinInlierRatio(minInlierRatio);
return p;
}
Ptr<MotionEstimatorBase> createMotionEstimatorBase(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<MotionEstimatorBase> p;
if (type == "MotionEstimatorL1")
p = createMotionEstimatorL1(first, last);
else if (type == "MotionEstimatorRansacL2")
p = createMotionEstimatorRansacL2(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized motion estimator %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MotionEstimatorBase");
return p;
}
Ptr<SparsePyrLkOptFlowEstimator> createSparsePyrLkOptFlowEstimator(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<SparsePyrLkOptFlowEstimator> p = makePtr<SparsePyrLkOptFlowEstimator>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create SparsePyrLkOptFlowEstimator");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "WinSize")
p->setWinSize(val.toSize());
else if (key == "MaxLevel")
p->setMaxLevel(val.toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<ISparseOptFlowEstimator> createISparseOptFlowEstimator(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<ISparseOptFlowEstimator> p;
if (type == "SparsePyrLkOptFlowEstimator")
p = createSparsePyrLkOptFlowEstimator(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized sparse optical flow estimator %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ISparseOptFlowEstimator");
return p;
}
Ptr<IDenseOptFlowEstimator> createIDenseOptFlowEstimator(
const string& type,
vector<MxArray>::const_iterator /*first*/,
vector<MxArray>::const_iterator /*last*/)
{
Ptr<IDenseOptFlowEstimator> p;
if (type == "DensePyrLkOptFlowEstimatorGpu")
// TODO: no CPU version, only CUDA
; //p = createDensePyrLkOptFlowEstimatorGpu(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized dense optical flow estimator %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create IDenseOptFlowEstimator");
return p;
}
Ptr<TranslationBasedLocalOutlierRejector> createTranslationBasedLocalOutlierRejector(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<TranslationBasedLocalOutlierRejector> p = makePtr<TranslationBasedLocalOutlierRejector>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create TranslationBasedLocalOutlierRejector");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "CellSize")
p->setCellSize(val.toSize());
else if (key == "RansacParams")
p->setRansacParams((val.isStruct()) ? toRansacParams(val) :
RansacParams::default2dMotion(MotionModelMap[val.toString()]));
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<IOutlierRejector> createIOutlierRejector(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
Ptr<IOutlierRejector> p;
if (type == "TranslationBasedLocalOutlierRejector")
p = createTranslationBasedLocalOutlierRejector(first, last);
else if (type == "NullOutlierRejector") {
nargchk(len==0);
p = makePtr<NullOutlierRejector>();
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized outlier rejector %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create IOutlierRejector");
return p;
}
Ptr<KeypointBasedMotionEstimator> createKeypointBasedMotionEstimator(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len>=1 && (len%2)==1);
Ptr<KeypointBasedMotionEstimator> p;
{
vector<MxArray> args(first->toVector<MxArray>()); ++first;
nargchk(args.size() >= 1);
Ptr<MotionEstimatorBase> estimator = createMotionEstimatorBase(
args[0].toString(), args.begin() + 1, args.end());
p = makePtr<KeypointBasedMotionEstimator>(estimator);
}
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create KeypointBasedMotionEstimator");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "Detector") {
vector<MxArray> args(val.toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<FeatureDetector> pp = createFeatureDetector(
args[0].toString(), args.begin() + 1, args.end());
p->setDetector(pp);
}
else if (key == "OpticalFlowEstimator") {
vector<MxArray> args(val.toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<ISparseOptFlowEstimator> pp = createISparseOptFlowEstimator(
args[0].toString(), args.begin() + 1, args.end());
p->setOpticalFlowEstimator(pp);
}
else if (key == "OutlierRejector") {
vector<MxArray> args(val.toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<IOutlierRejector> pp = createIOutlierRejector(
args[0].toString(), args.begin() + 1, args.end());
p->setOutlierRejector(pp);
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<FromFileMotionReader> createFromFileMotionReader(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len>=1 && (len%2)==1);
string path(first->toString()); ++first;
Ptr<FromFileMotionReader> p = makePtr<FromFileMotionReader>(path);
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create FromFileMotionReader");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<ToFileMotionWriter> createToFileMotionWriter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len>=2 && (len%2)==0);
Ptr<ToFileMotionWriter> p;
{
string path(first->toString()); ++first;
vector<MxArray> args(first->toVector<MxArray>()); ++first;
nargchk(args.size() >= 1);
Ptr<ImageMotionEstimatorBase> estimator = createImageMotionEstimator(
args[0].toString(), args.begin() + 1, args.end());
p = makePtr<ToFileMotionWriter>(path, estimator);
}
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ToFileMotionWriter");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<ImageMotionEstimatorBase> createImageMotionEstimator(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<ImageMotionEstimatorBase> p;
if (type == "KeypointBasedMotionEstimator")
p = createKeypointBasedMotionEstimator(first, last);
else if (type == "FromFileMotionReader")
p = createFromFileMotionReader(first, last);
else if (type == "ToFileMotionWriter")
p = createToFileMotionWriter(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized image motion estimator %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ImageMotionEstimatorBase");
return p;
}
Ptr<ColorInpainter> createColorInpainter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
int method = cv::INPAINT_TELEA;
double radius2 = 2.0;
int radius = 0;
MotionModel model = cv::videostab::MM_UNKNOWN;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
if (key == "Method")
method = InpaintingAlgMap[val.toString()];
else if (key == "Radius2")
radius2 = val.toDouble();
else if (key == "MotionModel")
model = MotionModelMap[val.toString()];
else if (key == "Radius")
radius = val.toInt();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Ptr<ColorInpainter> p = makePtr<ColorInpainter>(method, radius2);
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ColorInpainter");
p->setMotionModel(model);
p->setRadius(radius);
return p;
}
Ptr<ColorAverageInpainter> createColorAverageInpainter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<ColorAverageInpainter> p = makePtr<ColorAverageInpainter>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ColorAverageInpainter");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "Radius")
p->setRadius(val.toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<ConsistentMosaicInpainter> createConsistentMosaicInpainter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<ConsistentMosaicInpainter> p = makePtr<ConsistentMosaicInpainter>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create ConsistentMosaicInpainter");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "Radius")
p->setRadius(val.toInt());
else if (key == "StdevThresh")
p->setStdevThresh(val.toFloat());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<MotionInpainter> createMotionInpainter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<MotionInpainter> p = makePtr<MotionInpainter>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MotionInpainter");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "Radius")
p->setRadius(val.toInt());
else if (key == "FlowErrorThreshold")
p->setFlowErrorThreshold(val.toFloat());
else if (key == "DistThreshold")
p->setDistThreshold(val.toFloat());
else if (key == "BorderMode")
p->setBorderMode(BorderType[val.toString()]);
else if (key == "OptFlowEstimator") {
vector<MxArray> args(val.toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<IDenseOptFlowEstimator> pp = createIDenseOptFlowEstimator(
args[0].toString(), args.begin() + 1, args.end());
p->setOptFlowEstimator(pp);
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<InpaintingPipeline> createInpaintingPipeline(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len>=1 && (len%2)==1);
Ptr<InpaintingPipeline> p = makePtr<InpaintingPipeline>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create InpaintingPipeline");
{
vector<vector<MxArray> > inpainters(first->toVector(
const_mem_fun_ref_t<vector<MxArray>, MxArray>(
&MxArray::toVector<MxArray>))); ++first;
for (vector<vector<MxArray> >::const_iterator it = inpainters.begin(); it != inpainters.end(); ++it) {
nargchk(it->size() >= 1);
Ptr<InpainterBase> inpainter = createInpainterBase(
(*it)[0].toString(), it->begin() + 1, it->end());
p->pushBack(inpainter);
}
}
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// Frames, Motions, StabilizedFrames, StabilizationMotions: data from stabilizer
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "Radius")
p->setRadius(val.toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<InpainterBase> createInpainterBase(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
Ptr<InpainterBase> p;
if (type == "ColorInpainter")
p = createColorInpainter(first, last);
else if (type == "ColorAverageInpainter")
p = createColorAverageInpainter(first, last);
else if (type == "ConsistentMosaicInpainter")
p = createConsistentMosaicInpainter(first, last);
else if (type == "MotionInpainter")
p = createMotionInpainter(first, last);
else if (type == "InpaintingPipeline")
p = createInpaintingPipeline(first, last);
else if (type == "NullInpainter") {
nargchk(len==0);
p = makePtr<NullInpainter>();
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized inpainter %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create InpainterBase");
return p;
}
Ptr<GaussianMotionFilter> createGaussianMotionFilter(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
int radius = 15;
float stdev = -1.0f;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "Radius")
radius = val.toInt();
else if (key == "Stdev")
stdev = val.toFloat();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return makePtr<GaussianMotionFilter>(radius, stdev);
}
Ptr<MotionFilterBase> createMotionFilterBase(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<MotionFilterBase> p;
if (type == "GaussianMotionFilter")
p = createGaussianMotionFilter(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized motion filter %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MotionFilterBase");
return p;
}
Ptr<LpMotionStabilizer> createLpMotionStabilizer(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<LpMotionStabilizer> p = makePtr<LpMotionStabilizer>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create LpMotionStabilizer");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MotionModel")
p->setMotionModel(MotionModelMap[val.toString()]);
else if (key == "FrameSize")
p->setFrameSize(val.toSize());
else if (key == "TrimRatio")
p->setTrimRatio(val.toFloat());
else if (key == "Weight1")
p->setWeight1(val.toFloat());
else if (key == "Weight2")
p->setWeight2(val.toFloat());
else if (key == "Weight3")
p->setWeight3(val.toFloat());
else if (key == "Weight4")
p->setWeight4(val.toFloat());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<MotionStabilizationPipeline> createMotionStabilizationPipeline(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk(len==1);
Ptr<MotionStabilizationPipeline> p = makePtr<MotionStabilizationPipeline>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MotionStabilizationPipeline");
{
vector<vector<MxArray> > stabilizers(first->toVector(
const_mem_fun_ref_t<vector<MxArray>, MxArray>(
&MxArray::toVector<MxArray>))); ++first;
for (vector<vector<MxArray> >::const_iterator it = stabilizers.begin(); it != stabilizers.end(); ++it) {
nargchk(it->size() >= 1);
Ptr<IMotionStabilizer> stabilizer = createIMotionStabilizer(
(*it)[0].toString(), it->begin() + 1, it->end());
p->pushBack(stabilizer);
}
}
return p;
}
Ptr<IMotionStabilizer> createIMotionStabilizer(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<IMotionStabilizer> p;
if (type == "LpMotionStabilizer")
p = createLpMotionStabilizer(first, last);
else if (type == "GaussianMotionFilter")
p = createGaussianMotionFilter(first, last);
else if (type == "MotionStabilizationPipeline")
p = createMotionStabilizationPipeline(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized motion stabilizer %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create IMotionStabilizer");
return p;
}
Ptr<MoreAccurateMotionWobbleSuppressor> createMoreAccurateMotionWobbleSuppressor(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
Ptr<MoreAccurateMotionWobbleSuppressor> p = makePtr<MoreAccurateMotionWobbleSuppressor>();
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create MoreAccurateMotionWobbleSuppressor");
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
// FrameCount, Motions, Motions2, StabilizationMotions: data from stabilizer
if (key == "MotionEstimator") {
vector<MxArray> args(val.toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<ImageMotionEstimatorBase> pp = createImageMotionEstimator(
args[0].toString(), args.begin() + 1, args.end());
p->setMotionEstimator(pp);
}
else if (key == "Period")
p->setPeriod(val.toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return p;
}
Ptr<WobbleSuppressorBase> createWobbleSuppressorBase(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
Ptr<WobbleSuppressorBase> p;
if (type == "MoreAccurateMotionWobbleSuppressor")
p = createMoreAccurateMotionWobbleSuppressor(first, last);
else if (type == "NullWobbleSuppressor") {
nargchk(len==0);
p = makePtr<NullWobbleSuppressor>();
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized wobble suppressor %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create WobbleSuppressorBase");
return p;
}
| 34.739377 | 113 | 0.598141 | [
"vector",
"model"
] |
f03189e9e428767adc735f9a72f3b0ddc2f16b09 | 620 | cpp | C++ | Basic/1046.cpp | GodLovesJonny/PAT-Solutions | b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77 | [
"MIT"
] | 6 | 2019-03-13T10:07:25.000Z | 2019-09-29T14:10:11.000Z | Basic/1046.cpp | GodLovesJonny/PAT-Solutions | b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77 | [
"MIT"
] | null | null | null | Basic/1046.cpp | GodLovesJonny/PAT-Solutions | b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int N;
int main() {
ios::sync_with_stdio(false);
cin >> N;
int i;
int cnta = 0, cntb = 0;
int a1, a2, b1, b2, res;
for (i = 0; i < N; i++) {
cin >> a1 >> a2 >> b1 >> b2;
res = a1 + b1;
if (a2 == res && b2 == res) {
// cnta++;
// cntb++;
continue;
}
if (a2 == res && b2 != res) {
cntb++;
continue;
}
if (b2 == res && a2 != res) {
cnta++;
continue;
}
}
cout << cnta << ' ' << cntb << endl;
return 0;
}
| 15.121951 | 37 | 0.514516 | [
"vector"
] |
f03a22e1f99ba9b5cc287ae506571617b0c1234e | 2,409 | hpp | C++ | plugins/monitor_plugin/httpc_only_send.hpp | ultrain-os/ultrain-core-production | 5d26bbe51033db183d3c069a30d87bcbe9cf736e | [
"MIT"
] | 38 | 2019-08-15T08:38:15.000Z | 2022-01-14T07:31:51.000Z | plugins/monitor_plugin/httpc_only_send.hpp | sighttviewliu/ultrain-core-production | c2807d9310da8b5dc1408502866be59299a96c22 | [
"MIT"
] | 4 | 2019-08-19T13:07:10.000Z | 2020-10-17T02:45:04.000Z | plugins/monitor_plugin/httpc_only_send.hpp | sighttviewliu/ultrain-core-production | c2807d9310da8b5dc1408502866be59299a96c22 | [
"MIT"
] | 7 | 2019-08-15T11:11:09.000Z | 2022-01-14T08:11:46.000Z | /**
* @file
* @copyright defined in ultrain/LICENSE.txt
*/
#pragma once
namespace ultrainio { namespace client { namespace http {
namespace detail {
class http_context_impl;
struct http_context_deleter {
void operator()(http_context_impl*) const;
};
}
using http_context = std::unique_ptr<detail::http_context_impl, detail::http_context_deleter>;
http_context create_http_context();
using namespace std;
struct parsed_url {
string scheme;
string server;
string port;
string path;
static string normalize_path(const string& path);
parsed_url operator+ (string sub_path) {
return {scheme, server, port, path + sub_path};
}
};
parsed_url parse_url( const string& server_url );
struct resolved_url : parsed_url {
resolved_url( const parsed_url& url, vector<string>&& resolved_addresses, uint16_t resolved_port, bool is_loopback)
:parsed_url(url)
,resolved_addresses(std::move(resolved_addresses))
,resolved_port(resolved_port)
,is_loopback(is_loopback)
{
}
vector<string> resolved_addresses;
uint16_t resolved_port;
bool is_loopback;
};
resolved_url resolve_url( const http_context& context,
const parsed_url& url );
struct connection_param {
const http_context& context;
resolved_url url;
bool verify_cert;
std::vector<string>& headers;
connection_param( const http_context& context,
const resolved_url& url,
bool verify,
std::vector<string>& h) : context(context),url(url), headers(h) {
verify_cert = verify;
}
connection_param( const http_context& context,
const parsed_url& url,
bool verify,
std::vector<string>& h) : context(context),url(resolve_url(context, url)), headers(h) {
verify_cert = verify;
}
};
fc::variant do_http_call(
const connection_param& cp,
const fc::variant& postdata = fc::variant(),
bool print_request = false,
bool print_response = false);
FC_DECLARE_EXCEPTION( connection_exception, 1100000, "Connection Exception" );
}}}
| 28.678571 | 121 | 0.600664 | [
"vector"
] |
f03c1be825f9a5ff1c0145b86c5e89e3559a027d | 10,645 | hpp | C++ | src/metaspades/src/common/visualization/graph_print_utils.hpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | src/metaspades/src/common/visualization/graph_print_utils.hpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | src/metaspades/src/common/visualization/graph_print_utils.hpp | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | 2 | 2021-06-05T07:40:20.000Z | 2021-06-05T08:02:58.000Z | //***************************************************************************
//* Copyright (c) 2015 Saint Petersburg State University
//* Copyright (c) 2011-2014 Saint Petersburg Academic University
//* All Rights Reserved
//* See file LICENSE for details.
//***************************************************************************
#ifndef GRAPH_PRINTER_HPP_
#define GRAPH_PRINTER_HPP_
#include <string>
#include <sstream>
namespace visualization {
template<class VertexId>
struct BaseVertex {
VertexId id_;
std::string label_;
std::string href_;
std::string fill_color_;
BaseVertex(VertexId id, const std::string &label, const std::string &reference, const std::string &fill_color):
id_(id), label_(label), href_(reference), fill_color_(fill_color) {
}
};
template<class VertexId>
struct BaseEdge {
VertexId from;
VertexId to;
std::string label;
std::string color;
BaseEdge(VertexId _from, VertexId _to, const std::string &_label, const std::string &_color):
from(_from), to(_to), label(_label), color(_color) {
}
};
class StreamRecorder {
private:
std::ostream &os_;
protected:
virtual std::ostream &os() {
return os_;
}
public:
StreamRecorder(std::ostream &os) : os_(os) {
}
virtual ~StreamRecorder() {
}
};
template<class Vertex, class Edge>
class GraphRecorder {
public:
virtual void recordVertex(Vertex vertex) = 0;
virtual void recordEdge(Edge edge) = 0;
virtual inline void startGraphRecord(const std::string &name) = 0;
virtual inline void endGraphRecord() = 0;
virtual ~GraphRecorder(){
}
};
template<class VertexId>
class SingleGraphRecorder : public GraphRecorder<BaseVertex<VertexId>, BaseEdge<VertexId>> {
protected:
typedef BaseVertex<VertexId> Vertex;
typedef BaseEdge<VertexId> Edge;
};
template<class VertexId>
class PairedGraphRecorder : public GraphRecorder<std::pair<BaseVertex<VertexId>, BaseVertex<VertexId>>, BaseEdge<std::pair<VertexId, VertexId>>> {
protected:
typedef std::pair<BaseVertex<VertexId>, BaseVertex<VertexId>> Vertex;
typedef BaseEdge<std::pair<VertexId, VertexId>> Edge;
};
template<class VertexId>
class DotGraphRecorder : public StreamRecorder {
public:
DotGraphRecorder(std::ostream &os) : StreamRecorder(os) {
}
protected:
template<class vid>
void recordVertexId(vid id) {
this->os() << "vertex_" << id;
}
std::string IdToStr(VertexId u) {
std::stringstream ss;
ss << u;
return ss.str();
}
std::string constructNodeId(VertexId v) {
return constructNodePairId(v, v);
}
inline void recordParameter(std::ostream &os, const std::string &name, const std::string &value) {
os << name << "=" << "<" << value << "> ";
}
inline void recordParameter(const std::string &name, const std::string &value) {
recordParameter(this->os(), name, value);
}
inline void recordParameterInQuotes(std::ostream &os, const std::string &name, const std::string &value) {
os << name << "=" << "\"" << value << "\" ";
}
inline void recordParameterInQuotes(const std::string &name, const std::string &value) {
recordParameterInQuotes(this->os(), name, value);
}
inline double getColorParameter(int l, int r, double perc) {
return l * perc + r * (1 - perc);
}
inline std::string getColor(int currentLength, int approximateLength) {
currentLength %= approximateLength;
int points[8][3] = {{0, 0, 1}, {0, 1, 1}, {1, 1, 1}, {0, 1, 0}, {1, 1, 0}, {1, 0, 1}, {0, 0, 1}};
std::stringstream ss;
int bound = approximateLength / 6;
int num = currentLength / bound;
double perc = (currentLength % bound) * 1. / bound;
for (int i = 0; i < 3; i++) {
ss << getColorParameter(points[num][i], points[num + 1][i], perc);
if (i != 2)
ss << ",";
}
return ss.str();
}
};
template<class SingleVertexId>
class DotSingleGraphRecorder: public SingleGraphRecorder<SingleVertexId>, public DotGraphRecorder<SingleVertexId> {
private:
typedef BaseVertex<SingleVertexId> Vertex;
typedef BaseEdge<SingleVertexId> Edge;
public:
DotSingleGraphRecorder(std::ostream &os) : DotGraphRecorder<SingleVertexId>(os) {
}
void recordVertex(Vertex vertex) {
this->recordVertexId(vertex.id_);
this->os() << "[";
this->recordParameterInQuotes("label", vertex.label_);
this->os() << ",";
this->recordParameter("style", "filled");
this->os() << ",";
this->recordParameter("color", "black");
this->os() << ",";
if(vertex.href_ != "") {
this->recordParameterInQuotes("href", vertex.href_);
this->os() << ",";
}
this->recordParameter("fillcolor", vertex.fill_color_);
this->os() << "]" << std::endl;
}
void recordEdge(Edge edge) {
this->recordVertexId(edge.from);
this->os() << "->";
this->recordVertexId(edge.to);
this->os() << "[";
this->recordParameterInQuotes("label", edge.label);
this->os() << ",";
this->recordParameter("color", edge.color);
this->os() << "]" << std::endl;
}
inline void startGraphRecord(const std::string &name) {
this->os() << "digraph " << name << " {" << std::endl;
this->os() << "node" << "[";
this->recordParameter("fontname", "Courier");
this->recordParameter("penwidth", "1.8");
this->os() << "]\n";
}
inline void endGraphRecord() {
this->os() << "}\n";
}
};
template<class SingleVertexId>
class DotPairedGraphRecorder: public PairedGraphRecorder<SingleVertexId>, public DotGraphRecorder<SingleVertexId> {
private:
typedef BaseVertex<SingleVertexId> SingleVertex;
typedef BaseEdge<SingleVertexId> SingleEdge;
typedef typename PairedGraphRecorder<SingleVertexId>::Vertex Vertex;
typedef typename PairedGraphRecorder<SingleVertexId>::Edge Edge;
std::string constructNodePairId(SingleVertexId u, SingleVertexId v) {
std::stringstream ss;
auto u_str = this->IdToStr(u);
auto v_str = this->IdToStr(v);
if (u == v)
ss << u;
else if (u_str > v_str)
ss << v_str << "_" << u_str;
else
ss << u_str << "_" << v_str;
return ss.str();
}
inline std::string constructPortCell(const std::string &port, const std::string &href, const std::string &color) {
std::stringstream ss;
ss << "<TD BORDER=\"0\" PORT = \"port_" << port << "\" ";
this->recordParameterInQuotes(ss, "color", color);
this->recordParameterInQuotes(ss, "bgcolor", color);
if (!href.empty()) {
ss << "href=\"" << href << "\"";
}
ss << "></TD>";
return ss.str();
}
inline std::string constructLabelCell(const std::string &label, const std::string &href, const std::string &color) {
std::stringstream ss;
ss << "<TD BORDER=\"0\" ";
this->recordParameterInQuotes(ss, "color", color);
this->recordParameterInQuotes(ss, "bgcolor", color);
if(href != "") {
ss <<"href=\"" << href << "\"";
}
ss << ">"
<< label << "</TD>";
return ss.str();
}
std::string constructComplexNodeId(std::string pairId, SingleVertexId v) {
std::stringstream ss;
ss << pairId << ":port_" << v;
return ss.str();
}
std::string constructTableEntry(SingleVertex v/*, const string &label, const string &href*/) {
std::stringstream ss;
ss << "<TR>";
ss << constructPortCell(std::to_string(v.id_) + "_in", v.href_, v.fill_color_);
ss << constructLabelCell(v.label_, v.href_, v.fill_color_);
ss << constructPortCell(std::to_string(v.id_) + "_out", v.href_, v.fill_color_);
ss << "</TR>\n";
return ss.str();
}
std::string constructReverceTableEntry(SingleVertex v/*, const string &label, const string &href*/) {
std::stringstream ss;
ss << "<TR>";
ss << constructPortCell(std::to_string(v.id_) + "_out", v.href_, v.fill_color_);
ss << constructLabelCell(v.label_, v.href_, v.fill_color_);
ss << constructPortCell(std::to_string(v.id_) + "_in", v.href_, v.fill_color_);
ss << "</TR>\n";
return ss.str();
}
std::string constructComplexNodeLabel(Vertex v) {
return "<TABLE BORDER=\"1\" CELLSPACING=\"0\" >\n" + constructTableEntry(v.first)
+ constructReverceTableEntry(v.second) + "</TABLE>";
}
std::string constructVertexInPairId(SingleVertexId v, SingleVertexId rc) {
return constructComplexNodeId(constructNodePairId(v, rc), v);
}
public:
DotPairedGraphRecorder(std::ostream &os) : DotGraphRecorder<SingleVertexId>(os) {
}
void recordPairedVertexId(SingleVertexId id1, SingleVertexId id2) {
this->os() << "vertex_" << constructNodePairId(id1, id2);
}
void recordVertex(Vertex vertex) {
auto pairLabel = constructComplexNodeLabel(vertex);
recordPairedVertexId(vertex.first.id_, vertex.second.id_);
this->os() << "[";
this->recordParameter("label", constructComplexNodeLabel(vertex));
this->os() << ",";
this->recordParameter("color", "black");
this->os() << ",";
this->recordParameter("URL", "/vertex/" + std::to_string(vertex.first.id_) + ".svg");
this->os() << "]\n";
}
void recordEdge(Edge edge) {
this->recordVertexId(constructVertexInPairId(edge.from.first, edge.from.second));
this->os() << "_out";
this->os() << "->";
this->recordVertexId(constructVertexInPairId(edge.to.first, edge.to.second));
this->os() << "_in";
this->os() << "[";
this->recordParameterInQuotes("label", edge.label);
this->os() << ",";
this->recordParameter("color", edge.color);
this->os() << "]\n";
}
inline void startGraphRecord(const std::string &name) {
this->os() << "digraph " << name << " {\n";
this->os() << "node" << "[";
this->recordParameter("fontname", "Courier");
this->os() << ",";
this->recordParameter("penwidth", "1.8");
this->os() << ",";
this->recordParameter("shape", "plaintext");
this->os() << "]\n";
}
inline void endGraphRecord() {
this->os() << "}\n";
}
};
}
#endif //GRAPH_PRINTER_HPP_//
| 32.553517 | 146 | 0.586285 | [
"shape"
] |
f03c43ed6f3e085da3c5f5aa454e27430bc991fa | 848 | hpp | C++ | src/cell_builder.hpp | brenthuisman/arbor-gui | 53a37e8fc27f8228867e88e1105933b9e975362e | [
"BSD-3-Clause"
] | 2 | 2021-03-18T15:09:22.000Z | 2021-03-18T15:25:21.000Z | src/cell_builder.hpp | brenthuisman/arbor-gui | 53a37e8fc27f8228867e88e1105933b9e975362e | [
"BSD-3-Clause"
] | 54 | 2020-11-12T10:23:03.000Z | 2021-09-08T08:28:52.000Z | src/cell_builder.hpp | arbor-sim/gui | 67e3f0318b9ea66e7be12cc4ee55a0cd2f2e945a | [
"BSD-3-Clause"
] | 8 | 2020-11-13T19:18:59.000Z | 2021-08-30T10:19:51.000Z | #pragma once
#include <arbor/cable_cell.hpp>
#include <arbor/morph/place_pwlin.hpp>
#include <arbor/morph/mprovider.hpp>
#include <arbor/morph/primitives.hpp>
#include <arbor/morph/region.hpp>
#include <arbor/morph/locset.hpp>
#include <glm/glm.hpp>
#include "location.hpp"
struct cell_builder {
arb::morphology morph;
arb::place_pwlin pwlin;
arb::label_dict labels;
arb::mprovider provider;
arb::cv_policy policy = arb::default_cv_policy();
cell_builder();
cell_builder(const arb::morphology& t);
std::vector<arb::msegment> make_segments(const arb::region&);
std::vector<glm::vec3> make_points(const arb::locset&);
std::vector<glm::vec3> make_boundary(const arb::cv_policy&);
void make_label_dict(std::vector<ls_def>& locsets, std::vector<rg_def>& regions);
};
| 29.241379 | 107 | 0.6875 | [
"vector"
] |
f050c3bb3e11d15c758977aaf62a74dfb2c80ad5 | 3,076 | hpp | C++ | sctxpy/sctx/snvs/_consensus.hpp | GWW/sctx | 797e56d3ac4bbb526d6de1f6e76f5db0d47e0e84 | [
"MIT"
] | null | null | null | sctxpy/sctx/snvs/_consensus.hpp | GWW/sctx | 797e56d3ac4bbb526d6de1f6e76f5db0d47e0e84 | [
"MIT"
] | null | null | null | sctxpy/sctx/snvs/_consensus.hpp | GWW/sctx | 797e56d3ac4bbb526d6de1f6e76f5db0d47e0e84 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <iostream>
#include <vector>
#include <numeric>
#include <numeric>
#include <fstream>
#include <cmath>
#include <limits>
#include "_cafimpl.hpp"
#include "_matrix.hpp"
namespace scapi{
void build_genotypes(const spCS<uint32_t> * counts, int32_t * labels, size_t G, uint32_t * out, double * summaries){
auto & cc = *counts;
//std::cout << "N = " << cc.N << " M = " << cc.M << " R = " << cc.R << " G = " << G << "\n";
PtrMatrix<uint32_t> umat(cc.R, G * 3, out);
PtrMatrix<double> dmat(cc.R, G * 4, summaries);
for(size_t i = 0; i < cc.R; i++){
int32_t s = cc.indptr[i];
int32_t e = cc.indptr[i + 1];
for(int32_t j = s; j < e; j++){
uint32_t ci = cc.indices[j];
int32_t l = labels[ci];
if(l < 0 || l > 1) continue;
umat(i, l * 3) += cc.ref[j];
umat(i, l * 3 + 1) += cc.alt[j];
umat(i, l * 3 + 2) += (cc.alt[j] > 0) | (cc.ref[j] > 0);
}
}
std::vector<std::vector<double>> AFs(G);
std::vector<double> tots(G);
for(size_t i = 0; i < cc.R; i++){
for(size_t l = 0; l < G; l++){
//dmat(i, l * 2) = umat(i, l * 3 + 2) > 0 ? (1.0 * umat(i, l * 3 + 1) / (umat(i, l * 3) + umat(i, l * 3 + 1))) : 0.0;
AFs[l].clear();
tots[l] = 0.0;
}
int32_t s = cc.indptr[i];
int32_t e = cc.indptr[i + 1];
for(int32_t j = s; j < e; j++){
uint32_t ci = cc.indices[j];
int32_t l = labels[ci];
if(l < 0 || l > 1) continue;
double AF = 1.0 * cc.alt[j] / (cc.alt[j] + cc.ref[j]);
tots[l] += cc.alt[j] + cc.ref[j];
AFs[l].push_back(AF);
}
for(size_t l = 0; l < G; l++){
if(!AFs[l].empty()){
double mean = std::accumulate(AFs[l].begin(), AFs[l].end(), 0.0) / AFs[l].size();
double rmse = 0.0;
double mae = 0.0;
for(auto a : AFs[l]){
rmse += (a - mean) * (a - mean);
mae += std::abs(a - mean);
}
dmat(i, l * 4) = mean;
dmat(i, l * 4 + 1) = std::sqrt(rmse / AFs[l].size());
dmat(i, l * 4 + 2) = mae / AFs[l].size();
dmat(i, l * 4 + 3) = tots[l] / AFs[l].size();
}
}
}
}
void cell_div(const spCS<uint32_t> * counts, const uint32_t * ridx, size_t N, const double * summary_AF, double * div, uint32_t * cnts){
auto & cc = *counts;
std::cout << "N = " << cc.N << " M = " << cc.M << " R = " << cc.R << " ridx N = " << N << "\n";
for(size_t ii = 0; ii < N; ii++){
size_t i = ridx[ii];
int32_t s = cc.indptr[i];
int32_t e = cc.indptr[i + 1];
double saf = summary_AF[i];
for(int32_t j = s; j < e; j++){
uint32_t ci = cc.indices[j];
double AF = 1.0 * cc.alt[j] / (cc.alt[j] + cc.ref[j]);
cnts[ci]++;
div[ci] += std::abs(saf - AF);
}
}
}
};
| 35.356322 | 136 | 0.43498 | [
"vector"
] |
f05b2a3a0d245901804a9a7a25c68090876bbc8b | 1,722 | hh | C++ | src/bugengine/filesystem/include/watchpoint.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 4 | 2015-05-13T16:28:36.000Z | 2017-05-24T15:34:14.000Z | src/bugengine/filesystem/include/watchpoint.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | null | null | null | src/bugengine/filesystem/include/watchpoint.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 1 | 2017-03-21T08:28:07.000Z | 2017-03-21T08:28:07.000Z | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_FILESYSTEM_WATCHPOINT_HH_
#define BE_FILESYSTEM_WATCHPOINT_HH_
/**************************************************************************************************/
#include <bugengine/filesystem/stdafx.h>
#include <bugengine/filesystem/diskfolder.script.hh>
namespace BugEngine { namespace FileSystem {
class WatchPoint : public minitl::refcountable
{
friend class DiskFolder::Watch;
private:
typedef minitl::vector< weak< Folder::Watch > > WatchVector;
typedef minitl::vector< minitl::tuple< istring, ref< WatchPoint > > > ChildrenVector;
WatchVector m_watches;
ChildrenVector m_children;
weak< WatchPoint > m_parent;
u32 m_recursiveWatchCount;
public:
WatchPoint();
WatchPoint(weak< WatchPoint > parent);
~WatchPoint();
public:
void signalDirty();
static ref< Folder::Watch > addWatch(weak< DiskFolder > folder, const ipath& path);
static ref< WatchPoint > getWatchPoint(const ipath& path);
private:
void addWatch(weak< Folder::Watch > watch);
void removeWatch(weak< Folder::Watch > watch);
void cleanupTree();
static ref< WatchPoint > getWatchPointOrCreate(const ipath& path);
static void cleanup();
static ref< WatchPoint > s_root;
};
}} // namespace BugEngine::FileSystem
/**************************************************************************************************/
#endif
| 35.142857 | 100 | 0.526132 | [
"vector"
] |
f06092871252114d48e5a5e11a006b1295f12428 | 1,056 | hpp | C++ | drape_frontend/traffic_renderer.hpp | operon/omim_mapsme | c6d3bce1d5363789ca8ca49d21d983829db94edb | [
"Apache-2.0"
] | null | null | null | drape_frontend/traffic_renderer.hpp | operon/omim_mapsme | c6d3bce1d5363789ca8ca49d21d983829db94edb | [
"Apache-2.0"
] | null | null | null | drape_frontend/traffic_renderer.hpp | operon/omim_mapsme | c6d3bce1d5363789ca8ca49d21d983829db94edb | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "drape_frontend/traffic_generator.hpp"
#include "drape/gpu_program_manager.hpp"
#include "drape/pointers.hpp"
#include "drape/uniform_values_storage.hpp"
#include "geometry/screenbase.hpp"
#include "geometry/spline.hpp"
#include "std/map.hpp"
#include "std/vector.hpp"
#include "std/unordered_map.hpp"
namespace df
{
class TrafficRenderer final
{
public:
TrafficRenderer() = default;
void AddRenderData(ref_ptr<dp::GpuProgramManager> mng,
vector<TrafficRenderData> && renderData);
void SetTexCoords(unordered_map<int, glsl::vec2> && texCoords);
void UpdateTraffic(vector<TrafficSegmentData> const & trafficData);
void RenderTraffic(ScreenBase const & screen, int zoomLevel,
ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms);
void Clear();
private:
vector<TrafficRenderData> m_renderData;
unordered_map<int, glsl::vec2> m_texCoords;
unordered_map<uint64_t, TrafficHandle *> m_handles;
};
} // namespace df
| 24 | 70 | 0.726326 | [
"geometry",
"vector"
] |
f067832e834f60c8b5f60fbd7a398c84efde1355 | 11,865 | cpp | C++ | plugins/net_plugin/net_plugin.cpp | eonproject/EONCore | 4ed8651e7ba5cb99269a9e400922e027ca7a3efa | [
"MIT"
] | null | null | null | plugins/net_plugin/net_plugin.cpp | eonproject/EONCore | 4ed8651e7ba5cb99269a9e400922e027ca7a3efa | [
"MIT"
] | null | null | null | plugins/net_plugin/net_plugin.cpp | eonproject/EONCore | 4ed8651e7ba5cb99269a9e400922e027ca7a3efa | [
"MIT"
] | null | null | null | #include <eos/chain/types.hpp>
#include <eos/net_plugin/net_plugin.hpp>
#include <eos/net_plugin/protocol.hpp>
#include <fc/network/ip.hpp>
#include <fc/io/raw.hpp>
#include <fc/container/flat.hpp>
#include <fc/reflect/variant.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace eos {
using std::vector;
using boost::asio::ip::tcp;
using fc::time_point;
using fc::time_point_sec;
using eos::chain::transaction_id_type;
namespace bip = boost::interprocess;
using socket_ptr = std::shared_ptr<tcp::socket>;
struct node_transaction_state {
transaction_id_type id;
fc::time_point received;
fc::time_point_sec expires;
vector<char> packed_transaction;
uint64_t block_num = -1; /// block transaction was included in
bool validated = false; /// whether or not our node has validated it
};
/**
* Index by id
* Index by is_known, block_num, validated_time, this is the order we will broadcast
* to peer.
* Index by is_noticed, validated_time
*
*/
struct transaction_state {
transaction_id_type id;
bool is_known_by_peer = false; ///< true if we sent or received this trx to this peer or received notice from peer
bool is_noticed_to_peer = false; ///< have we sent peer noitce we know it (true if we reeive from this peer)
uint64_t block_num = -1; ///< the block number the transaction was included in
time_point validated_time; ///< infinity for unvalidated
time_point requested_time; /// incase we fetch large trx
};
typedef multi_index_container<
transaction_state,
indexed_by<
ordered_unique< tag<by_id>, member<transaction_state, transaction_id_type, &transaction_state::id > >
>
> transaction_state_index;
/**
*
*/
struct block_state {
block_id_type id;
bool is_known;
bool is_noticed_to_peer;
time_point requested_time;
};
typedef multi_index_container<
block_state,
indexed_by<
ordered_unique< tag<by_id>, member<block_state, block_id_type, &block_state::id > >
>
> block_state_index;
/**
* Index by start_block
*/
struct sync_state {
uint64_t start_block = 0;
uint64_t end_block = 0;
uint64_t last = 0; ///< last sent or received
time_point start_time;; ///< time request made or received
};
struct by_start_block;
typedef multi_index_container<
sync_state,
indexed_by<
ordered_unique< tag<by_start_block>, member<sync_state, uint64_t, &sync_state::start_block > >
>
> sync_request_index;
class connection {
public:
connection( socket_ptr s ):socket(s){
wlog( "created connection" );
pending_message_buffer.resize( 1024*1024*4 );
}
~connection() {
wlog( "released connection" );
}
block_state_index block_state;
transaction_state_index trx_state;
sync_request_index in_sync_state;
sync_request_index out_sync_state;
socket_ptr socket;
uint32_t pending_message_size;
vector<char> pending_message_buffer;
handshake_message last_handshake;
std::deque<net_message> out_queue;
void send( const net_message& m ) {
out_queue.push_back( m );
if( out_queue.size() == 1 )
send_next_message();
}
void send_next_message() {
if( !out_queue.size() )
return;
auto& m = out_queue.front();
vector<char> buffer;
uint32_t size = fc::raw::pack_size( m );
buffer.resize( size + sizeof(uint32_t) );
fc::datastream<char*> ds( buffer.data(), buffer.size() );
ds.write( (char*)&size, sizeof(size) );
fc::raw::pack( ds, m );
boost::asio::async_write( *socket, boost::asio::buffer( buffer.data(), buffer.size() ),
[this,buf=std::move(buffer)]( boost::system::error_code ec, std::size_t bytes_transferred ) {
ilog( "write message handler..." );
if( ec ) {
elog( "Error sending message: ${msg}", ("msg",ec.message() ) );
} else {
out_queue.pop_front();
send_next_message();
}
});
}
};
class net_plugin_impl {
public:
unique_ptr<tcp::acceptor> acceptor;
tcp::endpoint listen_endpoint;
tcp::endpoint public_endpoint;
vector<string> seed_nodes;
std::set<socket_ptr> pending_connections;
std::set< connection* > connections;
bool done = false;
void connect( const string& ep ) {
auto host = ep.substr( 0, ep.find(':') );
auto port = ep.substr( host.size()+1, host.size() );
idump((host)(port));
auto resolver = std::make_shared<tcp::resolver>( std::ref( app().get_io_service() ) );
tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str() );
resolver->async_resolve( query,
[resolver,ep,this]( const boost::system::error_code& err, tcp::resolver::iterator endpoint_itr ){
if( !err ) {
connect( resolver, endpoint_itr );
} else {
elog( "Unable to resolve ${ep}: ${error}", ( "ep", ep )("error", err.message() ) );
}
});
}
void connect( std::shared_ptr<tcp::resolver> resolver, tcp::resolver::iterator endpoint_itr ) {
auto sock = std::make_shared<tcp::socket>( std::ref( app().get_io_service() ) );
pending_connections.insert( sock );
auto current_endpoint = *endpoint_itr;
++endpoint_itr;
sock->async_connect( current_endpoint,
[sock,resolver,endpoint_itr,this]( const boost::system::error_code& err ) {
if( !err ) {
pending_connections.erase( sock );
start_session( new connection( sock ) );
} else {
if( endpoint_itr != tcp::resolver::iterator() ) {
connect( resolver, endpoint_itr );
}
}
}
);
}
/**
* This thread performs high level coordination among multiple connections and
* ensures connections are cleaned up, reconnected, etc.
*/
void network_loop() {
try {
ilog( "starting network loop" );
while( !done ) {
for( auto itr = connections.begin(); itr != connections.end(); ) {
auto con = *itr;
if( !con->socket->is_open() ) {
close(con);
itr = connections.begin();
continue;
}
++itr;
}
}
ilog("network loop done");
} FC_CAPTURE_AND_RETHROW() }
void start_session( connection* con ) {
connections.insert( con );
start_read_message( *con );
con->send( handshake_message{} );
// con->readloop_complete = bf::async( [=](){ read_loop( con ); } );
// con->writeloop_complete = bf::async( [=](){ write_loop( con ); } );
}
void start_listen_loop() {
auto socket = std::make_shared<tcp::socket>( std::ref( app().get_io_service() ) );
acceptor->async_accept( *socket, [socket,this]( boost::system::error_code ec ) {
if( !ec ) {
start_session( new connection( socket ) );
start_listen_loop();
} else {
elog( "Error accepting connection: ${m}", ("m", ec.message() ) );
}
});
}
void start_read_message( connection& c ) {
c.pending_message_size = 0;
boost::asio::async_read( *c.socket, boost::asio::buffer((char*)&c.pending_message_size,sizeof(c.pending_message_size)),
[&]( boost::system::error_code ec, std::size_t bytes_transferred ) {
ilog( "read size handler..." );
if( !ec ) {
if( c.pending_message_size <= c.pending_message_buffer.size() ) {
start_reading_pending_buffer( c );
return;
} else {
elog( "Received a message that was too big" );
}
} else {
elog( "Error reading message from connection: ${m}", ("m", ec.message() ) );
}
close( &c );
}
);
}
void start_reading_pending_buffer( connection& c ) {
boost::asio::async_read( *c.socket, boost::asio::buffer(c.pending_message_buffer.data(), c.pending_message_size ),
[&]( boost::system::error_code ec, std::size_t bytes_transferred ) {
ilog( "read buffer handler..." );
if( !ec ) {
try {
auto msg = fc::raw::unpack<net_message>( c.pending_message_buffer );
ilog( "received message of size: ${s}", ("s",bytes_transferred) );
start_read_message( c );
return;
} catch ( const fc::exception& e ) {
edump((e.to_detail_string() ));
}
} else {
elog( "Error reading message from connection: ${m}", ("m", ec.message() ) );
}
close( &c );
}
);
}
void write_loop( connection* c ) {
try {
c->send( handshake_message{} );
} catch ( ... ) {
wlog( "write loop exception" );
}
}
void close( connection* c ) {
ilog( "close ${c}", ("c",int64_t(c)));
if( c->socket )
c->socket->close();
connections.erase( c );
delete c;
}
};
net_plugin::net_plugin()
:my( new net_plugin_impl ) {
}
net_plugin::~net_plugin() {
}
void net_plugin::set_program_options( options_description& cli, options_description& cfg )
{
cfg.add_options()
("listen-endpoint", bpo::value<string>()->default_value( "127.0.0.1:9876" ), "The local IP address and port to listen for incoming connections.")
("remote-endpoint", bpo::value< vector<string> >()->composing(), "The IP address and port of a remote peer to sync with.")
("public-endpoint", bpo::value<string>()->default_value( "0.0.0.0:9876" ), "The public IP address and port that should be advertized to peers.")
;
}
void net_plugin::plugin_initialize( const variables_map& options ) {
ilog("Initialize net plugin");
if( options.count( "listen-endpoint" ) ) {
auto lipstr = options.at("listen-endpoint").as< string >();
auto fcep = fc::ip::endpoint::from_string( lipstr );
my->listen_endpoint = tcp::endpoint( boost::asio::ip::address_v4::from_string( (string)fcep.get_address() ), fcep.port() );
ilog( "configured net to listen on ${ep}", ("ep", fcep) );
my->acceptor.reset( new tcp::acceptor( app().get_io_service() ) );
}
if( options.count( "remote-endpoint" ) ) {
my->seed_nodes = options.at( "remote-endpoint" ).as< vector<string> >();
}
}
void net_plugin::plugin_startup() {
// boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
if( my->acceptor ) {
my->acceptor->open(my->listen_endpoint.protocol());
my->acceptor->set_option(tcp::acceptor::reuse_address(true));
my->acceptor->bind(my->listen_endpoint);
my->acceptor->listen();
my->start_listen_loop();
}
for( auto seed_node : my->seed_nodes ) {
my->connect( seed_node );
}
}
void net_plugin::plugin_shutdown() {
try {
ilog( "shutdown.." );
my->done = true;
if( my->acceptor ) {
ilog( "close acceptor" );
my->acceptor->close();
ilog( "close connections ${s}", ("s",my->connections.size()) );
auto cons = my->connections;
for( auto con : cons )
con->socket->close();
while( my->connections.size() ) {
auto c = *my->connections.begin();
my->close( c );
}
idump((my->connections.size()));
my->acceptor.reset(nullptr);
}
ilog( "exit shutdown" );
} FC_CAPTURE_AND_RETHROW() }
}
| 31.981132 | 154 | 0.579941 | [
"vector"
] |
f06beb5f6068315d7f869b8aef5f2605476b7a3e | 13,415 | cpp | C++ | main.cpp | 453647684/LongShotExplore | 3b0c11f5d903660d64fddea07fb998be392ee1b8 | [
"Apache-2.0"
] | null | null | null | main.cpp | 453647684/LongShotExplore | 3b0c11f5d903660d64fddea07fb998be392ee1b8 | [
"Apache-2.0"
] | null | null | null | main.cpp | 453647684/LongShotExplore | 3b0c11f5d903660d64fddea07fb998be392ee1b8 | [
"Apache-2.0"
] | null | null | null |
#include "imagemerger.h"
#include <QCoreApplication>
#include <QString>
#include <QDebug>
#include <QDir>
#include <QTime>
/*
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
return a.exec();
}
*/
#include<opencv2/opencv.hpp>
//#include<opencv2/highgui/highgui.hpp>"
//#include<opencv2/xfeatures2d/nonfree.hpp>
//#include<opencv2/legacy/legacy.hpp>
#include<iostream>
using namespace cv;
using namespace std;
/*
int surfImage()
{
Mat image01 = imread("2.jpg", 1); //右图
Mat image02 = imread("1.jpg", 1); //左图
namedWindow("p2", 0);
namedWindow("p1", 0);
imshow("p2", image01);
imshow("p1", image02);
//灰度图转换
Mat image1, image2;
cvtColor(image01, image1, CV_RGB2GRAY);
cvtColor(image02, image2, CV_RGB2GRAY);
//提取特征点
SurfFeatureDetector surfDetector(800); // 海塞矩阵阈值,在这里调整精度,值越大点越少,越精准
vector<KeyPoint> keyPoint1, keyPoint2;
surfDetector.detect(image1, keyPoint1);
surfDetector.detect(image2, keyPoint2);
//特征点描述,为下边的特征点匹配做准备
SurfDescriptorExtractor SurfDescriptor;
Mat imageDesc1, imageDesc2;
SurfDescriptor.compute(image1, keyPoint1, imageDesc1);
SurfDescriptor.compute(image2, keyPoint2, imageDesc2);
//获得匹配特征点,并提取最优配对
FlannBasedMatcher matcher;
vector<DMatch> matchePoints;
matcher.match(imageDesc1, imageDesc2, matchePoints, Mat());
cout << "total match points: " << matchePoints.size() << endl;
Mat img_match;
drawMatches(image01, keyPoint1, image02, keyPoint2, matchePoints, img_match);
namedWindow("match", 0);
imshow("match",img_match);
imwrite("match.jpg", img_match);
waitKey();
}
*/
// 比较图片m1的r1行像素和m2的r2行像素是否相等
bool CompareRowsData(const Mat &m1, const int r1, const Mat &m2, const int r2)
{
if(m1.cols != m2.cols)
return false;
for(int i = 0; i < m1.cols; ++i) {
if( m1.at<Vec3b>(r1, i)[0] != m2.at<Vec3b>(r2, i)[0]||
m1.at<Vec3b>(r1, i)[1] != m2.at<Vec3b>(r2, i)[1]||
m1.at<Vec3b>(r1, i)[2] != m2.at<Vec3b>(r2, i)[2]
) {
//qDebug() << r1 << r2 <<i;
return false;
}
}
return true;
}
// 获取两张图片变化区域
void getChangeArea(QString img1Path, QString img2Path, Mat &c1, Mat &c2)
{
//从两张图片中截取变化的区域
Mat img1=imread(img1Path.toLocal8Bit().data());
Mat img2=imread(img2Path.toLocal8Bit().data());
Mat dst;//存储结果
cout<<"img1 "<<int(img1.at<Vec3b>(10,10)[0])<<endl;//img1在坐标(10,10)的蓝色通道的值,强制转成int
cout<<"img2 "<<int(img2.at<Vec3b>(10,10)[0])<<endl;
int minI = img1.rows;
int minJ = img1.cols;
int maxI = 0;
int maxJ = 0;
// 计算变化部分
for(int i = 0; i < img1.rows; ++i) {
for(int j = 0; j < img1.cols; ++j) {
if(img1.at<Vec3b>(i, j)[0] != img2.at<Vec3b>(i, j)[0] || img1.at<Vec3b>(i, j)[1] != img2.at<Vec3b>(i, j)[1] || img1.at<Vec3b>(i, j)[2] != img2.at<Vec3b>(i, j)[2]) {
//cout << "rows:" << i << "cols:" << j << endl; //<< img1.at<Vec3b>(j, i) << img2.at<Vec3b>(j, i) << endl;
if( i < minI) minI = i;
if( j < minJ) minJ = j;
if( i > maxI) maxI = i;
if( j > maxJ) maxJ = j;
}
}
}
cout << "("<< minJ << " "<< minI << ")"<< "(" << maxJ - minJ << " " << maxI - minI<< ")" << endl;
// 截取变化部分
c1 = Mat(img1, Rect(minJ, minI, maxJ - minJ, maxI - minI));
c2 = Mat(img2, Rect(minJ, minI, maxJ - minJ, maxI - minI));
}
// 获取两张图片变化区域
Rect getChangeArea(Mat &img1, Mat &img2)
{
cout<<"img1 "<<int(img1.at<Vec3b>(10,10)[0])<<endl;//img1在坐标(10,10)的蓝色通道的值,强制转成int
cout<<"img2 "<<int(img2.at<Vec3b>(10,10)[0])<<endl;
int minI = img1.rows;
int minJ = img1.cols;
int maxI = 0;
int maxJ = 0;
// 计算变化部分
for(int i = 0; i < img1.rows; ++i) {
for(int j = 0; j < img1.cols; ++j) {
if(img1.at<Vec3b>(i, j)[0] != img2.at<Vec3b>(i, j)[0] || img1.at<Vec3b>(i, j)[1] != img2.at<Vec3b>(i, j)[1] || img1.at<Vec3b>(i, j)[2] != img2.at<Vec3b>(i, j)[2]) {
//cout << "rows:" << i << "cols:" << j << endl; //<< img1.at<Vec3b>(j, i) << img2.at<Vec3b>(j, i) << endl;
if( i < minI) minI = i;
if( j < minJ) minJ = j;
if( i > maxI) maxI = i;
if( j > maxJ) maxJ = j;
}
}
}
return Rect(minJ, minI, maxJ - minJ, maxI - minI);
}
// openCV 融合拼接算法
bool mergeImgOpenCV(Mat &pano, Mat &img1, Mat &img2)
{
vector<Mat> imgs;
imgs.push_back(img1);
imgs.push_back(img2);
Ptr<Stitcher> stitcher = Stitcher::create(Stitcher::SCANS, true);
//Ptr<Stitcher> stitcher = Stitcher::create(Stitcher::PANORAMA, true);
Stitcher::Status status = stitcher->stitch(imgs, pano);
if(status == Stitcher::OK) {
return true;
}
return false;
}
// openCV 融合拼接算法
bool mergeImgOpenCV(Mat &pano, vector<Mat> &imgs)
{
Ptr<Stitcher> stitcher = Stitcher::create(Stitcher::SCANS, true);
//Ptr<Stitcher> stitcher = Stitcher::create(Stitcher::PANORAMA, true);
Stitcher::Status status = stitcher->stitch(imgs, pano);
if(status == Stitcher::OK) {
return true;
}
return false;
}
bool mergeImg(Mat &pano, Mat &img1, Mat &img2)
{
//变化部分重复计算
int i = 0;
int j = 0;
int k = 0;
int start = 0;
bool find = false;
for(i = 0; i < img1.rows; ++i) {
find = true;
for(j = 0; j < img1.cols; ++j) {
if(img1.at<Vec3b>(img1.rows, j)[0] != img2.at<Vec3b>(i, j)[0] ||
img1.at<Vec3b>(img1.rows, j)[1] != img2.at<Vec3b>(i, j)[1] ||
img1.at<Vec3b>(img1.rows, j)[2] != img2.at<Vec3b>(i, j)[2]) {
find = false;
continue;
}
}
if(find)
goto S;
}
S:
cout <<"s " << i << endl;
pano = Mat(img2, Rect(0, 0, img2.cols, img2.rows));
return true;
}
Mat getMatByRect(QString str, Rect &rect)
{
Mat img = imread(str.toLocal8Bit().data());
return Mat(img, rect);
}
cv::Mat get_merage_image(cv::Mat cur_frame, cv::Mat cur_frame1)
{
cv::Mat image_one=cur_frame;
cv::Mat image_two=cur_frame1;
//创建连接后存入的图像,两幅图像按左右排列,所以列数+1
cv::Mat img_merge(image_one.rows,image_one.cols+
image_two.cols+1,image_one.type());
//图像拷贝,不能用Mat中的clone和copyTo函数,单幅图像拷贝可用,clone和copyTo不仅拷贝图像数据,还拷贝一///些其他的信息
//而现在是将两幅图像的数据拷贝到一副图像中,只拷贝图像数据
//因此用colRange来访问图像的列数据colRange第一参数是起始列,是从0开始索引,而第二个参数是结束列,
//从1开始索引,与我们以前使用的不同,因此,参数分别为0和image_one.cols
image_one.colRange(0,image_one.cols).
copyTo(img_merge.colRange(0,image_one.cols));
//第二幅图像拷贝,中间的一行作为两幅图像的分割线
image_two.colRange(0,image_two.cols).copyTo(
img_merge.colRange(image_one.cols+1,img_merge.cols));
return img_merge;
}
cv::Mat get_merage_image2(cv::Mat cur_frame, cv::Mat cur_frame1)
{
cv::Mat img_merge;
cv::Size size(cur_frame.cols + cur_frame1.cols, MAX(cur_frame.rows, cur_frame1.rows));
img_merge.create(size, CV_MAKETYPE(cur_frame.depth(), 3));
img_merge = cv::Scalar::all(0);
cv::Mat outImg_left, outImg_right;
//2.在新建合并图像中设置感兴趣区域
outImg_left = img_merge(cv::Rect(0, 0, cur_frame.cols, cur_frame.rows));
outImg_right = img_merge(cv::Rect(cur_frame.cols, 0, cur_frame.cols, cur_frame.rows));
//3.将待拷贝图像拷贝到感性趣区域中
cur_frame.copyTo(outImg_left);
cur_frame1.copyTo(outImg_right);
return img_merge;
}
cv::Mat getMerageImage(cv::Mat cur_frame, cv::Mat cur_frame1)
{
cv::Mat image_one=cur_frame;
cv::Mat image_two=cur_frame1;
//创建连接后存入的图像,两幅图像按左右排列,所以列数+1
cv::Mat img_merge(image_one.rows + image_two.rows, image_one.cols, image_one.type());
qDebug() << img_merge.rows <<img_merge.cols;
//图像拷贝,不能用Mat中的clone和copyTo函数,单幅图像拷贝可用,clone和copyTo不仅拷贝图像数据,还拷贝一///些其他的信息
//而现在是将两幅图像的数据拷贝到一副图像中,只拷贝图像数据
//因此用colRange来访问图像的列数据colRange第一参数是起始列,是从0开始索引,而第二个参数是结束列,
//从1开始索引,与我们以前使用的不同,因此,参数分别为0和image_one.cols
image_one.rowRange(0,image_one.rows).copyTo(img_merge.rowRange(0,image_one.rows));
//第二幅图像拷贝,中间的一行作为两幅图像的分割线
image_two.rowRange(0,image_two.rows).copyTo(img_merge.rowRange(image_one.rows, img_merge.rows));
return img_merge;
}
cv::Mat getMerageImage2(cv::Mat cur_frame, cv::Mat cur_frame1)
{
cv::Mat img_merge;
cv::Size size(MAX(cur_frame.cols , cur_frame1.cols), cur_frame.rows + cur_frame1.rows);
img_merge.create(size, CV_MAKETYPE(cur_frame.depth(), 3));
img_merge = cv::Scalar::all(0);
cv::Mat outImg_left, outImg_right;
//2.在新建合并图像中设置感兴趣区域
outImg_left = img_merge(cv::Rect(0, 0, cur_frame.cols, cur_frame.rows));
outImg_right = img_merge(cv::Rect(0, cur_frame.rows, cur_frame1.cols, cur_frame1.rows));
//3.将待拷贝图像拷贝到感性趣区域中
cur_frame.copyTo(outImg_left);
cur_frame1.copyTo(outImg_right);
return img_merge;
}
bool isBestValue(const Mat &c1, const int r1, const Mat &c2, const int r2)
{
for (int i = r1 - 1; i > r1 - 7; --i) {
for (int j = r2 + 1; j < r2 + 7; ++j) {
if(!CompareRowsData(c1, i, c2, j)) {
return false;
}
}
}
return true;
}
void getPicture(const Mat &c1, const Mat &c2, Rect &r1, Rect &r2)
{
if(c1.cols != c2.cols)
return;
for (int i = c1.rows - 1; i >= 0; --i) {
for (int j = 0; j < c2.rows; ++j) {
if(CompareRowsData(c1, i, c2, j)) {
qDebug() << i << j << "sssssssss";
r1 = Rect(0, 0, c1.cols, i);
r2 = Rect(0, j, c2.cols, c2.rows - j);
//if(isBestValue(c1, i, c2, j)) {
return;
//}
}
}
}
}
const int COM_ROW = 5;
// 提取两张图片的变化区域
// 拼接变化区域
void test1(QString img1, QString img2)
{
Mat c1;
Mat c2;
getChangeArea(img1, img2, c1, c2);
imshow("c1",c1);
imshow("c2",c2);
Mat pano;
if(mergeImgOpenCV(pano, c1, c2)){
imshow("pano", pano);
}
}
void test2(QString img1, QString img2)
{
Mat c1;
Mat c2;
getChangeArea(img1, img2, c1, c2);
imshow("c1",c1);
imshow("c2",c2);
Mat pano;
if(mergeImg(pano, c1, c2)){
imshow("pano", pano);
}
}
void getLongPictureFormDir(const QString str)
{
QDir dir(str);
if(!dir.exists())
return;
// 过滤出目录下的png格式图片
QString filtername = "*.png";
QStringList filter;
filter << filtername;
dir.setNameFilters(filter);
QStringList temp_file = dir.entryList();
qDebug() << temp_file;
// 图片数小于2不能做拼图
if(temp_file.size() < 2)
return;
// 根据前两张图片,识别出图片滑动区域
vector<Mat> imgs;
Mat img1 = imread((str + "/" + temp_file[0]).toLocal8Bit().data());
Mat img2 = imread((str + "/" + temp_file[1]).toLocal8Bit().data());
Rect rect = getChangeArea(img1, img2);
// 从所有图片中,裁剪出滑动区域。并有序存入imgs中
foreach(QString s , temp_file) {
QString temp = str + "/" + s;
imgs.push_back(getMatByRect(temp, rect));
}
// 采用基于模板匹配的方式依次拼接图象
Mat pano;
pano = imgs[0];
for(int i = 1; i < imgs.size(); ++i) {
pano = ImageMerger::getMerageImageBasedOnTemplate1(pano, imgs[i]);
}
imshow("pano", pano);
// 保存拼接好的图片
imwrite("pano.png", pano);
}
void test4(QString img1, QString img2)
{
Mat c1;
Mat c2;
getChangeArea(img1, img2, c1, c2);
imshow("c1",c1);
imshow("c2",c2);
imwrite("c11.png", c1);
imwrite("c21.png", c2);
Mat merger = ImageMerger::getMerageImageBasedOnTemplate1(c1, c2);
imwrite("merger.png", merger);
imshow("merger", merger);
return;
Rect r1;
Rect r2;
getPicture(c1, c2, r1, r2);
imshow("c11", Mat(c1, r1));
imshow("c21", Mat(c2, r2));
Mat s = getMerageImage2(Mat(c1, r1), Mat(c2, r2));
qDebug() << s.cols << s.rows;
imshow("merger", s);
imwrite((img1 + img2 + ".png").toLocal8Bit().data(), s);
}
void test5(QString img1, QString img2)
{
Mat c1 = imread(img1.toLocal8Bit().data());
Mat c2 = imread(img2.toLocal8Bit().data());
imshow("c11", Mat(c1, Rect(0, 0, 1096, 621)));
imshow("c21", Mat(c2, Rect(0, 291, 1096, 632 - 291 )));
// imshow("merger", getMerageImage(Mat(c1, Rect(0, 0, 1096, 621)), Mat(c2, Rect(0, 291, 1096, 632 - 291 ))));
Mat s = getMerageImage2(Mat(c1, Rect(0, 0, 1096, 621)), Mat(c2, Rect(0, 291, 1096, 632 - 291 )));
qDebug() << s.cols << s.rows;
imshow("merger", s);
//for(int j = 0; j < c1.rows; ++j) {
for(int i = 0; i < c2.rows; ++i) {
if(CompareRowsData(c1, 621, c2, i)){
qDebug() << 621 << i;
}
}
//}
}
// 拼接测试
void test6()
{
Mat img = imread("s");
Mat img1 = imread("r");
// 横向拼接
//Mat imgout = get_merage_image(img, img1);
// 纵向拼接
//Mat imgout = getMerageImage(img, img1);
//Mat imgout = ImageMerger::getMerageImageBasedOnTemplate0(img, img1);
Mat imgout = ImageMerger::getMerageImageBasedOnTemplate1(img, img1);
imshow("merge", imgout);
}
int main()
{
QTime time;
time.start();
//getLongPictureFormDir("testImg");
//test1("a.png", "b.png");
//test2("a.png", "b.png");
//test3();
test4("./a1.png", "./a2.png");
//test4("b1.png", "b2.png");
//test6();
//qDebug()<<"time:" << time.elapsed() << "ms";
//test5("c1.png", "c2.png");
//test6();
waitKey(0);
return 0;
}
| 29.036797 | 176 | 0.579426 | [
"vector"
] |
7ef45ae594730a0448301e8b8bfb324297f2886d | 2,576 | cpp | C++ | src/web-server/http_handler_web_public_folder.cpp | freehackquest/backend | f3a370107974beea5580b5d0a0de6c90005daceb | [
"MIT"
] | 9 | 2017-05-20T04:45:51.000Z | 2018-11-13T11:39:18.000Z | src/web-server/http_handler_web_public_folder.cpp | freehackquest/backend | f3a370107974beea5580b5d0a0de6c90005daceb | [
"MIT"
] | 90 | 2017-06-19T18:30:56.000Z | 2018-12-11T03:32:16.000Z | src/web-server/http_handler_web_public_folder.cpp | freehackquest/backend | f3a370107974beea5580b5d0a0de6c90005daceb | [
"MIT"
] | 11 | 2017-10-04T13:18:46.000Z | 2018-11-28T15:20:09.000Z | #include "http_handler_web_public_folder.h"
#include <wsjcpp_core.h>
#include <employ_files.h>
// ----------------------------------------------------------------------
HttpHandlerWebPublicFolder::HttpHandlerWebPublicFolder(const std::string &sWebPublicFolder)
: WsjcppLightWebHttpHandlerBase("web-public-folder") {
TAG = "HttpHandlerWebPublicFolder";
m_sWebPublicFolder = sWebPublicFolder;
}
// ----------------------------------------------------------------------
bool HttpHandlerWebPublicFolder::canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) {
std::string _tag = TAG + "-" + sWorkerId;
// WsjcppLog::warn(_tag, "canHandle: " + pRequest->requestPath());
std::string sRequestPath = pRequest->getRequestPath();
if (!WsjcppCore::dirExists(m_sWebPublicFolder)) {
WsjcppLog::warn(_tag, "Directory '" + m_sWebPublicFolder + "' does not exists");
}
if (sRequestPath.rfind("/public/", 0) == 0) {
return true;
}
return false;
}
// ----------------------------------------------------------------------
bool HttpHandlerWebPublicFolder::handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) {
std::string _tag = TAG + "-" + sWorkerId;
WsjcppLightWebHttpResponse resp(pRequest->getSockFd());
std::string sRequestPath = pRequest->getRequestPath();
sRequestPath = sRequestPath.substr(8); // remove '/public/'
sRequestPath = WsjcppCore::doNormalizePath("/" + sRequestPath);
// TODO redsign this hardcode
std::string sFilename = "";
// if (sRequestPath.rfind("/quests/", 0) == 0) {
auto pEmployFiles = findWsjcppEmploy<EmployFiles>();
ModelQuestFile model;
if (pEmployFiles->findQuestFileByFilePath(sRequestPath, model)) {
// std::string sMessageError = "This file not registered in the system '" + sRequestPath + "'";
// WsjcppLog::err(TAG, sMessageError);
// resp.cacheSec(0).notFound().sendText("<h1>" + sMessageError + "</h1>");
// return true;
sFilename = model.getFileName();
pEmployFiles->updateDownloadsCounter(model);
}
std::string sFilePath = m_sWebPublicFolder + sRequestPath; // TODO check /../ in path
if (!WsjcppCore::fileExists(sFilePath)) {
std::string sMessageError = "File not found '" + sRequestPath + "'";
WsjcppLog::err(TAG, sMessageError);
resp.cacheSec(0).notFound().sendText("<h1>" + sMessageError + "</h1>");
return true;
}
resp.cacheSec(0).ok().sendFile(sFilePath, sFilename);
return true;
}
| 39.630769 | 111 | 0.617236 | [
"model"
] |
7d02122df0d5c3e8cc01ef387e53bf1cd2d87a9a | 9,153 | cpp | C++ | vmss_derecho/hello_world.cpp | xitanggg/Azure-IoT-Service-using-Derecho | f882ec344e766c92e8606fcd241b6ad2e33c8caf | [
"MIT"
] | null | null | null | vmss_derecho/hello_world.cpp | xitanggg/Azure-IoT-Service-using-Derecho | f882ec344e766c92e8606fcd241b6ad2e33c8caf | [
"MIT"
] | null | null | null | vmss_derecho/hello_world.cpp | xitanggg/Azure-IoT-Service-using-Derecho | f882ec344e766c92e8606fcd241b6ad2e33c8caf | [
"MIT"
] | null | null | null | /**
* @file hello_world.cpp
*
* hello_world.cpp creates one subgroup of type Foo (defined in sample_objects.h).
* It requires at least 2 nodes to join the group and they are all part of
* the Foo subgroup. (Can be easily configured to 3 nodes as well)
*
* Every node (identified by its node_id) sends back T2 (T2 = time Derecho
* process group receives TCP request) whenever it receives a TCP client connection.
*
* The first node also increases the foo_state by 1 in its subgroup each time
* it receives a TCP client connection.
*
* The second node also prints "Hello World" and prints the foo_state each time
* it receives a TCP client connection.
*
* Acknowledgement:
* simple_replicated_objects.cpp: https://github.com/Derecho-Project/derecho/blob/master/src/applications/demos/simple_replicated_objects.cpp
* Socket TCP Server in C: https://www.geeksforgeeks.org/socket-programming-cc/
* Print time format in C: https://stackoverflow.com/questions/3673226/how-to-print-time-in-format-2009-08-10-181754-811
*
* Xitang Zhao 2019-06-02
**/
#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include "sample_objects.hpp"
using derecho::ExternalCaller;
using derecho::Replicated;
using std::cout;
using std::endl;
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char** argv) {
//----------------------Begin of Derecho Setup------------------------------
// Read configurations from the command line options as well as the default config file
derecho::Conf::initialize(argc, argv);
//Define subgroup membership using the default subgroup allocator function
//Each Replicated type will have one subgroup and one shard, with two members in the shard
// Use derecho::fixed_even_shards(1,3) for three members group
derecho::SubgroupInfo subgroup_function {derecho::DefaultSubgroupAllocator({
{std::type_index(typeid(Foo)), derecho::one_subgroup_policy(derecho::fixed_even_shards(1,2))}
})};
//Each replicated type needs a factory; this can be used to supply constructor arguments
//for the subgroup's initial state. These must take a PersistentRegistry* argument, but
//in this case we ignore it because the replicated objects aren't persistent.
auto foo_factory = [](persistent::PersistentRegistry*) { return std::make_unique<Foo>(-1); };
derecho::Group<Foo> group(derecho::CallbackSet{}, subgroup_function, nullptr,
std::vector<derecho::view_upcall_t>{},
foo_factory);
cout << "Finished constructing/joining Derecho Group" << endl;
//Now have each node send some updates to the Replicated objects
//The code must be different depending on which subgroup this node is in,
//which we can determine based on which membership list it appears in
uint32_t my_id = derecho::getConfUInt32(CONF_DERECHO_LOCAL_ID);
std::vector<node_id_t> foo_members = group.get_subgroup_members<Foo>(0)[0];
auto find_in_foo_results = std::find(foo_members.begin(), foo_members.end(), my_id);
uint32_t rank_in_foo = std::distance(foo_members.begin(), find_in_foo_results);
Replicated<Foo>& foo_rpc_handle = group.get_subgroup<Foo>();
int foo_state = 0;
//----------------------End of Derecho Setup------------------------------
//-----------------Begin of Time & Socket Setup---------------------------
// Define variables for time info
struct tm* tm_info;
struct timeval tv;
int time_buffer_max_size = 40;
char print_time_buffer[time_buffer_max_size];
std::string T2_string;
char T2_char[time_buffer_max_size];
// Set up socket server for TCP connection
int socket_file_descriptor, new_socket_file_descriptor;
int port_num = 80;
struct sockaddr_in server_address, client_address;
socklen_t client_address_len = sizeof(client_address);
char socket_read_buffer[256];
int opt = 1;
int n;
bzero((char *) &server_address, sizeof(server_address));
bzero(socket_read_buffer,256);
// Create socket descriptor
socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if (socket_file_descriptor < 0) {
perror("ERROR opening socket"); exit(EXIT_FAILURE);
}
// Set socket option (helps in reuse of address and port)
if (setsockopt(socket_file_descriptor, SOL_SOCKET,
SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("ERROR setting socket"); exit(EXIT_FAILURE);
}
// Set and bind socket to address and port number
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(port_num);
if (bind(socket_file_descriptor,
(struct sockaddr *) &server_address,
sizeof(server_address)) < 0){
perror("ERROR on binding"); exit(EXIT_FAILURE);
}
// Put socket in listen mode
listen(socket_file_descriptor, 16);
// Enter while loop to wait for TCP connection and run Derecho
while (true){
bzero(socket_read_buffer,256);
// Establish connection between client and server
new_socket_file_descriptor = accept(socket_file_descriptor,
(struct sockaddr *) &client_address,
&client_address_len);
if (new_socket_file_descriptor < 0){
perror("ERROR on accept"); exit(EXIT_FAILURE);
}
// Get current time T2 (T2 = time Derecho process group receives TCP request)
gettimeofday(&tv, NULL);
tm_info = localtime(&tv.tv_sec);
strftime(print_time_buffer, time_buffer_max_size, "T2:%Y-%m-%d_%H:%M:%S.", tm_info);
T2_string = print_time_buffer+std::to_string(tv.tv_usec)+"_UTC-04:00";
strcpy(T2_char, T2_string.c_str());
//printf("%s\n", T2_char);
// Ignore TCP connection from 168.63.129.16, Azure health probes from Azure load balancer
if (strcmp(inet_ntoa(client_address.sin_addr), "168.63.129.16") == 0){
//printf("Ignore this IP\n");
}
// Take all other TCP connection
else{
//printf("Client's ip address is: %s\n", inet_ntoa(client_address.sin_addr));
// Read data sent by client
n = read(new_socket_file_descriptor, socket_read_buffer, 255);
if (n < 0) {
perror("ERROR reading from socket"); exit(EXIT_FAILURE);
}
//printf("Client's message: %s\n",socket_read_buffer);
// Send T2 (timestamps it receives the message) to client
n = write(new_socket_file_descriptor, T2_char, time_buffer_max_size);
if (n < 0) {
perror("ERROR writing to socket"); exit(EXIT_FAILURE);
}
// Run Derecho group processing if "HelloWorld" message received
if (strcmp(socket_read_buffer, "HelloWorld") == 0){
if(rank_in_foo == 0) {
foo_state += 1;
cout << "Changing Foo's state to " << foo_state << endl;
derecho::rpc::QueryResults<bool> results = foo_rpc_handle.ordered_send<RPC_NAME(change_state)>(foo_state);
decltype(results)::ReplyMap& replies = results.get();
cout << "Got a reply map!" << endl;
for(auto& reply_pair : replies) {
cout << "Reply from node " << reply_pair.first << " was " << std::boolalpha << reply_pair.second.get() << endl;
}
// Reading Foo's state just to allow node 1's message to be delivered
foo_rpc_handle.ordered_send<RPC_NAME(read_state)>();
}
else if(rank_in_foo == 1) {
cout << "Reading Foo's state from the group" << endl;
derecho::rpc::QueryResults<int> foo_results = foo_rpc_handle.ordered_send<RPC_NAME(read_state)>();
for(auto& reply_pair : foo_results.get()) {
cout << "HelloWorld - Node " << reply_pair.first << " says the state is: " << reply_pair.second.get() << endl;
}
}
// Uncomment the following if set up as three members group
/*
else if(rank_in_foo == 2) {
cout << "Reading Foo's state from the group" << endl;
derecho::rpc::QueryResults<int> foo_results = foo_rpc_handle.ordered_send<RPC_NAME(read_state)>();
for(auto& reply_pair : foo_results.get()) {
cout << "Node " << reply_pair.first << " says the state is: " << reply_pair.second.get() << endl;
}
}
*/
}
}
// Loop back in a while loop for the next TCP connection
}
close(new_socket_file_descriptor);
close(socket_file_descriptor);
}
| 45.08867 | 141 | 0.626898 | [
"vector"
] |
7d05bcc2df19046e1ce43c7c00f1966a908afc10 | 1,614 | cpp | C++ | genlipsum/genlipsum.cpp | elementbound/automata | 719b4994c0ea87a326c38e14c8a6bec667509335 | [
"MIT"
] | null | null | null | genlipsum/genlipsum.cpp | elementbound/automata | 719b4994c0ea87a326c38e14c8a6bec667509335 | [
"MIT"
] | null | null | null | genlipsum/genlipsum.cpp | elementbound/automata | 719b4994c0ea87a326c38e14c8a6bec667509335 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <cstdlib> //atoi, exit
#include <cctype>
#define die(msg) {std::cerr << msg << '\n'; exit(1);}
int main(int argc, char** argv)
{
if(argc < 4)
die("Usage: " << argv[0] << " <wordset file> <output size> <output file>");
const char* words_file = argv[1];
unsigned output_size = atoi(argv[2]);
const char* output_file = argv[3];
std::ifstream fis(words_file);
std::ofstream fos(output_file, std::ios::trunc);
if(!fis)
die("Couldn't open wordset file: " << words_file);
if(!fos)
die("Couldn't open output file: " << output_file);
std::set<std::string> wordset_unique;
while(fis.good())
{
std::string word;
fis >> word;
word.erase(std::remove_if(word.begin(), word.end(),
[](char c) -> bool {
return (!isalnum(c) || isspace(c) || ispunct(c));}
), word.end());
std::transform(word.begin(), word.end(), word.begin(),
[](char c) -> char {
return tolower(c);
}
);
if(!word.empty())
wordset_unique.insert(word);
}
std::vector<std::string> wordset_rand;
wordset_rand.reserve(wordset_unique.size());
for(const std::string& word: wordset_unique)
wordset_rand.push_back(word);
std::default_random_engine rng;
rng.seed(std::chrono::system_clock::now().time_since_epoch().count());
for(unsigned size=0; size < output_size; )
{
unsigned word_id = rng() % wordset_rand.size();
fos << wordset_rand[word_id] << " ";
size += wordset_rand[word_id].length() + 1;
}
return 0;
} | 23.057143 | 77 | 0.637546 | [
"vector",
"transform"
] |
7d171e68de6b1dac8fa0f16e7b1b5f923119d199 | 1,418 | cpp | C++ | 1036.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | 1036.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | 1036.cpp | hgfeaon/PAT | 3210bdab10eba77b69cdfb7a3c68638f9b7af5ac | [
"BSD-3-Clause"
] | null | null | null | #include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
class Stu {
public:
char name[12];
char id[12];
int grade;
char gender;
};
bool my_cmp(const Stu* a, const Stu* b) {
return a->grade < b->grade;
}
void print (vector<Stu*> &stu) {
int len = stu.size();
for (int i=0; i<len; i++) {
printf("%s %d\n", stu[i]->name, stu[i]->grade);
}
}
int main() {
vector<Stu*> male;
vector<Stu*> female;
int n = 0;
scanf("%d", &n);
for (int i=0; i<n; i++) {
Stu* p = new Stu();
scanf("%s %c %s %d", p->name, &(p->gender), p->id, &(p->grade));
if (p->gender == 'M') {
male.push_back(p);
} else {
female.push_back(p);
}
}
sort(male.begin(), male.end(), my_cmp);
sort(female.begin(), female.end(), my_cmp);
Stu* best = NULL;
Stu* worst= NULL;
if (female.empty()) {
printf("Absent\n");
} else {
best = female[female.size() - 1];
printf("%s %s\n", best->name, best->id);
}
if (male.empty()) {
printf("Absent\n");
} else {
worst = male[0];
printf("%s %s\n", worst->name, worst->id);
}
if (worst == NULL || best == NULL) {
printf("NA\n");
} else {
printf("%d", best->grade - worst->grade);
}
return 0;
}
| 20.550725 | 72 | 0.470381 | [
"vector"
] |
7d19303c31f4f71362eadcaf24083d6d4482e881 | 1,614 | hpp | C++ | include/FoundObject.hpp | bas200o/fenceless-robotics | 7c7592c079f406a65aba034c17f70b1159cb79f3 | [
"Apache-2.0"
] | null | null | null | include/FoundObject.hpp | bas200o/fenceless-robotics | 7c7592c079f406a65aba034c17f70b1159cb79f3 | [
"Apache-2.0"
] | 1 | 2021-12-16T12:55:40.000Z | 2021-12-16T13:10:04.000Z | include/FoundObject.hpp | bas200o/fenceless-robotics | 7c7592c079f406a65aba034c17f70b1159cb79f3 | [
"Apache-2.0"
] | null | null | null | /*Objects class for found objects in pointcloud*/
#pragma once
#include <tuple>
#include <vector>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/common/distances.h>
#include <cmath>
class FoundObject
{
private:
//Point with the location/centermass of the FoundObject
pcl::PointXYZRGB location;
//The longest size of an object
float size = 0;
double speed = -1;
//The centermass of the object
std::tuple<float, float, float> centerMass;
//The pointcloud of the object
pcl::PointCloud<pcl::PointXYZRGB> objectCloud;
//Calculates the size and location of the object
void CalculateValues();
//
int identificationNumber;
//
float directionHor = 0, directionVer = 0, direction;
public:
//Constructor
FoundObject(pcl::PointCloud<pcl::PointXYZRGB> objectCloud);
FoundObject();
//Destructor
~FoundObject();
void setSpeed(double sp);
double getSpeed();
pcl::PointCloud<pcl::PointXYZRGB> getObjectCloud();
pcl::PointXYZRGB getLocation();
std::tuple<float, float, float> getCenterMass();
float getSize();
void setIdentificationNumber(int number);
int getIdentificationNumber();
float getDirectionVer();
float getDirectionHor();
void setDirectionHor(float x);
void setDirectionVer(float y);
void setDirection(double idk);
};
| 25.619048 | 67 | 0.612763 | [
"object",
"vector"
] |
7d21b34c046beac140499aab0c5910a9f5751c0e | 14,297 | cpp | C++ | src/Yace/chip8.cpp | comfyneet/Yace | b5cc65fd3d3d1626786f65939a4e1572b5b099e6 | [
"MIT"
] | null | null | null | src/Yace/chip8.cpp | comfyneet/Yace | b5cc65fd3d3d1626786f65939a4e1572b5b099e6 | [
"MIT"
] | null | null | null | src/Yace/chip8.cpp | comfyneet/Yace | b5cc65fd3d3d1626786f65939a4e1572b5b099e6 | [
"MIT"
] | null | null | null | #include "Yace/chip8.hpp"
#include <random>
namespace priv
{
uint8_t generate_random_number(uint8_t min, uint8_t max);
std::mt19937 mersenne_twister{std::random_device()()};
std::array<uint8_t, 16 * 5> const fontset = std::array<uint8_t, 80>
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
}
namespace ye
{
uint32_t const chip8::height = 32;
uint32_t const chip8::width = 64;
chip8::chip8() :
redraw_flag(false),
sound_flag(false),
graphics({0}),
keys({0}),
opcode_(0),
memory_({0}),
registers_({0}),
stack_({0}),
address_register_(0),
pc_(0),
delay_timer_(0),
sound_timer_(0),
stack_ptr_(0)
{
}
void chip8::load(std::vector<uint8_t> const& buffer)
{
redraw_flag = true;
sound_flag = false;
graphics.fill(0);
keys.fill(0);
opcode_ = 0;
memory_.fill(0);
registers_.fill(0);
address_register_ = 0;
pc_ = 0x200; // program memory location starts at 0x200
delay_timer_ = 0;
sound_timer_ = 0;
stack_.fill(0);
stack_ptr_ = 0;
std::copy(priv::fontset.begin(), priv::fontset.end(), memory_.begin());
std::copy(buffer.begin(), buffer.end(), memory_.begin() + 0x200); // program memory location starts at 0x200
}
void chip8::emulate_cycle()
{
// Fetch opcode
opcode_ = memory_[pc_] << 8 | memory_[pc_ + 1];
//YACE_LOG("\t%x\n", opcode_);
// Decode & execute opcode
// nnn or addr - A 12-bit value, the lowest 12 bits of the instruction
// n or nibble - A 4-bit value, the lowest 4 bits of the instruction
// x - A 4-bit value, the lower 4 bits of the high uint8_t of the instruction
// y - A 4-bit value, the upper 4 bits of the low uint8_t of the instruction
// kk or uint8_t - An 8-bit value, the lowest 8 bits of the instruction
// 00E0 - CLS
// Clear the display.
if (opcode_ == 0x00E0)
{
graphics.fill(0);
redraw_flag = true;
pc_ += 2;
}
// 00EE - RET
// Return from a subroutine.
else if (opcode_ == 0x00EE)
{
--stack_ptr_;
pc_ = stack_[stack_ptr_];
pc_ += 2;
}
// 1nnn - JP addr
// Jump to location nnn.
else if ((opcode_ & 0xF000) == 0x1000)
pc_ = opcode_ & 0x0FFF;
// 2nnn - CALL addr
// Calls subroutine at nnn.
else if ((opcode_ & 0xF000) == 0x2000)
{
stack_[stack_ptr_] = pc_;
++stack_ptr_;
pc_ = opcode_ & 0x0FFF;
}
// 3xkk - SE Vx, uint8_t
// Skip next instruction if Vx = kk.
else if ((opcode_ & 0xF000) == 0x3000)
if (registers_[(opcode_ & 0x0F00) >> 8] == (opcode_ & 0x00FF))
pc_ += 4;
else
pc_ += 2;
// 4xkk - SNE Vx, uint8_t
// Skip next instruction if Vx != kk.
else if ((opcode_ & 0xF000) == 0x4000)
if (registers_[(opcode_ & 0x0F00) >> 8] != (opcode_ & 0x00FF))
pc_ += 4;
else
pc_ += 2;
// 5xy0 - SE Vx, Vy
// Skip next instruction if Vx = Vy.
else if ((opcode_ & 0xF00F) == 0x5000)
if (registers_[(opcode_ & 0x0F00) >> 8] == registers_[(opcode_ & 0x00F0) >> 4])
pc_ += 4;
else
pc_ += 2;
// 6xkk - LD Vx, uint8_t
// Set Vx = kk.
else if ((opcode_ & 0xF000) == 0x6000)
{
registers_[(opcode_ & 0x0F00) >> 8] = opcode_ & 0x00FF;
pc_ += 2;
}
// 7xkk - ADD Vx, uint8_t
// Set Vx = Vx + kk.
else if ((opcode_ & 0xF000) == 0x7000)
{
registers_[(opcode_ & 0x0F00) >> 8] += opcode_ & 0x00FF;
pc_ += 2;
}
// 8xy0 - LD Vx, Vy
// Set Vx = Vy.
else if ((opcode_ & 0xF00F) == 0x8000)
{
registers_[(opcode_ & 0x0F00) >> 8] = registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy1 - OR Vx, Vy
// Set Vx = Vx OR Vy.
else if ((opcode_ & 0xF00F) == 0x8001)
{
registers_[(opcode_ & 0x0F00) >> 8] |= registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy2 - AND Vx, Vy
// Set Vx = Vx AND Vy.
else if ((opcode_ & 0xF00F) == 0x8002)
{
registers_[(opcode_ & 0x0F00) >> 8] &= registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy3 - XOR Vx, Vy
// Set Vx = Vx XOR Vy.
else if ((opcode_ & 0xF00F) == 0x8003)
{
registers_[(opcode_ & 0x0F00) >> 8] ^= registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy4 - ADD Vx, Vy
// Set Vx = Vx + Vy, set VF = carry.
else if ((opcode_ & 0xF00F) == 0x8004)
{
if (registers_[(opcode_ & 0x0F00) >> 8] + registers_[(opcode_ & 0x00F0) >> 4] > 0xFF)
registers_[0xF] = 1;
else
registers_[0xF] = 0;
registers_[(opcode_ & 0x0F00) >> 8] += registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy5 - SUB Vx, Vy
// Set Vx = Vx - Vy, set VF = NOT borrow.
else if ((opcode_ & 0xF00F) == 0x8005)
{
if (registers_[(opcode_ & 0x0F00) >> 8] > registers_[(opcode_ & 0x00F0) >> 4])
registers_[0xF] = 1;
else
registers_[0xF] = 0;
registers_[(opcode_ & 0x0F00) >> 8] -= registers_[(opcode_ & 0x00F0) >> 4];
pc_ += 2;
}
// 8xy6 - SHR Vx {, Vy}
// Set Vx = Vx SHR 1.
else if ((opcode_ & 0xF00F) == 0x8006)
{
registers_[0xF] = registers_[(opcode_ & 0x0F00) >> 8] & 0x01;
registers_[(opcode_ & 0x0F00) >> 8] >>= 1;
pc_ += 2;
}
// 8xy7 - SUBN Vx, Vy
// Set Vx = Vy - Vx, set VF = NOT borrow.
else if ((opcode_ & 0xF00F) == 0x8007)
{
if (registers_[(opcode_ & 0x00F0) >> 4] > registers_[(opcode_ & 0x0F00) >> 8])
registers_[0xF] = 1;
else
registers_[0xF] = 0;
registers_[(opcode_ & 0x0F00) >> 8] = registers_[(opcode_ & 0x00F0) >> 4] - registers_[(opcode_ & 0x0F00) >>
8];
pc_ += 2;
}
// 8xyE - SHL Vx {, Vy}
// Set Vx = Vx SHL 1.
else if ((opcode_ & 0xF00F) == 0x800E)
{
registers_[0xF] = registers_[(opcode_ & 0x0F00) >> 8] >> 7;
registers_[(opcode_ & 0x0F00) >> 8] <<= 1;
pc_ += 2;
}
// 9xy0 - SNE Vx, Vy
// Skip next instruction if Vx != Vy.
else if ((opcode_ & 0xF00F) == 0x9000)
{
if (registers_[(opcode_ & 0x0F00) >> 8] != registers_[(opcode_ & 0x00F0) >> 4])
pc_ += 4;
else
pc_ += 2;
}
// Annn - LD I, addr
// Set I = nnn.
else if ((opcode_ & 0xF000) == 0xA000)
{
address_register_ = opcode_ & 0x0FFF;
pc_ += 2;
}
// Bnnn - JP V0, addr
// Jump to location nnn + V0.
else if ((opcode_ & 0xF000) == 0xB000)
pc_ = (opcode_ & 0x0FFF) + registers_[0x0];
// Cxkk - RND Vx, uint8_t
// Set Vx = random uint8_t AND kk.
else if ((opcode_ & 0xF000) == 0xC000)
{
registers_[(opcode_ & 0x0F00) >> 8] = priv::generate_random_number(0x00, 0xFF) & (opcode_ & 0x00FF);
pc_ += 2;
}
// Dxyn - DRW Vx, Vy, nibble
// Display n - uint8_t sprite starting at memory location I at(Vx, Vy), set VF = collision.
else if ((opcode_ & 0xF000) == 0xD000)
{
const uint16_t x = registers_[(opcode_ & 0x0F00) >> 8];
const uint16_t y = registers_[(opcode_ & 0x00F0) >> 4];
const uint32_t x_width = 8;
const uint32_t y_height = opcode_ & 0x000F;
registers_[0xF] = 0;
for (uint32_t y_line = 0; y_line < y_height; ++y_line)
{
const uint16_t pixel = memory_[address_register_ + y_line];
for (uint32_t x_line = 0; x_line < x_width; ++x_line)
// Check if the current evaluated pixel is set to 1
if ((pixel & (0x80 >> x_line)) != 0)
// Prevent "array subscript out of range" error
if (x + x_line + ((y + y_line) * width) < graphics.size())
{
// Check if the pixel on the display is set to 1
if (graphics[x + x_line + ((y + y_line) * width)] == 1)
registers_[0xF] = 1;
graphics[x + x_line + ((y + y_line) * width)] ^= 1;
}
}
redraw_flag = true;
pc_ += 2;
}
// Ex9E - SKP Vx
// Skip next instruction if key with the value of Vx is pressed.
else if ((opcode_ & 0xF0FF) == 0xE09E)
if (keys[registers_[(opcode_ & 0x0F00) >> 8]] != 0)
pc_ += 4;
else
pc_ += 2;
// ExA1 - SKNP Vx
// Skip next instruction if key with the value of Vx is not pressed.
else if ((opcode_ & 0xF0FF) == 0xE0A1)
if (keys[registers_[(opcode_ & 0x0F00) >> 8]] == 0)
pc_ += 4;
else
pc_ += 2;
// Fx07 - LD Vx, DT
// Set Vx = delay timer value.
else if ((opcode_ & 0xF0FF) == 0xF007)
{
registers_[(opcode_ & 0x0F00) >> 8] = delay_timer_;
pc_ += 2;
}
// Fx0A - LD Vx, K
// Wait for a key press, store the value of the key in Vx.
else if ((opcode_ & 0xF0FF) == 0xF00A)
{
auto key_press = false;
for (size_t i = 0; i < keys.size(); ++i)
{
if (keys[i] != 0)
{
registers_[(opcode_ & 0x0F00) >> 8] = static_cast<uint8_t>(i);
key_press = true;
}
}
if (!key_press)
return;
pc_ += 2;
}
// Fx15 - LD DT, Vx
// Set delay timer = Vx.
else if ((opcode_ & 0xF0FF) == 0xF015)
{
delay_timer_ = registers_[(opcode_ & 0x0F00) >> 8];
pc_ += 2;
}
// Fx18 - LD ST, Vx
// Set sound timer = Vx.
else if ((opcode_ & 0xF0FF) == 0xF018)
{
sound_timer_ = registers_[(opcode_ & 0x0F00) >> 8];
pc_ += 2;
}
// Fx1E - ADD I, Vx
// Set I = I + Vx.
else if ((opcode_ & 0xF0FF) == 0xF01E)
{
if (address_register_ + registers_[(opcode_ & 0x0F00) >> 8] > 0x0FFF)
registers_[0xF] = 1;
else
registers_[0xF] = 0;
address_register_ += registers_[(opcode_ & 0x0F00) >> 8];
pc_ += 2;
}
// Fx29 - LD F, Vx
//Set I = location of sprite for digit Vx.
else if ((opcode_ & 0xF0FF) == 0xF029)
{
address_register_ = registers_[((opcode_ & 0x0F00) >> 8)] * 0x5;
pc_ += 2;
}
// Fx33 - LD B, Vx
// Store BCD representation of Vx in memory locations I, I + 1, and I + 2.
else if ((opcode_ & 0xF0FF) == 0xF033)
{
memory_[address_register_] = registers_[(opcode_ & 0x0F00) >> 8] / 100;
memory_[address_register_ + 1] = (registers_[(opcode_ & 0x0F00) >> 8] / 10) % 10;
memory_[address_register_ + 2] = (registers_[(opcode_ & 0x0F00) >> 8] % 100) % 10;
pc_ += 2;
}
// Fx55 - LD [I], Vx
// Store registers V0 through Vx in memory starting at location I.
else if ((opcode_ & 0xF0FF) == 0xF055)
{
for (size_t i = 0x0; i <= ((opcode_ & 0x0F00) >> 8); ++i)
memory_[address_register_ + i] = registers_[i];
pc_ += 2;
}
// Fx65 - LD Vx, [I]
// Read registers V0 through Vx from memory starting at location I.
else if ((opcode_ & 0xF0FF) == 0xF065)
{
for (size_t i = 0x0; i <= ((opcode_ & 0x0F00) >> 8); ++i)
registers_[i] = memory_[address_register_ + i];
pc_ += 2;
}
else
throw std::runtime_error("Chip8: Failed to decode opcode.");
if (delay_timer_ > 0)
--delay_timer_;
if (sound_timer_ > 0)
{
if (sound_timer_ == 1)
sound_flag = true;
--sound_timer_;
}
}
uint16_t chip8::get_opcode() const
{
return opcode_;
}
}
namespace priv
{
uint8_t generate_random_number(uint8_t const min, uint8_t const max)
{
const std::uniform_int_distribution<uint32_t> distribution(min, max);
return static_cast<uint8_t>(distribution(mersenne_twister));
}
}
| 32.273138 | 120 | 0.45527 | [
"vector"
] |
7d255bee261bd43cf0ccf3b9a7b61999e709dc13 | 413,942 | cpp | C++ | pywinrt/winsdk/src/py.Windows.Data.Xml.Dom.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 3 | 2022-02-14T14:53:08.000Z | 2022-03-29T20:48:54.000Z | pywinrt/winsdk/src/py.Windows.Data.Xml.Dom.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 4 | 2022-01-28T02:53:52.000Z | 2022-02-26T18:10:05.000Z | pywinrt/winsdk/src/py.Windows.Data.Xml.Dom.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | null | null | null | // WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4
#include "pybase.h"
#include "py.Windows.Data.Xml.Dom.h"
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::DtdEntity>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::DtdNotation>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlAttribute>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlCDataSection>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlComment>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocument>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocumentFragment>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocumentType>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDomImplementation>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlElement>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlEntityReference>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlNamedNodeMap>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlNodeList>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlProcessingInstruction>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlText>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlCharacterData>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNode>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNodeSelector>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNodeSerializer>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlText>::python_type;
namespace py::cpp::Windows::Data::Xml::Dom
{
// ----- DtdEntity class --------------------
constexpr const char* const _type_name_DtdEntity = "DtdEntity";
static PyObject* _new_DtdEntity(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_DtdEntity);
return nullptr;
}
static void _dealloc_DtdEntity(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* DtdEntity_AppendChild(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_CloneNode(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_GetXml(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_Normalize(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdEntity_get_NotationName(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NotationName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_PublicId(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PublicId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_SystemId(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SystemId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdEntity_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* DtdEntity_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdEntity_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* DtdEntity_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdEntity_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdEntity_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::DtdEntity* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_DtdEntity(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::DtdEntity>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_DtdEntity[] = {
{ "append_child", reinterpret_cast<PyCFunction>(DtdEntity_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(DtdEntity_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(DtdEntity_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(DtdEntity_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(DtdEntity_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(DtdEntity_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(DtdEntity_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(DtdEntity_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(DtdEntity_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(DtdEntity_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(DtdEntity_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(DtdEntity_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_DtdEntity), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_DtdEntity[] = {
{ "notation_name", reinterpret_cast<getter>(DtdEntity_get_NotationName), nullptr, nullptr, nullptr },
{ "public_id", reinterpret_cast<getter>(DtdEntity_get_PublicId), nullptr, nullptr, nullptr },
{ "system_id", reinterpret_cast<getter>(DtdEntity_get_SystemId), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(DtdEntity_get_Prefix), reinterpret_cast<setter>(DtdEntity_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(DtdEntity_get_NodeValue), reinterpret_cast<setter>(DtdEntity_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(DtdEntity_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(DtdEntity_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(DtdEntity_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(DtdEntity_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(DtdEntity_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(DtdEntity_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(DtdEntity_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(DtdEntity_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(DtdEntity_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(DtdEntity_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(DtdEntity_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(DtdEntity_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(DtdEntity_get_InnerText), reinterpret_cast<setter>(DtdEntity_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_DtdEntity[] =
{
{ Py_tp_new, _new_DtdEntity },
{ Py_tp_dealloc, _dealloc_DtdEntity },
{ Py_tp_methods, _methods_DtdEntity },
{ Py_tp_getset, _getset_DtdEntity },
{ },
};
static PyType_Spec _type_spec_DtdEntity =
{
"_winsdk_Windows_Data_Xml_Dom.DtdEntity",
sizeof(py::wrapper::Windows::Data::Xml::Dom::DtdEntity),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_DtdEntity
};
// ----- DtdNotation class --------------------
constexpr const char* const _type_name_DtdNotation = "DtdNotation";
static PyObject* _new_DtdNotation(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_DtdNotation);
return nullptr;
}
static void _dealloc_DtdNotation(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* DtdNotation_AppendChild(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_CloneNode(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_GetXml(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_Normalize(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* DtdNotation_get_PublicId(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PublicId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_SystemId(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SystemId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdNotation_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* DtdNotation_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdNotation_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* DtdNotation_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* DtdNotation_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int DtdNotation_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::DtdNotation* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_DtdNotation(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::DtdNotation>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_DtdNotation[] = {
{ "append_child", reinterpret_cast<PyCFunction>(DtdNotation_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(DtdNotation_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(DtdNotation_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(DtdNotation_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(DtdNotation_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(DtdNotation_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(DtdNotation_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(DtdNotation_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(DtdNotation_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(DtdNotation_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(DtdNotation_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(DtdNotation_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_DtdNotation), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_DtdNotation[] = {
{ "public_id", reinterpret_cast<getter>(DtdNotation_get_PublicId), nullptr, nullptr, nullptr },
{ "system_id", reinterpret_cast<getter>(DtdNotation_get_SystemId), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(DtdNotation_get_Prefix), reinterpret_cast<setter>(DtdNotation_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(DtdNotation_get_NodeValue), reinterpret_cast<setter>(DtdNotation_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(DtdNotation_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(DtdNotation_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(DtdNotation_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(DtdNotation_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(DtdNotation_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(DtdNotation_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(DtdNotation_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(DtdNotation_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(DtdNotation_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(DtdNotation_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(DtdNotation_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(DtdNotation_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(DtdNotation_get_InnerText), reinterpret_cast<setter>(DtdNotation_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_DtdNotation[] =
{
{ Py_tp_new, _new_DtdNotation },
{ Py_tp_dealloc, _dealloc_DtdNotation },
{ Py_tp_methods, _methods_DtdNotation },
{ Py_tp_getset, _getset_DtdNotation },
{ },
};
static PyType_Spec _type_spec_DtdNotation =
{
"_winsdk_Windows_Data_Xml_Dom.DtdNotation",
sizeof(py::wrapper::Windows::Data::Xml::Dom::DtdNotation),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_DtdNotation
};
// ----- XmlAttribute class --------------------
constexpr const char* const _type_name_XmlAttribute = "XmlAttribute";
static PyObject* _new_XmlAttribute(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlAttribute);
return nullptr;
}
static void _dealloc_XmlAttribute(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlAttribute_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlAttribute_get_Value(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Value());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlAttribute_put_Value(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Value(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlAttribute_get_Specified(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Specified());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_Name(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Name());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlAttribute_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlAttribute_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlAttribute_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlAttribute_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlAttribute_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlAttribute_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlAttribute(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlAttribute>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlAttribute[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlAttribute_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlAttribute_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlAttribute_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlAttribute_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlAttribute_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlAttribute_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlAttribute_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlAttribute_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlAttribute_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlAttribute_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlAttribute_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlAttribute_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlAttribute), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlAttribute[] = {
{ "value", reinterpret_cast<getter>(XmlAttribute_get_Value), reinterpret_cast<setter>(XmlAttribute_put_Value), nullptr, nullptr },
{ "specified", reinterpret_cast<getter>(XmlAttribute_get_Specified), nullptr, nullptr, nullptr },
{ "name", reinterpret_cast<getter>(XmlAttribute_get_Name), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlAttribute_get_Prefix), reinterpret_cast<setter>(XmlAttribute_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlAttribute_get_NodeValue), reinterpret_cast<setter>(XmlAttribute_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlAttribute_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlAttribute_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlAttribute_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlAttribute_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlAttribute_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlAttribute_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlAttribute_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlAttribute_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlAttribute_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlAttribute_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlAttribute_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlAttribute_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlAttribute_get_InnerText), reinterpret_cast<setter>(XmlAttribute_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlAttribute[] =
{
{ Py_tp_new, _new_XmlAttribute },
{ Py_tp_dealloc, _dealloc_XmlAttribute },
{ Py_tp_methods, _methods_XmlAttribute },
{ Py_tp_getset, _getset_XmlAttribute },
{ },
};
static PyType_Spec _type_spec_XmlAttribute =
{
"_winsdk_Windows_Data_Xml_Dom.XmlAttribute",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlAttribute),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlAttribute
};
// ----- XmlCDataSection class --------------------
constexpr const char* const _type_name_XmlCDataSection = "XmlCDataSection";
static PyObject* _new_XmlCDataSection(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlCDataSection);
return nullptr;
}
static void _dealloc_XmlCDataSection(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlCDataSection_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_AppendData(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.AppendData(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_DeleteData(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
self->obj.DeleteData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_InsertData(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.InsertData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_ReplaceData(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.ReplaceData(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SplitText(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.SplitText(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_SubstringData(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
return py::convert(self->obj.SubstringData(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlCDataSection_get_Data(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlCDataSection_put_Data(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlCDataSection_get_Length(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlCDataSection_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlCDataSection_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlCDataSection_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlCDataSection_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlCDataSection_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlCDataSection_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlCDataSection(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlCDataSection>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlCDataSection[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlCDataSection_AppendChild), METH_VARARGS, nullptr },
{ "append_data", reinterpret_cast<PyCFunction>(XmlCDataSection_AppendData), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlCDataSection_CloneNode), METH_VARARGS, nullptr },
{ "delete_data", reinterpret_cast<PyCFunction>(XmlCDataSection_DeleteData), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlCDataSection_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlCDataSection_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlCDataSection_InsertBefore), METH_VARARGS, nullptr },
{ "insert_data", reinterpret_cast<PyCFunction>(XmlCDataSection_InsertData), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlCDataSection_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlCDataSection_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlCDataSection_ReplaceChild), METH_VARARGS, nullptr },
{ "replace_data", reinterpret_cast<PyCFunction>(XmlCDataSection_ReplaceData), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlCDataSection_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlCDataSection_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlCDataSection_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlCDataSection_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "split_text", reinterpret_cast<PyCFunction>(XmlCDataSection_SplitText), METH_VARARGS, nullptr },
{ "substring_data", reinterpret_cast<PyCFunction>(XmlCDataSection_SubstringData), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlCDataSection), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlCDataSection[] = {
{ "data", reinterpret_cast<getter>(XmlCDataSection_get_Data), reinterpret_cast<setter>(XmlCDataSection_put_Data), nullptr, nullptr },
{ "length", reinterpret_cast<getter>(XmlCDataSection_get_Length), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlCDataSection_get_Prefix), reinterpret_cast<setter>(XmlCDataSection_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlCDataSection_get_NodeValue), reinterpret_cast<setter>(XmlCDataSection_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlCDataSection_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlCDataSection_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlCDataSection_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlCDataSection_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlCDataSection_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlCDataSection_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlCDataSection_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlCDataSection_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlCDataSection_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlCDataSection_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlCDataSection_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlCDataSection_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlCDataSection_get_InnerText), reinterpret_cast<setter>(XmlCDataSection_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlCDataSection[] =
{
{ Py_tp_new, _new_XmlCDataSection },
{ Py_tp_dealloc, _dealloc_XmlCDataSection },
{ Py_tp_methods, _methods_XmlCDataSection },
{ Py_tp_getset, _getset_XmlCDataSection },
{ },
};
static PyType_Spec _type_spec_XmlCDataSection =
{
"_winsdk_Windows_Data_Xml_Dom.XmlCDataSection",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlCDataSection),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlCDataSection
};
// ----- XmlComment class --------------------
constexpr const char* const _type_name_XmlComment = "XmlComment";
static PyObject* _new_XmlComment(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlComment);
return nullptr;
}
static void _dealloc_XmlComment(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlComment_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_AppendData(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.AppendData(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_DeleteData(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
self->obj.DeleteData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_InsertData(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.InsertData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_ReplaceData(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.ReplaceData(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_SubstringData(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
return py::convert(self->obj.SubstringData(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlComment_get_Data(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlComment_put_Data(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlComment_get_Length(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlComment_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlComment_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlComment_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlComment_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlComment_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlComment_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlComment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlComment(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlComment>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlComment[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlComment_AppendChild), METH_VARARGS, nullptr },
{ "append_data", reinterpret_cast<PyCFunction>(XmlComment_AppendData), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlComment_CloneNode), METH_VARARGS, nullptr },
{ "delete_data", reinterpret_cast<PyCFunction>(XmlComment_DeleteData), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlComment_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlComment_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlComment_InsertBefore), METH_VARARGS, nullptr },
{ "insert_data", reinterpret_cast<PyCFunction>(XmlComment_InsertData), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlComment_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlComment_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlComment_ReplaceChild), METH_VARARGS, nullptr },
{ "replace_data", reinterpret_cast<PyCFunction>(XmlComment_ReplaceData), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlComment_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlComment_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlComment_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlComment_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "substring_data", reinterpret_cast<PyCFunction>(XmlComment_SubstringData), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlComment), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlComment[] = {
{ "data", reinterpret_cast<getter>(XmlComment_get_Data), reinterpret_cast<setter>(XmlComment_put_Data), nullptr, nullptr },
{ "length", reinterpret_cast<getter>(XmlComment_get_Length), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlComment_get_Prefix), reinterpret_cast<setter>(XmlComment_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlComment_get_NodeValue), reinterpret_cast<setter>(XmlComment_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlComment_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlComment_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlComment_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlComment_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlComment_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlComment_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlComment_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlComment_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlComment_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlComment_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlComment_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlComment_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlComment_get_InnerText), reinterpret_cast<setter>(XmlComment_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlComment[] =
{
{ Py_tp_new, _new_XmlComment },
{ Py_tp_dealloc, _dealloc_XmlComment },
{ Py_tp_methods, _methods_XmlComment },
{ Py_tp_getset, _getset_XmlComment },
{ },
};
static PyType_Spec _type_spec_XmlComment =
{
"_winsdk_Windows_Data_Xml_Dom.XmlComment",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlComment),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlComment
};
// ----- XmlDocument class --------------------
constexpr const char* const _type_name_XmlDocument = "XmlDocument";
static PyObject* _new_XmlDocument(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::Data::Xml::Dom::XmlDocument instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_XmlDocument(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlDocument_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateAttribute(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateAttribute(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateAttributeNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.CreateAttributeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateCDataSection(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateCDataSection(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateComment(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateComment(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateDocumentFragment(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.CreateDocumentFragment());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateElement(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateElement(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateElementNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.CreateElementNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateEntityReference(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateEntityReference(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateProcessingInstruction(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.CreateProcessingInstruction(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_CreateTextNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateTextNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_GetElementById(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetElementById(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_GetElementsByTagName(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetElementsByTagName(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_ImportNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<bool>(args, 1);
return py::convert(self->obj.ImportNode(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_LoadFromFileAsync(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::IStorageFile>(args, 0);
return py::convert(winrt::Windows::Data::Xml::Dom::XmlDocument::LoadFromFileAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::IStorageFile>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>(args, 1);
return py::convert(winrt::Windows::Data::Xml::Dom::XmlDocument::LoadFromFileAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_LoadFromUriAsync(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::Uri>(args, 0);
return py::convert(winrt::Windows::Data::Xml::Dom::XmlDocument::LoadFromUriAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::Uri>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>(args, 1);
return py::convert(winrt::Windows::Data::Xml::Dom::XmlDocument::LoadFromUriAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_LoadXml(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.LoadXml(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>(args, 1);
self->obj.LoadXml(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_LoadXmlFromBuffer(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::Streams::IBuffer>(args, 0);
self->obj.LoadXmlFromBuffer(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::Streams::IBuffer>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>(args, 1);
self->obj.LoadXmlFromBuffer(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_SaveToFileAsync(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::IStorageFile>(args, 0);
return py::convert(self->obj.SaveToFileAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocument_get_Doctype(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Doctype());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_DocumentElement(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DocumentElement());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_DocumentUri(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DocumentUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_Implementation(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Implementation());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocument_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocument_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocument_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocument_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocument_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocument_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocument* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlDocument(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlDocument>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlDocument[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlDocument_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlDocument_CloneNode), METH_VARARGS, nullptr },
{ "create_attribute", reinterpret_cast<PyCFunction>(XmlDocument_CreateAttribute), METH_VARARGS, nullptr },
{ "create_attribute_n_s", reinterpret_cast<PyCFunction>(XmlDocument_CreateAttributeNS), METH_VARARGS, nullptr },
{ "create_c_data_section", reinterpret_cast<PyCFunction>(XmlDocument_CreateCDataSection), METH_VARARGS, nullptr },
{ "create_comment", reinterpret_cast<PyCFunction>(XmlDocument_CreateComment), METH_VARARGS, nullptr },
{ "create_document_fragment", reinterpret_cast<PyCFunction>(XmlDocument_CreateDocumentFragment), METH_VARARGS, nullptr },
{ "create_element", reinterpret_cast<PyCFunction>(XmlDocument_CreateElement), METH_VARARGS, nullptr },
{ "create_element_n_s", reinterpret_cast<PyCFunction>(XmlDocument_CreateElementNS), METH_VARARGS, nullptr },
{ "create_entity_reference", reinterpret_cast<PyCFunction>(XmlDocument_CreateEntityReference), METH_VARARGS, nullptr },
{ "create_processing_instruction", reinterpret_cast<PyCFunction>(XmlDocument_CreateProcessingInstruction), METH_VARARGS, nullptr },
{ "create_text_node", reinterpret_cast<PyCFunction>(XmlDocument_CreateTextNode), METH_VARARGS, nullptr },
{ "get_element_by_id", reinterpret_cast<PyCFunction>(XmlDocument_GetElementById), METH_VARARGS, nullptr },
{ "get_elements_by_tag_name", reinterpret_cast<PyCFunction>(XmlDocument_GetElementsByTagName), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlDocument_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlDocument_HasChildNodes), METH_VARARGS, nullptr },
{ "import_node", reinterpret_cast<PyCFunction>(XmlDocument_ImportNode), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlDocument_InsertBefore), METH_VARARGS, nullptr },
{ "load_from_file_async", reinterpret_cast<PyCFunction>(XmlDocument_LoadFromFileAsync), METH_VARARGS | METH_STATIC, nullptr },
{ "load_from_uri_async", reinterpret_cast<PyCFunction>(XmlDocument_LoadFromUriAsync), METH_VARARGS | METH_STATIC, nullptr },
{ "load_xml", reinterpret_cast<PyCFunction>(XmlDocument_LoadXml), METH_VARARGS, nullptr },
{ "load_xml_from_buffer", reinterpret_cast<PyCFunction>(XmlDocument_LoadXmlFromBuffer), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlDocument_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlDocument_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlDocument_ReplaceChild), METH_VARARGS, nullptr },
{ "save_to_file_async", reinterpret_cast<PyCFunction>(XmlDocument_SaveToFileAsync), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlDocument_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlDocument_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlDocument_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlDocument_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlDocument), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlDocument[] = {
{ "doctype", reinterpret_cast<getter>(XmlDocument_get_Doctype), nullptr, nullptr, nullptr },
{ "document_element", reinterpret_cast<getter>(XmlDocument_get_DocumentElement), nullptr, nullptr, nullptr },
{ "document_uri", reinterpret_cast<getter>(XmlDocument_get_DocumentUri), nullptr, nullptr, nullptr },
{ "implementation", reinterpret_cast<getter>(XmlDocument_get_Implementation), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlDocument_get_Prefix), reinterpret_cast<setter>(XmlDocument_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlDocument_get_NodeValue), reinterpret_cast<setter>(XmlDocument_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlDocument_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlDocument_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlDocument_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlDocument_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlDocument_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlDocument_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlDocument_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlDocument_get_Attributes), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlDocument_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlDocument_get_ParentNode), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlDocument_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlDocument_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlDocument_get_InnerText), reinterpret_cast<setter>(XmlDocument_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlDocument[] =
{
{ Py_tp_new, _new_XmlDocument },
{ Py_tp_dealloc, _dealloc_XmlDocument },
{ Py_tp_methods, _methods_XmlDocument },
{ Py_tp_getset, _getset_XmlDocument },
{ },
};
static PyType_Spec _type_spec_XmlDocument =
{
"_winsdk_Windows_Data_Xml_Dom.XmlDocument",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlDocument),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlDocument
};
// ----- XmlDocumentFragment class --------------------
constexpr const char* const _type_name_XmlDocumentFragment = "XmlDocumentFragment";
static PyObject* _new_XmlDocumentFragment(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlDocumentFragment);
return nullptr;
}
static void _dealloc_XmlDocumentFragment(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlDocumentFragment_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentFragment_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocumentFragment_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentFragment_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocumentFragment_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentFragment_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentFragment_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlDocumentFragment(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlDocumentFragment>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlDocumentFragment[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlDocumentFragment_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlDocumentFragment_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlDocumentFragment_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlDocumentFragment_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlDocumentFragment_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlDocumentFragment_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlDocumentFragment_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlDocumentFragment_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlDocumentFragment_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlDocumentFragment_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlDocumentFragment_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlDocumentFragment_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlDocumentFragment), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlDocumentFragment[] = {
{ "prefix", reinterpret_cast<getter>(XmlDocumentFragment_get_Prefix), reinterpret_cast<setter>(XmlDocumentFragment_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlDocumentFragment_get_NodeValue), reinterpret_cast<setter>(XmlDocumentFragment_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlDocumentFragment_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlDocumentFragment_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlDocumentFragment_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlDocumentFragment_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlDocumentFragment_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlDocumentFragment_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlDocumentFragment_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlDocumentFragment_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlDocumentFragment_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlDocumentFragment_get_ParentNode), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlDocumentFragment_get_ChildNodes), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlDocumentFragment_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlDocumentFragment_get_InnerText), reinterpret_cast<setter>(XmlDocumentFragment_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlDocumentFragment[] =
{
{ Py_tp_new, _new_XmlDocumentFragment },
{ Py_tp_dealloc, _dealloc_XmlDocumentFragment },
{ Py_tp_methods, _methods_XmlDocumentFragment },
{ Py_tp_getset, _getset_XmlDocumentFragment },
{ },
};
static PyType_Spec _type_spec_XmlDocumentFragment =
{
"_winsdk_Windows_Data_Xml_Dom.XmlDocumentFragment",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentFragment),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlDocumentFragment
};
// ----- XmlDocumentType class --------------------
constexpr const char* const _type_name_XmlDocumentType = "XmlDocumentType";
static PyObject* _new_XmlDocumentType(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlDocumentType);
return nullptr;
}
static void _dealloc_XmlDocumentType(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlDocumentType_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlDocumentType_get_Entities(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Entities());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_Name(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Name());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_Notations(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Notations());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentType_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocumentType_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentType_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlDocumentType_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlDocumentType_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlDocumentType_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlDocumentType(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlDocumentType>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlDocumentType[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlDocumentType_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlDocumentType_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlDocumentType_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlDocumentType_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlDocumentType_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlDocumentType_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlDocumentType_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlDocumentType_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlDocumentType_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlDocumentType_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlDocumentType_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlDocumentType_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlDocumentType), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlDocumentType[] = {
{ "entities", reinterpret_cast<getter>(XmlDocumentType_get_Entities), nullptr, nullptr, nullptr },
{ "name", reinterpret_cast<getter>(XmlDocumentType_get_Name), nullptr, nullptr, nullptr },
{ "notations", reinterpret_cast<getter>(XmlDocumentType_get_Notations), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlDocumentType_get_Prefix), reinterpret_cast<setter>(XmlDocumentType_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlDocumentType_get_NodeValue), reinterpret_cast<setter>(XmlDocumentType_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlDocumentType_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlDocumentType_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlDocumentType_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlDocumentType_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlDocumentType_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlDocumentType_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlDocumentType_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlDocumentType_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlDocumentType_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlDocumentType_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlDocumentType_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlDocumentType_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlDocumentType_get_InnerText), reinterpret_cast<setter>(XmlDocumentType_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlDocumentType[] =
{
{ Py_tp_new, _new_XmlDocumentType },
{ Py_tp_dealloc, _dealloc_XmlDocumentType },
{ Py_tp_methods, _methods_XmlDocumentType },
{ Py_tp_getset, _getset_XmlDocumentType },
{ },
};
static PyType_Spec _type_spec_XmlDocumentType =
{
"_winsdk_Windows_Data_Xml_Dom.XmlDocumentType",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlDocumentType),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlDocumentType
};
// ----- XmlDomImplementation class --------------------
constexpr const char* const _type_name_XmlDomImplementation = "XmlDomImplementation";
static PyObject* _new_XmlDomImplementation(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlDomImplementation);
return nullptr;
}
static void _dealloc_XmlDomImplementation(py::wrapper::Windows::Data::Xml::Dom::XmlDomImplementation* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlDomImplementation_HasFeature(py::wrapper::Windows::Data::Xml::Dom::XmlDomImplementation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.HasFeature(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_XmlDomImplementation(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlDomImplementation>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlDomImplementation[] = {
{ "has_feature", reinterpret_cast<PyCFunction>(XmlDomImplementation_HasFeature), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlDomImplementation), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlDomImplementation[] = {
{ }
};
static PyType_Slot _type_slots_XmlDomImplementation[] =
{
{ Py_tp_new, _new_XmlDomImplementation },
{ Py_tp_dealloc, _dealloc_XmlDomImplementation },
{ Py_tp_methods, _methods_XmlDomImplementation },
{ Py_tp_getset, _getset_XmlDomImplementation },
{ },
};
static PyType_Spec _type_spec_XmlDomImplementation =
{
"_winsdk_Windows_Data_Xml_Dom.XmlDomImplementation",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlDomImplementation),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlDomImplementation
};
// ----- XmlElement class --------------------
constexpr const char* const _type_name_XmlElement = "XmlElement";
static PyObject* _new_XmlElement(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlElement);
return nullptr;
}
static void _dealloc_XmlElement(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlElement_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetAttribute(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetAttribute(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetAttributeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.GetAttributeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetAttributeNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetAttributeNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetAttributeNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.GetAttributeNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetElementsByTagName(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetElementsByTagName(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_RemoveAttribute(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.RemoveAttribute(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_RemoveAttributeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.RemoveAttributeNS(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_RemoveAttributeNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlAttribute>(args, 0);
return py::convert(self->obj.RemoveAttributeNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SetAttribute(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.SetAttribute(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SetAttributeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.SetAttributeNS(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SetAttributeNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlAttribute>(args, 0);
return py::convert(self->obj.SetAttributeNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_SetAttributeNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::XmlAttribute>(args, 0);
return py::convert(self->obj.SetAttributeNodeNS(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlElement_get_TagName(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.TagName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlElement_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlElement_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlElement_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlElement_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlElement_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlElement_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlElement* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlElement(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlElement>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlElement[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlElement_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlElement_CloneNode), METH_VARARGS, nullptr },
{ "get_attribute", reinterpret_cast<PyCFunction>(XmlElement_GetAttribute), METH_VARARGS, nullptr },
{ "get_attribute_n_s", reinterpret_cast<PyCFunction>(XmlElement_GetAttributeNS), METH_VARARGS, nullptr },
{ "get_attribute_node", reinterpret_cast<PyCFunction>(XmlElement_GetAttributeNode), METH_VARARGS, nullptr },
{ "get_attribute_node_n_s", reinterpret_cast<PyCFunction>(XmlElement_GetAttributeNodeNS), METH_VARARGS, nullptr },
{ "get_elements_by_tag_name", reinterpret_cast<PyCFunction>(XmlElement_GetElementsByTagName), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlElement_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlElement_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlElement_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlElement_Normalize), METH_VARARGS, nullptr },
{ "remove_attribute", reinterpret_cast<PyCFunction>(XmlElement_RemoveAttribute), METH_VARARGS, nullptr },
{ "remove_attribute_n_s", reinterpret_cast<PyCFunction>(XmlElement_RemoveAttributeNS), METH_VARARGS, nullptr },
{ "remove_attribute_node", reinterpret_cast<PyCFunction>(XmlElement_RemoveAttributeNode), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlElement_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlElement_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlElement_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlElement_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlElement_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlElement_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "set_attribute", reinterpret_cast<PyCFunction>(XmlElement_SetAttribute), METH_VARARGS, nullptr },
{ "set_attribute_n_s", reinterpret_cast<PyCFunction>(XmlElement_SetAttributeNS), METH_VARARGS, nullptr },
{ "set_attribute_node", reinterpret_cast<PyCFunction>(XmlElement_SetAttributeNode), METH_VARARGS, nullptr },
{ "set_attribute_node_n_s", reinterpret_cast<PyCFunction>(XmlElement_SetAttributeNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlElement), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlElement[] = {
{ "tag_name", reinterpret_cast<getter>(XmlElement_get_TagName), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlElement_get_Prefix), reinterpret_cast<setter>(XmlElement_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlElement_get_NodeValue), reinterpret_cast<setter>(XmlElement_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlElement_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlElement_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlElement_get_LocalName), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlElement_get_NextSibling), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlElement_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlElement_get_NodeType), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlElement_get_NodeName), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlElement_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlElement_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlElement_get_ParentNode), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlElement_get_ChildNodes), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlElement_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlElement_get_InnerText), reinterpret_cast<setter>(XmlElement_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlElement[] =
{
{ Py_tp_new, _new_XmlElement },
{ Py_tp_dealloc, _dealloc_XmlElement },
{ Py_tp_methods, _methods_XmlElement },
{ Py_tp_getset, _getset_XmlElement },
{ },
};
static PyType_Spec _type_spec_XmlElement =
{
"_winsdk_Windows_Data_Xml_Dom.XmlElement",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlElement),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlElement
};
// ----- XmlEntityReference class --------------------
constexpr const char* const _type_name_XmlEntityReference = "XmlEntityReference";
static PyObject* _new_XmlEntityReference(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlEntityReference);
return nullptr;
}
static void _dealloc_XmlEntityReference(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlEntityReference_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlEntityReference_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlEntityReference_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlEntityReference_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlEntityReference_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlEntityReference_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlEntityReference_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlEntityReference_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlEntityReference(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlEntityReference>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlEntityReference[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlEntityReference_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlEntityReference_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlEntityReference_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlEntityReference_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlEntityReference_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlEntityReference_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlEntityReference_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlEntityReference_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlEntityReference_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlEntityReference_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlEntityReference_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlEntityReference_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlEntityReference), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlEntityReference[] = {
{ "prefix", reinterpret_cast<getter>(XmlEntityReference_get_Prefix), reinterpret_cast<setter>(XmlEntityReference_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlEntityReference_get_NodeValue), reinterpret_cast<setter>(XmlEntityReference_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlEntityReference_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlEntityReference_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlEntityReference_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlEntityReference_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlEntityReference_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlEntityReference_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlEntityReference_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlEntityReference_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlEntityReference_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlEntityReference_get_ParentNode), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlEntityReference_get_ChildNodes), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlEntityReference_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlEntityReference_get_InnerText), reinterpret_cast<setter>(XmlEntityReference_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlEntityReference[] =
{
{ Py_tp_new, _new_XmlEntityReference },
{ Py_tp_dealloc, _dealloc_XmlEntityReference },
{ Py_tp_methods, _methods_XmlEntityReference },
{ Py_tp_getset, _getset_XmlEntityReference },
{ },
};
static PyType_Spec _type_spec_XmlEntityReference =
{
"_winsdk_Windows_Data_Xml_Dom.XmlEntityReference",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlEntityReference),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlEntityReference
};
// ----- XmlLoadSettings class --------------------
constexpr const char* const _type_name_XmlLoadSettings = "XmlLoadSettings";
static PyObject* _new_XmlLoadSettings(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::Data::Xml::Dom::XmlLoadSettings instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_XmlLoadSettings(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlLoadSettings_get_ValidateOnParse(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ValidateOnParse());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlLoadSettings_put_ValidateOnParse(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.ValidateOnParse(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlLoadSettings_get_ResolveExternals(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ResolveExternals());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlLoadSettings_put_ResolveExternals(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.ResolveExternals(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlLoadSettings_get_ProhibitDtd(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ProhibitDtd());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlLoadSettings_put_ProhibitDtd(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.ProhibitDtd(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlLoadSettings_get_MaxElementDepth(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MaxElementDepth());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlLoadSettings_put_MaxElementDepth(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<uint32_t>(arg);
self->obj.MaxElementDepth(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlLoadSettings_get_ElementContentWhiteSpace(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ElementContentWhiteSpace());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlLoadSettings_put_ElementContentWhiteSpace(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.ElementContentWhiteSpace(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlLoadSettings(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlLoadSettings[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlLoadSettings), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlLoadSettings[] = {
{ "validate_on_parse", reinterpret_cast<getter>(XmlLoadSettings_get_ValidateOnParse), reinterpret_cast<setter>(XmlLoadSettings_put_ValidateOnParse), nullptr, nullptr },
{ "resolve_externals", reinterpret_cast<getter>(XmlLoadSettings_get_ResolveExternals), reinterpret_cast<setter>(XmlLoadSettings_put_ResolveExternals), nullptr, nullptr },
{ "prohibit_dtd", reinterpret_cast<getter>(XmlLoadSettings_get_ProhibitDtd), reinterpret_cast<setter>(XmlLoadSettings_put_ProhibitDtd), nullptr, nullptr },
{ "max_element_depth", reinterpret_cast<getter>(XmlLoadSettings_get_MaxElementDepth), reinterpret_cast<setter>(XmlLoadSettings_put_MaxElementDepth), nullptr, nullptr },
{ "element_content_white_space", reinterpret_cast<getter>(XmlLoadSettings_get_ElementContentWhiteSpace), reinterpret_cast<setter>(XmlLoadSettings_put_ElementContentWhiteSpace), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlLoadSettings[] =
{
{ Py_tp_new, _new_XmlLoadSettings },
{ Py_tp_dealloc, _dealloc_XmlLoadSettings },
{ Py_tp_methods, _methods_XmlLoadSettings },
{ Py_tp_getset, _getset_XmlLoadSettings },
{ },
};
static PyType_Spec _type_spec_XmlLoadSettings =
{
"_winsdk_Windows_Data_Xml_Dom.XmlLoadSettings",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlLoadSettings),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlLoadSettings
};
// ----- XmlNamedNodeMap class --------------------
constexpr const char* const _type_name_XmlNamedNodeMap = "XmlNamedNodeMap";
static PyObject* _new_XmlNamedNodeMap(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlNamedNodeMap);
return nullptr;
}
static void _dealloc_XmlNamedNodeMap(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlNamedNodeMap_First(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.First());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_GetAt(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.GetAt(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_GetMany(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1_count = py::convert_to<winrt::com_array<winrt::Windows::Data::Xml::Dom::IXmlNode>::size_type>(args, 1);
winrt::com_array<winrt::Windows::Data::Xml::Dom::IXmlNode> param1 ( param1_count, py::empty_instance<winrt::Windows::Data::Xml::Dom::IXmlNode>::get() );
auto return_value = self->obj.GetMany(param0, param1);
py::pyobj_handle out_return_value{ py::convert(return_value) };
if (!out_return_value)
{
return nullptr;
}
py::pyobj_handle out1{ py::convert(param1) };
if (!out1)
{
return nullptr;
}
return PyTuple_Pack(2, out_return_value.get(), out1.get());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_GetNamedItem(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetNamedItem(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_GetNamedItemNS(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.GetNamedItemNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_IndexOf(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
uint32_t param1 { };
auto return_value = self->obj.IndexOf(param0, param1);
py::pyobj_handle out_return_value{ py::convert(return_value) };
if (!out_return_value)
{
return nullptr;
}
py::pyobj_handle out1{ py::convert(param1) };
if (!out1)
{
return nullptr;
}
return PyTuple_Pack(2, out_return_value.get(), out1.get());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_Item(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.Item(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_RemoveNamedItem(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.RemoveNamedItem(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_RemoveNamedItemNS(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.RemoveNamedItemNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_SetNamedItem(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.SetNamedItem(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_SetNamedItemNS(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.SetNamedItemNS(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_get_Length(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlNamedNodeMap_get_Size(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Size());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_XmlNamedNodeMap(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlNamedNodeMap>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _iterator_XmlNamedNodeMap(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self) noexcept
{
try
{
return py::convert(self->obj.First());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static Py_ssize_t _seq_length_XmlNamedNodeMap(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self) noexcept
{
try
{
return static_cast<Py_ssize_t>(self->obj.Size());
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _seq_item_XmlNamedNodeMap(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap* self, Py_ssize_t i) noexcept
{
try
{
return py::convert(self->obj.GetAt(static_cast<uint32_t>(i)));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlNamedNodeMap[] = {
{ "first", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_First), METH_VARARGS, nullptr },
{ "get_at", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_GetAt), METH_VARARGS, nullptr },
{ "get_many", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_GetMany), METH_VARARGS, nullptr },
{ "get_named_item", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_GetNamedItem), METH_VARARGS, nullptr },
{ "get_named_item_n_s", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_GetNamedItemNS), METH_VARARGS, nullptr },
{ "index_of", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_IndexOf), METH_VARARGS, nullptr },
{ "item", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_Item), METH_VARARGS, nullptr },
{ "remove_named_item", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_RemoveNamedItem), METH_VARARGS, nullptr },
{ "remove_named_item_n_s", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_RemoveNamedItemNS), METH_VARARGS, nullptr },
{ "set_named_item", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_SetNamedItem), METH_VARARGS, nullptr },
{ "set_named_item_n_s", reinterpret_cast<PyCFunction>(XmlNamedNodeMap_SetNamedItemNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlNamedNodeMap), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlNamedNodeMap[] = {
{ "length", reinterpret_cast<getter>(XmlNamedNodeMap_get_Length), nullptr, nullptr, nullptr },
{ "size", reinterpret_cast<getter>(XmlNamedNodeMap_get_Size), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlNamedNodeMap[] =
{
{ Py_tp_new, _new_XmlNamedNodeMap },
{ Py_tp_dealloc, _dealloc_XmlNamedNodeMap },
{ Py_tp_methods, _methods_XmlNamedNodeMap },
{ Py_tp_getset, _getset_XmlNamedNodeMap },
{ Py_tp_iter, _iterator_XmlNamedNodeMap },
{ Py_sq_length, _seq_length_XmlNamedNodeMap },
{ Py_sq_item, _seq_item_XmlNamedNodeMap },
{ },
};
static PyType_Spec _type_spec_XmlNamedNodeMap =
{
"_winsdk_Windows_Data_Xml_Dom.XmlNamedNodeMap",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlNamedNodeMap),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlNamedNodeMap
};
// ----- XmlNodeList class --------------------
constexpr const char* const _type_name_XmlNodeList = "XmlNodeList";
static PyObject* _new_XmlNodeList(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlNodeList);
return nullptr;
}
static void _dealloc_XmlNodeList(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlNodeList_First(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.First());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNodeList_GetAt(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.GetAt(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNodeList_GetMany(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1_count = py::convert_to<winrt::com_array<winrt::Windows::Data::Xml::Dom::IXmlNode>::size_type>(args, 1);
winrt::com_array<winrt::Windows::Data::Xml::Dom::IXmlNode> param1 ( param1_count, py::empty_instance<winrt::Windows::Data::Xml::Dom::IXmlNode>::get() );
auto return_value = self->obj.GetMany(param0, param1);
py::pyobj_handle out_return_value{ py::convert(return_value) };
if (!out_return_value)
{
return nullptr;
}
py::pyobj_handle out1{ py::convert(param1) };
if (!out1)
{
return nullptr;
}
return PyTuple_Pack(2, out_return_value.get(), out1.get());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNodeList_IndexOf(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
uint32_t param1 { };
auto return_value = self->obj.IndexOf(param0, param1);
py::pyobj_handle out_return_value{ py::convert(return_value) };
if (!out_return_value)
{
return nullptr;
}
py::pyobj_handle out1{ py::convert(param1) };
if (!out1)
{
return nullptr;
}
return PyTuple_Pack(2, out_return_value.get(), out1.get());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNodeList_Item(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.Item(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlNodeList_get_Length(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlNodeList_get_Size(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Size());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_XmlNodeList(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlNodeList>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _iterator_XmlNodeList(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self) noexcept
{
try
{
return py::convert(self->obj.First());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static Py_ssize_t _seq_length_XmlNodeList(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self) noexcept
{
try
{
return static_cast<Py_ssize_t>(self->obj.Size());
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _seq_item_XmlNodeList(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList* self, Py_ssize_t i) noexcept
{
try
{
return py::convert(self->obj.GetAt(static_cast<uint32_t>(i)));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlNodeList[] = {
{ "first", reinterpret_cast<PyCFunction>(XmlNodeList_First), METH_VARARGS, nullptr },
{ "get_at", reinterpret_cast<PyCFunction>(XmlNodeList_GetAt), METH_VARARGS, nullptr },
{ "get_many", reinterpret_cast<PyCFunction>(XmlNodeList_GetMany), METH_VARARGS, nullptr },
{ "index_of", reinterpret_cast<PyCFunction>(XmlNodeList_IndexOf), METH_VARARGS, nullptr },
{ "item", reinterpret_cast<PyCFunction>(XmlNodeList_Item), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlNodeList), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlNodeList[] = {
{ "length", reinterpret_cast<getter>(XmlNodeList_get_Length), nullptr, nullptr, nullptr },
{ "size", reinterpret_cast<getter>(XmlNodeList_get_Size), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlNodeList[] =
{
{ Py_tp_new, _new_XmlNodeList },
{ Py_tp_dealloc, _dealloc_XmlNodeList },
{ Py_tp_methods, _methods_XmlNodeList },
{ Py_tp_getset, _getset_XmlNodeList },
{ Py_tp_iter, _iterator_XmlNodeList },
{ Py_sq_length, _seq_length_XmlNodeList },
{ Py_sq_item, _seq_item_XmlNodeList },
{ },
};
static PyType_Spec _type_spec_XmlNodeList =
{
"_winsdk_Windows_Data_Xml_Dom.XmlNodeList",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlNodeList),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlNodeList
};
// ----- XmlProcessingInstruction class --------------------
constexpr const char* const _type_name_XmlProcessingInstruction = "XmlProcessingInstruction";
static PyObject* _new_XmlProcessingInstruction(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlProcessingInstruction);
return nullptr;
}
static void _dealloc_XmlProcessingInstruction(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlProcessingInstruction_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlProcessingInstruction_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlProcessingInstruction_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlProcessingInstruction_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlProcessingInstruction_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlProcessingInstruction_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlProcessingInstruction_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlProcessingInstruction_get_Data(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlProcessingInstruction_put_Data(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlProcessingInstruction_get_Target(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Target());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_XmlProcessingInstruction(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlProcessingInstruction>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlProcessingInstruction[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_CloneNode), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlProcessingInstruction_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlProcessingInstruction), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlProcessingInstruction[] = {
{ "prefix", reinterpret_cast<getter>(XmlProcessingInstruction_get_Prefix), reinterpret_cast<setter>(XmlProcessingInstruction_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlProcessingInstruction_get_NodeValue), reinterpret_cast<setter>(XmlProcessingInstruction_put_NodeValue), nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlProcessingInstruction_get_Attributes), nullptr, nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlProcessingInstruction_get_FirstChild), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlProcessingInstruction_get_ChildNodes), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlProcessingInstruction_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlProcessingInstruction_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlProcessingInstruction_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlProcessingInstruction_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlProcessingInstruction_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlProcessingInstruction_get_NodeType), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlProcessingInstruction_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlProcessingInstruction_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlProcessingInstruction_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlProcessingInstruction_get_InnerText), reinterpret_cast<setter>(XmlProcessingInstruction_put_InnerText), nullptr, nullptr },
{ "data", reinterpret_cast<getter>(XmlProcessingInstruction_get_Data), reinterpret_cast<setter>(XmlProcessingInstruction_put_Data), nullptr, nullptr },
{ "target", reinterpret_cast<getter>(XmlProcessingInstruction_get_Target), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlProcessingInstruction[] =
{
{ Py_tp_new, _new_XmlProcessingInstruction },
{ Py_tp_dealloc, _dealloc_XmlProcessingInstruction },
{ Py_tp_methods, _methods_XmlProcessingInstruction },
{ Py_tp_getset, _getset_XmlProcessingInstruction },
{ },
};
static PyType_Spec _type_spec_XmlProcessingInstruction =
{
"_winsdk_Windows_Data_Xml_Dom.XmlProcessingInstruction",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlProcessingInstruction),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlProcessingInstruction
};
// ----- XmlText class --------------------
constexpr const char* const _type_name_XmlText = "XmlText";
static PyObject* _new_XmlText(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_XmlText);
return nullptr;
}
static void _dealloc_XmlText(py::wrapper::Windows::Data::Xml::Dom::XmlText* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* XmlText_AppendChild(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_AppendData(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.AppendData(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_CloneNode(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_DeleteData(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
self->obj.DeleteData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_GetXml(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_InsertData(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.InsertData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_Normalize(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_ReplaceData(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.ReplaceData(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SplitText(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.SplitText(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_SubstringData(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
return py::convert(self->obj.SubstringData(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* XmlText_get_Data(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlText_put_Data(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlText_get_Length(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlText_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlText_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlText_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* XmlText_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* XmlText_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int XmlText_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::XmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_XmlText(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::XmlText>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_XmlText[] = {
{ "append_child", reinterpret_cast<PyCFunction>(XmlText_AppendChild), METH_VARARGS, nullptr },
{ "append_data", reinterpret_cast<PyCFunction>(XmlText_AppendData), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(XmlText_CloneNode), METH_VARARGS, nullptr },
{ "delete_data", reinterpret_cast<PyCFunction>(XmlText_DeleteData), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(XmlText_GetXml), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(XmlText_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(XmlText_InsertBefore), METH_VARARGS, nullptr },
{ "insert_data", reinterpret_cast<PyCFunction>(XmlText_InsertData), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(XmlText_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(XmlText_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(XmlText_ReplaceChild), METH_VARARGS, nullptr },
{ "replace_data", reinterpret_cast<PyCFunction>(XmlText_ReplaceData), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(XmlText_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(XmlText_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(XmlText_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(XmlText_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "split_text", reinterpret_cast<PyCFunction>(XmlText_SplitText), METH_VARARGS, nullptr },
{ "substring_data", reinterpret_cast<PyCFunction>(XmlText_SubstringData), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_XmlText), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_XmlText[] = {
{ "data", reinterpret_cast<getter>(XmlText_get_Data), reinterpret_cast<setter>(XmlText_put_Data), nullptr, nullptr },
{ "length", reinterpret_cast<getter>(XmlText_get_Length), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(XmlText_get_Prefix), reinterpret_cast<setter>(XmlText_put_Prefix), nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(XmlText_get_NodeValue), reinterpret_cast<setter>(XmlText_put_NodeValue), nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(XmlText_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(XmlText_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(XmlText_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(XmlText_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(XmlText_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(XmlText_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(XmlText_get_NodeType), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(XmlText_get_Attributes), nullptr, nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(XmlText_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(XmlText_get_ChildNodes), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(XmlText_get_ParentNode), nullptr, nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(XmlText_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(XmlText_get_InnerText), reinterpret_cast<setter>(XmlText_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_XmlText[] =
{
{ Py_tp_new, _new_XmlText },
{ Py_tp_dealloc, _dealloc_XmlText },
{ Py_tp_methods, _methods_XmlText },
{ Py_tp_getset, _getset_XmlText },
{ },
};
static PyType_Spec _type_spec_XmlText =
{
"_winsdk_Windows_Data_Xml_Dom.XmlText",
sizeof(py::wrapper::Windows::Data::Xml::Dom::XmlText),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_XmlText
};
// ----- IXmlCharacterData interface --------------------
constexpr const char* const _type_name_IXmlCharacterData = "IXmlCharacterData";
static PyObject* _new_IXmlCharacterData(PyTypeObject* /* unused */, PyObject* /* unused */, PyObject* /* unused */)
{
py::set_invalid_activation_error(_type_name_IXmlCharacterData);
return nullptr;
}
static void _dealloc_IXmlCharacterData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* IXmlCharacterData_AppendChild(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_AppendData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.AppendData(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_CloneNode(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_DeleteData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
self->obj.DeleteData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_GetXml(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_InsertData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.InsertData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_Normalize(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_ReplaceData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.ReplaceData(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_SubstringData(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
return py::convert(self->obj.SubstringData(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_Data(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlCharacterData_put_Data(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlCharacterData_get_Length(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlCharacterData_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlCharacterData_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlCharacterData_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlCharacterData_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlCharacterData_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlCharacterData_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_IXmlCharacterData(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::IXmlCharacterData>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_IXmlCharacterData[] = {
{ "append_data", reinterpret_cast<PyCFunction>(IXmlCharacterData_AppendData), METH_VARARGS, nullptr },
{ "delete_data", reinterpret_cast<PyCFunction>(IXmlCharacterData_DeleteData), METH_VARARGS, nullptr },
{ "insert_data", reinterpret_cast<PyCFunction>(IXmlCharacterData_InsertData), METH_VARARGS, nullptr },
{ "replace_data", reinterpret_cast<PyCFunction>(IXmlCharacterData_ReplaceData), METH_VARARGS, nullptr },
{ "substring_data", reinterpret_cast<PyCFunction>(IXmlCharacterData_SubstringData), METH_VARARGS, nullptr },
{ "append_child", reinterpret_cast<PyCFunction>(IXmlCharacterData_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(IXmlCharacterData_CloneNode), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(IXmlCharacterData_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(IXmlCharacterData_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(IXmlCharacterData_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(IXmlCharacterData_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(IXmlCharacterData_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(IXmlCharacterData_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(IXmlCharacterData_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(IXmlCharacterData_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(IXmlCharacterData_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(IXmlCharacterData_GetXml), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_IXmlCharacterData), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_IXmlCharacterData[] = {
{ "data", reinterpret_cast<getter>(IXmlCharacterData_get_Data), reinterpret_cast<setter>(IXmlCharacterData_put_Data), nullptr, nullptr },
{ "length", reinterpret_cast<getter>(IXmlCharacterData_get_Length), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(IXmlCharacterData_get_Attributes), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(IXmlCharacterData_get_ChildNodes), nullptr, nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(IXmlCharacterData_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(IXmlCharacterData_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(IXmlCharacterData_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(IXmlCharacterData_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(IXmlCharacterData_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(IXmlCharacterData_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(IXmlCharacterData_get_NodeType), nullptr, nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(IXmlCharacterData_get_NodeValue), reinterpret_cast<setter>(IXmlCharacterData_put_NodeValue), nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(IXmlCharacterData_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(IXmlCharacterData_get_ParentNode), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(IXmlCharacterData_get_Prefix), reinterpret_cast<setter>(IXmlCharacterData_put_Prefix), nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(IXmlCharacterData_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(IXmlCharacterData_get_InnerText), reinterpret_cast<setter>(IXmlCharacterData_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_IXmlCharacterData[] =
{
{ Py_tp_new, _new_IXmlCharacterData },
{ Py_tp_dealloc, _dealloc_IXmlCharacterData },
{ Py_tp_methods, _methods_IXmlCharacterData },
{ Py_tp_getset, _getset_IXmlCharacterData },
{ },
};
static PyType_Spec _type_spec_IXmlCharacterData =
{
"_winsdk_Windows_Data_Xml_Dom.IXmlCharacterData",
sizeof(py::wrapper::Windows::Data::Xml::Dom::IXmlCharacterData),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_IXmlCharacterData
};
// ----- IXmlNode interface --------------------
constexpr const char* const _type_name_IXmlNode = "IXmlNode";
static PyObject* _new_IXmlNode(PyTypeObject* /* unused */, PyObject* /* unused */, PyObject* /* unused */)
{
py::set_invalid_activation_error(_type_name_IXmlNode);
return nullptr;
}
static void _dealloc_IXmlNode(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* IXmlNode_AppendChild(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_CloneNode(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_GetXml(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_Normalize(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNode_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlNode_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlNode_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlNode_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlNode_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlNode_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlNode_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlNode* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_IXmlNode(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::IXmlNode>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_IXmlNode[] = {
{ "append_child", reinterpret_cast<PyCFunction>(IXmlNode_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(IXmlNode_CloneNode), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(IXmlNode_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(IXmlNode_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(IXmlNode_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(IXmlNode_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(IXmlNode_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(IXmlNode_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(IXmlNode_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(IXmlNode_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(IXmlNode_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(IXmlNode_GetXml), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_IXmlNode), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_IXmlNode[] = {
{ "attributes", reinterpret_cast<getter>(IXmlNode_get_Attributes), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(IXmlNode_get_ChildNodes), nullptr, nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(IXmlNode_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(IXmlNode_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(IXmlNode_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(IXmlNode_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(IXmlNode_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(IXmlNode_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(IXmlNode_get_NodeType), nullptr, nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(IXmlNode_get_NodeValue), reinterpret_cast<setter>(IXmlNode_put_NodeValue), nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(IXmlNode_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(IXmlNode_get_ParentNode), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(IXmlNode_get_Prefix), reinterpret_cast<setter>(IXmlNode_put_Prefix), nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(IXmlNode_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(IXmlNode_get_InnerText), reinterpret_cast<setter>(IXmlNode_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_IXmlNode[] =
{
{ Py_tp_new, _new_IXmlNode },
{ Py_tp_dealloc, _dealloc_IXmlNode },
{ Py_tp_methods, _methods_IXmlNode },
{ Py_tp_getset, _getset_IXmlNode },
{ },
};
static PyType_Spec _type_spec_IXmlNode =
{
"_winsdk_Windows_Data_Xml_Dom.IXmlNode",
sizeof(py::wrapper::Windows::Data::Xml::Dom::IXmlNode),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_IXmlNode
};
// ----- IXmlNodeSelector interface --------------------
constexpr const char* const _type_name_IXmlNodeSelector = "IXmlNodeSelector";
static PyObject* _new_IXmlNodeSelector(PyTypeObject* /* unused */, PyObject* /* unused */, PyObject* /* unused */)
{
py::set_invalid_activation_error(_type_name_IXmlNodeSelector);
return nullptr;
}
static void _dealloc_IXmlNodeSelector(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* IXmlNodeSelector_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNodeSelector_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNodeSelector_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNodeSelector_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_IXmlNodeSelector(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::IXmlNodeSelector>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_IXmlNodeSelector[] = {
{ "select_nodes", reinterpret_cast<PyCFunction>(IXmlNodeSelector_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(IXmlNodeSelector_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(IXmlNodeSelector_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(IXmlNodeSelector_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_IXmlNodeSelector), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_IXmlNodeSelector[] = {
{ }
};
static PyType_Slot _type_slots_IXmlNodeSelector[] =
{
{ Py_tp_new, _new_IXmlNodeSelector },
{ Py_tp_dealloc, _dealloc_IXmlNodeSelector },
{ Py_tp_methods, _methods_IXmlNodeSelector },
{ Py_tp_getset, _getset_IXmlNodeSelector },
{ },
};
static PyType_Spec _type_spec_IXmlNodeSelector =
{
"_winsdk_Windows_Data_Xml_Dom.IXmlNodeSelector",
sizeof(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSelector),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_IXmlNodeSelector
};
// ----- IXmlNodeSerializer interface --------------------
constexpr const char* const _type_name_IXmlNodeSerializer = "IXmlNodeSerializer";
static PyObject* _new_IXmlNodeSerializer(PyTypeObject* /* unused */, PyObject* /* unused */, PyObject* /* unused */)
{
py::set_invalid_activation_error(_type_name_IXmlNodeSerializer);
return nullptr;
}
static void _dealloc_IXmlNodeSerializer(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSerializer* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* IXmlNodeSerializer_GetXml(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSerializer* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlNodeSerializer_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSerializer* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlNodeSerializer_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSerializer* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_IXmlNodeSerializer(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::IXmlNodeSerializer>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_IXmlNodeSerializer[] = {
{ "get_xml", reinterpret_cast<PyCFunction>(IXmlNodeSerializer_GetXml), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_IXmlNodeSerializer), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_IXmlNodeSerializer[] = {
{ "inner_text", reinterpret_cast<getter>(IXmlNodeSerializer_get_InnerText), reinterpret_cast<setter>(IXmlNodeSerializer_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_IXmlNodeSerializer[] =
{
{ Py_tp_new, _new_IXmlNodeSerializer },
{ Py_tp_dealloc, _dealloc_IXmlNodeSerializer },
{ Py_tp_methods, _methods_IXmlNodeSerializer },
{ Py_tp_getset, _getset_IXmlNodeSerializer },
{ },
};
static PyType_Spec _type_spec_IXmlNodeSerializer =
{
"_winsdk_Windows_Data_Xml_Dom.IXmlNodeSerializer",
sizeof(py::wrapper::Windows::Data::Xml::Dom::IXmlNodeSerializer),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_IXmlNodeSerializer
};
// ----- IXmlText interface --------------------
constexpr const char* const _type_name_IXmlText = "IXmlText";
static PyObject* _new_IXmlText(PyTypeObject* /* unused */, PyObject* /* unused */, PyObject* /* unused */)
{
py::set_invalid_activation_error(_type_name_IXmlText);
return nullptr;
}
static void _dealloc_IXmlText(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* IXmlText_AppendChild(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.AppendChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_AppendData(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
self->obj.AppendData(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_CloneNode(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<bool>(args, 0);
return py::convert(self->obj.CloneNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_DeleteData(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
self->obj.DeleteData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_GetXml(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetXml());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_HasChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.HasChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_InsertBefore(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.InsertBefore(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_InsertData(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
self->obj.InsertData(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_Normalize(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Normalize();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_RemoveChild(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
return py::convert(self->obj.RemoveChild(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_ReplaceChild(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Data::Xml::Dom::IXmlNode>(args, 1);
return py::convert(self->obj.ReplaceChild(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_ReplaceData(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
self->obj.ReplaceData(param0, param1, param2);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SelectNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectNodes(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SelectNodesNS(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectNodesNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SelectSingleNode(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.SelectSingleNode(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SelectSingleNodeNS(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::IInspectable>(args, 1);
return py::convert(self->obj.SelectSingleNodeNS(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SplitText(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.SplitText(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_SubstringData(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
auto param1 = py::convert_to<uint32_t>(args, 1);
return py::convert(self->obj.SubstringData(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* IXmlText_get_Data(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlText_put_Data(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlText_get_Length(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Length());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_Attributes(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attributes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_ChildNodes(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChildNodes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_FirstChild(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FirstChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_LastChild(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastChild());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_LocalName(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LocalName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_NamespaceUri(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NamespaceUri());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_NextSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NextSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_NodeName(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_NodeType(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NodeValue());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlText_put_NodeValue(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.NodeValue(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlText_get_OwnerDocument(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OwnerDocument());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_ParentNode(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentNode());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Prefix());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlText_put_Prefix(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
self->obj.Prefix(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* IXmlText_get_PreviousSibling(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PreviousSibling());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* IXmlText_get_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InnerText());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int IXmlText_put_InnerText(py::wrapper::Windows::Data::Xml::Dom::IXmlText* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.InnerText(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_IXmlText(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::Data::Xml::Dom::IXmlText>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_IXmlText[] = {
{ "split_text", reinterpret_cast<PyCFunction>(IXmlText_SplitText), METH_VARARGS, nullptr },
{ "append_data", reinterpret_cast<PyCFunction>(IXmlText_AppendData), METH_VARARGS, nullptr },
{ "delete_data", reinterpret_cast<PyCFunction>(IXmlText_DeleteData), METH_VARARGS, nullptr },
{ "insert_data", reinterpret_cast<PyCFunction>(IXmlText_InsertData), METH_VARARGS, nullptr },
{ "replace_data", reinterpret_cast<PyCFunction>(IXmlText_ReplaceData), METH_VARARGS, nullptr },
{ "substring_data", reinterpret_cast<PyCFunction>(IXmlText_SubstringData), METH_VARARGS, nullptr },
{ "append_child", reinterpret_cast<PyCFunction>(IXmlText_AppendChild), METH_VARARGS, nullptr },
{ "clone_node", reinterpret_cast<PyCFunction>(IXmlText_CloneNode), METH_VARARGS, nullptr },
{ "has_child_nodes", reinterpret_cast<PyCFunction>(IXmlText_HasChildNodes), METH_VARARGS, nullptr },
{ "insert_before", reinterpret_cast<PyCFunction>(IXmlText_InsertBefore), METH_VARARGS, nullptr },
{ "normalize", reinterpret_cast<PyCFunction>(IXmlText_Normalize), METH_VARARGS, nullptr },
{ "remove_child", reinterpret_cast<PyCFunction>(IXmlText_RemoveChild), METH_VARARGS, nullptr },
{ "replace_child", reinterpret_cast<PyCFunction>(IXmlText_ReplaceChild), METH_VARARGS, nullptr },
{ "select_nodes", reinterpret_cast<PyCFunction>(IXmlText_SelectNodes), METH_VARARGS, nullptr },
{ "select_nodes_n_s", reinterpret_cast<PyCFunction>(IXmlText_SelectNodesNS), METH_VARARGS, nullptr },
{ "select_single_node", reinterpret_cast<PyCFunction>(IXmlText_SelectSingleNode), METH_VARARGS, nullptr },
{ "select_single_node_n_s", reinterpret_cast<PyCFunction>(IXmlText_SelectSingleNodeNS), METH_VARARGS, nullptr },
{ "get_xml", reinterpret_cast<PyCFunction>(IXmlText_GetXml), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_IXmlText), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_IXmlText[] = {
{ "data", reinterpret_cast<getter>(IXmlText_get_Data), reinterpret_cast<setter>(IXmlText_put_Data), nullptr, nullptr },
{ "length", reinterpret_cast<getter>(IXmlText_get_Length), nullptr, nullptr, nullptr },
{ "attributes", reinterpret_cast<getter>(IXmlText_get_Attributes), nullptr, nullptr, nullptr },
{ "child_nodes", reinterpret_cast<getter>(IXmlText_get_ChildNodes), nullptr, nullptr, nullptr },
{ "first_child", reinterpret_cast<getter>(IXmlText_get_FirstChild), nullptr, nullptr, nullptr },
{ "last_child", reinterpret_cast<getter>(IXmlText_get_LastChild), nullptr, nullptr, nullptr },
{ "local_name", reinterpret_cast<getter>(IXmlText_get_LocalName), nullptr, nullptr, nullptr },
{ "namespace_uri", reinterpret_cast<getter>(IXmlText_get_NamespaceUri), nullptr, nullptr, nullptr },
{ "next_sibling", reinterpret_cast<getter>(IXmlText_get_NextSibling), nullptr, nullptr, nullptr },
{ "node_name", reinterpret_cast<getter>(IXmlText_get_NodeName), nullptr, nullptr, nullptr },
{ "node_type", reinterpret_cast<getter>(IXmlText_get_NodeType), nullptr, nullptr, nullptr },
{ "node_value", reinterpret_cast<getter>(IXmlText_get_NodeValue), reinterpret_cast<setter>(IXmlText_put_NodeValue), nullptr, nullptr },
{ "owner_document", reinterpret_cast<getter>(IXmlText_get_OwnerDocument), nullptr, nullptr, nullptr },
{ "parent_node", reinterpret_cast<getter>(IXmlText_get_ParentNode), nullptr, nullptr, nullptr },
{ "prefix", reinterpret_cast<getter>(IXmlText_get_Prefix), reinterpret_cast<setter>(IXmlText_put_Prefix), nullptr, nullptr },
{ "previous_sibling", reinterpret_cast<getter>(IXmlText_get_PreviousSibling), nullptr, nullptr, nullptr },
{ "inner_text", reinterpret_cast<getter>(IXmlText_get_InnerText), reinterpret_cast<setter>(IXmlText_put_InnerText), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_IXmlText[] =
{
{ Py_tp_new, _new_IXmlText },
{ Py_tp_dealloc, _dealloc_IXmlText },
{ Py_tp_methods, _methods_IXmlText },
{ Py_tp_getset, _getset_IXmlText },
{ },
};
static PyType_Spec _type_spec_IXmlText =
{
"_winsdk_Windows_Data_Xml_Dom.IXmlText",
sizeof(py::wrapper::Windows::Data::Xml::Dom::IXmlText),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_IXmlText
};
// ----- Windows.Data.Xml.Dom Initialization --------------------
static int module_exec(PyObject* module) noexcept
{
try
{
py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) };
py::winrt_type<winrt::Windows::Data::Xml::Dom::DtdEntity>::python_type = py::register_python_type(module, _type_name_DtdEntity, &_type_spec_DtdEntity, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::DtdNotation>::python_type = py::register_python_type(module, _type_name_DtdNotation, &_type_spec_DtdNotation, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlAttribute>::python_type = py::register_python_type(module, _type_name_XmlAttribute, &_type_spec_XmlAttribute, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlCDataSection>::python_type = py::register_python_type(module, _type_name_XmlCDataSection, &_type_spec_XmlCDataSection, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlComment>::python_type = py::register_python_type(module, _type_name_XmlComment, &_type_spec_XmlComment, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocument>::python_type = py::register_python_type(module, _type_name_XmlDocument, &_type_spec_XmlDocument, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocumentFragment>::python_type = py::register_python_type(module, _type_name_XmlDocumentFragment, &_type_spec_XmlDocumentFragment, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDocumentType>::python_type = py::register_python_type(module, _type_name_XmlDocumentType, &_type_spec_XmlDocumentType, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlDomImplementation>::python_type = py::register_python_type(module, _type_name_XmlDomImplementation, &_type_spec_XmlDomImplementation, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlElement>::python_type = py::register_python_type(module, _type_name_XmlElement, &_type_spec_XmlElement, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlEntityReference>::python_type = py::register_python_type(module, _type_name_XmlEntityReference, &_type_spec_XmlEntityReference, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlLoadSettings>::python_type = py::register_python_type(module, _type_name_XmlLoadSettings, &_type_spec_XmlLoadSettings, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlNamedNodeMap>::python_type = py::register_python_type(module, _type_name_XmlNamedNodeMap, &_type_spec_XmlNamedNodeMap, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlNodeList>::python_type = py::register_python_type(module, _type_name_XmlNodeList, &_type_spec_XmlNodeList, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlProcessingInstruction>::python_type = py::register_python_type(module, _type_name_XmlProcessingInstruction, &_type_spec_XmlProcessingInstruction, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::XmlText>::python_type = py::register_python_type(module, _type_name_XmlText, &_type_spec_XmlText, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlCharacterData>::python_type = py::register_python_type(module, _type_name_IXmlCharacterData, &_type_spec_IXmlCharacterData, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNode>::python_type = py::register_python_type(module, _type_name_IXmlNode, &_type_spec_IXmlNode, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNodeSelector>::python_type = py::register_python_type(module, _type_name_IXmlNodeSelector, &_type_spec_IXmlNodeSelector, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlNodeSerializer>::python_type = py::register_python_type(module, _type_name_IXmlNodeSerializer, &_type_spec_IXmlNodeSerializer, bases.get());
py::winrt_type<winrt::Windows::Data::Xml::Dom::IXmlText>::python_type = py::register_python_type(module, _type_name_IXmlText, &_type_spec_IXmlText, bases.get());
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}};
PyDoc_STRVAR(module_doc, "Windows.Data.Xml.Dom");
static PyModuleDef module_def
= {PyModuleDef_HEAD_INIT,
"_winsdk_Windows_Data_Xml_Dom",
module_doc,
0,
nullptr,
module_slots,
nullptr,
nullptr,
nullptr};
} // py::cpp::Windows::Data::Xml::Dom
PyMODINIT_FUNC
PyInit__winsdk_Windows_Data_Xml_Dom (void) noexcept
{
return PyModuleDef_Init(&py::cpp::Windows::Data::Xml::Dom::module_def);
}
| 31.139848 | 221 | 0.543687 | [
"object"
] |
7d3ba8affccc7335330701c734e5dd1316cc82b5 | 14,466 | cpp | C++ | BitmapIcon.cpp | andybantly/MFC-Fractal | 89620fd23b74b7ce73af0a915d0e74fea06f34c1 | [
"Unlicense"
] | 3 | 2022-03-14T15:10:55.000Z | 2022-03-29T22:55:18.000Z | BitmapIcon.cpp | andybantly/MFC-Fractal | 89620fd23b74b7ce73af0a915d0e74fea06f34c1 | [
"Unlicense"
] | null | null | null | BitmapIcon.cpp | andybantly/MFC-Fractal | 89620fd23b74b7ce73af0a915d0e74fea06f34c1 | [
"Unlicense"
] | null | null | null | // Copyright (C) 2012-Present Andrew S. Bantly
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include "stdafx.h"
#include "BitmapIcon.h"
// Construct the frame
CDIBFrame::CDIBFrame() : m_x(0), m_y(0), m_nBitCount(32), m_nScale(4),
m_hBkgFrame(NULL), m_pBkgBits(NULL), m_hLastBkgFrame(NULL),
m_pBitmapInfo(NULL), m_pBitmapInfoHdr(NULL), m_bTrackPalette(false)
{
}
// Construct the frame
CDIBFrame::CDIBFrame(int x,int y,int nBitCount) : m_x(x), m_y(y), m_nBitCount(nBitCount),
m_hBkgFrame(NULL), m_pBkgBits(NULL), m_hLastBkgFrame(NULL),
m_pBitmapInfo(NULL), m_pBitmapInfoHdr(NULL), m_bTrackPalette(false)
{
// Create the frame
CreateFrame();
}
// Copy/Assignment constructor
CDIBFrame::CDIBFrame(const CDIBFrame & rhs)
{
*this = rhs;
}
// Deconstruct the frame
CDIBFrame::~CDIBFrame()
{
// Delete the frame
DeleteFrame();
}
// Copy/Assignment operator
CDIBFrame & CDIBFrame::operator = (const CDIBFrame & rhs)
{
if (this != &rhs)
{
// Initialize
m_bTrackPalette = rhs.m_bTrackPalette;
Init(rhs.m_x,rhs.m_y,rhs.m_bTrackPalette,rhs.m_nBitCount);
// Copy the color information
m_Palette = rhs.m_Palette;
m_RGB = rhs.m_RGB;
// Copy the source
memcpy(m_pBkgBits,rhs.m_pBkgBits,GetSizeImage());
}
return *this;
}
// Set the dimensions and create the frame
void CDIBFrame::Init(int x,int y,bool bTrackPalette,int nBitCount)
{
// Test the dimensions
if (x < 1 || y < 1)
return;
// Test for already being initialized
if (m_FrameDC && m_x == x && m_y == y)
return;
// Set the new dimensions
m_x = x;
m_y = y;
m_bTrackPalette = bTrackPalette;
m_nBitCount = nBitCount;
// Create the frame
CreateFrame();
}
// Create the frame
void CDIBFrame::CreateFrame()
{
// Cleanup the last frame
DeleteFrame();
// Set the scale
if (m_nBitCount == 32)
m_nScale = 4;
else if (m_nBitCount == 24)
m_nScale = 3;
else if (m_nBitCount == 8)
m_nScale = 1;
else if (m_nBitCount == 1)
m_nScale = 1;
// Create a DC for the compatible display
CDC DisplayDC;
DisplayDC.Attach(GetDC(GetDesktopWindow()));
// Create the last frame DC
m_FrameDC.CreateCompatibleDC(&DisplayDC);
if (m_FrameDC)
{
// Calculate the size of the bitmap info structure (header + color table)
DWORD dwLen = 0;
if (m_nBitCount == 8)
dwLen = (DWORD)((WORD)sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
else if (m_nBitCount == 1)
dwLen = (DWORD)((WORD)sizeof(BITMAPINFOHEADER) + 2 * sizeof(RGBQUAD));
else
dwLen = (DWORD)((WORD)sizeof(BITMAPINFOHEADER));
// Allocate the bitmap structure
m_Buffer.resize(dwLen,0);
BYTE * pBuffer = &m_Buffer[0];
// Set up the bitmap info structure for the DIB section
m_pBitmapInfo = (BITMAPINFO*)pBuffer;
m_pBitmapInfoHdr = (BITMAPINFOHEADER*)&(m_pBitmapInfo->bmiHeader);
m_pBitmapInfoHdr->biSize = sizeof(BITMAPINFOHEADER);
m_pBitmapInfoHdr->biWidth = m_x;
m_pBitmapInfoHdr->biHeight = m_y;
m_pBitmapInfoHdr->biPlanes = 1;
m_pBitmapInfoHdr->biBitCount = m_nBitCount;
m_pBitmapInfoHdr->biCompression = BI_RGB;
m_pBitmapInfoHdr->biClrUsed = 0;
m_pBitmapInfoHdr->biClrImportant = 0;
m_pBitmapInfoHdr->biSizeImage = ((m_pBitmapInfoHdr->biWidth * m_pBitmapInfoHdr->biBitCount / 8 + 3) & 0xFFFFFFFC) * m_pBitmapInfoHdr->biHeight;
// 1 meter = 39.3700787 inches
// 1 inch has a specific amount of X and Y pixels
int nLPX = DisplayDC.GetDeviceCaps(LOGPIXELSX);
int nLPY = DisplayDC.GetDeviceCaps(LOGPIXELSY);
m_pBitmapInfoHdr->biXPelsPerMeter = (LONG)(nLPX * 39.3700787 + 0.5);
m_pBitmapInfoHdr->biYPelsPerMeter = (LONG)(nLPY * 39.3700787 + 0.5);
// 256 color gray scale color table embedded in the DIB
if (m_nBitCount == 8)
{
RGBQUAD Colors;
for (int iColor = 0;iColor < 256;iColor++)
{
Colors.rgbBlue = Colors.rgbGreen = Colors.rgbRed = Colors.rgbReserved = iColor;
m_pBitmapInfo->bmiColors[iColor] = Colors;
}
m_pBitmapInfo->bmiHeader.biClrUsed = 256;
}
else if (m_nBitCount == 1)
{
RGBQUAD OffColor = {255,255,255,0};
RGBQUAD OnColor = {0,0,0,0};
m_pBitmapInfo->bmiColors[0] = OffColor;
m_pBitmapInfo->bmiColors[1] = OnColor;
m_pBitmapInfo->bmiHeader.biClrUsed = 2;
}
// Create the DIB for the frame
m_hBkgFrame = CreateDIBSection(m_FrameDC,m_pBitmapInfo,DIB_RGB_COLORS,(void**)&m_pBkgBits,NULL,0);
// Prepare the frame DIB for painting
m_hLastBkgFrame = (HBITMAP)m_FrameDC.SelectObject(m_hBkgFrame);
// Initialize the DIB to black
m_FrameDC.PatBlt(0,0,m_x,m_y,BLACKNESS);
// Initialize the palette
if (m_bTrackPalette && m_nBitCount != 1)
m_Palette.resize(m_x * m_y,0);
}
// Delete the dc's
ReleaseDC(GetDesktopWindow(),DisplayDC.Detach());
}
// Delete the frame
void CDIBFrame::DeleteFrame()
{
// Check for a frame to cleanup
if (m_FrameDC)
{
// UnSelect the DIB
m_FrameDC.SelectObject(m_hLastBkgFrame);
// Delete the DIB for the frame
DeleteObject(m_hBkgFrame);
m_pBkgBits = NULL;
m_pBitmapInfo = NULL;
m_pBitmapInfoHdr = NULL;
m_bTrackPalette = false;
// Delete the last frame DC
m_FrameDC.DeleteDC();
}
}
int CDIBFrame::GetWidth()
{
return m_x;
}
int CDIBFrame::GetHeight()
{
return m_y;
}
void CDIBFrame::SetPixelAndPaletteIndex(int X, int Y, BYTE R, BYTE G, BYTE B, int iPalette)
{
DWORD dwPos = (Y * m_x + X);
m_Palette[dwPos] = iPalette;
dwPos *= m_nScale;
m_pBkgBits[dwPos] = B;
m_pBkgBits[dwPos + 1] = G;
m_pBkgBits[dwPos + 2] = R;
}
void CDIBFrame::SetPixel(int X, int Y, BYTE R, BYTE G, BYTE B)
{
DWORD dwPos = (Y * m_x + X) * m_nScale;
m_pBkgBits[dwPos] = B;
m_pBkgBits[dwPos + 1] = G;
m_pBkgBits[dwPos + 2] = R;
}
void CDIBFrame::SetPixelPaletteIndex(int X, int Y, int iPalette)
{
DWORD dwPos = (Y * m_x + X);
m_Palette[dwPos] = iPalette;
}
void CDIBFrame::GetPixelAndPaletteIndex(int X, int Y, BYTE & R, BYTE & G, BYTE & B, int & iPalette)
{
DWORD dwPos = (Y * m_x + X);
iPalette = m_Palette[dwPos];
dwPos *= m_nScale;
B = m_pBkgBits[dwPos];
G = m_pBkgBits[dwPos + 1];
R = m_pBkgBits[dwPos + 2];
}
void CDIBFrame::GetPixel(int X, int Y, BYTE & R, BYTE & G, BYTE & B)
{
DWORD dwPos = (Y * m_x + X) * m_nScale;
B = m_pBkgBits[dwPos];
G = m_pBkgBits[dwPos + 1];
R = m_pBkgBits[dwPos + 2];
}
void CDIBFrame::GetPixelPaletteIndex(int X,int Y,int & iPalette)
{
DWORD dwPos = (Y * m_x + X);
iPalette = m_Palette[dwPos];
}
void CDIBFrame::SetRGB(std::vector<std::vector<BYTE> > & RGB)
{
m_RGB = RGB;
}
std::vector<std::vector<BYTE> > & CDIBFrame::GetRGB()
{
return m_RGB;
}
DWORD CDIBFrame::GetPixelCount()
{
return GetSizeImage() / m_nScale;
}
void CDIBFrame::DrawTo(HDC hDC,int x,int y,DWORD dwROP,HBRUSH hPatternBrush)
{
if (hPatternBrush)
hPatternBrush = (HBRUSH)SelectObject(hDC,hPatternBrush);
BitBlt(hDC,x,y,m_x,m_y,(HDC)m_FrameDC,0,0,dwROP);
if (hPatternBrush)
SelectObject(hDC,hPatternBrush);
}
void CDIBFrame::GradientFill(COLORREF arrRGB[],int nRGB,int R,int G,int B)
{
// Need an even amount of at least 2 colors
if (nRGB < 2 || nRGB % 2 == 1)
return;
// Define the gradient rectangle
GRADIENT_RECT gRect;
gRect.UpperLeft = 0;
gRect.LowerRight = 1;
// Get the COLOR16 colors
int ix = 0;
double dx = 1.0 / (double)(nRGB - 1);
int nx = (int)((double)m_x * dx);
TRIVERTEX Vert[2];
for (int iRGB = 0;iRGB < nRGB - 1;++iRGB)
{
int R1 = GetRValue(arrRGB[iRGB]) << 8;
int G1 = GetGValue(arrRGB[iRGB]) << 8;
int B1 = GetBValue(arrRGB[iRGB]) << 8;
int R2 = GetRValue(arrRGB[iRGB + 1]) << 8;
int G2 = GetGValue(arrRGB[iRGB + 1]) << 8;
int B2 = GetBValue(arrRGB[iRGB + 1]) << 8;
// Define the beginning gradient vertice
Vert[0].x = ix;
Vert[0].y = 0;
Vert[0].Red = R1;
Vert[0].Green = G1;
Vert[0].Blue = B1;
Vert[0].Alpha = 0;
// Define the ending gradient vertice
ix += nx;
if (iRGB + 1 == nRGB - 1)
ix = m_x;
Vert[1].x = ix;
Vert[1].y = m_y;
Vert[1].Red = R2;
Vert[1].Green = G2;
Vert[1].Blue = B2;
Vert[1].Alpha = 0;
// Fill the area with the gradient
::GradientFill((HDC)m_FrameDC,&Vert[0],2,&gRect,1,GRADIENT_FILL_RECT_H);
}
if (R || G || B)
{
// Scale the gradient with the base scale colors
for (int X = 0;X < m_x;++X)
{
for (int Y = 0;Y < m_y;++Y)
{
BYTE R1,G1,B1;
GetPixel(X,Y,R1,G1,B1);
R1 += R;
G1 += G;
B1 += B;
SetPixel(X,Y,R1,G1,B1);
}
}
}
}
void CDIBFrame::Fill(COLORREF RGB)
{
// Fill the area with a solid color
m_FrameDC.FillSolidRect(0,0,m_x,m_y,RGB);
}
// Blend two frames together to the destination, factoring out the key color of the foreground image
void CDIBFrame::MixFrame(int iMixAmt,CDIBFrame & DIBFore,CDIBFrame & DIBBack)
{
// Get the foreground color data
LPSTR pDIBForeBits = (LPSTR)DIBFore;
// Get the background color data
LPSTR pDIBBackBits = (LPSTR)DIBBack;
// Get the source and destination Bytes
BYTE * pDestBytes = (BYTE *)m_pBkgBits;
BYTE * pForeBytes = (BYTE *)pDIBForeBits;
BYTE * pBackBytes = (BYTE *)pDIBBackBits;
// Alpha blending level (0-255)
BYTE alpha = iMixAmt;
BYTE alpha2 = 255 - alpha;
// Process the DIB
DWORD dwBytes = GetSizeImage();
for (DWORD dw = 0;dw < dwBytes;dw += m_nScale)
{
// Get the foreground pixel
BYTE FR,FG,FB;
FB = pForeBytes[dw];
FG = pForeBytes[dw + 1];
FR = pForeBytes[dw + 2];
// Get the background pixel
BYTE BR,BG,BB;
BB = pBackBytes[dw];
BG = pBackBytes[dw + 1];
BR = pBackBytes[dw + 2];
// Get the destination pixel
BYTE & DB = pDestBytes[dw];
BYTE & DG = pDestBytes[dw + 1];
BYTE & DR = pDestBytes[dw + 2];
// Update by blending the sources to the destination
DB = (BB * alpha2 + FB * alpha) >> 8;
DG = (BG * alpha2 + FG * alpha) >> 8;
DR = (BR * alpha2 + FR * alpha) >> 8;
}
}
// Convert DIB to a DDB
HBITMAP CDIBFrame::ToDDB()
{
return CreateDIBitmap((HDC)m_FrameDC,m_pBitmapInfoHdr,CBM_INIT,(const void *)m_pBkgBits,m_pBitmapInfo,DIB_RGB_COLORS);
}
// The Petzold DrawBitmap function
void CDIBFrame::DrawDDBBitmap(HBITMAP hBitmap,int xStart,int yStart,DWORD dwROP,HBRUSH hPatternBrush)
{
HDC hdc = (HDC)m_FrameDC;
BITMAP bm;
HDC hdcMem;
POINT ptSize,ptOrg;
hdcMem = CreateCompatibleDC(hdc);
SelectObject(hdcMem,hBitmap);
SetMapMode(hdcMem,GetMapMode(hdc));
GetObject(hBitmap,sizeof(BITMAP),(LPVOID)&bm);
ptSize.x = bm.bmWidth;
ptSize.y = bm.bmHeight;
DPtoLP(hdc,&ptSize,1);
ptOrg.x = 0;
ptOrg.y = 0;
DPtoLP(hdcMem,&ptOrg,1);
if (hPatternBrush)
hPatternBrush = (HBRUSH)SelectObject(hdc,hPatternBrush);
BitBlt(hdc,xStart,yStart,ptSize.x,ptSize.y,hdcMem,ptOrg.x,ptOrg.y,dwROP);
if (hPatternBrush)
SelectObject(hdc,hPatternBrush);
DeleteDC(hdcMem);
}
// Convert the DIB to a DDB
void CDIBFrame::DrawDDBTo(CDIBFrame & Dest,int xStart,int yStart,DWORD dwROP,HBRUSH hPatternBrush)
{
CBitmap Bitmap;
Bitmap.Attach(ToDDB());
Dest.DrawDDBBitmap(Bitmap,xStart,yStart,dwROP,hPatternBrush);
}
// Convert the DIB to a pattern brush by way of DIB to DDB
HBRUSH CDIBFrame::DIBPatternBrush()
{
CBitmap BMPBrush;
BMPBrush.Attach(ToDDB());
CBrush PatternBrush;
PatternBrush.CreatePatternBrush(&BMPBrush);
HBRUSH hPatternBrush = (HBRUSH)PatternBrush.Detach();
return hPatternBrush;
}
CBitmapIcon::CBitmapIcon() : m_nID(0), m_crTransparentColor(RGB(0,0,0))
{
}
CBitmapIcon::CBitmapIcon(UINT nID) : m_nID(nID), m_crTransparentColor(RGB(0,0,0))
{
Initialize();
}
CBitmapIcon::CBitmapIcon(const CBitmapIcon & rhs)
{
*this = rhs;
}
CBitmapIcon::~CBitmapIcon()
{
}
CBitmapIcon & CBitmapIcon::operator = (const CBitmapIcon & rhs)
{
if (this != &rhs)
{
m_nID = rhs.m_nID;
Initialize();
}
return *this;
}
void CBitmapIcon::Load(UINT nID)
{
m_nID = nID;
Initialize();
}
void CBitmapIcon::LoadIcon(UINT nID)
{
m_Icon.LoadIcon(nID);
}
UINT CBitmapIcon::GetWidth()
{
return m_Icon.GetWidth();
}
UINT CBitmapIcon::GetHeight()
{
return m_Icon.GetHeight();
}
COLORREF CBitmapIcon::GetTransparentColor()
{
return m_crTransparentColor;
}
CBitmapIcon::operator HICON()
{
return m_Icon;
}
void CBitmapIcon::Initialize()
{
m_Bitmap.DeleteObject();
if (m_Bitmap.LoadBitmap(m_nID))
ConvertBitmap();
}
void CBitmapIcon::ConvertBitmap(HBITMAP hBitmap)
{
// Set the bitmap
CBitmap * pBitmap;
if (hBitmap == NULL)
pBitmap = &m_Bitmap;
else
pBitmap = CBitmap::FromHandle(hBitmap);
// Create a memory DC that contains the loaded up bitmap
CDC ImageDC;
ImageDC.CreateCompatibleDC(NULL);
CBitmap * pOldImageBitmap = ImageDC.SelectObject(pBitmap);
// Get the transparent pixel from the upper left of the bitmap
m_crTransparentColor = ImageDC.GetPixel(0,0);
// Get the bitmap information
BITMAP bm;
pBitmap->GetBitmap(&bm);
// Create a memory DC for the mask monochrome bitmap
CDC MaskDC;
MaskDC.CreateCompatibleDC(NULL);
// Initialize the "mask" monochrome bitmap
CBitmap MaskBitmap;
MaskBitmap.CreateBitmap(bm.bmWidth,bm.bmHeight,1,1,NULL);
CBitmap * pOldMaskBitmap = MaskDC.SelectObject(&MaskBitmap);
// Create the "mask" bitmap
ImageDC.SetBkColor(m_crTransparentColor);
MaskDC.BitBlt(0,0,bm.bmWidth,bm.bmHeight,&ImageDC,0,0,SRCCOPY);
// Create a memory DC for the color bitmap
CDC ColorDC;
ColorDC.CreateCompatibleDC(NULL);
// Initialize the "color" bitmap
CBitmap ColorBitmap;
ColorBitmap.CreateCompatibleBitmap(&ImageDC,bm.bmWidth,bm.bmHeight);
CBitmap * pOldOrBitmap = ColorDC.SelectObject(&ColorBitmap);
// Create the "color" bitmap
ColorDC.BitBlt(0,0,bm.bmWidth,bm.bmHeight,&ImageDC,0,0,SRCCOPY);
ColorDC.BitBlt(0,0,bm.bmWidth,bm.bmHeight,&MaskDC,0,0,0x220326);
// Clean up the image bitmap
ImageDC.SelectObject(pOldImageBitmap);
// Clean up the "color" bitmap
ColorDC.SelectObject(pOldOrBitmap);
// Clean up the "mask" bitmap
MaskDC.SelectObject(pOldMaskBitmap);
// Create the Icon
m_Icon.CreateIcon((HBITMAP)MaskBitmap,(HBITMAP)ColorBitmap);
}
HICON CBitmapIcon::CreateFromBitmap(HBITMAP hBitmap)
{
// Convert the bitmap to an icon
ConvertBitmap(hBitmap);
// Return the Icon
return (HICON)m_Icon;
} | 24.231156 | 145 | 0.698051 | [
"vector",
"solid"
] |
7d431cb6118efdb7bbb9d947fc13b590adaa4891 | 10,415 | cpp | C++ | project.2/project2.cpp | Svetoslavna/Project-DataBase | 9c718853e0741952093299f7fdd3d19c1bb97979 | [
"BSD-2-Clause"
] | 1 | 2019-09-12T07:35:12.000Z | 2019-09-12T07:35:12.000Z | project.2/project2.cpp | Svetoslavna/Project-DataBase | 9c718853e0741952093299f7fdd3d19c1bb97979 | [
"BSD-2-Clause"
] | null | null | null | project.2/project2.cpp | Svetoslavna/Project-DataBase | 9c718853e0741952093299f7fdd3d19c1bb97979 | [
"BSD-2-Clause"
] | null | null | null | #include "project2.h"
using namespace std;
typedef map<string, int> mapT;
mapT tables;
int save_tables() {
string fname = "Tables.bin";
FILE* fp = fopen(fname.c_str(), "w");
if (!fp)
return -errno;
mapT::iterator it = tables.begin();
for (int i = 0; it != tables.end(); it++, i++) {
fprintf(fp, "%s=%s\n", it->first.c_str(), to_string(it->second).c_str());
}
fclose(fp);
return 0;
}
int read_tables()
{
string fname = "Tables.bin";
ifstream input(fname);
string line;
tables.clear();
char* buf = 0;
size_t buflen = 0;
regex wrd("\\w+");
while (getline(input, line)) {
sregex_iterator wrd_next(line.begin(), line.end(), wrd);
//wrd_next++;
smatch match = *wrd_next;
string tn = match.str();
wrd_next++;
match = *wrd_next;
int tl = stoi(match.str());
tables[tn] = tl;
}
return 0;
}
int create_table(string s, int n) {
mapT::iterator it = tables.find(s);
if (it == tables.end()) {
tables[s] = n;
ofstream file;
file.open(s + ".dat", std::ofstream::out | std::ofstream::app);
file.close();
save_tables();
return 0;
}
else
{
//cout << "error of table creating 1" << endl;
return 1;
}
}
int delete_table(string s) {
mapT::iterator it = tables.find(s);
if (it != tables.end()) {
tables.erase(s);
if (remove((s + ".dat").c_str())) {
//cout << "Error removing file" << endl;
return 2;
}
else {
save_tables();
return 0;
}
}
else
{
//cout << "error of table deleting 2" << endl;
return 2;
}
}
string str_toupper(string s) {
transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return toupper(c); }
);
return s;
}
SClient::SClient(SOCKET s, SOCKADDR_IN sock_in)
{
c_sock = s;
c_addr = sock_in;
printf("Client created\n");
HandleThread = CreateThread(NULL, 0, ThreadF, this, 0, &IdThread);
}
SClient::~SClient()
{
TerminateThread(HandleThread, NULL);
CloseHandle(HandleThread);
}
int foo(string stroka, SOCKET &d_sock)
{
string stroke = str_toupper(stroka);
string chislo = "(\\-*\\d+(.\\d+){0,1})";
string datar = "\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d\\s\\d\\d\\:\\d\\d\\:\\d\\d";
regex insrt("I\\s+\\w+\\s+\\(" + chislo + "(\\s*\\,\\s+" + chislo + ")*\\)");
regex insrt2("\\(" + chislo + "(\\s*\\,\\s+" + chislo + ")*\\)");
regex crt("C\\s+\\w+\\s+\\d+");
regex dlt("D\\s+\\w+");
regex slt("S\\s+\\w+\\s+" + datar);
regex chi(chislo);
regex wrd("\\w+");
regex dtr(datar);
try {
sregex_iterator insrt_next(stroke.begin(), stroke.end(), insrt);
sregex_iterator end;
if (insrt_next != end) {
sregex_iterator wrd_next(stroke.begin(), stroke.end(), wrd);
wrd_next++;
smatch match = *wrd_next;
string table_name = match.str();
sregex_iterator chisla_next(stroke.begin(), stroke.end(), insrt2);
match = *chisla_next;
string chisla = match.str();
sregex_iterator next(chisla.begin(), chisla.end(), chi);
int nn = 0;
float chisla2[50];
while (next != end) {
nn += 1;
smatch match = *next;
chisla2[nn - 1] = stof(match.str());
next++;
}
mapT::iterator it = tables.find(table_name);
if (it != tables.end()) {
if (tables[table_name] == nn) {
time_t t = time(0);
ofstream file;
file.open(table_name + ".dat", ios::binary | ofstream::out | ofstream::in);
file.seekp(0, ios_base::end);
file.write((char*)(&t), sizeof(time_t));
file.write((char*)(&chisla2), sizeof(float) * nn);
file.close();
}
else {
//cout << "error 4" << endl;
return 4;
}
}
else {
///cout << "error 5" << endl;
return 5;
}
}
else {
sregex_iterator crt_next(stroke.begin(), stroke.end(), crt);
if (crt_next != end) {
sregex_iterator wrd_next(stroke.begin(), stroke.end(), wrd);
wrd_next++;
smatch match = *wrd_next;
string table_name = match.str();
wrd_next++;
match = *wrd_next;
int nn = stoi(match.str());
if (nn > 0) {
int err = create_table(table_name, nn);
if (err > 0) {
///cout << "error 2" << endl;
return 2;
}
}
else {
///cout << "error 1" << endl;
return 1;
}
}
else {
sregex_iterator dlt_next(stroke.begin(), stroke.end(), dlt);
if (dlt_next != end) {
sregex_iterator wrd_next(stroke.begin(), stroke.end(), wrd);
wrd_next++;
smatch match = *wrd_next;
string table_name = match.str();
int err = delete_table(table_name);
if (err > 0) {
///cout << "error 3" << endl;
return 3;
}
}
else {
sregex_iterator slt_next(stroke.begin(), stroke.end(), slt);
if (slt_next != end) {
sregex_iterator wrd_next(stroke.begin(), stroke.end(), wrd);
wrd_next++;
smatch match = *wrd_next;
string table_name = match.str();
sregex_iterator dtr_next(stroke.begin(), stroke.end(), dtr);
match = *dtr_next;
string startdata = match.str();
mapT::iterator it = tables.find(table_name);
if (it != tables.end()) {
tm tt1;
try
{
tt1.tm_sec = (startdata[17] - 48) * 10 + startdata[18] - 48;
tt1.tm_min = (startdata[14] - 48) * 10 + startdata[15] - 48;
tt1.tm_hour = (startdata[11] - 48) * 10 + startdata[12] - 48;
tt1.tm_mday = (startdata[0] - 48) * 10 + startdata[1] - 48;
tt1.tm_mon = (startdata[3] - 48) * 10 + startdata[4] - 48 - 1;
tt1.tm_year = (startdata[6] - 48) * 1000 + (startdata[7] - 48) * 100 + (startdata[8] - 48) * 10 + startdata[9] - 48 - 1900;
time_t tt2 = mktime(&tt1);
ifstream in(table_name + ".dat", ios::binary);
// Создаем вектор с соответствующим размером (запрашиваем его через
// выставление указателя на конец файла)
vector<unsigned char> v(in.seekg(0, ios::end).tellg());
// Возвращаем указатель на место
in.seekg(0, ios::beg);
// Читаем файл в вектор
in.read((char*)v.data(), v.size());
int params = tables[table_name];
int dl_zapis = 8 + params * 4;
int zapis = v.size() / dl_zapis;
if (zapis > 0) {
time_t* tt0 = (time_t*)&v[0];
time_t* ttn = (time_t*)&v[(zapis - 1) * dl_zapis];
if (tt2 > * ttn){
v.clear();
return 10;
}
else {
int startpos = 0;
if (tt2 > * tt0) {
int pos1 = 0;
int posn = zapis - 1;
while (pos1 + 1 < posn) {
int pos3 = (pos1 + posn) / 2;
time_t* tt3 = (time_t*)&v[pos3 * dl_zapis];
if (tt2 > * tt3) {
pos1 = pos3;
}
else {
posn = pos3;
}
}
startpos = posn;
}
char mm[1024];
memcpy(mm, v.data() + startpos*dl_zapis, 1024);
v.clear();
char mm1[4];
mm1[0] = 0;
mm1[1] = 0;
mm1[2] = params;
int ter = 1024 / dl_zapis;
if (startpos + ter > zapis) {
ter = zapis - startpos;
}
mm1[3] = ter;
send(d_sock, mm1, sizeof(mm1), NULL);
Sleep(10);
send(d_sock, mm, sizeof(mm), NULL);
//cout << asctime(localtime(tt0)) << endl;
//cout << asctime(localtime(ttn)) << endl;
//cout << params << " " << dl_zapis << " " << zapis << endl;
//v.clear();
return 0;
}
}
else {
v.clear();
return 9;
}
}
catch (...)
{
//cout << "error " << endl;
return 8;
}
}
else {
///cout << "error 5" << endl;
return 5;
}
}
else {
///cout << "error 6" << endl;
return 6;
}
}
}
}
}
catch (regex_error& e) {
cout << "regex error" << endl;
return 7;
}
return 0;
}
string str(char* a)
{
int i;
string s = "";
int ii = 0;
for (i = 0; i < DEFAULT_BUFFER_LENGTH; i++) {
if(ii==0)
s = s + a[i];
if (a[i] == 0)
ii = 1;
}
return s;
}
unsigned long SClient::CalculationThread()
{
//d_sock = &c_sock;
int er;
char recvstr[DEFAULT_BUFFER_LENGTH];
er = recv(c_sock, recvstr, DEFAULT_BUFFER_LENGTH, NULL);
if (er > 0) {
string stroka = str(recvstr);
cout << stroka << endl;
int res=-foo(stroka, c_sock);
char* c = (char*)&res;
char msg1[4];
msg1[0] = *c;
msg1[1] = *(c + 1);
msg1[2] = *(c + 2);
msg1[3] = *(c + 3);
send(c_sock, msg1, sizeof(msg1), NULL);
Sleep(10);
return res;
}
else if (er == 0) {
cout << "connection terminated\n";
return 1;
}
else {
cout << "connection error" << endl;
return 2;
}
///int k = recv(c_sock, buffer, sizeof(buffer), NULL);
///printf("%u\n", k);
Sleep(30);
}
SServer::SServer()
{
}
SServer::~SServer()
{
}
void SServer::startServer()
{
if (WSAStartup(MAKEWORD(2, 2), &wData) == 0)
{
printf("WSA Startup succes\n");
}
SOCKADDR_IN addr;
int addrl = sizeof(addr);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
addr.sin_port = htons(port);
cin.clear();
addr.sin_family = AF_INET;
SOCKADDR ssdf;
this_s = socket(AF_INET, SOCK_STREAM, NULL);
if (this_s == SOCKET_ERROR) {
printf("Socket not created\n");
}
if (bind(this_s, (struct sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR) {
printf("Socket succed binded\n");
}
if (listen(this_s, SOMAXCONN) != SOCKET_ERROR)
{
printf("Start listenin at port%u\n", ntohs(addr.sin_port));
}
handle();
}
void SServer::closeServer() {
closesocket(this_s);
WSACleanup();
cout << "Server was stoped. You can close app" << endl;
}
void SServer::handle() {
while (true)
{
SOCKET acceptS;
SOCKADDR_IN addr_c;
int addrlen = sizeof(addr_c);
char buffer[512];
struct sockaddr_in from_struct;
int froml = sizeof(from_struct);
if ((acceptS = accept(this_s, (struct sockaddr*)&addr_c, &addrlen)) != 0) {
printf("send\n");
printf("sended Client connected from 0 %u.%u.%u.%u:%u\n",
(unsigned char)addr_c.sin_addr.S_un.S_un_b.s_b1,
(unsigned char)addr_c.sin_addr.S_un.S_un_b.s_b2,
(unsigned char)addr_c.sin_addr.S_un.S_un_b.s_b3,
(unsigned char)addr_c.sin_addr.S_un.S_un_b.s_b4,
ntohs(addr_c.sin_port));
SClient* client = new SClient(acceptS, addr_c);
}
Sleep(200);
}
}
int main()
{
read_tables();
SServer* server = new SServer();
server->port = 3487;
server->startServer();
return 0;
}
| 24.053118 | 132 | 0.544503 | [
"vector",
"transform"
] |
7d51d2e2cce873fe026e0c352cbf15a31cd77b98 | 1,432 | cc | C++ | caffe2/transforms/single_op_transform.cc | KevinKecc/caffe2 | a2b6c6e2f0686358a84277df65e9489fb7d9ddb2 | [
"Apache-2.0"
] | 585 | 2015-08-10T02:48:52.000Z | 2021-12-01T08:46:59.000Z | caffe2/transforms/single_op_transform.cc | mingzhe09088/caffe2 | 8f41717c46d214aaf62b53e5b3b9b308b5b8db91 | [
"Apache-2.0"
] | 27 | 2018-04-14T06:44:22.000Z | 2018-08-01T18:02:39.000Z | caffe2/transforms/single_op_transform.cc | mingzhe09088/caffe2 | 8f41717c46d214aaf62b53e5b3b9b308b5b8db91 | [
"Apache-2.0"
] | 183 | 2015-08-10T02:49:04.000Z | 2021-12-01T08:47:13.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "caffe2/transforms/single_op_transform.h"
#include "caffe2/core/common.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/net.h"
#include "caffe2/proto/caffe2.pb.h"
namespace caffe2 {
using transform::Graph;
bool SingleOpTransform::PatternRule(
const Graph& g,
const std::vector<int>& subgraph,
int idx) {
if (subgraph.size() == 0) {
return MatchOperator(g.node(idx).op);
}
return false;
}
bool SingleOpTransform::ValidatorRule(
const Graph& g,
const std::vector<int>& subgraph) {
if (subgraph.size() == 1) {
return true;
}
return false;
}
bool SingleOpTransform::ReplaceRule(
const std::vector<int>& subgraph,
Graph* g_ptr) {
CHECK(g_ptr);
auto& g = *g_ptr;
ReplaceOperator(&(g.node(subgraph[0]).op));
return true;
}
} // namespace caffe2
| 25.122807 | 75 | 0.698324 | [
"vector",
"transform"
] |
7d599008037b284d33bee7fd1730012a0c180cb5 | 16,002 | cpp | C++ | src/LORE/Renderer/Renderers/Forward2DRenderer.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | 2 | 2021-07-14T06:05:48.000Z | 2021-07-14T18:07:18.000Z | src/LORE/Renderer/Renderers/Forward2DRenderer.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | src/LORE/Renderer/Renderers/Forward2DRenderer.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
// The MIT License (MIT)
// This source file is part of LORE
// ( Lightweight Object-oriented Rendering Engine )
//
// Copyright (c) 2017-2021 Jordan Sparks
//
// 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 "Forward2DRenderer.h"
#include <LORE/Config/Config.h>
#include <LORE/Math/Math.h>
#include <LORE/Resource/Box.h>
#include <LORE/Resource/Prefab.h>
#include <LORE/Renderer/IRenderAPI.h>
#include <LORE/Resource/Font.h>
#include <LORE/Resource/Sprite.h>
#include <LORE/Resource/StockResource.h>
#include <LORE/Resource/Textbox.h>
#include <LORE/Resource/Texture.h>
#include <LORE/Scene/AABB.h>
#include <LORE/Scene/Camera.h>
#include <LORE/Scene/Light.h>
#include <LORE/Scene/Scene.h>
#include <LORE/Scene/SpriteController.h>
#include <LORE/Shader/GPUProgram.h>
#include <LORE/Window/RenderTarget.h>
#include <LORE/Window/Window.h>
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
using namespace Lore;
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
Forward2DRenderer::Forward2DRenderer()
{
// Initialize all available queues.
_queues.resize( DefaultRenderQueueCount );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::addRenderData( PrefabPtr prefab,
NodePtr node )
{
// TODO: Consider a way of optimizing this by skipping processing data here
// and directly storing references to nodes in lists in the renderer.
const uint queueId = prefab->getRenderQueue();
const bool blended = prefab->getMaterial()->blendingMode.enabled;
// TODO: Fix two lookups here.
// Add this queue to the active queue list if not already there.
activateQueue( queueId, _queues[queueId] );
//
// Add render data for this prefab at the node's position to the queue.
RenderQueue& queue = _queues.at( queueId );
if ( blended ) {
RenderQueue::PrefabNodePair pair { prefab, node };
queue.transparents.insert( { node->getDepth(), pair } );
}
else {
if ( prefab->isInstanced() ) {
RenderQueue::InstancedPrefabSet& set = queue.instancedSolids;
// Only add instanced prefabs that haven't been processed yet.
if ( set.find( prefab ) == set.end() ) {
set.insert( prefab );
}
}
else {
RenderQueue::NodeList& nodes = queue.solids[prefab];
nodes.push_back( node );
}
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::addBox( BoxPtr box,
const glm::mat4& transform )
{
const uint queueId = RenderQueue::General;
activateQueue( queueId, _queues[queueId] );
RenderQueue& queue = _queues.at( queueId );
RenderQueue::BoxData data;
data.box = box;
data.model = transform;
queue.boxes.push_back( data );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::addTextbox( TextboxPtr textbox,
const glm::mat4& transform )
{
const uint queueId = textbox->getRenderQueue();
activateQueue( queueId, _queues[queueId] );
RenderQueue& queue = _queues.at( queueId );
RenderQueue::TextboxData data;
data.textbox = textbox;
data.model = transform;
queue.textboxes.push_back( data );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::addLight( LightPtr light, const NodePtr node )
{
const uint queueId = RenderQueue::General;
activateQueue( queueId, _queues[queueId] );
RenderQueue& queue = _queues.at( queueId );
switch ( light->getType() ) {
default:
break;
case Light::Type::Directional:
queue.lights.directionalLights.push_back( static_cast< DirectionalLightPtr >( light ) );
break;
case Light::Type::Point:
queue.lights.pointLights.emplace_back( static_cast< PointLightPtr >( light ), node->getWorldPosition() );
break;
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::present( const RenderView& rv, const WindowPtr window )
{
// Build render queues for this RenderView.
rv.scene->updateSceneGraph();
const real aspectRatio = (rv.renderTarget) ? rv.renderTarget->getAspectRatio() : window->getAspectRatio();
rv.camera->updateTracking();
if ( rv.renderTarget ) {
rv.renderTarget->bind();
_api->setViewport( 0,
0,
static_cast<uint32_t>( rv.viewport.w * rv.renderTarget->getWidth() ),
static_cast<uint32_t>( rv.viewport.h * rv.renderTarget->getHeight() ) );
}
else {
// TODO: Get rid of gl_viewport.
_api->setViewport( rv.gl_viewport.x,
rv.gl_viewport.y,
rv.gl_viewport.width,
rv.gl_viewport.height );
}
_api->setDepthTestEnabled( true );
Color bg = rv.scene->getSkyboxColor();
_api->clear();
_api->clearColor( bg.r, bg.g, bg.b, 1.f );
_api->setPolygonMode( IRenderAPI::PolygonMode::Fill );
_api->setCullingMode( IRenderAPI::CullingMode::Back );
// Setup view-projection matrix.
// TODO: Take viewport dimensions into account. Cache more things inside window.
const glm::mat4 projection = glm::ortho( -aspectRatio, aspectRatio,
-1.f, 1.f,
1500.f, -1500.f );
const glm::mat4 viewProjection = projection * rv.camera->getViewMatrix();
// Render skybox before scene node prefabs.
renderSkybox( rv, aspectRatio, projection );
// Iterate through all active render queues and render each object.
for ( const auto& activeQueue : _activeQueues ) {
RenderQueue& queue = activeQueue.second;
// Render solids.
renderSolids( rv, queue, viewProjection );
// Render transparents.
renderTransparents( rv, queue, viewProjection );
// Render boxes.
renderBoxes( queue, viewProjection );
}
// AABBs.
/*auto renderAABBs = Config::GetValue( "RenderAABBs" );
if ( GET_VARIANT<bool>( renderAABBs ) ) {
RenderQueue tmpQueue;
std::function<void( NodePtr )> AddAABB = [&] ( NodePtr node ) {
AABBPtr aabb = node->getAABB();
if ( aabb ) {
RenderQueue::BoxData data;
data.box = aabb->getBox();
data.model = Math::CreateTransformationMatrix( node->getWorldPosition(), glm::quat(), aabb->getDimensions() * 5.f );
data.model[3][2] = Node::Depth::Min;
tmpQueue.boxes.push_back( data );
}
Node::ChildNodeIterator it = node->getChildNodeIterator();
while ( it.hasMore() ) {
AddAABB( it.getNext() );
}
};
auto root = rv.scene->getRootNode();
Node::ChildNodeIterator it = root->getChildNodeIterator();
while ( it.hasMore() ) {
AddAABB( it.getNext() );
}
renderBoxes( tmpQueue, viewProjection );
}*/
if ( rv.renderTarget ) {
rv.renderTarget->flush();
// Re-bind default frame buffer if custom render target was specified.
_api->bindDefaultFramebuffer();
}
_clearRenderQueues();
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::_clearRenderQueues()
{
// Remove all data from each queue.
for ( auto& queue : _queues ) {
queue.clear();
}
// Erase all queues from the active queue list.
_activeQueues.clear();
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::activateQueue( const uint id, RenderQueue& rq )
{
const auto lookup = _activeQueues.find( id );
if ( _activeQueues.end() == lookup ) {
_activeQueues.insert( { id, rq } );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::renderSkybox( const RenderView& rv,
const real aspectRatio,
const glm::mat4& proj )
{
SkyboxPtr skybox = rv.scene->getSkybox();
const SkyboxLayerMap& layers = skybox->getLayerMap();
ModelPtr model = StockResource::GetModel( "Skybox2D" );
const glm::vec3 camPos = rv.camera->getPosition();
for ( const auto& pair : layers ) {
const SkyboxLayer& layer = pair.second;
MaterialPtr mat = layer.getMaterial();
// TODO: Move this to uniform updaters in Skybox2D program.
if ( mat->sprite && mat->sprite->getTextureCount( 0, Texture::Type::Diffuse ) ) {
GPUProgramPtr program = mat->program;
// Enable blending if set.
if ( mat->blendingMode.enabled ) {
_api->setBlendingEnabled( true );
_api->setBlendingFunc( mat->blendingMode.srcFactor, mat->blendingMode.dstFactor );
}
// Get the active sprite frame for this layer.
size_t spriteFrame = 0;
if ( layer.getSpriteController() ) {
spriteFrame = layer.getSpriteController()->getActiveFrame();
}
TexturePtr texture = mat->sprite->getTexture( spriteFrame, Texture::Type::Diffuse );
program->use();
texture->bind();
program->setUniformVar( "gamma", rv.gamma );
Rect sampleRegion = mat->getTexSampleRegion();
program->setUniformVar( "texSampleRegion.x", sampleRegion.x );
program->setUniformVar( "texSampleRegion.y", sampleRegion.y );
program->setUniformVar( "texSampleRegion.w", sampleRegion.w );
program->setUniformVar( "texSampleRegion.h", sampleRegion.h );
program->setUniformVar( "material.diffuse", mat->diffuse );
// Apply scrolling and parallax offsets.
glm::vec2 offset = mat->getTexCoordOffset();
offset.x += camPos.x * layer.getParallax().x;
offset.y += camPos.y * layer.getParallax().y;
program->setUniformVar( "texSampleOffset", offset );
glm::mat4 transform( 1.f );
transform[0][0] = aspectRatio;
transform[1][1] = glm::clamp( aspectRatio, 1.f, 90.f ); // HACK to prevent clipping skybox on aspect ratios < 1.0.
transform[3][2] = layer.getDepth();
program->setTransformVar( proj * transform );
model->draw( program );
}
if ( mat->blendingMode.enabled ) {
_api->setBlendingEnabled( false );
}
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::renderSolids( const RenderView& rv,
const RenderQueue& queue,
const glm::mat4& viewProjection ) const
{
// Render instanced solids.
for ( const auto& prefab : queue.instancedSolids ) {
MaterialPtr material = prefab->getMaterial();
ModelPtr model = prefab->getInstancedModel();
GPUProgramPtr program = material->program;
const NodePtr node = prefab->getInstanceControllerNode();
_api->setCullingMode( prefab->cullingMode );
program->use();
program->updateUniforms( rv, material, queue.lights );
program->updateNodeUniforms( material, node, viewProjection );
model->draw( program, prefab->getInstanceCount() );
}
// Render non-instanced solids.
for ( auto& pair : queue.solids ) {
const PrefabPtr prefab = pair.first;
const RenderQueue::NodeList& nodes = pair.second;
const MaterialPtr material = prefab->getMaterial();
const ModelPtr model = prefab->getModel();
const GPUProgramPtr program = material->program;
_api->setCullingMode( prefab->cullingMode );
program->use();
program->updateUniforms( rv, material, queue.lights );
// Render each node associated with this prefab.
for ( const auto& node : nodes ) {
program->updateNodeUniforms( material, node, viewProjection );
model->draw( program );
}
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::renderTransparents( const RenderView& rv,
const RenderQueue& queue,
const glm::mat4& viewProjection ) const
{
_api->setBlendingEnabled( true );
// Render in forward order, so the farthest back is rendered first.
// (Depth values increase going farther back).
for (const auto& pair : queue.transparents) {
const PrefabPtr prefab = pair.second.first;
NodePtr node = pair.second.second;
const MaterialPtr material = prefab->getMaterial();
GPUProgramPtr program = material->program;
ModelPtr model = prefab->getModel();
if ( prefab->isInstanced() ) {
node = prefab->getInstanceControllerNode();
model = prefab->getInstancedModel();
switch ( model->getType() ) {
default:
throw Lore::Exception( "Instanced prefab must have an instanced model" );
case Mesh::Type::QuadInstanced:
program = StockResource::GetGPUProgram( "StandardInstanced2D" );
break;
case Mesh::Type::TexturedQuadInstanced:
program = StockResource::GetGPUProgram( "StandardTexturedInstanced2D" );
break;
}
}
// Set blending mode using material settings.
_api->setBlendingFunc( material->blendingMode.srcFactor, material->blendingMode.dstFactor );
_api->setCullingMode( prefab->cullingMode );
program->use();
program->updateUniforms( rv, material, queue.lights );
program->updateNodeUniforms( material, node, viewProjection );
// Draw the prefab.
model->draw( program, prefab->getInstanceCount() );
}
_api->setBlendingEnabled( false );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void Forward2DRenderer::renderBoxes( const RenderQueue& queue,
const glm::mat4& viewProjection ) const
{
_api->setBlendingEnabled( true );
_api->setBlendingFunc( BlendFactor::SrcAlpha, BlendFactor::OneMinusSrcAlpha );
GPUProgramPtr program = StockResource::GetGPUProgram( "StandardBox2D" );
ModelPtr model = StockResource::GetModel( "TexturedQuad" );
program->use();
for ( const RenderQueue::BoxData& data : queue.boxes ) {
BoxPtr box = data.box;
program->setUniformVar( "borderColor", box->getBorderColor() );
program->setUniformVar( "fillColor", box->getFillColor() );
program->setUniformVar( "borderWidth", box->getBorderWidth() );
program->setUniformVar( "scale", glm::vec2( data.model[0][0], data.model[1][1] ) * box->getSize() );
// Apply box scaling to final transform.
glm::mat4 modelMatrix = data.model;
modelMatrix[0][0] *= box->getWidth();
modelMatrix[1][1] *= box->getHeight();
program->setTransformVar( viewProjection * modelMatrix );
model->draw( program );
}
_api->setBlendingEnabled( false );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
| 33.830867 | 124 | 0.603862 | [
"mesh",
"render",
"object",
"model",
"transform"
] |
7d5e319dc80fe7d98e05fba9a834edbbca7fee41 | 1,518 | hpp | C++ | include/bs/temporal_median.hpp | gitter-badger/bs | 217e5fc1bf07b40441b73c5ba002f6dfe1ab0592 | [
"MIT"
] | 1 | 2021-02-28T20:15:52.000Z | 2021-02-28T20:15:52.000Z | include/bs/temporal_median.hpp | nikkoara/bs | 1d4339f0acb5967a4b8229f95f3ada577531d5d6 | [
"MIT"
] | null | null | null | include/bs/temporal_median.hpp | nikkoara/bs | 1d4339f0acb5967a4b8229f95f3ada577531d5d6 | [
"MIT"
] | 1 | 2020-11-30T12:57:47.000Z | 2020-11-30T12:57:47.000Z | #ifndef BS_TEMPORAL_MEDIAN_HPP
#define BS_TEMPORAL_MEDIAN_HPP
#include <bs/defs.hpp>
#include <bs/detail/base.hpp>
#include <opencv2/core/mat.hpp>
#include <boost/circular_buffer.hpp>
#include <vector>
namespace bs {
//
// Mostly based on the algorithm described in:
//
// @inproceedings{Calderara:2006:RBS:1178782.1178814,
// author = {Calderara, Simone and Melli, Rudy and Prati, Andrea and Cucchiara,
// Rita},
// title = {Reliable Background Suppression for Complex Scenes},
// booktitle = {Proceedings of the 4th ACM International Workshop on Video
// Surveillance and Sensor Networks},
// series = {VSSN '06},
// year = {2006},
// isbn = {1-59593-496-0},
// location = {Santa Barbara, California, USA},
// pages = {211--214},
// numpages = {4},
// url = {http://doi.acm.org/10.1145/1178782.1178814},
// doi = {10.1145/1178782.1178814},
// acmid = {1178814},
// publisher = {ACM},
// address = {New York, NY, USA},
// keywords = {background suppression, people detection and tracking, shadow
// detection},
// }
//
struct temporal_median_t : detail::base_t {
explicit temporal_median_t (
const cv::Mat&, size_t = 9, size_t = 16, size_t = 30, size_t = 60);
const cv::Mat&
operator() (const cv::Mat&);
private:
cv::Mat
calculate_median () const;
cv::Mat
merge_masks (const cv::Mat&, const cv::Mat&);
private:
boost::circular_buffer< cv::Mat > history_;
size_t lo_, hi_, frame_interval_, frame_counter_;
};
}
#endif // BS_TEMPORAL_MEDIAN_HPP
| 24.885246 | 80 | 0.66996 | [
"vector"
] |
de105facf17364faefdcbfb052c231f6f76c9771 | 5,807 | cpp | C++ | client/Rendering/CameraOrbital.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | client/Rendering/CameraOrbital.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | client/Rendering/CameraOrbital.cpp | firesgc/NovusCore-Client | 406010cfeca88b82363debe7dd9ca8d5e839b7f4 | [
"MIT"
] | null | null | null | #include "CameraOrbital.h"
#include <windows.h>
#include <InputManager.h>
#include <filesystem>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <GLFW/glfw3.h>
#include <Window/Window.h>
#include <Utils/DebugHandler.h>
#include <Utils/FileReader.h>
#include "../Utils/ServiceLocator.h"
#include "../Utils/MapUtils.h"
namespace fs = std::filesystem;
void CameraOrbital::Init()
{
InputManager* inputManager = ServiceLocator::GetInputManager();
inputManager->RegisterMouseScrollCallback("CameraOrbital Mouse Scroll", [this](Window* window, f32 xPos, f32 yPos)
{
if (!IsActive())
return;
_distance = glm::clamp(_distance - yPos, 5.f, 30.f);
});
inputManager->RegisterMousePositionCallback("CameraOrbital MouseLook", [this, inputManager](Window* window, f32 xPos, f32 yPos)
{
if (!IsActive())
return;
if (_captureMouse)
{
vec2 mousePosition = vec2(xPos, yPos);
if (_captureMouseHasMoved)
{
vec2 deltaPosition = _prevMousePosition - mousePosition;
_yaw += deltaPosition.x * _mouseSensitivity;
if (_yaw > 360)
_yaw -= 360;
else if (_yaw < 0)
_yaw += 360;
_pitch = Math::Clamp(_pitch + (deltaPosition.y * _mouseSensitivity), -89.0f, 89.0f);
/* TODO: Add proper collision for the camera so we don't go through the ground
the below code will do a quick test for the pitch but not the yaw.
We also need to use "distToCollision" to possibly add an offset.
f32 tmpPitch = Math::Clamp(_pitch + (deltaPosition.y * _mouseSensitivity), -89.0f, 89.0f);
f32 dist = tmpPitch - _pitch;
mat4x4 rotationMatrix = glm::yawPitchRoll(glm::radians(_yaw), glm::radians(_pitch), 0.0f);
vec3 t = vec3(_rotationMatrix * vec4(vec3(0, 0, _distance), 0.0f));
vec3 position = _position + t;
Geometry::AABoundingBox box;
box.min = position - vec3(0.5f, 2.5f, 0.5f);
box.max = position + vec3(0.5f, 2.5f, 0.5f);
Geometry::Triangle triangle;
f32 height = 0;
f32 distToCollision = 0;
if (!Terrain::MapUtils::Intersect_AABB_TERRAIN_SWEEP(box, triangle, height, dist, distToCollision))
{
_pitch = tmpPitch;
}*/
}
else
_captureMouseHasMoved = true;
_prevMousePosition = mousePosition;
}
});
inputManager->RegisterKeybind("CameraOrbital Left Mouseclick", GLFW_MOUSE_BUTTON_1, KEYBIND_ACTION_CLICK, KEYBIND_MOD_ANY, [this, inputManager](Window* window, std::shared_ptr<Keybind> keybind)
{
if (!IsActive())
return false;
if (inputManager->IsKeyPressed("CameraOrbital Right Mouseclick"_h))
return false;
if (keybind->state == GLFW_PRESS)
{
if (!_captureMouse)
{
_captureMouse = true;
_prevMousePosition = vec2(inputManager->GetMousePositionX(), inputManager->GetMousePositionY());
glfwSetInputMode(window->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
}
else
{
if (_captureMouse)
{
_captureMouse = false;
_captureMouseHasMoved = false;
glfwSetInputMode(window->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
return true;
});
inputManager->RegisterKeybind("CameraOrbital Right Mouseclick", GLFW_MOUSE_BUTTON_2, KEYBIND_ACTION_CLICK, KEYBIND_MOD_ANY, [this, inputManager](Window* window, std::shared_ptr<Keybind> keybind)
{
if (!IsActive())
return false;
if (inputManager->IsKeyPressed("CameraOrbital Left Mouseclick"_h))
return false;
if (keybind->state == GLFW_PRESS)
{
if (!_captureMouse)
{
_captureMouse = true;
_prevMousePosition = vec2(inputManager->GetMousePositionX(), inputManager->GetMousePositionY());
glfwSetInputMode(window->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
}
else
{
if (_captureMouse)
{
_captureMouse = false;
_captureMouseHasMoved = false;
glfwSetInputMode(window->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
return true;
});
}
void CameraOrbital::Enabled()
{
}
void CameraOrbital::Disabled()
{
_captureMouse = false;
_captureMouseHasMoved = false;
glfwSetInputMode(_window->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
void CameraOrbital::Update(f32 deltaTime, float fovInDegrees, float aspectRatioWH)
{
// Compute matrices
mat4x4 offsetPitchMatrix = glm::yawPitchRoll(0.0f, glm::radians(90.0f), 0.0f);
mat4x4 offsetYawMatrix = glm::yawPitchRoll(glm::radians(-90.0f), 0.0f, 0.0f);
_rotationMatrix = offsetPitchMatrix * offsetYawMatrix * glm::yawPitchRoll(glm::radians(_yaw), glm::radians(_pitch), 0.0f);
vec3 t = vec3(_rotationMatrix * vec4(vec3(0, 0, _distance), 0.0f));
vec3 position = _position + t;
_viewMatrix = glm::lookAt(position, _position, worldUp);
_projectionMatrix = glm::perspective(glm::radians(fovInDegrees), aspectRatioWH, GetFarClip(), GetNearClip());
_viewProjectionMatrix = _projectionMatrix * _viewMatrix;
UpdateCameraVectors();
UpdateFrustumPlanes(glm::transpose(_viewProjectionMatrix));
}
| 34.158824 | 198 | 0.597727 | [
"geometry"
] |
de12a70380de87ab1c3fc12a424112847bc56f4b | 15,291 | hxx | C++ | libbrep/build.hxx | build2/brep | d259750511b3c2aaeace49f8ccb1d7f3ad561452 | [
"MIT"
] | 9 | 2018-05-30T12:01:14.000Z | 2021-04-02T21:21:10.000Z | libbrep/build.hxx | build2/brep | d259750511b3c2aaeace49f8ccb1d7f3ad561452 | [
"MIT"
] | 2 | 2021-03-28T14:13:39.000Z | 2022-01-24T12:57:57.000Z | libbrep/build.hxx | build2/brep | d259750511b3c2aaeace49f8ccb1d7f3ad561452 | [
"MIT"
] | 2 | 2019-01-09T12:09:39.000Z | 2022-03-06T18:43:07.000Z | // file : libbrep/build.hxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#ifndef LIBBREP_BUILD_HXX
#define LIBBREP_BUILD_HXX
#include <chrono>
#include <odb/core.hxx>
#include <odb/section.hxx>
#include <libbutl/target-triplet.hxx>
#include <libbrep/types.hxx>
#include <libbrep/utility.hxx>
#include <libbrep/common.hxx>
#include <libbrep/build-package.hxx>
// Must be included after libbrep/common.hxx, so that the _version structure
// get defined before libbpkg/manifest.hxx inclusion.
//
// Note that if we start using assert() in get/set expressions in this header,
// we will have to redefine it for ODB compiler after all include directives
// (see libbrep/common.hxx for details).
//
#include <libbbot/manifest.hxx>
// Used by the data migration entries.
//
#define LIBBREP_BUILD_SCHEMA_VERSION_BASE 15
#pragma db model version(LIBBREP_BUILD_SCHEMA_VERSION_BASE, 16, closed)
// We have to keep these mappings at the global scope instead of inside
// the brep namespace because they need to be also effective in the
// bbot namespace from which we "borrow" types (and some of them use the mapped
// types).
//
#pragma db map type(bbot::result_status) as(std::string) \
to(to_string (?)) \
from(bbot::to_result_status (?))
namespace brep
{
#pragma db value
struct build_id
{
package_id package;
string configuration;
string toolchain_name;
canonical_version toolchain_version;
build_id () = default;
build_id (package_id p, string c, string n, const brep::version& v)
: package (move (p)),
configuration (move (c)),
toolchain_name (move (n)),
toolchain_version (v) {}
};
inline bool
operator< (const build_id& x, const build_id& y)
{
if (x.package != y.package)
return x.package < y.package;
if (int r = x.configuration.compare (y.configuration))
return r < 0;
if (int r = x.toolchain_name.compare (y.toolchain_name))
return r < 0;
return compare_version_lt (x.toolchain_version, y.toolchain_version, true);
}
// These allow comparing objects that have package, configuration,
// toolchain_name, and toolchain_version data members to build_id values.
// The idea is that this works for both query members of build id types as
// well as for values of the build_id type.
//
template <typename T>
inline auto
operator== (const T& x, const build_id& y)
-> decltype (x.package == y.package &&
x.configuration == y.configuration &&
x.toolchain_name == y.toolchain_name &&
x.toolchain_version.epoch == y.toolchain_version.epoch)
{
return x.package == y.package &&
x.configuration == y.configuration &&
x.toolchain_name == y.toolchain_name &&
compare_version_eq (x.toolchain_version, y.toolchain_version, true);
}
template <typename T>
inline auto
operator!= (const T& x, const build_id& y)
-> decltype (x.package == y.package &&
x.configuration == y.configuration &&
x.toolchain_name == y.toolchain_name &&
x.toolchain_version.epoch == y.toolchain_version.epoch)
{
return x.package != y.package ||
x.configuration != y.configuration ||
x.toolchain_name != y.toolchain_name ||
compare_version_ne (x.toolchain_version, y.toolchain_version, true);
}
// build_state
//
enum class build_state: std::uint8_t
{
building,
built
};
string
to_string (build_state);
build_state
to_build_state (const string&); // May throw invalid_argument.
inline ostream&
operator<< (ostream& os, build_state s) {return os << to_string (s);}
#pragma db map type(build_state) as(string) \
to(to_string (?)) \
from(brep::to_build_state (?))
// force_state
//
enum class force_state: std::uint8_t
{
unforced,
forcing, // Rebuild is forced while being in the building state.
forced // Rebuild is forced while being in the built state.
};
string
to_string (force_state);
force_state
to_force_state (const string&); // May throw invalid_argument.
inline ostream&
operator<< (ostream& os, force_state s) {return os << to_string (s);}
#pragma db map type(force_state) as(string) \
to(to_string (?)) \
from(brep::to_force_state (?))
// result_status
//
using bbot::result_status;
using optional_result_status = optional<result_status>;
#pragma db map type(optional_result_status) as(optional_string) \
to((?) ? bbot::to_string (*(?)) : brep::optional_string ()) \
from((?) \
? bbot::to_result_status (*(?)) \
: brep::optional_result_status ())
// target_triplet
//
#pragma db map type(butl::target_triplet) as(string) \
to((?).string ()) \
from(butl::target_triplet (?))
// operation_results
//
using bbot::operation_result;
#pragma db value(operation_result) definition
using bbot::operation_results;
#pragma db object pointer(shared_ptr) session
class build
{
public:
using timestamp_type = brep::timestamp;
using package_name_type = brep::package_name;
// Create the build object with the building state, non-existent status,
// the timestamp set to now, and the force state set to unforced.
//
build (string tenant,
package_name_type,
version,
string configuration,
string toolchain_name, version toolchain_version,
optional<string> interactive,
optional<string> agent_fingerprint,
optional<string> agent_challenge,
string machine, string machine_summary,
butl::target_triplet,
string controller_checksum,
string machine_checksum);
build_id id;
string& tenant; // Tracks id.package.tenant.
package_name_type& package_name; // Tracks id.package.name.
upstream_version package_version; // Original of id.package.version.
string& configuration; // Tracks id.configuration.
string& toolchain_name; // Tracks id.toolchain_name.
upstream_version toolchain_version; // Original of id.toolchain_version.
build_state state;
// If present, the login information for the interactive build. May be
// present only in the building state.
//
optional<string> interactive;
// Time of the last state change (the creation time initially).
//
timestamp_type timestamp;
force_state force;
// Must be present for the built state, may be present for the building
// state.
//
optional<result_status> status;
// Times of the last soft/hard completed (re)builds. Used to decide when
// to perform soft and hard rebuilds, respectively.
//
// The soft timestamp is updated whenever we receive a task result.
//
// The hard timestamp is updated whenever we receive a task result with
// a status other than skip.
//
// Also note that whenever hard_timestamp is updated, soft_timestamp is
// updated as well and whenever soft_timestamp is updated, timestamp is
// updated as well. Thus the following condition is always true:
//
// hard_timestamp <= soft_timestamp <= timestamp
//
// Note that the "completed" above means that we may analyze the task
// result/log and deem it as not completed and proceed with automatic
// rebuild (the flake monitor idea).
//
timestamp_type soft_timestamp;
timestamp_type hard_timestamp;
// May be present only for the building state.
//
optional<string> agent_fingerprint;
optional<string> agent_challenge;
string machine;
string machine_summary;
butl::target_triplet target;
// Note that the logs are stored as std::string/TEXT which is Ok since
// they are UTF-8 and our database is UTF-8.
//
operation_results results;
odb::section results_section;
// Checksums of entities involved in the build.
//
// Optional checksums are provided by the external entities (agent and
// worker). All are absent initially.
//
// Note that the agent checksum can also be absent after the hard rebuild
// task is issued and the worker and dependency checksums - after a failed
// rebuild (error result status or worse).
//
string controller_checksum;
string machine_checksum;
optional<string> agent_checksum;
optional<string> worker_checksum;
optional<string> dependency_checksum;
// Database mapping.
//
#pragma db member(id) id column("")
#pragma db member(tenant) transient
#pragma db member(package_name) transient
#pragma db member(package_version) \
set(this.package_version.init (this.id.package.version, (?)))
#pragma db member(configuration) transient
#pragma db member(toolchain_name) transient
#pragma db member(toolchain_version) \
set(this.toolchain_version.init (this.id.toolchain_version, (?)))
// Speed-up queries with ordering the result by the timestamp.
//
#pragma db member(timestamp) index
#pragma db member(results) id_column("") value_column("") \
section(results_section)
#pragma db member(results_section) load(lazy) update(always)
build (const build&) = delete;
build& operator= (const build&) = delete;
private:
friend class odb::access;
build ()
: tenant (id.package.tenant),
package_name (id.package.name),
configuration (id.configuration),
toolchain_name (id.toolchain_name) {}
};
// Note that ADL can't find the equal operator in join conditions, so we use
// the function call notation for them.
//
// Toolchains of existing buildable package builds.
//
#pragma db view object(build) \
object(build_package inner: \
brep::operator== (build::id.package, build_package::id) && \
build_package::buildable) \
query(distinct)
struct toolchain
{
string name;
upstream_version version;
// Database mapping. Note that the version member must be loaded after
// the virtual members since the version_ member must filled by that time.
//
#pragma db member(name) column(build::id.toolchain_name)
#pragma db member(version) column(build::toolchain_version) \
set(this.version.init (this.version_, (?)))
#pragma db member(epoch) virtual(uint16_t) \
before(version) access(version_.epoch) \
column(build::id.toolchain_version.epoch)
#pragma db member(canonical_upstream) virtual(std::string) \
before(version) access(version_.canonical_upstream) \
column(build::id.toolchain_version.canonical_upstream)
#pragma db member(canonical_release) virtual(std::string) \
before(version) access(version_.canonical_release) \
column(build::id.toolchain_version.canonical_release)
#pragma db member(revision) virtual(uint16_t) \
before(version) access(version_.revision) \
column(build::id.toolchain_version.revision)
private:
friend class odb::access;
#pragma db transient
canonical_version version_;
};
// Build of an existing buildable package.
//
#pragma db view \
object(build) \
object(build_package inner: \
brep::operator== (build::id.package, build_package::id) && \
build_package::buildable) \
object(build_tenant: build_package::id.tenant == build_tenant::id)
struct package_build
{
shared_ptr<brep::build> build;
};
#pragma db view \
object(build) \
object(build_package inner: \
brep::operator== (build::id.package, build_package::id) && \
build_package::buildable) \
object(build_tenant: build_package::id.tenant == build_tenant::id)
struct package_build_count
{
size_t result;
operator size_t () const {return result;}
// Database mapping.
//
#pragma db member(result) column("count(" + build::id.package.name + ")")
};
// Used to track the package build delays since the last build or, if not
// present, since the first opportunity to build the package.
//
#pragma db object pointer(shared_ptr) session
class build_delay
{
public:
using package_name_type = brep::package_name;
// If toolchain version is empty, then the object represents a minimum
// delay across all versions of the toolchain.
//
build_delay (string tenant,
package_name_type, version,
string configuration,
string toolchain_name, version toolchain_version,
timestamp package_timestamp);
build_id id;
string& tenant; // Tracks id.package.tenant.
package_name_type& package_name; // Tracks id.package.name.
upstream_version package_version; // Original of id.package.version.
string& configuration; // Tracks id.configuration.
string& toolchain_name; // Tracks id.toolchain_name.
upstream_version toolchain_version; // Original of id.toolchain_version.
// Times of the latest soft and hard rebuild delay reports. Initialized
// with timestamp_nonexistent by default.
//
// Note that both reports notify about initial build delays (at their
// respective time intervals).
//
timestamp report_soft_timestamp;
timestamp report_hard_timestamp;
// Time when the package is initially considered as buildable for this
// configuration and toolchain. It is used to track the build delay if the
// build object is absent (the first build task is not yet issued, the
// build is removed by brep-clean, etc).
//
timestamp package_timestamp;
// Database mapping.
//
#pragma db member(id) id column("")
#pragma db member(tenant) transient
#pragma db member(package_name) transient
#pragma db member(package_version) \
set(this.package_version.init (this.id.package.version, (?)))
#pragma db member(configuration) transient
#pragma db member(toolchain_name) transient
#pragma db member(toolchain_version) \
set(this.toolchain_version.init (this.id.toolchain_version, (?)))
private:
friend class odb::access;
build_delay ()
: tenant (id.package.tenant),
package_name (id.package.name),
configuration (id.configuration),
toolchain_name (id.toolchain_name) {}
};
}
#endif // LIBBREP_BUILD_HXX
| 33.313725 | 79 | 0.638938 | [
"object",
"model"
] |
de1a04c2a28fc6c5b5f0320f36aa190b434f8ed1 | 1,709 | cpp | C++ | Src/Collision/GeometryQuery.cpp | atlantis13579/Riemann | 5c4dcf08a0438e702f082be7876d9017ccd598f8 | [
"MIT"
] | 2 | 2021-07-06T05:24:07.000Z | 2021-07-07T01:52:41.000Z | Src/Collision/GeometryQuery.cpp | atlantis13579/Riemann | 5c4dcf08a0438e702f082be7876d9017ccd598f8 | [
"MIT"
] | null | null | null | Src/Collision/GeometryQuery.cpp | atlantis13579/Riemann | 5c4dcf08a0438e702f082be7876d9017ccd598f8 | [
"MIT"
] | null | null | null |
#include "GeometryQuery.h"
#include <algorithm>
#include "AABBTree.h"
#include "DynamicAABBTree.h"
#include "SparseSpatialHash.h"
GeometryQuery::GeometryQuery()
{
m_staticGeometry = nullptr;
m_dynamicPruner = nullptr;
m_SpatialHash = nullptr;
}
GeometryQuery::~GeometryQuery()
{
if (m_staticGeometry)
{
delete m_staticGeometry;
m_staticGeometry = nullptr;
}
if (m_dynamicPruner)
{
delete m_dynamicPruner;
m_dynamicPruner = nullptr;
}
if (m_SpatialHash)
{
delete m_SpatialHash;
m_SpatialHash = nullptr;
}
}
void GeometryQuery::BuildStaticGeometry(const std::vector<Geometry*>& Objects, int nPrimitivePerNode)
{
if (m_staticGeometry == nullptr)
{
m_staticGeometry = new AABBTree;
std::vector<Box3d> boxes;
boxes.resize(Objects.size());
for (size_t i = 0; i < Objects.size(); ++i)
{
boxes[i] = Objects[i]->GetBoundingVolume_WorldSpace();
}
m_Objects = Objects;
AABBTreeBuildData param(&boxes[0], (int)boxes.size(), nPrimitivePerNode);
m_staticGeometry->StaticBuild(param);
}
}
bool GeometryQuery::RayCast(const Vector3d& Origin, const Vector3d& Dir, const RayCastOption& Option, RayCastResult* Result)
{
Result->Reset();
if (m_staticGeometry)
{
Ray3d ray(Origin, Dir);
Geometry** pp = &m_Objects[0];
return m_staticGeometry->RayCast(ray, pp, Option, Result);
}
return false;
}
bool GeometryQuery::OverlapBox(const Vector3d& Center, const Vector3d& Extent, const OverlapOption& Option, OverlapResult* Result)
{
Result->Reset();
Geometry* Box = GeometryFactory::CreateOBB(Center, Extent);
Geometry** pp = &m_Objects[0];
m_staticGeometry->Overlap(Box, pp, Option, Result);
GeometryFactory::DeleteGeometry(Box);
return Result->overlaps;
}
| 21.910256 | 130 | 0.729666 | [
"geometry",
"vector"
] |
de1a54ea6c16d7447bba35af29fd4b39561149b6 | 1,521 | cpp | C++ | 2020-11-04/teleport.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | 2 | 2020-12-12T00:02:40.000Z | 2021-04-21T19:49:59.000Z | 2020-11-04/teleport.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | 2020-11-04/teleport.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long int huge;
const huge inf = 100010001000LL;
const int maxn = 200200;
struct interval {
huge begin, end;
vector<huge> bonus;
huge best_distance() {
if (bonus.empty())
return 0;
huge left = 2*(*bonus.rbegin() - begin);
huge right = 2*(end - *bonus.begin());
huge best = min(left, right);
huge through = end - begin;
best = min(best, through);
for(unsigned i=1; i<bonus.size(); ++i) {
huge current = 2*(bonus[i-1] - begin + end - bonus[i]);
best = min(best, current);
}
return best;
}
void debug() {
printf("%lld ~ %lld\n", begin, end);
printf("%lu:", bonus.size());
for(auto i : bonus)
printf(" %lld", i);
printf("\n%lld\n\n", best_distance());
}
};
interval ring[maxn];
int main() {
int n, m;
scanf(" %d %d", &n, &m);
ring[0].begin = -inf;
ring[n].end = inf;
for(int i=0; i<n; ++i) {
scanf(" %lld", &ring[i].end);
ring[i+1].begin = ring[i].end;
}
int current_ring=0;
for(int i=0; i<m; ++i) {
huge current_bonus;
scanf(" %lld", ¤t_bonus);
while(current_bonus > ring[current_ring].end)
++current_ring;
ring[current_ring].bonus.push_back(current_bonus);
}
huge total=0;
for(int i=0; i<=n; ++i) {
// ring[i].debug();
total+=ring[i].best_distance();
}
printf("%lld\n", total);
return 0;
}
| 23.045455 | 62 | 0.543721 | [
"vector"
] |
de1cac7f80ed78686cb57c7d9f794e9e47228aa9 | 48,040 | cpp | C++ | src/couchit/couchDB.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | 4 | 2017-03-20T22:14:10.000Z | 2018-03-21T09:24:32.000Z | src/couchit/couchDB.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | src/couchit/couchDB.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | /*
* couchDB.cpp
*
* Created on: 8. 3. 2016
* Author: ondra
*/
#include <fstream>
#include <assert.h>
#include <couchit/validator.h>
#include <mutex>
#include "changeset.h"
#include "couchDB.h"
#include <imtjson/json.h>
#include <imtjson/value.h>
#include <imtjson/binjson.tcc>
#include <experimental/string_view>
#include "shared/logOutput.h"
#include "batch.h"
#include "exception.h"
#include "query.h"
#include "changes.h"
#include "defaultUIDGen.h"
#include "queryCache.h"
#include "document.h"
#include "showProc.h"
#include "updateProc.h"
using ondra_shared::logFatal;
using std::experimental::fundamentals_v1::string_view;
namespace couchit {
StrViewA CouchDB::fldTimestamp("~timestamp");
std::size_t CouchDB::maxSerializedKeysSizeForGETRequest = 1024;
CouchDB::CouchDB(const Config& cfg)
:cfg(cfg)
,curConnections(0)
,uidGen(cfg.uidgen == nullptr?DefaultUIDGen::getInstance():*cfg.uidgen)
,queryable(*this)
{
if (!cfg.authInfo.username.empty()) {
authObj = Object("name",cfg.authInfo.username)
("password",cfg.authInfo.password);
}
}
CouchDB::CouchDB(const CouchDB& other)
:cfg(other.cfg)
,curConnections(0)
,uidGen(other.uidGen)
,authObj(other.authObj)
,queryable(*this)
{
}
void CouchDB::setCurrentDB(String database) {
cfg.databaseName = database.str();
}
String CouchDB::getCurrentDB() const {
return cfg.databaseName;
}
void CouchDB::createDatabase() {
PConnection conn = getConnection();
requestPUT(conn,Value());
}
void CouchDB::createDatabase(unsigned int numShards, unsigned int numReplicas) {
PConnection conn = getConnection();
conn->add("n", numReplicas);
conn->add("q", numShards);
requestPUT(conn,Value());
}
void CouchDB::deleteDatabase() {
PConnection conn = getConnection();
requestDELETE(conn,nullptr);
}
CouchDB::~CouchDB() {
assert(curConnections == 0);
}
enum ListenExceptionStop {listenExceptionStop};
Query CouchDB::createQuery(const View &view) {
return Query(view, queryable);
}
Changeset CouchDB::createChangeset() {
return Changeset(*this);
}
SeqNumber CouchDB::getLastSeqNumber() {
ChangesFeed chsink = createChangesFeed();
Changes chgs = chsink.setFilterFlags(::couchit::Filter::reverseOrder).limit(1).setTimeout(0).exec();
if (chgs.hasItems()) return ChangeEvent(chgs.getNext()).seqId;
else return SeqNumber();
}
SeqNumber CouchDB::getLastKnownSeqNumber() const {
LockGuard _(lock);
return lksqid;
}
Query CouchDB::createQuery(std::size_t viewFlags) {
View v("_all_docs", viewFlags|View::update);
return createQuery(v);
}
Query CouchDB::allDocs(Flags viewFlags) {
View v("_all_docs", viewFlags|View::update);
return createQuery(v);
}
Query CouchDB::localDocs(Flags viewFlags) {
View v("_local_docs", viewFlags|View::update);
return createQuery(v);
}
static std::string readFile(const std::string &name) {
std::ifstream in(name);
if (!in) return std::string();
std::string res;
std::getline(in, res);
return res;
}
static std::string generateNodeID() {
std::string id = readFile("/etc/machine-id");
if (!id.empty()) return id;
std::string path;
const char* home = getenv("HOME");
path.append(home);
path.append("/.couchit-machine-id");
id = readFile(path);
if (!id.empty()) return id;
std::vector<char> buffer;
DefaultUIDGen::getInstance()(buffer, "");
{
std::ofstream out(path, std::ios::out| std::ios::trunc);
out.write(buffer.data(), buffer.size());
out << std::endl;
if (!out) throw std::runtime_error("Need node_id - and can't generate anyone");
}
id = readFile(path);
if (!id.empty()) return id;
throw std::runtime_error("Unable to generate node_id");
}
Value CouchDB::getLocal(const StrViewA &localId, std::size_t flags) {
if (flags & flgNodeLocal) {
if (cfg.node_id.empty()) {
static std::string localId =generateNodeID();
cfg.node_id = localId;
}
std::string id = cfg.node_id;
id.push_back(':');
id.append(localId.data, localId.length);
return getLocal(id, flags & ~flgNodeLocal);
}
PConnection conn = getConnection("_local");
conn->add(localId);
try {
return requestGET(conn,nullptr, flags & (flgDisableCache|flgRefreshCache));
} catch (const RequestError &e) {
if (e.getCode() == 404 && (flags & flgCreateNew)) {
return Object("_id",String({"_local/",localId}));
}
else throw;
}
}
StrViewA CouchDB::lkGenUID() const {
return uidGen(uidBuffer,StrViewA());
}
StrViewA CouchDB::lkGenUID(StrViewA prefix) const {
return uidGen(uidBuffer,prefix);
}
Value CouchDB::get(const StrViewA &docId, const StrViewA & revId, std::size_t flags) {
if (flags & flgNodeLocal) {
if (cfg.node_id.empty()) {
static std::string localId =generateNodeID();
cfg.node_id = localId;
}
std::string id = docId;
id.push_back(':');
id.append(cfg.node_id);
return get(id, flags & ~flgNodeLocal);
}
PConnection conn = getConnection();
conn->add(docId);
if (!revId.empty()) conn->add("rev",revId);
if (flags & flgAttachments) conn->add("attachments","true");
if (flags & flgAttEncodingInfo) conn->add("att_encoding_info","true");
if (flags & flgConflicts) conn->add("conflicts","true");
if (flags & flgDeletedConflicts) conn->add("deleted_conflicts","true");
if (flags & flgSeqNumber) conn->add("local_seq","true");
if (flags & flgRevisions) conn->add("revs","true");
if (flags & flgRevisionsInfo) conn->add("revs_info","true");
if (cfg.readQuorum) conn->add("r",cfg.readQuorum);
try {
return requestGET(conn,nullptr,flags & (flgDisableCache|flgRefreshCache));
} catch (const RequestError &e) {
if (e.getCode() == 404) {
if (flags & flgCreateNew) {
return Object("_id",docId);
} else if (flags & flgNullIfMissing) {
return nullptr;
}
}
throw;
}
}
Value CouchDB::get(const StrViewA &docId, std::size_t flags) {
return get(docId, StrViewA(), flags);
}
UpdateResult CouchDB::execUpdateProc(StrViewA updateHandlerPath, StrViewA documentId,
Value arguments) {
PConnection conn = getConnection(updateHandlerPath);
conn->add(documentId);
for (auto &&v:arguments) {
StrViewA key = v.getKey();
String vstr = v.toString();
conn->add(key,vstr);
}
Value h(Object("Accept","*/*"));
Value v = requestPUT(conn, nullptr, &h, flgStoreHeaders);
lksqid.markOld();
String rev (h["X-Couch-Update-NewRev"]);
String ctt(h["content-type"]);
if (ctt != "application/json") {
return UpdateResult(v["content"],ctt, rev);
} else {
return UpdateResult(v,ctt, rev);
}
}
ShowResult CouchDB::execShowProc(const StrViewA &showHandlerPath, const StrViewA &documentId,
const Value &arguments, std::size_t flags) {
PConnection conn = getConnection(showHandlerPath);
conn->add(documentId);
for (auto &&v:arguments) {
StrViewA key = v.getKey();
String vstr = v.toString();
conn->add(key,vstr);
}
Value h(Object("Accept","*/*"));
Value v = requestGET(conn,&h,flags|flgStoreHeaders);
String ctt(h["content-type"]);
if (ctt != "application/json") {
return ShowResult(v["content"],ctt);
} else {
return ShowResult(v,ctt);
}
}
Upload CouchDB::putAttachment(const Value &document, const StrViewA &attachmentName, const StrViewA &contentType) {
StrViewA documentId = document["_id"].getString();
StrViewA revId = document["_rev"].getString();
PConnection conn = getConnection();
conn->add(documentId);
conn->add(attachmentName);
if (!revId.empty()) conn->add("rev",revId);
class UploadClass: public Upload::Target {
public:
UploadClass( PConnection &&urlline)
:http(urlline->http)
,out(http.beginBody())
,urlline(std::move(urlline))
,finished(false)
{
}
~UploadClass() noexcept(false) {
//if not finished, finish now
if (!finished) finish();
}
virtual void operator()(json::BinaryView strm) {
out(strm);
}
String finish() {
if (finished) return String(response);
finished = true;
out(nullptr);
int status = http.send();
if (status != 201) {
Value errorVal;
try{
errorVal = Value::parse(http.getResponse());
} catch (...) {
}
http.close();
StrViewA url(*urlline);
throw RequestError(url,status, http.getStatusMessage(), errorVal);
} else {
Value v = Value::parse(http.getResponse());
http.close();
response = v["rev"];
return String(response);
}
}
protected:
HttpClient &http;
OutputStream out;
Value response;
PConnection urlline;
bool finished;
};
lksqid.markOld();
//open request
conn->http.open(conn->getUrl(),"PUT",true);
//send header
conn->http.setHeaders(Object("Content-Type",contentType)("Cookie",getToken()));
//create upload object
return Upload(new UploadClass(std::move(conn)));
}
String CouchDB::putAttachment(const Value &document, const StrViewA &attachmentName, const AttachmentDataRef &attachmentData) {
Upload upld = putAttachment(document,attachmentName,attachmentData.contentType);
upld.write(BinaryView(attachmentData));
return upld.finish();
}
Value CouchDB::genUIDValue() const {
LockGuard _(lock);
return StrViewA(lkGenUID());
}
Value CouchDB::genUIDValue(StrViewA prefix) const {
LockGuard _(lock);
return lkGenUID(prefix);
}
Document CouchDB::newDocument() {
return Document(lkGenUID(),StrViewA());
}
Document CouchDB::newDocument(const StrViewA &prefix) {
return Document(lkGenUID(StrViewA(prefix)),StrViewA());
}
template<typename Fn>
class DesignDocumentParse: public json::Parser<Fn> {
public:
std::string functionBuff;
typedef json::Parser<Fn> Super;
DesignDocumentParse(Fn &&source)
:Super(std::forward<Fn>(source)) {}
virtual json::Value parse() {
const char *functionkw = "function";
const char *falsekw = "false";
int x = Super::rd.next();
if (x == 'f') {
Super::rd.commit();
x = Super::rd.next();
if (x == 'a') {
Super::checkString(falsekw+1);
return Value(false);
} else if (x == 'u') {
Super::checkString(functionkw+1);
functionBuff.clear();
functionBuff.append(functionkw);
std::vector<char> levelStack;
while(true) {
int c = Super::rd.nextCommit();
functionBuff.push_back(c);
if (c == '(' || c == '[' || c == '{') {
levelStack.push_back(c);
} else if (c == ')' || c == ']' || c == '}') {
char t = levelStack.empty()?0:levelStack[levelStack.size()-1];
if (t == 0 ||
(c == ')' && t != '(') ||
(c == '}' && t != '{') ||
(c == ']' && t != '['))
throw json::ParseError(functionBuff, c);
levelStack.pop_back();
if (levelStack.empty() && c == '}') break;
} else if (c == '"') {
json::Value v = Super::parseString();
v.serialize([&](char c) {functionBuff.push_back(c);});
}
}
return json::Value(functionBuff);
} else {
throw json::ParseError("Unexpected token", x);
}
} else {
return Super::parse();
}
}
};
bool CouchDB::putDesignDocument(const Value &content, DesignDocUpdateRule updateRule) {
/*
class DDResolver: public ConflictResolver {
public:
DDResolver(CouchDB &db, bool attachments, DesignDocUpdateRule rule):
ConflictResolver(db,attachments),rule(rule) {}
virtual ConstValue resolveConflict(Document &doc, const Path &path,
const ConstValue &leftValue, const ConstValue &rightValue) {
switch (rule) {
case ddurMergeSkip: return leftValue;
case ddurMergeOverwrite: return rightValue;
default: return ConflictResolver::resolveConflict(doc,path,leftValue,rightValue);
}
}
virtual bool isEqual(const ConstValue &leftValue, const ConstValue &rightValue) {
Document doc(leftValue);
ConstValue res = ConflictResolver::makeDiffObject(doc,Path::root, leftValue, rightValue);
return res == null;
}
protected:
DesignDocUpdateRule rule;
};
*/
Changeset chset = createChangeset();
Document newddoc = content;
try {
Document curddoc = this->get(content["_id"].getString(),0);
newddoc.setRev(curddoc.getRev());
///design document already exists, skip uploading
if (updateRule == ddurSkipExisting) return false;
//need because couchapp creates empty _attachments node
newddoc.optimizeAttachments();
/* Value(curddoc).toStream(std::cerr);std::cerr<<std::endl;
Value(newddoc).toStream(std::cerr);std::cerr<<std::endl;*/
///no change in design document, skip uploading
if (Value(curddoc) == Value(newddoc)) return false;
if (updateRule == ddurCheck) {
UpdateException::ErrorItem errItem;
errItem.document = content;
errItem.errorDetails = Object();
errItem.errorType = "conflict";
errItem.reason = "ddurCheck in effect, cannot update design document";
throw UpdateException(StringView<UpdateException::ErrorItem>(&errItem,1));
}
if (updateRule == ddurOverwrite) {
chset.update(newddoc);
} else {
throw std::runtime_error("Feature is not supported");
}
} catch (HttpStatusException &e) {
if (e.getCode() == 404) {
chset.update(content);
} else {
throw;
}
}
try {
chset.commit();
} catch (UpdateException &e) {
if (e.getErrors()[0].errorType == "conflict") {
return putDesignDocument(content,updateRule);
} else {
throw;
}
}
return true;
}
template<typename Fn>
Value parseDesignDocument(Fn &&fn) {
DesignDocumentParse<Fn> parser(std::forward<Fn>(fn));
return parser.parse();
}
bool CouchDB::putDesignDocument(const std::string &pathname, DesignDocUpdateRule updateRule) {
std::ifstream infile(pathname, std::ios::in);
if (!infile) {
UpdateException::ErrorItem err;
err.errorType = "not found";
err.reason = String({"Failed to open file: ",pathname});
throw UpdateException(StringView<UpdateException::ErrorItem>(&err,1));
}
return putDesignDocument(parseDesignDocument(json::fromStream(infile)), updateRule);
}
bool CouchDB::putDesignDocument(const char* content,
std::size_t contentLen, DesignDocUpdateRule updateRule) {
StrViewA ctt(content, contentLen);
return putDesignDocument(parseDesignDocument(json::fromString(ctt)), updateRule);
}
int CouchDB::initChangesFeed(const PConnection& conn, ChangesFeed& feed) {
ChangesFeed::State &state = feed.state;
return retry([&]{
std::unique_lock<std::recursive_mutex> _(state.initLock);
Value jsonBody;
StrViewA method = "GET";
if (state.curConn != nullptr) {
throw std::runtime_error("Changes feed is already in progress");
}
if (state.canceled) return 0;
if (feed.seqNumber.defined()) {
conn->add("since", feed.seqNumber.toString());
}
if (feed.outlimit != ((std::size_t) (-1))) {
conn->add("limit", feed.outlimit);
}
if (feed.filterInUse) {
const ::couchit::Filter& flt = feed.filter;
if (!flt.viewPath.empty()) {
StrViewA fltpath = flt.viewPath;
StrViewA ddocName;
StrViewA filterName;
bool isView = false;
auto iter = fltpath.split("/");
StrViewA x = iter();
if (x == "_design")
x = iter();
ddocName = x;
x = iter();
if (x == "_view") {
isView = true;
x = iter();
}
filterName = x;
String fpath( { ddocName, "/", filterName });
if (isView) {
conn->add("filter", "_view");
conn->add("view", fpath);
} else {
conn->add("filter", fpath);
}
}
if (flt.flags & ::couchit::Filter::allRevs)
conn->add("style", "all_docs");
if (flt.flags & ::couchit::Filter::includeDocs || feed.forceIncludeDocs) {
conn->add("include_docs", "true");
if (flt.flags & ::couchit::Filter::attachments) {
conn->add("attachments", "true");
}
if (flt.flags & ::couchit::Filter::conflicts) {
conn->add("conflicts", "true");
}
if (flt.flags & ::couchit::Filter::attEncodingInfo) {
conn->add("att_encoding_info", "true");
}
}
if (((flt.flags & ::couchit::Filter::reverseOrder) != 0) != feed.forceReversed) {
conn->add("descending", "true");
}
for (auto&& itm : flt.args) {
if (!feed.filterArgs[itm.getKey()].defined()) {
conn->add(StrViewA(itm.getKey()), StrViewA(itm.toString()));
}
}
} else {
if (feed.forceIncludeDocs) {
conn->add("include_docs", "true");
}
if (feed.forceReversed) {
conn->add("descending", "true");
}
if (feed.docFilter.defined()) {
conn->add("filter","_doc_ids");
Value docIds;
if (feed.docFilter.type() == json::string) {
docIds = Value(json::array, {feed.docFilter});
} else {
docIds = feed.docFilter;
}
jsonBody = Object("doc_ids", docIds);
method="POST";
}
}
for (auto&& v : feed.filterArgs) {
String val = v.toString();
StrViewA key = v.getKey();
conn->add(key, val);
}
conn->http.open(conn->getUrl(), method, true);
conn->http.connect();
state.curConn = conn.get();
_.unlock();
try {
conn->http.setTimeout(feed.iotimeout);
conn->http.setHeaders(Object("Accept", "application/json")("Cookie", getToken())("Content-Type","application/json"));
OutputStream out(nullptr);
if (jsonBody.defined()) {
out = conn->http.beginBody();
jsonBody.serialize(out);
out(nullptr);
out.flush();
}
int status = conn->http.send();
return status;
} catch (...) {
state.curConn = nullptr;
throw;
}
});
}
Changes CouchDB::receiveChanges(ChangesFeed& feed) {
PConnection conn = getConnection("_changes");
if (feed.timeout > 0) {
conn->add("feed","longpoll");
if (feed.timeout == ((std::size_t)-1)) {
conn->add("heartbeat","true");
} else {
conn->add("timeout",feed.timeout);
}
}
int status = initChangesFeed(conn, feed);
if (feed.state.canceled) {
feed.state.cancelEpilog();
return Value(json::undefined);
}
try {
Value v;
if (status/100 != 2) {
handleUnexpectedStatus(conn);
} else {
InputStream stream = conn->http.getResponse();
try {
v = Value::parse(stream);
} catch (...) {
feed.state.errorEpilog();
return Value(json::undefined);
}
conn->http.close();
feed.state.finishEpilog();
}
Value results=v["results"];
feed.seqNumber = v["last_seq"];
{
SeqNumber l (feed.seqNumber);
LockGuard _(lock);
if (l > lksqid) lksqid = l;
}
return results;
} catch (...) {
feed.state.errorEpilog();
throw;
}
}
void CouchDB::updateSeqNum(const Value& seq) {
SeqNumber l(seq);
LockGuard _(lock);
if (l > lksqid)
lksqid = l;
}
void CouchDB::receiveChangesContinuous(ChangesFeed& feed, ChangesFeedHandler &fn) {
bool restartable = false;
do {
std::chrono::steady_clock::time_point stop_time;
PConnection conn = getConnection("_changes",true);
conn->add("feed","continuous");
if (feed.timeout == ((std::size_t)-1)) {
conn->add("timeout",feed.restart_after);
restartable =true;
stop_time = std::chrono::steady_clock::now()+ std::chrono::milliseconds(feed.restart_after);
} else {
conn->add("timeout",feed.timeout);
}
int status = initChangesFeed(conn, feed);
if (feed.state.canceled) {
feed.state.cancelEpilog();
return;
}
try {
Value v;
if (status/100 != 2) {
handleUnexpectedStatus(conn);
} else {
InputStream stream = conn->http.getResponse();
bool rep = true;
do {
v = Value::parse(stream);
Value lastSeq = v["last_seq"];
if (lastSeq.defined()) {
feed.seqNumber = lastSeq;
updateSeqNum(feed.seqNumber);
conn->http.close();
rep = false;
} else {
ChangeEvent chdoc(v);
feed.seqNumber = v["seq"];
if (!fn(chdoc)) {
conn->http.abort();
restartable = false;
rep = false;
}
if (restartable && std::chrono::steady_clock::now() > stop_time) {
conn->http.abort();
rep = false;
}
}
} while (rep);
feed.state.finishEpilog();
}
} catch (...) {
feed.state.errorEpilog();
}
updateSeqNum(feed.seqNumber);
} while (restartable && !feed.state.wasCanceledState);
}
ChangesFeed CouchDB::createChangesFeed() {
return ChangesFeed(*this);
}
class EmptyDownload: public Download::Source {
public:
virtual BinaryView impl_read() override {
return BinaryView(nullptr, 0);
}
};
class StreamDownload: public Download::Source {
public:
StreamDownload(const InputStream &stream, CouchDB::PConnection &&conn):stream(stream),conn(std::move(conn)) {}
virtual BinaryView impl_read() override {
return stream.read();
}
~StreamDownload() {
conn->http.close();
}
protected:
InputStream stream;
CouchDB::PConnection conn;
};
Download CouchDB::downloadAttachmentCont(PConnection &conn, const StrViewA &etag) {
return retry([&]{
conn->http.open(conn->getUrl(), "GET", true);
Object hdr;
hdr("Cookie", getToken());
if (!etag.empty()) hdr("If-None-Match",etag);
conn->http.setHeaders(hdr);
int status = conn->http.send();
if (status != 200 && status != 304) {
handleUnexpectedStatus(conn);
throw;
} else {
Value hdrs = conn->http.getHeaders();
Value ctx = hdrs["Content-Type"];
Value len = hdrs["Content-Length"];
Value etag = hdrs["ETag"];
std::size_t llen = ((std::size_t)-1);
if (len.defined()) llen = len.getUInt();
if (status == 304) return Download(new EmptyDownload,ctx.getString(),etag.getString(),llen,true);
else return Download(new StreamDownload(conn->http.getResponse(),std::move(conn)),ctx.getString(),etag.getString(),llen,false);
}
});
}
Download CouchDB::getAttachment(const Document &document, const StrViewA &attachmentName, const StrViewA &etag) {
StrViewA documentId = document["_id"].getString();
StrViewA revId = document["_rev"].getString();
return getAttachment(documentId, attachmentName, etag, revId);
}
Download CouchDB::getAttachment(const StrViewA &docId, const StrViewA &attachmentName, const StrViewA &etag, const StrViewA &rev) {
PConnection url = getConnection("");
url->add(docId);
url->add(attachmentName);
if (!rev.empty()) url->add("rev",rev);
return downloadAttachmentCont(url,etag);
}
CouchDB::Queryable::Queryable(CouchDB& owner):owner(owner) {
}
Value CouchDB::Queryable::executeQuery(const QueryRequest& r) {
SeqNumber lastSeq = owner.getLastKnownSeqNumber();
if (lastSeq.getRevId() == 0 || (lastSeq.isOld() && r.needUpdateSeq))
lastSeq = owner.getLastSeqNumber();
PConnection conn = owner.getConnection(r.view.viewPath);
StrViewA startKey = "startkey";
StrViewA endKey = "endkey";
StrViewA startKeyDocId = "startkey_docid";
StrViewA endKeyDocId = "endkey_docid";
bool desc = (r.view.flags & View::reverseOrder) != 0;
if (r.reversedOrder) desc = !desc;
if (desc) conn->add("descending","true");
Value postBody = r.postData;
if (desc) {
std::swap(startKey,endKey);
std::swap(startKeyDocId,endKeyDocId);
}
// bool useCache = (r.view.flags & View::noCache) == 0 && !r.nocache;
switch (r.mode) {
case qmAllItems: break;
case qmKeyList: if (r.keys.size() == 1) {
conn->addJson("key",r.keys[0]);
}else if (r.keys.size() > 1){
if (postBody.defined()) {
conn->add("keys",Value(r.keys).stringify());
} else {
String ser = Value(r.keys).stringify();
if (ser.length() > maxSerializedKeysSizeForGETRequest ) {
postBody = Object("keys",r.keys);
} else {
conn->add("keys",ser);
}
}
} else {
return Object("total_rows",0)
("offset",0)
("rows",json::array)
("update_seq",owner.getLastKnownSeqNumber().toValue());
}
break;
case qmKeyRange: {
Value start = r.keys[0];
Value end = r.keys[1];
conn->addJson(startKey,start);
conn->addJson(endKey,end);
if (r.docIdFromGetKey) {
StrViewA startDocId = start.getKey();
if (!startDocId.empty()) {
conn->add(startKeyDocId, startDocId);
}
StrViewA endDocId = end.getKey();
if (!endDocId.empty()) {
conn->add(endKeyDocId, endDocId);
}
}
}
break;
case qmKeyPrefix:
conn->addJson(startKey,addToArray(r.keys[0],Query::minKey));
conn->addJson(endKey,addToArray(r.keys[0],Query::maxKey));
break;
case qmStringPrefix:
conn->addJson(startKey,addSuffix(r.keys[0],Query::minString));
conn->addJson(endKey,addSuffix(r.keys[0],Query::maxString));
break;
}
switch (r.reduceMode) {
case rmDefault:
if ((r.view.flags & (View::reduce|View::groupLevelMask)) == 0 ) conn->add("reduce","false");
else {
std::size_t level = (r.view.flags & View::groupLevelMask) / View::groupLevel;
if (r.mode == qmKeyList) {
conn->add("group","true");
} else {
conn->add("group_level",level);
}
}
break;
case rmGroup:
conn->add("group","true");
break;
case rmGroupLevel:
conn->add("group_level",r.groupLevel);
break;
case rmNoReduce:
conn->add("reduce","false");
break;
case rmReduce:
break;
}
if (r.offset) conn->add("skip",r.offset);
if (r.limit != ((std::size_t)-1)) conn->add("limit",r.limit);
if (r.nosort) conn->add("sorted","false");
if (r.view.flags & View::includeDocs) {
conn->add("include_docs","true");
if (r.view.flags & View::conflicts) conn->add("conflicts","true");
if (r.view.flags & View::attachments) conn->add("attachments","true");
if (r.view.flags & View::attEncodingInfo) conn->add("att_encoding_info","true");
}
if (r.exclude_end) conn->add("inclusive_end","false");
if (owner.cfg.readQuorum) conn->add("r",owner.cfg.readQuorum);
conn->add("update_seq","true");
if (r.view.flags & View::stale) conn->add("stale","ok");
else if ((r.view.flags & View::update) == 0) conn->add("stale","update_after");
else conn->http.setTimeout(std::max(owner.cfg.syncQueryTimeout, owner.cfg.iotimeout));
if (r.view.args.type() == json::object) {
for(auto &&item: r.view.args) {
conn->add(StrViewA(item.getKey()),StrViewA(item.toString()));
}
} else if (r.view.args.defined()) {
conn->add("args",StrViewA(r.view.args.toString()));
}
Value result;
if (!postBody.defined()) {
result = owner.requestGET(conn,0,0);
} else {
result = owner.requestPOST(conn,postBody,0,0);
}
if (r.view.postprocess) result = r.view.postprocess(&owner, r.ppargs, result);
Value sq = result["update_seq"];
if (sq.defined()) {
SeqNumber l(sq);
if (l.getRevId() == 0) {
//HACK: https://github.com/apache/couchdb/issues/984
l = lastSeq;
result = result.replace("update_seq", l.toValue());
}
LockGuard _(owner.lock);
if (l > owner.lksqid) owner.lksqid = l;
}
return result;
}
Value CouchDB::bulkUpload(const Value docs, bool replication ) {
if (docs.size() > cfg.maxBulkSizeDocs) {
auto splt = docs.splitAt(cfg.maxBulkSizeDocs);
Value res1 = bulkUpload(splt.first);
Value res2 = bulkUpload(splt.second);
Array res(res1);
res.addSet(res2);
return res;
} else if (docs.size() < cfg.minBulkSizeDocs) {
Array results;
for (Value v : docs) {
Value id = v["_id"];
Value r;
try {
PConnection b = getConnection("");;
if (replication) b->add("new_edits","false");
if (id.defined()) {
b->add(id.getString());
r= requestPUT(b,v,nullptr,0);
} else {
r = requestPOST(b,v,nullptr,0);
}
results.push_back(r);
} catch (RequestError &e) {
results.push_back(Object(e.getExtraInfo())("id",id));
}
}
return results;
} else {
PConnection b = getConnection("_bulk_docs");
if (replication) b->add("new_edits","false");
Object wholeRequest;
wholeRequest.set("docs", docs);
Value r = requestPOST(b,wholeRequest,0,0);
lksqid.markOld();
return r;
}
}
void CouchDB::put(Document& doc) {
Value rev = put(Value(doc));
doc.setRev(rev);
}
bool CouchDB::put(Document& doc, const WriteOptions &opts, bool no_exception) {
Value rev = put(Value(doc), opts, no_exception);
if (rev == nullptr) return false;
doc.setRev(rev);
return true;
}
CouchDB::PConnection CouchDB::getConnection(StrViewA resourcePath, bool fresh) {
if (magic != magic_const) {
logFatal("Magic const damaged");
abort();
}
std::unique_lock<std::mutex> _(lock);
auto now = SysClock::now();
auto lpcd = now - lastPoolCheck;
auto keepAliveTm = std::chrono::milliseconds(cfg.keepAliveTimeout);
auto keepAliveMaxAge = std::chrono::milliseconds(cfg.keepAliveMaxAge);
if (lpcd > keepAliveTm) {
ConnPool newConPool;
for (auto && x: connPool) {
auto dur = now - x->lastUse;
if (dur < keepAliveTm) newConPool.push_back(std::move(x));
}
connPool = std::move(newConPool);
lastPoolCheck = now;
}
if (cfg.databaseName.empty() && resourcePath.substr(0,1) != StrViewA("/"))
throw std::runtime_error("No database selected");
if (curConnections >= cfg.maxConnections) {
connRelease.wait(_,[&]{return curConnections<cfg.maxConnections;});
}
PConnection b(nullptr);
if (connPool.empty()) {
b = PConnection(new Connection, ConnectionDeleter(this));
} else if (fresh) {
connPool.erase(connPool.begin());
b = PConnection(new Connection, ConnectionDeleter(this));
} else {
b = PConnection(connPool[connPool.size()-1].release(), ConnectionDeleter(this));
connPool.pop_back();
auto dur = now - b->lastUse;
auto durf = now - b->firstUse;
if (dur > keepAliveTm) {
connPool.clear();
delete b.release();
b = PConnection(new Connection, ConnectionDeleter(this));
} else if (durf > keepAliveMaxAge) {
delete b.release();
b = PConnection(new Connection, ConnectionDeleter(this));
}
}
b->http.setTimeout(cfg.iotimeout);
setUrl(b,resourcePath);
curConnections++;
return b;
}
void CouchDB::setUrl(PConnection &conn, StrViewA resourcePath) {
conn->init(cfg.baseUrl,cfg.databaseName,resourcePath);
}
void CouchDB::releaseConnection(Connection* b) {
LockGuard _(lock);
b->lastUse = SysClock::now();
connPool.push_back(PConnection(b));
curConnections--;
if (curConnections+1==cfg.maxConnections) {
connRelease.notify_one();
}
}
void CouchDB::handleUnexpectedStatus(PConnection& conn) {
Value errorVal;
try{
errorVal = Value::parse(conn->http.getResponse());
} catch (...) {
}
conn->http.close();
throw RequestError(conn->getUrl(),conn->http.getStatus(), conn->http.getStatusMessage(), errorVal);
}
Value CouchDB::parseResponse(PConnection& conn) {
return Value::parse(conn->http.getResponse());
}
Value CouchDB::parseResponseBin(PConnection& conn) {
return Value::parseBinary(conn->http.getResponse());
}
Value CouchDB::postRequest(PConnection& conn, const StrViewA &cacheKey, Value *headers, std::size_t flags) {
HttpClient &http = conn->http;
int status = http.getStatus();
if (status/100 != 2) {
handleUnexpectedStatus(conn);
throw;
} else {
Value ctt = http.getHeaders()["Content-Type"];
Value v;
if (ctt.getString() == "application/binjson") {
v = parseResponseBin(conn);
if (!cacheKey.empty()) {
Value fld = http.getHeaders()["ETag"];
if (fld.defined()) {
cfg.cache->set(QueryCache::CachedItem(cacheKey, fld.getString(), v));
}
}
} else if (ctt.getString() == "application/json") {
v = parseResponse(conn);
if (!cacheKey.empty()) {
Value fld = http.getHeaders()["ETag"];
if (fld.defined()) {
cfg.cache->set(QueryCache::CachedItem(cacheKey, fld.getString(), v));
}
}
} else {
std::vector<std::uint8_t> data;
InputStream rd = http.getResponse();
int i = rd();
while (i != json::eof) {
data.push_back((std::uint8_t)i);
i = rd();
}
Object r;
r.set("content", Value(BinaryView(&data[0],data.size()),json::defaultBinaryEncoding));
r.set("content-type",ctt);
v = r;
}
if (flags & flgStoreHeaders && headers != nullptr) {
*headers = http.getHeaders();
}
http.close();
return v;
}
}
Value CouchDB::requestGET(PConnection& conn, Value* headers, std::size_t flags) {
return retry([&]{
bool usecache = (flags & flgDisableCache) == 0 && cfg.cache != nullptr;
StrViewA path = conn->getUrl();
StrViewA cacheKey;
if (usecache) {
std::size_t baseUrlLen = cfg.baseUrl.length();
std::size_t databaseLen = cfg.databaseName.length();
std::size_t prefixLen = baseUrlLen+databaseLen+1;
if (path.substr(0,baseUrlLen) != StrViewA(cfg.baseUrl)
|| path.substr(baseUrlLen, databaseLen) != StrViewA(cfg.databaseName)) {
usecache = false;
} else {
cacheKey = path.substr(prefixLen);
}
}
//there will be stored cached item
QueryCache::CachedItem cachedItem;
if (usecache) {
cachedItem = cfg.cache->find(cacheKey);
}
HttpClient &http = conn->http;
http.open(path,"GET",true);
bool redirectRetry = false;
int status;
do {
redirectRetry = false;
Object hdr(headers?*headers:Value());
if (!hdr["Accept"].defined()) {
hdr("Accept","application/binjson, application/json");
}
if (cachedItem.isDefined()) {
hdr("If-None-Match", cachedItem.etag);
}
if ((flags & flgNoAuth) == 0) hdr("Cookie", getToken());
status = http.setHeaders(hdr).send();
if (status == 304 && cachedItem.isDefined()) {
http.close();
return cachedItem.value;
}
if (status == 301 || status == 302 || status == 303 || status == 307) {
json::Value val = http.getHeaders()["Location"];
if (!val.defined()) {
http.abort();
throw RequestError(path,http.getStatus(),http.getStatusMessage(), Value("Redirect without Location"));
}
http.close();
http.open(val.getString(), "GET",true);
redirectRetry = true;
}
}
while (redirectRetry);
return postRequest(conn,cacheKey,headers,flags);
});
}
template<typename Fn>
auto CouchDB::retry(Fn &&fn) -> decltype(std::declval<Fn>()()) {
auto now = std::chrono::system_clock::now();
auto exp = now+std::chrono::seconds(cfg.inintialWait);
while(true) {
try {
auto x = fn();
cfg.inintialWait = 0;
return x;
} catch (const RequestError &e) {
if (e.getCode() != 0) throw;
now = std::chrono::system_clock::now();
if (now > exp) throw;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
Value CouchDB::requestPOST(PConnection& conn,
const Value& postData, Value* headers, std::size_t flags) {
return retry([&]{
return jsonPUTPOST(conn,true,postData,headers,flags);
});
}
Value CouchDB::requestPUT(PConnection& conn, const Value& postData,
Value* headers, std::size_t flags) {
return retry([&]{
return jsonPUTPOST(conn,false,postData,headers,flags);
});
}
Value CouchDB::requestDELETE(PConnection& conn, Value* headers,
std::size_t flags) {
return retry([&]{
HttpClient &http = conn->http;
StrViewA path = conn->getUrl();
http.open(path,"DELETE",true);
Object hdr(headers?*headers:Value());
if (!hdr["Accept"].defined())
hdr("Accept","application/binjson, application/json");
if ((flags & flgNoAuth) == 0) hdr("Cookie", getToken());
http.setHeaders(hdr).send();
return postRequest(conn,StrViewA(),headers,flags);
});
}
Value CouchDB::jsonPUTPOST(PConnection& conn, bool methodPost,
Value data, Value* headers, std::size_t flags) {
typedef std::uint8_t byte;
HttpClient &http = conn->http;
StrViewA path = conn->getUrl();
http.open(path,methodPost?"POST":"PUT",true);
Object hdr(headers?*headers:Value());
if (!hdr["Accept"].defined())
hdr("Accept","application/binjson, application/json");
hdr("Content-Type","application/json");
if ((flags & flgNoAuth) == 0) hdr("Cookie", getToken());
http.setHeaders(hdr);
if (data.type() == json::undefined) {
http.send(StrViewA());
} else {
bool hdrSent = false;
byte buffer[4096];
int bpos = 0;
OutputStream outstr(nullptr);
data.serialize([&](int i) {
buffer[bpos++] = (byte)i;
if (bpos == sizeof(buffer)) {
if (!hdrSent) {
outstr = http.beginBody();
hdrSent = true;
}
outstr(BinaryView(buffer,bpos));
bpos = 0;
}
});
if (hdrSent) {
if (bpos) {
outstr(BinaryView(buffer,bpos));
}
outstr(nullptr);
}
outstr = nullptr;
http.send(buffer,bpos);
}
return postRequest(conn,StrViewA(),headers,flags);
}
Value CouchDB::getToken() {
if (!authObj.defined()) return json::undefined;
time_t now;
time(&now);
if (now > tokenRefreshTime) {
std::unique_lock<std::mutex> sl(tokenLock, std::defer_lock);
if (now > tokenExpireTime) {
sl.lock();
if (now <= tokenExpireTime) return token;
prevToken = token;
} else {
if (!sl.try_lock()) return token;
}
Value headers;
PConnection conn = getConnection("/_session");
Value result = requestPOST(conn,authObj,&headers,flgStoreHeaders|flgNoAuth);
if (result["ok"].getBool()) {
StrViewA c = headers["Set-Cookie"].getString();
auto splt = c.split(";");
token = splt();
tokenExpireTime = now+cfg.tokenTimeout-10;
tokenRefreshTime = tokenExpireTime-cfg.tokenTimeout/2;
return token;
} else {
throw RequestError(conn->getUrl(),500, "Failed to retrieve token",Value());
}
}
return token;
}
std::size_t CouchDB::updateView(const View& view, bool wait) {
PConnection conn = getConnection(view.viewPath);
if (!wait)
conn->add("stale","update_after");
conn->add("limit",0);
Value r = requestGET(conn, 0, flgDisableCache);
return r["total_rows"].getUInt();
}
void CouchDB::setupHttpConn(HttpClient &http, Flags flags) {
if (flags & flgLongOperation) {
http.setTimeout(cfg.syncQueryTimeout);
}
}
CouchDB::Connection::Connection():firstUse(SysClock::now()) {
}
Value CouchDB::getSerialNr() {
if (serialNr.defined()) return serialNr;
//there is no such database serial number.
//so we will emulate serial number using local document _local/serialNr;
//on the very first access, serial number is generated
Document doc = getLocal("serialNr",flgCreateNew);;
serialNr = doc["serialNr"];
if (serialNr.defined()) return serialNr;
doc.set("serialNr", serialNr = genUID());
try {
this->put(doc);
} catch (UpdateException &e) {
if (e.getErrors()[0].isConflict()) return getSerialNr();
throw;
}
return serialNr;
}
Value CouchDB::getRevisions(const StrViewA docId, Value revisions, Flags flags) {
PConnection conn = getConnection();
conn->add(docId);
if (revisions.empty()) conn->add("open_revs","all");
else conn->addJson("open_revs",revisions);
if (flags & flgAttachments) conn->add("attachments","true");
if (flags & flgRevisions) conn->add("revs","true");
if (cfg.readQuorum) conn->add("r",cfg.readQuorum);
Value res = requestGET(conn, nullptr,flags & (flgDisableCache|flgRefreshCache));
Array output;
output.reserve(res.size());
for (Value x: res) {
output.push_back(x[0]); //<pick fist and only value;
}
return output;
}
void CouchDB::pruneConflicts(Document& doc) {
PConnection conn = getConnection();
conn->add("_bulk_docs");
{
Revision curRev(doc.getRevValue());
Revision newRev(curRev.getRevId()+1, String({curRev.getTag(),"M"}));
auto revs = doc.object("_revisions");
auto ids = revs.array("ids");
if (ids.empty()) ids.insert(0, curRev.getRevId());
ids.insert(0, newRev.getTag());
revs("start", newRev.getRevId());
doc.setRev(newRev.toString());
}
Value id = doc.getIDValue();
Value docv(doc);
if (cfg.validator) {
auto r = cfg.validator->validateDoc(docv);
if (!r.valid) throw ValidationFailedException(r);
}
Array docs;
for (Value c : doc.conflicts()) {
Revision curRev(c);
Revision newRev(curRev.getRevId()+1, String({curRev.getTag(),"R"}));
docs.push_back(Value(json::object,{
Value("_id",id),
Value("_rev",newRev.toString()),
Value("_revisions",Value(json::object,{
Value("start",newRev.getRevId()),
Value("ids",{newRev.getTag(),curRev.getTag()})
})),
Value("_deleted",true)
}));
}
docs.push_back(docv);
Value req(json::object,{
Value("new_edits",false),
Value("docs",docs)
});
// std::cout << req.toString();
Value r = requestPOST(conn,req,nullptr,0);
lksqid.markOld();
std::vector<UpdateException::ErrorItem> errors;
for (Value x: r) {
if (x["error"].defined()) {
UpdateException::ErrorItem err;
err.document = x["id"];
err.errorType = x["error"].toString();
err.reason = x["reason"].toString();
err.errorDetails = x;
errors.push_back(err);
}
}
if (!errors.empty()) {
throw UpdateException(std::move(errors));
}
}
Result CouchDB::mget_impl(Array &idlist, Flags flags) {
if (idlist.empty()) return Result(json::undefined);
if ((flags & flgOpenRevs) == 0){
Query q = createQuery(0);
Array keys;
for (Value v: idlist) {
if (!v["rev"].defined()) keys.push_back(v["id"]);
}
q.keys(keys);
Result res = q.exec();
auto src = res.begin();
auto trg = idlist.begin();
auto src_end = res.end();
auto trg_end = idlist.end();
while (trg != trg_end) {
if (!(*trg)["rev"].defined()){
if (src != src_end && (*trg)["id"] == (*src)["id"]) {
*trg = (*trg).replace("rev", (*src)["rev"]);
++src;
}
}
++trg;
}
}
bool only_deleted = (flags & flgOpenRevs) && (!(flags & flgConflicts) || (flags & flgDeletedConflicts)) ;
bool only_conflicts = (flags & flgOpenRevs) && (!(flags & flgDeletedConflicts) || (flags & flgConflicts));
PConnection conn = getConnection();
conn->add("_bulk_get");
if (flags & flgAttachments) conn->add("attachments","true");
if (flags & flgRevisions) conn->add("revs","true");
if (cfg.readQuorum) conn->add("r",cfg.readQuorum);
Value req = Object("docs", idlist);
Array lst;
try {
Value r = requestPOST(conn, req, nullptr, 0);
Value res = r["results"];
Array conflicts;
Array deleted_conflicts;
for (Value v : res) {
Value docs = v["docs"];
Value lastDoc = docs.reduce([](Value a, Value b){
Value ok = b["ok"];
if (ok.hasValue() && !ok["_deleted"].getBool()) {
if (a.hasValue()) {
Revision reva(a["_rev"]);
Revision revb(ok["_rev"]);
if (reva>revb) return a;
}
return ok.stripKey();
} else {
return a;
}
},Value());
if (lastDoc.defined()) {
for (Value d: docs) {
Value doc = d[0];
Value itm;
bool deleted;
if (doc.getKey() == "ok") {
deleted = doc["_deleted"].getBool();
itm = doc;
} else {
deleted = doc["deleted"].getBool();
itm = doc["rev"];
}
if (!itm.isCopyOf(lastDoc)) {
if (deleted) {
if (only_deleted) deleted_conflicts.push_back(itm);
} else {
if (only_conflicts) conflicts.push_back(itm);
}
}
}
if (!conflicts.empty()) {
lastDoc = lastDoc.replace("_conflicts", conflicts);
conflicts.clear();
}
if (!deleted_conflicts.empty()) {
lastDoc = lastDoc.replace("_deleted_conflicts", deleted_conflicts);
deleted_conflicts.clear();
}
lst.push_back(lastDoc);
}
else {
lst.push_back(nullptr);
}
}
return Result(lst,lst.size(),0,nullptr);
} catch (RequestError &e) {
/* if (e.getCode() != 400) throw;
Array response;
for (Value v: req["docs"]) {
Value id = v["id"];
Value rev = v["rev"];
Value r;
if (rev.defined()) {
r=this->get(id.getString(),rev.getString(),flgNullIfMissing|flgRevisions);
} else {
r=this->get(id.getString(),flgNullIfMissing|flgRevisions);
}
}
return Result(response,response.size(),0,nullptr);*/
throw;
}
}
Value CouchDB::put(const Value &doc) {
return put(doc, {}, false);
}
Value CouchDB::put(const Value &doc, const WriteOptions &opts, bool no_exception ) {
Value id = doc["_id"];
if (id.type() != json::string) throw std::runtime_error("CoucDB::put needs document _id");
Value wdoc;
if (doc[fldTimestamp].defined()) {
wdoc = doc.replace(fldTimestamp, std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
} else {
wdoc = doc;
}
if (opts.async) {
if (batchWrite == nullptr) {
std::lock_guard _(lock);
if (batchWrite == nullptr) batchWrite = std::make_unique<BatchWrite>(*this);
}
if (opts.replication) {
batchWrite->replicate(wdoc);
} else {
batchWrite->put(wdoc, BatchWrite::Callback(opts.async_cb));
}
return wdoc["_rev"];
} else {
PConnection b = getConnection("");
b->add(id.getString());
if (opts.batchok) b->add("batch","ok");
if (opts.replication) b->add("new_edits","false");
if (opts.quorum) b->add("w",opts.quorum);
try {
Value resp = requestPUT(b,wdoc,nullptr,0);
return resp["rev"];
} catch (const RequestError &e) {
if (e.getCode() == 409) {
if (no_exception) return nullptr;
else throw UpdateException(StringView({
UpdateException::ErrorItem{
"conflict","conflict",wdoc,nullptr
}
}));
} else {
throw;
}
}
}
}
void CouchDB::getAsync(const json::String &docId, std::function<void(Document &doc)> &&cb) {
if (batchWrite == nullptr) {
std::lock_guard _(lock);
if (batchWrite == nullptr) batchWrite = std::make_unique<BatchWrite>(*this);
}
batchWrite->get(docId, std::move(cb));
}
Changes CouchDB::receiveChanges(ChangeFeedState &feedState) {
feedState.connection = nullptr;
if (feedState.canceled.load()) return Changes();
auto pollInterval = std::min(std::max(feedState.poll_interval,cfg.minChangesPollInterval), feedState.timeout);
auto limit = std::min<unsigned int>(feedState.limit, cfg.maxChangesBatchSize);
auto now = std::chrono::system_clock::now();
auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(now-feedState.last_request_time).count();
if (dur < pollInterval) {
std::this_thread::sleep_for(std::chrono::milliseconds(pollInterval-dur));
now = std::chrono::system_clock::now();
}
if (feedState.canceled.load()) return Changes();
feedState.last_request_time = now;
PConnection c = getConnection("_changes");
if (feedState.since.defined()) c->add("since", feedState.since.toString());
if (feedState.include_docs) c->add("include_docs", "true");
if (feedState.conflicts) c->add("conflicts", "true");
if (feedState.attachments) c->add("attachments", "true");
if (feedState.descending) c->add("descending", "true");
Value body;
switch (feedState.filter) {
case Filter::no_filter:break;
case Filter::custom: c->add("filter", feedState.filter_spec.toString());break;
case Filter::view: c->add("view", feedState.filter_spec.toString());
c->add("filter","_view");
break;
case Filter::selector: c->add("filter","_selector");body = feedState.filter_spec;break;
case Filter::docids: c->add("filter","_doc_ids");body = json::Object("doc_ids",feedState.filter_spec);break;
case Filter::design: c->add("filter","_design");break;
}
c->add("limit", limit);
c->add("r","1");
if (feedState.timeout) {
c->add("timeout", feedState.timeout);
c->add("feed","longpoll");
c->http.setTimeout(feedState.timeout+cfg.iotimeout);
} else {
c->add("feed","normal");
}
if (limit>0 && feedState.batching) c->add("seq_interval",limit);
if (feedState.extra_args.type() == json::object) {
for (Value a: feedState.extra_args) c->addJson(a.getKey(), a);
}
auto url = c->getUrl();
c->http.connect();
HttpClient &http = c->http;
feedState.connection = std::move(c);
if (feedState.canceled.load()) {
http.abort();
feedState.connection = nullptr;
return Changes();
}
int status;
Object headers;
headers("Cookie", getToken());
if (body.defined()) {
http.open(url, "POST");
headers("Content-Type","application/json");
http.setHeaders(headers);
status = http.send(body.toString());
} else {
http.open(url, "GET");
http.setHeaders(headers);
status = http.send();
}
if (feedState.canceled) {
http.close();
return Changes();
}
Value response;
try {
response = Value::parse(http.getResponse());
http.close();
} catch (...) {
http.close();
if (feedState.canceled.load())
return Changes();
if (status == 200) throw;
}
if (status != 200) {
throw RequestError(url,status, http.getStatusMessage(), response);
} else {
json::Value results = response["results"].stripKey();
if (results.size() >= limit/2) {
feedState.last_request_time = std::chrono::system_clock::from_time_t(0);
}
feedState.since = response["last_seq"].stripKey();
{
SeqNumber l (feedState.since);
LockGuard _(lock);
if (l > lksqid) lksqid = l;
}
return results;
}
}
void CouchDB::abortReceiveChanges(ChangeFeedState &feedState) {
bool c1 = false;
if (feedState.canceled.compare_exchange_strong(c1, true)) {
Connection *c = feedState.connection.get();
if (c) c->http.abort();
}
}
}
| 25.84185 | 132 | 0.652394 | [
"object",
"vector"
] |
de1efdb4a0fa330e2e97af60cace5b903eeea81c | 13,753 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/triangulator/triviswidget.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/triangulator/triviswidget.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/manual/triangulator/triviswidget.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "triviswidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QWheelEvent>
#include <QScrollBar>
#include <QPainter>
#include <QPainterPath>
#include <QTimer>
#include <QtGui/private/qtriangulator_p.h>
#include <QtGui/private/qtriangulatingstroker_p.h>
#include <QDebug>
static const int W = 100;
static const int H = 100;
static const int MAX_ZOOM = 512;
class ScrollArea : public QScrollArea {
protected:
void wheelEvent(QWheelEvent *event) override {
if (!event->modifiers().testFlag(Qt::ControlModifier))
QScrollArea::wheelEvent(event);
}
};
TriangulationVisualizer::TriangulationVisualizer(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *mainLayout = new QVBoxLayout;
QHBoxLayout *headerLayout = new QHBoxLayout;
QGroupBox *cbBox = new QGroupBox(QLatin1String("Shape"));
m_cbShape = new QComboBox;
QVBoxLayout *cbBoxLayout = new QVBoxLayout;
cbBoxLayout->addWidget(m_cbShape);
cbBox->setLayout(cbBoxLayout);
headerLayout->addWidget(cbBox);
m_lbPreview = new QLabel;
m_lbPreview->setFixedSize(W, H);
headerLayout->addWidget(m_lbPreview);
QGroupBox *typeBox = new QGroupBox(QLatin1String("Type"));
m_rdStroke = new QRadioButton(QLatin1String("Stroke"));
m_rdStroke->setChecked(true);
m_rdFill = new QRadioButton(QLatin1String("Fill"));
QVBoxLayout *typeBoxLayout = new QVBoxLayout;
typeBoxLayout->addWidget(m_rdStroke);
typeBoxLayout->addWidget(m_rdFill);
typeBox->setLayout(typeBoxLayout);
headerLayout->addWidget(typeBox);
QGroupBox *paramBox = new QGroupBox(QLatin1String("Stroke params"));
QVBoxLayout *paramBoxLayout = new QVBoxLayout;
m_spStrokeWidth = new QSpinBox;
m_spStrokeWidth->setPrefix(QLatin1String("Stroke width: "));
m_spStrokeWidth->setMinimum(1);
m_spStrokeWidth->setMaximum(32);
m_spStrokeWidth->setValue(1);
m_chDash = new QCheckBox(QLatin1String("Dash stroke"));
paramBoxLayout->addWidget(m_spStrokeWidth);
paramBoxLayout->addWidget(m_chDash);
paramBox->setLayout(paramBoxLayout);
headerLayout->addWidget(paramBox);
m_lbInfo = new QLabel;
headerLayout->addWidget(m_lbInfo);
QGroupBox *animBox = new QGroupBox(QLatin1String("Step through"));
QVBoxLayout *animBoxLayout = new QVBoxLayout;
m_chStepEnable = new QCheckBox(QLatin1String("Enable"));
m_spStepStroke = new QSpinBox;
m_spStepStroke->setPrefix(QLatin1String("Stroke steps: "));
m_spStepStroke->setMinimum(3);
m_spStepStroke->setMaximum(INT_MAX);
m_spStepStroke->setEnabled(false);
m_spStepFill = new QSpinBox;
m_spStepFill->setPrefix(QLatin1String("Fill steps: "));
m_spStepFill->setMinimum(3);
m_spStepFill->setMaximum(INT_MAX);
m_spStepFill->setEnabled(false);
animBoxLayout->addWidget(m_chStepEnable);
animBoxLayout->addWidget(m_spStepStroke);
animBoxLayout->addWidget(m_spStepFill);
animBox->setLayout(animBoxLayout);
headerLayout->addWidget(animBox);
m_canvas = new TriVisCanvas;
m_scrollArea = new ScrollArea;
m_scrollArea->setWidget(m_canvas);
m_scrollArea->setMinimumSize(W, H);
mainLayout->addLayout(headerLayout);
mainLayout->addWidget(m_scrollArea);
mainLayout->setStretchFactor(m_scrollArea, 9);
setLayout(mainLayout);
for (const QString &shapeName : m_canvas->shapes())
m_cbShape->addItem(shapeName);
connect(m_cbShape, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [this]() {
m_canvas->setIndex(m_cbShape->currentIndex());
m_canvas->retriangulate();
});
connect(m_rdFill, &QRadioButton::toggled, [this]() {
m_canvas->setType(TriVisCanvas::Fill);
m_canvas->retriangulate();
});
connect(m_rdStroke, &QRadioButton::toggled, [this]() {
m_canvas->setType(TriVisCanvas::Stroke);
m_canvas->retriangulate();
});
connect(m_spStrokeWidth, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this]() {
m_canvas->setStrokeWidth(m_spStrokeWidth->value());
m_canvas->regeneratePreviews();
m_canvas->retriangulate();
});
connect(m_chDash, &QCheckBox::toggled, [this]() {
m_canvas->setDashStroke(m_chDash->isChecked());
m_canvas->regeneratePreviews();
m_canvas->retriangulate();
});
connect(m_chStepEnable, &QCheckBox::toggled, [this]() {
bool enable = m_chStepEnable->isChecked();
m_spStepStroke->setEnabled(enable);
m_spStepFill->setEnabled(enable);
if (enable)
m_canvas->setStepLimits(m_spStepStroke->value(), m_spStepFill->value());
else
m_canvas->setStepLimits(0, 0);
});
connect(m_spStepStroke, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this]() {
m_canvas->setStepLimits(m_spStepStroke->value(), m_spStepFill->value());
});
connect(m_spStepFill, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this]() {
m_canvas->setStepLimits(m_spStepStroke->value(), m_spStepFill->value());
});
connect(m_canvas, &TriVisCanvas::retriangulated, [this]() {
updateInfoLabel();
updatePreviewLabel();
});
connect(m_canvas, &TriVisCanvas::zoomChanged, [this](float oldZoom, float newZoom) {
QScrollBar *sb = m_scrollArea->horizontalScrollBar();
float x = sb->value() / oldZoom;
sb->setValue(x * newZoom);
sb = m_scrollArea->verticalScrollBar();
float y = sb->value() / oldZoom;
sb->setValue(y * newZoom);
updateInfoLabel();
});
m_canvas->retriangulate();
}
void TriangulationVisualizer::updateInfoLabel()
{
m_lbInfo->setText(QString(QStringLiteral("Type: %1\n%2 vertices (x, y)\n%3 indices\nzoom: %4\nUSE CTRL+WHEEL TO ZOOM"))
.arg(m_canvas->geomType() == TriVisCanvas::Triangles ? QLatin1String("Triangles") : QLatin1String("Triangle strips"))
.arg(m_canvas->vertexCount())
.arg(m_canvas->indexCount())
.arg(m_canvas->zoomLevel()));
}
void TriangulationVisualizer::updatePreviewLabel()
{
m_lbPreview->setPixmap(QPixmap::fromImage(m_canvas->preview()).scaled(m_lbPreview->size()));
}
const int TLX = 10;
const int TLY = 10;
TriVisCanvas::TriVisCanvas(QWidget *parent)
: QWidget(parent)
{
resize(W * m_zoom, H * m_zoom);
QPainterPath linePath;
linePath.moveTo(TLX, TLY);
linePath.lineTo(TLX + 30, TLY + 30);
m_paths << linePath;
QPainterPath rectPath;
rectPath.moveTo(TLX, TLY);
rectPath.lineTo(TLX + 30, TLY);
rectPath.lineTo(TLX + 30, TLY + 30);
rectPath.lineTo(TLX, TLY + 30);
rectPath.lineTo(TLX, TLY);
m_paths << rectPath;
QPainterPath roundRectPath;
roundRectPath.addRoundedRect(TLX, TLY, TLX + 29, TLY + 29, 5, 5);
m_paths << roundRectPath;
QPainterPath ellipsePath;
ellipsePath.addEllipse(TLX, TLY, 40, 20);
m_paths << ellipsePath;
QPainterPath cubicPath;
cubicPath.moveTo(TLX, TLY + 30);
cubicPath.cubicTo(15, 2, 40, 40, 30, 10);
m_paths << cubicPath;
QPainterPath cubicPath2;
cubicPath2.moveTo(TLX, TLY + 20);
cubicPath2.cubicTo(15, 2, 30, 30, 30, 35);
m_paths << cubicPath2;
regeneratePreviews();
}
QStringList TriVisCanvas::shapes() const
{
return QStringList()
<< "line"
<< "rect"
<< "roundedrect"
<< "ellipse"
<< "cubic curve 1"
<< "cubic curve 2";
}
void TriVisCanvas::regeneratePreviews()
{
m_strokePreviews.clear();
m_fillPreviews.clear();
for (int i = 0; i < m_paths.count(); ++i)
addPreview(i);
}
void TriVisCanvas::addPreview(int idx)
{
QPen pen(Qt::black);
pen.setWidthF(m_strokeWidth);
if (m_dashStroke)
pen.setStyle(Qt::DashLine);
QImage img(W, H, QImage::Format_RGB32);
img.fill(Qt::white);
QPainter p(&img);
p.translate(-TLX, -TLY);
p.scale(2, 2);
p.strokePath(m_paths[idx], pen);
p.end();
m_strokePreviews.append(img);
img = QImage(W, H, QImage::Format_RGB32);
img.fill(Qt::white);
p.begin(&img);
p.translate(-TLX, -TLY);
p.scale(2, 2);
p.fillPath(m_paths[idx], QBrush(Qt::gray));
p.end();
m_fillPreviews.append(img);
}
QImage TriVisCanvas::preview() const
{
if (m_type == Stroke)
return m_strokePreviews[m_idx];
else
return m_fillPreviews[m_idx];
}
static const qreal SCALE = 100;
void TriVisCanvas::retriangulate()
{
const QPainterPath &path(m_paths[m_idx]);
if (m_type == Stroke) {
const QVectorPath &vp = qtVectorPathForPath(path);
const QSize clipSize(W, H);
const QRectF clip(QPointF(0, 0), clipSize);
const qreal inverseScale = 1.0 / SCALE;
QTriangulatingStroker stroker;
stroker.setInvScale(inverseScale);
QPen pen;
pen.setWidthF(m_strokeWidth);
if (m_dashStroke)
pen.setStyle(Qt::DashLine);
if (pen.style() == Qt::SolidLine) {
stroker.process(vp, pen, clip, 0);
} else {
QDashedStrokeProcessor dashStroker;
dashStroker.setInvScale(inverseScale);
dashStroker.process(vp, pen, clip, 0);
QVectorPath dashStroke(dashStroker.points(), dashStroker.elementCount(),
dashStroker.elementTypes(), 0);
stroker.process(dashStroke, pen, clip, 0);
}
m_strokeVertices.resize(stroker.vertexCount() / 2);
if (!m_strokeVertices.isEmpty()) {
const float *vsrc = stroker.vertices();
for (int i = 0; i < m_strokeVertices.count(); ++i)
m_strokeVertices[i].set(vsrc[i * 2], vsrc[i * 2 + 1]);
}
} else {
const QVectorPath &vp = qtVectorPathForPath(path);
QTriangleSet ts = qTriangulate(vp, QTransform::fromScale(SCALE, SCALE), 1, true);
const int vertexCount = ts.vertices.count() / 2;
m_fillVertices.resize(vertexCount);
Vertex *vdst = reinterpret_cast<Vertex *>(m_fillVertices.data());
const qreal *vsrc = ts.vertices.constData();
for (int i = 0; i < vertexCount; ++i)
vdst[i].set(vsrc[i * 2] / SCALE, vsrc[i * 2 + 1] / SCALE);
m_fillIndices.resize(ts.indices.size());
if (ts.indices.type() == QVertexIndexVector::UnsignedShort) {
const quint16 *shortD = static_cast<const quint16 *>(ts.indices.data());
for (int i = 0; i < m_fillIndices.count(); ++i)
m_fillIndices[i] = shortD[i];
} else {
memcpy(m_fillIndices.data(), ts.indices.data(), ts.indices.size() * sizeof(quint32));
}
}
emit retriangulated();
update();
}
void TriVisCanvas::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.fillRect(rect(), Qt::white);
if (m_type == Stroke) {
QPointF prevPt[3];
int cnt = 0;
for (int i = 0; i < m_strokeVertices.count() && (!m_strokeStepLimit || i < m_strokeStepLimit); ++i) {
auto &v = m_strokeVertices[i];
QPointF pt(v.x, v.y);
pt *= m_zoom;
if (cnt == 1 || cnt == 2)
p.drawLine(prevPt[cnt - 1], pt);
prevPt[cnt] = pt;
cnt = (cnt + 1) % 3;
if (!cnt) {
p.drawLine(pt, prevPt[cnt]);
i -= 2;
}
}
} else {
QPointF prevPt[3];
int cnt = 0;
for (int i = 0; i < m_fillIndices.count() && (!m_fillStepLimit || i < m_fillStepLimit); ++i) {
auto &v = m_fillVertices[m_fillIndices[i]];
QPointF pt(v.x, v.y);
pt *= m_zoom;
if (cnt == 1 || cnt == 2)
p.drawLine(prevPt[cnt - 1], pt);
prevPt[cnt] = pt;
cnt = (cnt + 1) % 3;
if (!cnt)
p.drawLine(pt, prevPt[cnt]);
}
}
}
void TriVisCanvas::wheelEvent(QWheelEvent *event)
{
int change = 0;
if (event->modifiers().testFlag(Qt::ControlModifier)) {
if (event->delta() > 0 && m_zoom < MAX_ZOOM) {
m_zoom += 1;
change = 1;
} else if (event->delta() < 0 && m_zoom > 1) {
m_zoom -= 1;
change = -1;
}
}
resize(W * m_zoom, H * m_zoom);
emit zoomChanged(m_zoom - change, m_zoom);
update();
}
| 32.823389 | 139 | 0.625173 | [
"shape"
] |
de2b9eae54b7356e9324f7d5a72f19bfc587d610 | 1,246 | cpp | C++ | gui/src/wrappers/dialoguserviewwrapper.cpp | sqglobe/SecureDialogues | bde56c7a62fb72b1cdfba8cebc0a770157b5f751 | [
"MIT"
] | 3 | 2019-07-05T12:01:36.000Z | 2021-03-19T22:48:48.000Z | gui/src/wrappers/dialoguserviewwrapper.cpp | sqglobe/SecureDialogues | bde56c7a62fb72b1cdfba8cebc0a770157b5f751 | [
"MIT"
] | 41 | 2019-11-26T18:59:54.000Z | 2020-05-01T10:52:47.000Z | gui/src/wrappers/dialoguserviewwrapper.cpp | sqglobe/SecureDialogues | bde56c7a62fb72b1cdfba8cebc0a770157b5f751 | [
"MIT"
] | 3 | 2019-05-21T17:48:16.000Z | 2021-03-19T22:48:49.000Z | #include "dialoguserviewwrapper.h"
#include <QListView>
#include "models/dialogs-list/dialogsortmodel.h"
#include "models/dialogs-list/dialogusermodel.h"
DialogUserViewWrapper::DialogUserViewWrapper(
QListView* view,
std::shared_ptr<DialogUserModel> model,
QObject* parent) :
QObject(parent),
mView(view), mProxy(new DialogSortModel), mModel(std::move(model)) {
mProxy->setDynamicSortFilter(true);
mProxy->setSourceModel(mModel.get());
mView->setModel(mProxy.get());
mProxy->sort(0, Qt::DescendingOrder);
connect(mView, &QListView::activated, this,
&DialogUserViewWrapper::requestToActivateItem);
connect(mView, &QListView::clicked, this,
&DialogUserViewWrapper::requestToActivateItem);
}
void DialogUserViewWrapper::requestToShowMenu(QPoint pos) {
auto index = mView->indexAt(pos);
auto sIndex = mProxy->mapToSource(index);
if (sIndex.isValid()) {
auto [status, dialogId] = mModel->getDialogInfo(sIndex);
emit showMenuForDialog(mView->viewport()->mapToGlobal(pos), status,
dialogId);
}
}
void DialogUserViewWrapper::requestToActivateItem(const QModelIndex& index) {
auto sIndex = mProxy->mapToSource(index);
mModel->rowWasSelected(sIndex);
}
| 33.675676 | 77 | 0.723114 | [
"model"
] |
de36dd9ebce94d299e2adf1c5d0c5bb00b36483d | 4,006 | cpp | C++ | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelCell.cpp | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 38 | 2018-04-17T17:10:59.000Z | 2022-01-11T22:00:13.000Z | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelCell.cpp | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 1 | 2020-06-06T08:01:18.000Z | 2020-06-07T05:40:15.000Z | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelCell.cpp | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 12 | 2018-07-27T19:32:35.000Z | 2022-01-11T22:00:14.000Z | // Copyright 2018 Pavlov Dmitriy
#include "LevelCell.h"
#include "LevelGeneratorSettings.h"
#include "Rooms/LevelRooms.h"
#include "LevelGenPluginRuntime_LogCategory.h"
#include "LevelFloor.h"
#include "LevelGraphNode.h"
#include "ProceduralFigure.h"
#include "ProceduralMeshActor.h"
#include "Rooms/PlacedLevelRoom.h"
//.........................................
//EDirection
//.........................................
static_assert(ELevelCellType::end == (ELevelCellType)5, "You must update ELevelCellTypeCreate after add new enum");
FLevelCellBase* ELevelCellTypeCreate(ELevelCellType Type, FLevelCellData& CellData)
{
switch (Type)
{
case ELevelCellType::Road:
return new FLevelCellRoad(CellData);
case ELevelCellType::MainRoad:
return new FLevelCellMainRoad(CellData);
case ELevelCellType::Bilding:
return new FLevelCellBilding(CellData);
case ELevelCellType::Tower:
return new FLevelCellTower(CellData);
default: throw;
}
}
//******************************************************
//FLevelCellData
//*******************************************************
FLevelCellData::FLevelCellData(const FLevelGeneratorSettings& Settings, FVector2D _CellCoordinate, const FDataStorage& DataStorage) : CellCoordinate(_CellCoordinate), LevelSettings(Settings)
{
Floors.resize(Settings.FloorNum, FLevelFloorData(DataStorage));
for (int i = 0; i < Floors.size(); i++)
{
Floors[i].SetCoordinate(FVector(CellCoordinate, i));
}
}
//******************************************************
//FLevelCellRoad
//*******************************************************
bool FLevelCellRoad::CanRoomPlacedOnCell(ERoomType RoomType) const
{
static_assert((int)ERoomType::end == 4, "Check CanRoomPlacedOnCell");
switch (RoomType)
{
case ERoomType::NodeRoom:
return false;
case ERoomType::GroundLinkRoom:
return false;
case ERoomType::RoadLinkRoom:
return true;
case ERoomType::TerraceLinkRoom:
return true;
default: throw;
}
return false;
}
//******************************************************
//FLevelCellBilding
//*******************************************************
void FLevelCellBilding::SetBaseLevelNum()
{
std::vector<FPlacedLevelRoomLinkedToLevel*> Rooms;
Rooms.reserve(CellData.LevelSettings.FloorNum);
for (int k = 0; k < CellData.LevelSettings.FloorNum; k++)
{
if (CellData.Floors[k].PlasedRoom)
{
Rooms.push_back(CellData.Floors[k].PlasedRoom);
}
}
if (!Rooms.empty())
{
CellData.LowerBaseLevelNum = (*Rooms.begin())->GetStartCoordinate().Z;
CellData.UpperBaseLevelNum = Rooms.back()->GetStartCoordinate().Z;
CellData.BaseLevelNumFirstIniciate = true;
}
else
{
CellData.BaseLevelNumFirstIniciate = false;
}
}
bool FLevelCellBilding::CanRoomPlacedOnCell(ERoomType RoomType) const
{
static_assert((int)ERoomType::end == 4, "Check CanRoomPlacedOnCell");
switch (RoomType)
{
case ERoomType::NodeRoom:
return true;
case ERoomType::GroundLinkRoom:
return true;
case ERoomType::RoadLinkRoom:
return false;
case ERoomType::TerraceLinkRoom:
return false;
default: throw;
}
return false;
}
//******************************************************
//FLevelCellTower
//*******************************************************
void FLevelCellTower::SetBaseLevelNum()
{
CellData.BaseLevelNumFirstIniciate = true;
CellData.UpperBaseLevelNum = CellData.LevelSettings.FloorNum;
CellData.LowerBaseLevelNum = 0;
}
bool FLevelCellTower::CanRoomPlacedOnCell(ERoomType RoomType) const
{
static_assert((int)ERoomType::end == 4, "Check CanRoomPlacedOnCell");
switch (RoomType)
{
case ERoomType::NodeRoom:
return true;
case ERoomType::GroundLinkRoom:
return true;
case ERoomType::RoadLinkRoom:
return false;
case ERoomType::TerraceLinkRoom:
return false;
default: throw;
}
return false;
}
void FLevelCellThroughCell::SetBaseLevelNum()
{
CellData.BaseLevelNumFirstIniciate = true;
CellData.UpperBaseLevelNum = 0;
CellData.LowerBaseLevelNum = 0;
}
| 19.831683 | 190 | 0.651023 | [
"vector"
] |
de3e7892ab5668f6c2c55618e83d4ef0800f1110 | 55,157 | cpp | C++ | project2D/Vector4.cpp | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/Vector4.cpp | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/Vector4.cpp | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | // #include, using, etc
#include "Vector4.h"
//--------------------------------------------------------------------------------------
// Default Constructor
//--------------------------------------------------------------------------------------
Vector4::Vector4()
{
x = 0;
y = 0;
z = 0;
w = 1;
}
//--------------------------------------------------------------------------------------
// Constructor for passing in four floats.
//--------------------------------------------------------------------------------------
Vector4::Vector4(float x, float y, float z, float w)
{
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
//--------------------------------------------------------------------------------------
// Default Destructor
//--------------------------------------------------------------------------------------
Vector4::~Vector4()
{
}
//--------------------------------------------------------------------------------------
// Addition: Overloads the "+" operator so that Vector4s can be added together.
//
// Param:
// rhs: The right hand side value being passed into the function that you want added.
// Return:
// Returns a Vector4 value equel to the values you added together.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator+(const Vector4& rhs)
{
Vector4 result;
result.x = x + rhs.x;
result.y = y + rhs.y;
result.z = z + rhs.z;
result.w = w + rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Subtraction: Overloads the "-" operator so that Vector4s can be subtracted from each other.
//
// Param:
// rhs: The right hand side value being passed into the function that you want subtract.
// Return:
// Returns a Vector4 value equel to the values you subtract together.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator-(const Vector4& rhs)
{
Vector4 result;
result.x = x - rhs.x;
result.y = y - rhs.y;
result.z = z - rhs.z;
result.w = w - rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Divide: Overloads the "/" operator so that Vector4s can be Divided together.
//
// Param:
// rhs: The right hand side value being passed into the function that you want Divide.
// Return:
// Returns a Vector4 value equel to the values you Divide together.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator/(const float rhs)
{
Vector4 result;
result.x = x / rhs;
result.y = y / rhs;
result.z = z / rhs;
result.w = w / rhs;
return result;
}
//--------------------------------------------------------------------------------------
// Multiply vector by float: Overloads the "*" operator so that Vector4s can be Multiplied by floats.
//
// Param:
// rhs: The float you would like to be multiplied by the vector
// Return:
// Returns a Vector4 value equel to the values you Multiplied by.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator*(const float rhs)
{
Vector4 result;
result.x = x * rhs;
result.y = y * rhs;
result.z = z * rhs;
result.w = w * rhs;
return result;
}
//--------------------------------------------------------------------------------------
// Multiply float by vector: Overloads the "*" operator so that floats can be Multiplied by Vector4s.
//
// Param:
// lhs: The float you would like to multiply by the Vector4.
// rhs: The Vector4 you would like to be multiplied by the float.
// Return:
// Returns a Vector4 value equel to the values you Multiplied by.
//
// (out side of class so we can order)
//--------------------------------------------------------------------------------------
Vector4 operator*(float lhs, const Vector4& rhs)
{
Vector4 result;
result.x = lhs * rhs.x;
result.y = lhs * rhs.y;
result.z = lhs * rhs.z;
result.w = lhs * rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Allow negative vectors: overload the "-" operator to also allow negative vectors.
//
// Return:
// Returns a negative Vector4.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator-()
{
Vector4 result;
result.x = -x;
result.y = -y;
result.z = -z;
result.w = -w;
return result;
}
//--------------------------------------------------------------------------------------
// Greater then operator: Overloads the ">" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is greater then or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator>(const Vector4 rhs)
{
return (x > rhs.x && y > rhs.y && z > rhs.z && w > rhs.w);
}
// --------------------------------------------------------------------------------------
// Less then operator: Overloads the "<" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is less then or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator<(const Vector4 rhs)
{
return (x < rhs.x && y < rhs.y && z < rhs.z && w < rhs.w);
}
//--------------------------------------------------------------------------------------
// Plus equal: Overloads the "+=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector you would like to increase incremently.
// Return:
// Returns a Vector4.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator+=(const Vector4& rhs)
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
return *this;
}
//--------------------------------------------------------------------------------------
// Subtract equal: Overloads the "-=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector you would like to decrease incremently.
// Return:
// Returns a Vector4.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator-=(const Vector4& rhs)
{
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
w -= rhs.w;
return *this;
}
//--------------------------------------------------------------------------------------
// Multiply equal: Overloads the "*=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector you would like to decrease incremently.
// Return:
// Returns a Vector4.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator*=(const float rhs)
{
Vector4 result;
result.x = x *= rhs;
result.y = y *= rhs;
result.z = z *= rhs;
result.w = w *= rhs;
return result;
}
//--------------------------------------------------------------------------------------
// Divide equal: Overloads the "/=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector you would like to Divide incremently.
// Return:
// Returns a Vector4.
//--------------------------------------------------------------------------------------
Vector4 Vector4::operator/=(const float rhs)
{
Vector4 result;
result.x = x /= rhs;
result.y = y /= rhs;
result.z = z /= rhs;
result.w = w /= rhs;
return result;
}
//--------------------------------------------------------------------------------------
// Sub-script operator returning a reference
//
// Param:
// rhs: takes in an int.
// Return:
// Returns a float.
//--------------------------------------------------------------------------------------
float& Vector4::operator[](const int rhs)
{
if (rhs == 0)
return x;
else if (rhs == 1)
return y;
else if (rhs == 2)
return z;
else if (rhs == 3)
return w;
else
return x;
}
//--------------------------------------------------------------------------------------
// Cast operator to float pointer
//--------------------------------------------------------------------------------------
Vector4::operator float*()
{
return &x;
}
//--------------------------------------------------------------------------------------
// Equal to operator: Overloads the "==" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is equal to or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator==(const Vector4 rhs)
{
return (x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w);
}
//--------------------------------------------------------------------------------------
// Not Equal to operator: Overloads the "!=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is equal to or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator!=(const Vector4 rhs)
{
return (x != rhs.x && y != rhs.y && z != rhs.z && w != rhs.w);
}
//--------------------------------------------------------------------------------------
// Greater then or equal to operator: Overloads the ">=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is greater then or equal to or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator>=(const Vector4 rhs)
{
return (x >= rhs.x && y >= rhs.y && z >= rhs.z && w >= rhs.w);
}
//--------------------------------------------------------------------------------------
// Less then or equal to operator: Overloads the "<=" operator so that it can be used with Vectors.
//
// Param:
// rhs: The Vector to be checked against.
// Return:
// Returns a bool of true or false for if the value is less then or equal or not.
//--------------------------------------------------------------------------------------
bool Vector4::operator<=(const Vector4 rhs)
{
return (x <= rhs.x && y <= rhs.y && z <= rhs.z && w <= rhs.w);
}
//--------------------------------------------------------------------------------------
// Dot Product: Dot Product of two vectors.
//
// Param:
// rhs: Vector4 you want the dot product of.
// Return:
// Returns a float value of the dot product of the vector.
//--------------------------------------------------------------------------------------
float Vector4::dot(const Vector4& rhs)
{
float result;
result = x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Cross: Cross Product of two vectors is another Vector.
//
// Param:
// rhs: Vector4 to do the corss product on.
// Return:
// Returns a Vector4 value that is the new Vector.
//--------------------------------------------------------------------------------------
Vector4 Vector4::cross(const Vector4& rhs)
{
Vector4 result;
result.x = y * rhs.z - z * rhs.y;
result.y = z * rhs.x - x * rhs.z;
result.z = x * rhs.y - y * rhs.x;
result.w = 0;
return result;
}
//--------------------------------------------------------------------------------------
// Magnitude: Returns the length of this vector.
//
// Return:
// Returns a float that is the length of the vector.
//--------------------------------------------------------------------------------------
float Vector4::magnitude()
{
float result;
result = sqrtf(x*x + y*y + z*z + w*w);
return result;
}
//--------------------------------------------------------------------------------------
// MagnititudeSquared: Returns the squared length of this vector
//
// Return:
// Returns a float that is the length of the vector.
//--------------------------------------------------------------------------------------
float Vector4::MagnititudeSquared()
{
float result;
result = x*x + y*y + z*z + w*w;
return result;
}
//--------------------------------------------------------------------------------------
// Normalise: Makes this vector have a magnitude of 1. (It keeps the same direction)
// This function will change the current vector.
//--------------------------------------------------------------------------------------
void Vector4::normalise()
{
float mag = magnitude();
if (mag != 0)
{
x = x / mag;
y = y / mag;
z = z / mag;
w = w / mag;
}
}
//--------------------------------------------------------------------------------------
// Normalised: Makes this vector have a magnitude of 1. (It keeps the same direction)
// This function will not change the current vector and a new one will be created.
//
// Param:
// data: A Vector4 to be normalised.
// Return:
// Returns a Vector4 of the normalised value.
//--------------------------------------------------------------------------------------
Vector4 Vector4::Normalised(Vector4 data)
{
float mag = data.magnitude();
Vector4 result;
if (mag != 0)
{
result.x = data.x / mag;
result.y = data.y / mag;
result.z = data.z / mag;
result.w = data.w / mag;
return result;
}
return Vector4();
}
//--------------------------------------------------------------------------------------
// CalcNormal: Calculate the normal of a face.
//
// Param:
// pos: Vector4 position.
// Return:
// Returns a Vector4 value that is the normal of a face.
//--------------------------------------------------------------------------------------
Vector4 Vector4::CalcNormal(Vector4 pos1, Vector4 pos2)
{
Vector4 vec1;
Vector4 vec2;
vec1.x = pos1.x - x;
vec1.y = pos1.y - y;
vec1.z = pos1.z - z;
vec2.x = pos2.x - x;
vec2.y = pos2.y - y;
vec2.z = pos2.z - z;
Vector4 res = vec1.cross(vec2);
res.normalise();
return res;
}
//--------------------------------------------------------------------------------------
// Min: Returns a vector that is made from the smallest components of two vectors.
//
// Param:
// rhs: The second vector to compare to.
// Return:
// Returns a Vector4 that is the smallest components of two vectors.
//--------------------------------------------------------------------------------------
Vector4 Vector4::Min(Vector4 rhs)
{
Vector4 result;
if (x < rhs.x)
result.x = x;
else
result.x = rhs.x;
if (y < rhs.y)
result.y = y;
else
result.y = rhs.y;
if (z < rhs.z)
result.z = z;
else
result.z = rhs.z;
if (w < rhs.w)
result.w = w;
else
result.w = rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Max: Returns a vector that is made from the largest components of two vectors.
//
// Param:
// rhs: The second vector to compare to.
// Return:
// Returns a Vector4 that is the largest components of two vectors.
//--------------------------------------------------------------------------------------
Vector4 Vector4::Max(Vector4 rhs)
{
Vector4 result;
if (x > rhs.x)
result.x = x;
else
result.x = rhs.x;
if (y > rhs.y)
result.y = y;
else
result.y = rhs.y;
if (z > rhs.z)
result.z = z;
else
result.z = rhs.z;
if (w > rhs.w)
result.w = w;
else
result.w = rhs.w;
return result;
}
//--------------------------------------------------------------------------------------
// Clamp: Stop a vector at a max length.
//
// Param:
// min: The minimum of the vector.
// max: The maximum of the vector.
// Return:
// Returns a Vector4 clamped at the maxlength.
//--------------------------------------------------------------------------------------
Vector4 Vector4::Clamp(Vector4 min, Vector4 max)
{
Vector4 result;
result = this->Max(min);
result = result.Min(max);
return result;
}
//--------------------------------------------------------------------------------------
// Lerp: Linearly interpolates between vectors a and b by t.
//
// Param:
// a: Vector4
// b: Vector4
// t: Float
// Return:
// Returns a Vector4
//--------------------------------------------------------------------------------------
Vector4 Vector4::Lerp(Vector4 a, Vector4 b, float t)
{
return (a + b) * t;
}
//--------------------------------------------------------------------------------------
// Distance: Returns the distance between a and b.
//
// Param:
// a: Vector4
// b: Vector4
// Return:
// Returns a float which is the distance between a and b.
//--------------------------------------------------------------------------------------
float Vector4::Distance(Vector4 pos1, Vector4 pos2)
{
Vector4 diff = pos1 - pos2;
return diff.magnitude();
}
//--------------------------------------------------------------------------------------
// Bezier: A function to calculate a bezier curves.
//
// Param:
// t: A float representing time.
// a: Vector4 point.
// b: Vector4 point.
// c: Vector4 point.
// Return:
// Returns a Vector4 value of the Bezier curve.
//--------------------------------------------------------------------------------------
Vector4 Vector4::Bezier(float t, Vector4 a, Vector4 b, Vector4 c)
{
Vector4 result;
Vector4 ab = Lerp(a, b, t);
Vector4 bc = Lerp(b, c, t);
result = Lerp(ab, bc, t);
return result;
}
//--------------------------------------------------------------------------------------
// hermiteCurve: A function to calculate a hermite Curve.
//
// Param:
// point0: Vector4 point.
// tangent0: Vector4 tangent.
// point1: Vector4 point.
// tangent1: Vector4 tangent.
// t: A float representing time.
// Return:
// Returns a Vector4 value of the hermite curve.
//--------------------------------------------------------------------------------------
Vector4 Vector4::hermiteCurve(Vector4 point0, Vector4 tangent0, Vector4 point1, Vector4 tangent1, float t)
{
// calculate t-squared and t-cubed
float tsq = t * t;
float tcub = tsq * t;
// calculate the 4 basis functions
float h00 = 2 * tcub - 3 * tsq + 1;
float h01 = -2 * tcub + 3 * tsq;
float h10 = tcub - 2 * tsq + t;
float h11 = tcub - tsq;
// return the combined result
return h00 * point0 + h10 * tangent0 + h01 * point1 + h11 * tangent1;
}
//--------------------------------------------------------------------------------------
// Swizzle: Switch around the values of x, y, z and w to every possible combo.
//
// Return:
// Returns a Vector4 value with the applied changes.
//--------------------------------------------------------------------------------------
//////////////// SWIZZLE ////////////////
// Swizzle for wwww
Vector4 Vector4::wwww()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = w;
result.w = w;
return result;
}
// Swizzle for wwwx
Vector4 Vector4::wwwx()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = w;
result.w = x;
return result;
}
// Swizzle for wwwy
Vector4 Vector4::wwwy()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = w;
result.w = y;
return result;
}
// Swizzle for wwwz
Vector4 Vector4::wwwz()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = w;
result.w = z;
return result;
}
// Swizzle for wwxw
Vector4 Vector4::wwxw()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = x;
result.w = w;
return result;
}
// Swizzle for wwxx
Vector4 Vector4::wwxx()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = x;
result.w = x;
return result;
}
// Swizzle for wwxy
Vector4 Vector4::wwxy()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = x;
result.w = y;
return result;
}
// Swizzle for wwxz
Vector4 Vector4::wwxz()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = x;
result.w = z;
return result;
}
// Swizzle for wwyw
Vector4 Vector4::wwyw()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = y;
result.w = w;
return result;
}
// Swizzle for wwyx
Vector4 Vector4::wwyx()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = y;
result.w = x;
return result;
}
// Swizzle for wwyy
Vector4 Vector4::wwyy()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = y;
result.w = y;
return result;
}
// Swizzle for wwyz
Vector4 Vector4::wwyz()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = y;
result.w = z;
return result;
}
// Swizzle for wwzw
Vector4 Vector4::wwzw()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = z;
result.w = w;
return result;
}
// Swizzle for wwzx
Vector4 Vector4::wwzx()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = z;
result.w = x;
return result;
}
// Swizzle for wwzy
Vector4 Vector4::wwzy()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = z;
result.w = y;
return result;
}
// Swizzle for wwzz
Vector4 Vector4::wwzz()
{
Vector4 result;
result.x = w;
result.y = w;
result.z = z;
result.w = z;
return result;
}
// Swizzle for wxww
Vector4 Vector4::wxww()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = w;
result.w = w;
return result;
}
// Swizzle for wxwx
Vector4 Vector4::wxwx()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = w;
result.w = x;
return result;
}
// Swizzle for wxwy
Vector4 Vector4::wxwy()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = w;
result.w = y;
return result;
}
// Swizzle for wxwz
Vector4 Vector4::wxwz()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = w;
result.w = z;
return result;
}
// Swizzle for wxxw
Vector4 Vector4::wxxw()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = x;
result.w = w;
return result;
}
// Swizzle for wxxx
Vector4 Vector4::wxxx()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = x;
result.w = x;
return result;
}
// Swizzle for wxxy
Vector4 Vector4::wxxy()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = x;
result.w = y;
return result;
}
// Swizzle for wxxz
Vector4 Vector4::wxxz()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = x;
result.w = z;
return result;
}
// Swizzle for wxyw
Vector4 Vector4::wxyw()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = y;
result.w = w;
return result;
}
// Swizzle for wxyx
Vector4 Vector4::wxyx()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = y;
result.w = x;
return result;
}
// Swizzle for wxyy
Vector4 Vector4::wxyy()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = y;
result.w = y;
return result;
}
// Swizzle for wxyz
Vector4 Vector4::wxyz()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = y;
result.w = z;
return result;
}
// Swizzle for wxzw
Vector4 Vector4::wxzw()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = z;
result.w = w;
return result;
}
// Swizzle for wxzx
Vector4 Vector4::wxzx()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = z;
result.w = x;
return result;
}
// Swizzle for wxzy
Vector4 Vector4::wxzy()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = z;
result.w = y;
return result;
}
// Swizzle for wxzz
Vector4 Vector4::wxzz()
{
Vector4 result;
result.x = w;
result.y = x;
result.z = z;
result.w = z;
return result;
}
// Swizzle for wyww
Vector4 Vector4::wyww()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = w;
result.w = w;
return result;
}
// Swizzle for wywx
Vector4 Vector4::wywx()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = w;
result.w = x;
return result;
}
// Swizzle for wywy
Vector4 Vector4::wywy()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = w;
result.w = y;
return result;
}
// Swizzle for wywz
Vector4 Vector4::wywz()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = w;
result.w = z;
return result;
}
// Swizzle for wyxw
Vector4 Vector4::wyxw()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = x;
result.w = w;
return result;
}
// Swizzle for wyxx
Vector4 Vector4::wyxx()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = x;
result.w = x;
return result;
}
// Swizzle for wyxy
Vector4 Vector4::wyxy()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = x;
result.w = y;
return result;
}
// Swizzle for wyxz
Vector4 Vector4::wyxz()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = x;
result.w = z;
return result;
}
// Swizzle for wyyw
Vector4 Vector4::wyyw()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = y;
result.w = w;
return result;
}
// Swizzle for wyyx
Vector4 Vector4::wyyx()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = y;
result.w = x;
return result;
}
// Swizzle for wyyy
Vector4 Vector4::wyyy()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = y;
result.w = y;
return result;
}
// Swizzle for wyyz
Vector4 Vector4::wyyz()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = y;
result.w = z;
return result;
}
// Swizzle for wyzw
Vector4 Vector4::wyzw()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = z;
result.w = w;
return result;
}
// Swizzle for wyzx
Vector4 Vector4::wyzx()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = z;
result.w = x;
return result;
}
// Swizzle for wyzy
Vector4 Vector4::wyzy()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = z;
result.w = y;
return result;
}
// Swizzle for wyzz
Vector4 Vector4::wyzz()
{
Vector4 result;
result.x = w;
result.y = y;
result.z = z;
result.w = z;
return result;
}
// Swizzle for wzww
Vector4 Vector4::wzww()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = w;
result.w = w;
return result;
}
// Swizzle for wzwx
Vector4 Vector4::wzwx()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = w;
result.w = x;
return result;
}
// Swizzle for wzwy
Vector4 Vector4::wzwy()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = w;
result.w = y;
return result;
}
// Swizzle for wzwz
Vector4 Vector4::wzwz()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = w;
result.w = z;
return result;
}
// Swizzle for wzxw
Vector4 Vector4::wzxw()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = x;
result.w = w;
return result;
}
// Swizzle for wzxx
Vector4 Vector4::wzxx()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = x;
result.w = x;
return result;
}
// Swizzle for wzxy
Vector4 Vector4::wzxy()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = x;
result.w = y;
return result;
}
// Swizzle for wzxz
Vector4 Vector4::wzxz()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = x;
result.w = z;
return result;
}
// Swizzle for wzyw
Vector4 Vector4::wzyw()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = y;
result.w = w;
return result;
}
// Swizzle for wzyx
Vector4 Vector4::wzyx()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = y;
result.w = x;
return result;
}
// Swizzle for wzyy
Vector4 Vector4::wzyy()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = y;
result.w = y;
return result;
}
// Swizzle for wzyz
Vector4 Vector4::wzyz()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = y;
result.w = z;
return result;
}
// Swizzle for wzzw
Vector4 Vector4::wzzw()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = z;
result.w = w;
return result;
}
// Swizzle for wzzx
Vector4 Vector4::wzzx()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = z;
result.w = x;
return result;
}
// Swizzle for wzzy
Vector4 Vector4::wzzy()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = z;
result.w = y;
return result;
}
// Swizzle for wzzz
Vector4 Vector4::wzzz()
{
Vector4 result;
result.x = w;
result.y = z;
result.z = z;
result.w = z;
return result;
}
// Swizzle for xwww
Vector4 Vector4::xwww()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = w;
result.w = w;
return result;
}
// Swizzle for xwwx
Vector4 Vector4::xwwx()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = w;
result.w = x;
return result;
}
// Swizzle for xwwy
Vector4 Vector4::xwwy()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = w;
result.w = y;
return result;
}
// Swizzle for xwwz
Vector4 Vector4::xwwz()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = w;
result.w = z;
return result;
}
// Swizzle for xwxw
Vector4 Vector4::xwxw()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = x;
result.w = w;
return result;
}
// Swizzle for xwxx
Vector4 Vector4::xwxx()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = x;
result.w = x;
return result;
}
// Swizzle for xwxy
Vector4 Vector4::xwxy()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = x;
result.w = y;
return result;
}
// Swizzle for xwxz
Vector4 Vector4::xwxz()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = x;
result.w = z;
return result;
}
// Swizzle for xwyw
Vector4 Vector4::xwyw()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = y;
result.w = w;
return result;
}
// Swizzle for xwyx
Vector4 Vector4::xwyx()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = y;
result.w = x;
return result;
}
// Swizzle for xwyy
Vector4 Vector4::xwyy()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = y;
result.w = y;
return result;
}
// Swizzle for xwyz
Vector4 Vector4::xwyz()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = y;
result.w = z;
return result;
}
// Swizzle for xwzw
Vector4 Vector4::xwzw()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = z;
result.w = w;
return result;
}
// Swizzle for xwzx
Vector4 Vector4::xwzx()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = z;
result.w = x;
return result;
}
// Swizzle for xwzy
Vector4 Vector4::xwzy()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = z;
result.w = y;
return result;
}
// Swizzle for xwzz
Vector4 Vector4::xwzz()
{
Vector4 result;
result.x = x;
result.y = w;
result.z = z;
result.w = z;
return result;
}
// Swizzle for xxww
Vector4 Vector4::xxww()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = w;
result.w = w;
return result;
}
// Swizzle for xxwx
Vector4 Vector4::xxwx()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = w;
result.w = x;
return result;
}
// Swizzle for xxwy
Vector4 Vector4::xxwy()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = w;
result.w = y;
return result;
}
// Swizzle for xxwz
Vector4 Vector4::xxwz()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = w;
result.w = z;
return result;
}
// Swizzle for xxxw
Vector4 Vector4::xxxw()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = x;
result.w = w;
return result;
}
// Swizzle for xxxx
Vector4 Vector4::xxxx()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = x;
result.w = x;
return result;
}
// Swizzle for xxxy
Vector4 Vector4::xxxy()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = x;
result.w = y;
return result;
}
// Swizzle for xxxz
Vector4 Vector4::xxxz()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = x;
result.w = z;
return result;
}
// Swizzle for xxyw
Vector4 Vector4::xxyw()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = y;
result.w = w;
return result;
}
// Swizzle for xxyx
Vector4 Vector4::xxyx()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = y;
result.w = x;
return result;
}
// Swizzle for xxyy
Vector4 Vector4::xxyy()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = y;
result.w = y;
return result;
}
// Swizzle for xxyz
Vector4 Vector4::xxyz()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = y;
result.w = z;
return result;
}
// Swizzle for xxzw
Vector4 Vector4::xxzw()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = z;
result.w = w;
return result;
}
// Swizzle for xxzx
Vector4 Vector4::xxzx()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = z;
result.w = x;
return result;
}
// Swizzle for xxzy
Vector4 Vector4::xxzy()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = z;
result.w = y;
return result;
}
// Swizzle for xxzz
Vector4 Vector4::xxzz()
{
Vector4 result;
result.x = x;
result.y = x;
result.z = z;
result.w = z;
return result;
}
// Swizzle for xyww
Vector4 Vector4::xyww()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = w;
result.w = w;
return result;
}
// Swizzle for xywx
Vector4 Vector4::xywx()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = w;
result.w = x;
return result;
}
// Swizzle for xywy
Vector4 Vector4::xywy()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = w;
result.w = y;
return result;
}
// Swizzle for xywz
Vector4 Vector4::xywz()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = w;
result.w = z;
return result;
}
// Swizzle for xyxw
Vector4 Vector4::xyxw()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = x;
result.w = w;
return result;
}
// Swizzle for xyxx
Vector4 Vector4::xyxx()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = x;
result.w = x;
return result;
}
// Swizzle for xyxy
Vector4 Vector4::xyxy()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = x;
result.w = y;
return result;
}
// Swizzle for xyxz
Vector4 Vector4::xyxz()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = x;
result.w = z;
return result;
}
// Swizzle for xyyw
Vector4 Vector4::xyyw()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = y;
result.w = w;
return result;
}
// Swizzle for xyyx
Vector4 Vector4::xyyx()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = y;
result.w = x;
return result;
}
// Swizzle for xyyy
Vector4 Vector4::xyyy()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = y;
result.w = y;
return result;
}
// Swizzle for xyyz
Vector4 Vector4::xyyz()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = y;
result.w = z;
return result;
}
// Swizzle for xyzw
Vector4 Vector4::xyzw()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
}
// Swizzle for xyzx
Vector4 Vector4::xyzx()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = z;
result.w = x;
return result;
}
// Swizzle for xyzy
Vector4 Vector4::xyzy()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = z;
result.w = y;
return result;
}
// Swizzle for xyzz
Vector4 Vector4::xyzz()
{
Vector4 result;
result.x = x;
result.y = y;
result.z = z;
result.w = z;
return result;
}
// Swizzle for xzww
Vector4 Vector4::xzww()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = w;
result.w = w;
return result;
}
// Swizzle for xzwx
Vector4 Vector4::xzwx()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = w;
result.w = x;
return result;
}
// Swizzle for xzwy
Vector4 Vector4::xzwy()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = w;
result.w = y;
return result;
}
// Swizzle for xzwz
Vector4 Vector4::xzwz()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = w;
result.w = z;
return result;
}
// Swizzle for xzxw
Vector4 Vector4::xzxw()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = x;
result.w = w;
return result;
}
// Swizzle for xzxx
Vector4 Vector4::xzxx()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = x;
result.w = x;
return result;
}
// Swizzle for xzxy
Vector4 Vector4::xzxy()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = x;
result.w = y;
return result;
}
// Swizzle for xzxz
Vector4 Vector4::xzxz()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = x;
result.w = z;
return result;
}
// Swizzle for xzyw
Vector4 Vector4::xzyw()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = y;
result.w = w;
return result;
}
// Swizzle for xzyx
Vector4 Vector4::xzyx()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = y;
result.w = x;
return result;
}
// Swizzle for xzyy
Vector4 Vector4::xzyy()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = y;
result.w = y;
return result;
}
// Swizzle for xzyz
Vector4 Vector4::xzyz()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = y;
result.w = z;
return result;
}
// Swizzle for xzzw
Vector4 Vector4::xzzw()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = z;
result.w = w;
return result;
}
// Swizzle for xzzx
Vector4 Vector4::xzzx()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = z;
result.w = x;
return result;
}
// Swizzle for xzzy
Vector4 Vector4::xzzy()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = z;
result.w = y;
return result;
}
// Swizzle for xzzz
Vector4 Vector4::xzzz()
{
Vector4 result;
result.x = x;
result.y = z;
result.z = z;
result.w = z;
return result;
}
// Swizzle for ywww
Vector4 Vector4::ywww()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = w;
result.w = w;
return result;
}
// Swizzle for ywwx
Vector4 Vector4::ywwx()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = w;
result.w = x;
return result;
}
// Swizzle for ywwy
Vector4 Vector4::ywwy()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = w;
result.w = y;
return result;
}
// Swizzle for ywwz
Vector4 Vector4::ywwz()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = w;
result.w = z;
return result;
}
// Swizzle for ywxw
Vector4 Vector4::ywxw()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = x;
result.w = w;
return result;
}
// Swizzle for ywxx
Vector4 Vector4::ywxx()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = x;
result.w = x;
return result;
}
// Swizzle for ywxy
Vector4 Vector4::ywxy()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = x;
result.w = y;
return result;
}
// Swizzle for ywxz
Vector4 Vector4::ywxz()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = x;
result.w = z;
return result;
}
// Swizzle for ywyw
Vector4 Vector4::ywyw()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = y;
result.w = w;
return result;
}
// Swizzle for ywyx
Vector4 Vector4::ywyx()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = y;
result.w = x;
return result;
}
// Swizzle for ywyy
Vector4 Vector4::ywyy()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = y;
result.w = y;
return result;
}
// Swizzle for ywyz
Vector4 Vector4::ywyz()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = y;
result.w = z;
return result;
}
// Swizzle for ywzw
Vector4 Vector4::ywzw()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = z;
result.w = w;
return result;
}
// Swizzle for ywzx
Vector4 Vector4::ywzx()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = z;
result.w = x;
return result;
}
// Swizzle for ywzy
Vector4 Vector4::ywzy()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = z;
result.w = y;
return result;
}
// Swizzle for ywzz
Vector4 Vector4::ywzz()
{
Vector4 result;
result.x = y;
result.y = w;
result.z = z;
result.w = z;
return result;
}
// Swizzle for yxww
Vector4 Vector4::yxww()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = w;
result.w = w;
return result;
}
// Swizzle for yxwx
Vector4 Vector4::yxwx()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = w;
result.w = x;
return result;
}
// Swizzle for yxwy
Vector4 Vector4::yxwy()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = w;
result.w = y;
return result;
}
// Swizzle for yxwz
Vector4 Vector4::yxwz()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = w;
result.w = z;
return result;
}
// Swizzle for yxxw
Vector4 Vector4::yxxw()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = x;
result.w = w;
return result;
}
// Swizzle for yxxx
Vector4 Vector4::yxxx()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = x;
result.w = x;
return result;
}
// Swizzle for yxxy
Vector4 Vector4::yxxy()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = x;
result.w = y;
return result;
}
// Swizzle for yxxz
Vector4 Vector4::yxxz()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = x;
result.w = z;
return result;
}
// Swizzle for yxyw
Vector4 Vector4::yxyw()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = y;
result.w = w;
return result;
}
// Swizzle for yxyx
Vector4 Vector4::yxyx()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = y;
result.w = x;
return result;
}
// Swizzle for yxyy
Vector4 Vector4::yxyy()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = y;
result.w = y;
return result;
}
// Swizzle for yxyz
Vector4 Vector4::yxyz()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = y;
result.w = z;
return result;
}
// Swizzle for yxzw
Vector4 Vector4::yxzw()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = z;
result.w = w;
return result;
}
// Swizzle for yxzx
Vector4 Vector4::yxzx()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = z;
result.w = x;
return result;
}
// Swizzle for yxzy
Vector4 Vector4::yxzy()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = z;
result.w = y;
return result;
}
// Swizzle for yxzz
Vector4 Vector4::yxzz()
{
Vector4 result;
result.x = y;
result.y = x;
result.z = z;
result.w = z;
return result;
}
// Swizzle for yyww
Vector4 Vector4::yyww()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = w;
result.w = w;
return result;
}
// Swizzle for yywx
Vector4 Vector4::yywx()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = w;
result.w = x;
return result;
}
// Swizzle for yywy
Vector4 Vector4::yywy()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = w;
result.w = y;
return result;
}
// Swizzle for yywz
Vector4 Vector4::yywz()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = w;
result.w = z;
return result;
}
// Swizzle for yyxw
Vector4 Vector4::yyxw()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = x;
result.w = w;
return result;
}
// Swizzle for yyxx
Vector4 Vector4::yyxx()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = x;
result.w = x;
return result;
}
// Swizzle for yyxy
Vector4 Vector4::yyxy()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = x;
result.w = y;
return result;
}
// Swizzle for yyxz
Vector4 Vector4::yyxz()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = x;
result.w = z;
return result;
}
// Swizzle for yyyw
Vector4 Vector4::yyyw()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = y;
result.w = w;
return result;
}
// Swizzle for yyyx
Vector4 Vector4::yyyx()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = y;
result.w = x;
return result;
}
// Swizzle for yyyy
Vector4 Vector4::yyyy()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = y;
result.w = y;
return result;
}
// Swizzle for yyyz
Vector4 Vector4::yyyz()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = y;
result.w = z;
return result;
}
// Swizzle for yyzw
Vector4 Vector4::yyzw()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = z;
result.w = w;
return result;
}
// Swizzle for yyzx
Vector4 Vector4::yyzx()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = z;
result.w = x;
return result;
}
// Swizzle for yyzy
Vector4 Vector4::yyzy()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = z;
result.w = y;
return result;
}
// Swizzle for yyzz
Vector4 Vector4::yyzz()
{
Vector4 result;
result.x = y;
result.y = y;
result.z = z;
result.w = z;
return result;
}
// Swizzle for yzww
Vector4 Vector4::yzww()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = w;
result.w = w;
return result;
}
// Swizzle for yzwx
Vector4 Vector4::yzwx()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = w;
result.w = x;
return result;
}
// Swizzle for yzwy
Vector4 Vector4::yzwy()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = w;
result.w = y;
return result;
}
// Swizzle for yzwz
Vector4 Vector4::yzwz()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = w;
result.w = z;
return result;
}
// Swizzle for yzxw
Vector4 Vector4::yzxw()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = x;
result.w = w;
return result;
}
// Swizzle for yzxx
Vector4 Vector4::yzxx()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = x;
result.w = x;
return result;
}
// Swizzle for yzxy
Vector4 Vector4::yzxy()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = x;
result.w = y;
return result;
}
// Swizzle for yzxz
Vector4 Vector4::yzxz()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = x;
result.w = z;
return result;
}
// Swizzle for yzyw
Vector4 Vector4::yzyw()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = y;
result.w = w;
return result;
}
// Swizzle for yzyx
Vector4 Vector4::yzyx()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = y;
result.w = x;
return result;
}
// Swizzle for yzyy
Vector4 Vector4::yzyy()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = y;
result.w = y;
return result;
}
// Swizzle for yzyz
Vector4 Vector4::yzyz()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = y;
result.w = z;
return result;
}
// Swizzle for yzzw
Vector4 Vector4::yzzw()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = z;
result.w = w;
return result;
}
// Swizzle for yzzx
Vector4 Vector4::yzzx()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = z;
result.w = x;
return result;
}
// Swizzle for yzzy
Vector4 Vector4::yzzy()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = z;
result.w = y;
return result;
}
// Swizzle for yzzz
Vector4 Vector4::yzzz()
{
Vector4 result;
result.x = y;
result.y = z;
result.z = z;
result.w = z;
return result;
}
// Swizzle for zwww
Vector4 Vector4::zwww()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = w;
result.w = w;
return result;
}
// Swizzle for zwwx
Vector4 Vector4::zwwx()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = w;
result.w = x;
return result;
}
// Swizzle for zwwy
Vector4 Vector4::zwwy()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = w;
result.w = y;
return result;
}
// Swizzle for zwwz
Vector4 Vector4::zwwz()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = w;
result.w = z;
return result;
}
// Swizzle for zwxw
Vector4 Vector4::zwxw()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = x;
result.w = w;
return result;
}
// Swizzle for zwxx
Vector4 Vector4::zwxx()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = x;
result.w = x;
return result;
}
// Swizzle for zwxy
Vector4 Vector4::zwxy()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = x;
result.w = y;
return result;
}
// Swizzle for zwxz
Vector4 Vector4::zwxz()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = x;
result.w = z;
return result;
}
// Swizzle for zwyw
Vector4 Vector4::zwyw()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = y;
result.w = w;
return result;
}
// Swizzle for zwyx
Vector4 Vector4::zwyx()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = y;
result.w = x;
return result;
}
// Swizzle for zwyy
Vector4 Vector4::zwyy()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = y;
result.w = y;
return result;
}
// Swizzle for zwyz
Vector4 Vector4::zwyz()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = y;
result.w = z;
return result;
}
// Swizzle for zwzw
Vector4 Vector4::zwzw()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = z;
result.w = w;
return result;
}
// Swizzle for zwzx
Vector4 Vector4::zwzx()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = z;
result.w = x;
return result;
}
// Swizzle for zwzy
Vector4 Vector4::zwzy()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = z;
result.w = y;
return result;
}
// Swizzle for zwzz
Vector4 Vector4::zwzz()
{
Vector4 result;
result.x = z;
result.y = w;
result.z = z;
result.w = z;
return result;
}
// Swizzle for zxww
Vector4 Vector4::zxww()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = w;
result.w = w;
return result;
}
// Swizzle for zxwx
Vector4 Vector4::zxwx()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = w;
result.w = x;
return result;
}
// Swizzle for zxwy
Vector4 Vector4::zxwy()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = w;
result.w = y;
return result;
}
// Swizzle for zxwz
Vector4 Vector4::zxwz()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = w;
result.w = z;
return result;
}
// Swizzle for zxxw
Vector4 Vector4::zxxw()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = x;
result.w = w;
return result;
}
// Swizzle for zxxx
Vector4 Vector4::zxxx()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = x;
result.w = x;
return result;
}
// Swizzle for zxxy
Vector4 Vector4::zxxy()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = x;
result.w = y;
return result;
}
// Swizzle for zxxz
Vector4 Vector4::zxxz()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = x;
result.w = z;
return result;
}
// Swizzle for zxyw
Vector4 Vector4::zxyw()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = y;
result.w = w;
return result;
}
// Swizzle for zxyx
Vector4 Vector4::zxyx()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = y;
result.w = x;
return result;
}
// Swizzle for zxyy
Vector4 Vector4::zxyy()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = y;
result.w = y;
return result;
}
// Swizzle for zxyz
Vector4 Vector4::zxyz()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = y;
result.w = z;
return result;
}
// Swizzle for zxzw
Vector4 Vector4::zxzw()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = z;
result.w = w;
return result;
}
// Swizzle for zxzx
Vector4 Vector4::zxzx()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = z;
result.w = x;
return result;
}
// Swizzle for zxzy
Vector4 Vector4::zxzy()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = z;
result.w = y;
return result;
}
// Swizzle for zxzz
Vector4 Vector4::zxzz()
{
Vector4 result;
result.x = z;
result.y = x;
result.z = z;
result.w = z;
return result;
}
// Swizzle for zyww
Vector4 Vector4::zyww()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = w;
result.w = w;
return result;
}
// Swizzle for zywx
Vector4 Vector4::zywx()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = w;
result.w = x;
return result;
}
// Swizzle for zywy
Vector4 Vector4::zywy()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = w;
result.w = y;
return result;
}
// Swizzle for zywz
Vector4 Vector4::zywz()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = w;
result.w = z;
return result;
}
// Swizzle for zyxw
Vector4 Vector4::zyxw()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = x;
result.w = w;
return result;
}
// Swizzle for zyxx
Vector4 Vector4::zyxx()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = x;
result.w = x;
return result;
}
// Swizzle for zyxy
Vector4 Vector4::zyxy()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = x;
result.w = y;
return result;
}
// Swizzle for zyxz
Vector4 Vector4::zyxz()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = x;
result.w = z;
return result;
}
// Swizzle for zyyw
Vector4 Vector4::zyyw()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = y;
result.w = w;
return result;
}
// Swizzle for zyyx
Vector4 Vector4::zyyx()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = y;
result.w = x;
return result;
}
// Swizzle for zyyy
Vector4 Vector4::zyyy()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = y;
result.w = y;
return result;
}
// Swizzle for zyyz
Vector4 Vector4::zyyz()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = y;
result.w = z;
return result;
}
// Swizzle for zyzw
Vector4 Vector4::zyzw()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = z;
result.w = w;
return result;
}
// Swizzle for zyzx
Vector4 Vector4::zyzx()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = z;
result.w = x;
return result;
}
// Swizzle for zyzy
Vector4 Vector4::zyzy()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = z;
result.w = y;
return result;
}
// Swizzle for zyzz
Vector4 Vector4::zyzz()
{
Vector4 result;
result.x = z;
result.y = y;
result.z = z;
result.w = z;
return result;
}
// Swizzle for zzww
Vector4 Vector4::zzww()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = w;
result.w = w;
return result;
}
// Swizzle for zzwx
Vector4 Vector4::zzwx()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = w;
result.w = x;
return result;
}
// Swizzle for zzwy
Vector4 Vector4::zzwy()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = w;
result.w = y;
return result;
}
// Swizzle for zzwz
Vector4 Vector4::zzwz()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = w;
result.w = z;
return result;
}
// Swizzle for zzxw
Vector4 Vector4::zzxw()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = x;
result.w = w;
return result;
}
// Swizzle for zzxx
Vector4 Vector4::zzxx()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = x;
result.w = x;
return result;
}
// Swizzle for zzxy
Vector4 Vector4::zzxy()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = x;
result.w = y;
return result;
}
// Swizzle for zzxz
Vector4 Vector4::zzxz()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = x;
result.w = z;
return result;
}
// Swizzle for zzyw
Vector4 Vector4::zzyw()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = y;
result.w = w;
return result;
}
// Swizzle for zzyx
Vector4 Vector4::zzyx()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = y;
result.w = x;
return result;
}
// Swizzle for zzyy
Vector4 Vector4::zzyy()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = y;
result.w = y;
return result;
}
// Swizzle for zzyz
Vector4 Vector4::zzyz()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = y;
result.w = z;
return result;
}
// Swizzle for zzzw
Vector4 Vector4::zzzw()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = z;
result.w = w;
return result;
}
// Swizzle for zzzx
Vector4 Vector4::zzzx()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = z;
result.w = x;
return result;
}
// Swizzle for zzzy
Vector4 Vector4::zzzy()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = z;
result.w = y;
return result;
}
// Swizzle for zzzz
Vector4 Vector4::zzzz()
{
Vector4 result;
result.x = z;
result.y = z;
result.z = z;
result.w = z;
return result;
}
//////////////// SWIZZLE //////////////// | 15.973646 | 106 | 0.559113 | [
"vector"
] |
de3f7e6dd1a9d7b633453e121ca48558aa42aae5 | 773 | cpp | C++ | codes/thread/mutex/owns_lock01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 3 | 2022-01-25T07:33:43.000Z | 2022-03-30T10:25:09.000Z | codes/thread/mutex/owns_lock01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | null | null | null | codes/thread/mutex/owns_lock01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 2 | 2022-01-17T13:39:12.000Z | 2022-03-30T10:25:12.000Z | // unique_lock::operator= example
#include <iostream> // std::cout
#include <vector> // std::vector
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock, std::try_to_lock
std::mutex mtx; // mutex for critical section
void print_star ()
{
std::unique_lock<std::mutex> lck(mtx,std::try_to_lock);
// print '*' if successfully locked, 'x' otherwise:
if ( lck.owns_lock() )
{
std::cout << '*';
}
else
{
std::cout << 'x';
}
}
int main ()
{
std::vector<std::thread> threads;
for ( int i = 0; i < 500; ++ i )
{
threads.emplace_back( print_star );
}
for ( auto& th: threads )
{
th.join();
}
return 0;
} | 20.891892 | 75 | 0.518758 | [
"vector"
] |
de413f613a06e83b052017abd8e6d3c45be54bf1 | 16,812 | cxx | C++ | alg/teca_cartesian_mesh_regrid.cxx | Data-Scientist-Wannabe/TECA | feb0ae7eb23e031842ca958b85168f7fdcae7f06 | [
"BSD-3-Clause-LBNL"
] | null | null | null | alg/teca_cartesian_mesh_regrid.cxx | Data-Scientist-Wannabe/TECA | feb0ae7eb23e031842ca958b85168f7fdcae7f06 | [
"BSD-3-Clause-LBNL"
] | null | null | null | alg/teca_cartesian_mesh_regrid.cxx | Data-Scientist-Wannabe/TECA | feb0ae7eb23e031842ca958b85168f7fdcae7f06 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "teca_cartesian_mesh_regrid.h"
#include "teca_cartesian_mesh.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"
#include "teca_coordinate_util.h"
#include <algorithm>
#include <iostream>
#if defined(TECA_HAS_BOOST)
#include <boost/program_options.hpp>
#endif
using std::cerr;
using std::endl;
//#define TECA_DEBUG
template<typename NT1, typename NT2, typename NT3, class interp_t>
int interpolate(unsigned long target_nx, unsigned long target_ny,
unsigned long target_nz, const NT1 *p_target_xc, const NT1 *p_target_yc,
const NT1 *p_target_zc, NT3 *p_target_a, const NT2 *p_source_xc,
const NT2 *p_source_yc, const NT2 *p_source_zc, const NT3 *p_source_a,
unsigned long source_ihi, unsigned long source_jhi, unsigned long source_khi,
unsigned long source_nx, unsigned long source_nxy)
{
interp_t f;
unsigned long q = 0;
for (unsigned long k = 0; k < target_nz; ++k)
{
NT2 tz = static_cast<NT2>(p_target_zc[k]);
for (unsigned long j = 0; j < target_ny; ++j)
{
NT2 ty = static_cast<NT2>(p_target_yc[j]);
for (unsigned long i = 0; i < target_nx; ++i, ++q)
{
NT2 tx = static_cast<NT2>(p_target_xc[i]);
if (f(tx,ty,tz,
p_source_xc, p_source_yc, p_source_zc,
p_source_a, source_ihi, source_jhi, source_khi,
source_nx, source_nxy,
p_target_a[q]))
{
TECA_ERROR("failed to interpolate i=(" << i << ", " << j << ", " << k
<< ") x=(" << tx << ", " << ty << ", " << tz << ")")
return -1;
}
}
}
}
return 0;
}
template<typename taget_coord_t, typename source_coord_t, typename array_t>
int interpolate(int mode, unsigned long target_nx, unsigned long target_ny,
unsigned long target_nz, const taget_coord_t *p_target_xc, const taget_coord_t *p_target_yc,
const taget_coord_t *p_target_zc, array_t *p_target_a, const source_coord_t *p_source_xc,
const source_coord_t *p_source_yc, const source_coord_t *p_source_zc, const array_t *p_source_a,
unsigned long source_ihi, unsigned long source_jhi, unsigned long source_khi,
unsigned long source_nx, unsigned long source_nxy)
{
using nearest_interp_t = teca_coordinate_util::interpolate_t<0>;
using linear_interp_t = teca_coordinate_util::interpolate_t<1>;
switch (mode)
{
case teca_cartesian_mesh_regrid::nearest:
return interpolate<taget_coord_t,source_coord_t,array_t,nearest_interp_t>(
target_nx, target_ny, target_nz, p_target_xc, p_target_yc, p_target_zc,
p_target_a, p_source_xc, p_source_yc, p_source_zc, p_source_a,
source_ihi, source_jhi, source_khi, source_nx, source_nxy);
break;
case teca_cartesian_mesh_regrid::linear:
return interpolate<taget_coord_t,source_coord_t,array_t,linear_interp_t>(
target_nx, target_ny, target_nz, p_target_xc, p_target_yc, p_target_zc,
p_target_a, p_source_xc, p_source_yc, p_source_zc, p_source_a,
source_ihi, source_jhi, source_khi, source_nx, source_nxy);
break;
}
TECA_ERROR("invalid interpolation mode \"" << mode << "\"")
return -1;
}
// --------------------------------------------------------------------------
teca_cartesian_mesh_regrid::teca_cartesian_mesh_regrid()
: target_input(0), interpolation_mode(nearest)
{
this->set_number_of_input_connections(2);
this->set_number_of_output_ports(1);
}
// --------------------------------------------------------------------------
teca_cartesian_mesh_regrid::~teca_cartesian_mesh_regrid()
{}
#if defined(TECA_HAS_BOOST)
// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::get_properties_description(
const std::string &prefix, options_description &global_opts)
{
options_description opts("Options for "
+ (prefix.empty()?"teca_cartesian_mesh_regrid":prefix));
opts.add_options()
TECA_POPTS_GET(int, prefix, target_input,
"select input connection that contains metadata (0)")
TECA_POPTS_GET(std::vector<std::string>, prefix, arrays,
"list of arrays to move from source to target mesh ("")")
TECA_POPTS_GET(int, prefix, interpolation_mode,
"linear or nearest interpolation (1)")
;
global_opts.add(opts);
}
// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::set_properties(
const std::string &prefix, variables_map &opts)
{
TECA_POPTS_SET(opts, int, prefix, target_input)
TECA_POPTS_SET(opts, std::vector<std::string>, prefix, arrays)
TECA_POPTS_SET(opts, int, prefix, interpolation_mode)
}
#endif
// --------------------------------------------------------------------------
teca_metadata teca_cartesian_mesh_regrid::get_output_metadata(
unsigned int port, const std::vector<teca_metadata> &input_md)
{
#ifdef TECA_DEBUG
cerr << teca_parallel_id()
<< "teca_cf_reader::get_output_metadata" << endl;
#endif
(void)port;
int md_src = this->target_input ? 0 : 1;
int md_tgt = this->target_input ? 1 : 0;
// start with a copy of metadata from the target
teca_metadata output_md(input_md[md_tgt]);
// get target metadata
std::vector<std::string> target_vars;
input_md[md_tgt].get("variables", target_vars);
std::vector<std::string> target_time_vars;
input_md[md_tgt].get("time variables", target_time_vars);
teca_metadata target_atts;
input_md[md_tgt].get("attributes", target_atts);
// get source metadata
std::vector<std::string> source_vars;
input_md[md_src].get("variables", source_vars);
std::vector<std::string> source_time_vars;
input_md[md_src].get("time variables", source_time_vars);
teca_metadata source_atts;
input_md[md_src].get("attributes", source_atts);
// merge metadata from source and target
// variables and time variables should be unique lists.
// attributes are indexed by variable names
// in the case of collisions, the target variable
// is kept, the source variable is ignored
size_t n_source_vars = source_vars.size();
for (size_t i = 0; i < n_source_vars; ++i)
{
const std::string &source = source_vars[i];
// check that there's not a variable of that same name in target
std::vector<std::string>::iterator first = target_vars.begin();
std::vector<std::string>::iterator last = target_vars.end();
if (find(first, last, source) == last)
{
// not present in target, ok to add it
target_vars.push_back(source);
teca_metadata atts;
source_atts.get(source, atts);
target_atts.set(source, atts);
// check if it's a time var as well
first = source_time_vars.begin();
last = source_time_vars.end();
if (find(first, last, source) != last)
target_time_vars.push_back(source);
}
}
// update with merged lists
output_md.set("variables", target_vars);
output_md.set("time variables", target_time_vars);
output_md.set("attributes", target_atts);
return output_md;
}
// --------------------------------------------------------------------------
std::vector<teca_metadata> teca_cartesian_mesh_regrid::get_upstream_request(
unsigned int port, const std::vector<teca_metadata> &input_md,
const teca_metadata &request)
{
(void)port;
std::vector<teca_metadata> up_reqs(2);
// route requests for arrays to either target or the source.
// if the array exists in both then it is take from the target
teca_metadata target_req(request);
teca_metadata source_req(request);
// get target metadata
int md_tgt = this->target_input ? 1 : 0;
std::vector<std::string> target_vars;
input_md[md_tgt].get("variables", target_vars);
std::vector<std::string>::iterator tgt_0 = target_vars.begin();
std::vector<std::string>::iterator tgt_1 = target_vars.end();
// get source metadata
int md_src = this->target_input ? 0 : 1;
std::vector<std::string> source_vars;
input_md[md_src].get("variables", source_vars);
std::vector<std::string>::iterator src_0 = source_vars.begin();
std::vector<std::string>::iterator src_1 = source_vars.end();
// get the requested arrays
std::vector<std::string> req_arrays;
request.get("arrays", req_arrays);
// add any explicitly named
std::copy(this->arrays.begin(), this->arrays.end(),
std::back_inserter(req_arrays));
// route. if found in the target then routed there, else
// if found in the source routed there, else skipped
std::vector<std::string> target_arrays;
std::vector<std::string> source_arrays;
std::vector<std::string>::iterator it = req_arrays.begin();
std::vector<std::string>::iterator end = req_arrays.end();
for (; it != end; ++it)
{
if (find(tgt_0, tgt_1, *it) != tgt_1)
target_arrays.push_back(*it);
else if (find(src_0, src_1, *it) != src_1)
source_arrays.push_back(*it);
else
TECA_ERROR("\"" << *it << "\" was not in target nor source")
}
target_req.set("arrays", target_arrays);
source_req.set("arrays", source_arrays);
// get the target extent and coordinates
teca_metadata target_coords;
p_teca_variant_array target_x, target_y, target_z;
if (input_md[md_tgt].get("coordinates", target_coords)
|| !(target_x = target_coords.get("x"))
|| !(target_y = target_coords.get("y"))
|| !(target_z = target_coords.get("z")))
{
TECA_ERROR("failed to locate target mesh coordinates")
return up_reqs;
}
// get the actual bounds of what we will be served with. this will be a
// region covering the requested bounds. we need to insure that source data
// covers this region, not just the requested bounds.
double request_bounds[6] = {0.0};
unsigned long target_extent[6] = {0l};
if (request.get("bounds", request_bounds, 6))
{
if (request.get("extent", target_extent, 6))
{
TECA_ERROR("neither \"bounds\" nor \"extent\" has been requested")
return up_reqs;
}
}
else
{
if (teca_coordinate_util::bounds_to_extent(request_bounds,
target_x, target_y, target_z, target_extent))
{
TECA_ERROR("invalid bounds requested [" << request_bounds[0] << ", "
<< request_bounds[1] << ", " << request_bounds[2] << ", "
<< request_bounds[3] << ", " << request_bounds[4] << ", "
<< request_bounds[5] << "]")
return up_reqs;
}
}
double target_bounds[6] = {0.0};
target_x->get(target_extent[0], target_bounds[0]);
target_x->get(target_extent[1], target_bounds[1]);
target_y->get(target_extent[2], target_bounds[2]);
target_y->get(target_extent[3], target_bounds[3]);
target_z->get(target_extent[4], target_bounds[4]);
target_z->get(target_extent[5], target_bounds[5]);
// send the target bounds to the source as well
source_req.set("bounds", target_bounds, 6);
// send the requests up
up_reqs[md_tgt] = target_req;
up_reqs[md_src] = source_req;
return up_reqs;
}
// --------------------------------------------------------------------------
const_p_teca_dataset teca_cartesian_mesh_regrid::execute(
unsigned int port, const std::vector<const_p_teca_dataset> &input_data,
const teca_metadata &request)
{
#ifdef TECA_DEBUG
cerr << teca_parallel_id()
<< "teca_cartesian_mesh_regrid::execute" << endl;
#endif
(void)port;
int md_src = this->target_input ? 0 : 1;
int md_tgt = this->target_input ? 1 : 0;
p_teca_cartesian_mesh in_target
= std::dynamic_pointer_cast<teca_cartesian_mesh>(
std::const_pointer_cast<teca_dataset>(input_data[md_tgt]));
const_p_teca_cartesian_mesh source
= std::dynamic_pointer_cast<const teca_cartesian_mesh>(
input_data[md_src]);
if (!in_target || !source)
{
TECA_ERROR("invalid input. target invalid "
<< !in_target << " source invalid " << !source )
return nullptr;
}
// create the output
p_teca_cartesian_mesh target = teca_cartesian_mesh::New();
target->shallow_copy(in_target);
// get the source and targent extents
std::vector<unsigned long> source_ext;
source->get_extent(source_ext);
std::vector<unsigned long> target_ext;
target->get_extent(target_ext);
// get the list of arrays to move
std::vector<std::string> req_arrays;
request.get("regrid_arrays", req_arrays);
// add any explicitly named
std::copy(this->arrays.begin(), this->arrays.end(),
std::back_inserter(req_arrays));
// route. if found in the target then routed there, else
// if found in the source routed there, else skipped
std::vector<std::string> source_arrays;
std::vector<std::string>::iterator it = req_arrays.begin();
std::vector<std::string>::iterator end = req_arrays.end();
for (; it != end; ++it)
{
if (!target->get_point_arrays()->has(*it))
source_arrays.push_back(*it);
}
// move the arrays
const_p_teca_variant_array target_xc = target->get_x_coordinates();
const_p_teca_variant_array target_yc = target->get_y_coordinates();
const_p_teca_variant_array target_zc = target->get_z_coordinates();
p_teca_array_collection target_ac = target->get_point_arrays();
unsigned long target_nx = target_xc->size();
unsigned long target_ny = target_yc->size();
unsigned long target_nz = target_zc->size();
unsigned long target_size = target_nx*target_ny*target_nz;
const_p_teca_variant_array source_xc = source->get_x_coordinates();
const_p_teca_variant_array source_yc = source->get_y_coordinates();
const_p_teca_variant_array source_zc = source->get_z_coordinates();
const_p_teca_array_collection source_ac = source->get_point_arrays();
unsigned long source_nx = source_xc->size();
unsigned long source_ny = source_yc->size();
unsigned long source_nz = source_zc->size();
unsigned long source_nxy = source_nx*source_ny;
unsigned long source_ihi = source_nx - 1;
unsigned long source_jhi = source_ny - 1;
unsigned long source_khi = source_nz - 1;
NESTED_TEMPLATE_DISPATCH_FP(
const teca_variant_array_impl,
target_xc.get(),
1,
const NT1 *p_target_xc = std::dynamic_pointer_cast<TT1>(target_xc)->get();
const NT1 *p_target_yc = std::dynamic_pointer_cast<TT1>(target_yc)->get();
const NT1 *p_target_zc = std::dynamic_pointer_cast<TT1>(target_zc)->get();
NESTED_TEMPLATE_DISPATCH_FP(
const teca_variant_array_impl,
source_xc.get(),
2,
const NT2 *p_source_xc = std::dynamic_pointer_cast<TT2>(source_xc)->get();
const NT2 *p_source_yc = std::dynamic_pointer_cast<TT2>(source_yc)->get();
const NT2 *p_source_zc = std::dynamic_pointer_cast<TT2>(source_zc)->get();
size_t n_arrays = source_arrays.size();
for (size_t i = 0; i < n_arrays; ++i)
{
const_p_teca_variant_array source_a = source_ac->get(source_arrays[i]);
p_teca_variant_array target_a = source_a->new_instance();
target_a->resize(target_size);
NESTED_TEMPLATE_DISPATCH(
teca_variant_array_impl,
target_a.get(),
3,
const NT3 *p_source_a = std::static_pointer_cast<const TT3>(source_a)->get();
NT3 *p_target_a = std::static_pointer_cast<TT3>(target_a)->get();
if (interpolate(this->interpolation_mode, target_nx, target_ny, target_nz,
p_target_xc, p_target_yc, p_target_zc, p_target_a, p_source_xc,
p_source_yc, p_source_zc, p_source_a, source_ihi, source_jhi,
source_khi, source_nx, source_nxy))
{
TECA_ERROR("Failed to move \"" << source_arrays[i] << "\"")
return nullptr;
}
target_ac->set(source_arrays[i], target_a);
)
}
)
)
return target;
}
| 36.949451 | 100 | 0.62616 | [
"mesh",
"vector"
] |
de47ce3d55e71af157a7c9684380acd2fb360db0 | 47,039 | cpp | C++ | src/coreTest/UMACoreTestFixture.cpp | kotmasha/kodlab-uma-encapsulated | cb812f07906c62d958041d41d58623fd99fdb8ac | [
"MIT"
] | null | null | null | src/coreTest/UMACoreTestFixture.cpp | kotmasha/kodlab-uma-encapsulated | cb812f07906c62d958041d41d58623fd99fdb8ac | [
"MIT"
] | 1 | 2019-11-16T02:57:35.000Z | 2019-11-16T02:57:35.000Z | src/coreTest/UMACoreTestFixture.cpp | kotmasha/kodlab-uma-encapsulated | cb812f07906c62d958041d41d58623fd99fdb8ac | [
"MIT"
] | 1 | 2021-08-02T21:14:54.000Z | 2021-08-02T21:14:54.000Z | #include "UMACoreTestFixture.h"
#include "PropertyMap.h"
#include "UMAutil.h"
extern int ind(int row, int col);
extern int compi(int x);
WorldTestFixture::WorldTestFixture() {}
WorldTestFixture::~WorldTestFixture() {}
SnapshotUpdateQTestFixture::SnapshotUpdateQTestFixture() {
agentStationary = new Agent("agentStationary", nullptr);
snapshotStationary = agentStationary->createSnapshot("snapshotStationary");
snapshotStationary->_ppm->add("q", "1");
agentQualitative = new AgentQualitative("agentQualitative", nullptr);
snapshotQualitative = agentQualitative->createSnapshot("snapshotQualitative");
snapshotQualitative->_ppm->add("q", "2");
agentDiscounted = new AgentDiscounted("agentDiscounted", nullptr);
snapshotDiscounted = agentDiscounted->createSnapshot("snapshotDiscounted");
snapshotDiscounted->_ppm->add("q", "3");
agentEmpirical = new AgentEmpirical("agentEmpirical", nullptr);
snapshotEmpirical = agentEmpirical->createSnapshot("snapshotEmpirical");
}
SnapshotUpdateQTestFixture::~SnapshotUpdateQTestFixture() {
delete agentStationary, agentQualitative, agentDiscounted, agentEmpirical;
}
void SnapshotUpdateQTestFixture::testUpdateQ() {
EXPECT_EQ(0, snapshotStationary->getQ());// value of q is hard-coded to be 0
snapshotStationary->updateQ();
EXPECT_EQ(1, snapshotStationary->getQ());
EXPECT_EQ(0, snapshotQualitative->getQ());
snapshotQualitative->updateQ();
EXPECT_EQ(0, snapshotQualitative->getQ());
EXPECT_EQ(0, snapshotDiscounted->getQ());
snapshotDiscounted->updateQ();
EXPECT_EQ(3, snapshotDiscounted->getQ());
EXPECT_EQ(0, snapshotEmpirical->getQ());
snapshotEmpirical->setQ(1.5);
snapshotEmpirical->updateQ();
EXPECT_EQ(2, snapshotEmpirical->getQ());
}
AmperAndTestFixture::AmperAndTestFixture(){
agent = new Agent("agent", nullptr);
snapshot = agent->createSnapshot("snapshot");
snapshot->setTotal(1);
snapshot->setOldTotal(1);
vector<vector<double>> w0 = { { 0.2, 0.0, 0.0, 0.8 } };
vector<vector<double>> w1 = { { 0.2, 0.2, 0.0, 0.6 },{ 0.4, 0.0, 0.0, 0.6 } };
vector<vector<double>> w2 = { { 0.2, 0.4, 0.0, 0.4 },{ 0.4, 0.2, 0.0, 0.4 },{ 0.6, 0.0, 0.0, 0.4 } };
vector<vector<double>> w3 = { { 0.2, 0.6, 0.0, 0.2 },{ 0.4, 0.4, 0.0, 0.2 },{ 0.6, 0.2, 0.0, 0.2 },{ 0.8, 0.0, 0.0, 0.2 } };
vector<vector<bool>> b0 = { { true, false, false, true } };
vector<vector<bool>> b1 = { { false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b2 = { { false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b3 = { { false, false, false, false },{ false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
std::pair<string, string> p0 = { "s0", "cs0" };
std::pair<string, string> p1 = { "s1", "cs1" };
std::pair<string, string> p2 = { "s2", "cs2" };
std::pair<string, string> p3 = { "s3", "cs3" };
vector<double> diag;
snapshot->createSensor(p0, diag, w0, b0);
snapshot->createSensor(p1, diag, w1, b1);
snapshot->createSensor(p2, diag, w2, b2);
snapshot->createSensor(p3, diag, w3, b3);
}
AmperAndTestFixture::~AmperAndTestFixture() {
delete agent;
}
vector<vector<double>> AmperAndTestFixture::testAmperAnd(int mid1, int mid2, bool merge, std::pair<string, string> &p) {
snapshot->ampersand(mid1, mid2, merge, p);
vector<vector<double>> w;
for (int i = 0; i < 2 * snapshot->_sensors.size(); ++i) {
vector<double> tmp;
for (int j = 0; j <= i; ++j) {
AttrSensorPair *asp = snapshot->getAttrSensorPair(i, j);
tmp.push_back(asp->_vw);
}
w.push_back(tmp);
}
return w;
}
GenerateDelayedWeightsTestFixture::GenerateDelayedWeightsTestFixture() {
agent = new Agent("agent", nullptr);
snapshot = agent->createSnapshot("snapshot");
agentQualitative = new AgentQualitative("agentQualitative", nullptr);
snapshotQualitative = agentQualitative->createSnapshot("snapshotQualitative");
vector<vector<double>> w0 = { { 0.2, 0.0, 0.0, 0.8 } };
vector<vector<double>> w1 = { { 0.2, 0.2, 0.0, 0.6 },{ 0.4, 0.0, 0.0, 0.6 } };
vector<vector<double>> w2 = { { 0.2, 0.4, 0.0, 0.4 },{ 0.4, 0.2, 0.0, 0.4 },{ 0.6, 0.0, 0.0, 0.4 } };
vector<vector<double>> w3 = { { 0.2, 0.6, 0.0, 0.2 },{ 0.4, 0.4, 0.0, 0.2 },{ 0.6, 0.2, 0.0, 0.2 },{ 0.8, 0.0, 0.0, 0.2 } };
vector<vector<bool>> b0 = { { true, false, false, true } };
vector<vector<bool>> b1 = { { false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b2 = { { false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b3 = { { false, false, false, false },{ false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
std::pair<string, string> p0 = { "s0", "cs0" };
std::pair<string, string> p1 = { "s1", "cs1" };
std::pair<string, string> p2 = { "s2", "cs2" };
std::pair<string, string> p3 = { "s3", "cs3" };
vector<double> diag;
Sensor *s0 = snapshot->createSensor(p0, diag, w0, b0);
Sensor *s1 = snapshot->createSensor(p1, diag, w1, b1);
Sensor *s2 = snapshot->createSensor(p2, diag, w2, b2);
Sensor *s3 = snapshot->createSensor(p3, diag, w3, b3);
snapshot->getAttrSensor(0)->_vdiag = 0.2;
snapshot->getAttrSensor(1)->_vdiag = 0.8;
snapshot->getAttrSensor(2)->_vdiag = 0.4;
snapshot->getAttrSensor(3)->_vdiag = 0.6;
snapshot->getAttrSensor(4)->_vdiag = 0.6;
snapshot->getAttrSensor(5)->_vdiag = 0.4;
snapshot->getAttrSensor(6)->_vdiag = 0.8;
snapshot->getAttrSensor(7)->_vdiag = 0.2;
snapshotQualitative->createSensor(p0, diag, w0, b0);
snapshotQualitative->createSensor(p1, diag, w1, b1);
snapshotQualitative->createSensor(p2, diag, w2, b2);
snapshotQualitative->createSensor(p3, diag, w3, b3);
snapshotQualitative->getAttrSensor(0)->_vdiag = -1;
snapshotQualitative->getAttrSensor(1)->_vdiag = -1;
snapshotQualitative->getAttrSensor(2)->_vdiag = -1;
snapshotQualitative->getAttrSensor(3)->_vdiag = -1;
snapshotQualitative->getAttrSensor(4)->_vdiag = -1;
snapshotQualitative->getAttrSensor(5)->_vdiag = -1;
snapshotQualitative->getAttrSensor(6)->_vdiag = -1;
snapshotQualitative->getAttrSensor(7)->_vdiag = -1;
}
GenerateDelayedWeightsTestFixture::~GenerateDelayedWeightsTestFixture() {
delete agent, agentQualitative;
}
vector<vector<double>> GenerateDelayedWeightsTestFixture::testGenerateDelayedWeights(int mid, bool merge, const std::pair<string, string> &idPair
, vector<bool> &observe, UMA_AGENT type) {
for (int i = 0; i < 2 * snapshot->_sensors.size(); ++i) {
*(snapshot->getAttrSensor(i)->_observe) = observe[i];
*(snapshot->getAttrSensor(i)->_observe_) = observe[i];
}
Snapshot *currentSnapshot = nullptr;
if (UMA_AGENT::AGENT_QUALITATIVE == type) {
currentSnapshot = snapshotQualitative;
}
else {
currentSnapshot = snapshot;
}
currentSnapshot->generateDelayedWeights(mid, merge, idPair);
vector<vector<double>> w;
for (int i = 0; i < 2 * currentSnapshot->_sensors.size(); ++i) {
vector<double> tmp;
for (int j = 0; j <= i; ++j) {
AttrSensorPair *asp = currentSnapshot->getAttrSensorPair(i, j);
tmp.push_back(asp->_vw);
}
w.push_back(tmp);
}
return w;
}
AmperTestFixture::AmperTestFixture() {
agent = new Agent("agent", nullptr);
snapshot = agent->createSnapshot("snapshot");
snapshot->setTotal(1);
snapshot->setOldTotal(1);
vector<vector<double>> w0 = { { 0.2, 0.0, 0.0, 0.8 } };
vector<vector<double>> w1 = { { 0.2, 0.2, 0.0, 0.6 },{ 0.4, 0.0, 0.0, 0.6 } };
vector<vector<double>> w2 = { { 0.2, 0.4, 0.0, 0.4 },{ 0.4, 0.2, 0.0, 0.4 },{ 0.6, 0.0, 0.0, 0.4 } };
vector<vector<double>> w3 = { { 0.2, 0.6, 0.0, 0.2 },{ 0.4, 0.4, 0.0, 0.2 },{ 0.6, 0.2, 0.0, 0.2 },{ 0.8, 0.0, 0.0, 0.2 } };
vector<vector<bool>> b0 = { { true, false, false, true } };
vector<vector<bool>> b1 = { { false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b2 = { { false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
vector<vector<bool>> b3 = { { false, false, false, false },{ false, false, false, false },{ false, false, false, false },{ true, false, false, true } };
std::pair<string, string> p0 = { "s0", "cs0" };
std::pair<string, string> p1 = { "s1", "cs1" };
std::pair<string, string> p2 = { "s2", "cs2" };
std::pair<string, string> p3 = { "s3", "cs3" };
vector<double> diag;
snapshot->createSensor(p0, diag, w0, b0);
snapshot->createSensor(p1, diag, w1, b1);
snapshot->createSensor(p2, diag, w2, b2);
snapshot->createSensor(p3, diag, w3, b3);
}
AmperTestFixture::~AmperTestFixture() {
delete agent;
}
vector<vector<double>> AmperTestFixture::testAmper(const vector<int> &list, const std::pair<string, string> &uuid) {
snapshot->amper(list, uuid);
vector<vector<double>> w;
for (int i = 0; i < 2 * snapshot->_sensors.size(); ++i) {
vector<double> tmp;
for (int j = 0; j <= i; ++j) {
AttrSensorPair *asp = snapshot->getAttrSensorPair(i, j);
tmp.push_back(asp->_vw);
}
w.push_back(tmp);
}
return w;
}
UMACoreDataFlowTestFixture::UMACoreDataFlowTestFixture() {
dm = new DataManager(nullptr);
std::pair<string, string> sensor1 = { "s1", "cs1" };
std::pair<string, string> sensor2 = { "s2", "cs2" };
std::pair<string, string> sensor3 = { "s3", "cs3" };
std::pair<string, string> sensor4 = { "s4", "cs4" };
vector<double> d1 = { 0.2, 0.8 };
vector<vector<double>> w1, w3;
vector<vector<double>> w0 = { { 0.2, 0.8, 0.457, 0.543 } };
vector<vector<double>> w2 = { { 0.2, 0.8, 0.4, 0.6 },{ 0.1, 0.9, 0, 1 },{ 0.3, 0.7, 0.8, 0.2 } };
vector<vector<bool>> b1, b3;
vector<vector<bool>> b0 = { { true, false, true, false } };
vector<vector<bool>> b2 = { { true, false, false, true },{ false, false, false, false },{ true, true, true, true } };
weights = { 0.2, 0.457, 0.543, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.2, 0.8, 0.1, 0.9, 0.3, 0.4, 0.6,
0.0, 1.0, 0.8, 0.2, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 };
thresholds = { 0.125, 0.25, 0.25, 0.125, 0.125, 0.125, 0.5, 0.5, 0.5, 0.5 };
observe = { true, false, false, true, false, true, true, false };
dirs = { 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 };
diag = { 0.5, 0.5, 0.2, 0.8, 0.5, 0.5, 0.5, 0.5 };
sensors.push_back(new Sensor(sensor1, nullptr, 1.0, 0));
sensors.push_back(new Sensor(sensor2, nullptr, d1, 1));
sensors.push_back(new Sensor(sensor3, nullptr, 1.0, 2));
sensors.push_back(new Sensor(sensor4, nullptr, 1.0, 3));
sensorPairs.push_back(new SensorPair(nullptr, sensors[0], sensors[0], 0.125, w0[0], b0[0]));
sensorPairs.push_back(new SensorPair(nullptr, sensors[1], sensors[0], 0.25, 1.0));
sensorPairs.push_back(new SensorPair(nullptr, sensors[1], sensors[1], 0.25, 1.0));
sensorPairs.push_back(new SensorPair(nullptr, sensors[2], sensors[0], 0.125, w2[0], b2[0]));
sensorPairs.push_back(new SensorPair(nullptr, sensors[2], sensors[1], 0.125, w2[1], b2[1]));
sensorPairs.push_back(new SensorPair(nullptr, sensors[2], sensors[2], 0.125, w2[2], b2[2]));
sensorPairs.push_back(new SensorPair(nullptr, sensors[3], sensors[0], 0.5, 1.0));
sensorPairs.push_back(new SensorPair(nullptr, sensors[3], sensors[1], 0.5, 1.0));
sensorPairs.push_back(new SensorPair(nullptr, sensors[3], sensors[2], 0.5, 1.0));
sensorPairs.push_back(new SensorPair(nullptr, sensors[3], sensors[3], 0.5, 1.0));
sensors[0]->_m->_vobserve = true; sensors[0]->_m->_vobserve_ = true;
sensors[0]->_cm->_vobserve = false; sensors[0]->_cm->_vobserve_ = false;
sensors[1]->_m->_vobserve = false; sensors[1]->_m->_vobserve_ = false;
sensors[1]->_cm->_vobserve = true; sensors[1]->_cm->_vobserve_ = true;
sensors[2]->_m->_vobserve = false; sensors[2]->_m->_vobserve_ = false;
sensors[2]->_cm->_vobserve = true; sensors[2]->_cm->_vobserve_ = true;
sensors[3]->_m->_vobserve = true; sensors[3]->_m->_vobserve_ = true;
sensors[3]->_cm->_vobserve = false; sensors[3]->_cm->_vobserve_ = false;
double total = 1.0;
dm->reallocateMemory(total, 4);
}
UMACoreDataFlowTestFixture::~UMACoreDataFlowTestFixture(){
delete dm;
for (int i = 0; i < sensors.size(); ++i) {
delete sensors[i];
sensors[i] = NULL;
}
for (int i = 0; i < sensorPairs.size(); ++i) {
delete sensorPairs[i];
sensorPairs[i] = NULL;
}
}
void UMACoreDataFlowTestFixture::testUmaCoreDataFlow(int startIdx, int endIdx) {
dm->createSensorsToArraysIndex(startIdx, endIdx, sensors);
dm->createSensorPairsToArraysIndex(startIdx, endIdx, sensorPairs);
for (int i = startIdx; i < endIdx; ++i) {
EXPECT_EQ(sensors[i]->_m->_diag, dm->h_diag + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_diag, dm->h_diag + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_diag_, dm->h_diag_ + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_diag_, dm->h_diag_ + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_observe, dm->h_observe + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_observe, dm->h_observe + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_observe_, dm->h_observe_ + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_observe_, dm->h_observe_ + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_current, dm->h_current + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_current, dm->h_current + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_target, dm->h_target + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_target, dm->h_target + 2 * i + 1);
EXPECT_EQ(sensors[i]->_m->_prediction, dm->h_prediction + 2 * i);
EXPECT_EQ(sensors[i]->_cm->_prediction, dm->h_prediction + 2 * i + 1);
}
for (int i = ind(startIdx, 0); i < ind(endIdx, 0); ++i) {
int idxI = 2 * sensorPairs[i]->_sensor_i->_idx;
int idxJ = 2 * sensorPairs[i]->_sensor_j->_idx;
EXPECT_EQ(sensorPairs[i]->mij->_w, dm->h_weights + ind(idxI, idxJ));
EXPECT_EQ(sensorPairs[i]->mi_j->_w, dm->h_weights + ind(idxI, idxJ + 1));
EXPECT_EQ(sensorPairs[i]->m_ij->_w, dm->h_weights + ind(idxI + 1, idxJ));
EXPECT_EQ(sensorPairs[i]->m_i_j->_w, dm->h_weights + ind(idxI + 1, idxJ + 1));
EXPECT_EQ(sensorPairs[i]->mij->_d, dm->h_dirs + ind(idxI, idxJ));
EXPECT_EQ(sensorPairs[i]->mi_j->_d, dm->h_dirs + ind(idxI, idxJ + 1));
EXPECT_EQ(sensorPairs[i]->m_ij->_d, dm->h_dirs + ind(idxI + 1, idxJ));
EXPECT_EQ(sensorPairs[i]->m_i_j->_d, dm->h_dirs + ind(idxI + 1, idxJ + 1));
EXPECT_EQ(sensorPairs[i]->_threshold, dm->h_thresholds + ind(idxI / 2, idxJ / 2));
}
dm->copySensorsToArrays(startIdx, endIdx, sensors);
dm->copySensorPairsToArrays(startIdx, endIdx, sensorPairs);
dm->copyArraysToSensors(startIdx, endIdx, sensors);
dm->copyArraysToSensorPairs(startIdx, endIdx, sensorPairs);
for (int i = startIdx; i < endIdx; ++i) {
EXPECT_EQ(diag[2 * i], sensors[i]->_m->_vdiag);
EXPECT_EQ(diag[2 * i + 1], sensors[i]->_cm->_vdiag);
EXPECT_EQ(diag[2 * i], sensors[i]->_m->_vdiag_);
EXPECT_EQ(diag[2 * i + 1], sensors[i]->_cm->_vdiag_);
EXPECT_EQ(observe[2 * i], sensors[i]->_m->_vobserve);
EXPECT_EQ(observe[2 * i], sensors[i]->_m->_vobserve_);
EXPECT_EQ(observe[2 * i + 1], sensors[i]->_cm->_vobserve);
EXPECT_EQ(observe[2 * i + 1], sensors[i]->_cm->_vobserve_);
}
for (int i = ind(startIdx, 0); i < ind(endIdx, 0); ++i) {
int idxI = 2 * sensorPairs[i]->_sensor_i->_idx;
int idxJ = 2 * sensorPairs[i]->_sensor_j->_idx;
EXPECT_DOUBLE_EQ(weights[ind(idxI, idxJ)], sensorPairs[i]->mij->_vw);
EXPECT_DOUBLE_EQ(weights[ind(idxI, idxJ + 1)], sensorPairs[i]->mi_j->_vw);
EXPECT_DOUBLE_EQ(weights[ind(idxI + 1, idxJ)], sensorPairs[i]->m_ij->_vw);
EXPECT_DOUBLE_EQ(weights[ind(idxI + 1, idxJ + 1)], sensorPairs[i]->m_i_j->_vw);
EXPECT_EQ(dirs[ind(idxI, idxJ)], sensorPairs[i]->mij->_vd);
EXPECT_EQ(dirs[ind(idxI, idxJ + 1)], sensorPairs[i]->mi_j->_vd);
EXPECT_EQ(dirs[ind(idxI + 1, idxJ)], sensorPairs[i]->m_ij->_vd);
EXPECT_EQ(dirs[ind(idxI + 1, idxJ + 1)], sensorPairs[i]->m_i_j->_vd);
EXPECT_DOUBLE_EQ(thresholds[ind(idxI / 2, idxJ / 2)], sensorPairs[i]->_vthreshold);
}
}
SensorValuePointerConvertionTestFixture::SensorValuePointerConvertionTestFixture() {
pair<string, string> p1 = { "s1", "cs1" };
pair<string, string> p2 = { "s2", "cs2" };
pair<string, string> p3 = { "s3", "cs3" };
pair<string, string> p4 = { "s4", "cs4" };
s1 = new Sensor(p1, nullptr, 1.0, 0);
s2 = new Sensor(p2, nullptr, 1.0, 1);
s3 = new Sensor(p3, nullptr, 1.0, 2);
s4 = new Sensor(p4, nullptr, 1.0, 3);
s = { s1, s2, s3, s4 };
h_diag = new double[8];
h_diag_ = new double[8];
h_observe = new bool[8];
h_observe_ = new bool[8];
h_current = new bool[8];
h_current_ = new bool[8];
h_target = new bool[8];
h_prediction = new bool[8];
for (int i = 0; i < 8; ++i) {
h_diag[i] = i * 0.1;
h_diag_[i] = i * 0.2;
h_observe[i] = i % 2;
h_observe_[i] = i % 2;
h_current[i] = i % 2;
h_current_[i] = i % 2;
h_target[i] = !i % 2;
h_prediction[i] = !i % 2;
}
}
SensorValuePointerConvertionTestFixture::~SensorValuePointerConvertionTestFixture() {
delete h_diag, h_diag_, h_observe, h_observe_, h_current, h_current_, h_target, h_prediction;
delete s1, s2, s3, s4;
}
void SensorValuePointerConvertionTestFixture::testPointerToNull() {
for (int i = 0; i < s.size(); ++i) {
s[i]->pointersToNull();
EXPECT_EQ(nullptr, s[i]->_m->_diag);
EXPECT_EQ(nullptr, s[i]->_cm->_diag);
EXPECT_EQ(nullptr, s[i]->_m->_diag_);
EXPECT_EQ(nullptr, s[i]->_cm->_diag_);
EXPECT_EQ(nullptr, s[i]->_m->_observe);
EXPECT_EQ(nullptr, s[i]->_cm->_observe);
EXPECT_EQ(nullptr, s[i]->_m->_observe_);
EXPECT_EQ(nullptr, s[i]->_cm->_observe_);
EXPECT_EQ(nullptr, s[i]->_m->_current);
EXPECT_EQ(nullptr, s[i]->_cm->_current);
EXPECT_EQ(nullptr, s[i]->_m->_target);
EXPECT_EQ(nullptr, s[i]->_cm->_target);
EXPECT_EQ(nullptr, s[i]->_m->_prediction);
EXPECT_EQ(nullptr, s[i]->_cm->_prediction);
}
}
void SensorValuePointerConvertionTestFixture::testPointersToValues() {
for (int i = 0; i < s.size(); ++i) {
s[i]->setAttrSensorDiagPointers(h_diag, h_diag_);
s[i]->setAttrSensorObservePointers(h_observe, h_observe_);
s[i]->setAttrSensorCurrentPointers(h_current, h_current_);
s[i]->setAttrSensorTargetPointers(h_target);
s[i]->setAttrSensorPredictionPointers(h_prediction);
EXPECT_EQ(h_diag + 2 * i, s[i]->_m->_diag);
EXPECT_EQ(h_diag + 2 * i + 1, s[i]->_cm->_diag);
EXPECT_EQ(h_diag_ + 2 * i, s[i]->_m->_diag_);
EXPECT_EQ(h_diag_ + 2 * i + 1, s[i]->_cm->_diag_);
EXPECT_EQ(h_observe + 2 * i, s[i]->_m->_observe);
EXPECT_EQ(h_observe + 2 * i + 1, s[i]->_cm->_observe);
EXPECT_EQ(h_observe_ + 2 * i, s[i]->_m->_observe_);
EXPECT_EQ(h_observe_ + 2 * i + 1, s[i]->_cm->_observe_);
EXPECT_EQ(h_current + 2 * i, s[i]->_m->_current);
EXPECT_EQ(h_current + 2 * i + 1, s[i]->_cm->_current);
EXPECT_EQ(h_target + 2 * i, s[i]->_m->_target);
EXPECT_EQ(h_target + 2 * i + 1, s[i]->_cm->_target);
EXPECT_EQ(h_prediction + 2 * i, s[i]->_m->_prediction);
EXPECT_EQ(h_prediction + 2 * i + 1, s[i]->_cm->_prediction);
s[i]->pointersToValues();
EXPECT_EQ(h_diag[2 * i], s[i]->_m->_vdiag);
EXPECT_EQ(h_diag[2 * i + 1], s[i]->_cm->_vdiag);
EXPECT_EQ(h_diag_[2 * i], s[i]->_m->_vdiag_);
EXPECT_EQ(h_diag_[2 * i + 1], s[i]->_cm->_vdiag_);
EXPECT_EQ(h_observe[2 * i], s[i]->_m->_vobserve);
EXPECT_EQ(h_observe[2 * i + 1], s[i]->_cm->_vobserve);
EXPECT_EQ(h_observe_[2 * i], s[i]->_m->_vobserve_);
EXPECT_EQ(h_observe_[2 * i + 1], s[i]->_cm->_vobserve_);
EXPECT_EQ(h_target[2 * i], s[i]->_m->_vtarget);
EXPECT_EQ(h_target[2 * i + 1], s[i]->_cm->_vtarget);
}
}
void SensorValuePointerConvertionTestFixture::testValuesToPointers() {
for (int i = 0; i < s.size(); ++i) {
s[i]->_m->_vdiag = 0.1;
s[i]->_cm->_vdiag = 0.2;
s[i]->_m->_vdiag_ = 0.3;
s[i]->_cm->_vdiag_ = 0.4;
s[i]->_m->_vobserve = true;
s[i]->_cm->_vobserve = false;
s[i]->_m->_vobserve_ = false;
s[i]->_cm->_vobserve_ = true;
s[i]->_m->_vtarget = true;
s[i]->_cm->_vtarget = false;
s[i]->valuesToPointers();
EXPECT_EQ(h_diag[2 * i], s[i]->_m->_vdiag);
EXPECT_EQ(h_diag[2 * i + 1], s[i]->_cm->_vdiag);
EXPECT_EQ(h_diag_[2 * i], s[i]->_m->_vdiag_);
EXPECT_EQ(h_diag_[2 * i + 1], s[i]->_cm->_vdiag_);
EXPECT_EQ(h_observe[2 * i], s[i]->_m->_vobserve);
EXPECT_EQ(h_observe[2 * i + 1], s[i]->_cm->_vobserve);
EXPECT_EQ(h_observe_[2 * i], s[i]->_m->_vobserve_);
EXPECT_EQ(h_observe_[2 * i + 1], s[i]->_cm->_vobserve_);
EXPECT_EQ(h_target[2 * i], s[i]->_m->_vtarget);
EXPECT_EQ(h_target[2 * i + 1], s[i]->_cm->_vtarget);
}
}
SensorSavingLoading::SensorSavingLoading() {
fileName = "sensor_test.uma";
pair<string, string> p1 = { "s", "cs" };
s1 = new Sensor(p1, nullptr, 1.0, 10);
s1->_amper.push_back(0);
s1->_amper.push_back(2);
s1->_amper.push_back(5);
}
SensorSavingLoading::~SensorSavingLoading() {
SysUtil::UMARemove(fileName);
delete s1, s2, s3;
}
void SensorSavingLoading::savingAndLoading() {
ofstream output;
output.open(fileName, ios::binary | ios::out);
s1->saveSensor(output);
output.close();
ifstream input;
input.open(fileName, ios::binary | ios::in);
s2 = Sensor::loadSensor(input, nullptr);
input.close();
asserting(s1, s2);
}
void SensorSavingLoading::copying() {
s3 = new Sensor(*s1, nullptr);
asserting(s1, s3);
}
void SensorSavingLoading::asserting(Sensor *si, Sensor *sj) {
EXPECT_EQ(si->_uuid, sj->_uuid);
EXPECT_EQ(si->_idx, sj->_idx);
EXPECT_EQ(si->_amper, sj->_amper);
}
AttrSensorSavingLoading::AttrSensorSavingLoading() {
fileName = "attr_sensor_test.uma";
const string uuid = "attr_sensor_0";
as1 = new AttrSensor(uuid, nullptr, 10, true, 10.12);
}
AttrSensorSavingLoading::~AttrSensorSavingLoading() {
SysUtil::UMARemove(fileName);
delete as1, as2, as3;
}
void AttrSensorSavingLoading::savingAndLoading() {
ofstream output;
output.open(fileName, ios::binary | ios::out);
as1->saveAttrSensor(output);
output.close();
ifstream input;
input.open(fileName, ios::binary | ios::in);
as2 = AttrSensor::loadAttrSensor(input, nullptr);
input.close();
asserting(as1, as2);
}
void AttrSensorSavingLoading::copying() {
as3 = new AttrSensor(*as1, nullptr);
asserting(as1, as3);
}
void AttrSensorSavingLoading::asserting(AttrSensor *asi, AttrSensor *asj) {
EXPECT_EQ(asi->_uuid, asj->_uuid);
EXPECT_EQ(asi->_idx, asj->_idx);
EXPECT_EQ(asi->_isOriginPure, asj->_isOriginPure);
EXPECT_EQ(asi->_vdiag, asj->_vdiag);
EXPECT_EQ(asi->_vdiag_, asj->_vdiag_);
}
SensorPairSavingLoading::SensorPairSavingLoading() {
fileName = "sensor_pair.uma";
const string uuid = "attr_sensor_0";
pair<string, string> p1 = { "s1", "cs1" };
pair<string, string> p2 = { "s2", "cs2" };
s1 = new Sensor(p1, nullptr, 1.0, 1);
s2 = new Sensor(p2, nullptr, 0.5, 3);
sp1 = new SensorPair(nullptr, s1, s2, 0.123);
}
SensorPairSavingLoading::~SensorPairSavingLoading() {
SysUtil::UMARemove(fileName);
delete sp1, sp2, sp3;
delete s1, s2;
}
void SensorPairSavingLoading::savingAndLoading() {
ofstream output;
output.open(fileName, ios::binary | ios::out);
sp1->saveSensorPair(output);
output.close();
vector<Sensor*> sensors = {nullptr, s1, nullptr, s2 };
ifstream input;
input.open(fileName, ios::binary | ios::in);
sp2 = SensorPair::loadSensorPair(input, sensors, nullptr);
input.close();
asserting(sp1, sp2);
}
void SensorPairSavingLoading::copying() {
sp3 = new SensorPair(*sp1, nullptr, s1, s2);
asserting(sp1, sp3);
}
void SensorPairSavingLoading::asserting(SensorPair *spi, SensorPair *spj) {
EXPECT_EQ(spi->_uuid, spj->_uuid);
EXPECT_EQ(spi->_vthreshold, spj->_vthreshold);
EXPECT_EQ(spi->_sensor_i, spj->_sensor_i);
EXPECT_EQ(spi->_sensor_j, spj->_sensor_j);
}
AttrSensorPairSavingLoading::AttrSensorPairSavingLoading() {
fileName = "attr_sensor_pair.uma";
const string uuid = "attr_sensor_0";
pair<string, string> p1 = { "s1", "cs1" };
pair<string, string> p2 = { "s2", "cs2" };
as1 = new AttrSensor("attr_sensor0", nullptr, 0, true, 0.12);
as2 = new AttrSensor("attr_sensor1", nullptr, 2, false, 0.23);
asp1 = new AttrSensorPair(nullptr, as1, as2, 0.98, true);
}
AttrSensorPairSavingLoading::~AttrSensorPairSavingLoading() {
SysUtil::UMARemove(fileName);
delete asp1, asp2, asp3;
delete as1, as2;
}
void AttrSensorPairSavingLoading::savingAndLoading() {
ofstream output;
output.open(fileName, ios::binary | ios::out);
asp1->saveAttrSensorPair(output);
output.close();
ifstream input;
input.open(fileName, ios::binary | ios::in);
asp2 = AttrSensorPair::loadAttrSensorPair(input, as1, as2, true, nullptr);
input.close();
asserting(asp1, asp2);
}
void AttrSensorPairSavingLoading::copying() {
asp3 = new AttrSensorPair(*asp1, nullptr, as1, as2);
asserting(asp1, asp3);
}
void AttrSensorPairSavingLoading::asserting(AttrSensorPair *aspi, AttrSensorPair *aspj) {
EXPECT_EQ(aspi->_uuid, aspj->_uuid);
EXPECT_EQ(aspi->_attrSensorI, aspj->_attrSensorI);
EXPECT_EQ(aspi->_attrSensorJ, aspj->_attrSensorJ);
EXPECT_EQ(aspi->_vw, aspj->_vw);
}
DataManagerSavingLoading::DataManagerSavingLoading() {
fileName = "dm_test.uma";
dm1 = new DataManager(nullptr);
dm1->_memoryExpansion = 0.2;
}
DataManagerSavingLoading::~DataManagerSavingLoading() {
SysUtil::UMARemove(fileName);
delete dm1, dm2;
}
void DataManagerSavingLoading::savingAndLoading() {
ofstream output;
output.open(fileName, ios::binary | ios::out);
dm1->saveDM(output);
output.close();
ifstream input;
input.open(fileName, ios::binary | ios::in);
dm2 = DataManager::loadDM(input, nullptr);
input.close();
EXPECT_EQ(dm1->_uuid, dm2->_uuid);
EXPECT_EQ(dm1->_memoryExpansion, dm2->_memoryExpansion);
}
void DataManagerSavingLoading::copying() {
DataManager *dm3 = new DataManager(*dm1, nullptr);
EXPECT_EQ(dm1->_uuid, dm3->_uuid);
EXPECT_EQ(dm1->_memoryExpansion, dm3->_memoryExpansion);
}
SnapshotSavingLoading::SnapshotSavingLoading() {
s1FileName = "s1.uma";
s2FileName = "s2.uma";
s3FileName = "s3.uma";
s4FileName = "s4.uma";
agent1 = new Agent("agent1", nullptr);
agent2 = new Agent("agent2", nullptr);
s1 = new Snapshot("snapshot0", agent1);
s2 = new SnapshotQualitative("snapshot1", agent1);
s3 = new SnapshotEmpirical("snapshot2", agent1);
s4 = new SnapshotDiscounted("snapshot3", agent1);
s1->setInitialSize();
s2->setInitialSize();
s3->setInitialSize();
s4->setInitialSize();
s1->_q = 0.12;
s2->_q = 0.23;
s3->_q = 0.34;
s4->_q = 0.45;
s1->_threshold = 0.001;
s2->_threshold = 0.002;
s3->_threshold = 0.003;
s4->_threshold = 0.004;
s1->_autoTarget = true;
s2->_autoTarget = false;
s3->_autoTarget = false;
s4->_autoTarget = true;
s1->_propagateMask = false;
s2->_propagateMask = true;
s3->_propagateMask = true;
s4->_propagateMask = false;
s1->_delayCount = 10;
s2->_delayCount = 100;
s3->_delayCount = 1000;
s4->_delayCount = 10000;
s1->_delayCount = 10;
}
SnapshotSavingLoading::~SnapshotSavingLoading() {
SysUtil::UMARemove(s1FileName);
SysUtil::UMARemove(s2FileName);
SysUtil::UMARemove(s3FileName);
SysUtil::UMARemove(s4FileName);
delete agent1, agent2;
delete s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12;
}
void SnapshotSavingLoading::savingAndLoading() {
ofstream output;
output.open(s1FileName, ios::binary | ios::out);
s1->saveSnapshot(output);
output.close();
output.open(s2FileName, ios::binary | ios::out);
s2->saveSnapshot(output);
output.close();
output.open(s3FileName, ios::binary | ios::out);
s3->saveSnapshot(output);
output.close();
output.open(s4FileName, ios::binary | ios::out);
s4->saveSnapshot(output);
output.close();
ifstream input;
input.open(s1FileName, ios::binary | ios::in);
s5 = Snapshot::loadSnapshot(input, agent2);
input.close();
input.open(s2FileName, ios::binary | ios::in);
s6 = Snapshot::loadSnapshot(input, agent2);
input.close();
input.open(s3FileName, ios::binary | ios::in);
s7 = Snapshot::loadSnapshot(input, agent2);
input.close();
input.open(s4FileName, ios::binary | ios::in);
s8 = Snapshot::loadSnapshot(input, agent2);
input.close();
EXPECT_EQ(s1->_type, s5->_type);
EXPECT_EQ(s2->_type, s6->_type);
EXPECT_EQ(s3->_type, s7->_type);
EXPECT_EQ(s4->_type, s8->_type);
EXPECT_EQ(s1->_uuid, s5->_uuid);
EXPECT_EQ(s2->_uuid, s6->_uuid);
EXPECT_EQ(s3->_uuid, s7->_uuid);
EXPECT_EQ(s4->_uuid, s8->_uuid);
EXPECT_EQ(s1->_initialSize, s5->_initialSize);
EXPECT_EQ(s2->_initialSize, s6->_initialSize);
EXPECT_EQ(s3->_initialSize, s7->_initialSize);
EXPECT_EQ(s4->_initialSize, s8->_initialSize);
EXPECT_EQ(s1->_q, s5->_q);
EXPECT_EQ(s2->_q, s6->_q);
EXPECT_EQ(s3->_q, s7->_q);
EXPECT_EQ(s4->_q, s8->_q);
EXPECT_EQ(s1->_total, s5->_total);
EXPECT_EQ(s2->_total, s6->_total);
EXPECT_EQ(s3->_total, s7->_total);
EXPECT_EQ(s4->_total, s8->_total);
EXPECT_EQ(s1->_threshold, s5->_threshold);
EXPECT_EQ(s2->_threshold, s6->_threshold);
EXPECT_EQ(s3->_threshold, s7->_threshold);
EXPECT_EQ(s4->_threshold, s8->_threshold);
EXPECT_EQ(s1->_autoTarget, s5->_autoTarget);
EXPECT_EQ(s2->_autoTarget, s6->_autoTarget);
EXPECT_EQ(s3->_autoTarget, s7->_autoTarget);
EXPECT_EQ(s4->_autoTarget, s8->_autoTarget);
EXPECT_EQ(s1->_propagateMask, s5->_propagateMask);
EXPECT_EQ(s2->_propagateMask, s6->_propagateMask);
EXPECT_EQ(s3->_propagateMask, s7->_propagateMask);
EXPECT_EQ(s4->_propagateMask, s8->_propagateMask);
EXPECT_EQ(s1->_delayCount, s5->_delayCount);
EXPECT_EQ(s2->_delayCount, s6->_delayCount);
EXPECT_EQ(s3->_delayCount, s7->_delayCount);
EXPECT_EQ(s4->_delayCount, s8->_delayCount);
}
void SnapshotSavingLoading::copying() {
s9 = new Snapshot(*s1, agent2);
s10 = new SnapshotQualitative(*dynamic_cast<SnapshotQualitative*>(s2), agent2);
s11 = new SnapshotEmpirical(*dynamic_cast<SnapshotEmpirical*>(s3), agent2);
s12 = new SnapshotDiscounted(*dynamic_cast<SnapshotDiscounted*>(s4), agent2);
EXPECT_EQ(s1->_type, s9->_type);
EXPECT_EQ(s2->_type, s10->_type);
EXPECT_EQ(s3->_type, s11->_type);
EXPECT_EQ(s4->_type, s12->_type);
EXPECT_EQ(s1->_uuid, s9->_uuid);
EXPECT_EQ(s2->_uuid, s10->_uuid);
EXPECT_EQ(s3->_uuid, s11->_uuid);
EXPECT_EQ(s4->_uuid, s12->_uuid);
EXPECT_EQ(s1->_initialSize, s9->_initialSize);
EXPECT_EQ(s2->_initialSize, s10->_initialSize);
EXPECT_EQ(s3->_initialSize, s11->_initialSize);
EXPECT_EQ(s4->_initialSize, s12->_initialSize);
EXPECT_EQ(s1->_q, s9->_q);
EXPECT_EQ(s2->_q, s10->_q);
EXPECT_EQ(s3->_q, s11->_q);
EXPECT_EQ(s4->_q, s12->_q);
EXPECT_EQ(s1->_total, s5->_total);
EXPECT_EQ(s2->_total, s6->_total);
EXPECT_EQ(s3->_total, s7->_total);
EXPECT_EQ(s4->_total, s8->_total);
EXPECT_EQ(s1->_threshold, s9->_threshold);
EXPECT_EQ(s2->_threshold, s10->_threshold);
EXPECT_EQ(s3->_threshold, s11->_threshold);
EXPECT_EQ(s4->_threshold, s12->_threshold);
EXPECT_EQ(s1->_autoTarget, s9->_autoTarget);
EXPECT_EQ(s2->_autoTarget, s10->_autoTarget);
EXPECT_EQ(s3->_autoTarget, s11->_autoTarget);
EXPECT_EQ(s4->_autoTarget, s12->_autoTarget);
EXPECT_EQ(s1->_propagateMask, s9->_propagateMask);
EXPECT_EQ(s2->_propagateMask, s10->_propagateMask);
EXPECT_EQ(s3->_propagateMask, s11->_propagateMask);
EXPECT_EQ(s4->_propagateMask, s12->_propagateMask);
EXPECT_EQ(s1->_delayCount, s9->_delayCount);
EXPECT_EQ(s2->_delayCount, s10->_delayCount);
EXPECT_EQ(s3->_delayCount, s11->_delayCount);
EXPECT_EQ(s4->_delayCount, s12->_delayCount);
}
AgentSavingLoading::AgentSavingLoading() {
a1FileName = "a1.uma";
a2FileName = "a2.uma";
a3FileName = "a3.uma";
a4FileName = "a4.uma";
a1 = new Agent("agent1", nullptr);
a2 = new AgentQualitative("agent2", nullptr);
a3 = new AgentDiscounted("agent3", nullptr);
a4 = new AgentEmpirical("agent4", nullptr);
}
AgentSavingLoading::~AgentSavingLoading() {
SysUtil::UMARemove(a1FileName);
SysUtil::UMARemove(a2FileName);
SysUtil::UMARemove(a3FileName);
SysUtil::UMARemove(a4FileName);
delete a1, a2, a3, a4, a5, a6, a7, a8,a9, a10, a11, a12;
}
void AgentSavingLoading::savingAndLoading() {
ofstream output;
output.open(a1FileName, ios::binary | ios::out);
a1->saveAgent(output);
output.close();
output.open(a2FileName, ios::binary | ios::out);
a2->saveAgent(output);
output.close();
output.open(a3FileName, ios::binary | ios::out);
a3->saveAgent(output);
output.close();
output.open(a4FileName, ios::binary | ios::out);
a4->saveAgent(output);
output.close();
ifstream input;
input.open(a1FileName, ios::binary | ios::in);
a5 = Agent::loadAgent(input, nullptr);
input.close();
input.open(a2FileName, ios::binary | ios::in);
a6 = Agent::loadAgent(input, nullptr);
input.close();
input.open(a3FileName, ios::binary | ios::in);
a7 = Agent::loadAgent(input, nullptr);
input.close();
input.open(a4FileName, ios::binary | ios::in);
a8 = Agent::loadAgent(input, nullptr);
input.close();
EXPECT_EQ(a1->_type, a5->_type);
EXPECT_EQ(a2->_type, a6->_type);
EXPECT_EQ(a3->_type, a7->_type);
EXPECT_EQ(a4->_type, a8->_type);
EXPECT_EQ(a1->_uuid, a5->_uuid);
EXPECT_EQ(a2->_uuid, a6->_uuid);
EXPECT_EQ(a3->_uuid, a7->_uuid);
EXPECT_EQ(a4->_uuid, a8->_uuid);
}
void AgentSavingLoading::copying() {
a9 = new Agent(*a1, nullptr, a1->_uuid);
a10 = new AgentQualitative(*dynamic_cast<AgentQualitative*>(a2), nullptr, a2->_uuid);
a11 = new AgentDiscounted(*dynamic_cast<AgentDiscounted*>(a3), nullptr, a3->_uuid);
a12 = new AgentEmpirical(*dynamic_cast<AgentEmpirical*>(a4), nullptr, a4->_uuid);
EXPECT_EQ(a1->_type, a9->_type);
EXPECT_EQ(a2->_type, a10->_type);
EXPECT_EQ(a3->_type, a11->_type);
EXPECT_EQ(a4->_type, a12->_type);
EXPECT_EQ(a1->_uuid, a9->_uuid);
EXPECT_EQ(a2->_uuid, a10->_uuid);
EXPECT_EQ(a3->_uuid, a11->_uuid);
EXPECT_EQ(a4->_uuid, a12->_uuid);
}
ExperimentSavingLoading::ExperimentSavingLoading() {
exp1 = new Experiment("experiment0");
}
ExperimentSavingLoading::~ExperimentSavingLoading() {
SysUtil::UMARemove(exp1->getUUID() + ".uma");
delete exp1, exp2;
}
void ExperimentSavingLoading::savingAndLoading() {
exp1->saveExperiment();
exp2 = Experiment::loadExperiment(exp1->getUUID());
EXPECT_EQ("load_" + exp1->_uuid, exp2->_uuid);
EXPECT_EQ(exp1->_agents.size(), exp2->_agents.size());
}
UMASavingLoading::UMASavingLoading() {
exp1 = new Experiment("uma_test");
Agent *a1 = exp1->createAgent("agent1", UMA_AGENT::AGENT_QUALITATIVE);
Agent *a2 = exp1->createAgent("agent2", UMA_AGENT::AGENT_DISCOUNTED);
Snapshot *s1 = a1->createSnapshot("snapshot1");
Snapshot *s2 = a1->createSnapshot("snapshot2");
Snapshot *s3 = a2->createSnapshot("snapshot3");
Snapshot *s4 = a2->createSnapshot("snapshot4");
s1->_autoTarget = true;
s2->_propagateMask = false;
s3->_threshold = 0.02;
s4->_q = 0.22;
s1->_delayCount = 10;
s2->_q = 0.29;
std::pair<string, string> sList1 = { "s1", "cs1" };
std::pair<string, string> sList2 = { "s2", "cs2" };
std::pair<string, string> sList3 = { "s3", "cs3" };
vector<double> diag1 = { 0.4, 0.6 };
vector<double> diag2 = { 0.3, 0.7 };
vector<vector<double>> w1 = { {0.2, 0.2, 0,0, 0.6} }, w2 = { {0.2, 0.1, 0.3, 0.4}, {0.0, 0.5, 0.2, 0.3} };
vector<vector<double>> w3 = { {0,9, 0.1, 0, 0}, {0.2, 0.3, 0.1, 0.4}, {0.7, 0.2, 0.05, 0.05} };
vector<vector<bool>> b1 = { {true, false, false, true} }, b2 = { {false, false, true, true}, {true, true, false, false} };
vector<vector<bool>> b3 = { {false, false, false, false}, {true, false, true, false}, {false, true, false, false} };
s1->createSensor(sList1, diag1, w1, b1);
s1->createSensor(sList3, diag2, w2, b2);
s2->createSensor(sList2, diag2, w1, b1);
s3->createSensor(sList1, diag1, w1, b1);
s3->createSensor(sList2, diag2, w2, b2);
s3->createSensor(sList3, diag1, w3, b3);
s1->setInitialSize();
s2->setInitialSize();
s3->setInitialSize();
s4->setInitialSize();
vector<vector<bool>> lists = { {false, true, true, false} };
vector<std::pair<string, string>> pairs = { {"delay1", "delay2"} };
s1->delays(lists, pairs);
}
UMASavingLoading::~UMASavingLoading() {
SysUtil::UMARemove(exp1->getUUID() + ".uma");
delete exp1, exp2;
}
void assertingExperiment(Experiment *exp1, Experiment *exp2) {
}
void UMASavingLoading::savingAndLoading() {
exp1->saveExperiment();
exp2 = Experiment::loadExperiment(exp1->getUUID());
EXPECT_EQ("load_" + exp1->_uuid, exp2->_uuid);
for (auto agentIt = exp1->_agents.begin(); agentIt != exp1->_agents.end(); ++agentIt) {
string agentName = agentIt->first;
Agent *agent1 = exp1->_agents[agentName], *agent2 = exp2->_agents[agentName];
EXPECT_EQ(agent1->_type, agent2->_type);
EXPECT_EQ(agent1->_uuid, agent2->_uuid);
for (auto snapshotIt = agent1->_snapshots.begin(); snapshotIt != agent1->_snapshots.end(); ++snapshotIt) {
string snapshotName = snapshotIt->first;
Snapshot *snapshot1 = agent1->_snapshots[snapshotName], *snapshot2 = agent2->_snapshots[snapshotName];
EXPECT_EQ(snapshot1->_type, snapshot2->_type);
EXPECT_EQ(snapshot1->_uuid, snapshot2->_uuid);
EXPECT_EQ(snapshot1->_initialSize, snapshot2->_initialSize);
EXPECT_EQ(snapshot1->_q, snapshot2->_q);
EXPECT_EQ(snapshot1->_threshold, snapshot2->_threshold);
EXPECT_EQ(snapshot1->_total, snapshot2->_total);
EXPECT_EQ(snapshot1->_autoTarget, snapshot2->_autoTarget);
EXPECT_EQ(snapshot1->_propagateMask, snapshot2->_propagateMask);
EXPECT_EQ(snapshot1->_delayCount, snapshot2->_delayCount);
for (auto idxIt = snapshot1->_sensorIdx.begin(); idxIt != snapshot1->_sensorIdx.end(); ++idxIt) {
string sensorName = idxIt->first;
EXPECT_NO_THROW(snapshot2->_sensorIdx[sensorName]);
}
for (auto delayHashIt = snapshot1->_delaySensorHash.begin(); delayHashIt != snapshot1->_delaySensorHash.end(); ++delayHashIt) {
size_t hash = *delayHashIt;
EXPECT_NE(snapshot2->_delaySensorHash.find(hash), snapshot2->_delaySensorHash.end());
}
DataManager *dm1 = snapshot1->_dm, *dm2 = snapshot2->_dm;
EXPECT_EQ(dm1->_uuid, dm2->_uuid);
EXPECT_EQ(dm1->_memoryExpansion, dm2->_memoryExpansion);
EXPECT_EQ(dm1->_sensorSize, dm2->_sensorSize);
for (int i = 0; i < dm1->_attrSensor2dSize; ++i) {
// testing weight
EXPECT_EQ(dm1->h_weights[i], dm2->h_weights[i]);
}
for (int i = 0; i < dm1->_sensor2dSize; ++i) {
// testing threshold
EXPECT_EQ(dm1->h_thresholds[i], dm2->h_thresholds[i]);
}
for (int i = 0; i < snapshot1->_sensors.size(); ++i) {
Sensor *sensor1 = snapshot1->_sensors[i], *sensor2 = snapshot2->_sensors[i];
EXPECT_EQ(sensor1->_uuid, sensor2->_uuid);
EXPECT_EQ(sensor1->_idx, sensor2->_idx);
EXPECT_EQ(sensor1->_amper, sensor2->_amper);
EXPECT_EQ(sensor1->_m->_uuid, sensor2->_m->_uuid);
EXPECT_EQ(sensor1->_m->_idx, sensor2->_m->_idx);
EXPECT_EQ(sensor1->_m->_isOriginPure, sensor2->_m->_isOriginPure);
EXPECT_EQ(sensor1->_m->_vdiag, sensor2->_m->_vdiag);
EXPECT_EQ(sensor1->_m->_vdiag_, sensor2->_m->_vdiag_);
EXPECT_EQ(sensor1->_cm->_uuid, sensor2->_cm->_uuid);
EXPECT_EQ(sensor1->_cm->_idx, sensor2->_cm->_idx);
EXPECT_EQ(sensor1->_cm->_isOriginPure, sensor2->_cm->_isOriginPure);
EXPECT_EQ(sensor1->_cm->_vdiag, sensor2->_cm->_vdiag);
EXPECT_EQ(sensor1->_cm->_vdiag_, sensor2->_cm->_vdiag_);
}
for (int i = 0; i < snapshot1->_sensorPairs.size(); ++i) {
SensorPair *sensorPair1 = snapshot1->_sensorPairs[i], *sensorPair2 = snapshot2->_sensorPairs[i];
EXPECT_EQ(sensorPair1->_uuid, sensorPair2->_uuid);
EXPECT_EQ(sensorPair1->_vthreshold, sensorPair2->_vthreshold);
EXPECT_EQ(sensorPair1->mij->_uuid, sensorPair2->mij->_uuid);
EXPECT_EQ(sensorPair1->mij->_vw, sensorPair2->mij->_vw);
EXPECT_EQ(sensorPair1->mi_j->_uuid, sensorPair2->mi_j->_uuid);
EXPECT_EQ(sensorPair1->mi_j->_vw, sensorPair2->mi_j->_vw);
EXPECT_EQ(sensorPair1->m_ij->_uuid, sensorPair2->m_ij->_uuid);
EXPECT_EQ(sensorPair1->m_ij->_vw, sensorPair2->m_ij->_vw);
EXPECT_EQ(sensorPair1->m_i_j->_uuid, sensorPair2->m_i_j->_uuid);
EXPECT_EQ(sensorPair1->m_i_j->_vw, sensorPair2->m_i_j->_vw);
}
}
}
}
UMAAgentCopying::UMAAgentCopying() {
exp = new Experiment("test_experiment");
Agent *a1 = exp->createAgent("agent1", UMA_AGENT::AGENT_QUALITATIVE);
Agent *a2 = exp->createAgent("agent2", UMA_AGENT::AGENT_DISCOUNTED);
Snapshot *s1 = a1->createSnapshot("snapshot1");
Snapshot *s2 = a1->createSnapshot("snapshot2");
Snapshot *s3 = a2->createSnapshot("snapshot3");
Snapshot *s4 = a2->createSnapshot("snapshot4");
s1->_autoTarget = true;
s2->_propagateMask = false;
s3->_threshold = 0.02;
s4->_q = 0.22;
s1->_delayCount = 10;
s2->_q = 0.29;
std::pair<string, string> sList1 = { "s1", "cs1" };
std::pair<string, string> sList2 = { "s2", "cs2" };
std::pair<string, string> sList3 = { "s3", "cs3" };
vector<double> diag1 = { 0.4, 0.6 };
vector<double> diag2 = { 0.3, 0.7 };
vector<vector<double>> w1 = { { 0.2, 0.2, 0,0, 0.6 } }, w2 = { { 0.2, 0.1, 0.3, 0.4 },{ 0.0, 0.5, 0.2, 0.3 } };
vector<vector<double>> w3 = { { 0,9, 0.1, 0, 0 },{ 0.2, 0.3, 0.1, 0.4 },{ 0.7, 0.2, 0.05, 0.05 } };
vector<vector<bool>> b1 = { { true, false, false, true } }, b2 = { { false, false, true, true },{ true, true, false, false } };
vector<vector<bool>> b3 = { { false, false, false, false },{ true, false, true, false },{ false, true, false, false } };
s1->createSensor(sList1, diag1, w1, b1);
s1->createSensor(sList3, diag2, w2, b2);
s2->createSensor(sList2, diag2, w1, b1);
s3->createSensor(sList1, diag1, w1, b1);
s3->createSensor(sList2, diag2, w2, b2);
s3->createSensor(sList3, diag1, w3, b3);
s1->setInitialSize();
s2->setInitialSize();
s3->setInitialSize();
s4->setInitialSize();
vector<vector<bool>> lists = { { false, true, true, false } };
vector<std::pair<string, string>> pairs = { { "delay1", "delay2" } };
s1->delays(lists, pairs);
}
UMAAgentCopying::~UMAAgentCopying() {
delete exp;
}
void UMAAgentCopying::copyingAgents() {
AgentQualitative *agent1 = dynamic_cast<AgentQualitative*>(exp->getAgent("agent1"));
AgentDiscounted *agent2 = dynamic_cast<AgentDiscounted*>(exp->getAgent("agent2"));
Agent *cAgent1 = new AgentQualitative(*agent1, nullptr, "agent1");
Agent *cAgent2 = new AgentDiscounted(*agent2, nullptr, "agent2");
assertingAgents(agent1, cAgent1);
assertingAgents(agent2, cAgent2);
}
void UMAAgentCopying::assertingAgents(Agent *agent1, Agent *agent2) {
EXPECT_EQ(agent1->_type, agent2->_type);
EXPECT_EQ(agent1->_uuid, agent2->_uuid);
for (auto snapshotIt = agent1->_snapshots.begin(); snapshotIt != agent1->_snapshots.end(); ++snapshotIt) {
string snapshotName = snapshotIt->first;
Snapshot *snapshot1 = agent1->_snapshots[snapshotName], *snapshot2 = agent2->_snapshots[snapshotName];
EXPECT_EQ(snapshot1->_type, snapshot2->_type);
EXPECT_EQ(snapshot1->_uuid, snapshot2->_uuid);
EXPECT_EQ(snapshot1->_initialSize, snapshot2->_initialSize);
EXPECT_EQ(snapshot1->_q, snapshot2->_q);
EXPECT_EQ(snapshot1->_threshold, snapshot2->_threshold);
EXPECT_EQ(snapshot1->_total, snapshot2->_total);
EXPECT_EQ(snapshot1->_autoTarget, snapshot2->_autoTarget);
EXPECT_EQ(snapshot1->_propagateMask, snapshot2->_propagateMask);
EXPECT_EQ(snapshot1->_delayCount, snapshot2->_delayCount);
for (auto idxIt = snapshot1->_sensorIdx.begin(); idxIt != snapshot1->_sensorIdx.end(); ++idxIt) {
string sensorName = idxIt->first;
EXPECT_NO_THROW(snapshot2->_sensorIdx[sensorName]);
}
for (auto delayHashIt = snapshot1->_delaySensorHash.begin(); delayHashIt != snapshot1->_delaySensorHash.end(); ++delayHashIt) {
size_t hash = *delayHashIt;
EXPECT_NE(snapshot2->_delaySensorHash.find(hash), snapshot2->_delaySensorHash.end());
}
DataManager *dm1 = snapshot1->_dm, *dm2 = snapshot2->_dm;
EXPECT_EQ(dm1->_uuid, dm2->_uuid);
EXPECT_EQ(dm1->_memoryExpansion, dm2->_memoryExpansion);
EXPECT_EQ(dm1->_sensorSize, dm2->_sensorSize); // all other size will not be tested, since they all come from sensorSize
for (int i = 0; i < dm1->_attrSensor2dSize; ++i) {
// testing weight
EXPECT_EQ(dm1->h_weights[i], dm2->h_weights[i]);
// testing dir
EXPECT_EQ(dm1->h_dirs[i], dm2->h_dirs[i]);
}
for (int i = 0; i < dm1->_sensor2dSize; ++i) {
// testing threshold
EXPECT_EQ(dm1->h_thresholds[i], dm2->h_thresholds[i]);
}
for (int i = 0; i < dm1->_npdirSize; ++i) {
// testing npdirs
EXPECT_EQ(dm1->h_npdirs[i], dm2->h_npdirs[i]);
}
for (int i = 0; i < dm1->_maskAmperSize; ++i) {
// testing mask amper
EXPECT_EQ(dm1->h_mask_amper[i], dm2->h_mask_amper[i]);
}
for (int i = 0; i < dm1->_sensorSize * dm1->_attrSensorSize; ++i) {
// testing npdir mask
EXPECT_EQ(dm1->h_npdir_mask[i], dm2->h_npdir_mask[i]);
}
for (int i = 0; i < dm1->_attrSensorSize * dm1->_attrSensorSize; ++i) {
// testing signal
EXPECT_EQ(dm1->h_signals[i], dm2->h_signals[i]);
// testing lsignal
EXPECT_EQ(dm1->h_lsignals[i], dm2->h_lsignals[i]);
// testing dists
EXPECT_EQ(dm1->h_dists[i], dm2->h_dists[i]);
}
for (int i = 0; i < dm1->_sensorSize; ++i) {
// testing union root
EXPECT_EQ(dm1->h_union_root[i], dm2->h_union_root[i]);
}
for (int i = 0; i < dm1->_attrSensorSize; ++i) {
// testing other parameters
EXPECT_EQ(dm1->h_observe[i], dm2->h_observe[i]);
EXPECT_EQ(dm1->h_observe_[i], dm2->h_observe_[i]);
EXPECT_EQ(dm1->h_current[i], dm2->h_current[i]);
EXPECT_EQ(dm1->h_current_[i], dm2->h_current_[i]);
EXPECT_EQ(dm1->h_load[i], dm2->h_load[i]);
EXPECT_EQ(dm1->h_mask[i], dm2->h_mask[i]);
EXPECT_EQ(dm1->h_target[i], dm2->h_target[i]);
EXPECT_EQ(dm1->h_negligible[i], dm2->h_negligible[i]);
EXPECT_EQ(dm1->h_diag[i], dm2->h_diag[i]);
EXPECT_EQ(dm1->h_diag_[i], dm2->h_diag_[i]);
EXPECT_EQ(dm1->h_prediction[i], dm2->h_prediction[i]);
}
for (int i = 0; i < snapshot1->_sensors.size(); ++i) {
Sensor *sensor1 = snapshot1->_sensors[i], *sensor2 = snapshot2->_sensors[i];
EXPECT_EQ(sensor1->_uuid, sensor2->_uuid);
EXPECT_EQ(sensor1->_idx, sensor2->_idx);
EXPECT_EQ(sensor1->_amper, sensor2->_amper);
EXPECT_EQ(sensor1->_m->_uuid, sensor2->_m->_uuid);
EXPECT_EQ(sensor1->_m->_idx, sensor2->_m->_idx);
EXPECT_EQ(sensor1->_m->_isOriginPure, sensor2->_m->_isOriginPure);
EXPECT_EQ(sensor1->_m->_vdiag, sensor2->_m->_vdiag);
EXPECT_EQ(sensor1->_m->_vdiag_, sensor2->_m->_vdiag_);
EXPECT_EQ(sensor1->_cm->_uuid, sensor2->_cm->_uuid);
EXPECT_EQ(sensor1->_cm->_idx, sensor2->_cm->_idx);
EXPECT_EQ(sensor1->_cm->_isOriginPure, sensor2->_cm->_isOriginPure);
EXPECT_EQ(sensor1->_cm->_vdiag, sensor2->_cm->_vdiag);
EXPECT_EQ(sensor1->_cm->_vdiag_, sensor2->_cm->_vdiag_);
}
for (int i = 0; i < snapshot1->_sensorPairs.size(); ++i) {
SensorPair *sensorPair1 = snapshot1->_sensorPairs[i], *sensorPair2 = snapshot2->_sensorPairs[i];
EXPECT_EQ(sensorPair1->_uuid, sensorPair2->_uuid);
EXPECT_EQ(sensorPair1->_vthreshold, sensorPair2->_vthreshold);
EXPECT_EQ(sensorPair1->mij->_uuid, sensorPair2->mij->_uuid);
EXPECT_EQ(sensorPair1->mij->_vw, sensorPair2->mij->_vw);
EXPECT_EQ(sensorPair1->mi_j->_uuid, sensorPair2->mi_j->_uuid);
EXPECT_EQ(sensorPair1->mi_j->_vw, sensorPair2->mi_j->_vw);
EXPECT_EQ(sensorPair1->m_ij->_uuid, sensorPair2->m_ij->_uuid);
EXPECT_EQ(sensorPair1->m_ij->_vw, sensorPair2->m_ij->_vw);
EXPECT_EQ(sensorPair1->m_i_j->_uuid, sensorPair2->m_i_j->_uuid);
EXPECT_EQ(sensorPair1->m_i_j->_vw, sensorPair2->m_i_j->_vw);
}
}
} | 36.100537 | 153 | 0.677417 | [
"vector"
] |
de5207ca2ce674222346bda69d686497d0c85ad5 | 6,182 | cxx | C++ | HLT/ZDC/AliHLTZDCAgent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | HLT/ZDC/AliHLTZDCAgent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | HLT/ZDC/AliHLTZDCAgent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //-*- Mode: C++ -*-
// $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Chiara Oppedisano <Chiara.Oppedisano@to.infn.it> *
* for The ALICE HLT Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/** @file AliHLTZDCAgent.cxx
@author Chiara Oppedisano <Chiara.Oppedisano@to.infn.it>
@brief Agent of the libAliHLTZDC library
*/
#include <cassert>
#include "TSystem.h"
#include "AliDAQ.h"
#include "AliHLTZDCAgent.h"
#include "AliHLTErrorGuard.h"
// header files of library components
#include "AliHLTZDCESDRecoComponent.h"
// raw data handler of HLTOUT data
#include "AliHLTOUTHandlerEquId.h"
#include "AliHLTOUTHandlerEsdBranch.h"
/** global instance for agent registration */
AliHLTZDCAgent gAliHLTZDCAgent;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTZDCAgent)
AliHLTZDCAgent::AliHLTZDCAgent() :
AliHLTModuleAgent("ZDC")
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTZDCAgent::~AliHLTZDCAgent()
{
// see header file for class documentation
}
UInt_t AliHLTZDCAgent::GetDetectorMask() const
{
return AliDAQ::kZDC;
}
int AliHLTZDCAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
AliRawReader* rawReader,
AliRunLoader* runloader) const
{
// see header file for class documentation
if (!handler)
return -EINVAL;
if (rawReader || !runloader) {
// AliSimulation: use the AliRawReaderPublisher if the raw reader is available
// Alireconstruction: indicated by runloader==NULL, run always on raw data
// -- Define the ZDC raw publisher
// -----------------------------------
TString arg("-equipmentid 3840 -datatype 'DDL_RAW ' 'ZDC ' -dataspec 0x01");
handler->CreateConfiguration("ZDC-DP_0", "AliRawReaderPublisher", NULL , arg.Data());
// -- Define the VZERO reconstruction components
// -----------------------------------------------
handler->CreateConfiguration("ZDC-RECO", "ZDCESDReco", "ZDC-DP_0", "");
}
else if (runloader && !rawReader) {
// indicates AliSimulation with no RawReader available -> run on digits
/* NOT Tested/ implemented yet
handler->CreateConfiguration("DigitPublisher","AliLoaderPublisher",NULL,
"-loader ZDCLoader -datatype 'ALITREED' 'ZDC '");
handler->CreateConfiguration("Digit","ZDCReconstruction","DigitPublisher","");
*/
}
return 0;
}
const char* AliHLTZDCAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
AliRunLoader* /*runloader*/) const
{
// see header file for class documentation
// ZDC called only from the EsdConverter
return NULL;
}
const char* AliHLTZDCAgent::GetRequiredComponentLibraries() const
{
// see header file for class documentation
return "libAliHLTUtil.so libAliHLTZDC.so";
}
int AliHLTZDCAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
// see header file for class documentation
assert(pHandler);
if (!pHandler) return -EINVAL;
pHandler->AddComponent(new AliHLTZDCESDRecoComponent);
return 0;
}
int AliHLTZDCAgent::GetHandlerDescription(AliHLTComponentDataType dt,
AliHLTUInt32_t spec,
AliHLTOUTHandlerDesc& desc) const
{
// see header file for class documentation
if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginZDC)) {
desc=AliHLTOUTHandlerDesc(kRawReader, dt, GetModuleId());
HLTInfo("module %s handles data block type %s specification %d (0x%x)",
GetModuleId(), AliHLTComponent::DataType2Text(dt).c_str(), spec, spec);
return 1;
}
// add TObject data blocks of type {ESD_CONT:ZDC } to ESD
if (dt==(kAliHLTDataTypeESDContent|kAliHLTDataOriginZDC)) {
desc=AliHLTOUTHandlerDesc(kEsd, dt, GetModuleId());
HLTInfo("module %s handles data block type %s specification %d (0x%x)",
GetModuleId(), AliHLTComponent::DataType2Text(dt).c_str(), spec, spec);
return 1;
}
return 0;
}
AliHLTOUTHandler* AliHLTZDCAgent::GetOutputHandler(AliHLTComponentDataType dt,
AliHLTUInt32_t /*spec*/)
{
// see header file for class documentation
if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginZDC)) {
// use the default handler
static AliHLTOUTHandlerEquId handler;
return &handler;
}
if (dt==(kAliHLTDataTypeESDContent|kAliHLTDataOriginZDC)) {
// use AliHLTOUTHandlerEsdBranch handler to add the TObject
// to the ESD branch
// Note: the object should have an appropriate name returned
// by GetName(). Use SetName() to prepare the object before streaming
static AliHLTOUTHandlerEsdBranch handler;
return &handler;
}
return NULL;
}
int AliHLTZDCAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
// see header file for class documentation
if (pInstance==NULL) return -EINVAL;
// nothing to delete, the handler have been defined static
return 0;
}
// #################################################################################
AliHLTModulePreprocessor* AliHLTZDCAgent::GetPreprocessor() {
// see header file for class documentation
ALIHLTERRORGUARD(5, "GetPreProcessor not implemented for this module");
return NULL;
}
| 33.236559 | 89 | 0.654804 | [
"object"
] |
de65985ca5604d79a47ec14ec813362b891e3b4e | 12,161 | cpp | C++ | mpvss/mpinterpolation.cpp | ouyun/FnFnCoreWallet | 3aa61145bc3f524d1dc10ada22e164689a73d794 | [
"MIT"
] | 1 | 2019-12-23T11:56:55.000Z | 2019-12-23T11:56:55.000Z | mpvss/mpinterpolation.cpp | ouyun/FnFnCoreWallet | 3aa61145bc3f524d1dc10ada22e164689a73d794 | [
"MIT"
] | null | null | null | mpvss/mpinterpolation.cpp | ouyun/FnFnCoreWallet | 3aa61145bc3f524d1dc10ada22e164689a73d794 | [
"MIT"
] | null | null | null | // Copyright (c) 2017-2019 The Multiverse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "mpinterpolation.h"
#include "curve25519/curve25519.h"
using namespace std;
// [-1/50, 1/50] mod 2^252+27742317777372353535851937790883648493
static const CSC25519 SCInverse[101] =
{
CSC25519({0x1a17ca2895da543aULL,0xe5096a6aa2744012ULL,0xae147ae147ae147aULL,0x2e147ae147ae147ULL}),
CSC25519({0xd6c1048e38e29734ULL,0x703b6f3c1d4691bULL,0xfac687d6343eb1a2ULL,0xd6343eb1a1f58d0ULL}),
CSC25519({0x8e8e2c645252d35cULL,0x656be09b9d9ede3aULL,0x5555555555555555ULL,0xc55555555555555ULL}),
CSC25519({0xed7c29d21ba8e31cULL,0x624022dde9bf9fadULL,0xe4c415c9882b9310ULL,0x882b9310572620aULL}),
CSC25519({0x683b4fb698af7860ULL,0x8017863313c72aacULL,0xbd37a6f4de9bd37aULL,0xcde9bd37a6f4de9ULL}),
CSC25519({0xa34117ad84d07dfdULL,0x26865663f298f3a7ULL,0xc16c16c16c16c16cULL,0xc16c16c16c16c16ULL}),
CSC25519({0x5374c8120dbfc4d1ULL,0x5d90b4396c6e5ad6ULL,0x45d1745d1745d174ULL,0x5d1745d1745d17ULL}),
CSC25519({0x61bd53ee3c7fb44eULL,0xcf9dcac28a50b45ULL,0x82fa0be82fa0be83ULL,0xe82fa0be82fa0beULL}),
CSC25519({0x952a433f04647874ULL,0xfa450432a0281211ULL,0xcf3cf3cf3cf3cf3cULL,0x4f3cf3cf3cf3cf3ULL}),
CSC25519({0x9a59a82eec1dfaa0ULL,0xf60eb453588e963fULL,0x1f3831f3831f3831ULL,0x1f3831f3831f383ULL}),
CSC25519({0xcca6ee3fe9cbd33fULL,0xa8bb41f49c8d1e81ULL,0x9999999999999999ULL,0xb99999999999999ULL}),
CSC25519({0x58034cdd58e3eaf6ULL,0xe2ecf1c57fb64a19ULL,0x2df2df2df2df2df2ULL,0x2df2df2df2df2dfULL}),
CSC25519({0x9ce4a4bb271a74e5ULL,0x1c4d969773cae1f6ULL,0x79435e50d79435e5ULL,0xb5e50d79435e50dULL}),
CSC25519({0x46be53ec5e4655b0ULL,0x2785790fa89a5fefULL,0xacf914c1bacf914cULL,0x914c1bacf914c1bULL}),
CSC25519({0xf60cc4d24ec72881ULL,0x2af02d854681495bULL,0x71c71c71c71c71c7ULL,0xb1c71c71c71c71cULL}),
CSC25519({0x1b0a8c283d0c0fb3ULL,0x9f3f015beec4a6fcULL,0xf8af8af8af8af8afULL,0xf8af8af8af8af8aULL}),
CSC25519({0x72263ac7ddb7bf61ULL,0x1844410f6603d440ULL,0xf0f0f0f0f0f0f0fULL,0x70f0f0f0f0f0f0fULL}),
CSC25519({0x6f4660181255066cULL,0x7cc0f04c909323c8ULL,0x7c1f07c1f07c1f0ULL,0x7c1f07c1f07c1fULL}),
CSC25519({0x7dc2df7c1e86691dULL,0x342d70ac976b081ULL,0x0ULL,0x280000000000000ULL}),
CSC25519({0x72e45a0b4d3a8476ULL,0xee73e2ad70a7324cULL,0xbdef7bdef7bdef7bULL,0xbdef7bdef7bdef7ULL}),
CSC25519({0x48d871f718bdd305ULL,0x2f5a04a69a699f10ULL,0x2222222222222222ULL,0xa22222222222222ULL}),
CSC25519({0xacf858ead3f4130ULL,0x20c4c698645b07a4ULL,0x9611a7b9611a7b96ULL,0xb9611a7b9611a7bULL}),
CSC25519({0x5fbf64de8696b4aeULL,0x7767864bf03c1b1aULL,0xb6db6db6db6db6dbULL,0x76db6db6db6db6dULL}),
CSC25519({0x62af6f06d5bafe0eULL,0xd600eb729c074e96ULL,0x97b425ed097b425eULL,0x425ed097b425ed0ULL}),
CSC25519({0x404f34c0555e071ULL,0x54636aa83f916f26ULL,0xc4ec4ec4ec4ec4ecULL,0x44ec4ec4ec4ec4eULL}),
CSC25519({0x342f94512bb4a874ULL,0xca12d4d544e88024ULL,0x5c28f5c28f5c28f5ULL,0x5c28f5c28f5c28fULL}),
CSC25519({0xc509f5ae47afd2cbULL,0xb5f8c75898461f9eULL,0xaaaaaaaaaaaaaaaaULL,0x8aaaaaaaaaaaaaaULL}),
CSC25519({0x78643c52d4691cd3ULL,0xeb5012878496b882ULL,0x7a6f4de9bd37a6f4ULL,0x9bd37a6f4de9bd3ULL}),
CSC25519({0xa6e990241b7f89a2ULL,0xbb216872d8dcb5acULL,0x8ba2e8ba2e8ba2e8ULL,0xba2e8ba2e8ba2eULL}),
CSC25519({0x2a54867e08c8f0e8ULL,0xf48a086540502423ULL,0x9e79e79e79e79e79ULL,0x9e79e79e79e79e7ULL}),
CSC25519({0x413b796576a1d291ULL,0x3c978a0a9622a02dULL,0x3333333333333333ULL,0x733333333333333ULL}),
CSC25519({0xe1b6e65bf13f15ddULL,0x23bc3350449e2716ULL,0xf286bca1af286bcaULL,0x6bca1af286bca1aULL}),
CSC25519({0x9407268a40987d15ULL,0x4101612bea0af5e1ULL,0xe38e38e38e38e38eULL,0x638e38e38e38e38ULL}),
CSC25519({0xe44c758fbb6f7ec2ULL,0x3088821ecc07a880ULL,0x1e1e1e1e1e1e1e1eULL,0xe1e1e1e1e1e1e1eULL}),
CSC25519({0xfb85bef83d0cd23aULL,0x685ae1592ed6102ULL,0x0ULL,0x500000000000000ULL}),
CSC25519({0x399e80d3d485d21dULL,0x49d50f6e91dba14aULL,0x4444444444444444ULL,0x444444444444444ULL}),
CSC25519({0xbf7ec9bd0d2d695cULL,0xeecf0c97e0783634ULL,0x6db6db6db6db6db6ULL,0xedb6db6db6db6dbULL}),
CSC25519({0x809e6980aabc0e2ULL,0xa8c6d5507f22de4cULL,0x89d89d89d89d89d8ULL,0x89d89d89d89d89dULL}),
CSC25519({0x320188423269d1a9ULL,0x571294d28d94a267ULL,0x5555555555555555ULL,0x155555555555555ULL}),
CSC25519({0x4dd3204836ff1344ULL,0x7642d0e5b1b96b59ULL,0x1745d1745d1745d1ULL,0x1745d1745d1745dULL}),
CSC25519({0x8276f2caed43a522ULL,0x792f14152c45405aULL,0x6666666666666666ULL,0xe66666666666666ULL}),
CSC25519({0x280e4d148130fa2aULL,0x8202c257d415ebc3ULL,0xc71c71c71c71c71cULL,0xc71c71c71c71c71ULL}),
CSC25519({0xf70b7df07a19a474ULL,0xd0b5c2b25dac205ULL,0x0ULL,0xa00000000000000ULL}),
CSC25519({0x26eb305fbd64fecbULL,0xc8bf1f511df8cf93ULL,0xdb6db6db6db6db6dULL,0xdb6db6db6db6db6ULL}),
CSC25519({0x6403108464d3a352ULL,0xae2529a51b2944ceULL,0xaaaaaaaaaaaaaaaaULL,0x2aaaaaaaaaaaaaaULL}),
CSC25519({0xacdb827b7d917657ULL,0xdd7f2e4bb592e3deULL,0xccccccccccccccccULL,0xcccccccccccccccULL}),
CSC25519({0x960498c6973d74fbULL,0x537be77a8bde735ULL,0x0ULL,0x400000000000000ULL}),
CSC25519({0xc8062108c9a746a4ULL,0x5c4a534a3652899cULL,0x5555555555555555ULL,0x555555555555555ULL}),
CSC25519({0x2c09318d2e7ae9f6ULL,0xa6f7cef517bce6bULL,0x0ULL,0x800000000000000ULL}),
CSC25519({0x5812631a5cf5d3ecULL,0x14def9dea2f79cd6ULL,0x0ULL,0x1000000000000000ULL}),
CSC25519({0x0ULL,0x0ULL,0x0ULL,0x0ULL}),
CSC25519({0x1ULL,0x0ULL,0x0ULL,0x0ULL}),
CSC25519({0x2c09318d2e7ae9f7ULL,0xa6f7cef517bce6bULL,0x0ULL,0x800000000000000ULL}),
CSC25519({0x900c4211934e8d49ULL,0xb894a6946ca51339ULL,0xaaaaaaaaaaaaaaaaULL,0xaaaaaaaaaaaaaaaULL}),
CSC25519({0xc20dca53c5b85ef2ULL,0xfa73b66fa39b5a0ULL,0x0ULL,0xc00000000000000ULL}),
CSC25519({0xab36e09edf645d96ULL,0x375fcb92ed64b8f7ULL,0x3333333333333333ULL,0x333333333333333ULL}),
CSC25519({0xf40f5295f822309bULL,0x66b9d03987ce5807ULL,0x5555555555555555ULL,0xd55555555555555ULL}),
CSC25519({0x312732ba9f90d522ULL,0x4c1fda8d84fecd43ULL,0x2492492492492492ULL,0x249249249249249ULL}),
CSC25519({0x6106e529e2dc2f79ULL,0x7d39db37d1cdad0ULL,0x0ULL,0x600000000000000ULL}),
CSC25519({0x30041605dbc4d9c3ULL,0x92dc3786cee1b113ULL,0x38e38e38e38e38e3ULL,0x38e38e38e38e38eULL}),
CSC25519({0xd59b704f6fb22ecbULL,0x9bafe5c976b25c7bULL,0x9999999999999999ULL,0x199999999999999ULL}),
CSC25519({0xa3f42d225f6c0a9ULL,0x9e9c28f8f13e317dULL,0xe8ba2e8ba2e8ba2eULL,0xe8ba2e8ba2e8ba2ULL}),
CSC25519({0x2610dad82a8c0244ULL,0xbdcc650c1562fa6fULL,0xaaaaaaaaaaaaaaaaULL,0xeaaaaaaaaaaaaaaULL}),
CSC25519({0x50087c82524a130bULL,0x6c18248e23d4be8aULL,0x7627627627627627ULL,0x762762762762762ULL}),
CSC25519({0x9893995d4fc86a91ULL,0x260fed46c27f66a1ULL,0x9249249249249249ULL,0x124924924924924ULL}),
CSC25519({0x1e73e246887001d0ULL,0xcb09ea70111bfb8cULL,0xbbbbbbbbbbbbbbbbULL,0xbbbbbbbbbbbbbbbULL}),
CSC25519({0x5c8ca4221fe901b3ULL,0xe594bc9100a3bd3ULL,0x0ULL,0xb00000000000000ULL}),
CSC25519({0x73c5ed8aa186552bULL,0xe45677bfd6eff455ULL,0xe1e1e1e1e1e1e1e1ULL,0x1e1e1e1e1e1e1e1ULL}),
CSC25519({0xc40b3c901c5d56d8ULL,0xd3dd98b2b8eca6f4ULL,0x1c71c71c71c71c71ULL,0x9c71c71c71c71c7ULL}),
CSC25519({0x765b7cbe6bb6be10ULL,0xf122c68e5e5975bfULL,0xd79435e50d79435ULL,0x9435e50d79435e5ULL}),
CSC25519({0x16d6e9b4e654015cULL,0xd8476fd40cd4fca9ULL,0xccccccccccccccccULL,0x8ccccccccccccccULL}),
CSC25519({0x2dbddc9c542ce305ULL,0x2054f17962a778b3ULL,0x6186186186186186ULL,0x618618618618618ULL}),
CSC25519({0xb128d2f641764a4bULL,0x59bd916bca1ae729ULL,0x745d1745d1745d17ULL,0xf45d1745d1745d1ULL}),
CSC25519({0xdfae26c7888cb71aULL,0x298ee7571e60e453ULL,0x8590b21642c8590bULL,0x642c8590b21642cULL}),
CSC25519({0x93086d6c15460122ULL,0x5ee632860ab17d37ULL,0x5555555555555555ULL,0x755555555555555ULL}),
CSC25519({0x23e2cec931412b79ULL,0x4acc25095e0f1cb2ULL,0xa3d70a3d70a3d70aULL,0xa3d70a3d70a3d70ULL}),
CSC25519({0x540d6fce579ff37cULL,0xc07b8f3663662db0ULL,0x3b13b13b13b13b13ULL,0xbb13b13b13b13b1ULL}),
CSC25519({0xf562f413873ad5dfULL,0x3ede0e6c06f04e3fULL,0x684bda12f684bda1ULL,0xbda12f684bda12fULL}),
CSC25519({0xf852fe3bd65f1f3fULL,0x9d777392b2bb81bbULL,0x4924924924924924ULL,0x892492492492492ULL}),
CSC25519({0x4d42dd8bafb692bdULL,0xf41a33463e9c9532ULL,0x69ee58469ee58469ULL,0x469ee58469ee584ULL}),
CSC25519({0xf39f123443800e8ULL,0xe584f538088dfdc6ULL,0xddddddddddddddddULL,0x5ddddddddddddddULL}),
CSC25519({0xe52e090f0fbb4f77ULL,0x266b173132506a89ULL,0x4210842108421084ULL,0x421084210842108ULL}),
CSC25519({0xda4f839e3e6f6ad0ULL,0x119c22d3d980ec54ULL,0x0ULL,0xd80000000000000ULL}),
CSC25519({0xe8cc03024aa0cd81ULL,0x981e09921264790dULL,0xf83e0f83e0f83e0fULL,0xf83e0f83e0f83e0ULL}),
CSC25519({0xe5ec28527f3e148cULL,0xfc9ab8cf3cf3c895ULL,0xf0f0f0f0f0f0f0f0ULL,0x8f0f0f0f0f0f0f0ULL}),
CSC25519({0x3d07d6f21fe9c43aULL,0x759ff882b432f5daULL,0x750750750750750ULL,0x75075075075075ULL}),
CSC25519({0x62059e480e2eab6cULL,0xe9eecc595c76537aULL,0x8e38e38e38e38e38ULL,0x4e38e38e38e38e3ULL}),
CSC25519({0x11540f2dfeaf7e3dULL,0xed5980cefa5d3ce7ULL,0x5306eb3e45306eb3ULL,0x6eb3e45306eb3e4ULL}),
CSC25519({0xbb2dbe5f35db5f08ULL,0xf89163472f2cbadfULL,0x86bca1af286bca1aULL,0x4a1af286bca1af2ULL}),
CSC25519({0xf163d0411e8f7ULL,0x31f20819234152bdULL,0xd20d20d20d20d20dULL,0xd20d20d20d20d20ULL}),
CSC25519({0x8b6b74da732a00aeULL,0x6c23b7ea066a7e54ULL,0x6666666666666666ULL,0x466666666666666ULL}),
CSC25519({0xbdb8baeb70d7d94dULL,0x1ed0458b4a690696ULL,0xe0c7ce0c7ce0c7ceULL,0xe0c7ce0c7ce0c7cULL}),
CSC25519({0xc2e81fdb58915b79ULL,0x1a99f5ac02cf8ac4ULL,0x30c30c30c30c30c3ULL,0xb0c30c30c30c30cULL}),
CSC25519({0xf6550f2c20761f9fULL,0x7e51d327a529190ULL,0x7d05f417d05f417dULL,0x17d05f417d05f41ULL}),
CSC25519({0x49d9b084f360f1cULL,0xb74e45a536894200ULL,0xba2e8ba2e8ba2e8bULL,0xfa2e8ba2e8ba2e8ULL}),
CSC25519({0xb4d14b6cd82555f0ULL,0xee58a37ab05ea92eULL,0x3e93e93e93e93e93ULL,0x3e93e93e93e93e9ULL}),
CSC25519({0xefd71363c4465b8dULL,0x94c773ab8f307229ULL,0x42c8590b21642c85ULL,0x321642c8590b216ULL}),
CSC25519({0x6a963948414cf0d1ULL,0xb29ed700b937fd28ULL,0x1b3bea3677d46cefULL,0x77d46cefa8d9df5ULL}),
CSC25519({0xc98436b60aa30091ULL,0xaf7319430558be9bULL,0xaaaaaaaaaaaaaaaaULL,0x3aaaaaaaaaaaaaaULL}),
CSC25519({0x81515e8c24133cb9ULL,0xddb42eae12333baULL,0x5397829cbc14e5eULL,0x29cbc14e5e0a72fULL}),
CSC25519({0x3dfa98f1c71b7fb3ULL,0x2fd58f7400835cc4ULL,0x51eb851eb851eb85ULL,0xd1eb851eb851eb8ULL}),
};
static const CSC25519* SCInverseZero = &SCInverse[50];
// Lagrange interpolation polynomial. Return f(0)
const uint256 MPLagrange(vector<pair<uint32_t,uint256> >& vShare)
{
CSC25519 s0;
for (size_t i = 0;i < vShare.size();i++)
{
CSC25519 l(1);
for (size_t j = 0;j < vShare.size();j++)
{
if (i != j)
{
l *= *(SCInverseZero + vShare[j].first - vShare[i].first) * vShare[j].first;
}
}
s0 += l * CSC25519(vShare[i].second.begin());
}
return uint256(s0.value);
}
// Newton interpolation polynomial. Return f(0)
// f(x) = f(x0) + (x-x0)*f(x0,x1) + (x-x0)*(x-x1)*f(x0,x1,x2) + ... + (x-x0)*(x-x1)*...*(x - xn-1))*f(x0,x1,...,xn)
//
// vDiffSet:
// f(x0)
// f(x1) f(x0, x1)
// f(x2) f(x1, x2) f(x0, x1, x2)
// f(x3) f(x2, x3) f(x1, x2, x3) f(x0, x1, x2, x3)
// ...
// f(xn) f(xn, xn-1) ... f(x0, x1, ..., xn)
//
// coeff:
// f(x0, x1, ..., xn) = (f(x1, x2, ..., xn) - f(x0, x1, ..., xn-1)) / (xn - x0)
const uint256 MPNewton(vector<pair<uint32_t,uint256> >& vShare)
{
vector<vector<CSC25519> > vDiffSet;
vDiffSet.reserve(vShare.size());
CSC25519 basis(1);
CSC25519 s0;
for (size_t i = 0;i < vShare.size();i++)
{
vector<CSC25519> vDiff;
vDiff.reserve(i + 1);
vDiff.push_back(CSC25519(vShare[i].second.begin()));
for (size_t j = 0; j < i; j++)
{
CSC25519 coeff = vDiff[j] - vDiffSet[i-1][j];
const CSC25519& inverse = *(SCInverseZero + vShare[i].first - vShare[i-j-1].first);
coeff *= inverse;
vDiff.push_back(coeff);
}
s0 += basis * vDiff.back();
basis *= vShare[i].first;
basis.Negative();
vDiffSet.push_back(std::move(vDiff));
}
return uint256(s0.value);
}
| 67.938547 | 115 | 0.832415 | [
"vector"
] |
de67230d350fd894fea86314c301eb220abb4b23 | 5,032 | cc | C++ | tests/test_trie.cc | jfjlaros/trie | b12fe42162be9f43aa245ce000794dd395572c0e | [
"RSA-MD"
] | null | null | null | tests/test_trie.cc | jfjlaros/trie | b12fe42162be9f43aa245ce000794dd395572c0e | [
"RSA-MD"
] | null | null | null | tests/test_trie.cc | jfjlaros/trie | b12fe42162be9f43aa245ce000794dd395572c0e | [
"RSA-MD"
] | null | null | null | #include <catch.hpp>
#include <vector>
#include "../src/trie.tcc"
using std::vector;
TEST_CASE("Trie", "[find][add]") {
Trie<4, Leaf> trie;
SECTION("Find non-existent word") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
REQUIRE(trie.find(word) == NULL);
}
SECTION("Add word") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
Leaf* leaf = trie.add(word);
REQUIRE(leaf != NULL);
REQUIRE(leaf->count == 1);
SECTION("Find newly added word") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
Node<4, Leaf>* node = trie.find(word);
REQUIRE(node != NULL);
REQUIRE(node->leaf->count == 1);
}
SECTION("Add word again") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
Leaf* leaf = trie.add(word);
REQUIRE(leaf->count == 2);
SECTION("Find newly added word again") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
Node<4, Leaf>* node = trie.find(word);
REQUIRE(node != NULL);
REQUIRE(node->leaf->count == 2);
}
SECTION("Remove word") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
trie.remove(word);
Node<4, Leaf>* node = trie.find(word);
REQUIRE(node != NULL);
REQUIRE(node->leaf->count == 1);
SECTION("Remove word again") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
trie.remove(word);
Node<4, Leaf>* node = trie.find(word);
REQUIRE(node == NULL);
SECTION("No prefixes remaining") {
vector<uint8_t> prefix = {0x00, 0x01};
Node<4, Leaf>* node = trie.find(prefix);
REQUIRE(node == NULL);
prefix = {0x00};
node = trie.find(prefix);
REQUIRE(node == NULL);
}
SECTION("Add word after emptying trie") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
Leaf* leaf = trie.add(word);
REQUIRE(leaf != NULL);
REQUIRE(leaf->count == 1);
}
}
}
}
}
SECTION("Add multiple words") {
vector<vector<uint8_t>> words = {
{0x00, 0x01, 0x02},
{0x00, 0x01, 0x03},
{0x00, 0x02, 0x02},
{0x00, 0x02, 0x03},
{0x01, 0x01, 0x02}};
for (vector<uint8_t> word: words) {
trie.add(word);
REQUIRE(trie.find(word) != NULL);
}
SECTION("Traverse") {
size_t i = 0;
for (Result<Leaf> result: trie.walk()) {
REQUIRE(result.leaf->count == 1);
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
SECTION("Hamming") {
vector<uint8_t> word = {0x00, 0x01, 0x03};
vector<vector<uint8_t>> words = {
{0x00, 0x01, 0x02},
{0x00, 0x01, 0x03},
{0x00, 0x02, 0x03}};
size_t i = 0;
for (Result<Leaf> result: trie.hamming(word, 1)) {
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
SECTION("Asymmetric Hamming") {
vector<uint8_t> word = {0x00, 0x01, 0x03};
vector<vector<uint8_t>> words = {
{0x00, 0x01, 0x03},
{0x00, 0x02, 0x03}};
size_t i = 0;
for (Result<Leaf> result: trie.asymmetricHamming(word, 1)) {
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
}
SECTION("Add multiple words of different length") {
vector<vector<uint8_t>> words = {
{0x00, 0x00, 0x01, 0x02},
{0x00, 0x00, 0x02},
{0x00, 0x00, 0x03, 0x02},
{0x00, 0x01},
{0x00, 0x01, 0x02},
{0x00, 0x01, 0x02, 0x03},
{0x00, 0x02},
{0x00, 0x02, 0x02},
{0x00, 0x03}};
for (vector<uint8_t> word: words) {
trie.add(word);
REQUIRE(trie.find(word) != NULL);
}
SECTION("Traverse") {
size_t i = 0;
for (Result<Leaf> result: trie.walk()) {
REQUIRE(result.leaf->count == 1);
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
SECTION("Levenshtein") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
vector<vector<uint8_t>> words = {
{0x00, 0x02},
{0x00, 0x00, 0x02},
{0x00, 0x00, 0x01, 0x02},
{0x00, 0x01},
{0x00, 0x01, 0x02},
{0x00, 0x01, 0x02, 0x03},
{0x00, 0x01, 0x02},
{0x00, 0x02, 0x02},
{0x00, 0x00, 0x01, 0x02}};
size_t i = 0;
for (Result<Leaf> result: trie.levenshtein(word, 1)) {
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
SECTION("Asymmetric Levenshtein") {
vector<uint8_t> word = {0x00, 0x01, 0x02};
vector<vector<uint8_t>> words = {
{0x00, 0x02},
{0x00, 0x01},
{0x00, 0x01, 0x02},
{0x00, 0x01, 0x02, 0x03},
{0x00, 0x01, 0x02},
{0x00, 0x02, 0x02},
{0x00, 0x00, 0x01, 0x02}};
size_t i = 0;
for (Result<Leaf> result: trie.asymmetricLevenshtein(word, 1)) {
REQUIRE(result.path == words[i++]);
}
REQUIRE(i == words.size());
}
}
}
| 25.938144 | 70 | 0.515302 | [
"vector"
] |
de69980248be27ad44b088170884859a79a15150 | 7,223 | cc | C++ | src/d3d11/d3d11_view_rtv.cc | R2Northstar/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | 3 | 2022-02-17T03:11:52.000Z | 2022-02-20T21:20:16.000Z | src/d3d11/d3d11_view_rtv.cc | pg9182/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | null | null | null | src/d3d11/d3d11_view_rtv.cc | pg9182/NorthstarStubs | e60bba45092f7fdb70b60c0e2e920584f78f1b85 | [
"Zlib"
] | 2 | 2022-02-17T14:04:09.000Z | 2022-02-20T17:52:55.000Z | #include "d3d11_buffer.h"
#include "d3d11_device.h"
#include "d3d11_device_child.h"
#include "d3d11_include.h"
#include "d3d11_resource.h"
#include "d3d11_texture.h"
#include "d3d11_view_rtv.h"
namespace dxvk {
D3D11RenderTargetView::D3D11RenderTargetView(
D3D11Device* pDevice,
ID3D11Resource* pResource,
const D3D11_RENDER_TARGET_VIEW_DESC1* pDesc)
: D3D11DeviceChild<ID3D11RenderTargetView1>(pDevice),
m_resource(pResource), m_desc(*pDesc) {
ResourceAddRefPrivate(m_resource);
}
D3D11RenderTargetView::~D3D11RenderTargetView() {
ResourceReleasePrivate(m_resource);
}
HRESULT STDMETHODCALLTYPE D3D11RenderTargetView::QueryInterface(REFIID riid, void** ppvObject) {
if (ppvObject == nullptr)
return E_POINTER;
*ppvObject = nullptr;
if (riid == __uuidof(IUnknown)
|| riid == __uuidof(ID3D11DeviceChild)
|| riid == __uuidof(ID3D11View)
|| riid == __uuidof(ID3D11RenderTargetView)
|| riid == __uuidof(ID3D11RenderTargetView1)) {
*ppvObject = ref(this);
return S_OK;
}
DXVK_LOG_UNK_IFACE(riid);
return E_NOINTERFACE;
}
void STDMETHODCALLTYPE D3D11RenderTargetView::GetResource(ID3D11Resource** ppResource) {
*ppResource = ref(m_resource);
}
void STDMETHODCALLTYPE D3D11RenderTargetView::GetDesc(D3D11_RENDER_TARGET_VIEW_DESC* pDesc) {
pDesc->Format = m_desc.Format;
pDesc->ViewDimension = m_desc.ViewDimension;
switch (m_desc.ViewDimension) {
case D3D11_RTV_DIMENSION_UNKNOWN:
break;
case D3D11_RTV_DIMENSION_BUFFER:
pDesc->Buffer = m_desc.Buffer;
break;
case D3D11_RTV_DIMENSION_TEXTURE1D:
pDesc->Texture1D = m_desc.Texture1D;
break;
case D3D11_RTV_DIMENSION_TEXTURE1DARRAY:
pDesc->Texture1DArray = m_desc.Texture1DArray;
break;
case D3D11_RTV_DIMENSION_TEXTURE2D:
pDesc->Texture2D.MipSlice = m_desc.Texture2D.MipSlice;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DARRAY:
pDesc->Texture2DArray.MipSlice = m_desc.Texture2DArray.MipSlice;
pDesc->Texture2DArray.FirstArraySlice = m_desc.Texture2DArray.FirstArraySlice;
pDesc->Texture2DArray.ArraySize = m_desc.Texture2DArray.ArraySize;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMS:
pDesc->Texture2DMS = m_desc.Texture2DMS;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY:
pDesc->Texture2DMSArray = m_desc.Texture2DMSArray;
break;
case D3D11_RTV_DIMENSION_TEXTURE3D:
pDesc->Texture3D = m_desc.Texture3D;
break;
}
}
void STDMETHODCALLTYPE D3D11RenderTargetView::GetDesc1(D3D11_RENDER_TARGET_VIEW_DESC1* pDesc) {
*pDesc = m_desc;
}
HRESULT D3D11RenderTargetView::GetDescFromResource(
ID3D11Resource* pResource,
D3D11_RENDER_TARGET_VIEW_DESC1* pDesc) {
D3D11_RESOURCE_DIMENSION resourceDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
pResource->GetType(&resourceDim);
switch (resourceDim) {
case D3D11_RESOURCE_DIMENSION_TEXTURE1D: {
D3D11_TEXTURE1D_DESC resourceDesc;
static_cast<D3D11Texture1D*>(pResource)->GetDesc(&resourceDesc);
pDesc->Format = resourceDesc.Format;
if (resourceDesc.ArraySize == 1) {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D;
pDesc->Texture1D.MipSlice = 0;
} else {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY;
pDesc->Texture1DArray.MipSlice = 0;
pDesc->Texture1DArray.FirstArraySlice = 0;
pDesc->Texture1DArray.ArraySize = resourceDesc.ArraySize;
}
} return S_OK;
case D3D11_RESOURCE_DIMENSION_TEXTURE2D: {
D3D11_TEXTURE2D_DESC resourceDesc;
static_cast<D3D11Texture2D*>(pResource)->GetDesc(&resourceDesc);
pDesc->Format = resourceDesc.Format;
if (resourceDesc.SampleDesc.Count == 1) {
if (resourceDesc.ArraySize == 1) {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
pDesc->Texture2D.MipSlice = 0;
pDesc->Texture2D.PlaneSlice = 0;
} else {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
pDesc->Texture2DArray.MipSlice = 0;
pDesc->Texture2DArray.FirstArraySlice = 0;
pDesc->Texture2DArray.ArraySize = resourceDesc.ArraySize;
pDesc->Texture2DArray.PlaneSlice = 0;
}
} else {
if (resourceDesc.ArraySize == 1) {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
} else {
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
pDesc->Texture2DMSArray.FirstArraySlice = 0;
pDesc->Texture2DMSArray.ArraySize = resourceDesc.ArraySize;
}
}
} return S_OK;
case D3D11_RESOURCE_DIMENSION_TEXTURE3D: {
D3D11_TEXTURE3D_DESC resourceDesc;
static_cast<D3D11Texture3D*>(pResource)->GetDesc(&resourceDesc);
pDesc->Format = resourceDesc.Format;
pDesc->ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
pDesc->Texture3D.MipSlice = 0;
pDesc->Texture3D.FirstWSlice = 0;
pDesc->Texture3D.WSize = resourceDesc.Depth;
} return S_OK;
default:
DXVK_LOG("err", "Unsupported dimension for render target view: %d", resourceDim);
return E_INVALIDARG;
}
}
D3D11_RENDER_TARGET_VIEW_DESC1 D3D11RenderTargetView::PromoteDesc(
const D3D11_RENDER_TARGET_VIEW_DESC* pDesc,
UINT Plane) {
D3D11_RENDER_TARGET_VIEW_DESC1 dstDesc;
dstDesc.Format = pDesc->Format;
dstDesc.ViewDimension = pDesc->ViewDimension;
switch (pDesc->ViewDimension) {
case D3D11_RTV_DIMENSION_UNKNOWN:
break;
case D3D11_RTV_DIMENSION_BUFFER:
dstDesc.Buffer = pDesc->Buffer;
break;
case D3D11_RTV_DIMENSION_TEXTURE1D:
dstDesc.Texture1D = pDesc->Texture1D;
break;
case D3D11_RTV_DIMENSION_TEXTURE1DARRAY:
dstDesc.Texture1DArray = pDesc->Texture1DArray;
break;
case D3D11_RTV_DIMENSION_TEXTURE2D:
dstDesc.Texture2D.MipSlice = pDesc->Texture2D.MipSlice;
dstDesc.Texture2D.PlaneSlice = Plane;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DARRAY:
dstDesc.Texture2DArray.MipSlice = pDesc->Texture2DArray.MipSlice;
dstDesc.Texture2DArray.FirstArraySlice = pDesc->Texture2DArray.FirstArraySlice;
dstDesc.Texture2DArray.ArraySize = pDesc->Texture2DArray.ArraySize;
dstDesc.Texture2DArray.PlaneSlice = Plane;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMS:
dstDesc.Texture2DMS = pDesc->Texture2DMS;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY:
dstDesc.Texture2DMSArray = pDesc->Texture2DMSArray;
break;
case D3D11_RTV_DIMENSION_TEXTURE3D:
dstDesc.Texture3D = pDesc->Texture3D;
break;
}
return dstDesc;
}
}
| 32.245536 | 98 | 0.665236 | [
"render"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.