hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
80256ee05f2edfc46da778f9d02243586a9fe46f
4,832
cc
C++
usr_local/src/festival/src/arch/festival/ngram.cc
parnurzeal/tts-tutorial
db11aed2adc5101cc6d06d1138f74d5f5afe666f
[ "Apache-2.0" ]
30
2016-09-23T06:38:08.000Z
2022-02-14T02:02:14.000Z
usr_local/src/festival/src/arch/festival/ngram.cc
xbsdsongnan/docker-festival
1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6
[ "Apache-2.0" ]
3
2020-06-05T18:09:02.000Z
2021-06-10T20:06:02.000Z
usr_local/src/festival/src/arch/festival/ngram.cc
xbsdsongnan/docker-festival
1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6
[ "Apache-2.0" ]
13
2016-11-06T05:52:23.000Z
2020-08-26T18:38:00.000Z
/*************************************************************************/ /* */ /* Centre for Speech Technology Research */ /* University of Edinburgh, UK */ /* Copyright (c) 1996,1997 */ /* All Rights Reserved. */ /* */ /* Permission is hereby granted, free of charge, to use and distribute */ /* this software and its documentation without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of this work, and to */ /* permit persons to whom this work is furnished to do so, subject to */ /* the following conditions: */ /* 1. The code must retain the above copyright notice, this list of */ /* conditions and the following disclaimer. */ /* 2. Any modifications must be clearly marked as such. */ /* 3. Original authors' names are not deleted. */ /* 4. The authors' names are not used to endorse or promote products */ /* derived from this software without specific prior written */ /* permission. */ /* */ /* THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK */ /* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */ /* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ /* SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE */ /* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */ /* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */ /* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */ /* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */ /* THIS SOFTWARE. */ /* */ /*************************************************************************/ /* Authors: Alan W Black */ /* Date : December 1997 */ /*-----------------------------------------------------------------------*/ /* Access to the Ngrammar */ /* */ /*=======================================================================*/ #include <cstdio> #include "festival.h" #include "festivalP.h" static LISP ngram_loaded_list = NIL; static EST_Ngrammar *load_ngram(const EST_String &filename); static LISP add_ngram(const EST_String &name,EST_Ngrammar *n); SIOD_REGISTER_CLASS(ngrammar,EST_Ngrammar) static LISP lisp_load_ngram(LISP name, LISP filename) { EST_Ngrammar *n; n = load_ngram(get_c_string(filename)); add_ngram(get_c_string(name),n); return name; } static EST_Ngrammar *load_ngram(const EST_String &filename) { EST_Ngrammar *n = new EST_Ngrammar(); if (n->load(filename) != 0) { fprintf(stderr,"Ngrammar: failed to read ngrammar from \"%s\"", (const char *)filename); festival_error(); } return n; } static LISP add_ngram(const EST_String &name,EST_Ngrammar *n) { LISP lpair; lpair = siod_assoc_str(name,ngram_loaded_list); if (ngram_loaded_list == NIL) { // First time round so do a little initialization gc_protect(&ngram_loaded_list); } LISP ng = siod(n); if (lpair == NIL) ngram_loaded_list = cons(cons(strintern(name),cons(ng,NIL)),ngram_loaded_list); else { cwarn << "Ngrammar: " << name << " recreated" << endl; setcar(cdr(lpair),ng); } return ng; } EST_Ngrammar *get_ngram(const EST_String &name,const EST_String &filename) { // Find ngram named name, returns NULL if none; LISP lpair; lpair = siod_assoc_str(name,ngram_loaded_list); if (lpair == NIL) { if (filename != EST_String::Empty) { EST_Ngrammar *n = load_ngram(filename); add_ngram(name,n); return n; } else { cwarn << "Ngrammar: no ngram named \"" << name << "\"" << endl; return 0; } } else return ngrammar(car(cdr(lpair))); } void festival_ngram_init() { init_subr_2("ngram.load",lisp_load_ngram, "(ngram.load NAME FILENAME)\n\ Load an ngram from FILENAME and store it named NAME for later access."); }
37.457364
75
0.505174
parnurzeal
802bfd99f355e276d81944eeb98a2d0f0d00fdb7
8,183
cpp
C++
Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "Exporter.h" #include <AzCore/Math/Vector2.h> #include <AzCore/Math/Quaternion.h> namespace ExporterLib { void CopyVector2(EMotionFX::FileFormat::FileVector2& to, const AZ::Vector2& from) { to.mX = from.GetX(); to.mY = from.GetY(); } void CopyVector(EMotionFX::FileFormat::FileVector3& to, const AZ::PackedVector3f& from) { to.mX = from.GetX(); to.mY = from.GetY(); to.mZ = from.GetZ(); } void CopyQuaternion(EMotionFX::FileFormat::FileQuaternion& to, const AZ::Quaternion& from) { AZ::Quaternion q = from; if (q.GetW() < 0.0f) { q = -q; } to.mX = q.GetX(); to.mY = q.GetY(); to.mZ = q.GetZ(); to.mW = q.GetW(); } void Copy16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion& to, const AZ::Quaternion& from) { AZ::Quaternion q = from; if (q.GetW() < 0.0f) { q = -q; } const MCore::Compressed16BitQuaternion compressedQuat(q); to.mX = compressedQuat.mX; to.mY = compressedQuat.mY; to.mZ = compressedQuat.mZ; to.mW = compressedQuat.mW; } void Copy16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion& to, const MCore::Compressed16BitQuaternion& from) { MCore::Compressed16BitQuaternion q = from; if (q.mW < 0) { q.mX = -q.mX; q.mY = -q.mY; q.mZ = -q.mZ; q.mW = -q.mW; } to.mX = q.mX; to.mY = q.mY; to.mZ = q.mZ; to.mW = q.mW; } void CopyColor(const MCore::RGBAColor& from, EMotionFX::FileFormat::FileColor& to) { to.mR = from.r; to.mG = from.g; to.mB = from.b; to.mA = from.a; } void ConvertUnsignedInt(uint32* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertUnsignedInt32(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertInt(int* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertSignedInt32(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertUnsignedShort(uint16* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertUnsignedInt16(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFloat(float* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileChunk(EMotionFX::FileFormat::FileChunk* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertUnsignedInt32(&value->mChunkID, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mSizeInBytes, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mVersion, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileColor(EMotionFX::FileFormat::FileColor* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->mR, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mG, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mB, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mA, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileVector2(EMotionFX::FileFormat::FileVector2* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileVector3(EMotionFX::FileFormat::FileVector3* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFile16BitVector3(EMotionFX::FileFormat::File16BitVector3* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertUnsignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileQuaternion(EMotionFX::FileFormat::FileQuaternion* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFile16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertSignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertSignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertSignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertSignedInt16(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileMotionEvent(EMotionFX::FileFormat::FileMotionEvent* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->mStartTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->mEndTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mEventTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mMirrorTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt16(&value->mParamIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileMotionEventTable(EMotionFX::FileFormat::FileMotionEventTrack* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertUnsignedInt32(&value->mNumEvents, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mNumTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mNumParamStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertUnsignedInt32(&value->mNumMirrorTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertRGBAColor(MCore::RGBAColor* value, MCore::Endian::EEndianType targetEndianType) { MCore::Endian::ConvertFloat(&value->r, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->g, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->b, EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&value->a, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertVector3(AZ::PackedVector3f* value, MCore::Endian::EEndianType targetEndianType) { float* data = reinterpret_cast<float*>(value); MCore::Endian::ConvertFloat(&data[0], EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&data[1], EXPLIB_PLATFORM_ENDIAN, targetEndianType); MCore::Endian::ConvertFloat(&data[2], EXPLIB_PLATFORM_ENDIAN, targetEndianType); } } // namespace ExporterLib
40.310345
158
0.695222
aaarsene
802e9c367d218d9f58b162804d0b8470d0ff89d1
2,202
hpp
C++
src/Resources.hpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
4
2019-12-19T17:08:04.000Z
2020-09-20T08:31:15.000Z
src/Resources.hpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
null
null
null
src/Resources.hpp
ArthurSonzogni/pigami
bc33ed2797ba1da534d9cd4337e59d33ce46d4c5
[ "MIT" ]
null
null
null
// Copyright 2019 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. #ifndef RESOURCE_HPP #define RESOURCE_HPP #include <list> #include <smk/Font.hpp> #include <smk/OpenGL.hpp> #include <smk/SoundBuffer.hpp> #include <smk/Texture.hpp> #include <variant> std::string ResourcePath(); std::string SavePath(); void PlaySound(const smk::SoundBuffer& snd); void SyncFilesystem(); extern smk::Font font_arial; extern smk::Texture texture_block; extern smk::Texture texture_bouton1; extern smk::Texture texture_bouton2; extern smk::Texture texture_bouton3; extern smk::Texture texture_box; extern smk::Texture texture_box_press_enter; extern smk::Texture texture_box_title; extern smk::Texture texture_dalle; extern smk::Texture texture_dalleback; extern smk::Texture texture_fragile1; extern smk::Texture texture_fragile2; extern smk::Texture texture_fragile3; extern smk::Texture texture_left_arrow; extern smk::Texture texture_level_background; extern smk::Texture texture_level_circle; extern smk::Texture texture_number_little; extern smk::Texture texture_number; extern smk::Texture texture_press_enter; extern smk::Texture texture_retractable; extern smk::Texture texture_right_arrow; extern smk::Texture texture_skybox_back; extern smk::Texture texture_skybox_bottom; extern smk::Texture texture_skybox_front; extern smk::Texture texture_skybox_left; extern smk::Texture texture_skybox_right; extern smk::Texture texture_skybox_top; extern smk::SoundBuffer sound_background; extern smk::SoundBuffer sound_fermeture; extern smk::SoundBuffer sound_ouverture; extern smk::SoundBuffer sound_win; extern smk::SoundBuffer sound_lose; extern smk::SoundBuffer sound_menu_change; extern smk::SoundBuffer sound_menu_select; extern smk::SoundBuffer sound_press_enter; extern smk::SoundBuffer sound_success; class ResourceInitializer { public: ResourceInitializer(); struct Resource { smk::Font* font = nullptr; smk::Texture* texture = nullptr; smk::SoundBuffer* soundbuffer = nullptr; std::string* path = nullptr; void Load(); }; std::list<Resource> resources; }; #endif // RESOURCE_HPP
29.756757
78
0.800182
ArthurSonzogni
802fbb6528162c2b00424ecf1be9bbd263fc6648
13,922
cpp
C++
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
1
2017-08-17T15:28:24.000Z
2017-08-17T15:28:24.000Z
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
examples/basic/pipelines.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
/* * Vulkan Example - Using different pipelines in one single renderpass * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanExampleBase.h" // Vertex layout for this example std::vector<vkx::VertexLayout> vertexLayout = { vkx::VertexLayout::VERTEX_LAYOUT_POSITION, vkx::VertexLayout::VERTEX_LAYOUT_NORMAL, vkx::VertexLayout::VERTEX_LAYOUT_UV, vkx::VertexLayout::VERTEX_LAYOUT_COLOR }; static vk::PhysicalDeviceFeatures features = [] { vk::PhysicalDeviceFeatures features; features.wideLines = VK_TRUE; return features; }(); class VulkanExample : public vkx::ExampleBase { public: struct { vk::PipelineVertexInputStateCreateInfo inputState; std::vector<vk::VertexInputBindingDescription> bindingDescriptions; std::vector<vk::VertexInputAttributeDescription> attributeDescriptions; } vertices; struct { vkx::MeshBuffer cube; } meshes; vkx::UniformData uniformDataVS; // Same uniform buffer layout as shader struct UboVS { glm::mat4 projection; glm::mat4 modelView; glm::vec4 lightPos = glm::vec4(0.0f, 2.0f, 1.0f, 0.0f); } uboVS; vk::PipelineLayout pipelineLayout; vk::DescriptorSet descriptorSet; vk::DescriptorSetLayout descriptorSetLayout; struct { vk::Pipeline phong; vk::Pipeline wireframe; vk::Pipeline toon; } pipelines; VulkanExample() : vkx::ExampleBase(ENABLE_VALIDATION) { camera.setZoom(-10.5f); camera.setRotation({ -25.0f, 15.0f, 0.0f }); enableTextOverlay = true; title = "Vulkan Example - vk::Pipeline state objects"; } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class device.destroyPipeline(pipelines.phong); if (deviceFeatures.fillModeNonSolid) { device.destroyPipeline(pipelines.wireframe); } device.destroyPipeline(pipelines.toon); device.destroyPipelineLayout(pipelineLayout); device.destroyDescriptorSetLayout(descriptorSetLayout); meshes.cube.destroy(); device.destroyBuffer(uniformDataVS.buffer); device.freeMemory(uniformDataVS.memory); } void updateDrawCommandBuffer(const vk::CommandBuffer& cmdBuffer) { cmdBuffer.setScissor(0, vkx::rect2D(size)); cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr); cmdBuffer.bindVertexBuffers(VERTEX_BUFFER_BIND_ID, meshes.cube.vertices.buffer, { 0 }); cmdBuffer.bindIndexBuffer(meshes.cube.indices.buffer, 0, vk::IndexType::eUint32); // Left : Solid colored vk::Viewport viewport = vkx::viewport((float)size.width / 3, (float)size.height, 0.0f, 1.0f); cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.phong); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); // Center : Toon viewport.x += viewport.width; cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.toon); cmdBuffer.setLineWidth(2.0f); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); auto lineWidthGranularity = deviceProperties.limits.lineWidthGranularity; auto lineWidthRange = deviceProperties.limits.lineWidthRange; if (deviceFeatures.fillModeNonSolid) { // Right : Wireframe viewport.x += viewport.width; cmdBuffer.setViewport(0, viewport); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.wireframe); cmdBuffer.drawIndexed(meshes.cube.indexCount, 1, 0, 0, 0); } } void loadMeshes() { meshes.cube = loadMesh(getAssetPath() + "models/treasure_smooth.dae", vertexLayout, 1.0f); } void setupVertexDescriptions() { // Binding description vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0] = vkx::vertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, vkx::vertexSize(vertexLayout), vk::VertexInputRate::eVertex); // Attribute descriptions // Describes memory layout and shader positions vertices.attributeDescriptions.resize(4); // Location 0 : Position vertices.attributeDescriptions[0] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, vk::Format::eR32G32B32Sfloat, 0); // Location 1 : Color vertices.attributeDescriptions[1] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, vk::Format::eR32G32B32Sfloat, sizeof(float) * 3); // Location 3 : Texture coordinates vertices.attributeDescriptions[2] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, vk::Format::eR32G32Sfloat, sizeof(float) * 6); // Location 2 : Normal vertices.attributeDescriptions[3] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, vk::Format::eR32G32B32Sfloat, sizeof(float) * 8); vertices.inputState = vk::PipelineVertexInputStateCreateInfo(); vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { std::vector<vk::DescriptorPoolSize> poolSizes = { vkx::descriptorPoolSize(vk::DescriptorType::eUniformBuffer, 1) }; vk::DescriptorPoolCreateInfo descriptorPoolInfo = vkx::descriptorPoolCreateInfo(poolSizes.size(), poolSizes.data(), 2); descriptorPool = device.createDescriptorPool(descriptorPoolInfo); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vkx::descriptorSetLayoutBinding( vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eVertex, 0) }; vk::DescriptorSetLayoutCreateInfo descriptorLayout = vkx::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), setLayoutBindings.size()); descriptorSetLayout = device.createDescriptorSetLayout(descriptorLayout); vk::PipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vkx::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); pipelineLayout = device.createPipelineLayout(pPipelineLayoutCreateInfo); } void setupDescriptorSet() { vk::DescriptorSetAllocateInfo allocInfo = vkx::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); descriptorSet = device.allocateDescriptorSets(allocInfo)[0]; std::vector<vk::WriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Vertex shader uniform buffer vkx::writeDescriptorSet( descriptorSet, vk::DescriptorType::eUniformBuffer, 0, &uniformDataVS.descriptor) }; device.updateDescriptorSets(writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { vk::PipelineInputAssemblyStateCreateInfo inputAssemblyState = vkx::pipelineInputAssemblyStateCreateInfo(vk::PrimitiveTopology::eTriangleList, vk::PipelineInputAssemblyStateCreateFlags(), VK_FALSE); vk::PipelineRasterizationStateCreateInfo rasterizationState = vkx::pipelineRasterizationStateCreateInfo(vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise); vk::PipelineColorBlendAttachmentState blendAttachmentState = vkx::pipelineColorBlendAttachmentState(); vk::PipelineColorBlendStateCreateInfo colorBlendState = vkx::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); vk::PipelineDepthStencilStateCreateInfo depthStencilState = vkx::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, vk::CompareOp::eLessOrEqual); vk::PipelineViewportStateCreateInfo viewportState = vkx::pipelineViewportStateCreateInfo(1, 1); vk::PipelineMultisampleStateCreateInfo multisampleState = vkx::pipelineMultisampleStateCreateInfo(vk::SampleCountFlagBits::e1); std::vector<vk::DynamicState> dynamicStateEnables = { vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eLineWidth, }; vk::PipelineDynamicStateCreateInfo dynamicState = vkx::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), dynamicStateEnables.size()); std::array<vk::PipelineShaderStageCreateInfo, 2> shaderStages; // Phong shading pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/phong.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/phong.frag.spv", vk::ShaderStageFlagBits::eFragment); vk::GraphicsPipelineCreateInfo pipelineCreateInfo = vkx::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); // We are using this pipeline as the base for the other pipelines (derivatives) // vk::Pipeline derivatives can be used for pipelines that share most of their state // Depending on the implementation this may result in better performance for pipeline // switchting and faster creation time pipelineCreateInfo.flags = vk::PipelineCreateFlagBits::eAllowDerivatives; // Textured pipeline pipelines.phong = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; // All pipelines created after the base pipeline will be derivatives pipelineCreateInfo.flags = vk::PipelineCreateFlagBits::eDerivative; // Base pipeline will be our first created pipeline pipelineCreateInfo.basePipelineHandle = pipelines.phong; // It's only allowed to either use a handle or index for the base pipeline // As we use the handle, we must set the index to -1 (see section 9.5 of the specification) pipelineCreateInfo.basePipelineIndex = -1; // Toon shading pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/toon.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/toon.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.toon = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; // Non solid rendering is not a mandatory Vulkan feature if (deviceFeatures.fillModeNonSolid) { // vk::Pipeline for wire frame rendering rasterizationState.polygonMode = vk::PolygonMode::eLine; shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelines/wireframe.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelines/wireframe.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.wireframe = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; } } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Create the vertex shader uniform buffer block uniformDataVS = createUniformBuffer(uboVS); updateUniformBuffers(); } void updateUniformBuffers() { uboVS.projection = glm::perspective(glm::radians(60.0f), (float)(size.width / 3.0f) / (float)size.height, 0.001f, 256.0f); uboVS.modelView = camera.matrices.view; uniformDataVS.copy(uboVS); } void prepare() { ExampleBase::prepare(); loadMeshes(); setupVertexDescriptions(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); updateDrawCommandBuffers(); prepared = true; } void render() override { if (!prepared) return; draw(); } void viewChanged() override { updateUniformBuffers(); } void getOverlayText(vkx::TextOverlay *textOverlay) override { textOverlay->addText("Phong shading pipeline", (float)size.width / 6.0f, size.height - 35.0f, vkx::TextOverlay::alignCenter); textOverlay->addText("Toon shading pipeline", (float)size.width / 2.0f, size.height - 35.0f, vkx::TextOverlay::alignCenter); textOverlay->addText("Wireframe pipeline", size.width - (float)size.width / 6.5f, size.height - 35.0f, vkx::TextOverlay::alignCenter); } }; RUN_EXAMPLE(VulkanExample)
42.445122
147
0.690777
ChristophLGDV
803281f2c8659764d6d54a8f9605c242e4bce664
8,435
cxx
C++
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PHOS/DA/PHSGAINda.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/* contact: Boris.Polishchuk@cern.ch link: see comments in the $ALICE_ROOT/PHOS/AliPHOSRcuDA1.cxx reference run: /alice/data/2009/LHC09b_PHOS/000075883/raw/09000075883017.20.root run type: PHYSICS DA type: MON number of events needed: 1000 input files: Mod0RCU0.data Mod0RCU1.data Mod0RCU2.data Mod0RCU3.data Mod1RCU0.data Mod1RCU1.data Mod1RCU2.data Mod1RCU3.data Mod2RCU0.data Mod2RCU1.data Mod2RCU2.data Mod2RCU3.data Mod3RCU0.data Mod3RCU1.data Mod3RCU2.data Mod3RCU3.data Mod4RCU0.data Mod4RCU1.data Mod4RCU2.data Mod4RCU3.data zs.txt Output files: PHOS_Calib_Total.root contains cumulative statistics for a number of runs. Trigger types used: PHYSICS */ #include "event.h" #include "monitor.h" extern "C" { #include "daqDA.h" } #include <stdio.h> #include <stdlib.h> #include <TSystem.h> #include <TROOT.h> #include <TPluginManager.h> #include "AliRawReader.h" #include "AliRawReaderDate.h" #include "AliPHOSRcuDA1.h" #include "AliPHOSRawFitterv0.h" #include "AliCaloAltroMapping.h" #include "AliCaloRawStreamV3.h" #include "AliLog.h" /* Main routine Arguments: 1- monitoring data source */ int main(int argc, char **argv) { gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); AliLog::SetGlobalDebugLevel(0) ; AliLog::SetGlobalLogLevel(AliLog::kFatal); int status; if (argc!=2) { printf("Wrong number of arguments\n"); return -1; } /* Retrieve ZS parameters from DAQ DB */ const char* zsfile = "zs.txt"; int failZS = daqDA_DB_getFile(zsfile, zsfile); Int_t offset,threshold; if(!failZS) { FILE *f = fopen(zsfile,"r"); int scan = fscanf(f,"%d %d",&offset,&threshold); } /* Retrieve mapping files from DAQ DB */ const char* mapFiles[20] = { "Mod0RCU0.data", "Mod0RCU1.data", "Mod0RCU2.data", "Mod0RCU3.data", "Mod1RCU0.data", "Mod1RCU1.data", "Mod1RCU2.data", "Mod1RCU3.data", "Mod2RCU0.data", "Mod2RCU1.data", "Mod2RCU2.data", "Mod2RCU3.data", "Mod3RCU0.data", "Mod3RCU1.data", "Mod3RCU2.data", "Mod3RCU3.data", "Mod4RCU0.data", "Mod4RCU1.data", "Mod4RCU2.data", "Mod4RCU3.data" }; for(Int_t iFile=0; iFile<20; iFile++) { int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]); if(failed) { printf("Cannot retrieve file %s from DAQ DB. Exit.\n",mapFiles[iFile]); return -1; } } /* Open mapping files */ AliAltroMapping *mapping[20]; TString path = "./"; path += "Mod"; TString path2; TString path3; Int_t iMap = 0; for(Int_t iMod = 0; iMod < 5; iMod++) { path2 = path; path2 += iMod; path2 += "RCU"; for(Int_t iRCU=0; iRCU<4; iRCU++) { path3 = path2; path3 += iRCU; path3 += ".data"; mapping[iMap] = new AliCaloAltroMapping(path3.Data()); iMap++; } } /* define data source : this is argument 1 */ status=monitorSetDataSource( argv[1] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* declare monitoring program */ status=monitorDeclareMp( __FILE__ ); if (status!=0) { printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status)); return -1; } /* define wait event timeout - 1s max */ monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); /* init some counters */ int nevents_physics=0; int nevents_total=0; AliRawReader *rawReader = NULL; AliPHOSRcuDA1* dAs[5]; for(Int_t iMod=0; iMod<5; iMod++) { dAs[iMod] = 0; } Float_t e[64][56][2]; Float_t t[64][56][2]; for(Int_t iX=0; iX<64; iX++) { for(Int_t iZ=0; iZ<56; iZ++) { for(Int_t iGain=0; iGain<2; iGain++) { e[iX][iZ][iGain] = 0.; t[iX][iZ][iGain] = 0.; } } } Int_t cellX = -1; Int_t cellZ = -1; Int_t nBunches = 0; Int_t sigStart, sigLength; Int_t caloFlag; /* main loop (infinite) */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* check shutdown condition */ if (daqDA_checkShutdown()) {break;} /* get next event (blocking call until timeout) */ status=monitorGetEventDynamic((void **)&event); if (status==MON_ERR_EOF) { printf ("End of File detected\n"); break; /* end of monitoring file has been reached */ } if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); break; } /* retry if got no event */ if (event==NULL) { continue; } /* use event - here, just write event id to result file */ eventT=event->eventType; if (eventT==PHYSICS_EVENT) { rawReader = new AliRawReaderDate((void*)event); AliCaloRawStreamV3 stream(rawReader,"PHOS",mapping); AliPHOSRawFitterv0 fitter; fitter.SubtractPedestals(kTRUE); // assume that data is non-ZS if(!failZS) { fitter.SubtractPedestals(kFALSE); fitter.SetAmpOffset(offset); fitter.SetAmpThreshold(threshold); } while (stream.NextDDL()) { while (stream.NextChannel()) { /* Retrieve ZS parameters from data*/ if(failZS) { short value = stream.GetAltroCFG1(); bool ZeroSuppressionEnabled = (value >> 15) & 0x1; bool AutomaticBaselineSubtraction = (value >> 14) & 0x1; if(ZeroSuppressionEnabled) { offset = (value >> 10) & 0xf; threshold = value & 0x3ff; fitter.SubtractPedestals(kFALSE); fitter.SetAmpOffset(offset); fitter.SetAmpThreshold(threshold); } } cellX = stream.GetCellX(); cellZ = stream.GetCellZ(); caloFlag = stream.GetCaloFlag(); // 0=LG, 1=HG, 2=TRU if(caloFlag!=0 && caloFlag!=1) continue; //TRU data! // In case of oscillating signals with ZS, //a channel can have several bunches. nBunches = 0; while (stream.NextBunch()) { nBunches++; if (nBunches > 1) continue; sigStart = stream.GetStartTimeBin(); sigLength = stream.GetBunchLength(); fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag); fitter.Eval(stream.GetSignals(),sigStart,sigLength); } // End of NextBunch() if (nBunches != 1) continue; e[cellX][cellZ][caloFlag] = fitter.GetEnergy(); t[cellX][cellZ][caloFlag] = fitter.GetTime(); } if(stream.GetModule()<0 || stream.GetModule()>4) continue; if(dAs[stream.GetModule()]) dAs[stream.GetModule()]->FillHistograms(e,t); else { dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0); dAs[stream.GetModule()]->FillHistograms(e,t); } for(Int_t iX=0; iX<64; iX++) { for(Int_t iZ=0; iZ<56; iZ++) { for(Int_t iGain=0; iGain<2; iGain++) { e[iX][iZ][iGain] = 0.; t[iX][iZ][iGain] = 0.; } } } } // da1.FillHistograms(e,t); // //da1.UpdateHistoFile(); delete rawReader; nevents_physics++; } nevents_total++; /* free resources */ free(event); /* exit when last event received, no need to wait for TERM signal */ if (eventT==END_OF_RUN) { printf("EOR event detected\n"); break; } } for(Int_t i = 0; i < 20; i++) delete mapping[i]; /* Be sure that all histograms are saved */ char h2name[80]; char totfile[80]; //Write the Total file (accumulated statistics for number of runs) sprintf(totfile,"PHOS_Calib_Total.root"); TFile * ftot = new TFile(totfile,"recreate"); // if (!ftot->IsZombie()){ // printf("Updating file %s.\n",ftot->GetName()); // for(Int_t iMod=0; iMod<5; iMod++) { // if(!dAs[iMod]) continue; // printf("DA1 for module %d detected.\n",iMod); // for(Int_t iX=0; iX<64; iX++) { // for(Int_t iZ=0; iZ<56; iZ++) { // for(Int_t iGain=0; iGain<2; iGain++) { // sprintf(h2name,"%d_%d_%d_%d",iMod,iX,iZ,iGain); // TH2F* h2tot = (TH2F*)ftot->Get(h2name); // const TH2F* h2run = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); // Time vs Energy // if(!h2tot && h2run) h2run->Write(); // if(h2tot && h2run) { h2tot->Add(h2run); h2tot->Write(h2tot->GetName(),TObject::kWriteDelete); } // } // } // } // } // } ftot->Close(); /* Store output files to the File Exchange Server */ daqDA_FES_storeFile(totfile,"AMPLITUDES"); return status; }
25.104167
299
0.617427
AllaMaevskaya
8036b66785a8f2df901b1356846d14daf8b024e7
14,732
hpp
C++
include/numberTheory.hpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
include/numberTheory.hpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
include/numberTheory.hpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#pragma once #include <bits/stdc++.h> #include "primary.hpp" using LL = long long; // 注意这里的 nthPrime 以 1 开始编号(其它地方以 0 开始)!即 p[1] = 2 namespace Prime { // O(\sqrt{N}) 最基本的单次素数判断 bool isPrime(LL n) { if (n == 2) return true; if (n == 1 || n % 2 == 0) return false; for (LL i = 3; i * i <= n; i += 2){ if (n % i == 0) return false; } return true; } // 预处理判断所有素数 constexpr int N = 1e7 + 2; bool isp[N]; // 此算法复杂度为 O(N \log \log N),实测 N < 1e9 时是最快的 std::vector<int> initPrime() { std::vector<int> p{0, 2}; isp[2] = true; for (int i = 3; i < N; i += 2) isp[i] = true; int sq = int(std::sqrt(N + 0.1)) | 1; for (int i = 3; i <= sq; i += 2) if (isp[i]) { p.emplace_back(i); for (int j = i * i; j < N; j += i << 1) isp[j] = false; } for (int i = sq + 2; i < N; i += 2) if (isp[i]) p.emplace_back(i); return p; } // 此算法是 $O(N)$ 的,但实测不如上面算法快。 std::vector<int> initPrimeS() { // 放在此处仅供记录。 std::vector<int> p{0, 2}; isp[2] = true; for (int i = 3; i < N; i += 2) isp[i] = true; for (int i = 3; i < N; i += 2) { if (isp[i]) p.emplace_back(i); for (int j = 2, t = (N - 1) / i + 1, np = p.size(); j < np && p[j] < t; ++j) { // 用除号是防止溢出 isp[i * p[j]] = false; // 不要下面的一步的话,复杂度 O(nloglogn), 但是不用除法,常数小 if (i % p[j] == 0) break; } } return p; } // 计算 pi(x),理论:https://dna049.com/computationOfPiX // 这里预处理 N = 1e7, M = 7 是最好的(预处理 200ms)。 // 如果 x 特别大,例 1e13 < x < 1e15,建议 N = 1e8, M = 8(预处理耗时很大,2s) constexpr int M = 7; // 请不要超过 8,M = 9 已经没有什么意义了。 int pi[N]; std::vector<int> p; std::vector<std::vector<int>> phi(M + 1); void init() { p = initPrime(); pi[2] = 1; for (int i = 3; i < N; ++i) { pi[i] = pi[i - 1]; if (isp[i]) ++pi[i]; } std::vector<int> sz(M + 1, 1); for (int i = 1; i <= M; ++i) sz[i] = p[i] * sz[i - 1]; phi[0] = {1}; // 注意这里 phi[0] 本质是无意义的 // 对本质逻辑 phi[j][i] = phi[j][i - 1] - phi[j / p[i]][i - 1]; 的细节和空间优化 for (int i = 1; i <= M; ++i) { phi[i].resize(sz[i]); for (int j = 0; j < p[i]; ++j) { for (int k = 0, jsz = j * sz[i - 1]; k < sz[i - 1]; ++k) { phi[i][jsz + k] = j * phi[i - 1].back() + phi[i - 1][k]; } } for (int k = 0; k < sz[i - 1]; ++k) { for (int j = 0, kp = k * p[i]; j < p[i]; ++j) { phi[i][kp + j] -= phi[i - 1][k]; } } } } LL primepi(LL x); LL primephi(LL x, int s) { if (s <= M) return (x / phi[s].size()) * phi[s].back() + phi[s][x % phi[s].size()]; if (x / p[s] <= p[s]) return primepi(x) - s + 1; if (x / p[s] / p[s] <= p[s] && x < N) { int s2x = pi[(int)(std::sqrt(x + 0.2))]; LL ans = pi[x] - (s2x + s - 2) * (s2x - s + 1) / 2; for (int i = s + 1; i <= s2x; ++i) { ans += pi[x / p[i]]; } return ans; } return primephi(x, s - 1) - primephi(x / p[s], s - 1); } LL primepi(LL x) { if (x < N) return pi[x]; int ps2x = primepi(int(std::sqrt(x + 0.2))); int ps3x = primepi(int(std::cbrt(x + 0.2))); LL ans = primephi(x, ps3x) + 1LL * (ps2x + ps3x - 2) * (ps2x - ps3x + 1) / 2; for (int i = ps3x + 1, ed = ps2x; i <= ed; ++i) { ans -= primepi(x / p[i]); } return ans; } // 动态规划版 O(\frac{n}{\log n}) 计算 pi(x),x < 10^12 LL primepiS(LL n) { int rn = std::sqrt(n + 0.2); std::vector<LL> R(rn + 1); for (int i = 1; i <= rn; ++i) R[i] = n / i - 1; int ln = n / (rn + 1) + 1; std::vector<LL> L(ln + 1); for (int i = 1; i <= ln; ++i) L[i] = i - 1; for (int p = 2; p <= rn; ++p) { if (L[p] == L[p - 1]) continue; for (int i = 1, tn = std::min(n / p / p, LL(rn)); i <= tn; ++i) { R[i] -= (i <= rn / p ? R[i * p] : L[n / i / p]) - L[p - 1]; } for (int i = ln; i / p >= p; --i) { L[i] -= L[i / p] - L[p - 1]; } } return R[1]; } // 查看 (s - n, s] (请保证区间较小)内每个数是否为素数,确保 p.back() * p.back() >= r std::vector<int> seive(LL s, int n) { // O(N log s) std::vector<int> isP(n, 1); // isP[i] = 1 表示 s - i 是素数 for (int i = 1; 1LL * p[i] * p[i] <= s; ++i) { for (int j = s % p[i]; j < n; j += p[i]) isP[j] = 0; } return isP; } // 使用前先初始化,返回第 n 个素数,从 1 开始标号 LL nthPrime(LL n) { // Newton 梯度法 if (n < (int)p.size()) return p[n]; LL ans = n * log(n), err = log(n) / log(10); LL m = primepi(ans); while (m < n || m > n + err) { ans += (n - m) / (log(m) - 1) * log(m) * log(m); m = primepi(ans); } int sn = std::sqrt(N); while (1) { auto isP = seive(ans, sn); for (int i = 0; i < sn; ++i) if (isP[i]) { if (m-- == n) return ans - i; } ans -= sn; } } // 原理:https://dna049.com/nthPrimeNumber/ } // namespace Prime // 单次求 Euler 函数 LL getPhi(LL n) { if (n % 2 == 0) n /= 2; LL r = n; while (n % 2 == 0) n /= 2; for (LL i = 3; i * i <= n; i += 2) { if (n % i == 0) { r = r / i * (i - 1); while (n % i == 0) n /= i; } } if (n > 1) r = r / n * (n - 1); return r; } // O(N \log \log N) 预处理 Euler 函数(不推荐) std::vector<int> initPhiS(int N) { std::vector<int> phi(N); for (int i = 1; i < N; i += 2) phi[i] = i; for (int i = 2; i < N; i += 2) phi[i] = i >> 1; for (int i = 3; i < N; i += 2) { if (phi[i] != i) continue; for (int j = i; j < N; j += i) phi[j] = phi[j] / i * (i - 1); } return phi; } // 函数 O(N) 预处理 Euler 函数 std::vector<int> initPhi(int N) { std::vector<int> phi(N), p{0, 2}; for (int i = 1; i < N; i += 2) phi[i] = i; for (int i = 2; i < N; i += 2) phi[i] = i >> 1; for (int i = 3; i < N; i += 2) { if (phi[i] == i) p.emplace_back(i), --phi[i]; for (int j = 2, t = (N - 1) / i + 1, np = p.size(); j < np && p[j] < t; ++j) { if (i % p[j] == 0) { phi[i * p[j]] = phi[i] * p[j]; break; } phi[i * p[j]] = phi[i] * (p[j] - 1); } } for (int i = 2; i < N; i += 4) phi[i] = phi[i >> 1]; for (int i = 4; i < N; i += 4) phi[i] = phi[i >> 1] << 1; return phi; } // 单次求 Mobius 函数(完全类似于单次欧拉函数)。 int getMu(LL n){ if (n % 4 == 0) return 0; int r = (n % 2 ? 1 : -1); if (n % 2 == 0) n /= 2; for (LL i = 3; i * i <= n; i += 2){ if (n % i == 0) { n /= i; if (n % i == 0) return 0; r = -r; } } return n > 1 ? -r : r; } // O(n log n) 预处理 Mobius 函数 std::vector<int> initMuS(int N) { std::vector<int> mu(N); mu[1] = 1; for (int i = 1; i < N; ++i) { for (int j = i * 2; j < N; j += i) { mu[j] -= mu[i]; } } return mu; } // O(n) 预处理版本 Mobius 函数 std::vector<int> initMu(int N) { std::vector<int> mu(N), p{0, 2}; for (int i = 1; i < N; i += 2) mu[i] = i; for (int i = 3; i < N; i += 2) { if (mu[i] == i) mu[i] = -1, p.emplace_back(i); for (int j = 2, t = (N - 1) / i + 1, np = p.size(); j < np && p[j] < t; ++j) { if (i % p[j] == 0) { mu[i * p[j]] = 0; break; } mu[i * p[j]] = -mu[i]; } } for (int i = 2; i < N; i += 4) mu[i] = -mu[i >> 1]; return mu; } // min_25 筛法 O(n^{\frac{2}{3}}) 求 Euler 函数前缀和 以及 Mobius 函数(绝对值)前缀和 namespace min_25 { // 请勿使用二维记忆化搜索的 map constexpr int N = 5e6 + 2; // Euler 函数前缀和 std::vector<LL> sumPhi(N); std::unordered_map<LL, LL> mpPhi; // 可选 unordered_map 是因为这些都是确定的数不会被 hack void initSumPhi() { auto phi = initPhi(N); for (int i = 1; i < N; ++i) sumPhi[i] = sumPhi[i - 1] + phi[i]; } LL getSumPhi(LL n) { if (n < N) return sumPhi[n]; if (mpPhi.count(n)) return mpPhi[n]; LL r = (n + 1) * n / 2; for (LL i = 2, j; i <= n; i = j + 1) { j = n / (n / i); r -= (j - i + 1) * getSumPhi(n / i); } return mpPhi[n] = r; } // Mobius 函数(绝对值)前缀和 std::vector<int> mu(N), sumMu(N); std::unordered_map<LL, int> mpMu; // 可选 unordered_map 是因为这些都是确定的数不会被 hack void initSumMu() { mu = initMu(N); for (int i = 1; i < N; ++i) sumMu[i] = sumMu[i - 1] + mu[i]; } // 当答案超过 int 时,n 已经大到没法计算了,因此可认为返回值为 int。 int getSumMu(LL n) { if (n < N) return sumMu[n]; if (mpMu.count(n)) return mpMu[n]; LL r = 1; for (LL i = 2, j; i <= n; i = j + 1) { j = n / (n / i); r -= (j - i + 1) * getSumMu(n / i); } return mpMu[n] = r; } // Mobius 函数绝对值前缀和 LL getAbsSum(LL n) { // Q(n) = Q(n-1) + |mu(n)| LL r = 0; for (LL i = 1; i * i < n; ++i) { r += mu[i] * (n / i / i); } return r; } } // namespace min_25 // 模板例题:https://www.luogu.com.cn/problem/P4213 // O(N) 预处理所有数的最小素因子 std::vector<int> spf(int N) { std::vector<int> sp(N), p{0, 2}; for (int i = 2; i < N; i += 2) sp[i] = 2; for (int i = 1; i < N; i += 2) sp[i] = i; for (int i = 3; i < N; i += 2) { if (sp[i] == i) p.emplace_back(i); for (int j = 2, np = p.size(); j < np && p[j] <= sp[i] && i * p[j] < N; ++j) { sp[i * p[j]] = p[j]; // 注意到sp只被赋值一次 } } return sp; } // O(N) 预处理所有数的(是否算重)素因子个数 std::pair<std::vector<int>, std::vector<int>> npf(int N) { std::vector<int> np(N, 1), nps(N, 1), p{0, 2}; nps[0] = nps[1] = 0; np[0] = np[1] = 0; for (int i = 3; i < N; i += 2) { if (nps[i] == 1) p.emplace_back(i); for (int j = 2, t, pSize = p.size(); j < pSize && (t = i * p[j]) < N; ++j) { nps[t] = nps[i] + 1; np[t] = np[i]; if (i % p[j] == 0) break; ++np[t]; } } for (int i = 2; i < N; i += 4) np[i] = np[i >> 1] + 1; for (int i = 4; i < N; i += 4) np[i] = np[i >> 1]; for (int i = 2; i < N; i += 2) nps[i] = nps[i >> 1] + 1; return {np, nps}; } // 获取全部不同素因子 std::vector<int> factor(int n, const std::vector<int> &sp) { std::vector<int> ans; while (n > 1) { int pn = sp[n]; ans.emplace_back(pn); while (n % pn == 0) n /= pn; } return ans; } // 获取全部素因子 std::vector<std::pair<int, int>> Factor(int n, const std::vector<int> &sp) { std::vector<std::pair<int, int>> ans; while (n > 1) { int pn = sp[n], cnt = 0; while (n % pn == 0) n /= pn, ++cnt; ans.emplace_back(pn, cnt); } return ans; } // 返回最小原根,无的话返回 0 int primitiveRoot(int n, const std::vector<int> &sp) { if (n < 2) return 0; if (n == 2 || n == 4) return n - 1; if (n % 4 == 0) return 0; int n2 = n % 2 == 0 ? n / 2 : n; int pn = sp[n2]; while (n2 % pn == 0) n2 /= pn; if (n2 != 1) return 0; auto fp = factor(pn - 1, sp); auto check = [&](int i) { for (auto x : fp) { if (powMod(i, (pn - 1) / x, pn) == 1) return false; } return true; }; int ans = 2; while (!check(ans)) ++ans; n2 = n % 2 == 0 ? n / 2 : n; if (n2 != pn) { int m = n2 / pn * (pn - 1); auto fm = factor(m, sp); for (auto x : fp) { if (powMod(ans, m / x, m) == 1) { ans += pn; break; } } } if (n2 != n && (ans % 2 == 0)) ans += n2; return ans; } // 返回所有原根,若无返回空 std::vector<int> primitiveRootAllS(int n, const std::vector<int> &sp) { int g = primitiveRoot(n, sp); if (g == 0) return {}; if (n == 2 || n == 4) return {n - 1}; int n2 = n & 1 ? n : n / 2; int pn = sp[n2], m = n2 / pn * (pn - 1), now = g; std::vector<int> ans{g}; for (int i = 2; i < m; ++i) { now = 1LL * now * g % n; if (std::gcd(i, m) == 1) ans.emplace_back(now); } std::sort(ans.begin(), ans.end()); return ans; } // 返回所有原根,若无返回空 std::vector<int> primitiveRootAll(int n, const std::vector<int> &sp) { if (n < 2) return {}; if (n == 2 || n == 4) return {n - 1}; if (n % 4 == 0) return {}; int n2 = n % 2 == 0 ? n / 2 : n, pn = sp[n2]; while (n2 % pn == 0) n2 /= pn; if (n2 != 1) return {}; int m = (n & 1 ? n : n / 2) / pn * (pn - 1); std::vector<int> vis(n, -1), ans; for (int i = 2; i < n; ++i) if (vis[i] == -1 && std::gcd(i, n) == 1) { bool flag = true; int now = 1; for (int j = 1; j < m; ++j) { now = 1LL * now * i % n; if (now == 1) { flag = false; break; } if (std::gcd(j, m) == 1) vis[now] = i; else vis[now] = 0; } if (flag) { // 此时 i 必然是最小原根 for (int j = 0; j < n; ++j) if (vis[j] == i) { ans.emplace_back(j); } return ans; } } return {}; } // 模板例题:https://www.luogu.com.cn/problem/P6091 // 大素数 Miller-Rabin 概率判别法 和 大整数的最 大/小 因子分解 namespace PollardRho { std::mt19937_64 rnd(std::chrono::steady_clock::now().time_since_epoch().count()); LL powModll(LL x, LL n, LL p) { LL r = 1; while (n) { if (n&1) r = __int128(r) * x % p; n >>= 1; x = __int128(x) * x % p; } return r; } // 1 < a < n,若 n 是素数,那么 a^(n - 1) = 1 mod n // m - 1 = m * 2 ^ t,返回 false 表示判断失败 bool witness(LL a, LL n, LL m, int t) { LL x = powModll(a, m, n); if (x == 1 || x == n - 1) return false; while (t--) { x = __int128(x) * x % n; if (x == n - 1) return false; } return true; } constexpr int TIMES = 52; bool rabin(LL n) { if (n < 2) return false; if (n == 2) return true; if (n % 2 == 0) return false; LL m = n - 1; int t = __builtin_ctzll(m); m >>= t; for (int cnt = 0; cnt < TIMES; ++cnt) { LL a = rnd() % (n - 1) + 1; if (witness(a, n, m, t)) return false; } return true; } LL pollardrho(LL n) { LL x = 0, y = 0, z = 1, i = 1, k = 2, c = rnd() % (n - 1) + 1; while (true) { x = (__int128(x) * x + c) % n; z = __int128(y - x + n) * z % n; // 累计 gcd 一次计算!太猛了啊 茶茶白 if (++i == k) { LL d = std::__gcd(z, n); if (d > 1) return d; y = x; if (k > n) return n; k <<= 1; } } } LL spf(LL n) { if (rabin(n) || n == 1) return n; LL d = n; while (d == n) d = pollardrho(n); return std::min(spf(d), spf(n / d)); } LL gpf(LL n, LL mxf = 1) { if (rabin(n)) return n; if (n <= mxf) return 1; LL d = n; while (d == n) d = pollardrho(n); LL res = gpf(d, mxf); return std::max(res, gpf(n / d, std::max(res, mxf))); } } // namespace PollardRho // 离散对数:返回最小的 x 使得 a^x = b mod p,p 为素数,无解输出 -1。 int babyStepGiantStep(int a, int b, int p) { a %= p, b %= p; if (a == 0) return b % p ? -1 : 1; if (b == 1) return 0; int cnt = 0, t = 1; for (int g = std::gcd(a, p); g != 1; g = std::gcd(a, p)) { if (b % g) return -1; p /= g, b /= g, t = 1LL * t * (a / g) % p; ++cnt; if (b == t) return cnt; } std::map<int, int> mp; int m = std::sqrt(p + 0.1) + 1; int base = b; for (int i = 0; i != m; ++i) { mp[base] = i; base = 1LL * base * a % p; } base = powMod(a, m, p); for (int i = 1; i <= m + 1; ++i) { t = 1ll * t * base % p; if (mp.count(t)) return (1LL * i * m - mp[t] + cnt) % p; } return -1; } // 模板例题:https://www.luogu.com.cn/problem/P3846 // 模素数开方:返回 x 使得 x^2 = a mod p, 无解输出 -1。复杂度 $O(\log^2 p)$ int sqrtModp(int a, int p) { // p 为素数,0 <= a < p < INT_MAX。 if (a == 0 || p == 2) return a; auto pow = [p](int x, int n) { int r = 1; while (n) { if (n&1) r = 1LL * r * x % p; n >>= 1; x = 1LL * x * x % p; } return r; }; int q = (p - 1) / 2; if (pow(a, q) != 1) return -1; if (q & 1) return pow(a, (q + 1) / 2); int b; // 寻找一个非二次剩余 std::mt19937 rnd(std::chrono::steady_clock::now().time_since_epoch().count()); while (pow(b = rnd() % (p - 1) + 1, q) == 1); int c = __builtin_ctzll(q); q >>= c; // p - 1 = q << (c + 1) b = pow(b, q); int x = pow(a, (q + 1) / 2), t = pow(a, q); // 始终保持 x^2 = a t, t^{2^c} = 1, b^{2^c} = -1 while (t != 1) { // 返回最小的 r 使得 u^{2^r} = -1 int cc = [p](int u) { int r = 0; while ((u = 1LL * u * u % p) != 1) ++r; return r; }(t); int d = pow(b, 1LL << (c - cc - 1)); // d^{2^{cc + 1}} = -1 // 更新原理 (xd)^2 = a t d^2, (t d^2)^{2^{cc}} = 1, (d^2)^{2^cc} = -1 x = 1LL * x * d % p; b = 1LL * d * d % p; t = 1LL * t * b % p; c = cc; } return x; } // 模板例题:https://www.luogu.com.cn/problem/P5491
25.891037
92
0.47278
GoatGirl98
80394afa90cf9774eeef2235550b565ee8bc07fa
2,805
hpp
C++
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
6
2020-09-12T19:16:49.000Z
2022-03-17T14:10:16.000Z
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
1
2021-11-15T10:13:17.000Z
2021-11-15T10:13:17.000Z
Ruken/Source/Include/Build/Config.hpp
Renondedju/Ruken
2b2944b0c7aabf0f921f4daafc45eb01e592d825
[ "MIT" ]
3
2020-09-03T16:41:35.000Z
2022-01-24T09:35:55.000Z
/* * MIT License * * Copyright (c) 2019-2020 Basile Combet, Philippe Yi * * 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 NON INFRINGEMENT. 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. */ #pragma once // ------------------------------ // Global Settings #define RUKEN_CONFIG_LEVEL_DEBUG 0 #define RUKEN_CONFIG_LEVEL_RELEASE 1 #ifndef NDEBUG #define RUKEN_CONFIG_LEVEL RUKEN_CONFIG_LEVEL_DEBUG #define RUKEN_CONFIG_DEBUG #define RUKEN_CONFIG_STR "Debug" #else #define RUKEN_CONFIG_LEVEL RUKEN_CONFIG_LEVEL_RELEASE #define RUKEN_CONFIG_RELEASE #define RUKEN_CONFIG_STR "Release" #endif #define RUKEN_DEBUG if constexpr(RUKEN_CONFIG_LEVEL == RUKEN_CONFIG_LEVEL_DEBUG) #define RUKEN_RELEASE if constexpr(RUKEN_CONFIG_LEVEL == RUKEN_CONFIG_LEVEL_RELEASE) // ------------------------------ // Threading #if !defined(no_multithread) && defined(__STDCPP_THREADS__) && !defined(RUKEN_REQUEST_SINGLE_THREADED_BUILD) #define RUKEN_MULTITHREAD_ENABLED #define RUKEN_MULTITHREAD_STATUS_STR "Enabled" #else #define RUKEN_MULTITHREAD_DISABLED #define RUKEN_MULTITHREAD_STATUS_STR "Disabled" #endif // ------------------------------ // Resource management #if defined(RUKEN_CONFIG_DEBUG) #define RUKEN_RESOURCE_MANIFEST_STORE_IDENTIFIER #endif // ------------------------------ // ECS // Sets the maximum number of components allowed by the ECS, keep this number // as low as possible. Must be a power of 2 with a minimum of 8. #define RUKEN_MAX_ECS_COMPONENTS 64 // ------------------------------ // Logging #if !defined(RUKEN_REQUEST_SILENT_BUILD) #define RUKEN_LOGGING_ENABLED #define RUKEN_LOGGING_STATUS_STR "Enabled" #else #define RUKEN_LOGGING_DISABLED #define RUKEN_LOGGING_STATUS_STR "Disabled" #endif
35.0625
108
0.714795
Renondedju
803a544d85582452b50445351d82a42e9d22c0eb
11,855
cpp
C++
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
r_mux/source/r_muxer.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
#include "r_mux/r_muxer.h" #include "r_mux/r_format_utils.h" #include "r_utils/r_string_utils.h" #include "r_utils/r_exception.h" #include <stdexcept> using namespace std; using namespace r_mux; using namespace r_utils; using namespace r_utils::r_std_utils; AVCodecID r_mux::encoding_to_av_codec_id(const string& codec_name) { auto lower_codec_name = r_string_utils::to_lower(codec_name); if(lower_codec_name == "h264") return AV_CODEC_ID_H264; else if(lower_codec_name == "h265" || lower_codec_name == "hevc") return AV_CODEC_ID_HEVC; else if(lower_codec_name == "mp4a-latm") return AV_CODEC_ID_AAC_LATM; else if(lower_codec_name == "mpeg4-generic") return AV_CODEC_ID_AAC; else if(lower_codec_name == "pcmu") return AV_CODEC_ID_PCM_MULAW; R_THROW(("Unknown codec name.")); } r_muxer::r_muxer(const std::string& path, bool output_to_buffer) : _path(path), _output_to_buffer(output_to_buffer), _buffer(), _fc([](AVFormatContext* fc){avformat_free_context(fc);}), _video_stream(nullptr), _audio_stream(nullptr), _needs_finalize(false), _video_bsf([](AVBSFContext* bsf){av_bsf_free(&bsf);}), _audio_bsf([](AVBSFContext* bsf){av_bsf_free(&bsf);}) { avformat_alloc_output_context2(&_fc.raw(), NULL, NULL, _path.c_str()); if(!_fc) R_THROW(("Unable to create libavformat output context")); if(_fc.get()->oformat->flags & AVFMT_GLOBALHEADER) _fc.get()->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; _fc.get()->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; } r_muxer::~r_muxer() { if(_needs_finalize) finalize(); } void r_muxer::add_video_stream(AVRational frame_rate, AVCodecID codec_id, uint16_t w, uint16_t h, int profile, int level) { auto codec = avcodec_find_encoder(codec_id); if(!codec) R_THROW(("Unable to find encoder stream.")); _video_stream = avformat_new_stream(_fc.get(), codec); if(!_video_stream) R_THROW(("Unable to allocate AVStream.")); _video_stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; _video_stream->codecpar->codec_id = codec_id; _video_stream->codecpar->width = w; _video_stream->codecpar->height = h; _video_stream->codecpar->format = AV_PIX_FMT_YUV420P; _video_stream->codecpar->profile = profile; _video_stream->codecpar->level = level; _video_stream->time_base.num = frame_rate.den; _video_stream->time_base.den = frame_rate.num; } void r_muxer::add_audio_stream(AVCodecID codec_id, uint8_t channels, uint32_t sample_rate) { auto codec = avcodec_find_encoder(codec_id); _audio_stream = avformat_new_stream(_fc.get(), codec); if(!_audio_stream) R_THROW(("Unable to allocate AVStream")); _audio_stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; _audio_stream->codecpar->codec_id = codec_id; _audio_stream->codecpar->channels = channels; _audio_stream->codecpar->sample_rate = sample_rate; _audio_stream->time_base.num = 1; _audio_stream->time_base.den = sample_rate; } void r_muxer::set_video_bitstream_filter(const std::string& filter_name) { const AVBitStreamFilter *filter = av_bsf_get_by_name(filter_name.c_str()); if(!filter) R_THROW(("Unable to find bitstream filter.")); auto ret = av_bsf_alloc(filter, &_video_bsf.raw()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_alloc()")); ret = avcodec_parameters_copy(_video_bsf.get()->par_in, _video_stream->codecpar); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); ret = av_bsf_init(_video_bsf.get()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_init()")); ret = avcodec_parameters_copy(_video_stream->codecpar, _video_bsf.get()->par_out); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); } void r_muxer::set_audio_bitstream_filter(const std::string& filter_name) { const AVBitStreamFilter *filter = av_bsf_get_by_name(filter_name.c_str()); if(!filter) R_THROW(("Unable to find bitstream filter.")); auto ret = av_bsf_alloc(filter, &_audio_bsf.raw()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_alloc()")); ret = avcodec_parameters_copy(_audio_bsf.get()->par_in, _audio_stream->codecpar); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); ret = av_bsf_init(_audio_bsf.get()); if(ret < 0) R_STHROW(r_internal_exception, ("Unable to av_bsf_init()")); ret = avcodec_parameters_copy(_audio_stream->codecpar, _audio_bsf.get()->par_out); if (ret < 0) R_STHROW(r_internal_exception, ("Unable to avcodec_parameters_copy()")); } void r_muxer::set_video_extradata(const std::vector<uint8_t>& ed) { if(!ed.empty()) { if(_video_stream->codecpar->extradata) av_free(_video_stream->codecpar->extradata); _video_stream->codecpar->extradata = (uint8_t*)av_malloc(ed.size()); memcpy(_video_stream->codecpar->extradata, &ed[0], ed.size()); _video_stream->codecpar->extradata_size = (int)ed.size(); } } void r_muxer::set_audio_extradata(const std::vector<uint8_t>& ed) { if(!ed.empty()) { if(_audio_stream->codecpar->extradata) av_free(_audio_stream->codecpar->extradata); _audio_stream->codecpar->extradata = (uint8_t*)av_malloc(ed.size()); memcpy(_audio_stream->codecpar->extradata, &ed[0], ed.size()); _audio_stream->codecpar->extradata_size = (int)ed.size(); } } void r_muxer::open() { if(_fc.get()->nb_streams < 1) R_THROW(("Please add a stream before opening this muxer.")); if(_output_to_buffer) { int res = avio_open_dyn_buf(&_fc.get()->pb); if(res < 0) R_THROW(("Unable to allocate a memory IO object: %s", ff_rc_to_msg(res).c_str())); } else { int res = avio_open(&_fc.get()->pb, _path.c_str(), AVIO_FLAG_WRITE); if(res < 0) R_THROW(("Unable to open output io context: %s", ff_rc_to_msg(res).c_str())); } int res = avformat_write_header(_fc.get(), NULL); if(res < 0) R_THROW(("Unable to write header to output file: %s", ff_rc_to_msg(res).c_str())); _needs_finalize = true; } static void _get_packet_defaults(AVPacket* pkt) { pkt->buf = nullptr; pkt->pts = AV_NOPTS_VALUE; pkt->dts = AV_NOPTS_VALUE; pkt->data = nullptr; pkt->size = 0; pkt->stream_index = 0; pkt->flags = 0; pkt->side_data = nullptr; pkt->side_data_elems = 0; pkt->duration = 0; pkt->pos = -1; } void r_muxer::write_video_frame(uint8_t* p, size_t size, int64_t input_pts, int64_t input_dts, AVRational input_time_base, bool key) { if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); raii_ptr<AVPacket> input_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(input_pkt.get()); input_pkt.get()->stream_index = _video_stream->index; input_pkt.get()->data = p; input_pkt.get()->size = (int)size; input_pkt.get()->pts = av_rescale_q(input_pts, input_time_base, _video_stream->time_base); input_pkt.get()->dts = av_rescale_q(input_dts, input_time_base, _video_stream->time_base); input_pkt.get()->flags |= (key)?AV_PKT_FLAG_KEY:0; if(_video_bsf) { int res = av_bsf_send_packet(_video_bsf.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to send packet to bitstream filter: %s", ff_rc_to_msg(res).c_str())); while(res == 0) { raii_ptr<AVPacket> output_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(output_pkt.get()); res = av_bsf_receive_packet(_video_bsf.get(), output_pkt.get()); if(res == 0) { res = av_interleaved_write_frame(_fc.get(), output_pkt.get()); if(res < 0) R_THROW(("Unable to write frame to output file: %s", ff_rc_to_msg(res).c_str())); } else if(res == AVERROR(EAGAIN)) { // no output packet, needs more input break; } else R_THROW(("Unable to receive packet from bitstream filter: %s", ff_rc_to_msg(res).c_str())); } } else { int res = av_interleaved_write_frame(_fc.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to write video frame to output file: %s", ff_rc_to_msg(res).c_str())); } } void r_muxer::write_audio_frame(uint8_t* p, size_t size, int64_t input_pts, AVRational input_time_base) { if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); if(_fc.get()->pb == nullptr) R_THROW(("Please call open() before writing frames.")); raii_ptr<AVPacket> input_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(input_pkt.get()); input_pkt.get()->stream_index = _audio_stream->index; input_pkt.get()->data = p; input_pkt.get()->size = (int)size; input_pkt.get()->pts = av_rescale_q(input_pts, input_time_base, _audio_stream->time_base); input_pkt.get()->dts = input_pkt.get()->pts; input_pkt.get()->flags = AV_PKT_FLAG_KEY; if(_audio_bsf) { int res = av_bsf_send_packet(_audio_bsf.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to send packet to bitstream filter: %s", ff_rc_to_msg(res).c_str())); while(res == 0) { raii_ptr<AVPacket> output_pkt(av_packet_alloc(), [](AVPacket* pkt){av_packet_free(&pkt);}); _get_packet_defaults(output_pkt.get()); res = av_bsf_receive_packet(_audio_bsf.get(), output_pkt.get()); if(res == 0) { res = av_interleaved_write_frame(_fc.get(), output_pkt.get()); if(res < 0) R_THROW(("Unable to write frame to output file: %s", ff_rc_to_msg(res).c_str())); } else if(res == AVERROR(EAGAIN)) { // no output packet, needs more input break; } else R_THROW(("Unable to receive packet from bitstream filter: %s", ff_rc_to_msg(res).c_str())); } } else { int res = av_interleaved_write_frame(_fc.get(), input_pkt.get()); if(res < 0) R_THROW(("Unable to write audio frame to output file: %s", ff_rc_to_msg(res).c_str())); } } void r_muxer::finalize() { if(_needs_finalize) { _needs_finalize = false; int res = av_write_trailer(_fc.get()); if(res < 0) R_THROW(("Unable to write trailer to output file: %s", ff_rc_to_msg(res).c_str())); if(_output_to_buffer) { raii_ptr<uint8_t> fileBytes([](uint8_t* p){av_freep(p);}); int fileSize = avio_close_dyn_buf(_fc.get()->pb, &fileBytes.raw()); _buffer.resize(fileSize); memcpy(&_buffer[0], fileBytes.get(), fileSize); } else { int res = avio_close(_fc.get()->pb); if(res < 0) R_THROW(("Unable to close output io context: %s", ff_rc_to_msg(res).c_str())); } } } const uint8_t* r_muxer::buffer() const { if(!_output_to_buffer) R_THROW(("Please only call buffer() on muxers configured to output to buffer.")); return &_buffer[0]; } size_t r_muxer::buffer_size() const { if(!_output_to_buffer) R_THROW(("Please only call buffer_size() on muxers configured to output to buffer.")); return _buffer.size(); }
33.394366
132
0.640489
TroyDL
803b5ca8edd0c5610516eab4a496ee6f3a4dc479
356
cpp
C++
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/TheUnnamedGame
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
7
2022-02-04T08:57:33.000Z
2022-03-06T12:54:05.000Z
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/MonkeyDelivery
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
79
2022-02-01T15:25:51.000Z
2022-03-30T22:17:20.000Z
MonkeyDelivery/Src/Control/NextStateCommand.cpp
miggon23/MonkeyDelivery
8b8fbf232772d5de90fb8646129afa5e8b11608e
[ "MIT" ]
null
null
null
#include "NextStateCommand.h" #include "./States/State.h" bool NextStateCommand::parse(SDL_Event& event) { if (event.type == SDL_KEYDOWN) { SDL_Keycode key = event.key.keysym.sym; if (key == SDLK_SPACE) { return true; } } return false; } void NextStateCommand::execute() { game->getState()->next(); }
17.8
47
0.601124
miggon23
d9aaac911acfc2fabb8f8c36b444ac6af9b7509b
3,886
cpp
C++
src/Examples/Mesh/GeometryHelpers.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
11
2017-06-26T08:59:03.000Z
2021-09-28T13:12:22.000Z
src/Examples/Mesh/GeometryHelpers.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
4
2016-07-09T14:54:22.000Z
2017-04-26T14:02:53.000Z
src/Examples/Mesh/GeometryHelpers.cpp
wrld3d/eegeo-sdk-samples
eb1a1e4d4b7d3eb79ad454cc5a09d1847018269d
[ "BSD-2-Clause" ]
9
2016-04-08T03:43:13.000Z
2016-12-12T02:07:49.000Z
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include "GeometryHelpers.h" #include "Bounds.h" namespace Examples { namespace GeometryHelpers { void BuildBox(const Eegeo::v3& halfDimensions, std::vector<Vertex>& out_vertices, std::vector<u16>& out_triangleIndices) { const int faces = 6; const int pointsPerFace = 4; out_vertices.clear(); out_triangleIndices.clear(); out_vertices.reserve(pointsPerFace*faces); out_triangleIndices.reserve(faces*3*2); Eegeo::v3 faceNormals[faces] = { Eegeo::v3(1.f, 0.f, 0.f), Eegeo::v3(0.f, 0.f, 1.f), Eegeo::v3(-1.f, 0.f, 0.f), Eegeo::v3(0.f, 0.f, -1.f), Eegeo::v3(0.f, 1.f, 0.f), Eegeo::v3(0.f, -1.f, 0.f) }; Eegeo::v3 points[8] = { Eegeo::v3(halfDimensions.x, halfDimensions.y, halfDimensions.z), Eegeo::v3(halfDimensions.x, halfDimensions.y, -halfDimensions.z), Eegeo::v3(halfDimensions.x, -halfDimensions.y, halfDimensions.z), Eegeo::v3(halfDimensions.x, -halfDimensions.y, -halfDimensions.z), Eegeo::v3(-halfDimensions.x, halfDimensions.y, halfDimensions.z), Eegeo::v3(-halfDimensions.x, halfDimensions.y, -halfDimensions.z), Eegeo::v3(-halfDimensions.x, -halfDimensions.y, halfDimensions.z), Eegeo::v3(-halfDimensions.x, -halfDimensions.y, -halfDimensions.z), }; int pointIndices[faces*pointsPerFace] = { 1, 0, 3, 2, 0, 4, 2, 6, 4, 5, 6, 7, 5, 1, 7, 3, 4, 0, 5, 1, 7, 3, 6, 2, }; Eegeo::Geometry::Bounds2D uvRects[] = { Eegeo::Geometry::Bounds2D(Eegeo::v2(0.0f, 0.0f), Eegeo::v2(0.5f, 0.5f)), // +ve x, "0" Eegeo::Geometry::Bounds2D(Eegeo::v2(0.5f, 0.0f), Eegeo::v2(1.0f, 0.5f)), // +ve z, "1" Eegeo::Geometry::Bounds2D(Eegeo::v2(0.0f, 0.5f), Eegeo::v2(0.5f, 1.0f)), // -ve x, "2" Eegeo::Geometry::Bounds2D(Eegeo::v2(0.5f, 0.5f), Eegeo::v2(1.0f, 1.0f)), // -ve z, "3" Eegeo::Geometry::Bounds2D(Eegeo::v2::Zero(), Eegeo::v2::One()), // +ve y (top) Eegeo::Geometry::Bounds2D(Eegeo::v2::Zero(), Eegeo::v2::One()), // -ve y (bottom) }; for (int i = 0; i < 6; ++i) { const Eegeo::v3& faceNormal = faceNormals[i]; const Eegeo::Geometry::Bounds2D& uvRect = uvRects[i]; u16 offset = static_cast<u16>(i*pointsPerFace); out_vertices.push_back(Vertex(points[pointIndices[offset + 0]], faceNormal, Eegeo::v2(uvRect.min.x, uvRect.max.y))); out_vertices.push_back(Vertex(points[pointIndices[offset + 1]], faceNormal, Eegeo::v2(uvRect.max.x, uvRect.max.y))); out_vertices.push_back(Vertex(points[pointIndices[offset + 2]], faceNormal, Eegeo::v2(uvRect.min.x, uvRect.min.y))); out_vertices.push_back(Vertex(points[pointIndices[offset + 3]], faceNormal, Eegeo::v2(uvRect.max.x, uvRect.min.y))); out_triangleIndices.push_back(offset + 0); out_triangleIndices.push_back(offset + 1); out_triangleIndices.push_back(offset + 2); out_triangleIndices.push_back(offset + 2); out_triangleIndices.push_back(offset + 1); out_triangleIndices.push_back(offset + 3); } } } }
46.261905
132
0.506948
wrld3d
d9b753fc62ef4f6f56ad748549c6d03dfbd436ef
25
cpp
C++
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
20
2020-01-15T22:00:23.000Z
2022-02-07T05:32:09.000Z
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
2
2021-02-26T15:13:49.000Z
2021-11-28T17:35:05.000Z
TOD1/SoundEmitter.cpp
Michael0ne/TOD_tools
0e55b28b7001d8b7ce7c0e0811f27682349b41c9
[ "FSFAP" ]
1
2020-05-07T18:41:50.000Z
2020-05-07T18:41:50.000Z
#include "SoundEmitter.h"
25
25
0.8
Michael0ne
d9b7937809b3d4c193c135c9dee0c3585b0d2253
5,655
cpp
C++
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
31
2021-01-20T08:12:48.000Z
2022-03-29T16:47:50.000Z
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
118
2021-02-04T17:57:48.000Z
2022-03-31T13:03:21.000Z
Plugins/CaptionMod/BaseUI.cpp
DrAbcrealone/MetaHookSv
db8306d325590a380a458758c8518519cab01891
[ "MIT" ]
13
2021-01-21T01:43:19.000Z
2022-03-15T04:51:19.000Z
#include <metahook.h> #include "BaseUI.h" #include <VGUI\IScheme.h> #include <VGUI\ILocalize.h> #include <VGUI\ISurface.h> #include <VGUI\IInput.h> #include "FontTextureCache.h" #include <IEngineSurface.h> #include "vgui_internal.h" #include "IKeyValuesSystem.h" #include "exportfuncs.h" #include "engfuncs.h" namespace vgui { bool VGui_InitInterfacesList(const char *moduleName, CreateInterfaceFn *factoryList, int numFactories); } void (__fastcall *m_pfnCBaseUI_Initialize)(void *pthis, int, CreateInterfaceFn *factories, int count); void (__fastcall *m_pfnCBaseUI_Start)(void *pthis, int, struct cl_enginefuncs_s *engineFuncs, int interfaceVersion); void (__fastcall *m_pfnCBaseUI_Shutdown)(void *pthis, int); int (__fastcall *m_pfnCBaseUI_Key_Event)(void *pthis, int, int down, int keynum, const char *pszCurrentBinding); void (__fastcall *m_pfnCBaseUI_CallEngineSurfaceProc)(void *pthis, int, void *hwnd, unsigned int msg, unsigned int wparam, long lparam); void (__fastcall *m_pfnCBaseUI_Paint)(void *pthis, int, int x, int y, int right, int bottom); void (__fastcall *m_pfnCBaseUI_HideGameUI)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_ActivateGameUI)(void *pthis, int); bool (__fastcall *m_pfnCBaseUI_IsGameUIVisible)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_HideConsole)(void *pthis, int); void (__fastcall *m_pfnCBaseUI_ShowConsole)(void *pthis, int); class CBaseUI : public IBaseUI { public: virtual void Initialize(CreateInterfaceFn *factories, int count); virtual void Start(struct cl_enginefuncs_s *engineFuncs, int interfaceVersion); virtual void Shutdown(void); virtual int Key_Event(int down, int keynum, const char *pszCurrentBinding); virtual void CallEngineSurfaceProc(void *hwnd, unsigned int msg, unsigned int wparam, long lparam); virtual void Paint(int x, int y, int right, int bottom); virtual void HideGameUI(void); virtual void ActivateGameUI(void); virtual bool IsGameUIVisible(void); virtual void HideConsole(void); virtual void ShowConsole(void); }; static CBaseUI s_BaseUI; IBaseUI *baseuifuncs; IGameUIFuncs *gameuifuncs; extern vgui::ISurface *g_pSurface; extern vgui::ISchemeManager *g_pScheme; extern IKeyValuesSystem *g_pKeyValuesSystem; extern IEngineSurface *staticSurface; static BOOL s_LoadingClientFactory = false; void CBaseUI::Initialize(CreateInterfaceFn *factories, int count) { //Patch ClientFactory if(!g_IsClientVGUI2 && *gCapFuncs.pfnClientFactory == NULL) { *gCapFuncs.pfnClientFactory = NewClientFactory; s_LoadingClientFactory = true; } m_pfnCBaseUI_Initialize(this, 0, factories, count); s_LoadingClientFactory = false; HINTERFACEMODULE hVGUI2 = (HINTERFACEMODULE)GetModuleHandle("vgui2.dll"); if(hVGUI2) { CreateInterfaceFn fnVGUI2CreateInterface = Sys_GetFactory(hVGUI2); g_pScheme = (vgui::ISchemeManager *)fnVGUI2CreateInterface(VGUI_SCHEME_INTERFACE_VERSION, NULL); g_pKeyValuesSystem = (IKeyValuesSystem *)fnVGUI2CreateInterface(KEYVALUESSYSTEM_INTERFACE_VERSION, NULL); } g_pSurface = (vgui::ISurface *)factories[0](VGUI_SURFACE_INTERFACE_VERSION, NULL); staticSurface = (IEngineSurface *)factories[0](ENGINE_SURFACE_VERSION, NULL); KeyValuesSystem_InstallHook(); Surface_InstallHook(); Scheme_InstallHook(); GameUI_InstallHook(); } void CBaseUI::Start(struct cl_enginefuncs_s *engineFuncs, int interfaceVersion) { m_pfnCBaseUI_Start(this, 0, engineFuncs, interfaceVersion); } void CBaseUI::Shutdown(void) { m_pfnCBaseUI_Shutdown(this, 0); } int CBaseUI::Key_Event(int down, int keynum, const char *pszCurrentBinding) { return m_pfnCBaseUI_Key_Event(this, 0, down, keynum, pszCurrentBinding); } void CBaseUI::CallEngineSurfaceProc(void *hwnd, unsigned int msg, unsigned int wparam, long lparam) { m_pfnCBaseUI_CallEngineSurfaceProc(this, 0, hwnd, msg, wparam, lparam); } void CBaseUI::Paint(int x, int y, int right, int bottom) { m_pfnCBaseUI_Paint(this, 0, x, y, right, bottom); } void CBaseUI::HideGameUI(void) { m_pfnCBaseUI_HideGameUI(this, 0); } void CBaseUI::ActivateGameUI(void) { m_pfnCBaseUI_ActivateGameUI(this, 0); } bool CBaseUI::IsGameUIVisible(void) { return m_pfnCBaseUI_IsGameUIVisible(this, 0); } void CBaseUI::HideConsole(void) { m_pfnCBaseUI_HideConsole(this, 0); } void CBaseUI::ShowConsole(void) { m_pfnCBaseUI_ShowConsole(this, 0); } void BaseUI_InstallHook(void) { CreateInterfaceFn fnCreateInterface = g_pMetaHookAPI->GetEngineFactory(); baseuifuncs = (IBaseUI *)fnCreateInterface(BASEUI_INTERFACE_VERSION, NULL); gameuifuncs = (IGameUIFuncs *)fnCreateInterface(VENGINE_GAMEUIFUNCS_VERSION, NULL); //Search CBaseUI::Initialize for ClientFactory if (g_iEngineType == ENGINE_SVENGINE) { #define CLIENTFACTORY_SIG_SVENGINE "\x83\xC4\x0C\x83\x3D" DWORD *vft = *(DWORD **)baseuifuncs; DWORD addr = (DWORD)g_pMetaHookAPI->SearchPattern((void *)vft[1], 0x200, CLIENTFACTORY_SIG_SVENGINE, Sig_Length(CLIENTFACTORY_SIG_SVENGINE)); Sig_AddrNotFound(ClientFactory); gCapFuncs.pfnClientFactory = (void *(**)(void))*(DWORD *)(addr + 5); DWORD *pVFTable = *(DWORD **)&s_BaseUI; g_pMetaHookAPI->VFTHook(baseuifuncs, 0, 1, (void *)pVFTable[1], (void **)&m_pfnCBaseUI_Initialize); } else { #define CLIENTFACTORY_SIG "\xCC\xA1\x2A\x2A\x2A\x2A\x85\xC0\x74" DWORD *vft = *(DWORD **)baseuifuncs; DWORD addr = (DWORD)g_pMetaHookAPI->SearchPattern((void *)vft[1], 0x200, CLIENTFACTORY_SIG, Sig_Length(CLIENTFACTORY_SIG)); Sig_AddrNotFound(ClientFactory); gCapFuncs.pfnClientFactory = (void *(**)(void))*(DWORD *)(addr + 2); DWORD *pVFTable = *(DWORD **)&s_BaseUI; g_pMetaHookAPI->VFTHook(baseuifuncs, 0, 1, (void *)pVFTable[1], (void **)&m_pfnCBaseUI_Initialize); } }
33.070175
143
0.774536
DrAbcrealone
d9b84a0b3afa685a84f54b3760a003bfa5cc9178
2,398
cc
C++
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
1
2021-06-26T05:32:43.000Z
2021-06-26T05:32:43.000Z
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
2
2019-10-14T06:46:43.000Z
2019-10-18T04:34:20.000Z
capstone.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
null
null
null
#include "capstone.h" #include <functional> #include <iomanip> #include <iostream> #include <memory> #include <string> using namespace std; using namespace std::placeholders; Capstone::Capstone(csh handle, const uint8_t* code, size_t size, uint64_t address) { this->handle = handle; this->code = code; this->size = size; this->address = address; } Capstone::~Capstone() { cs_close(&handle); } /* discard the consts here to match the vendor signature */ Capstone::const_iterator::const_iterator(const Capstone& c) : handle(c.handle), insn(cs_malloc(c.handle)), code(const_cast<const uint8_t*>(c.code)), size(c.size), address(c.address) {} Capstone::const_iterator::const_iterator() : handle(0), insn(NULL), code(NULL), size(0), address(0) {} /* copy will allocate additional memory */ Capstone::const_iterator::const_iterator(const const_iterator& c) : handle(c.handle), insn(cs_malloc(c.handle)), code(c.code), size(c.size), address(c.address) {} Capstone::const_iterator::~const_iterator() { if (insn) { cs_free(insn, 1); insn = NULL; } } const cs_insn& Capstone::const_iterator::operator*() const { return *insn; } Capstone::const_iterator& Capstone::const_iterator::operator++() { if (size == 0) { code = NULL; return *this; } // cout << "cs_disasm_iter(" << hex << handle << "," << (unsigned int)*code << "," << size << "," << address << ")" << // endl; bool i_sz = cs_disasm_iter(handle, &code, &size, &address, insn); // if it fails, reset to end() if (!i_sz) { size = 0; code = NULL; } return *this; } /* postfix is notably less efficient since it allocates a cs_insn each time */ Capstone::const_iterator Capstone::const_iterator::operator++(int) { const_iterator old(*this); operator++(); return old; } long operator-(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return lhs.code - rhs.code; } bool operator==(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return lhs.code == rhs.code && lhs.size == rhs.size; } bool operator!=(Capstone::const_iterator const& lhs, Capstone::const_iterator const& rhs) { return !(lhs == rhs); } Capstone::const_iterator Capstone::begin() const { return Capstone::const_iterator(*this); } Capstone::const_iterator Capstone::end() const { return Capstone::const_iterator(); }
26.351648
120
0.675146
justinleona
d9bbd6d6f04f630898221d3c4142a9d7d015d8d6
12,223
cc
C++
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
3
2020-12-17T14:38:23.000Z
2021-03-11T10:27:55.000Z
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
null
null
null
src/xi_nub.cc
michaeljclark/xi
f8370784d8d92dad535a9ad2c30bf6b6b9eda87f
[ "ISC" ]
null
null
null
/* * xi_nub - atomically create child process hosting static function. * * Copyright (c) 2020 Michael Clark <michaeljclark@mac.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "xi_common.h" #include "sha256.h" #include <cstdlib> #include <cinttypes> #include <vector> #include <algorithm> #include <threads.h> using string = std::string; template <typename T> using vector = std::vector<T>; struct xi_nub_ctx { string app_name; string user_name; string home_path; string profile_path; void *user_data; }; struct xi_nub_agent { xi_nub_ctx *ctx; vector<string> args; xi_nub_platform_desc listen_sock; vector<xi_nub_ch> ch; }; struct xi_nub_ch { xi_nub_ctx *ctx; xi_nub_agent *agent; xi_nub_platform_desc sock; void *user_data; }; /* * profile directory */ #if defined OS_WINDOWS const char *profile_template = "%s\\%s"; #elif defined OS_MACOS const char *profile_template = "%s/Library/Application Support/%s"; #elif defined OS_LINUX || defined OS_FREEBSD const char *profile_template = "%s/.config/%s"; #endif #if defined OS_WINDOWS static void xi_nub_find_dirs(xi_nub_ctx *ctx) { char profile_path_tmp[MAXPATHLEN]; ctx->user_name = _windows_getenv("USERNAME"); ctx->home_path = _windows_getenv("HOMEPATH"); string appdata = _windows_getenv("APPDATA"); snprintf(profile_path_tmp, MAX_PATH, profile_template, appdata.c_str(), ctx->app_name.c_str()); ctx->profile_path = profile_path_tmp; } #endif #if defined OS_POSIX static void xi_nub_find_dirs(xi_nub_ctx *ctx) { char profile_path_tmp[MAXPATHLEN]; struct passwd *p = getpwuid(getuid()); ctx->user_name = p->pw_name; ctx->home_path = p->pw_dir; snprintf(profile_path_tmp, MAXPATHLEN, profile_template, ctx->home_path.c_str(), ctx->app_name.c_str()); ctx->profile_path = profile_path_tmp; } #endif /* * convert command-line argument to a vector */ static vector<string> _get_args(int argc, const char **argv) { vector<string> args; for (size_t i = 0; i < argc; i++) { if (i == 0 && strcmp(argv[0], "<self>") == 0) { args.push_back(_executable_path()); } else { args.push_back(argv[i]); } } return args; } static char** _get_argv(vector<string> vec) { size_t alloc_size = (vec.size() + 1) * sizeof(char*); for (auto &s : vec) alloc_size += s.size() + 1; char **arr = (char **)malloc(alloc_size); char *data = (char*)&arr[vec.size() + 1]; for (size_t i = 0; i < vec.size(); i++) { arr[i] = data; memcpy(data, vec[i].data(), vec[i].size()); data[vec[i].size()] = 0; data += vec[i].size() + 1; } arr[vec.size()] = 0; return (char**)arr; } struct _argument_hash { unsigned char hash[32]; }; static _argument_hash _get_args_hash(vector<string> vec) { _argument_hash ah; sha256_ctx ctx; sha256_init(&ctx); for (auto &s : vec) { sha256_update(&ctx, s.c_str(), s.size() + 1); } sha256_final(&ctx, ah.hash); return ah; } static string _to_hex(const unsigned char *in, size_t in_len) { size_t o = 0, l = in_len << 1; char *buf = (char*)alloca(l + 1); for (size_t i = 0, o = 0; i < in_len; i++) { o+= snprintf(buf+o, l + 1 - o, "%02" PRIx8, in[i]); } return string(buf, l); } static string _get_nub_addr(xi_nub_ctx *ctx, vector<string> vec) { _argument_hash ah = _get_args_hash(vec); return ctx->app_name + string("-") + _to_hex(ah.hash, sizeof(ah.hash)); } /* * nub agent */ xi_nub_agent* xi_nub_agent_new(xi_nub_ctx *ctx, int argc, const char **argv) { xi_nub_agent *agent = new xi_nub_agent(); agent->ctx = ctx; agent->args = _get_args(argc, argv); _debug_func("agent=%p\n", agent); return agent; } void xi_nub_agent_destroy(xi_nub_agent *agent) { delete agent; } /* * nub server */ static void xi_nub_wake_all_waiters(xi_nub_ctx *ctx) { char sem_file[MAXPATHLEN]; const char* profile_path = xi_nub_ctx_get_profile_path(ctx); snprintf(sem_file, sizeof(sem_file), "%s%s", profile_path, PATH_SEPARATOR "semaphore"); auto f = _open_file(sem_file, file_open_existing, file_read_write); if (f.has_error()) return; /* no lock file */ char buf[1024]; xi_nub_result r = _read(&f, buf, sizeof(buf)); size_t num_waiters = (size_t)(r.bytes >> 2); uint32_t *p = (uint32_t*)buf; for (size_t i = 0; i < num_waiters; i++) { uint32_t pid = *p++; char sem_name[16]; snprintf(sem_name, sizeof(sem_name), "%s-%u", ctx->app_name.c_str(), pid); xi_nub_platform_semaphore sem = _semaphore_open(sem_name); if (sem.has_error()) { _panic("error: _semaphore_open: error_code=%d\n", sem.error_code()); } _debug_func("semaphore=%s *** signal ***\n", sem_name); _semaphore_signal(&sem); _semaphore_unlink(sem_name); _semaphore_close(&sem); } _close(&f); _delete_file(sem_file); } void xi_nub_agent_accept(xi_nub_agent *agent, int nthreads, xi_nub_accept_cb cb) { string pipe_addr = _get_nub_addr(agent->ctx, agent->args); agent->listen_sock = _listen_socket_create(pipe_addr.c_str()); if (agent->listen_sock.has_error()) { _panic("error: listen_socket_create failed: error=%d\n", agent->listen_sock.error_code()); } _debug_func("listening sock=%s\n", agent->listen_sock.identity()); xi_nub_wake_all_waiters(agent->ctx); /* TODO: create agent thread */ for (;;) { xi_nub_ch ch{ agent->ctx, agent, _listen_socket_accept(agent->listen_sock) }; _debug_func("accepted sock=%s\n", ch.sock.identity()); if (ch.sock.has_error()) { cb(&ch, ch.sock.error_code()); } else { cb(&ch, xi_nub_success); } /* TODO - implement server shutdown */ } } /* * nub client */ struct xi_name_object { char name[MAXPATHLEN]; }; struct xi_nub_ticket { uint32_t ticket; uint32_t pid; bool is_leader; xi_name_object obj; }; static xi_nub_ticket xi_nub_get_ticket(xi_nub_ctx *ctx) { xi_name_object obj; const char* profile_path = xi_nub_ctx_get_profile_path(ctx); snprintf(obj.name, sizeof(obj.name), "%s%s", profile_path, PATH_SEPARATOR "semaphore"); bool is_leader = false; auto f = _open_file(obj.name, file_create_new, file_append); if (f.has_error()) { f = _open_file(obj.name, file_open_existing, file_append); } else { is_leader = true; } uint32_t pid = (uint32_t)_get_processs_id(); _write(&f, &pid, sizeof(pid)); xi_nub_result off = _get_file_offset(&f); uint32_t ticket = (uint32_t)off.bytes >> 2; _close(&f); _debug("%s: ticket=%u, is_leader=%u, pid=%u, file=%s\n", __func__, ticket, is_leader, pid, obj.name); return xi_nub_ticket{ticket, pid, is_leader, obj }; } static void xi_nub_sleep_on_ticket(xi_nub_ctx *ctx, xi_nub_ticket ticket) { char sem_name[16]; snprintf(sem_name, sizeof(sem_name), "%s-%u", ctx->app_name.c_str(), ticket.pid); xi_nub_platform_semaphore sem = _semaphore_create(sem_name); if (sem.has_error()) { _panic("error: _semaphore_create: error_code=%d\n", sem.error_code()); } _debug_func("semaphore=%s *** created ***\n", sem_name); _semaphore_wait(&sem, 15000); #if defined OS_WINDOWS _thread_sleep(100); #endif _debug_func("semaphore=%s *** woke up ***\n", sem_name); } void xi_nub_agent_connect(xi_nub_agent *agent, int nthreads, xi_nub_connect_cb cb) { string pipe_addr = _get_nub_addr(agent->ctx, agent->args); xi_nub_ch ch{ agent->ctx, agent, _client_socket_connect(pipe_addr.c_str()) }; _debug_func("sock=%s\n", ch.sock.identity()); /* TODO: create agent thread */ /* if we get a socket error, we try to launch a new server */ if (ch.sock.has_error()) { _close(&ch.sock); /* get an atomic launch ticket, first caller is the leader */ xi_nub_ticket ticket = xi_nub_get_ticket(agent->ctx); /* launch a server if we are the leader */ if (ticket.is_leader) { char **argv = _get_argv(agent->args); int argc = (int)agent->args.size(); xi_nub_os_process p = _create_process(argc, (const char**)argv); free(argv); } /* wait for server to wake us up */ xi_nub_sleep_on_ticket(agent->ctx, ticket); /* attempt to reconnect */ ch.sock = _client_socket_connect(pipe_addr.c_str()); if (ch.sock.has_error()) { cb(&ch, ch.sock.error_code()); } else { cb(&ch, xi_nub_success); } } else { cb(&ch, xi_nub_success); } } /* * nub channel io */ void xi_nub_io_read(xi_nub_ch *ch, void *buf, size_t len, xi_nub_read_cb cb) { xi_nub_result result = _read(&ch->sock, buf, len); _debug_func("sock=%s, len=%zu: ret=%zd, error=%d\n", ch->sock.identity(), len, result.bytes, result.error); if (cb) cb(ch, result.error, buf, result.bytes); } void xi_nub_io_write(xi_nub_ch *ch, void *buf, size_t len, xi_nub_write_cb cb) { xi_nub_result result = _write(&ch->sock, buf, len); _debug_func("sock=%s, len=%zu: ret=%zd, error=%d\n", ch->sock.identity(), len, result.bytes, result.error); if (cb) cb(ch, result.error, buf, result.bytes); } void xi_nub_io_close(xi_nub_ch *ch, xi_nub_close_cb cb) { bool is_server = ch->agent->listen_sock.desc_type() == xi_nub_desc_type_pipe_listen; xi_nub_result result = is_server ? _disconnect(&ch->sock) : _close(&ch->sock); _debug_func("sock=%s: ret=%zd, error=%d\n", ch->sock.identity(), result.bytes, result.error); if (cb) cb(ch, result.error); } const char* xi_nub_io_get_identity(xi_nub_ch *ch) { return ch->sock.identity(); } /* * nub accessors */ static xi_nub_ctx *global_nub_ctx; void xi_nub_io_set_user_data(xi_nub_ch *ch, void *data) { ch->user_data = data; } void* xi_nub_io_get_user_data(xi_nub_ch *ch) { return ch->user_data; } xi_nub_agent* xi_nub_io_get_agent(xi_nub_ch *ch) { return ch->agent; } xi_nub_ctx* xi_nub_io_get_context(xi_nub_ch *ch) { return ch->ctx; } void xi_nub_ctx_set_user_data(xi_nub_ctx *ctx, void *data) { ctx->user_data = data; } void* xi_nub_ctx_get_user_data(xi_nub_ctx *ctx) { return ctx->user_data; } const char* xi_nub_ctx_get_profile_path(xi_nub_ctx *ctx) { return ctx->profile_path.c_str(); } xi_nub_ctx* xi_nub_ctx_get_initial_context() { return global_nub_ctx; } /* * nub context */ static void xi_nub_init(xi_nub_ctx *ctx, const char *app_name) { /* find user profile directory */ ctx->app_name = app_name; xi_nub_find_dirs(ctx); /* create profile directory if it does not exist */ if (!_directory_exists(ctx->profile_path.c_str())) { if(!_make_directory(ctx->profile_path.c_str())) { _panic("error: _make_directory failed: %s\n", ctx->profile_path.c_str()); } } #if defined OS_POSIX /* install handler to cleanup on exit */ _install_signal_handler(); #endif } xi_nub_ctx* xi_nub_ctx_create(const char *app_name) { xi_nub_ctx *ctx; ctx = new xi_nub_ctx(); xi_nub_init(ctx, app_name); if (!global_nub_ctx) { global_nub_ctx = ctx; } return ctx; } void xi_nub_ctx_destroy(xi_nub_ctx *ctx) { delete ctx; }
26.98234
94
0.647468
michaeljclark
d9bdf03336aea3a8efe4f5bcbd3197263a397a62
1,843
cpp
C++
plugins/opengl/src/sdl/context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/sdl/context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/sdl/context.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/opengl/backend/context.hpp> #include <sge/opengl/backend/current.hpp> #include <sge/opengl/backend/current_unique_ptr.hpp> #include <sge/opengl/sdl/context.hpp> #include <sge/opengl/sdl/current.hpp> #include <sge/renderer/exception.hpp> #include <sge/window/object.hpp> #include <sge/window/object_ref.hpp> #include <awl/backends/sdl/window/object.hpp> #include <fcppt/make_unique_ptr.hpp> #include <fcppt/text.hpp> #include <fcppt/unique_ptr_to_base.hpp> #include <fcppt/cast/dynamic.hpp> #include <fcppt/optional/to_exception.hpp> #include <fcppt/config/external_begin.hpp> #include <SDL_video.h> #include <fcppt/config/external_end.hpp> sge::opengl::sdl::context::context(sge::window::object_ref const _window) : sge::opengl::backend::context{}, window_{ fcppt::optional::to_exception( fcppt::cast::dynamic<awl::backends::sdl::window::object>(_window.get().awl_object()), [] { return sge::renderer::exception{ FCPPT_TEXT("Window passed to sdl::context is not an SDL window.")}; }) .get()}, context_{SDL_GL_CreateContext(&this->window_.get().get().get())} { } sge::opengl::sdl::context::~context() { SDL_GL_DeleteContext(this->context_); } sge::opengl::backend::current_unique_ptr sge::opengl::sdl::context::activate() { return fcppt::unique_ptr_to_base<sge::opengl::backend::current>( fcppt::make_unique_ptr<sge::opengl::sdl::current>(this->window_, this->context_)); } void sge::opengl::sdl::context::deactivate(sge::opengl::backend::current_unique_ptr &&) {}
38.395833
99
0.686923
cpreh
d9bf04ef6338d62f898bf95d48d7996a7644a4b4
696
hpp
C++
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
1
2021-05-01T15:05:47.000Z
2021-05-01T15:05:47.000Z
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
13
2015-01-02T11:59:58.000Z
2015-01-19T05:27:06.000Z
webmock/api/application.hpp
mrk21/cpp-webmock
13a7b8362e2e84d47de45071956a43ac3005c58a
[ "MIT" ]
null
null
null
#ifndef WEBMOCK_API_APPLICATION_HPP #define WEBMOCK_API_APPLICATION_HPP #include <webmock/core/request.hpp> #include <webmock/core/stub_registry.hpp> #include <functional> namespace webmock { namespace api { struct application { using stub_not_found_callback_type = std::function<void(core::request const &)>; core::stub_registry registry; struct { struct { stub_not_found_callback_type callback; bool is_connecting_to_net = false; } stub_not_found; } config; }; inline application & app() { static application instance; return instance; } }} #endif
24
88
0.632184
mrk21
d9c1c68ac81d35cb9e64bcafae2a489d45d035df
412
cpp
C++
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
7
2015-02-13T23:07:00.000Z
2022-03-04T08:01:04.000Z
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
null
null
null
Private/TB_GameMode.cpp
larsjsol/UE4_TurnBased
547a601cbeacec5b8380ec480b2764dd1822aedb
[ "MIT" ]
2
2019-06-25T06:38:18.000Z
2022-03-04T04:06:35.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "UE4_TurnBased.h" #include "TB_PlayerController.h" #include "TB_GameState.h" #include "TB_GameMode.h" ATB_GameMode::ATB_GameMode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PlayerControllerClass = ATB_PlayerController::StaticClass(); GameStateClass = ATB_GameState::StaticClass(); }
21.684211
78
0.791262
larsjsol
d9c48862fa5ed07ac1b2a037ddcfd936d469c912
1,130
hpp
C++
include/primer/result.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
14
2016-07-27T18:14:47.000Z
2018-06-15T19:54:10.000Z
include/primer/result.hpp
garbageslam/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
5
2016-11-01T23:20:35.000Z
2016-11-29T21:09:53.000Z
include/primer/result.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
2
2021-02-07T03:42:22.000Z
2021-02-10T14:12:00.000Z
// (C) Copyright 2015 - 2018 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once /*** * Signaling object used to indicate how to terminate a lua function call. */ #include <primer/base.hpp> PRIMER_ASSERT_FILESCOPE; #include <primer/expected.hpp> namespace primer { //[ primer_result // Tag used by the user to indicate a yield. struct yield { int n_; }; // Helper object: Represents a return or yield signal. struct return_or_yield { int n_; bool is_return_; bool is_valid() const { return n_ >= 0; } }; // Result object class result { expected<return_or_yield> payload_; public: // Ctors (implicit for ease of use) result(int i) : payload_(return_or_yield{i, true}) {} result(yield y) : payload_(return_or_yield{y.n_, false}) {} result(error e) : payload_(e) {} // Accessor const expected<return_or_yield> & get_payload() const & { return payload_; } expected<return_or_yield> & get_payload() & { return payload_; } }; //] } // end namespace primer
20.178571
80
0.69292
cbeck88
d9c7fb61a4bcddf1a828f1f705d83b9910670b6e
188
hpp
C++
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
cracking/minmax/note2.hpp
ancientscience/ancientscience.github.io
2c8e3c6a8017164fd86fabaaa3343257cea54405
[ "MIT" ]
null
null
null
std::reverse_iterator( first_min_element(v.begin(), v.end(), std::less<int>())) == last_max_element(v.rbegin(), v.rend(), std::greater<int>())
26.857143
41
0.515957
ancientscience
d9cabd911f0da74bba3738036b546b9d8ad03c6b
696
cpp
C++
C++ Solutions/CodeChef/COVID_Pandemic_and_Long_Queue.cpp
LearnEarn-Fun/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
1
2021-02-06T04:24:05.000Z
2021-02-06T04:24:05.000Z
C++ Solutions/CodeChef/COVID_Pandemic_and_Long_Queue.cpp
hridaya423/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
null
null
null
C++ Solutions/CodeChef/COVID_Pandemic_and_Long_Queue.cpp
hridaya423/Competitive-Programming-Solutions
2c353bea49413e3f0f14b8980baf982881ad2c65
[ "MIT" ]
1
2021-11-13T18:46:55.000Z
2021-11-13T18:46:55.000Z
#include <iostream> using namespace std; void solve(){ int N; cin>>N; int count=0, flag=0; int arr[] = {0, 0, 0, 0, 0, 0}; for(int i=0; i<N; i++){ arr[5] = arr[4]; arr[4] = arr[3]; arr[3] = arr[2]; arr[2] = arr[1]; arr[1] = arr[0]; cin>>arr[0]; count = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5]; if(count>1 && count<=6){ flag=1; break; } } if(flag) cout<<"NO\n"; else cout<<"YES\n"; } int main() { int testCases; cin>>testCases; while(testCases--){ solve(); } return 0; }
16.571429
68
0.385057
LearnEarn-Fun
d9cbfc4923dbb225bdd48cd9da3b08dd90957b05
419
cpp
C++
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
week1/project1/b/main.cpp
Arnarish/3ViknaPizzaD-t
65e214dfccd7932c25082206fc2f9a360d7efa07
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> using namespace std; int main(void) { string text; ofstream fout; fout.open("very_important_text.txt", ios::app); while (true) { cout << "Write whatever you wish, and it will be saved!" << endl; getline(cin, text); if (text[0] == '\\') { break; } fout << text << endl; } return 0; }
18.217391
73
0.539379
Arnarish
d9ce696b6678b1ea7bc0d80d458017484ac5d36b
4,369
cpp
C++
tests/BitmapTransformerTest.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
2
2017-05-19T08:53:12.000Z
2017-08-28T11:59:26.000Z
tests/BitmapTransformerTest.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
tests/BitmapTransformerTest.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** * Tests for SkBitmapTransformer.h and SkBitmapTransformer.cpp */ #include "Test.h" #include "SkBitmap.h" #include "SkBitmapTransformer.h" namespace skiatest { class BitmapTransformerTestClass : public Test { public: static Test* Factory(void*) {return SkNEW(BitmapTransformerTestClass); } protected: virtual void onGetName(SkString* name) { name->set("BitmapTransformer"); } virtual void onRun(Reporter* reporter) { this->fReporter = reporter; RunTest(); } private: void RunTest() { SkBitmap bitmap; SkBitmap::Config supportedConfig = SkBitmap::kARGB_8888_Config; SkBitmap::Config unsupportedConfig = SkBitmap::kARGB_4444_Config; SkBitmapTransformer::PixelFormat supportedPixelFormat = SkBitmapTransformer::kARGB_8888_Premul_PixelFormat; const int kWidth = 55; const int kHeight = 333; // Transformations that we know are unsupported: { bitmap.setConfig(unsupportedConfig, kWidth, kHeight); SkBitmapTransformer transformer = SkBitmapTransformer(bitmap, supportedPixelFormat); REPORTER_ASSERT(fReporter, !transformer.isValid()); } // Valid transformations: { // Bytes we expect to get: const int kWidth = 3; const int kHeight = 5; const unsigned char comparisonBuffer[] = { // kHeight rows, each with kWidth pixels, premultiplied ARGB for each pixel 0xff,0xff,0x00,0x00, 0xff,0xff,0x00,0x00, 0xff,0xff,0x00,0x00, // red 0xff,0x00,0xff,0x00, 0xff,0x00,0xff,0x00, 0xff,0x00,0xff,0x00, // green 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, // blue 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, // blue 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, // blue }; // A bitmap that should generate the above bytes: bitmap.setConfig(supportedConfig, kWidth, kHeight); REPORTER_ASSERT(fReporter, bitmap.allocPixels()); bitmap.setIsOpaque(true); bitmap.eraseColor(SK_ColorBLUE); bitmap.lockPixels(); // Change rows [0,1] from blue to [red,green]. SkColor oldColor = SK_ColorBLUE; SkColor newColors[] = {SK_ColorRED, SK_ColorGREEN}; for (int y = 0; y <= 1; y++) { for (int x = 0; x < kWidth; x++) { REPORTER_ASSERT(fReporter, bitmap.getColor(x, y) == oldColor); SkPMColor* pixel = static_cast<SkPMColor *>(bitmap.getAddr(x, y)); *pixel = SkPreMultiplyColor(newColors[y]); REPORTER_ASSERT(fReporter, bitmap.getColor(x, y) == newColors[y]); } } bitmap.unlockPixels(); // Transform the bitmap and confirm we got the expected results. SkBitmapTransformer transformer = SkBitmapTransformer(bitmap, supportedPixelFormat); REPORTER_ASSERT(fReporter, transformer.isValid()); REPORTER_ASSERT(fReporter, transformer.bytesNeededPerRow() == kWidth * 4); REPORTER_ASSERT(fReporter, transformer.bytesNeededTotal() == kWidth * kHeight * 4); int bufferSize = transformer.bytesNeededTotal(); SkAutoMalloc pixelBufferManager(bufferSize); char *pixelBuffer = static_cast<char *>(pixelBufferManager.get()); REPORTER_ASSERT(fReporter, transformer.copyBitmapToPixelBuffer(pixelBuffer, bufferSize)); REPORTER_ASSERT(fReporter, bufferSize == sizeof(comparisonBuffer)); REPORTER_ASSERT(fReporter, memcmp(pixelBuffer, comparisonBuffer, bufferSize) == 0); } } Reporter* fReporter; }; static TestRegistry gReg(BitmapTransformerTestClass::Factory); }
44.581633
100
0.585489
coltorchen
d9d0cd085c7da60b01c1d68ada67354e99ab1129
3,458
hpp
C++
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
3
2015-01-09T08:15:28.000Z
2019-05-24T08:34:04.000Z
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
src/tesseract/regression/LeastSquares.hpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2014 Soumyajit De * * 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 LEAST_SQUARES_H__ #define LEAST_SQUARES_H__ #include <tesseract/base/types.h> namespace tesseract { /** * Enum for defining which of the methods are to be used for solving * the least square problem instance */ enum LeastSquareMethod { LS_SVD, LS_QR, LS_NORMAL }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined systems \f$Ax=b\f$. */ template <typename T, enum LeastSquareMethod> struct LeastSquares; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using Jacobi SVD. */ template <typename T> struct LeastSquares<T, LS_SVD> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b); } }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using Householder QR decomposition. */ template <typename T> struct LeastSquares<T, LS_QR> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = A.colPivHouseholderQr().solve(b); } }; /** * @brief template class LeastSquares is the generic class for solving * least square problem for solving over-dertermined system \f$Ax=b\f$ * using \f$x=(A^T.A)^{-1}(A^T.b)\f$. */ template <typename T> struct LeastSquares<T, LS_NORMAL> { /** * Solves the over-determined system \f$Ax=b\f$. * @param A matrix \f$A\f$ * @param b vector \f$b\f$ * @param result result vector \f$x\f$ */ void solve(const Eigen::Ref<const Matrix<T>>& A, const Eigen::Ref<const Vector<T>>& b, Eigen::Ref<Vector<T>> result) const { result = (A.transpose() * A).ldlt().solve(A.transpose() * b); } }; } #endif // LEAST_SQUARES_H__
29.555556
87
0.707634
lambday
d9d0edfb4fc17c65fea6cc6e8f0bfcd9762bb869
5,514
cpp
C++
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
ELM_GUI_lib/ELM_GUI_lib/Device.cpp
therealddx/EagleLibraryManager
bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8
[ "MIT" ]
null
null
null
#include "Stdafx.h" #include "Device.h" namespace ELM_GUI_lib { Device::Device() { p = Package(); s = Symbol(); name = ""; XMLtext = ""; } Device::Device(std::string d_name) { /* <deviceset name="DUMMY"> <gates> </gates> <devices> <device name=""> <technologies> <technology name=""/> </technologies> </device> </devices> </deviceset> */ name = d_name; p = Package(name); s = Symbol(name); XMLtext = XMLParse::generateTag(XMLParse::XML_TAGS::DEVICESET_START, name); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::GATES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::GATES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICE_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGIES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGY)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::TECHNOLOGIES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICE_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::XML_TAGS::DEVICESET_END)); } Device::Device(std::string d_name, std::string d_XMLtext) { p = Package(d_name); s = Symbol(d_name); name = d_name; XMLtext = d_XMLtext; } void Device::compileXML(std::vector<std::string> padNames) { XMLtext = XMLParse::generateTag(XMLParse::DEVICESET_START, name); XMLtext.append(XMLParse::generateTag(XMLParse::GATES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::GATE, name)); XMLtext.append(XMLParse::generateTag(XMLParse::GATES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICE_START, name)); XMLtext.append(XMLParse::generateTag(XMLParse::CONNECTS_START)); for (std::string cur_name : padNames) XMLtext.append(XMLParse::generateTag(XMLParse::CONNECT, cur_name)); XMLtext.append(XMLParse::generateTag(XMLParse::CONNECTS_END)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGIES_START)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGY)); XMLtext.append(XMLParse::generateTag(XMLParse::TECHNOLOGIES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICE_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICES_END)); XMLtext.append(XMLParse::generateTag(XMLParse::DEVICESET_END)); } //Generates 2xN Device. Device::Device( std::string d_name, std::vector<std::string> padNames, double d_space_x, double d_space_y, double d_dim_x, double d_dim_y, int N ) { Package p_new(d_name, padNames, d_space_x, d_space_y, d_dim_x, d_dim_y, N); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, padNames, N*2); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(padNames); //Grouping pins will have to be presented as an option. //One example deviceset connection looks like this: // <deviceset name="VCO_805-900MHZ"> // <gates> // <gate name="G$1" symbol="VCO_805-900MHZ" x="60.96" y="5.08"/> // </gates> // <devices> // <device name="" package="VCO_805-900MHZ"> // <connects> // <connect gate="G$1" pin="GND" pad="GND0 GND1 GND2 GND3 GND4 GND5 GND6 GND7 GND8 GND9 GND10 GND11 GND12"/> // <connect gate="G$1" pin="RF" pad="RF"/> // <connect gate="G$1" pin="VCC" pad="VCC"/> // <connect gate="G$1" pin="VT" pad="VT"/> // </connects> // <technologies> // <technology name=""/> // </technologies> // </device> // </devices> // </deviceset> } //Generate RA. Device::Device( std::string d_name, std::vector<std::string> d_padNames, double d_REF, int d_N, double d_padW, double d_padL, double d_padSpace, double d_centeredSquarePad_DIM, double d_cornerSquarePads_REF, double d_cornerSquarePads_DIM ) { Package p_new( d_name, d_padNames, d_REF, d_N, d_padW, d_padL, d_padSpace, d_centeredSquarePad_DIM, d_cornerSquarePads_REF, d_cornerSquarePads_DIM ); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, d_padNames, p.numPads); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(d_padNames); } //Generate RxR. Device::Device( std::string d_name, std::vector<std::string> d_padNames, int d_N_rows, int* d_N_pads, double* d_padX, double* d_padY, double* d_padSpace, //length N_rows double* d_horizontalOffset, double* d_verticalOffset //length N_rows - 1 ) { Package p_new( d_name, d_padNames, d_N_rows, d_N_pads, d_padX, d_padY, d_padSpace, //length N_rows d_horizontalOffset, d_verticalOffset //length N_rows - 1 ); //Package p_new(d_name); p = p_new; Symbol s_new(d_name, d_padNames, p.numPads); //Symbol s_new(d_name); s = s_new; name = d_name; compileXML(d_padNames); } Device::Device(const Device& orig) { } Device::~Device() { } Device * Device::makeDummyDevices(std::vector<std::string> nameList) { int numDummyDevices = nameList.size(); Device * dummyDeviceList = new Device[numDummyDevices]; for (int n = 0; n < numDummyDevices; n++) { dummyDeviceList[n] = Device(nameList[n]); } return dummyDeviceList; } }
27.989848
113
0.673377
therealddx
d9d2a919f762ee2e36c64e4a2f3895827fc9c5ef
432
hpp
C++
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
src/lib/PageDownloader.hpp
alepez/bmrk
04db2646b42662b976b4f4a1a5fb414ca73df163
[ "MIT" ]
null
null
null
#ifndef PAGEDOWNLOADER_HPP_R1YIYM0U #define PAGEDOWNLOADER_HPP_R1YIYM0U #include "bmrk_fwd.hpp" #include <string> #include <future> namespace bmrk { /** * Download a document from a remote url */ class PageDownloader { public: /** * \return a future with the downloaded document */ virtual Future<String> load(const String& url) const; }; } /* bmrk */ #endif /* end of include guard: PAGEDOWNLOADER_HPP_R1YIYM0U */
18.782609
62
0.722222
alepez
d9d4e63d8d4b6c32e7e6c337834673972631e779
881
cpp
C++
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/arc105_a_17340899_625_plag.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/arc105/tasks/arc105_a A - Fourtune CookiesEditorial Time Limit : 2 sec / Memory Limit : 1024 MB 配点 : 200 点 */ #include <iostream> using namespace std; /* -------------------- ここまでテンプレ -------------------- */ int main() { bool ans = 0; int a, b, c, d; cin >> a >> b >> c >> d; ans |= (a) == (b + c + d); ans |= (a + b) == (c + d); ans |= (a + c) == (b + d); ans |= (a + d) == (b + c); ans |= (a + b + c) == (d); ans |= (a + b + d) == (c); ans |= (a + c + d) == (b); ans |= (a + b + c + d) == 0; ans |= (b) == (a + c + d); ans |= (b + c) == (a + d); ans |= (b + d) == (a + c); ans |= (b + c + d) == (a); ans |= (c) == (a + b + d); ans |= (c + d) == (a + b); ans |= (d) == (a + b + c); if (ans) cout << "Yes" << endl; else cout << "No" << endl; }
24.472222
60
0.351873
xryuseix
d9d77ffbab03541fa6af3f727b65cf5a893d37b7
126,811
cpp
C++
src/capi/typeobject.cpp
vinzenz/pyston
211aa1dd5b163be7fbe0c0dac85c38b01c36afc2
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
src/capi/typeobject.cpp
vinzenz/pyston
211aa1dd5b163be7fbe0c0dac85c38b01c36afc2
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
src/capi/typeobject.cpp
vinzenz/pyston
211aa1dd5b163be7fbe0c0dac85c38b01c36afc2
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2014-2015 Dropbox, 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 "capi/typeobject.h" #include "capi/types.h" #include "runtime/classobj.h" #include "runtime/hiddenclass.h" #include "runtime/objmodel.h" #include "runtime/rewrite_args.h" namespace pyston { typedef int (*update_callback)(PyTypeObject*, void*); static PyObject* tp_new_wrapper(PyTypeObject* self, BoxedTuple* args, Box* kwds) noexcept; extern "C" void conservativeGCHandler(GCVisitor* v, Box* b) noexcept { v->visitPotentialRange((void* const*)b, (void* const*)((char*)b + b->cls->tp_basicsize)); } extern "C" void conservativeAndBasesGCHandler(GCVisitor* v, Box* b) noexcept { // TODO: this function is expensive. We should try to make sure it doesn't get used // that often, or to come up with a better approach. // Call all the custom gc handlers defined anywhere in the hierarchy: assert(PyTuple_CheckExact(b->cls->tp_mro)); for (auto c : *static_cast<BoxedTuple*>(b->cls->tp_mro)) { if (!PyType_Check(c)) continue; auto gc_visit = static_cast<BoxedClass*>(c)->gc_visit; // Skip conservativeGCHandler since it's slow, and skip conservativeAndBasesGCHandler since // it would cause an infinite loop: if (gc_visit == conservativeGCHandler || gc_visit == conservativeAndBasesGCHandler) continue; gc_visit(v, b); } conservativeGCHandler(v, b); } static int check_num_args(PyObject* ob, int n) noexcept { if (!PyTuple_CheckExact(ob)) { PyErr_SetString(PyExc_SystemError, "PyArg_UnpackTuple() argument list is not a tuple"); return 0; } if (n == PyTuple_GET_SIZE(ob)) return 1; PyErr_Format(PyExc_TypeError, "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); return 0; } /* Helper to check for object.__setattr__ or __delattr__ applied to a type. This is called the Carlo Verre hack after its discoverer. */ static int hackcheck(PyObject* self, setattrofunc func, const char* what) noexcept { PyTypeObject* type = Py_TYPE(self); while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) type = type->tp_base; /* If type is NULL now, this is a really weird type. In the spirit of backwards compatibility (?), just shut up. */ if (type && type->tp_setattro != func) { PyErr_Format(PyExc_TypeError, "can't apply this %s to %s object", what, type->tp_name); return 0; } return 1; } #define WRAP_AVOIDABILITY(obj) ((obj)->cls->is_user_defined ? 10 : 20) static PyObject* wrap_setattr(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_setattr", WRAP_AVOIDABILITY(self)); setattrofunc func = (setattrofunc)wrapped; int res; PyObject* name, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) return NULL; if (!hackcheck(self, func, "__setattr__")) return NULL; res = (*func)(self, name, value); if (res < 0) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_delattr(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_delattr", WRAP_AVOIDABILITY(self)); setattrofunc func = (setattrofunc)wrapped; int res; PyObject* name; if (!check_num_args(args, 1)) return NULL; name = PyTuple_GET_ITEM(args, 0); if (!hackcheck(self, func, "__delattr__")) return NULL; res = (*func)(self, name, NULL); if (res < 0) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_hashfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_hashfunc", WRAP_AVOIDABILITY(self)); hashfunc func = (hashfunc)wrapped; long res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyInt_FromLong(res); } static PyObject* wrap_call(PyObject* self, PyObject* args, void* wrapped, PyObject* kwds) noexcept { STAT_TIMER(t0, "us_timer_wrap_call", WRAP_AVOIDABILITY(self)); ternaryfunc func = (ternaryfunc)wrapped; return (*func)(self, args, kwds); } static PyObject* wrap_richcmpfunc(PyObject* self, PyObject* args, void* wrapped, int op) noexcept { STAT_TIMER(t0, "us_timer_wrap_richcmpfunc", WRAP_AVOIDABILITY(self)); richcmpfunc func = (richcmpfunc)wrapped; PyObject* other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(self, other, op); } #undef RICHCMP_WRAPPER #define RICHCMP_WRAPPER(NAME, OP) \ static PyObject* richcmp_##NAME(PyObject* self, PyObject* args, void* wrapped) { \ return wrap_richcmpfunc(self, args, wrapped, OP); \ } RICHCMP_WRAPPER(lt, Py_LT) RICHCMP_WRAPPER(le, Py_LE) RICHCMP_WRAPPER(eq, Py_EQ) RICHCMP_WRAPPER(ne, Py_NE) RICHCMP_WRAPPER(gt, Py_GT) RICHCMP_WRAPPER(ge, Py_GE) static PyObject* wrap_next(PyObject* self, PyObject* args, void* wrapped) { STAT_TIMER(t0, "us_timer_wrap_next", WRAP_AVOIDABILITY(self)); unaryfunc func = (unaryfunc)wrapped; PyObject* res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == NULL && !PyErr_Occurred()) PyErr_SetNone(PyExc_StopIteration); return res; } static PyObject* wrap_descr_get(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_descr_get", WRAP_AVOIDABILITY(self)); descrgetfunc func = (descrgetfunc)wrapped; PyObject* obj; PyObject* type = NULL; if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) return NULL; if (obj == Py_None) obj = NULL; if (type == Py_None) type = NULL; if (type == NULL && obj == NULL) { PyErr_SetString(PyExc_TypeError, "__get__(None, None) is invalid"); return NULL; } return (*func)(self, obj, type); } static PyObject* wrap_coercefunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_coercefunc", WRAP_AVOIDABILITY(self)); coercion func = (coercion)wrapped; PyObject* other, *res; int ok; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); ok = func(&self, &other); if (ok < 0) return NULL; if (ok > 0) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } res = PyTuple_New(2); if (res == NULL) { Py_DECREF(self); Py_DECREF(other); return NULL; } PyTuple_SET_ITEM(res, 0, self); PyTuple_SET_ITEM(res, 1, other); return res; } static PyObject* wrap_ternaryfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_ternaryfunc", WRAP_AVOIDABILITY(self)); ternaryfunc func = (ternaryfunc)wrapped; PyObject* other; PyObject* third = Py_None; /* Note: This wrapper only works for __pow__() */ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) return NULL; return (*func)(self, other, third); } static PyObject* wrap_ternaryfunc_r(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_ternaryfunc_r", WRAP_AVOIDABILITY(self)); ternaryfunc func = (ternaryfunc)wrapped; PyObject* other; PyObject* third = Py_None; /* Note: This wrapper only works for __pow__() */ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) return NULL; return (*func)(other, self, third); } static PyObject* wrap_unaryfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_unaryfunc", WRAP_AVOIDABILITY(self)); unaryfunc func = (unaryfunc)wrapped; if (!check_num_args(args, 0)) return NULL; return (*func)(self); } static PyObject* wrap_inquirypred(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_inquirypred", WRAP_AVOIDABILITY(self)); inquiry func = (inquiry)wrapped; int res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyBool_FromLong((long)res); } static PyObject* wrapInquirypred(PyObject* self, PyObject* args, void* wrapped) { STAT_TIMER(t0, "us_timer_wrapInquirypred", WRAP_AVOIDABILITY(self)); inquiry func = (inquiry)wrapped; int res; if (!check_num_args(args, 0)) throwCAPIException(); res = (*func)(self); assert(res == 0 || res == 1); assert(!PyErr_Occurred()); return PyBool_FromLong((long)res); } static PyObject* wrap_binaryfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_binaryfunc", WRAP_AVOIDABILITY(self)); binaryfunc func = (binaryfunc)wrapped; PyObject* other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(self, other); } static PyObject* wrap_binaryfunc_l(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_binaryfunc_l", WRAP_AVOIDABILITY(self)); binaryfunc func = (binaryfunc)wrapped; PyObject* other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); if (!(self->cls->tp_flags & Py_TPFLAGS_CHECKTYPES) && !PyType_IsSubtype(other->cls, self->cls)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return (*func)(self, other); } static PyObject* wrap_binaryfunc_r(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_binaryfunc_r", WRAP_AVOIDABILITY(self)); binaryfunc func = (binaryfunc)wrapped; PyObject* other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); if (!(self->cls->tp_flags & Py_TPFLAGS_CHECKTYPES) && !PyType_IsSubtype(other->cls, self->cls)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return (*func)(other, self); } static Py_ssize_t getindex(PyObject* self, PyObject* arg) noexcept { Py_ssize_t i; i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); if (i == -1 && PyErr_Occurred()) return -1; if (i < 0) { PySequenceMethods* sq = Py_TYPE(self)->tp_as_sequence; if (sq && sq->sq_length) { Py_ssize_t n = (*sq->sq_length)(self); if (n < 0) return -1; i += n; } } return i; } static PyObject* wrap_lenfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_lenfunc", WRAP_AVOIDABILITY(self)); lenfunc func = (lenfunc)wrapped; Py_ssize_t res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyInt_FromLong((long)res); } static PyObject* wrap_indexargfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_indexargfunc", WRAP_AVOIDABILITY(self)); ssizeargfunc func = (ssizeargfunc)wrapped; PyObject* o; Py_ssize_t i; if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) return NULL; i = PyNumber_AsSsize_t(o, PyExc_OverflowError); if (i == -1 && PyErr_Occurred()) return NULL; return (*func)(self, i); } static PyObject* wrap_sq_item(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_sq_item", WRAP_AVOIDABILITY(self)); ssizeargfunc func = (ssizeargfunc)wrapped; PyObject* arg; Py_ssize_t i; if (PyTuple_GET_SIZE(args) == 1) { arg = PyTuple_GET_ITEM(args, 0); i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; return (*func)(self, i); } check_num_args(args, 1); assert(PyErr_Occurred()); return NULL; } static PyObject* wrap_ssizessizeargfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_ssizessizeargfunc", WRAP_AVOIDABILITY(self)); ssizessizeargfunc func = (ssizessizeargfunc)wrapped; Py_ssize_t i, j; if (!PyArg_ParseTuple(args, "nn", &i, &j)) return NULL; return (*func)(self, i, j); } static PyObject* wrap_sq_setitem(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_sq_setitem", WRAP_AVOIDABILITY(self)); ssizeobjargproc func = (ssizeobjargproc)wrapped; Py_ssize_t i; int res; PyObject* arg, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) return NULL; i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; res = (*func)(self, i, value); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_sq_delitem(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_sq_delitem", WRAP_AVOIDABILITY(self)); ssizeobjargproc func = (ssizeobjargproc)wrapped; Py_ssize_t i; int res; PyObject* arg; if (!check_num_args(args, 1)) return NULL; arg = PyTuple_GET_ITEM(args, 0); i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; res = (*func)(self, i, NULL); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_ssizessizeobjargproc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_ssizessizeobjargproc", WRAP_AVOIDABILITY(self)); ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped; Py_ssize_t i, j; int res; PyObject* value; if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value)) return NULL; res = (*func)(self, i, j, value); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_delslice(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_delslice", WRAP_AVOIDABILITY(self)); ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped; Py_ssize_t i, j; int res; if (!PyArg_ParseTuple(args, "nn", &i, &j)) return NULL; res = (*func)(self, i, j, NULL); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } /* XXX objobjproc is a misnomer; should be objargpred */ static PyObject* wrap_objobjproc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_objobjproc", WRAP_AVOIDABILITY(self)); objobjproc func = (objobjproc)wrapped; int res; PyObject* value; if (!check_num_args(args, 1)) return NULL; value = PyTuple_GET_ITEM(args, 0); res = (*func)(self, value); if (res == -1 && PyErr_Occurred()) return NULL; else return PyBool_FromLong(res); } static PyObject* wrap_objobjargproc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_objobjargproc", WRAP_AVOIDABILITY(self)); objobjargproc func = (objobjargproc)wrapped; int res; PyObject* key, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) return NULL; res = (*func)(self, key, value); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_delitem(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_delitem", WRAP_AVOIDABILITY(self)); objobjargproc func = (objobjargproc)wrapped; int res; PyObject* key; if (!check_num_args(args, 1)) return NULL; key = PyTuple_GET_ITEM(args, 0); res = (*func)(self, key, NULL); if (res == -1 && PyErr_Occurred()) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* wrap_cmpfunc(PyObject* self, PyObject* args, void* wrapped) noexcept { STAT_TIMER(t0, "us_timer_wrap_cmpfunc", WRAP_AVOIDABILITY(self)); cmpfunc func = (cmpfunc)wrapped; int res; PyObject* other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); if (Py_TYPE(other)->tp_compare != func && !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { PyErr_Format(PyExc_TypeError, "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'", Py_TYPE(self)->tp_name, Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name); return NULL; } res = (*func)(self, other); if (PyErr_Occurred()) return NULL; return PyInt_FromLong((long)res); } static PyObject* wrap_init(PyObject* self, PyObject* args, void* wrapped, PyObject* kwds) noexcept { STAT_TIMER(t0, "us_timer_wrap_init", WRAP_AVOIDABILITY(self)); initproc func = (initproc)wrapped; if (func(self, args, kwds) < 0) return NULL; Py_INCREF(Py_None); return Py_None; } static PyObject* lookup_maybe(PyObject* self, const char* attrstr, PyObject** attrobj) noexcept { PyObject* res; if (*attrobj == NULL) { *attrobj = PyString_InternFromString(attrstr); if (*attrobj == NULL) return NULL; } Box* obj = typeLookup(self->cls, (BoxedString*)*attrobj, NULL); if (obj) { try { return processDescriptor(obj, self, self->cls); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } return obj; } extern "C" PyObject* _PyObject_LookupSpecial(PyObject* self, const char* attrstr, PyObject** attrobj) noexcept { assert(!PyInstance_Check(self)); return lookup_maybe(self, attrstr, attrobj); } static PyObject* lookup_method(PyObject* self, const char* attrstr, PyObject** attrobj) noexcept { PyObject* res = lookup_maybe(self, attrstr, attrobj); if (res == NULL && !PyErr_Occurred()) PyErr_SetObject(PyExc_AttributeError, *attrobj); return res; } // Copied from CPython: static PyObject* call_method(PyObject* o, const char* name, PyObject** nameobj, const char* format, ...) noexcept { va_list va; PyObject* args, * func = 0, *retval; va_start(va, format); func = lookup_maybe(o, name, nameobj); if (func == NULL) { va_end(va); if (!PyErr_Occurred()) PyErr_SetObject(PyExc_AttributeError, *nameobj); return NULL; } if (format && *format) args = Py_VaBuildValue(format, va); else args = PyTuple_New(0); va_end(va); if (args == NULL) return NULL; assert(PyTuple_Check(args)); retval = PyObject_Call(func, args, NULL); Py_DECREF(args); Py_DECREF(func); return retval; } /* Clone of call_method() that returns NotImplemented when the lookup fails. */ static PyObject* call_maybe(PyObject* o, const char* name, PyObject** nameobj, const char* format, ...) noexcept { va_list va; PyObject* args, * func = 0, *retval; va_start(va, format); func = lookup_maybe(o, name, nameobj); if (func == NULL) { va_end(va); if (!PyErr_Occurred()) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return NULL; } if (format && *format) args = Py_VaBuildValue(format, va); else args = PyTuple_New(0); va_end(va); if (args == NULL) return NULL; assert(PyTuple_Check(args)); retval = PyObject_Call(func, args, NULL); Py_DECREF(args); Py_DECREF(func); return retval; } static int half_compare(PyObject* self, PyObject* other) noexcept { PyObject* func, *args, *res; static PyObject* cmp_str; Py_ssize_t c; func = lookup_method(self, "__cmp__", &cmp_str); if (func == NULL) { PyErr_Clear(); } else { args = PyTuple_Pack(1, other); if (args == NULL) res = NULL; else { res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); if (res != Py_NotImplemented) { if (res == NULL) return -2; c = PyInt_AsLong(res); Py_DECREF(res); if (c == -1 && PyErr_Occurred()) return -2; return (c < 0) ? -1 : (c > 0) ? 1 : 0; } Py_DECREF(res); } return 2; } /* This slot is published for the benefit of try_3way_compare in object.c */ extern "C" int _PyObject_SlotCompare(PyObject* self, PyObject* other) noexcept { int c; if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) { c = half_compare(self, other); if (c <= 1) return c; } if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) { c = half_compare(other, self); if (c < -1) return -2; if (c <= 1) return -c; } return (void*)self < (void*)other ? -1 : (void*)self > (void*)other ? 1 : 0; } #define SLOT_AVOIDABILITY(obj) ((obj)->cls->is_user_defined ? 10 : 20) static PyObject* slot_tp_repr(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_tprepr", SLOT_AVOIDABILITY(self)); try { return repr(self); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } static PyObject* slot_tp_str(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_tpstr", SLOT_AVOIDABILITY(self)); try { return str(self); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } static long slot_tp_hash(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_tphash", SLOT_AVOIDABILITY(self)); PyObject* func; static PyObject* hash_str, *eq_str, *cmp_str; long h; func = lookup_method(self, "__hash__", &hash_str); if (func != NULL && func != Py_None) { PyObject* res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; if (PyLong_Check(res)) h = PyLong_Type.tp_hash(res); else h = PyInt_AsLong(res); Py_DECREF(res); } else { Py_XDECREF(func); /* may be None */ PyErr_Clear(); func = lookup_method(self, "__eq__", &eq_str); if (func == NULL) { PyErr_Clear(); func = lookup_method(self, "__cmp__", &cmp_str); } if (func != NULL) { Py_DECREF(func); return PyObject_HashNotImplemented(self); } PyErr_Clear(); h = _Py_HashPointer((void*)self); } if (h == -1 && !PyErr_Occurred()) h = -2; return h; } PyObject* slot_tp_call(PyObject* self, PyObject* args, PyObject* kwds) noexcept { STAT_TIMER(t0, "us_timer_slot_tpcall", SLOT_AVOIDABILITY(self)); try { Py_FatalError("this function is untested"); // TODO: runtime ICs? return runtimeCall(self, ArgPassSpec(0, 0, true, true), args, kwds, NULL, NULL, NULL); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } static const char* name_op[] = { "__lt__", "__le__", "__eq__", "__ne__", "__gt__", "__ge__", }; static PyObject* half_richcompare(PyObject* self, PyObject* other, int op) noexcept { PyObject* func, *args, *res; static PyObject* op_str[6]; func = lookup_method(self, name_op[op], &op_str[op]); if (func == NULL) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } args = PyTuple_Pack(1, other); if (args == NULL) res = NULL; else { res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); return res; } /* Pyston change: static*/ PyObject* slot_tp_richcompare(PyObject* self, PyObject* other, int op) noexcept { STAT_TIMER(t0, "us_timer_slot_tprichcompare", SLOT_AVOIDABILITY(self)); static StatCounter slowpath_richcompare("slowpath_richcompare"); slowpath_richcompare.log(); #if 0 std::string per_name_stat_name = "slowpath_richcompare." + std::string(self->cls->tp_name); int id = Stats::getStatId(per_name_stat_name); Stats::log(id); #endif PyObject* res; if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) { res = half_richcompare(self, other, op); if (res != Py_NotImplemented) return res; Py_DECREF(res); } if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) { res = half_richcompare(other, self, _Py_SwappedOp[op]); if (res != Py_NotImplemented) { return res; } Py_DECREF(res); } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } PyObject* slot_tp_iter(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_tpiter", SLOT_AVOIDABILITY(self)); PyObject* func, *res; static PyObject* iter_str, *getitem_str; func = lookup_method(self, "__iter__", &iter_str); if (func != NULL) { PyObject* args; args = res = PyTuple_New(0); if (args != NULL) { res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); return res; } PyErr_Clear(); func = lookup_method(self, "__getitem__", &getitem_str); if (func == NULL) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not iterable", Py_TYPE(self)->tp_name); return NULL; } Py_DECREF(func); return PySeqIter_New(self); } /* Pyston change: static */ PyObject* slot_tp_iternext(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_tpiternext", SLOT_AVOIDABILITY(self)); static PyObject* next_str; return call_method(self, "next", &next_str, "()"); } static bool slotTppHasnext(PyObject* self) { STAT_TIMER(t0, "us_timer_slot_tpphasnext", SLOT_AVOIDABILITY(self)); static PyObject* hasnext_str; Box* r = self->hasnextOrNullIC(); assert(r); return r->nonzeroIC(); } static PyObject* slot_tp_descr_get(PyObject* self, PyObject* obj, PyObject* type) noexcept { STAT_TIMER(t0, "us_timer_slot_tpdescrget", SLOT_AVOIDABILITY(self)); PyTypeObject* tp = Py_TYPE(self); PyObject* get; static BoxedString* get_str = internStringImmortal("__get__"); get = typeLookup(tp, get_str, NULL); if (get == NULL) { /* Avoid further slowdowns */ if (tp->tp_descr_get == slot_tp_descr_get) tp->tp_descr_get = NULL; Py_INCREF(self); return self; } if (obj == NULL) obj = Py_None; if (type == NULL) type = Py_None; return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); } static PyObject* slot_tp_tpp_descr_get(PyObject* self, PyObject* obj, PyObject* type) noexcept { STAT_TIMER(t0, "us_timer_slot_tppdescrget", SLOT_AVOIDABILITY(self)); assert(self->cls->tpp_descr_get); try { return self->cls->tpp_descr_get(self, obj, type); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } static PyObject* slot_tp_getattro(PyObject* self, PyObject* name) noexcept { STAT_TIMER(t0, "us_timer_slot_tpgetattro", SLOT_AVOIDABILITY(self)); static PyObject* getattribute_str = NULL; return call_method(self, "__getattribute__", &getattribute_str, "(O)", name); } static int slot_tp_setattro(PyObject* self, PyObject* name, PyObject* value) noexcept { STAT_TIMER(t0, "us_timer_slot_tpsetattro", SLOT_AVOIDABILITY(self)); PyObject* res; static PyObject* delattr_str, *setattr_str; if (value == NULL) res = call_method(self, "__delattr__", &delattr_str, "(O)", name); else res = call_method(self, "__setattr__", &setattr_str, "(OO)", name, value); if (res == NULL) return -1; Py_DECREF(res); return 0; } static PyObject* call_attribute(PyObject* self, PyObject* attr, PyObject* name) noexcept { PyObject* res, * descr = NULL; descrgetfunc f = Py_TYPE(attr)->tp_descr_get; if (f != NULL) { descr = f(attr, self, (PyObject*)(Py_TYPE(self))); if (descr == NULL) return NULL; else attr = descr; } try { res = runtimeCall(attr, ArgPassSpec(1, 0, false, false), name, NULL, NULL, NULL, NULL); } catch (ExcInfo e) { setCAPIException(e); Py_XDECREF(descr); return NULL; } Py_XDECREF(descr); return res; } /* Pyston change: static */ PyObject* slot_tp_getattr_hook(PyObject* self, PyObject* name) noexcept { try { assert(name->cls == str_cls); return slotTpGetattrHookInternal(self, (BoxedString*)name, NULL); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } Box* slotTpGetattrHookInternal(Box* self, BoxedString* name, GetattrRewriteArgs* rewrite_args) { STAT_TIMER(t0, "us_timer_slot_tpgetattrhook", SLOT_AVOIDABILITY(self)); PyObject* getattr, *getattribute, * res = NULL; /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with __getattr__, even when the attribute is present. So we use _PyType_Lookup and create the method only when needed, with call_attribute. */ static BoxedString* _getattr_str = internStringImmortal("__getattr__"); // Don't need to do this in the rewritten version; if a __getattr__ later gets removed: // - if we ever get to the "call __getattr__" portion of the rewrite, the guards will // fail and we will end up back here // - if we never get to the "call __getattr__" portion and the "calling __getattribute__" // portion still has its guards pass, then that section is still behaviorally correct, and // I think should be close to as fast as the normal rewritten version we would generate. getattr = typeLookup(self->cls, _getattr_str, NULL); if (getattr == NULL) { assert(!rewrite_args || !rewrite_args->out_success); /* No __getattr__ hook: use a simpler dispatcher */ self->cls->tp_getattro = slot_tp_getattro; return slot_tp_getattro(self, name); } /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with __getattr__, even when self has the default __getattribute__ method. So we use _PyType_Lookup and create the method only when needed, with call_attribute. */ static BoxedString* _getattribute_str = internStringImmortal("__getattribute__"); RewriterVar* r_getattribute = NULL; if (rewrite_args) { RewriterVar* r_obj_cls = rewrite_args->obj->getAttr(offsetof(Box, cls), Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_obj_cls, Location::any()); getattribute = typeLookup(self->cls, _getattribute_str, &grewrite_args); if (!grewrite_args.out_success) rewrite_args = NULL; else if (getattribute) r_getattribute = grewrite_args.out_rtn; } else { getattribute = typeLookup(self->cls, _getattribute_str, NULL); } // Not sure why CPython checks if getattribute is NULL since I don't think that should happen. // Is there some legacy way of creating types that don't inherit from object? Anyway, I think we // have the right behavior even if getattribute was somehow NULL, but add an assert because that // case would still be very surprising to me: assert(getattribute); if (getattribute == NULL || (Py_TYPE(getattribute) == wrapperdescr_cls && ((BoxedWrapperDescriptor*)getattribute)->wrapped == (void*)PyObject_GenericGetAttr)) { assert(PyString_CHECK_INTERNED(name)); if (rewrite_args) { // Fetching getattribute should have done the appropriate guarding on whether or not // getattribute exists. if (getattribute) r_getattribute->addGuard((intptr_t)getattribute); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj, rewrite_args->destination); try { res = getattrInternalGeneric(self, name, &grewrite_args, false, false, NULL, NULL); } catch (ExcInfo e) { if (!e.matches(AttributeError)) throw e; grewrite_args.out_success = false; res = NULL; } if (!grewrite_args.out_success) rewrite_args = NULL; else if (res) rewrite_args->out_rtn = grewrite_args.out_rtn; } else { try { res = getattrInternalGeneric(self, name, NULL, false, false, NULL, NULL); } catch (ExcInfo e) { if (!e.matches(AttributeError)) throw e; res = NULL; } } } else { rewrite_args = NULL; res = call_attribute(self, getattribute, name); if (res == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else throwCAPIException(); } } // At this point, CPython would have three cases: res is non-NULL and no exception was thrown, // or res is NULL and an exception was thrown and either it was an AttributeError (in which case // we call __getattr__) or it wan't (in which case it propagates). // // We handled it differently: if a non-AttributeError was thrown, we already would have propagated // it. So there are only two cases: res is non-NULL if the attribute exists, or it is NULL if it // doesn't exist. if (res) { if (rewrite_args) rewrite_args->out_success = true; return res; } assert(!PyErr_Occurred()); CallattrFlags callattr_flags = {.cls_only = true, .null_on_nonexistent = false, .argspec = ArgPassSpec(1) }; if (rewrite_args) { // I was thinking at first that we could try to catch any AttributeErrors here and still // write out valid rewrite, but // - we need to let the original AttributeError propagate and not generate a new, potentially-different one // - we have no way of signalling that "we didn't get an attribute this time but that may be different // in future executions through the IC". // I think this should only end up mattering anyway if the getattr site throws every single time. CallRewriteArgs crewrite_args(rewrite_args->rewriter, rewrite_args->obj, rewrite_args->destination); assert(PyString_CHECK_INTERNED(name) == SSTATE_INTERNED_IMMORTAL); crewrite_args.arg1 = rewrite_args->rewriter->loadConst((intptr_t)name, Location::forArg(1)); res = callattrInternal<CXX>(self, _getattr_str, LookupScope::CLASS_ONLY, &crewrite_args, ArgPassSpec(1), name, NULL, NULL, NULL, NULL); assert(res); if (!crewrite_args.out_success) rewrite_args = NULL; else rewrite_args->out_rtn = crewrite_args.out_rtn; } else { // TODO: we already fetched the getattr attribute, it would be faster to call it rather than do // a second callattr. My guess though is that the gains would be small, so I would prefer to keep // the rewrite_args and non-rewrite_args case the same. // Actually, we might have gotten to the point that doing a runtimeCall on an instancemethod is as // fast as a callattr, but that hasn't typically been the case. res = callattrInternal<CXX>(self, _getattr_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(1), name, NULL, NULL, NULL, NULL); assert(res); } if (rewrite_args) rewrite_args->out_success = true; return res; } /* Pyston change: static */ PyObject* slot_tp_new(PyTypeObject* self, PyObject* args, PyObject* kwds) noexcept { STAT_TIMER(t0, "us_timer_slot_tpnew", SLOT_AVOIDABILITY(self)); try { // TODO: runtime ICs? static BoxedString* _new_str = internStringImmortal("__new__"); Box* new_attr = typeLookup(self, _new_str, NULL); assert(new_attr); new_attr = processDescriptor(new_attr, None, self); return runtimeCall(new_attr, ArgPassSpec(1, 0, true, true), self, args, kwds, NULL, NULL); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } static PyObject* slot_tp_del(PyObject* self) noexcept { static BoxedString* del_str = internStringImmortal("__del__"); try { // TODO: runtime ICs? Box* del_attr = typeLookup(self->cls, del_str, NULL); assert(del_attr); CallattrFlags flags{.cls_only = false, .null_on_nonexistent = true, .argspec = ArgPassSpec(0, 0, false, false) }; return callattr(self, del_str, flags, NULL, NULL, NULL, NULL, NULL); } catch (ExcInfo e) { // Python does not support exceptions thrown inside finalizers. Instead, it just // prints a warning that an exception was throw to stderr but ignores it. setCAPIException(e); PyErr_WriteUnraisable(self); return NULL; } } static int slot_tp_init(PyObject* self, PyObject* args, PyObject* kwds) noexcept { STAT_TIMER(t0, "us_timer_slot_tpinit", SLOT_AVOIDABILITY(self)); static PyObject* init_str; PyObject* meth = lookup_method(self, "__init__", &init_str); PyObject* res; if (meth == NULL) return -1; res = PyObject_Call(meth, args, kwds); Py_DECREF(meth); if (res == NULL) return -1; if (res != Py_None) { PyErr_Format(PyExc_TypeError, "__init__() should return None, not '%.200s'", Py_TYPE(res)->tp_name); Py_DECREF(res); return -1; } Py_DECREF(res); return 0; } PyObject* slot_sq_item(PyObject* self, Py_ssize_t i) noexcept { STAT_TIMER(t0, "us_timer_slot_sqitem", SLOT_AVOIDABILITY(self)); try { return getitem(self, boxInt(i)); } catch (ExcInfo e) { setCAPIException(e); return NULL; } } /* Pyston change: static */ Py_ssize_t slot_sq_length(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_sqlength", SLOT_AVOIDABILITY(self)); static PyObject* len_str; PyObject* res = call_method(self, "__len__", &len_str, "()"); Py_ssize_t len; if (res == NULL) return -1; len = PyInt_AsSsize_t(res); Py_DECREF(res); if (len < 0) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "__len__() should return >= 0"); return -1; } return len; } static PyObject* slot_sq_slice(PyObject* self, Py_ssize_t i, Py_ssize_t j) noexcept { STAT_TIMER(t0, "us_timer_slot_sqslice", SLOT_AVOIDABILITY(self)); static PyObject* getslice_str; if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; " "use __getitem__", 1) < 0) return NULL; return call_method(self, "__getslice__", &getslice_str, "nn", i, j); } static int slot_sq_ass_item(PyObject* self, Py_ssize_t index, PyObject* value) noexcept { STAT_TIMER(t0, "us_timer_slot_sqassitem", SLOT_AVOIDABILITY(self)); PyObject* res; static PyObject* delitem_str, *setitem_str; if (value == NULL) res = call_method(self, "__delitem__", &delitem_str, "(n)", index); else res = call_method(self, "__setitem__", &setitem_str, "(nO)", index, value); if (res == NULL) return -1; Py_DECREF(res); return 0; } static int slot_sq_ass_slice(PyObject* self, Py_ssize_t i, Py_ssize_t j, PyObject* value) noexcept { STAT_TIMER(t0, "us_timer_slot_sqassslice", SLOT_AVOIDABILITY(self)); PyObject* res; static PyObject* delslice_str, *setslice_str; if (value == NULL) { if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; " "use __delitem__", 1) < 0) return -1; res = call_method(self, "__delslice__", &delslice_str, "(nn)", i, j); } else { if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; " "use __setitem__", 1) < 0) return -1; res = call_method(self, "__setslice__", &setslice_str, "(nnO)", i, j, value); } if (res == NULL) return -1; Py_DECREF(res); return 0; } /* Pyston change: static*/ int slot_sq_contains(PyObject* self, PyObject* value) noexcept { STAT_TIMER(t0, "us_timer_slot_sqcontains", SLOT_AVOIDABILITY(self)); PyObject* func, *res, *args; int result = -1; static PyObject* contains_str; func = lookup_maybe(self, "__contains__", &contains_str); if (func != NULL) { args = PyTuple_Pack(1, value); if (args == NULL) res = NULL; else { res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); if (res != NULL) { result = PyObject_IsTrue(res); Py_DECREF(res); } } else if (!PyErr_Occurred()) { /* Possible results: -1 and 1 */ Py_FatalError("unimplemented"); // result = (int)_PySequence_IterSearch(self, value, PY_ITERSEARCH_CONTAINS); } return result; } // Copied from CPython: #define SLOT0(FUNCNAME, OPSTR) \ static PyObject* FUNCNAME(PyObject* self) noexcept { \ STAT_TIMER(t0, "us_timer_" #FUNCNAME, SLOT_AVOIDABILITY(self)); \ static PyObject* cache_str; \ return call_method(self, OPSTR, &cache_str, "()"); \ } #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ /* Pyston change: static */ PyObject* FUNCNAME(PyObject* self, ARG1TYPE arg1) noexcept { \ STAT_TIMER(t0, "us_timer_" #FUNCNAME, SLOT_AVOIDABILITY(self)); \ static PyObject* cache_str; \ return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ } /* Boolean helper for SLOT1BINFULL(). right.__class__ is a nontrivial subclass of left.__class__. */ static int method_is_overloaded(PyObject* left, PyObject* right, const char* name) noexcept { PyObject* a, *b; int ok; b = PyObject_GetAttrString((PyObject*)(Py_TYPE(right)), name); if (b == NULL) { PyErr_Clear(); /* If right doesn't have it, it's not overloaded */ return 0; } a = PyObject_GetAttrString((PyObject*)(Py_TYPE(left)), name); if (a == NULL) { PyErr_Clear(); Py_DECREF(b); /* If right has it but left doesn't, it's overloaded */ return 1; } ok = PyObject_RichCompareBool(a, b, Py_NE); Py_DECREF(a); Py_DECREF(b); if (ok < 0) { PyErr_Clear(); return 0; } return ok; } #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \ static PyObject* FUNCNAME(PyObject* self, PyObject* other) noexcept { \ static PyObject* cache_str, *rcache_str; \ int do_other = Py_TYPE(self) != Py_TYPE(other) && Py_TYPE(other)->tp_as_number != NULL \ && Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ if (Py_TYPE(self)->tp_as_number != NULL && Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ PyObject* r; \ if (do_other && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) \ && method_is_overloaded(self, other, ROPSTR)) { \ r = call_maybe(other, ROPSTR, &rcache_str, "(O)", self); \ if (r != Py_NotImplemented) \ return r; \ Py_DECREF(r); \ do_other = 0; \ } \ r = call_maybe(self, OPSTR, &cache_str, "(O)", other); \ if (r != Py_NotImplemented || Py_TYPE(other) == Py_TYPE(self)) \ return r; \ Py_DECREF(r); \ } \ if (do_other) { \ return call_maybe(other, ROPSTR, &rcache_str, "(O)", self); \ } \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \ static PyObject* FUNCNAME(PyObject* self, ARG1TYPE arg1, ARG2TYPE arg2) { \ static PyObject* cache_str; \ return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1, arg2); \ } #define slot_mp_length slot_sq_length SLOT1(slot_mp_subscript, "__getitem__", PyObject*, "O") static int slot_mp_ass_subscript(PyObject* self, PyObject* key, PyObject* value) noexcept { STAT_TIMER(t0, "us_timer_slot_mpasssubscript", SLOT_AVOIDABILITY(self)); PyObject* res; static PyObject* delitem_str, *setitem_str; if (value == NULL) res = call_method(self, "__delitem__", &delitem_str, "(O)", key); else res = call_method(self, "__setitem__", &setitem_str, "(OO)", key, value); if (res == NULL) return -1; Py_DECREF(res); return 0; } SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__") SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__") SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__") SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__") SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__") static PyObject* slot_nb_power(PyObject*, PyObject*, PyObject*) noexcept; SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, nb_power, "__pow__", "__rpow__") static PyObject* slot_nb_power(PyObject* self, PyObject* other, PyObject* modulus) noexcept { STAT_TIMER(t0, "us_timer_slot_nbpower", SLOT_AVOIDABILITY(self)); static PyObject* pow_str; if (modulus == Py_None) return slot_nb_power_binary(self, other); /* Three-arg power doesn't use __rpow__. But ternary_op can call this when the second argument's type uses slot_nb_power, so check before calling self.__pow__. */ if (Py_TYPE(self)->tp_as_number != NULL && Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { return call_method(self, "__pow__", &pow_str, "(OO)", other, modulus); } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } SLOT0(slot_nb_negative, "__neg__") SLOT0(slot_nb_positive, "__pos__") SLOT0(slot_nb_absolute, "__abs__") static int slot_nb_nonzero(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_nbnonzero", SLOT_AVOIDABILITY(self)); PyObject* func, *args; static PyObject* nonzero_str, *len_str; int result = -1; int using_len = 0; func = lookup_maybe(self, "__nonzero__", &nonzero_str); if (func == NULL) { if (PyErr_Occurred()) return -1; func = lookup_maybe(self, "__len__", &len_str); if (func == NULL) return PyErr_Occurred() ? -1 : 1; using_len = 1; } args = PyTuple_New(0); if (args != NULL) { PyObject* temp = PyObject_Call(func, args, NULL); Py_DECREF(args); if (temp != NULL) { if (PyInt_CheckExact(temp) || PyBool_Check(temp)) result = PyObject_IsTrue(temp); else { PyErr_Format(PyExc_TypeError, "%s should return " "bool or int, returned %s", (using_len ? "__len__" : "__nonzero__"), temp->cls->tp_name); result = -1; } Py_DECREF(temp); } } Py_DECREF(func); return result; } static PyObject* slot_nb_index(PyObject* self) noexcept { STAT_TIMER(t0, "us_timer_slot_nbindex", SLOT_AVOIDABILITY(self)); static PyObject* index_str; return call_method(self, "__index__", &index_str, "()"); } SLOT0(slot_nb_invert, "__invert__") SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__") SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__") SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__") SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__") SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__") static int slot_nb_coerce(PyObject** a, PyObject** b) noexcept { STAT_TIMER(t0, "us_timer_slot_nbcoerce", std::min(SLOT_AVOIDABILITY(*a), SLOT_AVOIDABILITY(*b))); static PyObject* coerce_str; PyObject* self = *a, * other = *b; if (self->cls->tp_as_number != NULL && self->cls->tp_as_number->nb_coerce == slot_nb_coerce) { PyObject* r; r = call_maybe(self, "__coerce__", &coerce_str, "(O)", other); if (r == NULL) return -1; if (r == Py_NotImplemented) { Py_DECREF(r); } else { if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { PyErr_SetString(PyExc_TypeError, "__coerce__ didn't return a 2-tuple"); Py_DECREF(r); return -1; } *a = PyTuple_GET_ITEM(r, 0); Py_INCREF(*a); *b = PyTuple_GET_ITEM(r, 1); Py_INCREF(*b); Py_DECREF(r); return 0; } } if (other->cls->tp_as_number != NULL && other->cls->tp_as_number->nb_coerce == slot_nb_coerce) { PyObject* r; r = call_maybe(other, "__coerce__", &coerce_str, "(O)", self); if (r == NULL) return -1; if (r == Py_NotImplemented) { Py_DECREF(r); return 1; } if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { PyErr_SetString(PyExc_TypeError, "__coerce__ didn't return a 2-tuple"); Py_DECREF(r); return -1; } *a = PyTuple_GET_ITEM(r, 1); Py_INCREF(*a); *b = PyTuple_GET_ITEM(r, 0); Py_INCREF(*b); Py_DECREF(r); return 0; } return 1; } SLOT0(slot_nb_int, "__int__") SLOT0(slot_nb_long, "__long__") SLOT0(slot_nb_float, "__float__") SLOT0(slot_nb_oct, "__oct__") SLOT0(slot_nb_hex, "__hex__") SLOT1(slot_nb_inplace_add, "__iadd__", PyObject*, "O") SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject*, "O") SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject*, "O") SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject*, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject*, "O") /* Can't use SLOT1 here, because nb_inplace_power is ternary */ static PyObject* slot_nb_inplace_power(PyObject* self, PyObject* arg1, PyObject* arg2) { STAT_TIMER(t0, "us_timer_slot_nbinplacepower", SLOT_AVOIDABILITY(self)); static PyObject* cache_str; return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject*, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject*, "O") SLOT1(slot_nb_inplace_and, "__iand__", PyObject*, "O") SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject*, "O") SLOT1(slot_nb_inplace_or, "__ior__", PyObject*, "O") SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, "__floordiv__", "__rfloordiv__") SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject*, "O") SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject*, "O") typedef wrapper_def slotdef; static void** slotptr(BoxedClass* type, int offset) noexcept { // We use the index into PyHeapTypeObject as the canonical way to represent offsets, even though we are not // (currently) using that object representation // copied from CPython: /* Note: this depends on the order of the members of PyHeapTypeObject! */ assert(offset >= 0); assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); char* ptr; if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { ptr = (char*)type->tp_as_sequence; offset -= offsetof(PyHeapTypeObject, as_sequence); } else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { ptr = (char*)type->tp_as_mapping; offset -= offsetof(PyHeapTypeObject, as_mapping); } else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { ptr = (char*)type->tp_as_number; offset -= offsetof(PyHeapTypeObject, as_number); } else { ptr = (char*)type; } if (ptr != NULL) ptr += offset; return (void**)ptr; } // Copied from CPython: #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ { NAME, offsetof(PyTypeObject, SLOT), (void*)(FUNCTION), WRAPPER, PyDoc_STR(DOC), 0, NULL } #define TPPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ { NAME, offsetof(PyTypeObject, SLOT), (void*)(FUNCTION), WRAPPER, PyDoc_STR(DOC), PyWrapperFlag_PYSTON, NULL } #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ { NAME, offsetof(PyTypeObject, SLOT), (void*)(FUNCTION), WRAPPER, PyDoc_STR(DOC), FLAGS, NULL } #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ { NAME, offsetof(PyHeapTypeObject, SLOT), (void*)(FUNCTION), WRAPPER, PyDoc_STR(DOC), 0, NULL } #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, "x." NAME "() <==> " DOC) #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, "x." NAME "(y) <==> x" DOC "y") #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, "x." NAME "(y) <==> x" DOC "y") #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, "x." NAME "(y) <==> y" DOC "x") #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, "x." NAME "(y) <==> " DOC) #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, "x." NAME "(y) <==> " DOC) static slotdef slotdefs[] = { TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc, "x.__cmp__(y) <==> cmp(x,y)"), TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, "x.__repr__() <==> repr(x)"), TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, "x.__hash__() <==> hash(x)"), FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, "x.__str__() <==> str(x)"), TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, "x.__setattr__('name', value) <==> x.name = value"), TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, "x.__delattr__('name') <==> del x.name"), TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, "x.__lt__(y) <==> x<y"), TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le, "x.__le__(y) <==> x<=y"), TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, "x.__eq__(y) <==> x==y"), TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, "x.__ne__(y) <==> x!=y"), TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, "x.__gt__(y) <==> x>y"), TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, "x.__ge__(y) <==> x>=y"), TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, "x.__iter__() <==> iter(x)"), TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next, "x.next() -> the next value, or raise StopIteration"), TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, "descr.__get__(obj[, type]) -> value"), FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, "x.__init__(...) initializes x; " "see help(type(x)) for signature", PyWrapperFlag_KEYWORDS), TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), FLSLOT("__class__", has___class__, NULL, NULL, "", PyWrapperFlag_BOOL), FLSLOT("__instancecheck__", has_instancecheck, NULL, NULL, "", PyWrapperFlag_BOOL), FLSLOT("__getattribute__", has_getattribute, NULL, NULL, "", PyWrapperFlag_BOOL), TPPSLOT("__hasnext__", tpp_hasnext, slotTppHasnext, wrapInquirypred, "hasnext"), BINSLOT("__add__", nb_add, slot_nb_add, "+"), // [force clang-format to line break] RBINSLOT("__radd__", nb_add, slot_nb_add, "+"), // BINSLOT("__sub__", nb_subtract, slot_nb_subtract, "-"), // RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, "-"), // BINSLOT("__mul__", nb_multiply, slot_nb_multiply, "*"), // RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, "*"), // BINSLOT("__div__", nb_divide, slot_nb_divide, "/"), // RBINSLOT("__rdiv__", nb_divide, slot_nb_divide, "/"), // BINSLOT("__mod__", nb_remainder, slot_nb_remainder, "%"), // RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, "%"), // BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, "divmod(x, y)"), // RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, "divmod(y, x)"), // NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, "x.__pow__(y[, z]) <==> pow(x, y[, z])"), // NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), // UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), // UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), // UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, "abs(x)"), // UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred, "x != 0"), // UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), // BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), // RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), // BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), // RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), // BINSLOT("__and__", nb_and, slot_nb_and, "&"), // RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), // BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), // RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), // BINSLOT("__or__", nb_or, slot_nb_or, "|"), // RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), // NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc, "x.__coerce__(y) <==> coerce(x, y)"), // UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, "int(x)"), // UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc, "long(x)"), // UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, "float(x)"), // UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc, "oct(x)"), // UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc, "hex(x)"), // IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, wrap_binaryfunc, "+="), // IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, wrap_binaryfunc, "-="), // IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, wrap_binaryfunc, "*="), // IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide, wrap_binaryfunc, "/="), // IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, wrap_binaryfunc, "%="), // IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, wrap_binaryfunc, "**="), // IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, wrap_binaryfunc, "<<="), // IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, wrap_binaryfunc, ">>="), // IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, wrap_binaryfunc, "&="), // IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, wrap_binaryfunc, "^="), // IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, wrap_binaryfunc, "|="), // BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), // RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), // BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), // RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), // IBSLOT("__ifloordiv__", nb_inplace_floor_divide, slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), // IBSLOT("__itruediv__", nb_inplace_true_divide, slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), // NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, "x[y:z] <==> x[y.__index__():z.__index__()]"), // MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, "x.__len__() <==> len(x)"), MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, wrap_binaryfunc, "x.__getitem__(y) <==> x[y]"), MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, wrap_objobjargproc, "x.__setitem__(i, y) <==> x[i]=y"), MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, wrap_delitem, "x.__delitem__(y) <==> del x[y]"), SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, "x.__len__() <==> len(x)"), /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. The logic in abstract.c always falls back to nb_add/nb_multiply in this case. Defining both the nb_* and the sq_* slots to call the user-defined methods has unexpected side-effects, as shown by test_descr.notimplemented() */ SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, "x.__add__(y) <==> x+y"), SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, "x.__mul__(n) <==> x*n"), SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, "x.__rmul__(n) <==> n*x"), SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, "x.__getitem__(y) <==> x[y]"), SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc, "x.__getslice__(i, j) <==> x[i:j]\n\ \n\ Use of negative indices is not supported."), SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, "x.__setitem__(i, y) <==> x[i]=y"), SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, "x.__delitem__(y) <==> del x[y]"), SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice, wrap_ssizessizeobjargproc, "x.__setslice__(i, j, y) <==> x[i:j]=y\n\ \n\ Use of negative indices is not supported."), SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice, "x.__delslice__(i, j) <==> del x[i:j]\n\ \n\ Use of negative indices is not supported."), SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, "x.__contains__(y) <==> y in x"), SQSLOT("__iadd__", sq_inplace_concat, NULL, wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), SQSLOT("__imul__", sq_inplace_repeat, NULL, wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), { "", 0, NULL, NULL, "", 0, NULL } }; static void init_slotdefs() noexcept { static bool initialized = false; if (initialized) return; for (int i = 0; i < sizeof(slotdefs) / sizeof(slotdefs[0]); i++) { slotdefs[i].name_strobj = internStringImmortal(slotdefs[i].name.data()); if (i > 0) { if (!slotdefs[i].name.size()) continue; #ifndef NDEBUG if (slotdefs[i - 1].offset > slotdefs[i].offset) { printf("slotdef for %s in the wrong place\n", slotdefs[i - 1].name.data()); for (int j = i; j < sizeof(slotdefs) / sizeof(slotdefs[0]); j++) { if (slotdefs[i - 1].offset <= slotdefs[j].offset) { printf("Should go before %s\n", slotdefs[j].name.data()); break; } } } #endif ASSERT(slotdefs[i].offset >= slotdefs[i - 1].offset, "%d %s", i, slotdefs[i - 1].name.data()); } } initialized = true; } /* Length of array of slotdef pointers used to store slots with the same __name__. There should be at most MAX_EQUIV-1 slotdef entries with the same __name__, for any __name__. Since that's a static property, it is appropriate to declare fixed-size arrays for this. */ #define MAX_EQUIV 10 /* Return a slot pointer for a given name, but ONLY if the attribute has exactly one slot function. The name must be an interned string. */ static void** resolve_slotdups(PyTypeObject* type, const std::string& name) noexcept { /* XXX Maybe this could be optimized more -- but is it worth it? */ /* pname and ptrs act as a little cache */ static std::string pname; static slotdef* ptrs[MAX_EQUIV]; slotdef* p, **pp; void** res, **ptr; if (pname != name) { /* Collect all slotdefs that match name into ptrs. */ pname = name; pp = ptrs; for (p = slotdefs; p->name.size() != 0; p++) { if (p->name == name) *pp++ = p; } *pp = NULL; } /* Look in all matching slots of the type; if exactly one of these has a filled-in slot, return its value. Otherwise return NULL. */ res = NULL; for (pp = ptrs; *pp; pp++) { ptr = slotptr(type, (*pp)->offset); if (ptr == NULL || *ptr == NULL) continue; if (res != NULL) return NULL; res = ptr; } return res; } static const slotdef* update_one_slot(BoxedClass* type, const slotdef* p) noexcept { assert(p->name.size() != 0); PyObject* descr; BoxedWrapperDescriptor* d; void* generic = NULL, * specific = NULL; int use_generic = 0; int offset = p->offset; void** ptr = slotptr(type, offset); if (ptr == NULL) { do { ++p; } while (p->offset == offset); return p; } do { descr = typeLookup(type, p->name_strobj, NULL); if (p->flags & PyWrapperFlag_BOOL) { // We are supposed to iterate over each slotdef; for now just assert that // there was only one: assert((p + 1)->offset > p->offset); static BoxedString* class_str = internStringImmortal("__class__"); if (p->name_strobj == class_str) { if (descr == object_cls->getattr(class_str)) descr = NULL; } static BoxedString* getattribute_str = internStringImmortal("__getattribute__"); if (p->name_strobj == getattribute_str) { if (descr && descr->cls == wrapperdescr_cls && ((BoxedWrapperDescriptor*)descr)->wrapped == PyObject_GenericGetAttr) descr = NULL; } *(bool*)ptr = (bool)descr; return p + 1; } if (descr == NULL) { if (ptr == (void**)&type->tp_iternext) { specific = (void*)_PyObject_NextNotImplemented; } continue; } if (Py_TYPE(descr) == wrapperdescr_cls && ((BoxedWrapperDescriptor*)descr)->wrapper->name == std::string(p->name)) { void** tptr = resolve_slotdups(type, p->name); if (tptr == NULL || tptr == ptr) generic = p->function; d = (BoxedWrapperDescriptor*)descr; if (d->wrapper->wrapper == p->wrapper && PyType_IsSubtype(type, d->type) && ((d->wrapper->flags & PyWrapperFlag_PYSTON) == (p->flags & PyWrapperFlag_PYSTON))) { if (specific == NULL || specific == d->wrapped) specific = d->wrapped; else use_generic = 1; } } else if (Py_TYPE(descr) == &PyCFunction_Type && PyCFunction_GET_FUNCTION(descr) == (PyCFunction)tp_new_wrapper && ptr == (void**)&type->tp_new) { /* The __new__ wrapper is not a wrapper descriptor, so must be special-cased differently. If we don't do this, creating an instance will always use slot_tp_new which will look up __new__ in the MRO which will call tp_new_wrapper which will look through the base classes looking for a static base and call its tp_new (usually PyType_GenericNew), after performing various sanity checks and constructing a new argument list. Cut all that nonsense short -- this speeds up instance creation tremendously. */ specific = (void*)type->tp_new; /* XXX I'm not 100% sure that there isn't a hole in this reasoning that requires additional sanity checks. I'll buy the first person to point out a bug in this reasoning a beer. */ } else if (offset == offsetof(BoxedClass, tp_descr_get) && descr->cls == function_cls && static_cast<BoxedFunction*>(descr)->f->always_use_version) { type->tpp_descr_get = (descrgetfunc) static_cast<BoxedFunction*>(descr)->f->always_use_version->code; specific = (void*)slot_tp_tpp_descr_get; } else if (descr == Py_None && ptr == (void**)&type->tp_hash) { /* We specifically allow __hash__ to be set to None to prevent inheritance of the default implementation from object.__hash__ */ specific = (void*)PyObject_HashNotImplemented; } else { use_generic = 1; generic = p->function; } } while ((++p)->offset == offset); if (specific && !use_generic) *ptr = specific; else *ptr = generic; return p; } /* In the type, update the slots whose slotdefs are gathered in the pp array. This is a callback for update_subclasses(). */ static int update_slots_callback(PyTypeObject* type, void* data) noexcept { slotdef** pp = (slotdef**)data; for (; *pp; pp++) update_one_slot(type, *pp); return 0; } static int update_subclasses(PyTypeObject* type, PyObject* name, update_callback callback, void* data) noexcept; static int recurse_down_subclasses(PyTypeObject* type, PyObject* name, update_callback callback, void* data) noexcept; bool update_slot(BoxedClass* type, llvm::StringRef attr) noexcept { slotdef* ptrs[MAX_EQUIV]; slotdef* p; slotdef** pp; int offset; /* Clear the VALID_VERSION flag of 'type' and all its subclasses. This could possibly be unified with the update_subclasses() recursion below, but carefully: they each have their own conditions on which to stop recursing into subclasses. */ PyType_Modified(type); init_slotdefs(); pp = ptrs; for (p = slotdefs; p->name.size() != 0; p++) { /* XXX assume name is interned! */ if (p->name == attr) *pp++ = p; } *pp = NULL; for (pp = ptrs; *pp; pp++) { p = *pp; offset = p->offset; while (p > slotdefs && (p - 1)->offset == offset) --p; *pp = p; } if (ptrs[0] == NULL) return false; /* Not an attribute that affects any slots */ int r = update_subclasses(type, boxString(attr), update_slots_callback, (void*)ptrs); // TODO this is supposed to be a CAPI function! if (r) throwCAPIException(); return true; } void fixup_slot_dispatchers(BoxedClass* self) noexcept { init_slotdefs(); const slotdef* p = slotdefs; while (p->name.size() != 0) p = update_one_slot(self, p); } static int update_subclasses(PyTypeObject* type, PyObject* name, update_callback callback, void* data) noexcept { if (callback(type, data) < 0) return -1; return recurse_down_subclasses(type, name, callback, data); } static int recurse_down_subclasses(PyTypeObject* type, PyObject* name, update_callback callback, void* data) noexcept { PyTypeObject* subclass; PyObject* ref, *subclasses, *dict; Py_ssize_t i, n; subclasses = type->tp_subclasses; if (subclasses == NULL) return 0; assert(PyList_Check(subclasses)); n = PyList_GET_SIZE(subclasses); for (i = 0; i < n; i++) { ref = PyList_GET_ITEM(subclasses, i); assert(PyWeakref_CheckRef(ref)); subclass = (PyTypeObject*)PyWeakref_GET_OBJECT(ref); assert(subclass != NULL); if ((PyObject*)subclass == Py_None) continue; assert(PyType_Check(subclass)); /* Avoid recursing down into unaffected classes */ dict = subclass->tp_dict; if (dict != NULL && PyDict_Check(dict) && PyDict_GetItem(dict, name) != NULL) continue; if (update_subclasses(subclass, name, callback, data) < 0) return -1; } return 0; } static PyObject* tp_new_wrapper(PyTypeObject* self, BoxedTuple* args, Box* kwds) noexcept { RELEASE_ASSERT(isSubclass(self->cls, type_cls), ""); // ASSERT(self->tp_new != Py_CallPythonNew, "going to get in an infinite loop"); RELEASE_ASSERT(args->cls == tuple_cls, ""); RELEASE_ASSERT(!kwds || kwds->cls == dict_cls, ""); RELEASE_ASSERT(args->size() >= 1, ""); BoxedClass* subtype = static_cast<BoxedClass*>(args->elts[0]); RELEASE_ASSERT(isSubclass(subtype->cls, type_cls), ""); RELEASE_ASSERT(isSubclass(subtype, self), ""); BoxedTuple* new_args = BoxedTuple::create(args->size() - 1, &args->elts[1]); return self->tp_new(subtype, new_args, kwds); } static struct PyMethodDef tp_new_methoddef[] = { { "__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("T.__new__(S, ...) -> " "a new object with type S, a subtype of T") }, { 0, 0, 0, 0 } }; static void add_tp_new_wrapper(BoxedClass* type) noexcept { static BoxedString* new_str = internStringImmortal("__new__"); if (type->getattr(new_str)) return; type->giveAttr(new_str, new BoxedCApiFunction(tp_new_methoddef, type)); } void add_operators(BoxedClass* cls) noexcept { init_slotdefs(); for (const slotdef& p : slotdefs) { if (!p.wrapper) continue; void** ptr = slotptr(cls, p.offset); if (!ptr || !*ptr) continue; if (cls->getattr(p.name_strobj)) continue; if (*ptr == PyObject_HashNotImplemented) { cls->giveAttr(p.name_strobj, None); } else { cls->giveAttr(p.name_strobj, new BoxedWrapperDescriptor(&p, cls, *ptr)); } } if (cls->tp_new) add_tp_new_wrapper(cls); } static void type_mro_modified(PyTypeObject* type, PyObject* bases) { /* Check that all base classes or elements of the mro of type are able to be cached. This function is called after the base classes or mro of the type are altered. Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type inherits from an old-style class, either directly or if it appears in the MRO of a new-style class. No support either for custom MROs that include types that are not officially super types. Called from mro_internal, which will subsequently be called on each subclass when their mro is recursively updated. */ Py_ssize_t i, n; int clear = 0; if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) return; n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { PyObject* b = PyTuple_GET_ITEM(bases, i); PyTypeObject* cls; if (!PyType_Check(b)) { clear = 1; break; } cls = (PyTypeObject*)b; if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || !PyType_IsSubtype(type, cls)) { clear = 1; break; } } if (clear) type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG | Py_TPFLAGS_VALID_VERSION_TAG); } static int extra_ivars(PyTypeObject* type, PyTypeObject* base) noexcept { size_t t_size = type->tp_basicsize; size_t b_size = base->tp_basicsize; assert(t_size >= b_size); /* Else type smaller than base! */ if (type->tp_itemsize || base->tp_itemsize) { /* If itemsize is involved, stricter rules */ return t_size != b_size || type->tp_itemsize != base->tp_itemsize; } if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && type->tp_weaklistoffset + sizeof(PyObject*) == t_size && type->tp_flags & Py_TPFLAGS_HEAPTYPE) t_size -= sizeof(PyObject*); if (type->tp_dictoffset && base->tp_dictoffset == 0 && type->tp_dictoffset + sizeof(PyObject*) == t_size && type->tp_flags & Py_TPFLAGS_HEAPTYPE) t_size -= sizeof(PyObject*); // Pyston change: if (type->instancesHaveHCAttrs() && !base->instancesHaveHCAttrs()) t_size -= sizeof(HCAttrs); return t_size != b_size; } static PyTypeObject* solid_base(PyTypeObject* type) noexcept { PyTypeObject* base; if (type->tp_base) base = solid_base(type->tp_base); else base = object_cls; if (extra_ivars(type, base)) return type; else return base; } PyTypeObject* best_base(PyObject* bases) noexcept { Py_ssize_t i, n; PyTypeObject* base, *winner, *candidate, *base_i; PyObject* base_proto; assert(PyTuple_Check(bases)); n = PyTuple_GET_SIZE(bases); assert(n > 0); base = NULL; winner = NULL; for (i = 0; i < n; i++) { base_proto = PyTuple_GET_ITEM(bases, i); if (PyClass_Check(base_proto)) continue; if (!PyType_Check(base_proto)) { PyErr_SetString(PyExc_TypeError, "bases must be types"); return NULL; } base_i = (PyTypeObject*)base_proto; // Pyston change: we require things are already ready if (base_i->tp_dict == NULL) { assert(base_i->is_pyston_class); #if 0 if (PyType_Ready(base_i) < 0) return NULL; #endif } candidate = solid_base(base_i); if (winner == NULL) { winner = candidate; base = base_i; } else if (PyType_IsSubtype(winner, candidate)) ; else if (PyType_IsSubtype(candidate, winner)) { winner = candidate; base = base_i; } else { PyErr_SetString(PyExc_TypeError, "multiple bases have " "instance lay-out conflict"); return NULL; } } if (base == NULL) PyErr_SetString(PyExc_TypeError, "a new-style class can't have only classic bases"); return base; } static int fill_classic_mro(PyObject* mro, PyObject* cls) { PyObject* bases, *base; Py_ssize_t i, n; assert(PyList_Check(mro)); assert(PyClass_Check(cls)); i = PySequence_Contains(mro, cls); if (i < 0) return -1; if (!i) { if (PyList_Append(mro, cls) < 0) return -1; } bases = ((BoxedClassobj*)cls)->bases; assert(bases && PyTuple_Check(bases)); n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { base = PyTuple_GET_ITEM(bases, i); if (fill_classic_mro(mro, base) < 0) return -1; } return 0; } static PyObject* classic_mro(PyObject* cls) { PyObject* mro; assert(PyClass_Check(cls)); mro = PyList_New(0); if (mro != NULL) { if (fill_classic_mro(mro, cls) == 0) return mro; Py_DECREF(mro); } return NULL; } /* Method resolution order algorithm C3 described in "A Monotonic Superclass Linearization for Dylan", by Kim Barrett, Bob Cassel, Paul Haahr, David A. Moon, Keith Playford, and P. Tucker Withington. (OOPSLA 1996) Some notes about the rules implied by C3: No duplicate bases. It isn't legal to repeat a class in a list of base classes. The next three properties are the 3 constraints in "C3". Local precendece order. If A precedes B in C's MRO, then A will precede B in the MRO of all subclasses of C. Monotonicity. The MRO of a class must be an extension without reordering of the MRO of each of its superclasses. Extended Precedence Graph (EPG). Linearization is consistent if there is a path in the EPG from each class to all its successors in the linearization. See the paper for definition of EPG. */ static int tail_contains(PyObject* list, int whence, PyObject* o) { Py_ssize_t j, size; size = PyList_GET_SIZE(list); for (j = whence + 1; j < size; j++) { if (PyList_GET_ITEM(list, j) == o) return 1; } return 0; } static PyObject* class_name(PyObject* cls) { PyObject* name = PyObject_GetAttrString(cls, "__name__"); if (name == NULL) { PyErr_Clear(); Py_XDECREF(name); name = PyObject_Repr(cls); } if (name == NULL) return NULL; if (!PyString_Check(name)) { Py_DECREF(name); return NULL; } return name; } static int check_duplicates(PyObject* list) { Py_ssize_t i, j, n; /* Let's use a quadratic time algorithm, assuming that the bases lists is short. */ n = PyList_GET_SIZE(list); for (i = 0; i < n; i++) { PyObject* o = PyList_GET_ITEM(list, i); for (j = i + 1; j < n; j++) { if (PyList_GET_ITEM(list, j) == o) { o = class_name(o); PyErr_Format(PyExc_TypeError, "duplicate base class %s", o ? PyString_AS_STRING(o) : "?"); Py_XDECREF(o); return -1; } } } return 0; } /* Raise a TypeError for an MRO order disagreement. It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ static void set_mro_error(PyObject* to_merge, int* remain) noexcept { Py_ssize_t i, n, off, to_merge_size; char buf[1000]; PyObject* k, *v; PyObject* set = PyDict_New(); if (!set) return; to_merge_size = PyList_GET_SIZE(to_merge); for (i = 0; i < to_merge_size; i++) { PyObject* L = PyList_GET_ITEM(to_merge, i); if (remain[i] < PyList_GET_SIZE(L)) { PyObject* c = PyList_GET_ITEM(L, remain[i]); if (PyDict_SetItem(set, c, Py_None) < 0) { Py_DECREF(set); return; } } } n = PyDict_Size(set); off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ consistent method resolution\norder (MRO) for bases"); i = 0; while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { PyObject* name = class_name(k); off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name ? PyString_AS_STRING(name) : "?"); Py_XDECREF(name); if (--n && (size_t)(off + 1) < sizeof(buf)) { buf[off++] = ','; buf[off] = '\0'; } } PyErr_SetString(PyExc_TypeError, buf); Py_DECREF(set); } static int pmerge(PyObject* acc, PyObject* to_merge) noexcept { Py_ssize_t i, j, to_merge_size, empty_cnt; int* remain; int ok; to_merge_size = PyList_GET_SIZE(to_merge); /* remain stores an index into each sublist of to_merge. remain[i] is the index of the next base in to_merge[i] that is not included in acc. */ remain = (int*)PyMem_MALLOC(SIZEOF_INT * to_merge_size); if (remain == NULL) return -1; for (i = 0; i < to_merge_size; i++) remain[i] = 0; again: empty_cnt = 0; for (i = 0; i < to_merge_size; i++) { PyObject* candidate; PyObject* cur_list = PyList_GET_ITEM(to_merge, i); if (remain[i] >= PyList_GET_SIZE(cur_list)) { empty_cnt++; continue; } /* Choose next candidate for MRO. The input sequences alone can determine the choice. If not, choose the class which appears in the MRO of the earliest direct superclass of the new class. */ candidate = PyList_GET_ITEM(cur_list, remain[i]); for (j = 0; j < to_merge_size; j++) { PyObject* j_lst = PyList_GET_ITEM(to_merge, j); if (tail_contains(j_lst, remain[j], candidate)) { goto skip; /* continue outer loop */ } } ok = PyList_Append(acc, candidate); if (ok < 0) { PyMem_Free(remain); return -1; } for (j = 0; j < to_merge_size; j++) { PyObject* j_lst = PyList_GET_ITEM(to_merge, j); if (remain[j] < PyList_GET_SIZE(j_lst) && PyList_GET_ITEM(j_lst, remain[j]) == candidate) { remain[j]++; } } goto again; skip: ; } if (empty_cnt == to_merge_size) { PyMem_FREE(remain); return 0; } set_mro_error(to_merge, remain); PyMem_FREE(remain); return -1; } static PyObject* mro_implementation(PyTypeObject* type) noexcept { Py_ssize_t i, n; int ok; PyObject* bases, *result; PyObject* to_merge, *bases_aslist; // Pyston change: we require things are already ready if (type->tp_dict == NULL) { assert(type->is_pyston_class); #if 0 if (PyType_Ready(type) < 0) return NULL; #endif } /* Find a superclass linearization that honors the constraints of the explicit lists of bases and the constraints implied by each base class. to_merge is a list of lists, where each list is a superclass linearization implied by a base class. The last element of to_merge is the declared list of bases. */ bases = type->tp_bases; assert(type->tp_bases); assert(type->tp_bases->cls == tuple_cls); n = PyTuple_GET_SIZE(bases); to_merge = PyList_New(n + 1); if (to_merge == NULL) return NULL; for (i = 0; i < n; i++) { PyObject* base = PyTuple_GET_ITEM(bases, i); PyObject* parentMRO; if (PyType_Check(base)) parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); else parentMRO = classic_mro(base); if (parentMRO == NULL) { Py_DECREF(to_merge); return NULL; } PyList_SET_ITEM(to_merge, i, parentMRO); } bases_aslist = PySequence_List(bases); if (bases_aslist == NULL) { Py_DECREF(to_merge); return NULL; } /* This is just a basic sanity check. */ if (check_duplicates(bases_aslist) < 0) { Py_DECREF(to_merge); Py_DECREF(bases_aslist); return NULL; } PyList_SET_ITEM(to_merge, n, bases_aslist); result = Py_BuildValue("[O]", (PyObject*)type); if (result == NULL) { Py_DECREF(to_merge); return NULL; } ok = pmerge(result, to_merge); Py_DECREF(to_merge); if (ok < 0) { Py_DECREF(result); return NULL; } return result; } // Pyston change: made this non-static PyObject* mro_external(PyObject* self) noexcept { PyTypeObject* type = (PyTypeObject*)self; return mro_implementation(type); } static int mro_internal(PyTypeObject* type) noexcept { PyObject* mro, *result, *tuple; int checkit = 0; if (Py_TYPE(type) == &PyType_Type) { result = mro_implementation(type); } else { static PyObject* mro_str; checkit = 1; mro = lookup_method((PyObject*)type, "mro", &mro_str); if (mro == NULL) return -1; result = PyObject_CallObject(mro, NULL); Py_DECREF(mro); } if (result == NULL) return -1; tuple = PySequence_Tuple(result); Py_DECREF(result); if (tuple == NULL) return -1; if (checkit) { Py_ssize_t i, len; PyObject* cls; PyTypeObject* solid; solid = solid_base(type); len = PyTuple_GET_SIZE(tuple); for (i = 0; i < len; i++) { PyTypeObject* t; cls = PyTuple_GET_ITEM(tuple, i); if (PyClass_Check(cls)) continue; else if (!PyType_Check(cls)) { PyErr_Format(PyExc_TypeError, "mro() returned a non-class ('%.500s')", Py_TYPE(cls)->tp_name); Py_DECREF(tuple); return -1; } t = (PyTypeObject*)cls; if (!PyType_IsSubtype(solid, solid_base(t))) { PyErr_Format(PyExc_TypeError, "mro() returned base with unsuitable layout ('%.500s')", t->tp_name); Py_DECREF(tuple); return -1; } } } type->tp_mro = tuple; type_mro_modified(type, type->tp_mro); /* corner case: the old-style super class might have been hidden from the custom MRO */ type_mro_modified(type, type->tp_bases); PyType_Modified(type); return 0; } extern "C" int PyType_IsSubtype(PyTypeObject* a, PyTypeObject* b) noexcept { PyObject* mro; if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS)) return b == a || b == &PyBaseObject_Type; mro = a->tp_mro; if (mro != NULL) { /* Deal with multiple inheritance without recursion by walking the MRO tuple */ Py_ssize_t i, n; assert(PyTuple_Check(mro)); n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject*)b) return 1; } return 0; } else { /* a is not completely initilized yet; follow tp_base */ do { if (a == b) return 1; a = a->tp_base; } while (a != NULL); return b == &PyBaseObject_Type; } } #define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER) // This is copied from CPython with some modifications: static void inherit_special(PyTypeObject* type, PyTypeObject* base) noexcept { Py_ssize_t oldsize, newsize; /* Special flag magic */ if (!type->tp_as_buffer && base->tp_as_buffer) { type->tp_flags &= ~BUFFER_FLAGS; type->tp_flags |= base->tp_flags & BUFFER_FLAGS; } if (!type->tp_as_sequence && base->tp_as_sequence) { type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN; type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN; } if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) != (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) { if ((!type->tp_as_number && base->tp_as_number) || (!type->tp_as_sequence && base->tp_as_sequence)) { type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS; if (!type->tp_as_number && !type->tp_as_sequence) { type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS; } } /* Wow */ } if (!type->tp_as_number && base->tp_as_number) { type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES; type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES; } /* Copying basicsize is connected to the GC flags */ oldsize = base->tp_basicsize; newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && (base->tp_flags & Py_TPFLAGS_HAVE_GC) && (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE /*GC slots exist*/) && (!type->tp_traverse && !type->tp_clear)) { type->tp_flags |= Py_TPFLAGS_HAVE_GC; if (type->tp_traverse == NULL) type->tp_traverse = base->tp_traverse; if (type->tp_clear == NULL) type->tp_clear = base->tp_clear; } if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { /* The condition below could use some explanation. It appears that tp_new is not inherited for static types whose base class is 'object'; this seems to be a precaution so that old extension types don't suddenly become callable (object.__new__ wouldn't insure the invariants that the extension type's own factory function ensures). Heap types, of course, are under our control, so they do inherit tp_new; static extension types that specify some other built-in type as the default are considered new-style-aware so they also inherit object.__new__. */ if (base != object_cls || (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { if (type->tp_new == NULL) type->tp_new = base->tp_new; } } type->tp_basicsize = newsize; /* Copy other non-function slots */ #undef COPYVAL #define COPYVAL(SLOT) \ if (type->SLOT == 0) \ type->SLOT = base->SLOT COPYVAL(tp_itemsize); if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) { COPYVAL(tp_weaklistoffset); } if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { COPYVAL(tp_dictoffset); } /* Setup fast subclass flags */ if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; else if (PyType_IsSubtype(base, &PyType_Type)) type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; else if (PyType_IsSubtype(base, &PyInt_Type)) type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS; else if (PyType_IsSubtype(base, &PyLong_Type)) type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; else if (PyType_IsSubtype(base, &PyString_Type)) type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS; #ifdef Py_USING_UNICODE else if (PyType_IsSubtype(base, &PyUnicode_Type)) type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; #endif else if (PyType_IsSubtype(base, &PyTuple_Type)) type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; else if (PyType_IsSubtype(base, &PyList_Type)) type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; else if (PyType_IsSubtype(base, &PyDict_Type)) type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static int overrides_name(PyTypeObject* type, const char* name) noexcept { PyObject* dict = type->tp_dict; assert(dict != NULL); if (PyDict_GetItemString(dict, name) != NULL) { return 1; } return 0; } #define OVERRIDES_HASH(x) overrides_name(x, "__hash__") #define OVERRIDES_EQ(x) overrides_name(x, "__eq__") static void inherit_slots(PyTypeObject* type, PyTypeObject* base) noexcept { // Pyston addition: if (base->tp_base == NULL) assert(base == object_cls); PyTypeObject* basebase; #undef SLOTDEFINED #undef COPYSLOT #undef COPYNUM #undef COPYSEQ #undef COPYMAP #undef COPYBUF #define SLOTDEFINED(SLOT) (base->SLOT != 0 && (basebase == NULL || base->SLOT != basebase->SLOT)) #define COPYSLOT(SLOT) \ if (!type->SLOT && SLOTDEFINED(SLOT)) \ type->SLOT = base->SLOT #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) /* This won't inherit indirect slots (from tp_as_number etc.) if type doesn't provide the space. */ if (type->tp_as_number != NULL && base->tp_as_number != NULL) { basebase = base->tp_base; if (basebase->tp_as_number == NULL) basebase = NULL; COPYNUM(nb_add); COPYNUM(nb_subtract); COPYNUM(nb_multiply); COPYNUM(nb_divide); COPYNUM(nb_remainder); COPYNUM(nb_divmod); COPYNUM(nb_power); COPYNUM(nb_negative); COPYNUM(nb_positive); COPYNUM(nb_absolute); COPYNUM(nb_nonzero); COPYNUM(nb_invert); COPYNUM(nb_lshift); COPYNUM(nb_rshift); COPYNUM(nb_and); COPYNUM(nb_xor); COPYNUM(nb_or); COPYNUM(nb_coerce); COPYNUM(nb_int); COPYNUM(nb_long); COPYNUM(nb_float); COPYNUM(nb_oct); COPYNUM(nb_hex); COPYNUM(nb_inplace_add); COPYNUM(nb_inplace_subtract); COPYNUM(nb_inplace_multiply); COPYNUM(nb_inplace_divide); COPYNUM(nb_inplace_remainder); COPYNUM(nb_inplace_power); COPYNUM(nb_inplace_lshift); COPYNUM(nb_inplace_rshift); COPYNUM(nb_inplace_and); COPYNUM(nb_inplace_xor); COPYNUM(nb_inplace_or); if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) { COPYNUM(nb_true_divide); COPYNUM(nb_floor_divide); COPYNUM(nb_inplace_true_divide); COPYNUM(nb_inplace_floor_divide); } if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) { COPYNUM(nb_index); } } if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { basebase = base->tp_base; if (basebase->tp_as_sequence == NULL) basebase = NULL; COPYSEQ(sq_length); COPYSEQ(sq_concat); COPYSEQ(sq_repeat); COPYSEQ(sq_item); COPYSEQ(sq_slice); COPYSEQ(sq_ass_item); COPYSEQ(sq_ass_slice); COPYSEQ(sq_contains); COPYSEQ(sq_inplace_concat); COPYSEQ(sq_inplace_repeat); } if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { basebase = base->tp_base; if (basebase->tp_as_mapping == NULL) basebase = NULL; COPYMAP(mp_length); COPYMAP(mp_subscript); COPYMAP(mp_ass_subscript); } if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { basebase = base->tp_base; if (basebase->tp_as_buffer == NULL) basebase = NULL; COPYBUF(bf_getreadbuffer); COPYBUF(bf_getwritebuffer); COPYBUF(bf_getsegcount); COPYBUF(bf_getcharbuffer); COPYBUF(bf_getbuffer); COPYBUF(bf_releasebuffer); } basebase = base->tp_base; COPYSLOT(tp_dealloc); COPYSLOT(tp_print); if (type->tp_getattr == NULL && type->tp_getattro == NULL) { type->tp_getattr = base->tp_getattr; type->tp_getattro = base->tp_getattro; } if (type->tp_setattr == NULL && type->tp_setattro == NULL) { type->tp_setattr = base->tp_setattr; type->tp_setattro = base->tp_setattro; } /* tp_compare see tp_richcompare */ COPYSLOT(tp_repr); /* tp_hash see tp_richcompare */ COPYSLOT(tp_call); COPYSLOT(tp_str); if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) { if (type->tp_compare == NULL && type->tp_richcompare == NULL && type->tp_hash == NULL) { type->tp_compare = base->tp_compare; type->tp_richcompare = base->tp_richcompare; type->tp_hash = base->tp_hash; /* Check for changes to inherited methods in Py3k*/ if (Py_Py3kWarningFlag) { if (base->tp_hash && (base->tp_hash != PyObject_HashNotImplemented) && !OVERRIDES_HASH(type)) { if (OVERRIDES_EQ(type)) { if (PyErr_WarnPy3k("Overriding " "__eq__ blocks inheritance " "of __hash__ in 3.x", 1) < 0) /* XXX This isn't right. If the warning is turned into an exception, we should be communicating the error back to the caller, but figuring out how to clean up in that case is tricky. See issue 8627 for more. */ PyErr_Clear(); } } } } } else { COPYSLOT(tp_compare); } if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) { COPYSLOT(tp_iter); COPYSLOT(tp_iternext); } if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { COPYSLOT(tp_descr_get); COPYSLOT(tp_descr_set); COPYSLOT(tp_dictoffset); COPYSLOT(tp_init); COPYSLOT(tp_alloc); COPYSLOT(tp_is_gc); if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { /* They agree about gc. */ COPYSLOT(tp_free); } else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && type->tp_free == NULL && base->tp_free == _PyObject_Del) { /* A bit of magic to plug in the correct default * tp_free function when a derived class adds gc, * didn't define tp_free, and the base uses the * default non-gc tp_free. */ // Pyston change: don't do this: // type->tp_free = PyObject_GC_Del; } /* else they didn't agree about gc, and there isn't something * obvious to be done -- the type is on its own. */ } } static int add_subclass(PyTypeObject* base, PyTypeObject* type) noexcept { Py_ssize_t i; int result; PyObject* list, *ref, *newobj; list = base->tp_subclasses; if (list == NULL) { base->tp_subclasses = list = PyList_New(0); if (list == NULL) return -1; } assert(PyList_Check(list)); newobj = PyWeakref_NewRef((PyObject*)type, NULL); i = PyList_GET_SIZE(list); while (--i >= 0) { ref = PyList_GET_ITEM(list, i); assert(PyWeakref_CheckRef(ref)); if (PyWeakref_GET_OBJECT(ref) == Py_None) return PyList_SetItem(list, i, newobj); } result = PyList_Append(list, newobj); Py_DECREF(newobj); return result; } static void remove_subclass(PyTypeObject* base, PyTypeObject* type) noexcept { Py_ssize_t i; PyObject* list, *ref; list = base->tp_subclasses; if (list == NULL) { return; } assert(PyList_Check(list)); i = PyList_GET_SIZE(list); while (--i >= 0) { ref = PyList_GET_ITEM(list, i); assert(PyWeakref_CheckRef(ref)); if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { /* this can't fail, right? */ PySequence_DelItem(list, i); return; } } } static int equiv_structs(PyTypeObject* a, PyTypeObject* b) noexcept { // Pyston change: added attrs_offset equality check // return a == b || (a != NULL && b != NULL && a->tp_basicsize == b->tp_basicsize // && a->tp_itemsize == b->tp_itemsize // && a->tp_dictoffset == b->tp_dictoffset && a->tp_weaklistoffset == b->tp_weaklistoffset // && ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == (b->tp_flags & Py_TPFLAGS_HAVE_GC))); return a == b || (a != NULL && b != NULL && a->tp_basicsize == b->tp_basicsize && a->tp_itemsize == b->tp_itemsize && a->tp_dictoffset == b->tp_dictoffset && a->tp_weaklistoffset == b->tp_weaklistoffset && a->attrs_offset == b->attrs_offset && ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == (b->tp_flags & Py_TPFLAGS_HAVE_GC))); } static void update_all_slots(PyTypeObject* type) noexcept { slotdef* p; init_slotdefs(); for (p = slotdefs; p->name.size() > 0; p++) { /* update_slot returns int but can't actually fail */ update_slot(type, p->name); } } static int same_slots_added(PyTypeObject* a, PyTypeObject* b) noexcept { PyTypeObject* base = a->tp_base; Py_ssize_t size; PyObject* slots_a, *slots_b; assert(base == b->tp_base); size = base->tp_basicsize; if (a->tp_dictoffset == size && b->tp_dictoffset == size) size += sizeof(PyObject*); // Pyston change: have to check attrs_offset if (a->attrs_offset == size && b->attrs_offset == size) size += sizeof(HCAttrs); if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) size += sizeof(PyObject*); /* Check slots compliance */ slots_a = ((PyHeapTypeObject*)a)->ht_slots; slots_b = ((PyHeapTypeObject*)b)->ht_slots; if (slots_a && slots_b) { if (PyObject_Compare(slots_a, slots_b) != 0) return 0; size += sizeof(PyObject*) * PyTuple_GET_SIZE(slots_a); } return size == a->tp_basicsize && size == b->tp_basicsize; } static int compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr) noexcept { PyTypeObject* newbase, *oldbase; if (newto->tp_dealloc != oldto->tp_dealloc || newto->tp_free != oldto->tp_free) { PyErr_Format(PyExc_TypeError, "%s assignment: " "'%s' deallocator differs from '%s'", attr, newto->tp_name, oldto->tp_name); return 0; } newbase = newto; oldbase = oldto; while (equiv_structs(newbase, newbase->tp_base)) newbase = newbase->tp_base; while (equiv_structs(oldbase, oldbase->tp_base)) oldbase = oldbase->tp_base; if (newbase != oldbase && (newbase->tp_base != oldbase->tp_base || !same_slots_added(newbase, oldbase))) { PyErr_Format(PyExc_TypeError, "%s assignment: " "'%s' object layout differs from '%s'", attr, newto->tp_name, oldto->tp_name); return 0; } return 1; } static int mro_subclasses(PyTypeObject* type, PyObject* temp) noexcept { PyTypeObject* subclass; PyObject* ref, *subclasses, *old_mro; Py_ssize_t i, n; subclasses = type->tp_subclasses; if (subclasses == NULL) return 0; assert(PyList_Check(subclasses)); n = PyList_GET_SIZE(subclasses); for (i = 0; i < n; i++) { ref = PyList_GET_ITEM(subclasses, i); assert(PyWeakref_CheckRef(ref)); subclass = (PyTypeObject*)PyWeakref_GET_OBJECT(ref); assert(subclass != NULL); if ((PyObject*)subclass == Py_None) continue; assert(PyType_Check(subclass)); old_mro = subclass->tp_mro; if (mro_internal(subclass) < 0) { subclass->tp_mro = old_mro; return -1; } else { PyObject* tuple; tuple = PyTuple_Pack(2, subclass, old_mro); Py_DECREF(old_mro); if (!tuple) return -1; if (PyList_Append(temp, tuple) < 0) return -1; Py_DECREF(tuple); } if (mro_subclasses(subclass, temp) < 0) return -1; } return 0; } int type_set_bases(PyTypeObject* type, PyObject* value, void* context) noexcept { Py_ssize_t i; int r = 0; PyObject* ob, *temp; PyTypeObject* new_base, *old_base; PyObject* old_bases, *old_mro; if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { PyErr_Format(PyExc_TypeError, "can't set %s.__bases__", type->tp_name); return -1; } if (!value) { PyErr_Format(PyExc_TypeError, "can't delete %s.__bases__", type->tp_name); return -1; } if (!PyTuple_Check(value)) { PyErr_Format(PyExc_TypeError, "can only assign tuple to %s.__bases__, not %s", type->tp_name, Py_TYPE(value)->tp_name); return -1; } if (PyTuple_GET_SIZE(value) == 0) { PyErr_Format(PyExc_TypeError, "can only assign non-empty tuple to %s.__bases__, not ()", type->tp_name); return -1; } for (i = 0; i < PyTuple_GET_SIZE(value); i++) { ob = PyTuple_GET_ITEM(value, i); if (!PyClass_Check(ob) && !PyType_Check(ob)) { PyErr_Format(PyExc_TypeError, "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", type->tp_name, Py_TYPE(ob)->tp_name); return -1; } if (PyType_Check(ob)) { if (PyType_IsSubtype((PyTypeObject*)ob, type)) { PyErr_SetString(PyExc_TypeError, "a __bases__ item causes an inheritance cycle"); return -1; } } } new_base = best_base(value); if (!new_base) { return -1; } if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) return -1; Py_INCREF(new_base); Py_INCREF(value); old_bases = type->tp_bases; old_base = type->tp_base; old_mro = type->tp_mro; type->tp_bases = value; type->tp_base = new_base; if (mro_internal(type) < 0) { goto bail; } temp = PyList_New(0); if (!temp) goto bail; r = mro_subclasses(type, temp); if (r < 0) { for (i = 0; i < PyList_Size(temp); i++) { PyTypeObject* cls; PyObject* mro; PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), "", 2, 2, &cls, &mro); Py_INCREF(mro); ob = cls->tp_mro; cls->tp_mro = mro; Py_DECREF(ob); } Py_DECREF(temp); goto bail; } Py_DECREF(temp); /* any base that was in __bases__ but now isn't, we need to remove |type| from its tp_subclasses. conversely, any class now in __bases__ that wasn't needs to have |type| added to its subclasses. */ /* for now, sod that: just remove from all old_bases, add to all new_bases */ for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { ob = PyTuple_GET_ITEM(old_bases, i); if (PyType_Check(ob)) { remove_subclass((PyTypeObject*)ob, type); } } for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { ob = PyTuple_GET_ITEM(value, i); if (PyType_Check(ob)) { if (add_subclass((PyTypeObject*)ob, type) < 0) r = -1; } } update_all_slots(type); Py_DECREF(old_bases); Py_DECREF(old_base); Py_DECREF(old_mro); return r; bail: Py_DECREF(type->tp_bases); Py_DECREF(type->tp_base); if (type->tp_mro != old_mro) { Py_DECREF(type->tp_mro); } type->tp_bases = old_bases; type->tp_base = old_base; type->tp_mro = old_mro; return -1; } // commonClassSetup is for the common code between PyType_Ready (which is just for extension classes) // and our internal type-creation endpoints (BoxedClass::BoxedClass()). // TODO: Move more of the duplicated logic into here. void commonClassSetup(BoxedClass* cls) { if (cls->tp_bases == NULL) { if (cls->tp_base) cls->tp_bases = BoxedTuple::create({ cls->tp_base }); else cls->tp_bases = BoxedTuple::create({}); } /* Link into each base class's list of subclasses */ for (PyObject* b : *static_cast<BoxedTuple*>(cls->tp_bases)) { if (PyType_Check(b) && add_subclass((PyTypeObject*)b, cls) < 0) throwCAPIException(); } /* Calculate method resolution order */ if (mro_internal(cls) < 0) throwCAPIException(); if (cls->tp_base) inherit_special(cls, cls->tp_base); assert(cls->tp_mro); assert(cls->tp_mro->cls == tuple_cls); for (auto b : *static_cast<BoxedTuple*>(cls->tp_mro)) { if (b == cls) continue; if (PyType_Check(b)) inherit_slots(cls, static_cast<BoxedClass*>(b)); } assert(cls->tp_dict && cls->tp_dict->cls == attrwrapper_cls); } extern "C" void PyType_Modified(PyTypeObject* type) noexcept { // We don't cache anything yet that would need to be invalidated: } template <ExceptionStyle S> static Box* tppProxyToTpCall(Box* self, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<BoxedString*>* keyword_names) noexcept(S == CAPI) { ParamReceiveSpec paramspec(0, 0, true, true); if (!argspec.has_kwargs && argspec.num_keywords == 0) { paramspec.takes_kwargs = false; } bool rewrite_success = false; Box* oarg1, * oarg2 = NULL, *oarg3, ** oargs = NULL; try { rearrangeArguments(paramspec, NULL, "", NULL, rewrite_args, rewrite_success, argspec, arg1, arg2, arg3, args, keyword_names, oarg1, oarg2, oarg3, oargs); } catch (ExcInfo e) { if (S == CAPI) { setCAPIException(e); return NULL; } else throw e; } if (!rewrite_success) rewrite_args = NULL; if (rewrite_args) { if (!paramspec.takes_kwargs) rewrite_args->arg2 = rewrite_args->rewriter->loadConst(0, Location::forArg(2)); // Currently, guard that the value of tp_call didn't change, and then // emit a call to the current function address. // It might be better to just load the current value of tp_call and call it // (after guarding it's not null), or maybe not. But the rewriter doesn't currently // support calling a RewriterVar (can only call fixed function addresses). RewriterVar* r_cls = rewrite_args->obj->getAttr(offsetof(Box, cls)); r_cls->addAttrGuard(offsetof(BoxedClass, tp_call), (intptr_t)self->cls->tp_call); rewrite_args->out_rtn = rewrite_args->rewriter->call(true, (void*)self->cls->tp_call, rewrite_args->obj, rewrite_args->arg1, rewrite_args->arg2); if (S == CXX) rewrite_args->rewriter->checkAndThrowCAPIException(rewrite_args->out_rtn); rewrite_args->out_success = true; } Box* r = self->cls->tp_call(self, oarg1, oarg2); if (!r && S == CXX) throwCAPIException(); return r; } extern "C" int PyType_Ready(PyTypeObject* cls) noexcept { ASSERT(!cls->is_pyston_class, "should not call this on Pyston classes"); gc::registerNonheapRootObject(cls, sizeof(PyTypeObject)); // unhandled fields: int ALLOWABLE_FLAGS = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_HAVE_NEWBUFFER; ALLOWABLE_FLAGS |= Py_TPFLAGS_INT_SUBCLASS | Py_TPFLAGS_LONG_SUBCLASS | Py_TPFLAGS_LIST_SUBCLASS | Py_TPFLAGS_TUPLE_SUBCLASS | Py_TPFLAGS_STRING_SUBCLASS | Py_TPFLAGS_UNICODE_SUBCLASS | Py_TPFLAGS_DICT_SUBCLASS | Py_TPFLAGS_BASE_EXC_SUBCLASS | Py_TPFLAGS_TYPE_SUBCLASS; RELEASE_ASSERT((cls->tp_flags & ~ALLOWABLE_FLAGS) == 0, ""); RELEASE_ASSERT(cls->tp_is_gc == NULL, ""); RELEASE_ASSERT(cls->tp_mro == NULL, ""); RELEASE_ASSERT(cls->tp_cache == NULL, ""); RELEASE_ASSERT(cls->tp_subclasses == NULL, ""); RELEASE_ASSERT(cls->tp_weaklist == NULL, ""); RELEASE_ASSERT(cls->tp_del == NULL, ""); RELEASE_ASSERT(cls->tp_version_tag == 0, ""); // I think it is safe to ignore these for for now: // RELEASE_ASSERT(cls->tp_weaklistoffset == 0, ""); // RELEASE_ASSERT(cls->tp_traverse == NULL, ""); // RELEASE_ASSERT(cls->tp_clear == NULL, ""); assert(cls->attrs.hcls == NULL); new (&cls->attrs) HCAttrs(HiddenClass::makeSingleton()); #define INITIALIZE(a) new (&(a)) decltype(a) #undef INITIALIZE BoxedClass* base = cls->tp_base; if (base == NULL) base = cls->tp_base = object_cls; if (!cls->cls) cls->cls = cls->tp_base->cls; cls->giveAttr("__base__", base); assert(cls->tp_dict == NULL); cls->tp_dict = cls->getAttrWrapper(); assert(cls->tp_name); // Inherit some special protocols. Normally methods are automatically inherited, // when a Python class is declared, but that may not be the case with C extensions. if (base != NULL) { if (cls->tp_as_number == NULL) cls->tp_as_number = base->tp_as_number; if (cls->tp_as_sequence == NULL) cls->tp_as_sequence = base->tp_as_sequence; if (cls->tp_as_mapping == NULL) cls->tp_as_mapping = base->tp_as_mapping; if (cls->tp_as_buffer == NULL) cls->tp_as_buffer = base->tp_as_buffer; } if (cls->tp_call) { cls->tpp_call.capi_val = tppProxyToTpCall<CAPI>; cls->tpp_call.cxx_val = tppProxyToTpCall<CXX>; } try { add_operators(cls); } catch (ExcInfo e) { abort(); } for (PyMethodDef* method = cls->tp_methods; method && method->ml_name; ++method) { cls->setattr(internStringMortal(method->ml_name), new BoxedMethodDescriptor(method, cls), NULL); } for (PyMemberDef* member = cls->tp_members; member && member->name; ++member) { cls->giveAttr(internStringMortal(member->name), new BoxedMemberDescriptor(member)); } for (PyGetSetDef* getset = cls->tp_getset; getset && getset->name; ++getset) { // TODO do something with __doc__ cls->giveAttr(internStringMortal(getset->name), new (capi_getset_cls) BoxedGetsetDescriptor(getset->get, (void (*)(Box*, Box*, void*))getset->set, getset->closure)); } try { commonClassSetup(cls); } catch (ExcInfo e) { setCAPIException(e); return -1; } static BoxedString* doc_str = internStringImmortal("__doc__"); if (!cls->hasattr(doc_str)) { if (cls->tp_doc) { cls->giveAttr(doc_str, boxString(cls->tp_doc)); } else { cls->giveAttr(doc_str, None); } } if (cls->tp_alloc == &PystonType_GenericAlloc) cls->tp_alloc = &PyType_GenericAlloc; // If an extension class visits from a Pyston class that does custom visiting, // the base class needs to call the parent's visit function in case it visits // non-inline data. There's not an easy way to put in a function pointer here // that defers to a specific class's gc_visit, even if it's a base class, since // the gc_visit could get inherited by subclasses. For now just use an expensive // function, conservativeAndBasesGCHandler if (base->gc_visit != object_cls->gc_visit && base->gc_visit != &conservativeGCHandler) cls->gc_visit = &conservativeAndBasesGCHandler; else cls->gc_visit = &conservativeGCHandler; cls->is_user_defined = true; if (!cls->instancesHaveHCAttrs() && cls->tp_base) { // These doesn't get copied in inherit_slots like other slots do. if (cls->tp_base->instancesHaveHCAttrs()) { cls->attrs_offset = cls->tp_base->attrs_offset; } // Example of when this code path could be reached and needs to be: // If this class is a metaclass defined in a C extension, chances are that some of its // instances may be hardcoded in the C extension as well. Those instances will call // PyType_Ready and expect their class (this metaclass) to have a place to put attributes. // e.g. CTypes does this. bool is_metaclass = PyType_IsSubtype(cls, type_cls); assert(!is_metaclass || cls->instancesHaveHCAttrs() || cls->instancesHaveDictAttrs()); } else { // this should get automatically initialized to 0 on this path: assert(cls->attrs_offset == 0); } if (Py_TPFLAGS_BASE_EXC_SUBCLASS & cls->tp_flags) { exception_types.push_back(cls); } return 0; } extern "C" PyObject* PyType_GenericNew(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept { return type->tp_alloc(type, 0); } } // namespace pyston
37.253525
120
0.589003
vinzenz
d9d8aecc63c2ce097ee4d081d7b66de84f8aa770
288
cpp
C++
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
1
2019-05-01T19:13:02.000Z
2019-05-01T19:13:02.000Z
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
null
null
null
lib/except.cpp
kenavolic/nforce
34ca3ad924047f47c22c1db332b2da3885c5eed4
[ "Apache-2.0" ]
null
null
null
#include "nforce/core/except.h" namespace n4 { //------------------------------------- // Public nexcept::nexcept(const std::string &str, status_type s) : std::exception{}, m_status{s} {} status_type nexcept::status() const noexcept { return m_status; } } // namespace n4
26.181818
66
0.579861
kenavolic
d9d8ec9ad576d4e46bf8f3fa0027ec24fd06096c
2,552
cpp
C++
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
backend/Sensors/Sensor.cpp
Sorong/Smarrium
dc3a6b8e0d428e01b936679a8ca221c2b610b0f6
[ "MIT" ]
null
null
null
#include "./backend/Sensors/Sensor.h" #include <QDebug> Sensor::Sensor(int interval) { this->_id = QUuid::createUuid(); this->_interval = interval; this->lastCheckedHour = -1; start(interval); connect(this, SIGNAL(timeout()), this, SLOT(intervallElapsed())); //eventValueLog = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; //TODO: Remove me } const QString &Sensor::toString() { return this->name; } QUuid Sensor::getUuid() { return this->_id; } void Sensor::intervallElapsed(){ sensors_event_t* event = new sensors_event_t(); this->getEvent(event); logEvent(event); emit newSensorEvent(event); } void Sensor::fillLog(float val) { for (int i = 0; i < 24; i++) { this->eventValueLog.push_back(val); qDebug() << "Logeintrag erstellt"; } } int Sensor::getInterval(){ return this->_interval; } void Sensor::setInterval(int interval){ stop(); start(interval); } QString Sensor::getId(){ return this->_id.toString(); } void Sensor::logEvent(sensors_event_t *event){ float value = 0; switch(event->type){ case SENSOR_TYPE_IRTEMPERATURE: value = event->irTemperature; break; case SENSOR_TYPE_LIGHT: value = event->light; break; case SENSOR_TYPE_MOISTURE: value = event->moisture; break; case SENSOR_TYPE_RELATIVE_HUMIDITY: value = event->relative_humidity; break; case SENSOR_TYPE_TEMPERATURE: value = event->temperature; break; case SENSOR_TYPE_UV: value = event->uv; break; default: return; } qDebug() << "Intervall elapsed: " << value << "Sensor: " << this->getSort(); int currentHour = QTime::currentTime().hour(); if(this->lastCheckedHour == -1) { this->fillLog(value); this->lastCheckedHour = currentHour; return; } if(this->lastCheckedHour < currentHour || currentHour == 0){ qDebug() << "Logeintrag erstellt"; if(eventValueLog.size() == 24){ this->eventValueLog.pop_front(); this->eventValueLog.push_back(value); } else{ this->eventValueLog.push_back(value); } this->lastCheckedHour = currentHour; } } QList<qreal> Sensor::getEventValueLog(){ return this->eventValueLog; } float Sensor::getLastEventValue(){ if(this->eventValueLog.isEmpty()){ return 0; } else{ return this->eventValueLog.last(); } }
21.445378
116
0.604232
Sorong
d9dc6adc969a4aaaaf38afa04b249c5ef18249ed
1,398
cpp
C++
GraPhlAnPlugin.cpp
movingpictures83/GraPhlAn
80f59cc0327eb6454395559109d9010dc8204714
[ "MIT" ]
null
null
null
GraPhlAnPlugin.cpp
movingpictures83/GraPhlAn
80f59cc0327eb6454395559109d9010dc8204714
[ "MIT" ]
null
null
null
GraPhlAnPlugin.cpp
movingpictures83/GraPhlAn
80f59cc0327eb6454395559109d9010dc8204714
[ "MIT" ]
null
null
null
#include "PluginManager.h" #include <stdio.h> #include <stdlib.h> #include "GraPhlAnPlugin.h" void GraPhlAnPlugin::input(std::string file) { inputfile = file; annotateFlag = false; std::ifstream ifile(inputfile.c_str(), std::ios::in); while (!ifile.eof()) { std::string key, value; ifile >> key; if (key == "annotations") annotateFlag = true; std::cout << key << std::endl; ifile >> value; parameters[key] = value; } } void GraPhlAnPlugin::run() { } void GraPhlAnPlugin::output(std::string file) { //std::string command = "export OLDPATH=${PYTHONPATH}; export PYTHONPATH=${PYTHON2_DIST_PACKAGES}:${PYTHON2_SITE_PACKAGES}:${PYTHONPATH}; " // This is a Python2 application, but does not need these to be set (checked TMC) std::string command = ""; if (annotateFlag) { command += "graphlan_annotate.py "+parameters["tree"]+" "+file+".annot.xml"+" --annot "+parameters["annotations"]+"; "; command += "graphlan.py "+file+".annot.xml"+" "+file+".png"+" --dpi "+parameters["dpi"]+" --size "+parameters["size"]; } else { command += "graphlan.py "+parameters["tree"]+" "+file+".png"+" --dpi "+parameters["dpi"]+" --size "+parameters["size"]; } std::cout << command << std::endl; system(command.c_str()); } PluginProxy<GraPhlAnPlugin> GraPhlAnPluginProxy = PluginProxy<GraPhlAnPlugin>("GraPhlAn", PluginManager::getInstance());
33.285714
142
0.650215
movingpictures83
d9e3e4a0826be431fa25cbbe29a862edbe9ed409
3,014
cpp
C++
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1521/c.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <unordered_map> #include <vector> #include <cassert> #include <algorithm> #include <chrono> #include <random> using namespace std; void solve() { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); unordered_map<int, int> mp; int n; cin >> n; // Initial phase. cout << "? " << 1 << " " << 1 << " " << 2 << " " << n - 1 << "\n"; int max_1_2; int min_1_2; int num; cin >> max_1_2; cout << "? " << 1 << " " << 2 << " " << 1 << " " << n - 1 << "\n"; cin >> num; max_1_2 = max(max_1_2, num); cout << "? " << 1 << " " << 2 << " " << 1 << " " << max_1_2 - 1 << "\n"; cin >> num; // p1 < p2 => result is p2 - 1 int cur_unknown_idx; int max_known = max_1_2; if (num == max_known - 1) { mp[max_known] = 2; cur_unknown_idx = 1; } else { // p1 > p2 otherwise. mp[max_known] = 1; cur_unknown_idx = 2; } // Get second cout << "? " << 2 << " " << cur_unknown_idx << " " << mp[max_known] << " " << 1 << "\n"; cin >> min_1_2; if (min_1_2 == max(2, max_known)) { cout << "? " << 1 << " " << mp[max_known] << " " << cur_unknown_idx << " " << n - 1 << "\n"; cin >> max_1_2; mp[max_1_2] = cur_unknown_idx; max_known = max(max_known, max_1_2); } else { mp[min_1_2] = cur_unknown_idx; max_known = max(max_known, min_1_2); } // The first and second are known. // find the others vector<int> indices; for (int i = 3; i <= n; ++i) { indices.push_back(i); } shuffle(indices.begin(), indices.end(), std::default_random_engine(seed)); for (int i = 3; i <= n; ++i) { // still don't know n - i + 1 numbers int cnt_less_unknown = max_known - (i - 1); int cnt_greater_unknown = n - max_known + 1; int idx = indices[i - 3]; // chances are we'll encounter the number that is less! if (cnt_less_unknown > cnt_greater_unknown) { cout << "? 2 " << idx << " " << mp[max_known] << " " << 1 << endl; cin >> min_1_2; if (min_1_2 == max_known) { // ops, bad luck! cout << "? 1 " << mp[max_known] << " " << idx << " " << n - 1 << endl; cin >> max_1_2; mp[max_1_2] = idx; max_known = max(max_known, max_1_2); } else { mp[min_1_2] = idx; } } else { // chances are we'll encounter the number that is greater cout << "? 1 " << mp[max_known] << " " << idx << " " << n - 1 << endl; cin >> max_1_2; if (max_1_2 == min(max_known, n - 1)) { // ops, bad luck! cout << "? 2 " << idx << " " << mp[max_known] << " " << 1 << endl; cin >> min_1_2; mp[min_1_2] = idx; } else { mp[max_1_2] = idx; max_known = max(max_known, max_1_2); } } } vector<int> ans(n, 0); for (auto [num, idx]: mp) { ans[idx - 1] = num; } cout << "! "; for (auto el: ans) { cout << el << " "; } cout << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } cout.flush(); return 0; }
25.982759
96
0.500664
vladshablinsky
d9e50470ee21ab61a147555aaf145938bc90c2df
16,993
cpp
C++
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
shimmer/src/configuration.cpp
jasbok/libshimmer
794b0e27ee8492f46202efebd24dab32a7c5c1da
[ "MIT" ]
null
null
null
#include "configuration.h" #include "common/env.h" #include "common/file.h" #include "common/json.h" #include <sstream> namespace shimmer { const common::logger& config::logger = common::logger::get ( "shimmer::config" ); nlohmann::json config::merge ( const nlohmann::json& a, const nlohmann::json& b ) { auto merged = b.flatten(); for ( const auto& prop : a.items() ) { if ( !prop.value().is_null() ) merged[prop.key()] = prop.value(); } return merged.unflatten(); } nlohmann::json config::from_environment() { nlohmann::json conf = nlohmann::json::object(); auto evars = common::env::find_all ( std::regex ( "^SHIMMER_.*" ) ); if ( !evars.empty() ) { for ( auto& evar : evars ) { auto key = evar.first.substr ( 8, evar.first.length() ); key = common::str::replace ( key, "_", "/" ); key = common::str::lower ( key ); conf["/" + key] = evar.second; } conf = conf.unflatten(); } logger.debug ( "Environment config: {}", conf.dump ( 2 ) ); return conf; } nlohmann::json config::from_file ( const std::string& path ) { auto conf = nlohmann::json ( common::file::read_all ( path ) ); logger.debug ( "File config ({}): {}", path, conf.dump ( 2 ) ); return nlohmann::json ( conf ); } config config::create() { config conf = from_environment(); if ( !conf.general.config_dirs.empty() ) { try { auto config_file = common::file::find ( "shimmer.conf", conf.general.config_dirs ); conf = merge ( from_file ( config_file ), conf ); } catch ( const std::exception& ex ) { logger.warn ( "Failed to load config file:\n{}", ex.what() ); } } logger.debug ( "Shimmer configuration: {}", nlohmann::json ( conf ).dump ( 2 ) ); return conf; } template<typename T> void set_property ( T& property, const nlohmann::json& json, const std::string& field ) { try { property = json.at ( field ).get<T>(); } catch ( const nlohmann::json::exception& ex ) { if ( ex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } template<> void set_property ( unsigned int& property, const nlohmann::json& json, const std::string& field ) { try { auto value = json.at ( field ); if ( value.is_string() ) { value = std::stof ( value.get<std::string>() ); } property = value.get<unsigned int>(); } catch ( const nlohmann::json::exception& jex ) { if ( jex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\n{}", field, json.at ( field ).dump(), jex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nExpected an unsigned integer.\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } template<> void set_property ( float& property, const nlohmann::json& json, const std::string& field ) { try { auto value = json.at ( field ); if ( value.is_string() ) { value = std::stof ( value.get<std::string>() ); } property = value.get<float>(); } catch ( const nlohmann::json::exception& jex ) { if ( jex.id == 403 ) {} else { config::logger.warn ( "Unable to set config property: {} -> {}\n{}", field, json.at ( field ).dump(), jex.what() ); } } catch ( const std::exception& ex ) { config::logger.warn ( "Unable to set config property: {} -> {}\nExpected a float.\nException: {}", field, json.at ( field ).dump(), ex.what() ); } } config::mapping_exception::mapping_exception( const std::string& property, const std::string& value, const std::vector<std::string>& expected ) : runtime_error ( "Could not map value: '" + property + "' => '" + value + "'; expected one of the following: [" + common::str::join ( expected, ", " ) + "]." ) {} std::string to_string ( const enum config::logging::level& level ) { switch ( level ) { case config::logging::level::debug: return "debug"; case config::logging::level::error: return "error"; case config::logging::level::fatal: return "fatal"; case config::logging::level::info: return "info"; case config::logging::level::off: return "off"; case config::logging::level::trace: return "trace"; case config::logging::level::warning: return "warning"; } return "warning"; } std::string to_string ( const enum config::logging::output& output ) { switch ( output ) { case config::logging::output::console: return "console"; case config::logging::output::file: return "file"; } return "console"; } std::string to_string ( const enum config::video::filter& filter ) { switch ( filter ) { case config::video::filter::linear: return "linear"; case config::video::filter::nearest: return "nearest"; } return "nearest"; } std::string to_string ( const enum config::video::aspect& aspect ) { switch ( aspect ) { case config::video::aspect::custom: return "custom"; case config::video::aspect::original: return "original"; case config::video::aspect::stretch: return "stretch"; case config::video::aspect::zoom: return "zoom"; } return "original"; } std::string to_string ( const enum config::video::shape::type& shape ) { switch ( shape ) { case config::video::shape::type::lens: return "lens"; case config::video::shape::type::rectangle: return "rectangle"; } return "rectangle"; } void from_string ( enum config::logging::level& level, const std::string& str ) { if ( str.compare ( "debug" ) == 0 ) { level = config::logging::level::debug; } else if ( str.compare ( "error" ) == 0 ) { level = config::logging::level::error; } else if ( str.compare ( "fatal" ) == 0 ) { level = config::logging::level::fatal; } else if ( str.compare ( "info" ) == 0 ) { level = config::logging::level::info; } else if ( str.compare ( "off" ) == 0 ) { level = config::logging::level::off; } else if ( str.compare ( "trace" ) == 0 ) { level = config::logging::level::trace; } else if ( str.compare ( "warning" ) == 0 ) { level = config::logging::level::warning; } else { throw config::mapping_exception ( "config::logging::level", str, { "trace", "debug", "info", "warning", "error", "fatal", "off" } ); } } void from_string ( enum config::logging::output& output, const std::string& str ) { if ( str.compare ( "console" ) == 0 ) { output = config::logging::output::console; } else if ( str.compare ( "file" ) == 0 ) { output = config::logging::output::file; } else { throw config::mapping_exception ( "config::logging::output", str, { "console", "file" } ); } } void from_string ( enum config::video::filter& filter, const std::string& str ) { if ( str.compare ( "linear" ) == 0 ) { filter = config::video::filter::linear; } else if ( str.compare ( "nearest" ) == 0 ) { filter = config::video::filter::nearest; } else { throw config::mapping_exception ( "config::video::filter", str, { "linear", "nearest" } ); } } void from_string ( enum config::video::aspect& aspect, const std::string& str ) { if ( str.compare ( "custom" ) == 0 ) { aspect = config::video::aspect::custom; } else if ( str.compare ( "original" ) == 0 ) { aspect = config::video::aspect::original; } else if ( str.compare ( "stretch" ) == 0 ) { aspect = config::video::aspect::stretch; } else if ( str.compare ( "zoom" ) == 0 ) { aspect = config::video::aspect::zoom; } else { throw config::mapping_exception ( "config::video::aspect", str, { "custom", "original", "stretch", "zoom" } ); } } void from_string ( enum config::video::shape::type& shape, const std::string& str ) { if ( str.compare ( "lens" ) == 0 ) { shape = config::video::shape::type::lens; } else if ( str.compare ( "rectangle" ) == 0 ) { shape = config::video::shape::type::rectangle; } else { throw config::mapping_exception ( "config::video::shape::type", str, { "lens", "rectangle" } ); } } void to_json ( nlohmann::json& json, const config& config ) { json = { { "general", config.general }, { "input", config.input }, { "logging", config.logging }, { "video", config.video }, }; } void from_json ( const nlohmann::json& json, config& config ) { set_property ( config.general, json, "general" ); set_property ( config.input, json, "input" ); set_property ( config.logging, json, "logging" ); set_property ( config.video, json, "video" ); } void to_json ( nlohmann::json& json, const struct config::general& general ) { json = { { "config_dirs", general.config_dirs }, { "data_dirs", general.data_dirs }, { "font_dirs", general.font_dirs }, { "image_dirs", general.image_dirs }, { "shaders_dirs", general.shader_dirs }, }; } void from_json ( const nlohmann::json& json, struct config::general& general ) { set_property ( general.config_dirs, json, "config_dirs" ); set_property ( general.data_dirs, json, "data_dirs" ); set_property ( general.font_dirs, json, "font_dirs" ); set_property ( general.image_dirs, json, "image_dirs" ); set_property ( general.shader_dirs, json, "shader_dirs" ); } void to_json ( nlohmann::json& json, const struct config::input& input ) { json = { { "grab", input.grab } }; } void from_json ( const nlohmann::json& json, struct config::input& input ) { set_property ( input.grab, json, "grab" ); } void to_json ( nlohmann::json& json, const struct config::logging& logging ) { json = { { "level", logging.level }, { "output", logging.output }, { "file", logging.file } }; } void from_json ( const nlohmann::json& json, struct config::logging& logging ) { set_property ( logging.level, json, "level" ); set_property ( logging.output, json, "output" ); set_property ( logging.file, json, "file" ); } void to_json ( nlohmann::json& json, const enum config::logging::level& level ) { json = to_string ( level ); } void from_json ( const nlohmann::json& json, enum config::logging::level& level ) { from_string ( level, json ); } void to_json ( nlohmann::json& json, const enum config::logging::output& output ) { json = to_string ( output ); } void from_json ( const nlohmann::json& json, enum config::logging::output& output ) { from_string ( output, json ); } void to_json ( nlohmann::json& json, const struct config::video& video ) { json = { { "aspect", video.aspect }, { "custom_aspect", video.custom_aspect }, { "filter", video.filter }, { "font", video.font }, { "limiter", video.limiter }, { "shader", video.shader }, { "shape", video.shape } }; } void from_json ( const nlohmann::json& json, struct config::video& video ) { set_property ( video.aspect, json, "aspect" ); set_property ( video.custom_aspect, json, "custom_aspect" ); set_property ( video.filter, json, "filter" ); set_property ( video.font, json, "font" ); set_property ( video.limiter, json, "limiter" ); set_property ( video.shader, json, "shader" ); set_property ( video.shape, json, "shape" ); } void to_json ( nlohmann::json& json, const enum config::video::aspect& aspect ) { json = to_string ( aspect ); } void from_json ( const nlohmann::json& json, enum config::video::aspect& aspect ) { from_string ( aspect, json ); } void to_json ( nlohmann::json& json, const enum config::video::filter& filter ) { json = to_string ( filter ); } void from_json ( const nlohmann::json& json, enum config::video::filter& filter ) { from_string ( filter, json ); } void to_json ( nlohmann::json& json, const struct config::video::limiter& limiter ) { json = { { "rate", limiter.rate }, { "samples", limiter.samples } }; } void from_json ( const nlohmann::json& json, struct config::video::limiter& limiter ) { set_property ( limiter.rate, json, "rate" ); set_property ( limiter.samples, json, "samples" ); } void to_json ( nlohmann::json& json, const struct config::video::shader& shader ) { json = { { "fragment", shader.fragment }, { "scale", shader.scale }, { "vertex", shader.vertex } }; } void from_json ( const nlohmann::json& json, struct config::video::shader& shader ) { set_property ( shader.fragment, json, "fragment" ); set_property ( shader.scale, json, "scale" ); set_property ( shader.vertex, json, "vertex" ); } void to_json ( nlohmann::json& json, const struct config::video::shape& shape ) { json = { { "type", shape.type }, { "lens", shape.lens } }; } void from_json ( const nlohmann::json& json, struct config::video::shape& shape ) { set_property ( shape.lens, json, "lens" ); set_property ( shape.type, json, "type" ); } void to_json ( nlohmann::json& json, const struct config::video::shape::lens& lens ) { json = { { "curve", lens.curve }, { "quality", lens.quality } }; } void from_json ( const nlohmann::json& json, struct config::video::shape::lens& lens ) { set_property ( lens.curve, json, "curve" ); set_property ( lens.quality, json, "quality" ); } void to_json ( nlohmann::json& json, const enum config::video::shape::type& type ) { json = to_string ( type ); } void from_json ( const nlohmann::json& json, enum config::video::shape::type& type ) { from_string ( type, json ); } } // namespace shimmer
31.009124
100
0.496852
jasbok
d9e897debb36785021c3255d4f5a1bdb1e3c0111
3,126
hpp
C++
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
1
2020-09-27T04:33:53.000Z
2020-09-27T04:33:53.000Z
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
null
null
null
cm730controller/include/cm730controller/cm730controller.hpp
threeal/ros2_cm730
2f5e3a60395405c4af6dcfb5a7c5a56ede921b09
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Bold Hearts // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CM730CONTROLLER__CM730CONTROLLER_HPP_ #define CM730CONTROLLER__CM730CONTROLLER_HPP_ #include <rclcpp/rclcpp.hpp> #include <cm730driver_msgs/srv/write.hpp> #include <cm730driver_msgs/srv/bulk_read.hpp> #include <cm730driver_msgs/srv/sync_write.hpp> #include <cm730controller_msgs/msg/cm730_info.hpp> #include <cm730controller_msgs/msg/mx28_info_array.hpp> #include <cm730controller_msgs/msg/mx28_command.hpp> #include <map> #include "cm730controller/visibility_control.h" namespace cm730controller { class Cm730Controller : public rclcpp::Node { public: Cm730Controller(); virtual ~Cm730Controller(); private: // Convenience types using Write = cm730driver_msgs::srv::Write; using BulkRead = cm730driver_msgs::srv::BulkRead; using SyncWrite = cm730driver_msgs::srv::SyncWrite; using CM730Info = cm730controller_msgs::msg::CM730Info; using MX28InfoArray = cm730controller_msgs::msg::MX28InfoArray; using MX28Command = cm730controller_msgs::msg::MX28Command; using CM730EepromTable = cm730controller_msgs::msg::CM730EepromTable; using MX28EepromTable = cm730controller_msgs::msg::MX28EepromTable; using WriteClient = rclcpp::Client<Write>; using BulkReadClient = rclcpp::Client<BulkRead>; using SyncWriteClient = rclcpp::Client<SyncWrite>; // Clients for CM730 driver services WriteClient::SharedPtr writeClient_; BulkReadClient::SharedPtr bulkReadClient_; SyncWriteClient::SharedPtr syncWriteClient_; // Subscribers rclcpp::Subscription<MX28Command>::SharedPtr mx28CommandSub_; std::mutex mx28CommandMutex_; MX28Command::SharedPtr mx28Command_; // Publishers rclcpp::Publisher<CM730Info>::SharedPtr cm730InfoPub_; rclcpp::Publisher<MX28InfoArray>::SharedPtr mx28InfoPub_; // Static info CM730EepromTable::SharedPtr staticCm730Info_; std::map<uint8_t, MX28EepromTable::SharedPtr> staticMx28Info_; // Timer for main loop rclcpp::TimerBase::SharedPtr loopTimer_; void powerOn(); void readStaticInfo(); void handleStaticInfo(BulkReadClient::SharedFuture response); void startLoop(); void handleDynamicInfo(BulkReadClient::SharedFuture response); void writeCommands(); template<typename TCommand> typename TCommand::SharedPtr grabCommand(typename TCommand::SharedPtr & cmd, std::mutex & mutex) { std::lock_guard<std::mutex> lock{mutex}; if (cmd == nullptr) { return nullptr; } auto grab = cmd; cmd.reset(); return grab; } }; } // namespace cm730controller #endif // CM730CONTROLLER__CM730CONTROLLER_HPP_
30.647059
98
0.769354
threeal
d9ec3646acd7ee895d51e55d3a494c7b51b0af94
592
cpp
C++
test-suite/generated-src/jni/NativeJavaOnlyListener.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/jni/NativeJavaOnlyListener.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/jni/NativeJavaOnlyListener.cpp
ggilles/djinni
f8b6b6bdd4ef95d63b78d2640b415f3636e58fa5
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from single_language_interfaces.djinni #include "NativeJavaOnlyListener.hpp" // my header namespace djinni_generated { NativeJavaOnlyListener::NativeJavaOnlyListener() : ::djinni::JniInterface<::testsuite::JavaOnlyListener, NativeJavaOnlyListener>() {} NativeJavaOnlyListener::~NativeJavaOnlyListener() = default; NativeJavaOnlyListener::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { } NativeJavaOnlyListener::JavaProxy::~JavaProxy() = default; } // namespace djinni_generated
32.888889
133
0.785473
ggilles
d9ecd7a377e127ff44518c0ae390d90fed546d81
2,134
cpp
C++
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
2
2018-06-30T06:05:29.000Z
2021-08-24T22:34:19.000Z
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
13
2018-07-07T00:11:08.000Z
2018-09-05T02:49:11.000Z
SensorPi/src/ui.cpp
tfrec-kalcsits/SensorSystem
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
[ "MIT" ]
null
null
null
#include <sensorpi/ui.h> #include <wiringPi.h> #include <mcp23017.h> #include <lcd.h> //functions taken from lcd-adafruit.c in wiringPi namespace sensorsystem { static void setBacklightColour (int colour) { colour &= 7 ; digitalWrite (AF_RED, !(colour & 1)) ; digitalWrite (AF_GREEN, !(colour & 2)) ; digitalWrite (AF_BLUE, !(colour & 4)) ; } static int adafruitLCDSetup (int colour) { int i ; pinMode (AF_RED, OUTPUT) ; pinMode (AF_GREEN, OUTPUT) ; pinMode (AF_BLUE, OUTPUT) ; setBacklightColour (colour) ; for (i = 0 ; i <= 4 ; ++i) { pinMode (AF_BASE + i, INPUT) ; pullUpDnControl (AF_BASE + i, PUD_UP) ; } pinMode (AF_RW, OUTPUT) ; digitalWrite (AF_RW, LOW) ; return lcdInit (2, 16, 4, AF_RS, AF_E, AF_DB4,AF_DB5,AF_DB6,AF_DB7, 0,0,0,0) ; } int initLCD() { mcp23017Setup(AF_BASE, 0x20); return adafruitLCDSetup(7); } void initMainScreen(int handle) { lcdClear(handle); lcdHome(handle); lcdPuts(handle, "A:"); lcdPosition(handle, 0, 1); lcdPuts(handle, "O: L:"); } void printMainScreenMeasurements(int handle, float ambient, float object, float lux) { lcdPosition(handle, 2, 0); lcdPrintf(handle, "%.2f", ambient); lcdPosition(handle, 2, 1); lcdPrintf(handle, "%.2f", object); lcdPosition(handle, 10,1); lcdPrintf(handle, "%.1f", lux); } bool isButtonPressed(int handle, uint8_t button) { return digitalRead(button) == LOW; } void waitForRelease(int handle) { while(isButtonPressed(handle, AF_UP) || isButtonPressed(handle, AF_DOWN) || isButtonPressed(handle, AF_LEFT) || isButtonPressed(handle, AF_RIGHT) || isButtonPressed(handle, AF_SELECT)); } uint8_t waitForInput(int handle) { for(;;) { if(isButtonPressed(handle, AF_UP)) return AF_UP; if(isButtonPressed(handle, AF_DOWN)) return AF_DOWN; if(isButtonPressed(handle, AF_RIGHT)) return AF_RIGHT; if(isButtonPressed(handle, AF_LEFT)) return AF_LEFT; if(isButtonPressed(handle, AF_SELECT)) return AF_SELECT; } } }
22
84
0.636364
tfrec-kalcsits
d9ed3409b8c5e807cd7ef53aff859ba86be8cffa
9,126
cpp
C++
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
4
2018-12-08T15:35:38.000Z
2021-08-06T03:23:06.000Z
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
src/bkGL/vao/VertexAttributePointer.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * 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 <algorithm> #include <string> #include <bkGL/vao/VertexAttributePointer.h> #include <bkGL/gl_type_traits.h> namespace bk { //==================================================================================================== //===== MEMBERS //==================================================================================================== class VertexAttributePointer::Impl { public: GLuint id; GLenum value_type; GLboolean normalized; // GL_FALSE / GL_TRUE std::string name; Impl(GLuint id, GLenum value_type, bool normalized, std::string name) : id(id), value_type(value_type), normalized(normalized ? GL_TRUE : GL_FALSE), name(name) { /* do nothing */ } Impl(const Impl&) = default; Impl(Impl&&) noexcept = default; ~Impl() = default; [[maybe_unused]] Impl& operator=(const Impl&) = default; [[maybe_unused]] Impl& operator=(Impl&&) noexcept = default; }; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== /// @{ -------------------------------------------------- CTOR VertexAttributePointer::VertexAttributePointer() : VertexAttributePointer(0, GL_FLOAT, false, "var") { /* do nothing */ } VertexAttributePointer::VertexAttributePointer(GLuint id, GLenum value_type, bool normalized, std::string name) : _pdata(id, value_type, normalized, name) { /* do nothing */ } VertexAttributePointer::VertexAttributePointer(const self_type&) = default; VertexAttributePointer::VertexAttributePointer(self_type&&) noexcept = default; /// @} /// @{ -------------------------------------------------- DTOR VertexAttributePointer::~VertexAttributePointer() = default; /// @} //==================================================================================================== //===== GETTER //==================================================================================================== /// @{ -------------------------------------------------- GET ID GLuint VertexAttributePointer::id() const { return _pdata->id; } /// @} /// @{ -------------------------------------------------- GET NUMEL GLint VertexAttributePointer::numel() const { return gl_numel(_pdata->value_type); } /// @} /// @{ -------------------------------------------------- GET VALUE_TYPE GLenum VertexAttributePointer::value_type() const { return _pdata->value_type; } /// @} /// @{ -------------------------------------------------- GET SIZE IN BYTES GLsizei VertexAttributePointer::size_in_bytes() const { return gl_size_in_bytes(_pdata->value_type); } /// @} /// @{ -------------------------------------------------- GET NORMALIZED GLboolean VertexAttributePointer::is_normalized() const { return _pdata->normalized; } /// @} /// @{ -------------------------------------------------- GET NAME const std::string& VertexAttributePointer::name() const { return _pdata->name; } /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = auto VertexAttributePointer::operator=(const self_type& other) -> self_type& = default; auto VertexAttributePointer::operator=(self_type&&) noexcept -> self_type& = default; /// @} /// @{ -------------------------------------------------- SET VALUE TYPE void VertexAttributePointer::set_value_type(GLenum type) { _pdata->value_type = type; } void VertexAttributePointer::set_value_type_BYTE() { set_value_type(GL_BYTE); } void VertexAttributePointer::set_value_type_UNSIGNED_BYTE() { set_value_type(GL_UNSIGNED_BYTE); } void VertexAttributePointer::set_value_type_SHORT() { set_value_type(GL_SHORT); } void VertexAttributePointer::set_value_type_UNSIGNED_SHORT() { set_value_type(GL_UNSIGNED_SHORT); } void VertexAttributePointer::set_value_type_INT_VEC2() { set_value_type(GL_INT_VEC2); } void VertexAttributePointer::set_value_type_INT_VEC3() { set_value_type(GL_INT_VEC3); } void VertexAttributePointer::set_value_type_INT_VEC4() { set_value_type(GL_INT_VEC4); } void VertexAttributePointer::set_value_type_INT() { set_value_type(GL_INT); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC2() { set_value_type(GL_UNSIGNED_INT_VEC2); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC3() { set_value_type(GL_UNSIGNED_INT_VEC3); } void VertexAttributePointer::set_value_type_UNSIGNED_INT_VEC4() { set_value_type(GL_UNSIGNED_INT_VEC4); } void VertexAttributePointer::set_value_type_UNSIGNED_INT() { set_value_type(GL_UNSIGNED_INT); } void VertexAttributePointer::set_value_type_FLOAT_VEC2() { set_value_type(GL_FLOAT_VEC2); } void VertexAttributePointer::set_value_type_FLOAT_VEC3() { set_value_type(GL_FLOAT_VEC3); } void VertexAttributePointer::set_value_type_FLOAT_VEC4() { set_value_type(GL_FLOAT_VEC4); } void VertexAttributePointer::set_value_type_FLOAT_MAT2() { set_value_type(GL_FLOAT_MAT2); } void VertexAttributePointer::set_value_type_FLOAT_MAT2x3() { set_value_type(GL_FLOAT_MAT2x3); } void VertexAttributePointer::set_value_type_FLOAT_MAT2x4() { set_value_type(GL_FLOAT_MAT2x4); } void VertexAttributePointer::set_value_type_FLOAT_MAT3() { set_value_type(GL_FLOAT_MAT3); } void VertexAttributePointer::set_value_type_FLOAT_MAT3x2() { set_value_type(GL_FLOAT_MAT3x2); } void VertexAttributePointer::set_value_type_FLOAT_MAT3x4() { set_value_type(GL_FLOAT_MAT3x4); } void VertexAttributePointer::set_value_type_FLOAT_MAT4() { set_value_type(GL_FLOAT_MAT4); } void VertexAttributePointer::set_value_type_FLOAT_MAT4x2() { set_value_type(GL_FLOAT_MAT4x2); } void VertexAttributePointer::set_value_type_FLOAT_MAT4x3() { set_value_type(GL_FLOAT_MAT4x3); } void VertexAttributePointer::set_value_type_FLOAT() { set_value_type(GL_FLOAT); } void VertexAttributePointer::set_value_type_DOUBLE_VEC2() { set_value_type(GL_DOUBLE_VEC2); } void VertexAttributePointer::set_value_type_DOUBLE_VEC3() { set_value_type(GL_DOUBLE_VEC3); } void VertexAttributePointer::set_value_type_DOUBLE_VEC4() { set_value_type(GL_DOUBLE_VEC4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2() { set_value_type(GL_DOUBLE_MAT2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2x3() { set_value_type(GL_DOUBLE_MAT2x3); } void VertexAttributePointer::set_value_type_DOUBLE_MAT2x4() { set_value_type(GL_DOUBLE_MAT2x4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3() { set_value_type(GL_DOUBLE_MAT3); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3x2() { set_value_type(GL_DOUBLE_MAT3x2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT3x4() { set_value_type(GL_DOUBLE_MAT3x4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4() { set_value_type(GL_DOUBLE_MAT4); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4x2() { set_value_type(GL_DOUBLE_MAT4x2); } void VertexAttributePointer::set_value_type_DOUBLE_MAT4x3() { set_value_type(GL_DOUBLE_MAT4x3); } void VertexAttributePointer::set_value_type_DOUBLE() { set_value_type(GL_DOUBLE); } /// @} /// @{ -------------------------------------------------- SET NORMALIZED void VertexAttributePointer::set_normalized(bool b) { _pdata->normalized = b ? GL_TRUE : GL_FALSE; } /// @} /// @{ -------------------------------------------------- SET NAME void VertexAttributePointer::set_name(std::string name) { _pdata->name = name; } /// @} } // namespace bk
36.358566
113
0.623603
BenKoehler
d9edcbce7865b0e126ad3b005bc0448ce001ff11
7,233
cpp
C++
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
test/unit/type-analysis/DexTypeEnvironmentTest.cpp
agampe/redex
e49d6e26c10fedc7becf5b3ee2b76ea6f2610aae
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "DexTypeEnvironment.h" #include <boost/optional/optional_io.hpp> #include "Creators.h" #include "RedexTest.h" struct DexTypeEnvironmentTest : public RedexTest { public: /* * Ljava/lang/Object; * | * A * / \ * B C * \ * D * \ * E * * Ljava/lang/Object; * | * H * | * I */ DexTypeEnvironmentTest() { // Synthesizing Ljava/lang/Object; ClassCreator creator = ClassCreator(type::java_lang_Object()); creator.create(); m_type_a = DexType::make_type("A"); creator = ClassCreator(m_type_a); creator.set_super(type::java_lang_Object()); creator.create(); m_type_b = DexType::make_type("B"); creator = ClassCreator(m_type_b); creator.set_super(m_type_a); creator.create(); m_type_c = DexType::make_type("C"); creator = ClassCreator(m_type_c); creator.set_super(m_type_a); creator.create(); m_type_d = DexType::make_type("D"); creator = ClassCreator(m_type_d); creator.set_super(m_type_c); creator.create(); m_type_e = DexType::make_type("E"); creator = ClassCreator(m_type_e); creator.set_super(m_type_d); creator.create(); m_type_h = DexType::make_type("H"); creator = ClassCreator(m_type_h); creator.set_super(type::java_lang_Object()); creator.create(); m_type_i = DexType::make_type("I"); creator = ClassCreator(m_type_i); creator.set_super(m_type_h); creator.create(); } protected: DexType* m_type_a; DexType* m_type_b; DexType* m_type_c; DexType* m_type_d; DexType* m_type_e; DexType* m_type_h; DexType* m_type_i; }; TEST_F(DexTypeEnvironmentTest, BasicTest) { auto env = DexTypeEnvironment(); EXPECT_TRUE(env.is_top()); auto& reg_env = env.get_reg_environment(); EXPECT_TRUE(reg_env.is_top()); auto& field_env = env.get_field_environment(); EXPECT_TRUE(field_env.is_top()); } TEST_F(DexTypeEnvironmentTest, RegisterEnvTest) { auto env = DexTypeEnvironment(); reg_t v0 = 0; auto type = env.get(v0); EXPECT_TRUE(type.is_top()); env.set(v0, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(v0), DexTypeDomain(m_type_a)); reg_t v1 = 1; env.set(v1, DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(v1), DexTypeDomain(m_type_b)); auto a_join_b = DexTypeDomain(m_type_a); a_join_b.join_with(env.get(v1)); EXPECT_EQ(a_join_b, DexTypeDomain(m_type_a)); auto b_join_a = DexTypeDomain(m_type_b); b_join_a.join_with(env.get(v0)); EXPECT_EQ(b_join_a, DexTypeDomain(m_type_a)); } TEST_F(DexTypeEnvironmentTest, FieldEnvTest) { auto env = DexTypeEnvironment(); DexField* f1 = (DexField*)1; auto type = env.get(f1); EXPECT_TRUE(type.is_top()); env.set(f1, DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); DexField* f2 = (DexField*)2; EXPECT_TRUE(env.get(f2).is_top()); env.set(f2, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); auto a_join_b = env.get(f2); a_join_b.join_with(env.get(f1)); EXPECT_EQ(a_join_b, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); auto b_join_a = env.get(f1); b_join_a.join_with(env.get(f2)); EXPECT_EQ(b_join_a, DexTypeDomain(m_type_a)); EXPECT_EQ(env.get(f1), DexTypeDomain(m_type_b)); EXPECT_EQ(env.get(f2), DexTypeDomain(m_type_a)); } TEST_F(DexTypeEnvironmentTest, JoinWithTest) { auto domain_b = DexTypeDomain(m_type_b); auto domain_c = DexTypeDomain(m_type_c); domain_b.join_with(domain_c); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); domain_b = DexTypeDomain(m_type_b); auto domain_d = DexTypeDomain(m_type_d); domain_b.join_with(domain_d); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); domain_b = DexTypeDomain(m_type_b); auto domain_e = DexTypeDomain(m_type_e); domain_b.join_with(domain_e); EXPECT_EQ(domain_b, DexTypeDomain(m_type_a)); auto domain_a = DexTypeDomain(m_type_a); domain_e = DexTypeDomain(m_type_e); domain_a.join_with(domain_e); EXPECT_EQ(domain_a, DexTypeDomain(m_type_a)); auto top1 = DexTypeDomain::top(); auto top2 = DexTypeDomain::top(); top1.join_with(top2); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(top2.is_top()); domain_a = DexTypeDomain(m_type_a); auto domain_h = DexTypeDomain(m_type_h); domain_a.join_with(domain_h); EXPECT_EQ(domain_a, DexTypeDomain(type::java_lang_Object())); domain_b = DexTypeDomain(m_type_b); domain_h = DexTypeDomain(m_type_h); domain_b.join_with(domain_h); EXPECT_EQ(domain_b, DexTypeDomain(type::java_lang_Object())); domain_d = DexTypeDomain(m_type_d); domain_h = DexTypeDomain(m_type_h); domain_d.join_with(domain_h); EXPECT_EQ(domain_d, DexTypeDomain(type::java_lang_Object())); domain_e = DexTypeDomain(m_type_e); domain_h = DexTypeDomain(m_type_h); domain_e.join_with(domain_h); EXPECT_EQ(domain_e, DexTypeDomain(type::java_lang_Object())); domain_b = DexTypeDomain(m_type_b); auto domain_i = DexTypeDomain(m_type_i); domain_b.join_with(domain_i); EXPECT_TRUE(domain_b.get_type_domain().is_top()); EXPECT_FALSE(domain_i.get_type_domain().is_top()); } TEST_F(DexTypeEnvironmentTest, NullableDexTypeDomainTest) { auto null1 = DexTypeDomain::null(); EXPECT_FALSE(null1.is_bottom()); EXPECT_FALSE(null1.is_top()); EXPECT_TRUE(null1.get_type_domain().is_none()); auto type_a = DexTypeDomain(m_type_a); null1.join_with(type_a); EXPECT_FALSE(null1.is_null()); EXPECT_FALSE(null1.is_not_null()); EXPECT_TRUE(null1.is_nullable()); EXPECT_NE(null1, DexTypeDomain(m_type_a)); EXPECT_EQ(*null1.get_dex_type(), m_type_a); EXPECT_EQ(type_a, DexTypeDomain(m_type_a)); EXPECT_FALSE(null1.get_type_domain().is_none()); EXPECT_FALSE(type_a.get_type_domain().is_none()); type_a = DexTypeDomain(m_type_a); null1 = DexTypeDomain::null(); type_a.join_with(null1); EXPECT_FALSE(type_a.is_null()); EXPECT_FALSE(type_a.is_not_null()); EXPECT_TRUE(type_a.is_nullable()); EXPECT_NE(type_a, DexTypeDomain(m_type_a)); EXPECT_EQ(*type_a.get_dex_type(), m_type_a); EXPECT_EQ(null1, DexTypeDomain::null()); EXPECT_FALSE(type_a.get_type_domain().is_none()); EXPECT_TRUE(null1.get_type_domain().is_none()); auto top1 = DexTypeDomain::top(); auto top2 = DexTypeDomain::top(); top1.join_with(top2); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(top2.is_top()); EXPECT_FALSE(top1.get_type_domain().is_none()); EXPECT_FALSE(top2.get_type_domain().is_none()); top1 = DexTypeDomain::top(); auto bottom = DexTypeDomain::bottom(); top1.join_with(bottom); EXPECT_TRUE(top1.is_top()); EXPECT_TRUE(bottom.is_bottom()); EXPECT_FALSE(top1.get_type_domain().is_none()); EXPECT_FALSE(bottom.get_type_domain().is_none()); bottom = DexTypeDomain::bottom(); top1 = DexTypeDomain::top(); bottom.join_with(top1); EXPECT_TRUE(bottom.is_top()); EXPECT_TRUE(top1.is_top()); EXPECT_FALSE(bottom.get_type_domain().is_none()); EXPECT_FALSE(top1.get_type_domain().is_none()); }
28.932
66
0.7163
agampe
d9ef6378ff8a25a2feaa85428776e8cab4a6c3ee
3,621
cpp
C++
libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
ternarylabs/orb
8c89894dc1eabfd99743f16d35786ff354dcc4e5
[ "MIT" ]
2
2017-06-22T16:56:06.000Z
2017-12-14T20:54:14.000Z
src/libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
snrub/big-red-button
dbaaf6969959717de60ad57c933f11e2894621dc
[ "MIT" ]
null
null
null
src/libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
snrub/big-red-button
dbaaf6969959717de60ad57c933f11e2894621dc
[ "MIT" ]
1
2020-05-21T14:00:46.000Z
2020-05-21T14:00:46.000Z
/* * WFSEthernetServer.cpp * Arduino Ethernet Server class for wifi devices * Based on Arduino 1.0 EthernetServer class * * Credits: * First to the Arduino Ethernet team for their model upon which this is based. * Modifications: * Copyright GPL 2.1 Tom Waldock 2012 Version 1.07 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; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "WiFlySerial.h" #include "WFSsocket.h" extern "C" { #include "string.h" } #include "WFSEthernet.h" #include "WFSEthernetClient.h" #include "WFSEthernetServer.h" WFSEthernetServer::WFSEthernetServer(uint16_t port) { _port = port; } // begin // Sets basics for device configuration void WFSEthernetServer::begin() { char bufRequest[COMMAND_BUFFER_SIZE]; wifi.SendCommand( (char*) F("set u m 0x1") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm idle 30") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm time 1000") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm size 255") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); } // setProfile // Configures server to respond in manner specified // Assumes wifi device is semi-automnous. // // Parameters: // serverProfile bit-mapped flag of profile options long WFSEthernetServer::setProfile(long serverProfile) { char bufRequest[SMALL_COMMAND_BUFFER_SIZE]; // Defaults as according to device. // Settings may be residual values from prior saved sessions. if ( serverProfile & ES_DEVICE_DEFAULT) { // Set to default somehow (factory reset?) } if ( serverProfile & ES_HTTP_SERVER ) { // No *HELLO* on connection - confuses browsers wifi.SendCommand( (char*) F("set comm remote 0") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, SMALL_COMMAND_BUFFER_SIZE); // Send packet on each tab character issued wifi.SendCommand( (char*) F("set comm match 0x9") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, SMALL_COMMAND_BUFFER_SIZE); } // Telnet response setup if ( serverProfile & ES_TELNET_SERVER) { } // UDP not implemented yet on CS libraries if ( serverProfile & ES_UDP_SERVER ) { } return serverProfile; } void WFSEthernetServer::accept() { int listening = 0; wifi.serveConnection(); } // returns a WFSEthernetClient using an available socket. // WiFly has one socket so ... use it. WFSEthernetClient WFSEthernetServer::available() { accept(); WFSEthernetClient client(_port); return client; // return WFSEthernetClient(MAX_SOCK_NUM); } size_t WFSEthernetServer::write(uint8_t b) { return write(&b, 1); } size_t WFSEthernetServer::write(const uint8_t *buffer, size_t size) { return wifi.write(buffer, size); }
28.289063
133
0.719967
ternarylabs
d9f1da1de600076dac730fcc06515fd69bed4b52
3,504
cpp
C++
production_apps/ESPRESO/src/input/generator/elements/3D/prisma15.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
production_apps/ESPRESO/src/input/generator/elements/3D/prisma15.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
null
null
null
production_apps/ESPRESO/src/input/generator/elements/3D/prisma15.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
1
2018-09-30T19:04:38.000Z
2018-09-30T19:04:38.000Z
#include "prisma15.h" #include "hexahedron20.h" #include "tetrahedron10.h" #include "../../../../mesh/elements/plane/triangle6.h" #include "../../../../mesh/elements/volume/prisma15.h" using namespace espreso::input; size_t Prisma15::subelements = 2; size_t Prisma15::subnodes[] = { 3, 3, 3 }; void Prisma15::addElements(std::vector<Element*> &elements, const eslocal indices[], const eslocal params[]) { eslocal prisma[15]; prisma[0] = indices[0]; prisma[1] = indices[2]; prisma[2] = indices[8]; prisma[3] = indices[18]; prisma[4] = indices[20]; prisma[5] = indices[26]; prisma[6] = indices[1]; prisma[7] = indices[5]; prisma[8] = indices[4]; prisma[9] = indices[19]; prisma[10] = indices[23]; prisma[11] = indices[22]; prisma[12] = indices[9]; prisma[13] = indices[11]; prisma[14] = indices[17]; elements.push_back(new espreso::Prisma15(prisma, 15, params)); prisma[0] = indices[0]; prisma[1] = indices[8]; prisma[2] = indices[6]; prisma[3] = indices[18]; prisma[4] = indices[26]; prisma[5] = indices[24];; prisma[6] = indices[4]; prisma[7] = indices[7]; prisma[8] = indices[3]; prisma[9] = indices[22]; prisma[10] = indices[25]; prisma[11] = indices[21]; prisma[12] = indices[9]; prisma[13] = indices[17]; prisma[14] = indices[15]; elements.push_back(new espreso::Prisma15(prisma, 15, params)); } void Prisma15::addEdges(std::vector<Element*> &edges, const eslocal indices[], CubeEdge edge) { ESINFO(GLOBAL_ERROR) << "Implement addEdges for PRISMA15"; } void Prisma15::addFaces(std::vector<Element*> &faces, const eslocal indices[], CubeFace face) { eslocal triangle1[6], triangle2[6]; switch (face) { case CubeFace::X_1: case CubeFace::Y_1: case CubeFace::X_0: case CubeFace::Y_0: Hexahedron20::addFaces(faces, indices, face); break; case CubeFace::Z_1: triangle1[0] = indices[20]; triangle1[1] = indices[26]; triangle1[2] = indices[18]; triangle1[3] = indices[23]; triangle1[4] = indices[22]; triangle1[5] = indices[19]; faces.push_back(new Triangle6(triangle1)); triangle2[0] = indices[26]; triangle2[1] = indices[24]; triangle2[2] = indices[18]; triangle2[3] = indices[25]; triangle2[4] = indices[21]; triangle2[5] = indices[22]; faces.push_back(new Triangle6(triangle2)); break; case CubeFace::Z_0: triangle1[0] = indices[ 0]; triangle1[1] = indices[ 6]; triangle1[2] = indices[ 8]; triangle1[3] = indices[ 3]; triangle1[4] = indices[ 7]; triangle1[5] = indices[ 4]; faces.push_back(new Triangle6(triangle1)); triangle2[0] = indices[ 0]; triangle2[1] = indices[ 8]; triangle2[2] = indices[ 2]; triangle2[3] = indices[ 4]; triangle2[4] = indices[ 5]; triangle2[5] = indices[ 1]; faces.push_back(new Triangle6(triangle2)); break; default: ESINFO(GLOBAL_ERROR) << "Incorrect face"; } } void Prisma15::pickNodes(const std::vector<Element*> &nodes, std::vector<Element*> &selection, const eslocal indices[], CubeEdge edge) { ESINFO(GLOBAL_ERROR) << "Implement pickNodes for an edge for HEXA20"; } void Prisma15::pickNodes(const std::vector<Element*> &nodes, std::vector<Element*> &selection, const eslocal indices[], CubeFace face) { switch (face) { case CubeFace::X_1: case CubeFace::Y_1: case CubeFace::X_0: case CubeFace::Y_0: Hexahedron20::pickNodes(nodes, selection, indices, face); break; case CubeFace::Z_0: case CubeFace::Z_1: Tetrahedron10::pickNodes(nodes, selection, indices, face); break; default: ESINFO(GLOBAL_ERROR) << "Incorrect face"; } }
26.748092
134
0.675228
readex-eu
d9f26db61de0feadeb15def7a7c52cc7681c21e0
671
cpp
C++
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
1
2019-03-07T13:08:06.000Z
2019-03-07T13:08:06.000Z
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
null
null
null
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
null
null
null
class Solution { public: vector<string> commonChars(vector<string> &A) { int mem[100][27]; vector<string> ans; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 27; ++j) { mem[i][j] = 0; } } for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < A[i].length(); ++j) { char temp = A[i][j]; mem[i][temp - 'a' + 1]++; } } for (int j = 1; j <= 26; ++j) { int Min = 1000; for (int i = 0; i < A.size(); ++i) { Min = min(Min, mem[i][j]); } char temp = 'a' - 1 + j; string input; input = input + temp; for (int i = 0; i < Min; ++i) { ans.push_back(input); } } return ans; } };
15.25
46
0.435171
WhiteDOU
d9f35e6d4889e81b956f3e104f23722883ad65eb
6,971
cc
C++
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
#include <unordered_set> #include "executor.h" #include "session.h" #include "attr_value_utils.h" #include "base/protobuf_op.h" #include "base/logging.h" #include "openmi/idl/proto/engine.pb.h" #include "openmi/idl/proto/communication.pb.h" using namespace openmi; Tensor* GetTensor(Executor& exec, std::string name) { Tensor* t = nullptr; Status status = exec.GetSessionState()->GetTensor(name, &t); CHECK(t != nullptr) << "tensor not found from session state. name: " << name; return t; } void InitColEmbedding(Tensor** t, std::vector<uint64_t>& batch_dims, const int rank, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); DLOG(INFO) << "placeholder variable:\n" << (*t)->tensor<float, 2>(); } void FillFeatureWeight(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); LOG(INFO) << __FUNCTION__ << " colid[" << colid << "] feature weight:\n" << (*t)->tensor<float, 2>(); } void FillFeatureValue(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); LOG(INFO) << __FUNCTION__ << " colid[" << colid << "] feature value:\n" << (*t)->tensor<float, 2>(); } void FillRowOffset(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, int max_offset) { typedef int32_t T; TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->vec<T>().setConstant(1); for (int i = 0; i < batch_dims[0]; ++i) { int offset = (i == batch_dims[0] - 1) ? max_offset : i+1; (*t)->vec<T>()(i) = offset; } LOG(INFO) << __FUNCTION__ << " colid[" << colid << "], row offset:\n" << (*t)->vec<T>(); } void Iter(Executor& exec, int batch_size) { LOG(INFO) << "================= [placeholder embedding] weigth/value/offset ================= \n"; LOG(INFO) << "batch_size[" << batch_size << "]. update feature weight/value/offset."; int value_size = batch_size * 2; int embedding_size = 8; std::vector<uint64_t> weight_dims; weight_dims.push_back(value_size); weight_dims.push_back(embedding_size); Tensor* embed_c1 = GetTensor(exec, "embed_c1"); Tensor* embed_c2 = GetTensor(exec, "embed_c2"); FillFeatureWeight(&embed_c1, weight_dims, 1, 0.1); FillFeatureWeight(&embed_c2, weight_dims, 2, 0.2); weight_dims[1] = 1; Tensor* x_c1 = GetTensor(exec, "x_c1"); Tensor* x_c2 = GetTensor(exec, "x_c2"); FillFeatureValue(&x_c1, weight_dims, 1, 0.1); FillFeatureValue(&x_c2, weight_dims, 2, 0.2); std::vector<uint64_t> offset_dims; offset_dims.push_back(batch_size); //offset_dims.push_back(1); Tensor* row_offset_c1 = GetTensor(exec, "row_offset_c1"); Tensor* row_offset_c2 = GetTensor(exec, "row_offset_c2"); FillRowOffset(&row_offset_c1, offset_dims, 1, value_size); FillRowOffset(&row_offset_c2, offset_dims, 2, value_size); LOG(INFO) << "================= [placeholder linear] ================= \n"; std::vector<uint64_t> linear_batch_dims; linear_batch_dims.push_back(batch_size); linear_batch_dims.push_back(1L); Tensor* c1_linear = GetTensor(exec, "c1_linear"); Tensor* c3_linear = GetTensor(exec, "c3_linear"); InitColEmbedding(&c1_linear, linear_batch_dims, 2, 0.0001); InitColEmbedding(&c3_linear, linear_batch_dims, 2, 0.0003); LOG(INFO) << "================= [label] ================= \n"; int num_label_dim = 1; Tensor* label = GetTensor(exec, "label"); std::vector<uint64_t> label_dims; label_dims.push_back(batch_size); label_dims.push_back(num_label_dim); TensorShape lshape(label_dims); label->AllocateTensor(lshape); label->tensor<float, 2>().setConstant(1); label->tensor<float, 2>()(0, 0) = 0; DLOG(INFO) << "label:\n" << label->tensor<float, 2>(); LOG(INFO) << "================= [w_layer1] ================= \n"; Tensor* w = GetTensor(exec, "w_layer1"); w->tensor<float, 2>().setConstant(0.03); DLOG(INFO) << "Variable(w_layer1):\n" << w->tensor<float, 2>(); LOG(INFO) << "================= [b_layer1] ================= \n"; Tensor* b = GetTensor(exec, "b_layer1"); b->vec<float>().setConstant(0.00002); DLOG(INFO) << "Variable(b_layer1):\n" << b->vec<float>(); // 2. forward & backword LOG(INFO) << "================= [exec.run] ================= \n"; Status s = exec.Run(); LOG(INFO) << "================= [after run. get grad info] ================= \n"; for (Node* node: exec.GetGraph()->reversed_variable_nodes()) { std::string grad_node_name = node->def().name(); std::string related_node_name = node->related_node_name(); Tensor* grad = GetTensor(exec, grad_node_name); LOG(INFO) << "grad node:" << grad_node_name << ", related_node_name:" << related_node_name; LOG(INFO) << "value:\n" << grad->matrix<float>(); LOG(INFO) << "its shape: " << grad->shape().DebugString(); } LOG(DEBUG) << "done"; } void VariableGradTest(std::unordered_map<std::string, Tensor*>& node2tensor_) { LOG(INFO) << "all valid source node."; for (auto it = node2tensor_.begin(); it != node2tensor_.end(); it++) { LOG(INFO) << "node: " + it->first << ", shape: " << it->second->shape().DebugString(); } } int main(int argc, char** argv) { const char* file = "unittest/conf/wide_and_deep_graph_demo.conf"; LOG(INFO) << "file: " << file; proto::GraphDef gdef; if (ProtobufOp::LoadObjectFromPbFile<proto::GraphDef>(file, &gdef) != 0) { LOG(ERROR) << "load graph def proto file failed."; return -1; } LOG(INFO) << "load graph file done."; Session sess; if (sess.Init(gdef) != 0) { LOG(ERROR) << "session init failed."; return -1; } LOG(INFO) << "session init done."; Executor* exec = sess.GetExecutor().get(); // int batch_size = 5; // Iter(*exec, batch_size); // Iter(*exec, batch_size*2); InstancesPtr instances = std::make_shared<proto::Instances>(); std::unordered_map<uint64_t, proto::comm::ValueList> model_weights; int batch_size = 5; for (int i = 0; i < batch_size; ++i) { auto ins1 = instances->add_instance(); ins1->mutable_label()->add_labels(i % 2 == 0 ? 1 : 0); int f_size = 10; for (int j = 0; j < f_size; ++j) { auto f = ins1->add_feature(); f->set_colid(j); f->set_weight((j+1)*0.1); uint64_t fid = (j*1000 + j); f->set_fid(fid); auto f2 = ins1->add_feature(); f2->set_colid(j); f2->set_weight((j+1)*0.1 + 0.1); auto fid2 = fid + 1; f2->set_fid(fid2); proto::comm::ValueList val_list; for (int k = 0; k < 9; ++k) { val_list.add_val(j*0.1); } model_weights.insert({fid, val_list}); model_weights.insert({fid2, val_list}); } } sess.Run(instances, true); // 1. 获取所有的SourceNode节点 (理应包括所有的reversed variable node) LOG(DEBUG) << "done"; return 0; }
34.855
103
0.619136
ComputationalAdvertising
d9f8e509dbecfd4c7958720f2a97d8c09e60f6d3
15,685
cpp
C++
mc_rtc_rviz_panel/src/PlotWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/PlotWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/PlotWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
#include "PlotWidget.h" #include <qwt_global.h> #if QWT_VERSION < 0x060100 # error "This requires Qwt >= 6.1.0 to build" #endif #include <qwt_plot_renderer.h> #include <qwt_plot_shapeitem.h> #include <qwt_symbol.h> namespace mc_rtc_rviz { namespace { using Color = mc_rtc::gui::Color; using Side = mc_rtc::gui::plot::Side; using Style = mc_rtc::gui::plot::Style; using PolygonDescription = mc_rtc::gui::plot::PolygonDescription; QColor convert(const Color & color) { return QColor::fromRgbF(color.r, color.g, color.b, color.a); } template<typename T> bool setPen(T * curve, Color color, Style style, double width = 0.) { if(style == Style::Point) { setPen(curve, color, Style::Dotted); return false; } auto qc = convert(color); auto pstyle = Qt::SolidLine; if(style == Style::Dashed) { pstyle = Qt::DashLine; } if(style == Style::Dotted) { pstyle = Qt::DotLine; } curve->setPen(qc, width, pstyle); return true; } } // namespace PlotWidget::Curve::Curve(QwtPlot * plot, const std::string & legend, mc_rtc::gui::plot::Side side) { curve_ = new QwtPlotCurve(QwtText(legend.c_str())); curve_->setLegendAttribute(QwtPlotCurve::LegendShowLine); curve_->setLegendIconSize({40, 8}); curve_->attach(plot); curve_->setRenderHint(QwtPlotItem::RenderAntialiased); curve_->setSamples(samples_); if(side == Side::Left) { curve_->setYAxis(QwtPlot::yLeft); } else { curve_->setYAxis(QwtPlot::yRight); } } PlotWidget::Curve::Curve(Curve && rhs) { if(curve_) { curve_->detach(); delete curve_; } curve_ = rhs.curve_; samples_ = rhs.samples_; rect_ = rhs.rect_; rhs.curve_ = nullptr; } PlotWidget::Curve & PlotWidget::Curve::operator=(Curve && rhs) { if(&rhs == this) { return *this; } if(curve_) { curve_->detach(); delete curve_; } curve_ = rhs.curve_; samples_ = rhs.samples_; rect_ = rhs.rect_; rhs.curve_ = nullptr; return *this; } QRectF PlotWidget::Curve::update(double x, double y, mc_rtc::gui::Color color, mc_rtc::gui::plot::Style style, double line_width) { if(samples_.size() == 0) { rect_.setLeft(x); rect_.setRight(x); rect_.setBottom(y); rect_.setTop(y); } if(setPen(curve_, color, style, line_width)) { curve_->setStyle(QwtPlotCurve::Lines); } else { samples_.resize(0); auto symbol = new QwtSymbol(QwtSymbol::XCross); auto qc = convert(color); symbol->setColor(qc); symbol->setPen(qc); symbol->setSize(10); curve_->setSymbol(symbol); curve_->setStyle(QwtPlotCurve::NoCurve); } samples_.push_back({x, y}); curve_->setSamples(samples_); rect_.setLeft(std::min(x, rect_.left())); rect_.setRight(std::max(x, rect_.right())); rect_.setBottom(std::max(y, rect_.bottom())); rect_.setTop(std::min(y, rect_.top())); return rect_; } PlotWidget::Curve::~Curve() { if(curve_) { curve_->detach(); delete curve_; } } PlotWidget::Polygon::Polygon(QwtPlot * plot, const std::string & legend, mc_rtc::gui::plot::Side side) { item_ = new QwtPlotShapeItem(QwtText(legend.c_str())); item_->attach(plot); item_->setRenderHint(QwtPlotItem::RenderAntialiased); item_->setPolygon(polygon_); if(side == Side::Left) { item_->setYAxis(QwtPlot::yLeft); } else { item_->setYAxis(QwtPlot::yRight); } } PlotWidget::Polygon::Polygon(Polygon && rhs) { if(item_) { item_->detach(); delete item_; } poly_ = rhs.poly_; item_ = rhs.item_; polygon_ = rhs.polygon_; rect_ = rhs.rect_; rhs.item_ = nullptr; if(item_) { item_->setPolygon(polygon_); } } PlotWidget::Polygon & PlotWidget::Polygon::operator=(Polygon && rhs) { if(&rhs == this) { return *this; } if(item_) { item_->detach(); delete item_; } poly_ = rhs.poly_; item_ = rhs.item_; polygon_ = rhs.polygon_; rect_ = rhs.rect_; rhs.item_ = nullptr; if(item_) { item_->setPolygon(polygon_); } return *this; } QRectF PlotWidget::Polygon::update(const PolygonDescription & poly) { if(poly_ == poly) { return rect_; } poly_ = poly; polygon_.clear(); if(poly_.points().size()) { const auto & p = poly_.points()[0]; rect_.setLeft(p[0]); rect_.setRight(p[0]); rect_.setTop(p[1]); rect_.setBottom(p[1]); } else { rect_ = QRectF(); } for(const auto & p : poly_.points()) { polygon_ << QPointF{p[0], p[1]}; rect_.setLeft(std::min(p[0], rect_.left())); rect_.setRight(std::max(p[0], rect_.right())); rect_.setBottom(std::max(p[1], rect_.bottom())); rect_.setTop(std::min(p[1], rect_.top())); } if(poly_.closed()) { const auto & p = poly_.points().front(); polygon_ << QPointF{p[0], p[1]}; } setPen(item_, poly_.outline(), poly_.style()); const auto & fill = poly_.fill(); if(poly_.closed()) { item_->setBrush(convert(fill)); } item_->setPolygon(polygon_); return rect_; } PlotWidget::Polygon::~Polygon() { if(item_) { item_->detach(); delete item_; } } PlotWidget::PolygonsVector::PolygonsVector(QwtPlot * plot, const std::string & legend, mc_rtc::gui::plot::Side side) : plot_(plot), legend_(legend), side_(side) { } QRectF PlotWidget::PolygonsVector::update(const std::vector<PolygonDescription> & poly) { polygons_.resize(poly.size()); for(size_t i = 0; i < polygons_.size(); ++i) { if(polygons_[i].poly() != poly[i]) { polygons_[i] = Polygon(plot_, legend_, side_); polygons_[i].update(poly[i]); } } QRectF rect; if(polygons_.size()) { rect = polygons_[0].rect(); } for(size_t i = 1; i < polygons_.size(); ++i) { rect = rect.united(polygons_[i].rect()); } return rect; } PlotWidget::PlotWidget(const std::string & title, QWidget * parent) : QWidget(parent), title_(title) { auto layout = new QVBoxLayout(this); plot_ = new QwtPlot(QwtText(title.c_str()), this); plot_->setCanvasBackground(Qt::white); legend_ = new QwtLegend(); plot_->insertLegend(legend_, QwtPlot::TopLegend); grid_ = new QwtPlotGrid(); grid_->setPen(QColor::fromRgbF(0.0, 0.0, 0.0, 0.5), 0.0, Qt::DashLine); grid_->attach(plot_); layout->addWidget(plot_); auto show_layout = new QHBoxLayout(); auto limit_xrange_cbox = new QCheckBox("Only show the last ", this); connect(limit_xrange_cbox, SIGNAL(stateChanged(int)), this, SLOT(limit_xrange_cbox_changed(int))); show_layout->addWidget(limit_xrange_cbox); auto duration_input = new QDoubleSpinBox(this); duration_input->setMinimum(0); duration_input->setSuffix("s"); duration_input->setValue(show_duration_); connect(duration_input, SIGNAL(valueChanged(double)), this, SLOT(show_duration_changed(double))); show_layout->addWidget(duration_input); layout->addLayout(show_layout); // Controls when paused (zoom, scroll, etc) auto setIcon = [](QPushButton * button, const QString & iconName, const QString & fallbackText) { if(QIcon::hasThemeIcon(iconName)) { button->setIcon(QIcon::fromTheme(iconName)); button->setToolTip(fallbackText); } else { button->setText(fallbackText); } }; controls_widget_ = new QWidget(); controls_widget_->setVisible(false); layout->addWidget(controls_widget_); auto clayout = new QHBoxLayout(controls_widget_); zoom_button_ = new QPushButton(); setIcon(zoom_button_, "zoom-in", "Zoom"); zoom_button_->setCheckable(true); connect(zoom_button_, SIGNAL(clicked()), this, SLOT(zoom_button_clicked())); auto reset_zoom_button = new QPushButton(); setIcon(reset_zoom_button, "go-home", "Reset"); connect(reset_zoom_button, SIGNAL(clicked()), this, SLOT(zoom_reset_button_clicked())); auto prev_zoom_button = new QPushButton(); setIcon(prev_zoom_button, "edit-undo", "Undo zoom"); connect(prev_zoom_button, SIGNAL(clicked()), this, SLOT(zoom_prev_button_clicked())); auto next_zoom_button = new QPushButton(); setIcon(next_zoom_button, "edit-redo", "Redo zoom"); connect(next_zoom_button, SIGNAL(clicked()), this, SLOT(zoom_next_button_clicked())); pan_button_ = new QPushButton(); setIcon(pan_button_, "transform-move", "Move"); pan_button_->setCheckable(true); connect(pan_button_, SIGNAL(clicked()), this, SLOT(pan_button_clicked())); clayout->addWidget(reset_zoom_button); clayout->addWidget(zoom_button_); clayout->addWidget(prev_zoom_button); clayout->addWidget(next_zoom_button); clayout->addWidget(pan_button_); auto hlayout = new QHBoxLayout(); pause_button_ = new QPushButton(); pause_button_->setIcon(style()->standardIcon(QStyle::SP_MediaPause)); pause_button_->setCheckable(true); pause_button_->setChecked(true); hlayout->addWidget(pause_button_); connect(pause_button_, SIGNAL(clicked()), this, SLOT(pause_button_clicked())); auto save_button = new QPushButton(this); setIcon(save_button, "document-save-as", "Save as..."); hlayout->addWidget(save_button); connect(save_button, SIGNAL(clicked()), this, SLOT(save_button_clicked())); options_button_ = new QPushButton("More"); options_button_->setCheckable(true); connect(options_button_, SIGNAL(clicked()), this, SLOT(toggle_options_widget())); hlayout->addWidget(options_button_); layout->addLayout(hlayout); // Additional options group (line width, etc), hidden by default options_widget_ = new QGroupBox("Style Options", this); options_widget_->setVisible(false); auto options_layout = new QVBoxLayout(); auto line_width_layout = new QHBoxLayout(); auto line_width_label = new QLabel("Line width"); line_width_layout->addWidget(line_width_label); auto line_width_input = new QDoubleSpinBox(this); line_width_input->setValue(line_width_); line_width_input->setMinimum(0); line_width_layout->addWidget(line_width_input); connect(line_width_input, SIGNAL(valueChanged(double)), this, SLOT(line_width_changed(double))); options_layout->addLayout(line_width_layout); options_widget_->setLayout(options_layout); layout->addWidget(options_widget_); show(); zoom_ = new QwtPlotZoomer(QwtPlot::xBottom, QwtPlot::yLeft, plot_->canvas()); zoom_->setEnabled(false); pan_ = new QwtPlotPanner(plot_->canvas()); pan_->setEnabled(false); } const std::string & PlotWidget::title() const { return title_; } void PlotWidget::setup_xaxis(const std::string & legend, const mc_rtc::gui::plot::Range & range) { if(legend.size()) { plot_->setAxisTitle(QwtPlot::xBottom, QwtText(legend.c_str())); } xRange_ = range; } void PlotWidget::setup_yaxis_left(const std::string & legend, const mc_rtc::gui::plot::Range & range) { if(legend.size()) { plot_->setAxisTitle(QwtPlot::yLeft, QwtText(legend.c_str())); } yLeftRange_ = range; } void PlotWidget::setup_yaxis_right(const std::string & legend, const mc_rtc::gui::plot::Range & range) { if(legend.size()) { plot_->setAxisTitle(QwtPlot::yRight, QwtText(legend.c_str())); } yRightRange_ = range; } void PlotWidget::plot(uint64_t id, const std::string & legend, double x, double y, mc_rtc::gui::Color color, mc_rtc::gui::plot::Style style, mc_rtc::gui::plot::Side side) { if(!curves_.count(id)) { curves_[id] = Curve(plot_, legend, side); } update(side, curves_[id].update(x, y, color, style, line_width_)); } void PlotWidget::plot(uint64_t id, const std::string & legend, const PolygonDescription & polygon, mc_rtc::gui::plot::Side side) { if(!polygons_.count(id)) { polygons_[id] = Polygon(plot_, legend, side); } update(side, polygons_[id].update(polygon)); } void PlotWidget::plot(uint64_t id, const std::string & legend, const std::vector<PolygonDescription> & polygons, mc_rtc::gui::plot::Side side) { if(!polygonsVectors_.count(id)) { polygonsVectors_[id] = PolygonsVector(plot_, legend, side); } update(side, polygonsVectors_[id].update(polygons)); } void PlotWidget::update(Side side, QRectF rect) { if(side == Side::Left) { if(!has_left_plot_) { has_left_plot_ = true; boundingRects_[side] = rect; } boundingRects_[side] = boundingRects_[side].united(rect); } else { if(!has_right_plot_) { has_right_plot_ = true; boundingRects_[side] = rect; } boundingRects_[side] = boundingRects_[side].united(rect); } } void PlotWidget::refresh() { if(paused_) { plot_->replot(); return; } if(!has_left_plot_) { plot_->enableAxis(QwtPlot::yLeft, false); } if(has_right_plot_) { plot_->enableAxis(QwtPlot::yRight); } auto inf = mc_rtc::gui::plot::Range::inf; auto setScale = [this, inf](int id, const mc_rtc::gui::plot::Range & range, double min, double max, bool limit) { min = range.min != -inf ? range.min : min; max = range.max != inf ? range.max : max; if(min == inf) { min = 0; max = 1; } if(min == max) { max = min + 0.1; } double r = max - min; if(limit && r > show_duration_) { min = max - show_duration_; } plot_->setAxisScale(id, min, max); }; auto & yLRect = boundingRects_[Side::Left]; auto & yRRect = boundingRects_[Side::Right]; auto xRect = yLRect.united(yRRect); if(has_left_plot_ && !has_right_plot_) { xRect = yLRect; } if(has_right_plot_ && !has_left_plot_) { xRect = yRRect; } setScale(QwtPlot::xBottom, xRange_, xRect.left(), xRect.right(), limit_xrange_); setScale(QwtPlot::yLeft, yLeftRange_, yLRect.top(), yLRect.bottom(), false); setScale(QwtPlot::yRight, yRightRange_, yRRect.top(), yRRect.bottom(), false); plot_->replot(); } void PlotWidget::limit_xrange_cbox_changed(int state) { limit_xrange_ = (state == Qt::Checked); } void PlotWidget::show_duration_changed(double value) { show_duration_ = value; } void PlotWidget::pause_button_clicked() { paused_ = !paused_; if(paused_) { pause_button_->setChecked(false); pause_button_->setIcon(style()->standardIcon(QStyle::SP_MediaPlay)); controls_widget_->setVisible(true); zoom_->setZoomBase(true); } else { pause_button_->setChecked(true); pause_button_->setIcon(style()->standardIcon(QStyle::SP_MediaPause)); controls_widget_->setVisible(false); } } void PlotWidget::zoom_button_clicked() { if(zoom_button_->isChecked()) { pan_->setEnabled(false); pan_button_->setChecked(false); zoom_->setEnabled(true); } else { zoom_->setEnabled(false); } } void PlotWidget::zoom_reset_button_clicked() { zoom_->zoom(0); } void PlotWidget::zoom_prev_button_clicked() { zoom_->zoom(-1); } void PlotWidget::zoom_next_button_clicked() { zoom_->zoom(1); } void PlotWidget::pan_button_clicked() { if(pan_button_->isChecked()) { zoom_->setEnabled(false); zoom_button_->setChecked(false); pan_->setEnabled(true); } else { pan_->setEnabled(false); } } void PlotWidget::save_button_clicked() { QwtPlotRenderer renderer(this); renderer.exportTo(plot_, (title_ + ".svg").c_str()); } void PlotWidget::toggle_options_widget() { options_widget_->setVisible(!options_widget_->isVisible()); if(options_widget_->isVisible()) { options_button_->setText("Less"); } else { options_button_->setText("More"); } } void PlotWidget::line_width_changed(double width) { line_width_ = width; } } // namespace mc_rtc_rviz
25.015949
116
0.658145
mmurooka
d9f9fd1eb20c152228eb50c6306f2dfad2bc4816
1,102
cpp
C++
ihm/src/sationsmeteo.cpp
etiennelndr/ihm_voilierautonome
8859c634a435fcbbe05093e38fc2ae345288a6f1
[ "MIT" ]
null
null
null
ihm/src/sationsmeteo.cpp
etiennelndr/ihm_voilierautonome
8859c634a435fcbbe05093e38fc2ae345288a6f1
[ "MIT" ]
null
null
null
ihm/src/sationsmeteo.cpp
etiennelndr/ihm_voilierautonome
8859c634a435fcbbe05093e38fc2ae345288a6f1
[ "MIT" ]
2
2018-09-26T13:14:02.000Z
2018-10-23T13:51:25.000Z
#include "sationsmeteo.h" #include "ui_sationsmeteo.h" #include "mainwindow.h" /** * CONSTRUCTOR * * @brief StationsMeteo::StationsMeteo : TODO * @param parent */ StationsMeteo::StationsMeteo(QWidget *parent) : QDialog(parent), ui(new Ui::StationsMeteo) { ui->setupUi(this); } /** * DESTRUCTOR * * @brief StationsMeteo::~StationsMeteo : TODO */ StationsMeteo::~StationsMeteo() { delete ui; } /** * SLOT -> TODO * * @brief StationsMeteo::on_pushButton_clicked : TODO */ void StationsMeteo::on_pushButton_clicked() { this->close(); int spin1 = ui->SpinMeteo->value(); StationsMeteo2* stationsmeteo2 = new StationsMeteo2(this,spin1); //------- Afficher une nouvelle page concernant les coordonees de chaque stations (Longitude/Latitude/Id) stationsmeteo2->setModal(true); stationsmeteo2->show(); connect(stationsmeteo2, SIGNAL(new_meteo(Meteo)), this, SLOT(transfer_new_meteo(Meteo))); } /** * SLOT -> TODO * * @brief StationsMeteo::transfer_new_meteo : TODO * @param m */ void StationsMeteo::transfer_new_meteo(Meteo m){ emit new_meteo(m); }
22.958333
109
0.693285
etiennelndr
d9fa341332c3fe9081905474b42b48e22e5b3d8d
1,440
cpp
C++
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
// make sure you include your own header file with the righ name . // make sure you implement the methods using the same signature as the assignment #include <iostream> #include "dlist.h" #include "dlist.cpp" using namespace std; int main(int argc, char* argv[]) { DList queue; initializeDList(queue); //insert 5 values for (int i = 1; i <= 5; i++) { cout << "put: " << 10 * i << endl; put(queue, 10 * i); } cout<<"______________________________________________________________________________"<<endl; //remove 3 values and print them to console for (int j = 1; j <= 3; j++) { int value; if (get(queue, value)) cout << " get: " << value << endl; } cout<<""<<endl; cout << "Length: " << dlistLength(queue) << endl; cout<<"______________________________________________________________________________"<<endl; //insert 5 values for (int i = 6; i <= 10; i++) { cout << "put: " << 10 * i << endl; put(queue, 10 * i); } cout<<""<<endl; cout << "Length: " << dlistLength(queue) << endl; cout<<"______________________________________________________________________________"<<endl; //remove all values and print them while(!isEmpty(queue)) { int value; get(queue, value); cout << " get: " << value << endl; } cout<<"______________________________________________________________________________"<<endl; cin.sync(); cin.get(); return 0; }
26.666667
97
0.647222
John-Ghaly88
d9fd9a2e05f7dfc05a1523451347f594e202ba1b
1,617
cpp
C++
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
#include <iostream> #include <limits> #include "Halide.h" #include "halide_benchmark.h" #define WIDTH 65536 #define USE_AUTO using namespace Halide; using namespace Halide::Tools; class PipelineClass { public: Func output; Buffer<int> input; PipelineClass(Buffer<int> in) : input(in) { // Parallel reduction: summation output() = 0; RDom r(0, WIDTH); output() = output() + input(r.x); } bool test_performance() { target = get_host_target(); target.set_feature(Target::CUDA); if (!target.has_gpu_feature()) { return false; } #ifdef USE_AUTO Pipeline p(output); p.auto_schedule(target); output.compile_jit(target); printf("Using auto-scheduler...\n"); #else output.compute_root(); output.compile_jit(target); printf("Computing from root...\n"); #endif // The equivalent C is: int c_ref = 0; for (int y = 0; y < WIDTH; y++) { c_ref += input(y); } input.copy_to_device(target); double best_time = benchmark(10, 5, [&]() { Buffer<int> out = output.realize(); out.copy_to_host(); out.device_sync(); }); printf("Halide time (best): %gms\n", best_time * 1e3); return true; } private: Var x; Target target; }; int main(int argc, char **argv) { const int width = WIDTH; // Initialize with random data Buffer<int> input(width); for (int x = 0; x < input.width(); x++) { input(x) = rand() & 0xfff; } printf("Running Halide pipeline...\n"); PipelineClass pipe(input); if (!pipe.test_performance()) { printf("Scheduling failed\n"); } return 0; }
19.719512
58
0.619048
qiao-bo
d9ffa7a99ce2696459ad8e7b2b4f86b83c223b6d
438
cpp
C++
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#include "RandomWord.h" #include "RWord.h" #include <cstdlib> const char* CGL::getRandomWord() { // Word is null at begining const char* word = nullptr; // Get random value CGL_internal::RWord* ptrWord = CGL_internal::RWord::get(); if (ptrWord) { // Compute random value unsigned int randomValue = rand() % ptrWord->getWordCount(); // Load word word = ptrWord->getWord(randomValue); } // Return word return word; }
17.52
62
0.678082
imgui-works
8a015aaf02070aa5ab41f54da4b423aceab25dd1
1,018
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; using namespace System::Collections; void PrintValues( IEnumerable^ myList ); int main() { // Creates and initializes a new ArrayList. ArrayList^ myAL = gcnew ArrayList; myAL->Add( "Hello" ); myAL->Add( "World" ); myAL->Add( "!" ); // Displays the properties and values of the ArrayList. Console::WriteLine( "myAL" ); Console::WriteLine( " Count: {0}", myAL->Count ); Console::WriteLine( " Capacity: {0}", myAL->Capacity ); Console::Write( " Values:" ); PrintValues( myAL ); } void PrintValues( IEnumerable^ myList ) { IEnumerator^ myEnum = myList->GetEnumerator(); while ( myEnum->MoveNext() ) { Object^ obj = safe_cast<Object^>(myEnum->Current); Console::Write( " {0}", obj ); } Console::WriteLine(); } /* This code produces output similar to the following: myAL Count: 3 Capacity: 4 Values: Hello World ! */ // </Snippet1>
22.622222
62
0.586444
hamarb123
8a06805a3233bdb9a497400bef9eae588661a939
7,956
cc
C++
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
7
2020-10-11T08:23:42.000Z
2022-03-03T10:23:55.000Z
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
null
null
null
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
1
2020-06-17T21:03:46.000Z
2020-06-17T21:03:46.000Z
#include <stdexcept> #include "cspace.hh" #include "fmt/format.h" #include "predicate.hh" #include "predicate-impl.hh" constexpr char TRACEBACK_NAME[] = "err_func"; static int traceback(lua_State* L) { // 'message' not a string? if (!lua_isstring(L, 1)) { return 1; // Keep it intact } lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); // Pass error message lua_pushinteger(L, 2); // Skip this function and traceback lua_call(L, 2, 1); // Call debug.traceback return 1; } static int wrap_exceptions(lua_State* L, lua_CFunction f) { try { return f(L); // Call wrapped function and return result. } catch (const char* s) { // Catch and convert exceptions. lua_pushstring(L, s); } catch (std::exception& e) { lua_pushstring(L, e.what()); } catch (...) { lua_pushliteral(L, "caught (...)"); } return lua_error(L); // Rethrow as a Lua error. } namespace symbolic::predicate { const structures::object::ObjectSet* objects = nullptr; const structures::object::ObjectSet* obstacles = nullptr; namespace cspace = planner::cspace; namespace { void load_c_fns(lua_State* L) { lua_pushcfunction(L, traceback); lua_setglobal(L, TRACEBACK_NAME); #ifdef DEBUG_LUA lua_pushlightuserdata(L, reinterpret_cast<void*>(wrap_exceptions)); luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); lua_pop(L, 1); #endif load_metatables(L); load_math_lib(L); } } // namespace bool LuaEnv<bool>::call(const spec::Formula& formula, const Map<Str, Str>& bindings, structures::scenegraph::Graph* const sg, const ob::State* const state, const ob::StateSpace* const space, const bool base_movable) { setup_world<double>(formula, bindings, sg); Transform3r base_tf; const auto& state_vec = generate_state_vector(space, state, base_movable); const double* const cont_vals = &(*state_vec.begin()) + (base_movable ? 4 : 0); const double* const joint_vals = cont_vals + planner::cspace::cont_joint_idxs.size(); if (base_movable) { make_base_tf(state_vec, base_tf); } sg->update_transforms(cont_vals, joint_vals, base_tf, [&](const structures::scenegraph::Node* const node, const bool new_value, const Transform3r& pose, const Transform3r& coll_pose) { update_object(node->name, pose); }); const bool result = call_formula<bool>(formula); teardown_world(formula); return result; } Vec<double> generate_state_vector(const ob::StateSpace* const space, const ob::State* const state, const bool base_movable) { // The state vector has the form [robot base pose (if it exists), continuous joints, other // joints] Vec<double> result(cspace::num_dims); // Separate out the state spaces for dimension and index information auto full_space = space->as<ob::CompoundStateSpace>(); auto robot_space = full_space->getSubspace(cspace::ROBOT_SPACE)->as<ob::CompoundStateSpace>(); const auto cstate = state->as<ob::CompoundState>(); const auto& robot_state = cstate->as<ob::CompoundState>(full_space->getSubspaceIndex(cspace::ROBOT_SPACE)); int offset = 0; if (base_movable) { auto robot_base_state = robot_state->as<cspace::RobotBaseSpace::StateType>( robot_space->getSubspaceIndex(cspace::BASE_SPACE)); // NOTE: This is only valid because we're only getting pose. Could be cleaner, too result[0] = robot_base_state->getX(); result[1] = robot_base_state->getY(); result[2] = robot_base_state->getZ(); const ob::SO2StateSpace::StateType& base_rotation = robot_base_state->rotation(); result[3] = base_rotation.value; offset += 4; } const auto& joint_state = robot_state->as<cspace::RobotJointSpace::StateType>( robot_space->getSubspaceIndex(cspace::JOINT_SPACE)); for (size_t i = 0; i < cspace::cont_joint_idxs.size(); ++i) { const auto idx = cspace::cont_joint_idxs[i]; result[offset + i] = robot_state->as<ob::SO2StateSpace::StateType>(idx)->value; } offset += cspace::cont_joint_idxs.size(); for (size_t i = 0; i < cspace::joint_bounds.size(); ++i) { result[offset + i] = joint_state->values[i]; } return result; } LuaEnvData::LuaEnvData(const Str& name, const Str& prelude_filename) : name(name) { log = spdlog::stdout_color_st(fmt::format("lua-{}", name)); L = luaL_newstate(); luaL_openlibs(L); load_c_fns(L); if (!prelude_filename.empty()) { log->debug("Loading prelude from {}", prelude_filename); if (luaL_dofile(L, prelude_filename.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading prelude from {} failed: {}", prelude_filename, err_msg); throw std::runtime_error("Failed to load Lua prelude!"); } } } bool LuaEnvData::load_predicates(const Str& predicates_filename) const { log->debug("Loading predicates from {}", predicates_filename); if (luaL_dofile(L, predicates_filename.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading predicates from {} failed: {}", predicates_filename, err_msg); throw std::runtime_error( fmt::format("Failed to load predicates from {}: {}", predicates_filename, err_msg)); } return true; } bool LuaEnvData::load_formula(spec::Formula* formula) const { log->debug("Loading formula: {}", formula->name); if (luaL_dostring(L, formula->normal_def.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading formula {} failed: {}", formula->name, err_msg); throw std::runtime_error(fmt::format("Failed to load formula {}: {}", formula->name, err_msg)); } lua_getglobal(L, formula->normal_fn_name.c_str()); formula->normal_fn[name] = luaL_ref(L, LUA_REGISTRYINDEX); return true; } void LuaEnvData::teardown_world(const spec::Formula& formula) const { // NOTE: If we for some reason stop making one object/binding (e.g. if there's something weird // with globals), then this is wrong and will cause segfaults lua_pop(L, formula.bindings.size()); } void LuaEnvData::cleanup() const { lua_gc(L, LUA_GCCOLLECT, 0); } int LuaEnvData::call_helper(const spec::Formula& formula, const int start_top) const { init_dn_block(); clear_dn_block(); // Push traceback lua_getglobal(L, TRACEBACK_NAME); const int err_func_idx = lua_gettop(L); // Retrieve the formula function ref - use at() to maintain constness lua_rawgeti(L, LUA_REGISTRYINDEX, formula.normal_fn.at(name)); // Copy the object tables as arguments for (size_t i = 0; i < binding_idx.size(); ++i) { lua_pushvalue(L, start_top - i); } // Call the function ref if (lua_pcall(L, binding_idx.size(), 1, err_func_idx) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Error calling {} for gradient: {}", formula.name, err_msg); int top_idx = lua_gettop(L); lua_pop(L, top_idx - err_func_idx + 1); throw std::runtime_error( fmt::format("Failed to call {} for gradient: {}", formula.name, err_msg)); } return err_func_idx; } void LuaEnvData::cleanup_helper(const int start_top, const int err_func_idx) const { // Pop cruft from the stack: the result table, a, v, err_func int top_idx = lua_gettop(L); lua_pop(L, top_idx - err_func_idx + 1); const auto end_top = lua_gettop(L); if (end_top != start_top) { log->error("Top grew from {} to {}", start_top, end_top); } } } // namespace symbolic::predicate
34.742358
99
0.651081
MiaoDragon
8a09851a7b473719a50e82b7a9cf3d0434812506
594
cpp
C++
ntuj/0163.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0163.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0163.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> #include<algorithm> int calc(int s[]) { int i,sum=0; for(i=1;i<4;i++) sum+=(s[i-1]-s[i])*(s[i-1]-s[i]); return sum; } main() { int i,j,a,b,min,s[6]; while(scanf("%d %d",&a,&b)==2 && a+b) { min=2147483647; for(i=1;i*i<=a;i++) if(a%i==0)for(j=1;j*j<=b;j++) { if(b%j)continue; s[0]=i; s[1]=a/i; s[2]=j; s[3]=b/j; std::sort(s,s+4); min<?=calc(s); } printf("%d\n",min); } }
19.8
41
0.340067
dk00
8a0b091ef9904d3ef700368612e82e5e3199c856
338
cpp
C++
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
44
2017-11-08T14:20:55.000Z
2021-03-18T14:22:52.000Z
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
null
null
null
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
19
2017-08-01T12:59:29.000Z
2021-04-11T08:09:59.000Z
#define _CRT_SECURE_NO_WARNINGS #include "Student.h" static void HelperFunc() { printf("main helper"); } int main() { //class (type) a object (instance) Student a("John"); a.print(); a.print(); a.print(); printf("=== Program Ended ===\n"); printf("Press any to key to Exit !"); _getch(); return 0; }
15.363636
39
0.585799
Jasonchan35
8a0b77669764613a4b62200578dc3e8743268d0d
168,987
cpp
C++
code_reading/oceanbase-master/src/share/schema/ob_schema_mgr.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/share/schema/ob_schema_mgr.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/share/schema/ob_schema_mgr.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SHARE_SCHEMA #include "ob_schema_mgr.h" #include "lib/oblog/ob_log.h" #include "share/schema/ob_schema_utils.h" #include "lib/utility/ob_hang_fatal_error.h" #include "share/schema/ob_schema_getter_guard.h" #include "share/ob_get_compat_mode.h" #include "observer/ob_server_struct.h" #include "rootserver/ob_root_utils.h" namespace oceanbase { using namespace common; using namespace common::hash; namespace share { namespace schema { ObSimpleTenantSchema::ObSimpleTenantSchema() : ObSchema() { reset(); } ObSimpleTenantSchema::ObSimpleTenantSchema(ObIAllocator* allocator) : ObSchema(allocator) { reset(); } ObSimpleTenantSchema::ObSimpleTenantSchema(const ObSimpleTenantSchema& other) : ObSchema() { reset(); *this = other; } ObSimpleTenantSchema::~ObSimpleTenantSchema() {} ObSimpleTenantSchema& ObSimpleTenantSchema::operator=(const ObSimpleTenantSchema& other) { if (this != &other) { reset(); int ret = OB_SUCCESS; error_ret_ = other.error_ret_; tenant_id_ = other.tenant_id_; schema_version_ = other.schema_version_; name_case_mode_ = other.name_case_mode_; read_only_ = other.read_only_; compatibility_mode_ = other.compatibility_mode_; gmt_modified_ = other.gmt_modified_; drop_tenant_time_ = other.drop_tenant_time_; status_ = other.status_; in_recyclebin_ = other.in_recyclebin_; if (OB_FAIL(deep_copy_str(other.tenant_name_, tenant_name_))) { LOG_WARN("Fail to deep copy tenant_name", K(ret)); } else if (OB_FAIL(deep_copy_str(other.primary_zone_, primary_zone_))) { LOG_WARN("Fail to deep copy primary_zone", K(ret)); } else if (OB_FAIL(deep_copy_str(other.locality_, locality_))) { LOG_WARN("Fail to deep copy locality", K(ret)); } else if (OB_FAIL(deep_copy_str(other.previous_locality_, previous_locality_))) { LOG_WARN("Fail to deep copy previous_locality", K(ret)); } if (OB_FAIL(ret)) { error_ret_ = ret; } } return *this; } bool ObSimpleTenantSchema::operator==(const ObSimpleTenantSchema& other) const { bool ret = false; if (tenant_id_ == other.tenant_id_ && schema_version_ == other.schema_version_ && tenant_name_ == other.tenant_name_ && name_case_mode_ == other.name_case_mode_ && read_only_ == other.read_only_ && primary_zone_ == other.primary_zone_ && locality_ == other.locality_ && previous_locality_ == other.previous_locality_ && compatibility_mode_ == other.compatibility_mode_ && gmt_modified_ == other.gmt_modified_ && drop_tenant_time_ == other.drop_tenant_time_ && status_ == other.status_ && in_recyclebin_ == other.in_recyclebin_) { ret = true; } return ret; } void ObSimpleTenantSchema::reset() { ObSchema::reset(); tenant_id_ = OB_INVALID_ID; schema_version_ = OB_INVALID_VERSION; tenant_name_.reset(); name_case_mode_ = OB_NAME_CASE_INVALID; read_only_ = false; primary_zone_.reset(); locality_.reset(); previous_locality_.reset(); compatibility_mode_ = ObCompatibilityMode::OCEANBASE_MODE; gmt_modified_ = 0; drop_tenant_time_ = 0; status_ = TENANT_STATUS_NORMAL; in_recyclebin_ = false; } bool ObSimpleTenantSchema::is_valid() const { bool ret = true; if (OB_INVALID_ID == tenant_id_ || schema_version_ < 0 || tenant_name_.empty()) { ret = false; } return ret; } int64_t ObSimpleTenantSchema::get_convert_size() const { int64_t convert_size = 0; convert_size += sizeof(ObSimpleTenantSchema); convert_size += tenant_name_.length() + 1; convert_size += primary_zone_.length() + 1; convert_size += locality_.length() + 1; convert_size += previous_locality_.length() + 1; return convert_size; } ObSimpleUserSchema::ObSimpleUserSchema() : ObSchema() { reset(); } ObSimpleUserSchema::ObSimpleUserSchema(ObIAllocator* allocator) : ObSchema(allocator) { reset(); } ObSimpleUserSchema::ObSimpleUserSchema(const ObSimpleUserSchema& other) : ObSchema() { reset(); *this = other; } ObSimpleUserSchema::~ObSimpleUserSchema() {} ObSimpleUserSchema& ObSimpleUserSchema::operator=(const ObSimpleUserSchema& other) { if (this != &other) { reset(); int ret = OB_SUCCESS; error_ret_ = other.error_ret_; tenant_id_ = other.tenant_id_; user_id_ = other.user_id_; type_ = other.type_; schema_version_ = other.schema_version_; if (OB_FAIL(deep_copy_str(other.user_name_, user_name_))) { LOG_WARN("Fail to deep copy user_name", K(ret)); } else if (OB_FAIL(deep_copy_str(other.host_name_, host_name_))) { LOG_WARN("Fail to deep copy host_name", K(ret)); } if (OB_FAIL(ret)) { error_ret_ = ret; } } return *this; } bool ObSimpleUserSchema::operator==(const ObSimpleUserSchema& other) const { bool ret = false; if (tenant_id_ == other.tenant_id_ && user_id_ == other.user_id_ && schema_version_ == other.schema_version_ && user_name_ == other.user_name_ && host_name_ == other.host_name_ && type_ == other.type_) { ret = true; } return ret; } void ObSimpleUserSchema::reset() { ObSchema::reset(); tenant_id_ = OB_INVALID_ID; user_id_ = OB_INVALID_ID; schema_version_ = OB_INVALID_VERSION; user_name_.reset(); host_name_.reset(); type_ = OB_USER; } bool ObSimpleUserSchema::is_valid() const { bool ret = true; if (OB_INVALID_ID == tenant_id_ || OB_INVALID_ID == user_id_ || schema_version_ < 0) { ret = false; } return ret; } int64_t ObSimpleUserSchema::get_convert_size() const { int64_t convert_size = 0; convert_size += sizeof(ObSimpleUserSchema); convert_size += user_name_.length() + host_name_.length() + 2; return convert_size; } ObSimpleDatabaseSchema::ObSimpleDatabaseSchema() : ObSchema() { reset(); } ObSimpleDatabaseSchema::ObSimpleDatabaseSchema(ObIAllocator* allocator) : ObSchema(allocator) { reset(); } ObSimpleDatabaseSchema::ObSimpleDatabaseSchema(const ObSimpleDatabaseSchema& other) : ObSchema() { reset(); *this = other; } ObSimpleDatabaseSchema::~ObSimpleDatabaseSchema() {} ObSimpleDatabaseSchema& ObSimpleDatabaseSchema::operator=(const ObSimpleDatabaseSchema& other) { if (this != &other) { reset(); int ret = OB_SUCCESS; error_ret_ = other.error_ret_; tenant_id_ = other.tenant_id_; database_id_ = other.database_id_; schema_version_ = other.schema_version_; default_tablegroup_id_ = other.default_tablegroup_id_; name_case_mode_ = other.name_case_mode_; drop_schema_version_ = other.drop_schema_version_; if (OB_FAIL(deep_copy_str(other.database_name_, database_name_))) { LOG_WARN("Fail to deep copy database_name", K(ret)); } if (OB_FAIL(ret)) { error_ret_ = ret; } } return *this; } bool ObSimpleDatabaseSchema::operator==(const ObSimpleDatabaseSchema& other) const { bool ret = false; if (tenant_id_ == other.tenant_id_ && database_id_ == other.database_id_ && schema_version_ == other.schema_version_ && default_tablegroup_id_ == other.default_tablegroup_id_ && database_name_ == other.database_name_ && name_case_mode_ == other.name_case_mode_ && drop_schema_version_ == other.drop_schema_version_) { ret = true; } return ret; } void ObSimpleDatabaseSchema::reset() { ObSchema::reset(); tenant_id_ = OB_INVALID_ID; database_id_ = OB_INVALID_ID; schema_version_ = OB_INVALID_VERSION; default_tablegroup_id_ = OB_INVALID_ID; database_name_.reset(); name_case_mode_ = OB_NAME_CASE_INVALID; drop_schema_version_ = OB_INVALID_VERSION; } bool ObSimpleDatabaseSchema::is_valid() const { bool ret = true; if (OB_INVALID_ID == tenant_id_ || OB_INVALID_ID == database_id_ || schema_version_ < 0 || database_name_.empty()) { ret = false; } return ret; } int64_t ObSimpleDatabaseSchema::get_convert_size() const { int64_t convert_size = 0; convert_size += sizeof(ObSimpleDatabaseSchema); convert_size += database_name_.length() + 1; return convert_size; } ObSimpleTablegroupSchema::ObSimpleTablegroupSchema() : ObSchema() { reset(); } ObSimpleTablegroupSchema::ObSimpleTablegroupSchema(ObIAllocator* allocator) : ObSchema(allocator) { reset(); } ObSimpleTablegroupSchema::ObSimpleTablegroupSchema(const ObSimpleTablegroupSchema& other) : ObSchema() { reset(); *this = other; } ObSimpleTablegroupSchema::~ObSimpleTablegroupSchema() {} ObSimpleTablegroupSchema& ObSimpleTablegroupSchema::operator=(const ObSimpleTablegroupSchema& other) { if (this != &other) { reset(); int ret = OB_SUCCESS; error_ret_ = other.error_ret_; tenant_id_ = other.tenant_id_; tablegroup_id_ = other.tablegroup_id_; schema_version_ = other.schema_version_; partition_status_ = other.partition_status_; binding_ = other.binding_; is_mock_global_index_invalid_ = other.is_mock_global_index_invalid_; partition_schema_version_ = other.partition_schema_version_; if (OB_FAIL(deep_copy_str(other.tablegroup_name_, tablegroup_name_))) { LOG_WARN("Fail to deep copy tablegroup_name", K(ret)); } else if (OB_FAIL(deep_copy_str(other.primary_zone_, primary_zone_))) { LOG_WARN("Fail to deep copy primary_zone", K(ret)); } else if (OB_FAIL(deep_copy_str(other.locality_, locality_))) { LOG_WARN("Fail to deep copy locality", K(ret)); } else if (OB_FAIL(deep_copy_str(other.previous_locality_, previous_locality_))) { LOG_WARN("Fail to deep copy previous_locality", K(ret)); } if (OB_FAIL(ret)) { error_ret_ = ret; } } return *this; } bool ObSimpleTablegroupSchema::operator==(const ObSimpleTablegroupSchema& other) const { bool ret = false; if (tenant_id_ == other.tenant_id_ && tablegroup_id_ == other.tablegroup_id_ && schema_version_ == other.schema_version_ && tablegroup_name_ == other.tablegroup_name_ && primary_zone_ == other.primary_zone_ && locality_ == other.locality_ && previous_locality_ == other.previous_locality_ && binding_ == other.binding_ && partition_status_ == other.partition_status_ && is_mock_global_index_invalid_ == other.is_mock_global_index_invalid_ && partition_schema_version_ == other.partition_schema_version_) { ret = true; } return ret; } void ObSimpleTablegroupSchema::reset() { ObSchema::reset(); tenant_id_ = OB_INVALID_ID; tablegroup_id_ = OB_INVALID_ID; schema_version_ = OB_INVALID_VERSION; tablegroup_name_.reset(); primary_zone_.reset(); locality_.reset(); previous_locality_.reset(); partition_status_ = PARTITION_STATUS_ACTIVE; is_mock_global_index_invalid_ = false; binding_ = false; partition_schema_version_ = 0; // Issues left over from history, set to 0 } bool ObSimpleTablegroupSchema::is_valid() const { bool ret = true; if (OB_INVALID_ID == tenant_id_ || OB_INVALID_ID == tablegroup_id_ || schema_version_ < 0 || tablegroup_name_.empty()) { ret = false; } return ret; } int64_t ObSimpleTablegroupSchema::get_convert_size() const { int64_t convert_size = 0; convert_size += sizeof(ObSimpleTablegroupSchema); convert_size += tablegroup_name_.length() + 1; convert_size += primary_zone_.length() + 1; convert_size += locality_.length() + 1; convert_size += previous_locality_.length() + 1; return convert_size; } int ObSimpleTablegroupSchema::get_zone_list( share::schema::ObSchemaGetterGuard& schema_guard, common::ObIArray<common::ObZone>& zone_list) const { int ret = OB_SUCCESS; if (!locality_.empty()) { ObString locality = locality_; if (OB_FAIL(rootserver::ObLocalityUtil::parse_zone_list_from_locality_str(locality, zone_list))) { LOG_WARN("fail to parse zone list", K(ret), K(locality)); } } else { const ObTenantSchema* tenant_schema = NULL; zone_list.reset(); if (OB_FAIL(schema_guard.get_tenant_info(get_tenant_id(), tenant_schema))) { LOG_WARN("fail to get tenant schema", K(ret), K(tablegroup_id_), K(tenant_id_)); } else if (OB_UNLIKELY(NULL == tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("tenant schema null", K(ret), K(tablegroup_id_), K(tenant_id_), KP(tenant_schema)); } else if (OB_FAIL(tenant_schema->get_zone_list(zone_list))) { LOG_WARN("fail to get zone list", K(ret)); } else { } // no more to do } return ret; } //////////////////////////////////////////////////////////////// ObSchemaMgr::ObSchemaMgr() : local_allocator_(ObModIds::OB_SCHEMA_GETTER_GUARD), allocator_(local_allocator_), schema_version_(OB_INVALID_VERSION), tenant_infos_(0, NULL, ObModIds::OB_SCHEMA_TENANT_INFO_VEC), user_infos_(0, NULL, ObModIds::OB_SCHEMA_USER_INFO_VEC), database_infos_(0, NULL, ObModIds::OB_SCHEMA_DB_INFO_VEC), database_name_map_(ObModIds::OB_SCHEMA_DATABASE_NAME_MAP), tablegroup_infos_(0, NULL, ObModIds::OB_SCHEMA_TABLEG_INFO_VEC), table_infos_(0, NULL, ObModIds::OB_SCHEMA_TABLE_INFO_VEC), index_infos_(0, NULL, ObModIds::OB_SCHEMA_INDEX_INFO_VEC), table_id_map_(ObModIds::OB_SCHEMA_TABLE_ID_MAP), table_name_map_(ObModIds::OB_SCHEMA_TABLE_NAME_MAP), index_name_map_(ObModIds::OB_SCHEMA_INDEX_NAME_MAP), outline_mgr_(allocator_), priv_mgr_(allocator_), synonym_mgr_(allocator_), udf_mgr_(allocator_), sequence_mgr_(allocator_), profile_mgr_(allocator_), foreign_key_name_map_(ObModIds::OB_SCHEMA_FOREIGN_KEY_NAME_MAP), constraint_name_map_(ObModIds::OB_SCHEMA_CONSTRAINT_NAME_MAP), sys_variable_mgr_(allocator_), tenant_id_(OB_INVALID_TENANT_ID), drop_tenant_infos_(0, NULL, ObModIds::OB_SCHEMA_DROP_TENANT_INFO_VEC), is_consistent_(true), delay_deleted_table_map_("DelayDelTbls"), delay_deleted_database_map_("DelayDelDbs"), dblink_mgr_(allocator_) {} ObSchemaMgr::ObSchemaMgr(ObIAllocator& allocator) : local_allocator_(ObModIds::OB_SCHEMA_GETTER_GUARD), allocator_(allocator), schema_version_(OB_INVALID_VERSION), tenant_infos_(0, NULL, ObModIds::OB_SCHEMA_TENANT_INFO_VEC), user_infos_(0, NULL, ObModIds::OB_SCHEMA_TENANT_INFO_VEC), database_infos_(0, NULL, ObModIds::OB_SCHEMA_DB_INFO_VEC), database_name_map_(ObModIds::OB_SCHEMA_DATABASE_NAME_MAP), tablegroup_infos_(0, NULL, ObModIds::OB_SCHEMA_TABLEG_INFO_VEC), table_infos_(0, NULL, ObModIds::OB_SCHEMA_TABLE_INFO_VEC), index_infos_(0, NULL, ObModIds::OB_SCHEMA_INDEX_INFO_VEC), table_id_map_(ObModIds::OB_SCHEMA_TABLE_ID_MAP), table_name_map_(ObModIds::OB_SCHEMA_TABLE_NAME_MAP), index_name_map_(ObModIds::OB_SCHEMA_INDEX_NAME_MAP), outline_mgr_(allocator_), priv_mgr_(allocator_), synonym_mgr_(allocator_), sequence_mgr_(allocator_), profile_mgr_(allocator_), foreign_key_name_map_(ObModIds::OB_SCHEMA_FOREIGN_KEY_NAME_MAP), constraint_name_map_(ObModIds::OB_SCHEMA_CONSTRAINT_NAME_MAP), sys_variable_mgr_(allocator_), tenant_id_(OB_INVALID_TENANT_ID), drop_tenant_infos_(0, NULL, ObModIds::OB_SCHEMA_DROP_TENANT_INFO_VEC), is_consistent_(true), delay_deleted_table_map_("DelayDelTbls"), delay_deleted_database_map_("DelayDelDbs"), dblink_mgr_(allocator_) {} ObSchemaMgr::~ObSchemaMgr() {} int ObSchemaMgr::init(const uint64_t tenant_id) { int ret = OB_SUCCESS; if (OB_FAIL(database_name_map_.init())) { LOG_WARN("init database name map failed", K(ret)); } else if (OB_FAIL(table_id_map_.init())) { LOG_WARN("init table id map failed", K(ret)); } else if (OB_FAIL(table_name_map_.init())) { LOG_WARN("init table name map failed", K(ret)); } else if (OB_FAIL(index_name_map_.init())) { LOG_WARN("init index name map failed", K(ret)); } else if (OB_FAIL(foreign_key_name_map_.init())) { LOG_WARN("init foreign key name map failed", K(ret)); } else if (OB_FAIL(constraint_name_map_.init())) { LOG_WARN("init constraint name map failed", K(ret)); } else if (OB_FAIL(outline_mgr_.init())) { LOG_WARN("init outline mgr failed", K(ret)); } else if (OB_FAIL(priv_mgr_.init())) { LOG_WARN("init priv mgr failed", K(ret)); } else if (OB_FAIL(synonym_mgr_.init())) { LOG_WARN("init synonym mgr failed", K(ret)); } else if (OB_FAIL(udf_mgr_.init())) { LOG_WARN("init udf mgr failed", K(ret)); } else if (OB_FAIL(sequence_mgr_.init())) { LOG_WARN("init sequence mgr failed", K(ret)); } else if (OB_FAIL(profile_mgr_.init())) { LOG_WARN("init profile mgr failed", K(ret)); } else if (OB_FAIL(sys_variable_mgr_.init())) { LOG_WARN("init sys variable mgr failed", K(ret)); } else if (OB_FAIL(dblink_mgr_.init())) { LOG_WARN("init dblink mgr failed", K(ret)); } else { tenant_id_ = tenant_id; } return ret; } void ObSchemaMgr::reset() { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_version_ = OB_INVALID_VERSION; is_consistent_ = true; // reset will not free memory for vector tenant_infos_.clear(); user_infos_.clear(); database_infos_.clear(); tablegroup_infos_.clear(); table_infos_.clear(); index_infos_.clear(); drop_tenant_infos_.clear(); database_name_map_.clear(); table_id_map_.clear(); table_name_map_.clear(); index_name_map_.clear(); foreign_key_name_map_.clear(); constraint_name_map_.clear(); outline_mgr_.reset(); priv_mgr_.reset(); synonym_mgr_.reset(); udf_mgr_.reset(); sequence_mgr_.reset(); profile_mgr_.reset(); sys_variable_mgr_.reset(); dblink_mgr_.reset(); tenant_id_ = OB_INVALID_TENANT_ID; delay_deleted_table_map_.clear(); delay_deleted_database_map_.clear(); } } ObSchemaMgr& ObSchemaMgr::operator=(const ObSchemaMgr& other) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_FAIL(assign(other))) { LOG_WARN("assign failed", K(ret)); } return *this; } int ObSchemaMgr::assign(const ObSchemaMgr& other) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (this != &other) { reset(); schema_version_ = other.schema_version_; tenant_id_ = other.tenant_id_; is_consistent_ = other.is_consistent_; #define ASSIGN_FIELD(x) \ if (OB_SUCC(ret)) { \ if (OB_FAIL(x.assign(other.x))) { \ LOG_WARN("assign " #x "failed", K(ret)); \ } \ } ASSIGN_FIELD(tenant_infos_); // System variables need to be assigned first if (OB_SUCC(ret)) { if (OB_FAIL(sys_variable_mgr_.assign(other.sys_variable_mgr_))) { LOG_WARN("assign sys variable mgr failed", K(ret)); } } ASSIGN_FIELD(user_infos_); ASSIGN_FIELD(database_infos_); ASSIGN_FIELD(database_name_map_); ASSIGN_FIELD(tablegroup_infos_); ASSIGN_FIELD(table_infos_); ASSIGN_FIELD(index_infos_); ASSIGN_FIELD(drop_tenant_infos_); ASSIGN_FIELD(table_id_map_); ASSIGN_FIELD(table_name_map_); ASSIGN_FIELD(index_name_map_); ASSIGN_FIELD(foreign_key_name_map_); ASSIGN_FIELD(constraint_name_map_); ASSIGN_FIELD(delay_deleted_table_map_); ASSIGN_FIELD(delay_deleted_database_map_); #undef ASSIGN_FIELD if (OB_SUCC(ret)) { if (OB_FAIL(outline_mgr_.assign(other.outline_mgr_))) { LOG_WARN("assign outline mgr failed", K(ret)); } else if (OB_FAIL(priv_mgr_.assign(other.priv_mgr_))) { LOG_WARN("assign priv mgr failed", K(ret)); } else if (OB_FAIL(synonym_mgr_.assign(other.synonym_mgr_))) { LOG_WARN("assign synonym mgr failed", K(ret)); } else if (OB_FAIL(udf_mgr_.assign(other.udf_mgr_))) { LOG_WARN("assign udf mgr failed", K(ret)); } else if (OB_FAIL(sequence_mgr_.assign(other.sequence_mgr_))) { LOG_WARN("assign sequence mgr failed", K(ret)); } else if (OB_FAIL(profile_mgr_.assign(other.profile_mgr_))) { LOG_WARN("assign profile mgr failed", K(ret)); } else if (OB_FAIL(dblink_mgr_.assign(other.dblink_mgr_))) { LOG_WARN("assign dblink mgr failed", K(ret)); } } } return ret; } int ObSchemaMgr::deep_copy(const ObSchemaMgr& other) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (this != &other) { reset(); schema_version_ = other.schema_version_; tenant_id_ = other.tenant_id_; is_consistent_ = other.is_consistent_; #define ADD_SCHEMA(SCHEMA, SCHEMA_TYPE, SCHEMA_ITER) \ if (OB_SUCC(ret)) { \ for (SCHEMA_ITER iter = other.SCHEMA##_infos_.begin(); OB_SUCC(ret) && iter != other.SCHEMA##_infos_.end(); \ iter++) { \ const SCHEMA_TYPE* schema = *iter; \ if (OB_ISNULL(schema)) { \ ret = OB_ERR_UNEXPECTED; \ LOG_WARN("NULL ptr", K(schema)); \ } else if (OB_FAIL(add_##SCHEMA(*schema))) { \ LOG_WARN("add " #SCHEMA " failed", K(ret), K(*schema)); \ } \ } \ } ADD_SCHEMA(tenant, ObSimpleTenantSchema, ConstTenantIterator); // System variables need to be copied first if (OB_SUCC(ret)) { if (OB_FAIL(sys_variable_mgr_.deep_copy(other.sys_variable_mgr_))) { LOG_WARN("deep copy sys variable mgr failed", K(ret)); } } ADD_SCHEMA(user, ObSimpleUserSchema, ConstUserIterator); ADD_SCHEMA(database, ObSimpleDatabaseSchema, ConstDatabaseIterator); ADD_SCHEMA(tablegroup, ObSimpleTablegroupSchema, ConstTablegroupIterator); ADD_SCHEMA(table, ObSimpleTableSchemaV2, ConstTableIterator); #undef ADD_SCHEMA if (OB_SUCC(ret)) { if (OB_FAIL(outline_mgr_.deep_copy(other.outline_mgr_))) { LOG_WARN("deep copy outline mgr failed", K(ret)); } else if (OB_FAIL(priv_mgr_.deep_copy(other.priv_mgr_))) { LOG_WARN("deep copy priv mgr failed", K(ret)); } else if (OB_FAIL(synonym_mgr_.deep_copy(other.synonym_mgr_))) { LOG_WARN("deep copy synonym mgr failed", K(ret)); } else if (OB_FAIL(udf_mgr_.deep_copy(other.udf_mgr_))) { LOG_WARN("deep copy udf mgr failed", K(ret)); } else if (OB_FAIL(sequence_mgr_.deep_copy(other.sequence_mgr_))) { LOG_WARN("deep copy sequence mgr failed", K(ret)); } else if (OB_FAIL(profile_mgr_.deep_copy(other.profile_mgr_))) { LOG_WARN("deep copy profile mgr failed", K(ret)); } else if (OB_FAIL(dblink_mgr_.deep_copy(other.dblink_mgr_))) { LOG_WARN("deep copy dblink mgr failed", K(ret)); } } if (OB_SUCC(ret)) { for (ConstDropTenantInfoIterator iter = other.drop_tenant_infos_.begin(); OB_SUCC(ret) && iter != other.drop_tenant_infos_.end(); iter++) { const ObDropTenantInfo& drop_tenant_info = *(*iter); if (OB_FAIL(add_drop_tenant_info(drop_tenant_info))) { LOG_WARN("add drop tenant info failed", K(ret), K(drop_tenant_info)); } } } } return ret; } bool ObSchemaMgr::check_inner_stat() const { bool ret = true; return ret; } bool ObSchemaMgr::compare_tenant(const ObSimpleTenantSchema* lhs, const ObSimpleTenantSchema* rhs) { return lhs->get_tenant_id() < rhs->get_tenant_id(); } bool ObSchemaMgr::equal_tenant(const ObSimpleTenantSchema* lhs, const ObSimpleTenantSchema* rhs) { return lhs->get_tenant_id() == rhs->get_tenant_id(); } bool ObSchemaMgr::compare_with_tenant_id(const ObSimpleTenantSchema* lhs, const uint64_t tenant_id) { return NULL != lhs ? (lhs->get_tenant_id() < tenant_id) : false; } bool ObSchemaMgr::equal_with_tenant_id(const ObSimpleTenantSchema* lhs, const uint64_t tenant_id) { return NULL != lhs ? (lhs->get_tenant_id() == tenant_id) : false; } bool ObSchemaMgr::compare_user(const ObSimpleUserSchema* lhs, const ObSimpleUserSchema* rhs) { return lhs->get_tenant_user_id() < rhs->get_tenant_user_id(); } bool ObSchemaMgr::equal_user(const ObSimpleUserSchema* lhs, const ObSimpleUserSchema* rhs) { return lhs->get_tenant_user_id() == rhs->get_tenant_user_id(); } bool ObSchemaMgr::compare_with_tenant_user_id(const ObSimpleUserSchema* lhs, const ObTenantUserId& tenant_user_id) { return NULL != lhs ? (lhs->get_tenant_user_id() < tenant_user_id) : false; } bool ObSchemaMgr::equal_with_tenant_user_id(const ObSimpleUserSchema* lhs, const ObTenantUserId& tenant_user_id) { return NULL != lhs ? (lhs->get_tenant_user_id() == tenant_user_id) : false; } bool ObSchemaMgr::compare_database(const ObSimpleDatabaseSchema* lhs, const ObSimpleDatabaseSchema* rhs) { return lhs->get_tenant_database_id() < rhs->get_tenant_database_id(); } bool ObSchemaMgr::equal_database(const ObSimpleDatabaseSchema* lhs, const ObSimpleDatabaseSchema* rhs) { return lhs->get_tenant_database_id() == rhs->get_tenant_database_id(); } bool ObSchemaMgr::compare_with_tenant_database_id( const ObSimpleDatabaseSchema* lhs, const ObTenantDatabaseId& tenant_database_id) { return NULL != lhs ? (lhs->get_tenant_database_id() < tenant_database_id) : false; } bool ObSchemaMgr::equal_with_tenant_database_id( const ObSimpleDatabaseSchema* lhs, const ObTenantDatabaseId& tenant_database_id) { return NULL != lhs ? (lhs->get_tenant_database_id() == tenant_database_id) : false; } bool ObSchemaMgr::compare_tablegroup(const ObSimpleTablegroupSchema* lhs, const ObSimpleTablegroupSchema* rhs) { return lhs->get_tenant_tablegroup_id() < rhs->get_tenant_tablegroup_id(); } bool ObSchemaMgr::equal_tablegroup(const ObSimpleTablegroupSchema* lhs, const ObSimpleTablegroupSchema* rhs) { return lhs->get_tenant_tablegroup_id() == rhs->get_tenant_tablegroup_id(); } bool ObSchemaMgr::compare_with_tenant_tablegroup_id( const ObSimpleTablegroupSchema* lhs, const ObTenantTablegroupId& tenant_tablegroup_id) { return NULL != lhs ? (lhs->get_tenant_tablegroup_id() < tenant_tablegroup_id) : false; } bool ObSchemaMgr::equal_with_tenant_tablegroup_id( const ObSimpleTablegroupSchema* lhs, const ObTenantTablegroupId& tenant_tablegroup_id) { return NULL != lhs ? (lhs->get_tenant_tablegroup_id() == tenant_tablegroup_id) : false; } bool ObSchemaMgr::compare_table(const ObSimpleTableSchemaV2* lhs, const ObSimpleTableSchemaV2* rhs) { return lhs->get_tenant_table_id() < rhs->get_tenant_table_id(); } // bool ObSchemaMgr::compare_table_with_data_table_id(const ObSimpleTableSchemaV2 *lhs, // const ObSimpleTableSchemaV2 *rhs) //{ // return lhs->get_tenant_data_table_id() < rhs->get_tenant_data_table_id(); //} bool ObSchemaMgr::compare_aux_table(const ObSimpleTableSchemaV2* lhs, const ObSimpleTableSchemaV2* rhs) { bool ret = lhs->get_tenant_data_table_id() < rhs->get_tenant_data_table_id(); if (lhs->get_tenant_data_table_id() == rhs->get_tenant_data_table_id()) { ret = lhs->get_tenant_table_id() < rhs->get_tenant_table_id(); } return ret; } bool ObSchemaMgr::equal_table(const ObSimpleTableSchemaV2* lhs, const ObSimpleTableSchemaV2* rhs) { return lhs->get_tenant_table_id() == rhs->get_tenant_table_id(); } bool ObSchemaMgr::compare_with_tenant_table_id(const ObSimpleTableSchemaV2* lhs, const ObTenantTableId& tenant_table_id) { return NULL != lhs ? (lhs->get_tenant_table_id() < tenant_table_id) : false; } bool ObSchemaMgr::compare_with_tenant_data_table_id( const ObSimpleTableSchemaV2* lhs, const ObTenantTableId& tenant_table_id) { return NULL != lhs ? (lhs->get_tenant_data_table_id() < tenant_table_id) : false; } bool ObSchemaMgr::equal_with_tenant_table_id(const ObSimpleTableSchemaV2* lhs, const ObTenantTableId& tenant_table_id) { return NULL != lhs ? (lhs->get_tenant_table_id() == tenant_table_id) : false; } bool ObSchemaMgr::compare_tenant_table_id_up(const ObTenantTableId& tenant_table_id, const ObSimpleTableSchemaV2* lhs) { return NULL != lhs ? (tenant_table_id < lhs->get_tenant_table_id()) : false; } bool ObSchemaMgr::compare_drop_tenant_info(const ObDropTenantInfo* lhs, const ObDropTenantInfo* rhs) { return lhs->get_tenant_id() < rhs->get_tenant_id(); } bool ObSchemaMgr::equal_drop_tenant_info(const ObDropTenantInfo* lhs, const ObDropTenantInfo* rhs) { return lhs->get_tenant_id() == rhs->get_tenant_id(); } int ObSchemaMgr::add_tenants(const ObIArray<ObSimpleTenantSchema>& tenant_schemas) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(tenant_schema, tenant_schemas, OB_SUCC(ret)) { if (OB_FAIL(add_tenant(*tenant_schema))) { LOG_WARN("add tenant failed", K(ret), "tenant_schema", *tenant_schema); } } } return ret; } int ObSchemaMgr::del_tenants(const ObIArray<uint64_t>& tenants) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(tenant, tenants, OB_SUCC(ret)) { if (OB_FAIL(del_tenant(*tenant))) { LOG_WARN("del tenant failed", K(ret), "tenant_id", *tenant); } } } return ret; } int ObSchemaMgr::add_tenant(const ObSimpleTenantSchema& tenant_schema) { int ret = OB_SUCCESS; ObSimpleTenantSchema* new_tenant_schema = NULL; TenantIterator iter = NULL; ObSimpleTenantSchema* replaced_tenant = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!tenant_schema.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_schema)); } else if (OB_FAIL(ObSchemaUtils::alloc_schema(allocator_, tenant_schema, new_tenant_schema))) { LOG_WARN("alloc schema failed", K(ret)); } else if (OB_ISNULL(new_tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(new_tenant_schema)); } else if (OB_FAIL(tenant_infos_.replace(new_tenant_schema, iter, compare_tenant, equal_tenant, replaced_tenant))) { LOG_WARN("failed to add tenant schema", K(ret)); } else { LOG_INFO("add tenant schema", K(ret), K_(tenant_id), K(tenant_schema)); } return ret; } int ObSchemaMgr::del_tenant(const uint64_t tenant_id) { int ret = OB_SUCCESS; ObSimpleTenantSchema* schema_to_del = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_FAIL(tenant_infos_.remove_if(tenant_id, compare_with_tenant_id, equal_with_tenant_id, schema_to_del))) { LOG_WARN("failed to remove tenant schema, ", K(tenant_id), K(ret)); } else if (OB_ISNULL(schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("removed tenant schema return NULL, ", K(tenant_id), K(ret)); } return ret; } int ObSchemaMgr::add_drop_tenant_info(const ObDropTenantInfo& drop_tenant_info) { int ret = OB_SUCCESS; ObDropTenantInfo tmp_info; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!drop_tenant_info.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid drop tenant info", K(ret), K(drop_tenant_info)); } else if (OB_FAIL(get_drop_tenant_info(drop_tenant_info.get_tenant_id(), tmp_info))) { LOG_WARN("fail to get drop tenant info", K(ret), K(drop_tenant_info)); } else if (tmp_info.is_valid()) { if (tmp_info.get_schema_version() != drop_tenant_info.get_schema_version()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("drop tenant info not match", K(ret), K(tmp_info), K(drop_tenant_info)); } else { // The incremental refresh process may fail and retry, it needs to be reentrant here LOG_INFO("drop tenant info already exist", K(ret), K(tmp_info), K(drop_tenant_info)); } } else { void* tmp_ptr = allocator_.alloc(sizeof(ObDropTenantInfo)); if (OB_ISNULL(tmp_ptr)) { ret = OB_ALLOCATE_MEMORY_FAILED; LOG_ERROR("alloc mem failed", K(ret)); } else { DropTenantInfoIterator iter = drop_tenant_infos_.end(); ObDropTenantInfo* new_ptr = new (tmp_ptr) ObDropTenantInfo; *new_ptr = drop_tenant_info; if (OB_FAIL(drop_tenant_infos_.insert(new_ptr, iter, compare_drop_tenant_info))) { LOG_WARN("fail to insert drop tenant info", K(ret), KPC(new_ptr)); } else { LOG_INFO("add drop tenant info", K(ret), KPC(new_ptr)); } } } return ret; } int ObSchemaMgr::add_drop_tenant_infos(const common::ObIArray<ObDropTenantInfo>& drop_tenant_infos) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { for (int64_t i = 0; OB_SUCC(ret) && i < drop_tenant_infos.count(); i++) { const ObDropTenantInfo& drop_tenant_info = drop_tenant_infos.at(i); if (OB_FAIL(add_drop_tenant_info(drop_tenant_info))) { LOG_WARN("fail to add drop tenant info", K(ret)); } } } return ret; } // for fallback schema_mgr used int ObSchemaMgr::del_drop_tenant_info(const uint64_t tenant_id) { int ret = OB_SUCCESS; ObDropTenantInfo* drop_tenant_info = NULL; ObDropTenantInfo tmp_info; tmp_info.set_tenant_id(tenant_id); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_FAIL(drop_tenant_infos_.remove_if( &tmp_info, compare_drop_tenant_info, equal_drop_tenant_info, drop_tenant_info))) { LOG_WARN("fail to remove drop tenant info", K(ret), K(tenant_id)); } else { LOG_INFO("remove drop tenant info", K(ret), K(tenant_id), KPC(drop_tenant_info)); } return ret; } int ObSchemaMgr::get_drop_tenant_info(const uint64_t tenant_id, ObDropTenantInfo& drop_tenant_info) const { int ret = OB_SUCCESS; ObDropTenantInfo tmp_info; tmp_info.set_tenant_id(tenant_id); DropTenantInfoIterator iter = drop_tenant_infos_.end(); drop_tenant_info.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_TENANT_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid tenant id", K(ret), K(tenant_id)); } else { ret = drop_tenant_infos_.find(&tmp_info, iter, compare_drop_tenant_info, equal_drop_tenant_info); if (OB_SUCCESS == ret) { drop_tenant_info = *(*iter); } else if (OB_ENTRY_NOT_EXIST == ret) { // Not found, as a tenant exists ret = OB_SUCCESS; } else { LOG_WARN("fail to find drop tenant info", K(ret), K(drop_tenant_info)); } } return ret; } int ObSchemaMgr::get_tenant_schema(const uint64_t tenant_id, const ObSimpleTenantSchema*& tenant_schema) const { int ret = OB_SUCCESS; tenant_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else { ObSimpleTenantSchema* tmp_schema = NULL; ConstTenantIterator iter = tenant_infos_.lower_bound(tenant_id, compare_with_tenant_id); if (iter == tenant_infos_.end()) { // do-nothing } else if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tenant_id != tmp_schema->get_tenant_id()) { // do-nothing } else { tenant_schema = tmp_schema; } } return ret; } int ObSchemaMgr::get_tenant_schema(const ObString& tenant_name, const ObSimpleTenantSchema*& tenant_schema) const { int ret = OB_SUCCESS; tenant_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (tenant_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_name)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_) { ret = OB_OP_NOT_ALLOW; LOG_WARN("get tenant schema from non-sys schema mgr not allowed", K(ret), K_(tenant_id)); } else { const ObSimpleTenantSchema* tmp_schema = NULL; bool is_stop = false; for (ConstTenantIterator iter = tenant_infos_.begin(); OB_SUCC(ret) && iter != tenant_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_name_str() != tenant_name) { // do-nothing } else { tenant_schema = tmp_schema; is_stop = true; } } } return ret; } int ObSchemaMgr::add_users(const ObIArray<ObSimpleUserSchema>& user_schemas) { int ret = OB_SUCCESS; ObWorker::CompatMode compat_mode = ObWorker::CompatMode::MYSQL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(user_schema, user_schemas, OB_SUCC(ret)) { // Here to try to get the compatibility mode of the tenant and put it in the global hash table for cache // When the compatibility mode of the corresponding tenant does not exist in the cache, internal sql will be sent, // if it exists, do nothing // In this way, it can avoid the situation that the bottom layer sends internal SQL to get the compatibility mode // and the error code cannot be perceived. // The reason for putting it here is that add_users is at the top of the brushing schema // If it is g_liboblog_mode_, don't get mode for now if (ObSchemaService::g_liboblog_mode_) { } else if (OB_FAIL(ObCompatModeGetter::get_tenant_mode(user_schema->get_tenant_id(), compat_mode))) { LOG_WARN("fail to set tenant mode in add_users", K(ret)); } if (OB_SUCC(ret)) { if (OB_FAIL(add_user(*user_schema))) { LOG_WARN("add user failed", K(ret), "user_schema", *user_schema); } } } } return ret; } // NOT USED int ObSchemaMgr::del_users(const ObIArray<ObTenantUserId>& users) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(user, users, OB_SUCC(ret)) { if (OB_FAIL(del_user(*user))) { LOG_WARN("del user failed", K(ret), "tenant_id", user->tenant_id_, "user_id", user->user_id_); } } } return ret; } int ObSchemaMgr::add_user(const ObSimpleUserSchema& user_schema) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleUserSchema* new_user_schema = NULL; UserIterator iter = NULL; ObSimpleUserSchema* replaced_user = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!user_schema.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(user_schema)); } else if (OB_FAIL(get_tenant_schema(user_schema.get_tenant_id(), tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", user_schema.get_tenant_id()); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } else if (OB_FAIL(ObSchemaUtils::alloc_schema(allocator_, user_schema, new_user_schema))) { LOG_WARN("alloc schema failed", K(ret)); } else if (OB_ISNULL(new_user_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(new_user_schema)); } else if (OB_FAIL(user_infos_.replace(new_user_schema, iter, compare_user, equal_user, replaced_user))) { LOG_WARN("failed to add user schema", K(ret)); } else { } return ret; } int ObSchemaMgr::del_user(const ObTenantUserId user) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleUserSchema* schema_to_del = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!user.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(user)); } else if (OB_FAIL(get_tenant_schema(user.tenant_id_, tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", user.tenant_id_); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } else if (OB_FAIL( user_infos_.remove_if(user, compare_with_tenant_user_id, equal_with_tenant_user_id, schema_to_del))) { LOG_WARN("failed to remove user schema, ", "tenant_id", user.tenant_id_, "user_id", user.user_id_, K(ret)); } else if (OB_ISNULL(schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("removed user schema return NULL, ", "tenant_id", user.tenant_id_, "user_id", user.user_id_, K(ret)); } return ret; } int ObSchemaMgr::get_user_schema(const uint64_t user_id, const ObSimpleUserSchema*& user_schema) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(user_id); user_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == user_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(user_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleUserSchema* tmp_schema = NULL; ObTenantUserId tenant_user_id_lower(tenant_id, user_id); ConstUserIterator iter = user_infos_.lower_bound(tenant_user_id_lower, compare_with_tenant_user_id); if (iter == user_infos_.end()) { // do-nothing } else if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tenant_id != tmp_schema->get_tenant_id() || user_id != tmp_schema->get_user_id()) { // do-nothing } else { user_schema = tmp_schema; } } return ret; } int ObSchemaMgr::get_user_schema(const uint64_t tenant_id, const ObString& user_name, const ObString& host_name, const ObSimpleUserSchema*& user_schema) const { int ret = OB_SUCCESS; user_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObTenantUserId tenant_user_id_lower(tenant_id, OB_MIN_ID); const ObSimpleUserSchema* tmp_schema = NULL; ConstUserIterator iter = user_infos_.lower_bound(tenant_user_id_lower, compare_with_tenant_user_id); bool is_stop = false; for (; OB_SUCC(ret) && iter != user_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_id() > tenant_id) { is_stop = true; } else if (tmp_schema->get_user_name_str() != user_name) { // do-nothing } else if (tmp_schema->get_host_name_str() != host_name) { // do-nothing } else { user_schema = tmp_schema; is_stop = true; } } } return ret; } int ObSchemaMgr::get_user_schema( const uint64_t tenant_id, const ObString& user_name, ObIArray<const ObSimpleUserSchema*>& users_schema) const { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObTenantUserId tenant_user_id_lower(tenant_id, OB_MIN_ID); const ObSimpleUserSchema* tmp_schema = NULL; ConstUserIterator iter = user_infos_.lower_bound(tenant_user_id_lower, compare_with_tenant_user_id); bool is_stop = false; for (; OB_SUCC(ret) && iter != user_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_id() > tenant_id) { is_stop = true; } else if (tmp_schema->get_user_name_str() != user_name) { // do-nothing } else if (OB_FAIL(users_schema.push_back(tmp_schema))) { LOG_WARN("failed to push back user schema", K(tmp_schema), K(ret)); } else { tmp_schema = NULL; ; } } } return ret; } int ObSchemaMgr::add_databases(const ObIArray<ObSimpleDatabaseSchema>& database_schemas) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(database_schema, database_schemas, OB_SUCC(ret)) { if (OB_FAIL(add_database(*database_schema))) { LOG_WARN("add database failed", K(ret), "database_schema", *database_schema); } } } return ret; } int ObSchemaMgr::del_databases(const ObIArray<ObTenantDatabaseId>& databases) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(database, databases, OB_SUCC(ret)) { if (OB_FAIL(del_database(*database))) { LOG_WARN( "del database failed", K(ret), "tenant_id", database->tenant_id_, "database_id", database->database_id_); } } } return ret; } int ObSchemaMgr::add_database(const ObSimpleDatabaseSchema& db_schema) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleDatabaseSchema* new_db_schema = NULL; DatabaseIterator db_iter = NULL; ObSimpleDatabaseSchema* replaced_db = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!db_schema.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(db_schema)); } else if (OB_FAIL(get_tenant_schema(db_schema.get_tenant_id(), tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", db_schema.get_tenant_id()); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_SUCC(ret)) { if (OB_SYS_TENANT_ID == tenant_id_ || OB_SYS_DATABASE_ID == extract_pure_id(db_schema.get_database_id())) { // The system tenant cannot obtain the name_case_mode of the other tenants, and the system tenant shall prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(db_schema.get_tenant_id(), mode))) { LOG_WARN("fail to get_tenant_name_case_mode", K(ret), "tenant_id", db_schema.get_tenant_id()); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } } if (OB_FAIL(ret)) { } else if (OB_FAIL(ObSchemaUtils::alloc_schema(allocator_, db_schema, new_db_schema))) { LOG_WARN("alloc schema failed", K(ret)); } else if (OB_ISNULL(new_db_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(new_db_schema)); } else if (FALSE_IT(new_db_schema->set_name_case_mode(mode))) { // will not reach here } else if (OB_FAIL(database_infos_.replace(new_db_schema, db_iter, compare_database, equal_database, replaced_db))) { LOG_WARN("failed to add db schema", K(ret)); } if (OB_FAIL(ret)) { } else if (NULL == replaced_db) { // do-nothing } else if (OB_FAIL(deal_with_db_rename(*replaced_db, *new_db_schema))) { LOG_WARN("failed to deal with rename", K(ret)); } if (OB_FAIL(ret)) { } else if (new_db_schema->is_dropped_schema()) { uint64_t database_id = new_db_schema->get_database_id(); if (OB_FAIL(delay_deleted_database_map_.set_refactored(database_id, new_db_schema, 1 /*overwrite*/))) { LOG_WARN("fail to set delay_deleted_database_id", KR(ret), K(database_id)); } } else { ObDatabaseSchemaHashWrapper database_name_wrapper( new_db_schema->get_tenant_id(), new_db_schema->get_name_case_mode(), new_db_schema->get_database_name_str()); int over_write = 1; int hash_ret = database_name_map_.set_refactored(database_name_wrapper, new_db_schema, over_write); if (OB_SUCCESS != hash_ret && OB_HASH_EXIST != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build database name hashmap failed", K(ret), K(hash_ret), "tenant_id", new_db_schema->get_tenant_id(), "database_name", new_db_schema->get_database_name()); } } return ret; } int ObSchemaMgr::del_database(const ObTenantDatabaseId database) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleDatabaseSchema* schema_to_del = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!database.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(database)); } else if (OB_FAIL(get_tenant_schema(database.tenant_id_, tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", database.tenant_id_); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_SUCC(ret)) { if (OB_SYS_TENANT_ID == tenant_id_ || OB_SYS_DATABASE_ID == extract_pure_id(database.database_id_)) { // The system tenant cannot obtain the name_case_mode of the other tenants, and the system tenant shall prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(database.tenant_id_, mode))) { LOG_WARN("fail to get_tenant_name_case_mode", K(ret), "tenant_id", database.tenant_id_); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } } if (OB_FAIL(ret)) { } else if (OB_FAIL(database_infos_.remove_if( database, compare_with_tenant_database_id, equal_with_tenant_database_id, schema_to_del))) { LOG_WARN( "failed to remove db schema, ", "tenant_id", database.tenant_id_, "database_id", database.database_id_, K(ret)); } else if (OB_ISNULL(schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("removed db schema return NULL, ", "tenant_id", database.tenant_id_, "database_id", database.database_id_, K(ret)); } else if (schema_to_del->is_dropped_schema()) { const uint64_t database_id = schema_to_del->get_database_id(); if (OB_FAIL(delay_deleted_database_map_.erase_refactored(database_id))) { LOG_WARN("fail to erase delay_deleted_database_id", KR(ret), K(database_id)); if (OB_HASH_NOT_EXIST == ret) { ret = OB_SUCCESS; } } } else { ObDatabaseSchemaHashWrapper database_name_wrapper( schema_to_del->get_tenant_id(), mode, schema_to_del->get_database_name_str()); int hash_ret = database_name_map_.erase_refactored(database_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete database from database name hashmap", K(ret), K(hash_ret), "tenant_id", schema_to_del->get_tenant_id(), "database_name", schema_to_del->get_database_name()); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } // ignore ret if (database_infos_.count() != (database_name_map_.item_count() + delay_deleted_database_map_.item_count())) { LOG_WARN("database info is non-consistent", "database_infos_count", database_infos_.count(), "database_name_map_item_count", database_name_map_.item_count(), "tenant_id", database.tenant_id_, "database_id", database.database_id_, "delay_deleted_database_num", delay_deleted_database_map_.item_count()); } return ret; } int ObSchemaMgr::get_database_schema(const uint64_t database_id, const ObSimpleDatabaseSchema*& database_schema) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(database_id); database_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == database_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(database_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleDatabaseSchema* tmp_schema = NULL; ObTenantDatabaseId tenant_database_id_lower(tenant_id, database_id); ConstDatabaseIterator database_iter = database_infos_.lower_bound(tenant_database_id_lower, compare_with_tenant_database_id); if (database_iter == database_infos_.end()) { // do-nothing } else if (OB_ISNULL(tmp_schema = *database_iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tenant_id != tmp_schema->get_tenant_id() || database_id != tmp_schema->get_database_id()) { // do-nothing } else { database_schema = tmp_schema; } } return ret; } int ObSchemaMgr::get_database_schema( const uint64_t tenant_id, const ObString& database_name, const ObSimpleDatabaseSchema*& database_schema) const { int ret = OB_SUCCESS; database_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || database_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_name)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleDatabaseSchema* tmp_schema = NULL; ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_SUCC(ret)) { if (OB_SYS_TENANT_ID == tenant_id_ || 0 == database_name.case_compare(OB_SYS_DATABASE_NAME)) { // The system tenant cannot obtain the name_case_mode of the other tenants, and the system tenant shall prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(tenant_id, mode))) { LOG_WARN("fail to get_tenant_name_case_mode", K(ret), K(tenant_id)); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } } if (OB_SUCC(ret)) { const ObDatabaseSchemaHashWrapper database_name_wrapper(tenant_id, mode, database_name); int hash_ret = database_name_map_.get_refactored(database_name_wrapper, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { database_schema = tmp_schema; } } } } return ret; } int ObSchemaMgr::add_tablegroups(const ObIArray<ObSimpleTablegroupSchema>& tablegroup_schemas) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(tablegroup_schema, tablegroup_schemas, OB_SUCC(ret)) { if (OB_FAIL(add_tablegroup(*tablegroup_schema))) { LOG_WARN("add tablegroup failed", K(ret), "tablegroup_schema", *tablegroup_schema); } } } return ret; } int ObSchemaMgr::del_tablegroups(const ObIArray<ObTenantTablegroupId>& tablegroups) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(tablegroup, tablegroups, OB_SUCC(ret)) { if (OB_FAIL(del_tablegroup(*tablegroup))) { LOG_WARN("del tablegroup failed", K(ret), "tenant_id", tablegroup->tenant_id_, "tablegroup_id", tablegroup->tablegroup_id_); } } } return ret; } int ObSchemaMgr::add_tablegroup(const ObSimpleTablegroupSchema& tg_schema) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleTablegroupSchema* new_tg_schema = NULL; TablegroupIterator tg_iter = NULL; ObSimpleTablegroupSchema* replaced_tg = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!tg_schema.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tg_schema)); } else if (OB_FAIL(get_tenant_schema(tg_schema.get_tenant_id(), tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", tg_schema.get_tenant_id()); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } else if (OB_FAIL(ObSchemaUtils::alloc_schema(allocator_, tg_schema, new_tg_schema))) { LOG_WARN("alloc schema failed", K(ret)); } else if (OB_ISNULL(new_tg_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(new_tg_schema)); } else if (OB_FAIL(tablegroup_infos_.replace( new_tg_schema, tg_iter, compare_tablegroup, equal_tablegroup, replaced_tg))) { LOG_WARN("failed to add tg schema", K(ret)); } return ret; } int ObSchemaMgr::del_tablegroup(const ObTenantTablegroupId tablegroup) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleTablegroupSchema* schema_to_del = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!tablegroup.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tablegroup)); } else if (OB_FAIL(get_tenant_schema(tablegroup.tenant_id_, tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", tablegroup.tenant_id_); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } else if (OB_FAIL(tablegroup_infos_.remove_if( tablegroup, compare_with_tenant_tablegroup_id, equal_with_tenant_tablegroup_id, schema_to_del))) { LOG_WARN("failed to remove tg schema, ", "tenant_id", tablegroup.tenant_id_, "tablegroup_id", tablegroup.tablegroup_id_, K(ret)); } else if (OB_ISNULL(schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("removed tg schema return NULL, ", "tenant_id", tablegroup.tenant_id_, "tablegroup_id", tablegroup.tablegroup_id_, K(ret)); } return ret; } int ObSchemaMgr::get_tablegroup_schema( const uint64_t tablegroup_id, const ObSimpleTablegroupSchema*& tablegroup_schema) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(tablegroup_id); tablegroup_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tablegroup_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tablegroup_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleTablegroupSchema* tmp_schema = NULL; ObTenantTablegroupId tenant_tablegroup_id_lower(tenant_id, tablegroup_id); ConstTablegroupIterator iter = tablegroup_infos_.lower_bound(tenant_tablegroup_id_lower, compare_with_tenant_tablegroup_id); if (iter == tablegroup_infos_.end()) { // do-nothing } else if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tenant_id != tmp_schema->get_tenant_id() || tablegroup_id != tmp_schema->get_tablegroup_id()) { // do-nothing } else { tablegroup_schema = tmp_schema; } } return ret; } int ObSchemaMgr::get_tablegroup_schema( const uint64_t tenant_id, const ObString& tablegroup_name, const ObSimpleTablegroupSchema*& tablegroup_schema) const { int ret = OB_SUCCESS; tablegroup_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || tablegroup_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(tablegroup_name)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObTenantTablegroupId tenant_tablegroup_id_lower(tenant_id, OB_MIN_ID); const ObSimpleTablegroupSchema* tmp_schema = NULL; ConstTablegroupIterator iter = tablegroup_infos_.lower_bound(tenant_tablegroup_id_lower, compare_with_tenant_tablegroup_id); bool is_stop = false; for (; OB_SUCC(ret) && iter != tablegroup_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_id() > tenant_id) { is_stop = true; } else if (tmp_schema->get_tablegroup_name() != tablegroup_name) { // do-nothing } else { tablegroup_schema = tmp_schema; is_stop = true; } } } return ret; } int ObSchemaMgr::add_tables(const ObIArray<ObSimpleTableSchemaV2>& table_schemas) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(table_schema, table_schemas, OB_SUCC(ret)) { if (OB_FAIL(add_table(*table_schema))) { LOG_WARN("add table failed", K(ret), "table_schema", *table_schema); } } } return ret; } int ObSchemaMgr::del_tables(const ObIArray<ObTenantTableId>& tables) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { FOREACH_CNT_X(table, tables, OB_SUCC(ret)) { if (OB_FAIL(del_table(*table))) { LOG_WARN("del table failed", K(ret), "tenant_id", table->tenant_id_, "table_id", table->table_id_); } } } return ret; } int ObSchemaMgr::add_table(const ObSimpleTableSchemaV2& table_schema) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleTableSchemaV2* new_table_schema = NULL; TableIterator iter = NULL; ObSimpleTableSchemaV2* replaced_table = NULL; const uint64_t table_id = table_schema.get_table_id(); bool is_system_table = false; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!table_schema.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(table_schema)); } else if (OB_FAIL(get_tenant_schema(table_schema.get_tenant_id(), tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", table_schema.get_tenant_id()); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_FAIL(ret)) { } else if (OB_FAIL(ObSysTableChecker::is_tenant_space_table_id(table_id, is_system_table))) { LOG_WARN("fail to check if table_id in tenant space", K(ret), K(table_id)); } else if (OB_SYS_TENANT_ID == tenant_id_ || is_system_table) { // The system tenant cannot obtain the name_case_mode of the other tenants, and the system tenant shall prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(table_schema.get_tenant_id(), mode))) { LOG_WARN("fail to get_tenant_name_case_mode", "tenant_id", table_schema.get_tenant_id(), K(ret)); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } if (OB_FAIL(ret)) { } else if (OB_FAIL(ObSchemaUtils::alloc_schema(allocator_, table_schema, new_table_schema))) { LOG_WARN("alloc schema failed", K(ret)); } else if (OB_ISNULL(new_table_schema) || !new_table_schema->is_valid()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(new_table_schema)); } if (OB_FAIL(ret)) { } else if (FALSE_IT(new_table_schema->set_name_case_mode(mode))) { // will not reach here } else if (OB_FAIL(table_infos_.replace(new_table_schema, iter, compare_table, equal_table, replaced_table))) { LOG_WARN("failed to add table schema", K(ret)); } else if (new_table_schema->is_index_table() || new_table_schema->is_materialized_view()) { ObSimpleTableSchemaV2* replaced_index_table = NULL; if (OB_FAIL(index_infos_.replace(new_table_schema, iter, compare_aux_table, equal_table, replaced_index_table))) { LOG_WARN("failed to add index schema", K(ret)); } } if (OB_SUCC(ret)) { if (NULL == replaced_table) { // do-nothing } else if (OB_FAIL(deal_with_table_rename(*replaced_table, *new_table_schema))) { LOG_WARN("failed to deal with rename", K(ret)); } if (NULL != replaced_table) { LOG_DEBUG("debug, replaced table", K(*replaced_table)); } } if (OB_SUCC(ret)) { int over_write = 1; int hash_ret = table_id_map_.set_refactored(new_table_schema->get_table_id(), new_table_schema, over_write); if (OB_SUCCESS != hash_ret && OB_HASH_EXIST != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build table id hashmap failed", K(ret), K(hash_ret), "table_id", new_table_schema->get_table_id()); } else { if (new_table_schema->is_dropped_schema()) { uint64_t table_id = new_table_schema->get_table_id(); if (OB_FAIL(delay_deleted_table_map_.set_refactored(table_id, new_table_schema, 1 /*overwrite*/))) { LOG_WARN("fail to set delay_deleted_table_id", KR(ret), K(table_id)); } } else if (new_table_schema->is_index_table()) { bool is_oracle_mode = false; if (OB_FAIL(new_table_schema->check_if_oracle_compat_mode(is_oracle_mode))) { LOG_WARN("fail to check if tenant mode is oracle mode", K(ret)); } else if (is_oracle_mode && !new_table_schema->is_in_recyclebin()) { // oracle mode and index is not in recyclebin if (OB_FAIL(new_table_schema->generate_origin_index_name())) { LOG_WARN("generate origin index name failed", K(ret), K(new_table_schema->get_table_name_str())); } else { ObIndexSchemaHashWrapper cutted_index_name_wrapper(new_table_schema->get_tenant_id(), new_table_schema->get_database_id(), new_table_schema->get_origin_index_name_str()); hash_ret = index_name_map_.set_refactored(cutted_index_name_wrapper, new_table_schema, over_write); if (OB_SUCCESS != hash_ret && OB_HASH_EXIST != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build index name hashmap failed", K(ret), K(hash_ret), "table_id", new_table_schema->get_table_id(), "index_name", new_table_schema->get_origin_index_name_str()); } } } else { // mysql mode or index is in recyclebin ObIndexSchemaHashWrapper index_name_wrapper(new_table_schema->get_tenant_id(), new_table_schema->get_database_id(), new_table_schema->get_table_name_str()); hash_ret = index_name_map_.set_refactored(index_name_wrapper, new_table_schema, over_write); if (OB_SUCCESS != hash_ret && OB_HASH_EXIST != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build index name hashmap failed", K(ret), K(hash_ret), "table_id", new_table_schema->get_table_id(), "index_name", new_table_schema->get_table_name()); } } } else { ObTableSchemaHashWrapper table_name_wrapper(new_table_schema->get_tenant_id(), new_table_schema->get_database_id(), new_table_schema->get_session_id(), new_table_schema->get_name_case_mode(), new_table_schema->get_table_name_str()); hash_ret = table_name_map_.set_refactored(table_name_wrapper, new_table_schema, over_write); if (OB_SUCCESS != hash_ret && OB_HASH_EXIST != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build table name hashmap failed", K(ret), K(hash_ret), "table_id", new_table_schema->get_table_id(), "table_name", new_table_schema->get_table_name()); } } if (OB_SUCC(ret) && new_table_schema->is_table()) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2100) { // do-nothing for liboblog } else { if (NULL != replaced_table) { // deal with the situation that alter table drop fk and truncate table enter the recycle bin, // and delete the foreign key information dropped from the hash map // First delete the foreign key information on the table from the hash map when truncate table, // and add it back when rebuild_table_hashmap if (OB_FAIL(check_and_delete_given_fk_in_table(replaced_table, new_table_schema))) { LOG_WARN("check and delete given fk in table failed", K(ret), K(*replaced_table), K(*new_table_schema)); } } if (OB_SUCC(ret)) { if (OB_FAIL(add_foreign_keys_in_table( new_table_schema->get_simple_foreign_key_info_array(), 1 /*over_write*/))) { LOG_WARN("add foreign keys info to a hash map failed", K(ret), K(*new_table_schema)); } else { // do nothing } } } } if (OB_SUCC(ret) && new_table_schema->is_table()) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2110) { // do-nothing for liboblog } else { if (NULL != replaced_table) { // deal with the situation that alter table drop cst and truncate table enter the recycle bin, // delete the constraint information dropped from the hash map // When truncate table, delete the constraint information on the table from the hash map first, // and add it back when rebuild_table_hashmap if (OB_FAIL(check_and_delete_given_cst_in_table(replaced_table, new_table_schema))) { LOG_WARN("check and delete given cst in table failed", K(ret), K(*replaced_table), K(*new_table_schema)); } } if (OB_SUCC(ret)) { if (OB_FAIL( add_constraints_in_table(new_table_schema->get_simple_constraint_info_array(), 1 /*over_write*/))) { LOG_WARN("add foreign keys info to a hash map failed", K(ret), K(*new_table_schema)); } else { // do nothing } } } } } } return ret; } // Used to add all foreign key information in a table to the member variable ForeignKeyNameMap of ObSchemaMgr int ObSchemaMgr::add_foreign_keys_in_table(const ObIArray<ObSimpleForeignKeyInfo>& fk_info_array, const int over_write) { int ret = OB_SUCCESS; if (fk_info_array.empty()) { // If there is no foreign key in the table, do nothing } else { FOREACH_CNT_X(simple_foreign_key_info, fk_info_array, OB_SUCC(ret)) { ObForeignKeyInfoHashWrapper foreign_key_name_wrapper(simple_foreign_key_info->tenant_id_, simple_foreign_key_info->database_id_, simple_foreign_key_info->foreign_key_name_); int hash_ret = foreign_key_name_map_.set_refactored( foreign_key_name_wrapper, const_cast<ObSimpleForeignKeyInfo*>(simple_foreign_key_info), over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build fk name hashmap failed", K(ret), K(hash_ret), "fk_id", simple_foreign_key_info->foreign_key_id_, "fk_name", simple_foreign_key_info->foreign_key_name_); } } } return ret; } // According to table_schema and foreign key name, delete the specified foreign key related to the corresponding // table_schema int ObSchemaMgr::delete_given_fk_from_mgr(const ObSimpleForeignKeyInfo& fk_info) { int ret = OB_SUCCESS; if (fk_info.tenant_id_ == common::OB_INVALID_ID || fk_info.database_id_ == common::OB_INVALID_ID || fk_info.foreign_key_name_.empty()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("fk_info should not be null", K(ret), K(fk_info)); } else { ObForeignKeyInfoHashWrapper foreign_key_name_wrapper( fk_info.tenant_id_, fk_info.database_id_, fk_info.foreign_key_name_); int hash_ret = foreign_key_name_map_.erase_refactored(foreign_key_name_wrapper); if (OB_HASH_NOT_EXIST == hash_ret) { // Because there is no guarantee to refresh in strict accordance with the version order of the schema version, // the return value of OB_HASH_NOT_EXIST is reasonable in very special scenarios // At this time, the foreign key information in foreign_key_name_map_ is inconsistent with the correct foreign key // information. It is necessary to rebuild foreign_key_name_map_ according to the correct foreign key information. is_consistent_ = false; LOG_WARN("fail to delete fk from fk name hashmap", K(ret), K(hash_ret), "tenant id", fk_info.tenant_id_, "database id", fk_info.database_id_, "fk name", fk_info.foreign_key_name_); } else if (OB_SUCCESS != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("fail to delete fk from fk name hashmap", K(ret), K(hash_ret), "tenant id", fk_info.tenant_id_, "database id", fk_info.database_id_, "fk name", fk_info.foreign_key_name_); } } return ret; } // Handle the situation of alter table drop fk, delete the foreign key information dropped from the hash map int ObSchemaMgr::check_and_delete_given_fk_in_table( const ObSimpleTableSchemaV2* replaced_table, const ObSimpleTableSchemaV2* new_table) { int ret = OB_SUCCESS; if (OB_ISNULL(replaced_table)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("replaced_table should not be null", K(ret)); } else if (OB_ISNULL(new_table)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("new_table should not be null", K(ret)); } else { const ObIArray<ObSimpleForeignKeyInfo>& replaced_fk_info_array = replaced_table->get_simple_foreign_key_info_array(); const ObIArray<ObSimpleForeignKeyInfo>& new_fk_info_array = new_table->get_simple_foreign_key_info_array(); for (int64_t i = 0; OB_SUCC(ret) && i < replaced_fk_info_array.count(); ++i) { const ObSimpleForeignKeyInfo& fk_info = replaced_fk_info_array.at(i); if (!has_exist_in_array(new_fk_info_array, fk_info)) { if (OB_FAIL(delete_given_fk_from_mgr(fk_info))) { LOG_WARN("fail to delete fk from fk name hashmap", K(ret)); } } } } return ret; } // Used to delete all foreign key information in a table from the member variable ForeignKeyNameMap of ObSchemaMgr int ObSchemaMgr::delete_foreign_keys_in_table(const ObSimpleTableSchemaV2& table_schema) { int ret = OB_SUCCESS; const ObIArray<ObSimpleForeignKeyInfo>& fk_info_array = table_schema.get_simple_foreign_key_info_array(); if (fk_info_array.empty()) { // If there is no foreign key in the table, do nothing } else { FOREACH_CNT_X(simple_foreign_key_info, fk_info_array, OB_SUCC(ret)) { if (OB_FAIL(delete_given_fk_from_mgr(*simple_foreign_key_info))) { LOG_WARN("fail to delete fk from table name hashmap", K(ret)); } } } return ret; } // Get foreign_key_id according to foreign_key_name int ObSchemaMgr::get_foreign_key_id(const uint64_t tenant_id, const uint64_t database_id, const ObString& foreign_key_name, uint64_t& foreign_key_id) const { int ret = OB_SUCCESS; foreign_key_id = OB_INVALID_ID; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || foreign_key_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(foreign_key_name)); } else { ObSimpleForeignKeyInfo* simple_foreign_key_info = NULL; const ObForeignKeyInfoHashWrapper foreign_key_name_wrapper(tenant_id, database_id, foreign_key_name); int hash_ret = foreign_key_name_map_.get_refactored(foreign_key_name_wrapper, simple_foreign_key_info); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(simple_foreign_key_info)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(simple_foreign_key_info)); } else { foreign_key_id = simple_foreign_key_info->foreign_key_id_; } } else { // If the table id is not found based on the library name and table name, nothing will be done } } return ret; } // Get foreign_key_info according to foreign_key_name int ObSchemaMgr::get_foreign_key_info(const uint64_t tenant_id, const uint64_t database_id, const ObString& foreign_key_name, ObSimpleForeignKeyInfo& foreign_key_info) const { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || foreign_key_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(foreign_key_name)); } else { ObSimpleForeignKeyInfo* simple_foreign_key_info = NULL; const ObForeignKeyInfoHashWrapper foreign_key_name_wrapper(tenant_id, database_id, foreign_key_name); int hash_ret = foreign_key_name_map_.get_refactored(foreign_key_name_wrapper, simple_foreign_key_info); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(simple_foreign_key_info)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(simple_foreign_key_info)); } else { foreign_key_info = *simple_foreign_key_info; foreign_key_info.foreign_key_name_.assign(const_cast<char*>(foreign_key_name.ptr()), foreign_key_name.length()); } } else { // If the table id is not found based on the library name and table name, nothing will be done } } return ret; } // Used to add all constraint information in a table to the member variable constraint_name_map_ of ObSchemaMgr int ObSchemaMgr::add_constraints_in_table(const ObIArray<ObSimpleConstraintInfo>& cst_info_array, const int over_write) { int ret = OB_SUCCESS; if (cst_info_array.empty()) { // If there is no foreign key in the table, do nothing } else { FOREACH_CNT_X(simple_constraint_info, cst_info_array, OB_SUCC(ret)) { ObConstraintInfoHashWrapper constraint_name_wrapper(simple_constraint_info->tenant_id_, simple_constraint_info->database_id_, simple_constraint_info->constraint_name_); int hash_ret = constraint_name_map_.set_refactored( constraint_name_wrapper, const_cast<ObSimpleConstraintInfo*>(simple_constraint_info), over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build cst name hashmap failed", K(ret), K(hash_ret), "tenant_id", simple_constraint_info->tenant_id_, "database_id", simple_constraint_info->database_id_, "table_id", simple_constraint_info->table_id_, "cst_id", simple_constraint_info->constraint_id_, "cst_name", simple_constraint_info->constraint_name_); } } } return ret; } // According to table_schema and constraint name, delete the specified constraint related to the corresponding // table_schema int ObSchemaMgr::delete_given_cst_from_mgr(const ObSimpleConstraintInfo& cst_info) { int ret = OB_SUCCESS; if (cst_info.tenant_id_ == common::OB_INVALID_ID || cst_info.database_id_ == common::OB_INVALID_ID || cst_info.constraint_name_.empty()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("cst_info should not be null", K(ret), K(cst_info)); } else { ObConstraintInfoHashWrapper constraint_name_wrapper( cst_info.tenant_id_, cst_info.database_id_, cst_info.constraint_name_); int hash_ret = constraint_name_map_.erase_refactored(constraint_name_wrapper); if (OB_HASH_NOT_EXIST == hash_ret) { // Because there is no guarantee to refresh in strict accordance with the version order of the schema version, // the return value of OB_HASH_NOT_EXIST is reasonable in very special scenarios // At this time, the cst information in constraint_name_map_ is inconsistent with the correct foreign key // information. It is necessary to rebuild the constraint_name_map_ according to the correct cst information. is_consistent_ = false; LOG_WARN("fail to delete cst from cst name hashmap", K(ret), K(hash_ret), "tenant id", cst_info.tenant_id_, "database id", cst_info.database_id_, "cst name", cst_info.constraint_name_); } else if (OB_SUCCESS != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("fail to delete cst from cst name hashmap", K(ret), K(hash_ret), "tenant id", cst_info.tenant_id_, "database id", cst_info.database_id_, "cst name", cst_info.constraint_name_); } } return ret; } // Handle the situation of alter table drop cst, delete the constraint information dropped from the hash map int ObSchemaMgr::check_and_delete_given_cst_in_table( const ObSimpleTableSchemaV2* replaced_table, const ObSimpleTableSchemaV2* new_table) { int ret = OB_SUCCESS; if (OB_ISNULL(replaced_table)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("replaced_table should not be null", K(ret)); } else if (OB_ISNULL(new_table)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("new_table should not be null", K(ret)); } else { const ObIArray<ObSimpleConstraintInfo>& replaced_cst_info_array = replaced_table->get_simple_constraint_info_array(); const ObIArray<ObSimpleConstraintInfo>& new_cst_info_array = new_table->get_simple_constraint_info_array(); for (int64_t i = 0; OB_SUCC(ret) && i < replaced_cst_info_array.count(); ++i) { const ObSimpleConstraintInfo& cst_info = replaced_cst_info_array.at(i); if (!has_exist_in_array(new_cst_info_array, cst_info)) { if (OB_FAIL(delete_given_cst_from_mgr(cst_info))) { LOG_WARN("fail to delete cst from cst name hashmap", K(ret)); } } } } return ret; } // Used to delete all constraint information in a table from the member variable ConstraintNameMap of ObSchemaMgr int ObSchemaMgr::delete_constraints_in_table(const ObSimpleTableSchemaV2& table_schema) { int ret = OB_SUCCESS; const ObIArray<ObSimpleConstraintInfo>& cst_info_array = table_schema.get_simple_constraint_info_array(); if (cst_info_array.empty()) { // If there are no constraints in the table, do nothing } else { FOREACH_CNT_X(simple_constraint_info, cst_info_array, OB_SUCC(ret)) { if (OB_FAIL(delete_given_cst_from_mgr(*simple_constraint_info))) { LOG_WARN("fail to delete cst from table name hashmap", K(ret)); } } } return ret; } // Obtain constraint_id according to constraint_name int ObSchemaMgr::get_constraint_id(const uint64_t tenant_id, const uint64_t database_id, const ObString& constraint_name, uint64_t& constraint_id) const { int ret = OB_SUCCESS; constraint_id = OB_INVALID_ID; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || constraint_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(constraint_name)); } else { ObSimpleConstraintInfo* simple_constraint_info = NULL; const ObConstraintInfoHashWrapper constraint_name_wrapper(tenant_id, database_id, constraint_name); int hash_ret = constraint_name_map_.get_refactored(constraint_name_wrapper, simple_constraint_info); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(simple_constraint_info)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(simple_constraint_info)); } else { constraint_id = simple_constraint_info->constraint_id_; } } else { // If the table id is not found based on the library name and table name, nothing will be done } } return ret; } int ObSchemaMgr::get_constraint_info(const uint64_t tenant_id, const uint64_t database_id, const common::ObString& constraint_name, ObSimpleConstraintInfo& constraint_info) const { int ret = OB_SUCCESS; constraint_info.constraint_id_ = OB_INVALID_ID; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || constraint_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(constraint_name)); } else { ObSimpleConstraintInfo* simple_constraint_info = NULL; const ObConstraintInfoHashWrapper constraint_name_wrapper(tenant_id, database_id, constraint_name); int hash_ret = constraint_name_map_.get_refactored(constraint_name_wrapper, simple_constraint_info); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(simple_constraint_info)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(simple_constraint_info)); } else { constraint_info = *simple_constraint_info; constraint_info.constraint_name_.assign(const_cast<char*>(constraint_name.ptr()), constraint_name.length()); } } else { LOG_INFO("get constraint info failed, entry not exist", K(constraint_name)); // If the table id is not found based on the library name and table name, nothing will be done } } return ret; } int ObSchemaMgr::get_dblink_schema(const uint64_t dblink_id, const ObDbLinkSchema*& dblink_schema) const { return dblink_mgr_.get_dblink_schema(dblink_id, dblink_schema); } int ObSchemaMgr::get_dblink_schema( const uint64_t tenant_id, const ObString& dblink_name, const ObDbLinkSchema*& dblink_schema) const { return dblink_mgr_.get_dblink_schema(tenant_id, dblink_name, dblink_schema); } bool ObSchemaMgr::check_schema_meta_consistent() { // Check the number of foreign keys here, if not, you need to rebuild if (!is_consistent_) { // false == is_consistent, do nothing LOG_WARN("fk or cst info is not consistent"); } if (database_infos_.count() != (database_name_map_.item_count() + delay_deleted_database_map_.item_count())) { is_consistent_ = false; LOG_WARN("database info is not consistent", "database_infos_count", database_infos_.count(), "database_name_map_item_count", database_name_map_.item_count(), "delay_deleted_database_num", delay_deleted_database_map_.item_count()); } if (table_infos_.count() != table_id_map_.item_count() || table_id_map_.item_count() != (table_name_map_.item_count() + index_name_map_.item_count() + delay_deleted_table_map_.item_count())) { is_consistent_ = false; LOG_WARN("schema meta is not consistent, need rebuild", "schema_mgr version", get_schema_version(), "table_infos_count", table_infos_.count(), "table_id_map_item_count", table_id_map_.item_count(), "table_name_map_item_count", table_name_map_.item_count(), "index_name_map_item_count", index_name_map_.item_count(), "delay_deleted_table_num", delay_deleted_table_map_.item_count()); } return is_consistent_; } int ObSchemaMgr::rebuild_schema_meta_if_not_consistent() { int ret = OB_SUCCESS; uint64_t fk_cnt = 0; uint64_t cst_cnt = 0; if (!check_schema_meta_consistent()) { LOG_WARN("schema meta is not consistent, need rebuild", K(ret)); if (OB_FAIL(rebuild_table_hashmap(fk_cnt, cst_cnt))) { LOG_WARN("rebuild table hashmap failed", K(ret)); } else if (OB_FAIL(rebuild_db_hashmap())) { LOG_WARN("rebuild db hashmap failed", K(ret)); } } if (OB_SUCC(ret)) { // If it is inconsistent (!is_consistent_), rebuild is required, after the rebuild is over, // check whether fk and cst are consistent // If they are the same, there is no need to rebuild and check whether fk and cst are the same if (!is_consistent_ && (fk_cnt != foreign_key_name_map_.item_count())) { is_consistent_ = false; LOG_WARN("fk info is still not consistent after rebuild, need fixing", K(fk_cnt), K(foreign_key_name_map_.item_count())); } else if (!is_consistent_ && (cst_cnt != constraint_name_map_.item_count())) { is_consistent_ = false; LOG_WARN("cst info is still not consistent after rebuild, need fixing", K(cst_cnt), K(constraint_name_map_.item_count())); } else { is_consistent_ = true; } // Check whether db and table are consistent if (!check_schema_meta_consistent()) { LOG_ERROR("schema meta is still not consistent after rebuild, need fixing", K(ret)); right_to_die_or_duty_to_live(); } } return ret; } int ObSchemaMgr::del_table(const ObTenantTableId table) { int ret = OB_SUCCESS; const ObSimpleTenantSchema* tenant_schema = NULL; ObSimpleTableSchemaV2* schema_to_del = NULL; const uint64_t table_id = table.table_id_; bool is_system_table = false; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!table.is_valid()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(table)); } else if (OB_FAIL(get_tenant_schema(table.tenant_id_, tenant_schema))) { LOG_WARN("get tenant schema failed", K(ret), "tenant_id", table.tenant_id_); } else if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tenant_schema)); } ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_FAIL(ret)) { } else if (OB_FAIL(ObSysTableChecker::is_tenant_space_table_id(table_id, is_system_table))) { LOG_WARN("fail to check if table_id in tenant space", K(ret), K(table_id)); } else if (OB_SYS_TENANT_ID == tenant_id_ || is_system_table) { // The system tenant cannot obtain the name_case_mode of the other tenants, // and the system tenant shall prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(table.tenant_id_, mode))) { LOG_WARN("fail to get_tenant_name_case_mode", "tenant_id", table.tenant_id_, K(ret)); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } if (OB_FAIL((ret))) { } else if (OB_FAIL(table_infos_.remove_if( table, compare_with_tenant_table_id, equal_with_tenant_table_id, schema_to_del))) { LOG_WARN("failed to remove table schema, ", "tenant_id", table.tenant_id_, "table_id", table.table_id_, K(ret)); } else if (OB_ISNULL(schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("removed table schema return NULL, ", "tenant_id", table.tenant_id_, "table_id", table.table_id_, K(ret)); } else { if (schema_to_del->is_index_table() || schema_to_del->is_materialized_view()) { if (OB_FAIL(remove_aux_table(*schema_to_del))) { LOG_WARN("failed to remove aux table schema", K(ret), K(*schema_to_del)); } } } if (OB_SUCC(ret)) { int hash_ret = table_id_map_.erase_refactored(schema_to_del->get_table_id()); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete table from table id hashmap, ", "hash_ret", hash_ret, "table_id", schema_to_del->get_table_id()); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } else { if (schema_to_del->is_dropped_schema()) { const uint64_t table_id = schema_to_del->get_table_id(); if (OB_FAIL(delay_deleted_table_map_.erase_refactored(table_id))) { LOG_WARN("fail to erase delay_deleted_table_id", KR(ret), K(table_id)); if (OB_HASH_NOT_EXIST == ret) { ret = OB_SUCCESS; } } } else if (schema_to_del->is_index_table()) { bool is_oracle_mode = false; if (OB_FAIL(schema_to_del->check_if_oracle_compat_mode(is_oracle_mode))) { LOG_WARN("fail to check if tenant mode is oracle mode", K(ret)); } else if (is_oracle_mode && !schema_to_del->is_in_recyclebin()) { // oracle mode and index is not in recyclebin if (OB_FAIL(schema_to_del->generate_origin_index_name())) { LOG_WARN("generate origin index name failed", K(ret), K(schema_to_del->get_table_name_str())); } else { ObIndexSchemaHashWrapper cutted_index_name_wrapper(schema_to_del->get_tenant_id(), schema_to_del->get_database_id(), schema_to_del->get_origin_index_name_str()); int hash_ret = index_name_map_.erase_refactored(cutted_index_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete index from index name hashmap, ", K(ret), K(hash_ret), "index_name", schema_to_del->get_origin_index_name_str()); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this // time, and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } else { // mysql mode or index is in recyclebin ObIndexSchemaHashWrapper index_schema_wrapper( schema_to_del->get_tenant_id(), schema_to_del->get_database_id(), schema_to_del->get_table_name_str()); int hash_ret = index_name_map_.erase_refactored(index_schema_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete index from index name hashmap, ", K(ret), K(hash_ret), "index_name", schema_to_del->get_table_name()); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } else { ObTableSchemaHashWrapper table_schema_wrapper(schema_to_del->get_tenant_id(), schema_to_del->get_database_id(), schema_to_del->get_session_id(), mode, schema_to_del->get_table_name_str()); int hash_ret = table_name_map_.erase_refactored(table_schema_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete table from table name hashmap, ", K(ret), K(hash_ret), "tenant_id", schema_to_del->get_tenant_id(), "database_id", schema_to_del->get_database_id(), "table_name", schema_to_del->get_table_name()); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } if (OB_SUCC(ret)) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2100) { // do-nothing for liboblog } else if (OB_FAIL(delete_foreign_keys_in_table(*schema_to_del))) { LOG_WARN("delete foreign keys info from a hash map failed", K(ret), K(*schema_to_del)); } } if (OB_SUCC(ret)) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2110) { // do-nothing for liboblog } else if (OB_FAIL(delete_constraints_in_table(*schema_to_del))) { LOG_WARN("delete constraint info from a hash map failed", K(ret), K(*schema_to_del)); } } } } } // ignore ret if (table_infos_.count() != table_id_map_.item_count() || table_id_map_.item_count() != (table_name_map_.item_count() + index_name_map_.item_count() + delay_deleted_table_map_.item_count())) { LOG_WARN("table info is non-consistent", "table_infos_count", table_infos_.count(), "table_id_map_item_count", table_id_map_.item_count(), "table_name_map_item_count", table_name_map_.item_count(), "index_name_map_item_count", index_name_map_.item_count(), "tenant_id", table.tenant_id_, "table_id", table.table_id_, "delay_deleted_table_num", delay_deleted_table_map_.item_count()); } return ret; } int ObSchemaMgr::remove_aux_table(const ObSimpleTableSchemaV2& schema_to_del) { int ret = OB_SUCCESS; ObSimpleTableSchemaV2* aux_schema_to_del = NULL; ObTenantTableId tenant_table_id(schema_to_del.get_tenant_id(), schema_to_del.get_table_id()); ObTenantTableId tenant_data_table_id(schema_to_del.get_tenant_id(), schema_to_del.get_data_table_id()); TableIterator iter = index_infos_.lower_bound(tenant_data_table_id, compare_with_tenant_data_table_id); TableIterator dst_iter = NULL; bool is_stop = false; for (; iter != index_infos_.end() && OB_SUCC(ret) && !is_stop; ++iter) { if (OB_ISNULL(aux_schema_to_del = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(aux_schema_to_del), K(ret)); } else if (!(aux_schema_to_del->get_tenant_data_table_id() == tenant_data_table_id)) { is_stop = true; } else if (!(aux_schema_to_del->get_tenant_table_id() == tenant_table_id)) { // do-nothing } else { dst_iter = iter; is_stop = true; } } if (OB_SUCC(ret)) { if (OB_ISNULL(dst_iter) || OB_ISNULL(aux_schema_to_del)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("dst_iter or aux_schema_to_del is NULL", K(dst_iter), K(aux_schema_to_del), K(ret)); } else if (OB_FAIL(index_infos_.remove(dst_iter, dst_iter + 1))) { LOG_WARN("failed to remove aux schema, ", "tenant_id", tenant_table_id.tenant_id_, "table_id", tenant_table_id.table_id_, K(ret)); } } return ret; } int ObSchemaMgr::get_table_schema(const uint64_t table_id, const ObSimpleTableSchemaV2*& table_schema) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(table_id); table_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == table_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(table_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else if (is_link_table_id(table_id)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("link table is not support here", K(ret), K(table_id)); } else { ObSimpleTableSchemaV2* tmp_schema = NULL; int hash_ret = table_id_map_.get_refactored(table_id, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } } return ret; } // table_schema->session_id = 0, This is a general situation, the schema is visible to any session; // table_schema->session_id<>0, schema is a) temp table; or b) The visibility of the table in the process of querying // the table creation is as follows: // For the internal session (parameter value session_id = OB_INVALID_ID), only b# is visible, a# is not visible, // because the temporary table T may exist between different sessions; (create temporary table as select not support // yet); For non-internal sessions (including session_id = 0), judge according to session->session_id == // table_schema->session_id; There may be problems, such as the SQL statement executed by ObMySQLProxy.write in the // internal session, when it involves a temporary table or incorrectly uses a non-temporary table with the same name or // reports an error that cannot be found; See the code for specific judgments ObTableSchemaHashWrapper::operator == int ObSchemaMgr::get_table_schema(const uint64_t tenant_id, const uint64_t database_id, // ObSchemaGetterGuard session_id, default value=0, initialized in ObSql::generate_stmt, if=OB_INVALID_ID is // internal session const uint64_t session_id, const ObString& table_name, const ObSimpleTableSchemaV2*& table_schema) const { int ret = OB_SUCCESS; bool is_system_table = false; table_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || table_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(table_name)); } else if (OB_FAIL(ObSysTableChecker::is_sys_table_name(database_id, table_name, is_system_table))) { LOG_WARN("fail to check if table is system table", K(ret), K(database_id), K(table_name)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleTableSchemaV2* tmp_schema = NULL; ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_SYS_TENANT_ID == tenant_id_ || is_system_table) { // Scenarios for special handling of user tenant system tables mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(tenant_id, mode))) { LOG_WARN("fail to get_tenant_name_case_mode", K(tenant_id), K(ret)); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } if (OB_SUCC(ret)) { const ObTableSchemaHashWrapper table_name_wrapper(tenant_id, database_id, session_id, mode, table_name); int hash_ret = table_name_map_.get_refactored(table_name_wrapper, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } else if (OB_HASH_NOT_EXIST == hash_ret && 0 != session_id && OB_INVALID_ID != session_id) { // If session_id != 0, the search just now is based on the possible match of the temporary table. // If it is not found, then it will be searched according to session_id = 0, which is the normal table. const ObTableSchemaHashWrapper table_name_wrapper2(tenant_id, database_id, 0, mode, table_name); hash_ret = table_name_map_.get_refactored(table_name_wrapper2, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } } } } return ret; } int ObSchemaMgr::get_index_schema(const uint64_t tenant_id, const uint64_t database_id, const ObString& table_name, const ObSimpleTableSchemaV2*& table_schema) const { int ret = OB_SUCCESS; table_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || table_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(table_name)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObSimpleTableSchemaV2* tmp_schema = NULL; ObWorker::CompatMode compat_mode = ObWorker::CompatMode::INVALID; if (OB_FAIL(ObCompatModeGetter::get_tenant_mode(tenant_id, compat_mode))) { LOG_WARN("fail to get tenant mode", K(ret)); } else if (ObWorker::CompatMode::ORACLE == compat_mode && extract_pure_id(database_id) != OB_RECYCLEBIN_SCHEMA_ID) { // FIXME: oracle mode, not support drop user/database to recyclebin yet, now // can determine whether the index is in the recycle bin based on database_id // oracle mode ObString cutted_index_name; ObSimpleTableSchemaV2 tmp_schema_for_cutting_ind_name; tmp_schema_for_cutting_ind_name.reset(); tmp_schema_for_cutting_ind_name.set_table_type(USER_INDEX); if (OB_FAIL(tmp_schema_for_cutting_ind_name.set_table_name(table_name))) { LOG_WARN("fail to set index name", K(ret)); } else if (OB_FAIL(tmp_schema_for_cutting_ind_name.get_index_name(cutted_index_name))) { if (OB_SCHEMA_ERROR == ret) { // If the input table_name of the function does not conform to the prefixed index name format // of'__idx_DataTableId_IndexName', an empty table schema pointer should be returned, and no error should be // reported, so reset the error code to OB_SUCCESS ret = OB_SUCCESS; } LOG_WARN("fail to get index name", K(ret)); } else { ObString cutted_index_name; ObSimpleTableSchemaV2 tmp_schema_for_cutting_ind_name; tmp_schema_for_cutting_ind_name.reset(); tmp_schema_for_cutting_ind_name.set_table_type(USER_INDEX); if (OB_FAIL(tmp_schema_for_cutting_ind_name.set_table_name(table_name))) { LOG_WARN("fail to set index name", K(ret)); } else if (OB_FAIL(tmp_schema_for_cutting_ind_name.get_index_name(cutted_index_name))) { LOG_WARN("fail to get index name", K(ret)); } else { const ObIndexSchemaHashWrapper cutted_index_name_wrapper(tenant_id, database_id, cutted_index_name); int hash_ret = index_name_map_.get_refactored(cutted_index_name_wrapper, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } } } } else if (ObWorker::CompatMode::MYSQL == compat_mode || (ObWorker::CompatMode::ORACLE == compat_mode && extract_pure_id(database_id) == OB_RECYCLEBIN_SCHEMA_ID)) { // mysql mode or oracle mode(in recyclebin) const ObIndexSchemaHashWrapper index_name_wrapper(tenant_id, database_id, table_name); int hash_ret = index_name_map_.get_refactored(index_name_wrapper, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } } else { ret = OB_ERR_UNEXPECTED; LOG_WARN("compat_mode should not be INVALID.", K(ret)); } } return ret; } int ObSchemaMgr::get_table_schema(const uint64_t tenant_id, const uint64_t database_id, const uint64_t session_id, const ObString& table_name, const bool is_index, const ObSimpleTableSchemaV2*& table_schema) const { int ret = OB_SUCCESS; if (!is_index) { ret = get_table_schema(tenant_id, database_id, session_id, table_name, table_schema); } else { ret = get_index_schema(tenant_id, database_id, table_name, table_schema); } return ret; } int ObSchemaMgr::get_object_with_synonym(const uint64_t tenant_id, const uint64_t database_id, const ObString& synonym_name, ObString& table_name, uint64_t& out_database_id, uint64_t& synonym_id, bool& do_exist) const { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ret = synonym_mgr_.get_object( tenant_id, database_id, synonym_name, out_database_id, synonym_id, table_name, do_exist); } return ret; } int ObSchemaMgr::get_synonym_schema(const uint64_t synonym_id, const ObSimpleSynonymSchema*& synonym_schema) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(synonym_id); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ret = synonym_mgr_.get_synonym_schema(synonym_id, synonym_schema); } return ret; } int ObSchemaMgr::get_sequence_schema(const uint64_t sequence_id, const ObSequenceSchema*& sequence_schema) const { return sequence_mgr_.get_sequence_schema(sequence_id, sequence_schema); } int ObSchemaMgr::get_tenant_schemas(ObIArray<const ObSimpleTenantSchema*>& tenant_schemas) const { int ret = OB_SUCCESS; tenant_schemas.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_) { ret = OB_OP_NOT_ALLOW; LOG_WARN("get tenant ids from non-sys schema mgr not allowed", K(ret), K_(tenant_id)); ; } else { for (ConstTenantIterator iter = tenant_infos_.begin(); OB_SUCC(ret) && iter != tenant_infos_.end(); ++iter) { ObSimpleTenantSchema* tenant_schema = *iter; if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("tenant_schema is nnull", K(ret)); } else if (OB_FAIL(tenant_schemas.push_back(tenant_schema))) { LOG_WARN("push_back failed", K(ret)); } } } return ret; } int ObSchemaMgr::get_tenant_ids(ObIArray<uint64_t>& tenant_ids) const { int ret = OB_SUCCESS; tenant_ids.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_) { ret = OB_OP_NOT_ALLOW; LOG_WARN("get tenant ids from non-sys schema mgr not allowed", K(ret), K_(tenant_id)); ; } else { for (ConstTenantIterator iter = tenant_infos_.begin(); OB_SUCC(ret) && iter != tenant_infos_.end(); ++iter) { ObSimpleTenantSchema* tenant_schema = *iter; if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("tenant_schema is nnull", K(ret)); } else if (OB_FAIL(tenant_ids.push_back(tenant_schema->get_tenant_id()))) { LOG_WARN("push_back failed", K(ret)); } } } return ret; } int ObSchemaMgr::get_available_tenant_ids(ObIArray<uint64_t>& tenant_ids) const { int ret = OB_SUCCESS; tenant_ids.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_) { ret = OB_OP_NOT_ALLOW; LOG_WARN("get tenant ids from non-sys schema mgr not allowed", K(ret), K_(tenant_id)); ; } else { for (ConstTenantIterator iter = tenant_infos_.begin(); OB_SUCC(ret) && iter != tenant_infos_.end(); ++iter) { ObSimpleTenantSchema* tenant_schema = *iter; if (OB_ISNULL(tenant_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("tenant_schema is nnull", K(ret)); } else if (TENANT_STATUS_NORMAL != tenant_schema->get_status()) { // tenant is creating or is dropping } else if (OB_FAIL(tenant_ids.push_back(tenant_schema->get_tenant_id()))) { LOG_WARN("push_back failed", K(ret)); } } } return ret; } // The system tenant caches the simple schema of all tenant system tables, which can be accessed directly. // For obtaining the simple table schema of the user tenant after the schema is split, it is necessary to obtain // the schema of the system table from the system tenant and the schema of the ordinary table from the user tenant. // TODO: check tenant schema mgr #define GET_SCHEMAS_IN_TENANT_FUNC_DEFINE(SCHEMA, SCHEMA_TYPE, TENANT_SCHEMA_ID_TYPE, SCHEMA_ITER) \ int ObSchemaMgr::get_##SCHEMA##_schemas_in_tenant( \ const uint64_t tenant_id, ObIArray<const SCHEMA_TYPE*>& schema_array) const \ { \ int ret = OB_SUCCESS; \ if (!check_inner_stat()) { \ ret = OB_NOT_INIT; \ LOG_WARN("not init", K(ret)); \ } else if (OB_INVALID_ID == tenant_id) { \ ret = OB_INVALID_ARGUMENT; \ LOG_WARN("invalid argument", K(ret), K(tenant_id)); \ } else { \ const SCHEMA_TYPE* schema = NULL; \ TENANT_SCHEMA_ID_TYPE tenant_schema_id_lower(tenant_id, OB_MIN_ID); \ SCHEMA_ITER iter = SCHEMA##_infos_.lower_bound(tenant_schema_id_lower, compare_with_tenant_##SCHEMA##_id); \ bool is_stop = false; \ for (; OB_SUCC(ret) && iter != SCHEMA##_infos_.end() && !is_stop; iter++) { \ if (OB_ISNULL(schema = *iter)) { \ ret = OB_ERR_UNEXPECTED; \ LOG_WARN("NULL ptr", K(schema), K(ret)); \ } else if (tenant_id != schema->get_tenant_id()) { \ is_stop = true; \ } else if (OB_FAIL(schema_array.push_back(schema))) { \ LOG_WARN("failed to push back " #SCHEMA " schema", K(ret)); \ } \ } \ } \ return ret; \ } GET_SCHEMAS_IN_TENANT_FUNC_DEFINE(user, ObSimpleUserSchema, ObTenantUserId, ConstUserIterator); GET_SCHEMAS_IN_TENANT_FUNC_DEFINE(database, ObSimpleDatabaseSchema, ObTenantDatabaseId, ConstDatabaseIterator); GET_SCHEMAS_IN_TENANT_FUNC_DEFINE(tablegroup, ObSimpleTablegroupSchema, ObTenantTablegroupId, ConstTablegroupIterator); #undef GET_SCHEMAS_IN_TENANT_FUNC_DEFINE // The system tenant caches the simple schema of all tenant system tables, which can be accessed directly. // For obtaining the simple table schema of the ordinary tenant after the schema is split, it is necessary to obtain // the schema of the system table from the system tenant and the schema of the ordinary table from the ordinary tenant. #define GET_TABLE_SCHEMAS_IN_DST_SCHEMA_FUNC_DEFINE(DST_SCHEMA) \ int ObSchemaMgr::get_table_schemas_in_##DST_SCHEMA(const uint64_t tenant_id, \ const uint64_t dst_schema_id, \ bool need_reset, \ ObIArray<const ObSimpleTableSchemaV2*>& schema_array) const \ { \ int ret = OB_SUCCESS; \ if (need_reset) { \ schema_array.reset(); \ } \ if (!check_inner_stat()) { \ ret = OB_NOT_INIT; \ LOG_WARN("not init", K(ret)); \ } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == dst_schema_id || \ extract_tenant_id(dst_schema_id) != tenant_id) { \ ret = OB_INVALID_ARGUMENT; \ LOG_WARN("invalid argument", K(ret), K(tenant_id), #DST_SCHEMA "_id", dst_schema_id); \ } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { \ ret = OB_INVALID_ARGUMENT; \ LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); \ } else { \ const ObSimpleTableSchemaV2* schema = NULL; \ ObTenantTableId tenant_table_id_lower(tenant_id, OB_MIN_ID); \ ConstTableIterator iter = table_infos_.lower_bound(tenant_table_id_lower, compare_with_tenant_table_id); \ bool is_stop = false; \ for (; OB_SUCC(ret) && iter != table_infos_.end() && !is_stop; iter++) { \ if (OB_ISNULL(schema = *iter)) { \ ret = OB_ERR_UNEXPECTED; \ LOG_WARN("NULL ptr", K(schema), K(ret)); \ } else if (tenant_id != schema->get_tenant_id()) { \ is_stop = true; \ } else if (dst_schema_id == schema->get_##DST_SCHEMA##_id()) { \ if (OB_FAIL(schema_array.push_back(schema))) { \ LOG_WARN("failed to push back table schema", K(ret)); \ } \ } \ } \ } \ return ret; \ } GET_TABLE_SCHEMAS_IN_DST_SCHEMA_FUNC_DEFINE(database); GET_TABLE_SCHEMAS_IN_DST_SCHEMA_FUNC_DEFINE(tablegroup); #undef GET_TABLE_SCHEMAS_IN_DST_SCHEMA_FUNC_DEFINE int ObSchemaMgr::get_table_schemas_in_tenant( const uint64_t tenant_id, bool need_reset, ObIArray<const ObSimpleTableSchemaV2*>& schema_array) const { int ret = OB_SUCCESS; if (need_reset) { schema_array.reset(); } if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else { const ObSimpleTableSchemaV2* schema = NULL; ObTenantTableId tenant_schema_id_lower(tenant_id, OB_MIN_ID); ConstTableIterator iter = table_infos_.lower_bound(tenant_schema_id_lower, compare_with_tenant_table_id); bool is_stop = false; for (; OB_SUCC(ret) && iter != table_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(schema), K(ret)); } else if (tenant_id != schema->get_tenant_id()) { is_stop = true; } else if (OB_FAIL(schema_array.push_back(schema))) { LOG_WARN("failed to push back SCHEMA schema", K(ret)); } } } return ret; } int ObSchemaMgr::check_database_exists_in_tablegroup( const uint64_t tenant_id, const uint64_t tablegroup_id, bool& not_empty) const { int ret = OB_SUCCESS; not_empty = false; if (!check_inner_stat()) { ret = OB_INNER_STAT_ERROR; LOG_WARN("inner stat error", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == tablegroup_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(tablegroup_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { ObTenantDatabaseId tenant_database_id_lower(tenant_id, OB_MIN_ID); ConstDatabaseIterator iter = database_infos_.lower_bound(tenant_database_id_lower, compare_with_tenant_database_id); bool is_stop = false; const ObSimpleDatabaseSchema* tmp_schema = NULL; for (; OB_SUCC(ret) && iter != database_infos_.end() && !is_stop; iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_id() != tenant_id) { is_stop = true; } else if (tmp_schema->get_default_tablegroup_id() != tablegroup_id) { // do-nothing } else { is_stop = true; not_empty = true; } } } return ret; } int ObSchemaMgr::get_aux_schemas(const uint64_t data_table_id, ObIArray<const ObSimpleTableSchemaV2*>& aux_schemas, const ObTableType table_type) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(data_table_id); UNUSED(table_type); aux_schemas.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == data_table_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(data_table_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K(tenant_id_), K(data_table_id)); } else { ObTenantTableId tenant_data_table_id(extract_tenant_id(data_table_id), data_table_id); TableIterator iter = index_infos_.lower_bound(tenant_data_table_id, compare_with_tenant_data_table_id); const ObSimpleTableSchemaV2* aux_schema = NULL; bool will_break = false; for (; iter != index_infos_.end() && OB_SUCC(ret) && !will_break; ++iter) { if (OB_ISNULL(aux_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(aux_schema), K(ret)); } else if (!(aux_schema->get_tenant_data_table_id() == tenant_data_table_id)) { will_break = true; } else if (OB_FAIL(aux_schemas.push_back(aux_schema))) { LOG_WARN("push back aux schema failed", K(ret)); } } } return ret; } int ObSchemaMgr::get_index_schemas( const uint64_t data_table_id, ObIArray<const ObSimpleTableSchemaV2*>& index_schemas) const { int ret = OB_SUCCESS; const uint64_t tenant_id = extract_tenant_id(data_table_id); index_schemas.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == data_table_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(data_table_id)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && tenant_id_ != tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("tenant_id not matched", K(ret), K(tenant_id), K_(tenant_id)); } else { // TODO: make index_infos_ added for mv ObTenantTableId tenant_data_table_id(extract_tenant_id(data_table_id), data_table_id); TableIterator iter = index_infos_.lower_bound(tenant_data_table_id, compare_with_tenant_data_table_id); const ObSimpleTableSchemaV2* index_schema = NULL; bool will_break = false; for (; iter != index_infos_.end() && OB_SUCC(ret) && !will_break; ++iter) { if (OB_ISNULL(index_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(index_schema), K(ret)); } else if (!(index_schema->get_tenant_data_table_id() == tenant_data_table_id)) { will_break = true; } else if (OB_FAIL(index_schemas.push_back(index_schema))) { LOG_WARN("push back index schema failed", K(ret)); } } } return ret; } int ObSchemaMgr::get_tenant_mv_ids(const uint64_t tenant_id, ObIArray<uint64_t>& mv_ids) const { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { const ObSimpleTableSchemaV2* mv = NULL; for (TableIterator iter = index_infos_.begin(); iter != index_infos_.end() && OB_SUCC(ret); ++iter) { if (OB_ISNULL(mv = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(mv), K(ret)); } else if (mv->is_materialized_view() && tenant_id == mv->get_tenant_id()) { if (OB_FAIL(mv_ids.push_back(mv->get_table_id()))) { LOG_WARN("push back mv table id failed", K(ret)); } else { } // do-nothing } else { } // do-nothing } } return ret; } // A single tenant needs to return ob_iter_end after iterating, and the outer layer handles the iteration of // the user tenant system table // The system tenant caches the simple schema of all tenant system tables int ObSchemaMgr::batch_get_next_table( const ObTenantTableId tenant_table_id, const int64_t get_size, ObIArray<ObTenantTableId>& table_array) const { int ret = OB_SUCCESS; uint64_t tenant_id = tenant_table_id.tenant_id_; uint64_t table_id = tenant_table_id.table_id_; table_array.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (!tenant_table_id.is_valid() || get_size < 0) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_table_id), K(get_size)); } else if (OB_INVALID_TENANT_ID == tenant_id || (OB_MIN_ID != table_id && extract_tenant_id(table_id) != tenant_id)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_table_id), K(get_size)); } else if (OB_INVALID_TENANT_ID != tenant_id_ && OB_SYS_TENANT_ID != tenant_id_ && tenant_id != tenant_id_) { // user tenant tenant schema mgr cannot get the tables of other tenants ret = OB_INVALID_ARGUMENT; LOG_WARN("invaild argument", K(ret), K(tenant_table_id), K(tenant_id_)); } else { ObTenantTableId tmp_tenant_table_id; const ObSimpleTableSchemaV2* tmp_schema = NULL; ConstTableIterator iter = table_infos_.upper_bound(tenant_table_id, compare_tenant_table_id_up); for (; OB_SUCC(ret) && table_array.count() < get_size && iter != table_infos_.end(); iter++) { if (OB_ISNULL(tmp_schema = *iter)) { ret = OB_ERR_UNEXPECTED; LOG_ERROR("NULL ptr", K(tmp_schema), K(ret)); } else if (tmp_schema->get_tenant_id() != tenant_id) { // After the iteration within the tenant, return in advance break; } else { tmp_tenant_table_id.tenant_id_ = tmp_schema->get_tenant_id(); tmp_tenant_table_id.table_id_ = tmp_schema->get_table_id(); if (OB_FAIL(table_array.push_back(tmp_tenant_table_id))) { LOG_WARN("push back tenant table id failed", K(ret)); } } } if (OB_SUCC(ret) && 0 == table_array.count()) { ret = OB_ITER_END; } } return ret; } int ObSchemaMgr::del_schemas_in_tenant(const uint64_t tenant_id) { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else { #define DEL_SCHEMA(SCHEMA, SCHEMA_TYPE, TENANT_SCHEMA_ID_TYPE, SCHEMA_ITER) \ if (OB_SUCC(ret)) { \ ObArray<const SCHEMA_TYPE*> schemas; \ const SCHEMA_TYPE* schema = NULL; \ TENANT_SCHEMA_ID_TYPE tenant_schema_id_lower(tenant_id, OB_MIN_ID); \ SCHEMA_ITER iter = SCHEMA##_infos_.lower_bound(tenant_schema_id_lower, compare_with_tenant_##SCHEMA##_id); \ bool is_stop = false; \ for (; OB_SUCC(ret) && iter != SCHEMA##_infos_.end() && !is_stop; iter++) { \ if (OB_ISNULL(schema = *iter)) { \ ret = OB_ERR_UNEXPECTED; \ LOG_WARN("NULL ptr", K(schema), K(ret)); \ } else if (tenant_id != schema->get_tenant_id()) { \ is_stop = true; \ } else if (OB_FAIL(schemas.push_back(schema))) { \ LOG_WARN("push back " #SCHEMA " schema failed", K(ret)); \ } \ } \ if (OB_SUCC(ret)) { \ FOREACH_CNT_X(schema, schemas, OB_SUCC(ret)) \ { \ TENANT_SCHEMA_ID_TYPE tenant_schema_id(tenant_id, (*schema)->get_##SCHEMA##_id()); \ if (OB_FAIL(del_##SCHEMA(tenant_schema_id))) { \ LOG_WARN("del " #SCHEMA " failed", \ "tenant_id", \ tenant_schema_id.tenant_id_, \ #SCHEMA "_id", \ tenant_schema_id.SCHEMA##_id_, \ K(ret)); \ } \ } \ } \ } DEL_SCHEMA(user, ObSimpleUserSchema, ObTenantUserId, ConstUserIterator); DEL_SCHEMA(database, ObSimpleDatabaseSchema, ObTenantDatabaseId, ConstDatabaseIterator); DEL_SCHEMA(tablegroup, ObSimpleTablegroupSchema, ObTenantTablegroupId, ConstTablegroupIterator); DEL_SCHEMA(table, ObSimpleTableSchemaV2, ObTenantTableId, ConstTableIterator); #undef DEL_SCHEMA if (OB_SUCC(ret)) { if (OB_FAIL(outline_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del schemas in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(synonym_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del synonym in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(udf_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del udf in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(sequence_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del sequence in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(sys_variable_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del sys variable in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(profile_mgr_.del_schemas_in_tenant(tenant_id))) { LOG_WARN("del profile in tenant failed", K(ret), K(tenant_id)); } else if (OB_FAIL(dblink_mgr_.del_dblink_schemas_in_tenant(tenant_id))) { LOG_WARN("del dblink in tenant failed", K(ret), K(tenant_id)); } } } return ret; } int ObSchemaMgr::get_schema_count(int64_t& schema_count) const { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { int64_t tenant_schema_count = tenant_infos_.size(); schema_count = tenant_schema_count + user_infos_.size() + database_infos_.size() + tablegroup_infos_.size() + table_infos_.size() + index_infos_.size(); int64_t outline_schema_count = 0; int64_t priv_schema_count = 0; int64_t synonym_schema_count = 0; int64_t udf_schema_count = 0; int64_t sequence_schema_count = 0; int64_t sys_variable_schema_count = 0; int64_t profile_schema_count = 0; if (OB_FAIL(outline_mgr_.get_outline_schema_count(outline_schema_count))) { LOG_WARN("get_outline_schema_count failed", K(ret)); } else if (OB_FAIL(priv_mgr_.get_priv_schema_count(priv_schema_count))) { LOG_WARN("get_priv_schema_count failed", K(ret)); } else if (OB_FAIL(synonym_mgr_.get_synonym_schema_count(synonym_schema_count))) { LOG_WARN("get_synonym_mgr_count failed", K(ret)); } else if (OB_FAIL(udf_mgr_.get_udf_schema_count(udf_schema_count))) { LOG_WARN("get_udf_mgr_count failed", K(ret)); } else if (OB_FAIL(sequence_mgr_.get_sequence_schema_count(sequence_schema_count))) { LOG_WARN("get_sequence_mgr_count failed", K(ret)); } else if (OB_FAIL(sys_variable_mgr_.get_sys_variable_schema_count(sys_variable_schema_count))) { LOG_WARN("get_sys_variable_mgr_count failed", K(ret)); } else if (OB_FAIL(profile_mgr_.get_schema_count(profile_schema_count))) { LOG_WARN("get profile schema count failed", K(ret)); } else { schema_count += (outline_schema_count + priv_schema_count + synonym_schema_count + udf_schema_count + sequence_schema_count + sys_variable_schema_count + profile_schema_count + sys_variable_schema_count); } } return ret; } int ObSchemaMgr::get_tenant_name_case_mode(const uint64_t tenant_id, ObNameCaseMode& mode) const { int ret = OB_SUCCESS; mode = OB_NAME_CASE_INVALID; const ObSimpleSysVariableSchema* sys_variable = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_FAIL(sys_variable_mgr_.get_sys_variable_schema(tenant_id, sys_variable))) { LOG_WARN("get sys variable schema failed", K(ret), K(tenant_id)); } else if (NULL == sys_variable) { // do-nothing } else { mode = sys_variable->get_name_case_mode(); } return ret; } int ObSchemaMgr::get_tenant_read_only(const uint64_t tenant_id, bool& read_only) const { int ret = OB_SUCCESS; read_only = false; const ObSimpleSysVariableSchema* sys_variable = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id)); } else if (OB_FAIL(sys_variable_mgr_.get_sys_variable_schema(tenant_id, sys_variable))) { LOG_WARN("get sys variable schema failed", K(ret), K(tenant_id)); } else if (NULL == sys_variable) { ret = OB_TENANT_NOT_EXIST; } else { read_only = sys_variable->get_read_only(); } return ret; } int ObSchemaMgr::deal_with_db_rename( const ObSimpleDatabaseSchema& old_db_schema, const ObSimpleDatabaseSchema& new_db_schema) { int ret = OB_SUCCESS; if (old_db_schema.get_database_id() != new_db_schema.get_database_id()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(old_db_schema), K(new_db_schema)); } else if (old_db_schema.is_dropped_schema()) { // It has been deleted from database_name_map_ before } else { if (old_db_schema.get_database_name_str() != new_db_schema.get_database_name_str()) { LOG_INFO("db renamed", K(old_db_schema), K(new_db_schema)); ObDatabaseSchemaHashWrapper db_name_wrapper( old_db_schema.get_tenant_id(), old_db_schema.get_name_case_mode(), old_db_schema.get_database_name_str()); int hash_ret = database_name_map_.erase_refactored(db_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed to delete database from database name hashmap", K(ret), K(hash_ret), K(old_db_schema)); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } return ret; } int ObSchemaMgr::deal_with_table_rename( const ObSimpleTableSchemaV2& old_table_schema, const ObSimpleTableSchemaV2& new_table_schema) { int ret = OB_SUCCESS; if (old_table_schema.get_table_id() != new_table_schema.get_table_id()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(old_table_schema), K(new_table_schema)); } else { const uint64_t old_database_id = old_table_schema.get_database_id(); const uint64_t new_database_id = new_table_schema.get_database_id(); const ObString& old_table_name = old_table_schema.get_table_name_str(); const ObString& new_table_name = new_table_schema.get_table_name_str(); bool is_rename = (old_table_name != new_table_name) || (old_database_id != new_database_id); // The delayed deletion object has been deleted from name_hash_map before if (!is_rename || old_table_schema.is_dropped_schema()) { // do-nothing } else { LOG_INFO("table renamed", K(old_database_id), K(old_table_name), K(new_database_id), K(new_table_name)); bool is_system_table = false; if (old_table_schema.is_index_table()) { bool is_oracle_mode = false; if (OB_FAIL(old_table_schema.check_if_oracle_compat_mode(is_oracle_mode))) { LOG_WARN("fail to check if tenant mode is oracle mode", K(ret)); } else if (is_oracle_mode && !old_table_schema.is_in_recyclebin()) { // oracle mode and index is not in recyclebin ObString cutted_index_name; if (OB_FAIL(old_table_schema.get_index_name(cutted_index_name))) { LOG_WARN("fail to get index name", K(ret)); } else { ObIndexSchemaHashWrapper cutted_index_name_wrapper( old_table_schema.get_tenant_id(), old_table_schema.get_database_id(), cutted_index_name); int hash_ret = index_name_map_.erase_refactored(cutted_index_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("failed delete index from index name hashmap, ", K(ret), K(hash_ret), K(cutted_index_name)); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this // time, and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } else { // mysql mode or index is in recyclebin ObIndexSchemaHashWrapper index_name_wrapper(old_table_schema.get_tenant_id(), old_table_schema.get_database_id(), old_table_schema.get_table_name_str()); int hash_ret = index_name_map_.erase_refactored(index_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("fail to delete index from index name hashmap", K(ret), K(hash_ret), K(old_table_name)); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } else { ObNameCaseMode mode = OB_NAME_CASE_INVALID; if (OB_FAIL(ObSysTableChecker::is_tenant_space_table_id(old_table_schema.get_table_id(), is_system_table))) { LOG_WARN("fail to check if table_id in tenant space", K(ret), "table_id", old_table_schema.get_table_id()); } else if (OB_SYS_TENANT_ID == tenant_id_ || is_system_table) { // The system tenant cannot obtain the name_case_mode of the other tenants, and the system tenant shall // prevail. mode = OB_ORIGIN_AND_INSENSITIVE; } else if (OB_FAIL(get_tenant_name_case_mode(old_table_schema.get_tenant_id(), mode))) { LOG_WARN("fail to get_tenant_name_case_mode", "tenant_id", old_table_schema.get_tenant_id(), K(ret)); } else if (OB_NAME_CASE_INVALID == mode) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid case mode", K(ret), K(mode)); } if (OB_SUCC(ret)) { ObTableSchemaHashWrapper table_name_wrapper(old_table_schema.get_tenant_id(), old_table_schema.get_database_id(), old_table_schema.get_session_id(), mode, old_table_schema.get_table_name_str()); int hash_ret = table_name_map_.erase_refactored(table_name_wrapper); if (OB_SUCCESS != hash_ret) { LOG_WARN("fail to delete table from table name hashmap", K(ret), K(hash_ret), K(old_table_name)); // Increase the fault-tolerant processing of incremental schema refresh, no error is reported at this time, // and the solution is solved by rebuild logic ret = OB_HASH_NOT_EXIST != hash_ret ? hash_ret : ret; } } } } } return ret; } int ObSchemaMgr::rebuild_db_hashmap() { int ret = OB_SUCCESS; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { database_name_map_.clear(); delay_deleted_database_map_.clear(); int over_write = 0; for (ConstDatabaseIterator iter = database_infos_.begin(); iter != database_infos_.end() && OB_SUCC(ret); ++iter) { ObSimpleDatabaseSchema* database_schema = *iter; if (OB_ISNULL(database_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("database schema is NULL", K(ret)); } else if (database_schema->is_dropped_schema()) { uint64_t database_id = database_schema->get_database_id(); if (OB_FAIL(delay_deleted_database_map_.set_refactored(database_id, database_schema, 1 /*overwrite*/))) { LOG_WARN("fail to set delay_deleted_database_id", KR(ret), K(database_id)); } } else { ObDatabaseSchemaHashWrapper db_name_wrapper(database_schema->get_tenant_id(), database_schema->get_name_case_mode(), database_schema->get_database_name()); int hash_ret = database_name_map_.set_refactored(db_name_wrapper, database_schema, over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build database name hashmap failed", K(ret), K(hash_ret), K(*database_schema)); } } } } return ret; } int ObSchemaMgr::rebuild_table_hashmap(uint64_t& fk_cnt, uint64_t& cst_cnt) { int ret = OB_SUCCESS; fk_cnt = 0; cst_cnt = 0; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { table_id_map_.clear(); table_name_map_.clear(); index_name_map_.clear(); foreign_key_name_map_.clear(); constraint_name_map_.clear(); delay_deleted_table_map_.clear(); ObSimpleTableSchemaV2* table_schema = NULL; // It is expected that OB_HASH_EXIST should not appear in the rebuild process int over_write = 0; for (ConstTableIterator iter = table_infos_.begin(); iter != table_infos_.end() && OB_SUCC(ret); ++iter) { table_schema = *iter; LOG_INFO("table_info is", "table_id", table_schema->get_table_id()); if (OB_ISNULL(table_schema) || !table_schema->is_valid()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("table_schema is unexpected", K(ret), K(table_schema)); } else { int hash_ret = table_id_map_.set_refactored(table_schema->get_table_id(), table_schema, over_write); if (OB_SUCCESS != hash_ret) { ret = OB_ERR_UNEXPECTED; LOG_WARN("build table id hashmap failed", K(ret), K(hash_ret), "table_id", table_schema->get_table_id()); } else if (table_schema->is_dropped_schema()) { uint64_t table_id = table_schema->get_table_id(); if (OB_FAIL(delay_deleted_table_map_.set_refactored(table_id, table_schema, 1 /*overwrite*/))) { LOG_WARN("fail to set delay_deleted_table_id", KR(ret), K(table_id)); } } else { if (table_schema->is_index_table()) { LOG_INFO("index is", "table_id", table_schema->get_table_id(), "database_id", table_schema->get_database_id(), "table_name", table_schema->get_table_name_str()); bool is_oracle_mode = false; // oracle mode and index is not in recyclebin if (OB_FAIL(table_schema->check_if_oracle_compat_mode(is_oracle_mode))) { LOG_WARN("fail to check if tenant mode is oracle mode", K(ret)); } else if (is_oracle_mode && !table_schema->is_in_recyclebin()) { if (OB_FAIL(table_schema->generate_origin_index_name())) { LOG_WARN("generate origin index name failed", K(ret), K(table_schema->get_table_name_str())); } else { ObIndexSchemaHashWrapper cutted_index_name_wrapper(table_schema->get_tenant_id(), table_schema->get_database_id(), table_schema->get_origin_index_name_str()); hash_ret = index_name_map_.set_refactored(cutted_index_name_wrapper, table_schema, over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build index name hashmap failed", K(ret), K(hash_ret), "table_id", table_schema->get_table_id(), "databse_id", table_schema->get_database_id(), "index_name", table_schema->get_origin_index_name_str()); } } } else { // mysql mode or index is in recyclebin ObIndexSchemaHashWrapper index_name_wrapper( table_schema->get_tenant_id(), table_schema->get_database_id(), table_schema->get_table_name_str()); hash_ret = index_name_map_.set_refactored(index_name_wrapper, table_schema, over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build index name hashmap failed", K(ret), K(hash_ret), "table_id", table_schema->get_table_id(), "databse_id", table_schema->get_database_id(), "index_name", table_schema->get_table_name()); } } } else { LOG_INFO("table is", "table_id", table_schema->get_table_id(), "database_id", table_schema->get_database_id(), "table_name", table_schema->get_table_name_str()); ObTableSchemaHashWrapper table_name_wrapper(table_schema->get_tenant_id(), table_schema->get_database_id(), table_schema->get_session_id(), table_schema->get_name_case_mode(), table_schema->get_table_name_str()); hash_ret = table_name_map_.set_refactored(table_name_wrapper, table_schema, over_write); if (OB_SUCCESS != hash_ret) { ret = OB_HASH_EXIST == hash_ret ? OB_SUCCESS : OB_ERR_UNEXPECTED; LOG_ERROR("build table name hashmap failed", K(ret), K(hash_ret), "table_id", table_schema->get_table_id(), "databse_id", table_schema->get_database_id(), "session_id", table_schema->get_session_id(), "name_case_mode", table_schema->get_name_case_mode(), "table_name", table_schema->get_table_name()); } if (OB_SUCC(ret)) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2100) { // do-nothing for liboblog } else if (OB_FAIL(add_foreign_keys_in_table( table_schema->get_simple_foreign_key_info_array(), over_write))) { LOG_WARN("add foreign keys info to a hash map failed", K(ret), K(table_schema->get_table_name_str())); } else { fk_cnt += table_schema->get_simple_foreign_key_info_array().count(); } } if (OB_SUCC(ret)) { if (ObSchemaService::g_liboblog_mode_ && GET_MIN_CLUSTER_VERSION() < CLUSTER_VERSION_2110) { // do-nothing for liboblog } else if (OB_FAIL( add_constraints_in_table(table_schema->get_simple_constraint_info_array(), over_write))) { LOG_WARN("add constraint info to a hash map failed", K(ret), K(table_schema->get_table_name_str())); } else { cst_cnt += table_schema->get_simple_constraint_info_array().count(); } } } } } } } return ret; } // only use in oracle mode int ObSchemaMgr::get_idx_schema_by_origin_idx_name(const uint64_t tenant_id, const uint64_t database_id, const common::ObString& ori_index_name, const ObSimpleTableSchemaV2*& table_schema) const { int ret = OB_SUCCESS; table_schema = NULL; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == database_id || ori_index_name.empty()) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), K(tenant_id), K(database_id), K(ori_index_name)); } else { ObSimpleTableSchemaV2* tmp_schema = NULL; const ObIndexSchemaHashWrapper index_name_wrapper(tenant_id, database_id, ori_index_name); int hash_ret = index_name_map_.get_refactored(index_name_wrapper, tmp_schema); if (OB_SUCCESS == hash_ret) { if (OB_ISNULL(tmp_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret), K(tmp_schema)); } else { table_schema = tmp_schema; } } else if (OB_HASH_NOT_EXIST == hash_ret) { // do nothing } } return ret; } void ObSchemaMgr::dump() const { int ret = OB_SUCCESS; int tmp_ret = OB_SUCCESS; int64_t schema_count = 0; int64_t schema_size = 0; tmp_ret = get_schema_count(schema_count); ret = OB_SUCC(ret) ? tmp_ret : ret; tmp_ret = get_schema_size(schema_size); LOG_INFO("[SCHEMA_STATISTICS] dump schema_mgr", K(tmp_ret), K_(tenant_id), K_(schema_version), K(schema_count), K(schema_size)); #define DUMP_SCHEMA(SCHEMA, SCHEMA_TYPE, SCHEMA_ITER) \ { \ for (SCHEMA_ITER iter = SCHEMA##_infos_.begin(); iter != SCHEMA##_infos_.end(); iter++) { \ SCHEMA_TYPE* schema = *iter; \ if (NULL == schema) { \ LOG_INFO("NULL ptr", K(schema)); \ } else { \ LOG_INFO(#SCHEMA, K(*schema)); \ } \ } \ } // DUMP_SCHEMA(tenant, ObSimpleTenantSchema, ConstTenantIterator); // DUMP_SCHEMA(user, ObSimpleUserSchema, ConstUserIterator); // DUMP_SCHEMA(database, ObSimpleDatabaseSchema, ConstDatabaseIterator); // DUMP_SCHEMA(tablegroup, ObSimpleTablegroupSchema, ConstTablegroupIterator); // DUMP_SCHEMA(table, ObSimpleTableSchemaV2, ConstTableIterator); // DUMP_SCHEMA(index, ObSimpleTableSchemaV2, ConstTableIterator); #undef DUMP_SCHEMA } int ObSchemaMgr::get_schema_size(int64_t& total_size) const { int ret = OB_SUCCESS; ObArray<ObSchemaStatisticsInfo> schema_infos; total_size = 0; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_FAIL(get_schema_statistics(schema_infos))) { LOG_WARN("fail to get schema size", K(ret)); } else { for (int64_t i = 0; OB_SUCC(ret) && i < schema_infos.size(); i++) { ObSchemaStatisticsInfo& schema_statistics = schema_infos.at(i); if (schema_statistics.schema_type_ < TENANT_SCHEMA || schema_statistics.schema_type_ >= OB_MAX_SCHEMA) { ret = OB_ERR_UNEXPECTED; LOG_WARN("invalid schema type", K(ret), K(schema_statistics)); } else { total_size += schema_statistics.size_; } } } return ret; } int ObSchemaMgr::get_schema_statistics(common::ObIArray<ObSchemaStatisticsInfo>& schema_infos) const { int ret = OB_SUCCESS; ObSchemaStatisticsInfo schema_info; schema_infos.reset(); if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else if (OB_FAIL(get_tenant_statistics(schema_info))) { LOG_WARN("fail to get tenant statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(get_user_statistics(schema_info))) { LOG_WARN("fail to get user statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(get_database_statistics(schema_info))) { LOG_WARN("fail to get database statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(get_tablegroup_statistics(schema_info))) { LOG_WARN("fail to get tablegroup statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(get_table_statistics(schema_info))) { LOG_WARN("fail to get table statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(outline_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get outline statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(priv_mgr_.get_schema_statistics(TABLE_PRIV, schema_info))) { LOG_WARN("fail to get table priv statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(priv_mgr_.get_schema_statistics(DATABASE_PRIV, schema_info))) { LOG_WARN("fail to get database priv statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(synonym_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get synonym statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(udf_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get udf statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(sequence_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get sequence statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(sys_variable_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get sys variable statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(profile_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get profile statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(priv_mgr_.get_schema_statistics(SYS_PRIV, schema_info))) { LOG_WARN("fail to get system priv statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(priv_mgr_.get_schema_statistics(OBJ_PRIV, schema_info))) { LOG_WARN("fail to get obj priv statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } else if (OB_FAIL(dblink_mgr_.get_schema_statistics(schema_info))) { LOG_WARN("fail to get dblink statistics", K(ret)); } else if (OB_FAIL(schema_infos.push_back(schema_info))) { LOG_WARN("fail to push back schema statistics", K(ret), K(schema_info)); } return ret; } int ObSchemaMgr::get_tenant_statistics(ObSchemaStatisticsInfo& schema_info) const { int ret = OB_SUCCESS; schema_info.reset(); schema_info.schema_type_ = TENANT_SCHEMA; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_info.count_ = tenant_infos_.size(); for (ConstTenantIterator it = tenant_infos_.begin(); OB_SUCC(ret) && it != tenant_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } } return ret; } int ObSchemaMgr::get_user_statistics(ObSchemaStatisticsInfo& schema_info) const { int ret = OB_SUCCESS; schema_info.reset(); schema_info.schema_type_ = USER_SCHEMA; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_info.count_ = user_infos_.size(); for (ConstUserIterator it = user_infos_.begin(); OB_SUCC(ret) && it != user_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } } return ret; } int ObSchemaMgr::get_database_statistics(ObSchemaStatisticsInfo& schema_info) const { int ret = OB_SUCCESS; schema_info.reset(); schema_info.schema_type_ = DATABASE_SCHEMA; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_info.count_ = database_infos_.size(); for (ConstDatabaseIterator it = database_infos_.begin(); OB_SUCC(ret) && it != database_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } } return ret; } int ObSchemaMgr::get_tablegroup_statistics(ObSchemaStatisticsInfo& schema_info) const { int ret = OB_SUCCESS; schema_info.reset(); schema_info.schema_type_ = TABLEGROUP_SCHEMA; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_info.count_ = tablegroup_infos_.size(); for (ConstTablegroupIterator it = tablegroup_infos_.begin(); OB_SUCC(ret) && it != tablegroup_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } } return ret; } int ObSchemaMgr::get_table_statistics(ObSchemaStatisticsInfo& schema_info) const { int ret = OB_SUCCESS; schema_info.reset(); schema_info.schema_type_ = TABLE_SCHEMA; int64_t size = 0; if (!check_inner_stat()) { ret = OB_NOT_INIT; LOG_WARN("not init", K(ret)); } else { schema_info.count_ = table_infos_.size() + index_infos_.size(); for (ConstTableIterator it = table_infos_.begin(); OB_SUCC(ret) && it != table_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } for (ConstTableIterator it = index_infos_.begin(); OB_SUCC(ret) && it != index_infos_.end(); it++) { if (OB_ISNULL(*it)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("schema is null", K(ret)); } else { schema_info.size_ += (*it)->get_convert_size(); } } } return ret; } } // end of namespace schema } // end of namespace share } // end of namespace oceanbase
41.02622
120
0.648174
wangcy6
8a0e09ff550a1aa92c0493279bdc6db8d3d6c2c0
1,863
cpp
C++
03-02-2018-lca/lca_rmq.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
03-02-2018-lca/lca_rmq.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
03-02-2018-lca/lca_rmq.cpp
rusucosmin/eMag---Hai-la-Olimpiada-
8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> using namespace std; const int maxn = 100005; const int maxk = 20; int n, m, dad[maxn], deep[maxn], euler[maxn * 2], K, euler_lvl[maxn * 2]; int rmq[maxk][2 * maxn], lg[2 * maxn], fst[maxn]; vector <int> g[maxn]; void dfs(int node) { euler[++ K] = node; euler_lvl[K] = deep[node]; fst[node] = K; for(auto it : g[node]) { deep[it] = deep[node] + 1; dfs(it); euler[++ K] = node; euler_lvl[K] = deep[node]; } } int lca(int x, int y) { x = fst[x]; y = fst[y]; if(x > y) { swap(x, y); } // x <= y int k = lg[y - x + 1]; int ind1 = rmq[k][x]; // [x, x + 2^k - 1] int ind2 = rmq[k][y - (1 << k) + 1]; // [y - 2^k + 1, y] // x + 2 ^ k - 1 - (y - 2^k + 1) = // x + 2 ^ k - 1 - y + 2^k - 1 = // x + 2 ^ k - 1 - y + 2^k - 1 = // -(y - x + 1) + 2 ^ (k + 1) - 1 // - 2 ^ k + 2 ^ (k + 1) - 1 // 2 ^ k - 1 >= 0 // k >= 1 // k = [log2(y - x + 1)] // 2 ^ k ~= y - x + 1 if(euler_lvl[ind1] < euler_lvl[ind2]) { return euler[ind1]; } else { return euler[ind2]; } } int main() { ifstream fin("lca.in"); ofstream fout("lca.out"); fin >> n >> m; for(int i = 2; i <= n; ++ i) { int x; fin >> x; g[x].push_back(i); } deep[1] = 1; dfs(1); // preprocesare rmq for(int i = 1; i <= K; ++ i) { rmq[0][i] = i; // retinem INDICI in rmq } for(int i = 2; i <= K; ++ i) { lg[i] = lg[i >> 1] + 1; } for(int k = 1; (1 << k) <= K; ++ k) { for(int i = 1; i + (1 << k) - 1 <= K; ++ i) { int ind1 = rmq[k - 1][i]; int ind2 = rmq[k - 1][i + (1 << (k - 1))]; if(euler_lvl[ind1] > euler_lvl[ind2]) { rmq[k][i] = ind2; } else { rmq[k][i] = ind1; } } } while(m --) { int x, y; fin >> x >> y; fout << lca(x, y) << '\n'; } return 0; }
18.264706
73
0.421363
rusucosmin
8a0f7997112d1c424a2bc17f1baf02b54521cfe1
5,318
cpp
C++
ga/module/encoder-nvenc/NvEncoderCommandParser.cpp
zhongguocs/gaminganywhere
b96d09b5366caef75e6796040c0e5ebc0ad30680
[ "BSD-3-Clause" ]
756
2015-01-01T17:34:34.000Z
2022-03-24T14:35:25.000Z
ga/module/encoder-nvenc/NvEncoderCommandParser.cpp
zhongguocs/gaminganywhere
b96d09b5366caef75e6796040c0e5ebc0ad30680
[ "BSD-3-Clause" ]
81
2015-03-22T06:14:36.000Z
2022-02-20T18:45:00.000Z
ga/module/encoder-nvenc/NvEncoderCommandParser.cpp
zhongguocs/gaminganywhere
b96d09b5366caef75e6796040c0e5ebc0ad30680
[ "BSD-3-Clause" ]
303
2015-01-01T11:18:16.000Z
2022-01-18T20:52:27.000Z
//////////////////////////////////////////////////////////////////////////// // // Copyright 1993-2014 NVIDIA Corporation. All rights reserved. // // Please refer to the NVIDIA end user license agreement (EULA) associated // with this source code for terms and conditions that govern your use of // this software. Any use, reproduction, disclosure, or distribution of // this software and related documentation outside the terms of the EULA // is strictly prohibited. // //////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <string> #include <iostream> #include <fstream> #include "NvEncoderLowLatency.h" void CNvEncoderLowLatency::ParseEncodeCommandFile(char *fileName) { std::fstream input(fileName, std::ios::in); std::string line; int lineNumber = 0; long value = 0; const std::string delims(" \t\n"); if (strlen(fileName) == 0) { PRINTERR("no encode command file available\n"); } else if (!input.is_open()) { PRINTERR("Can't open %s\n", fileName); exit(1); } else { int cmdIdx = 0; while (std::getline(input, line)) { lineNumber++; // check if a line is empty size_t beg_idx = line.find_first_not_of(delims, 0); // check if a line is a comment or empty if (beg_idx == std::string::npos || line[beg_idx] == '#') { continue; } char *begin, *end; begin = end = NULL; value = std::strtol(line.c_str(), &begin, 10); if (line.c_str() != begin) { m_nvEncCommands[cmdIdx].nvEncCommand = (NvEncLowLatencyCmd) value; } else { PRINTERR("Invalid command\n"); continue; } value = std::strtol(begin, &end, 10); if (begin != end) { m_nvEncCommands[cmdIdx].frameNumber = value; } else { PRINTERR("Invalid frame number\n"); continue; } begin = end; int numParams = 0; while (*begin && numParams < MAX_ENC_COMMAND_PARAMS) { value = strtol(begin, &end, 10); if (begin != end) { m_nvEncCommands[cmdIdx].params[numParams] = value; numParams++; } else { PRINTERR("Invalid parameter(s)\n"); break; } begin = end; } m_nvEncCommands[cmdIdx].numParams = numParams; cmdIdx++; } m_NumNvEncCommands = cmdIdx; } } void CNvEncoderLowLatency::CheckAndInitNvEncCommand(uint32_t curFrameIdx, NvEncPictureCommand *pEncPicCommand) { if (!pEncPicCommand) return; memset(pEncPicCommand, 0, sizeof(NvEncPictureCommand)); for (uint32_t cmdIdx = m_CurEncCommandIdx; cmdIdx < m_NumNvEncCommands; cmdIdx++) { if (m_nvEncCommands[cmdIdx].frameNumber == curFrameIdx) { if (m_nvEncCommands[cmdIdx].nvEncCommand == NV_ENC_DYNAMIC_RESOLUTION_CHANGE) { pEncPicCommand->bResolutionChangePending = true; pEncPicCommand->newWidth = m_nvEncCommands[cmdIdx].params[0]; pEncPicCommand->newHeight = m_nvEncCommands[cmdIdx].params[1]; } else if (m_nvEncCommands[cmdIdx].nvEncCommand == NV_ENC_DYNAMIC_BITRATE_CHANGE) { pEncPicCommand->bBitrateChangePending = true; pEncPicCommand->newBitrate = m_nvEncCommands[cmdIdx].params[0]; pEncPicCommand->newVBVSize = m_nvEncCommands[cmdIdx].params[1]; } else if (m_nvEncCommands[cmdIdx].nvEncCommand == NV_ENC_FORCE_IDR) { pEncPicCommand->bForceIDR = true; } else if (m_nvEncCommands[cmdIdx].nvEncCommand == NV_ENC_FORCE_INTRA_REFRESH) { pEncPicCommand->bForceIntraRefresh = true; pEncPicCommand->intraRefreshDuration = m_nvEncCommands[cmdIdx].params[0]; } else if (m_nvEncCommands[cmdIdx].nvEncCommand == NV_ENC_INVALIDATE_REFRENCE_FRAME) { pEncPicCommand->bInvalidateRefFrames = true; pEncPicCommand->numRefFramesToInvalidate = m_nvEncCommands[cmdIdx].numParams; for (uint32_t j = 0; j < pEncPicCommand->numRefFramesToInvalidate; j++) { pEncPicCommand->refFrameNumbers[j] = m_nvEncCommands[cmdIdx].params[j]; } } else { PRINTERR("Invalid Encode command = %d\n", m_nvEncCommands[cmdIdx].nvEncCommand); } } } } NVENCSTATUS CNvEncoderLowLatency::ProcessRefFrameInvalidateCommands(const NvEncPictureCommand *pEncPicCommand) { NVENCSTATUS nvStatus = NV_ENC_SUCCESS; nvStatus = m_pNvHWEncoder->NvEncInvalidateRefFrames(pEncPicCommand); return nvStatus; }
35.218543
111
0.535728
zhongguocs
8a123de67de9954635b45b6c38c8489ea9fb35d6
3,640
hxx
C++
image_loader.hxx
Sigill/itkVectorImageComposer
899f743eb62e05323e8c8ea998b5df7ee59a55cd
[ "Apache-2.0" ]
null
null
null
image_loader.hxx
Sigill/itkVectorImageComposer
899f743eb62e05323e8c8ea998b5df7ee59a55cd
[ "Apache-2.0" ]
null
null
null
image_loader.hxx
Sigill/itkVectorImageComposer
899f743eb62e05323e8c8ea998b5df7ee59a55cd
[ "Apache-2.0" ]
null
null
null
#ifndef IMAGE_LOADER_HXX #define IMAGE_LOADER_HXX #include "image_loader.h" #include <ostream> #include <algorithm> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include "log4cxx/logger.h" #include "itkImageFileReader.h" #include "itkImageSeriesReader.h" template <typename TImageType> typename TImageType::Pointer ImageLoader<TImageType>::load(const std::string filename) { log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); LOG4CXX_INFO(logger, "Loading image \"" << filename << "\""); try { boost::filesystem::path path(filename); if(boost::filesystem::exists(path)) { typename Self::ImageType::Pointer img; if(boost::filesystem::is_directory(path)) { LOG4CXX_DEBUG(logger, path << " is a folder"); img = loadImageSerie(filename); } else { LOG4CXX_DEBUG(logger, path << " is a file"); img = loadImage(filename); } LOG4CXX_INFO(logger, "Image " << path << " loaded"); return img; } else { std::stringstream err; err << "\"" << filename << "\" does not exists"; LOG4CXX_FATAL(logger, err.str()); throw ImageLoadingException(err.str()); } } catch(boost::filesystem::filesystem_error &ex) { std::stringstream err; err << filename << " cannot be read (" << ex.what() << ")" << std::endl; throw ImageLoadingException(err.str()); } } template <typename TImageType> typename TImageType::Pointer ImageLoader<TImageType>::loadImage(const std::string filename) { typedef itk::ImageFileReader< typename Self::ImageType > ImageReader; typename ImageReader::Pointer reader = ImageReader::New(); reader->SetFileName(filename); try { reader->Update(); } catch( itk::ExceptionObject &ex ) { std::stringstream err; err << "ITK is unable to load the image \"" << filename << "\" (" << ex.what() << ")"; throw ImageLoadingException(err.str()); } return reader->GetOutput(); } template <typename TImageType> typename TImageType::Pointer ImageLoader<TImageType>::loadImageSerie(const std::string filename) { typedef itk::ImageSeriesReader< typename Self::ImageType > ImageSeriesReader; typename ImageSeriesReader::FileNamesContainer filenames; typename ImageSeriesReader::Pointer reader = ImageSeriesReader::New(); log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); try { boost::filesystem::path path(filename); boost::regex pattern(".*\\.((?:png)|(?:bmp)|(?:jpe?g))", boost::regex::icase); typedef std::vector< boost::filesystem::path > path_list; path_list slices; std::copy(boost::filesystem::directory_iterator(path), boost::filesystem::directory_iterator(), std::back_inserter(slices)); std::sort(slices.begin(), slices.end()); for( path_list::const_iterator it(slices.begin()) ; it != slices.end() ; ++it) { boost::smatch match; if( !boost::regex_match( (*it).filename().string(), match, pattern ) ) continue; LOG4CXX_DEBUG(logger, "Loading slice \"" << boost::filesystem::absolute(*it).string() << "\""); filenames.push_back(boost::filesystem::absolute(*it).string()); } } catch(boost::filesystem::filesystem_error &ex) { std::stringstream err; err << filename << " cannot be read (" << ex.what() << ")" << std::endl; throw ImageLoadingException(err.str()); } std::sort(filenames.begin(), filenames.end()); reader->SetFileNames(filenames); try { reader->Update(); } catch( itk::ExceptionObject &ex ) { std::stringstream err; err << "ITK is unable to load the image serie located in \"" << filename << "\" (" << ex.what() << ")"; throw ImageLoadingException(err.str()); } return reader->GetOutput(); } #endif /* IMAGE_LOADER_HXX */
25.815603
126
0.682418
Sigill
8a12ef3f57a57c7bc0255930d13bd156353dbf09
500
hpp
C++
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
48
2019-05-14T10:07:08.000Z
2021-04-08T08:26:20.000Z
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
null
null
null
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
4
2019-11-18T15:35:32.000Z
2021-12-02T05:23:04.000Z
/** * Copyright Žiga Sajovic, XLAB 2019 * Distributed under the MIT License * * https://github.com/ZigaSajovic/CppML **/ #ifndef CPPML_VALUE_HPP #define CPPML_VALUE_HPP namespace ml { /* * Value: * Represents a typed value * */ template <typename T, T t> struct Value { using type = T; static constexpr T value = t; }; template <int N> using Int = Value<int, N>; template <bool N> using Bool = Value<bool, N>; template <char C> using Char = Value<char, C>; }; // namespace ml #endif
17.857143
46
0.674
changjurhee
8a1356ae8ff9ef2c3dfe56fc3070aadc5dcca86d
1,762
cpp
C++
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.UserConstructionScript // () void ATek_CloningChamber_Placement_Emitter_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.UserConstructionScript"); ATek_CloningChamber_Placement_Emitter_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ATek_CloningChamber_Placement_Emitter_C::ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter"); ATek_CloningChamber_Placement_Emitter_C_ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.912281
191
0.749716
2bite
8a143237f683fb14868fa0580fee67ee7e8ff0ed
973
cpp
C++
0901-1000/1000-Minimum Cost to Merge Stones/1000-Minimum Cost to Merge Stones.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0901-1000/1000-Minimum Cost to Merge Stones/1000-Minimum Cost to Merge Stones.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0901-1000/1000-Minimum Cost to Merge Stones/1000-Minimum Cost to Merge Stones.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: int mergeStones(vector<int>& stones, int K) { if ((stones.size() -1) % (K - 1)) { return -1; } vector<int> presum(1 + stones.size()); for (int i = 0; i < stones.size(); ++i) { presum[i + 1] = presum[i] + stones[i]; } vector<vector<int>> dp(stones.size(), vector<int>(stones.size())); for (int l = K; l <= stones.size(); ++l) { for (int start = 0; start <= stones.size() - l; ++start) { int end = start + l - 1; dp[start][end] = INT_MAX; for (int mid = start; mid < end; mid += K - 1) { dp[start][end] = min(dp[start][end], dp[start][mid] + dp[mid + 1][end]); } if ((end - start) % (K - 1) == 0) { dp[start][end] += presum[end + 1] - presum[start]; } } } return dp[0].back(); } };
31.387097
92
0.405961
jiadaizhao
8a16c01655e531689e15acb938a2ff977093b8c5
2,772
cc
C++
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
2
2019-08-27T04:18:45.000Z
2021-04-20T23:14:24.000Z
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
null
null
null
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
null
null
null
#include "Time.h" #include "Parameters.h" Time::Time(Parameters *prms, float main, float overtime, int stones) : params(prms), base_main(main), base_overtime(overtime), base_stones(stones) { this->setupTimeForColors(); } Time::Time(Parameters *prms, float main) : params(prms), base_main(main), base_overtime(0), base_stones(0) { this->setupTimeForColors(); } void Time::setupTimeForColors() { if (base_main>0) { black_time_left=base_main; white_time_left=base_main; black_stones_left=0; white_stones_left=0; } else if (this->isCanadianOvertime()) { black_time_left=base_overtime; white_time_left=base_overtime; black_stones_left=base_stones; white_stones_left=base_stones; } else { black_time_left=0; white_time_left=0; black_stones_left=0; white_stones_left=0; } } float *Time::timeLeftForColor(Go::Color col) const { if (col==Go::BLACK) return (float *)&black_time_left; else return (float *)&white_time_left; } int *Time::stonesLeftForColor(Go::Color col) const { if (col==Go::BLACK) return (int *)&black_stones_left; else return (int *)&white_stones_left; } void Time::useTime(Go::Color col, float timeused) { if (timeused>0 && !this->isNoTiming()) { float *timeleft=this->timeLeftForColor(col); *timeleft-=timeused; if (*timeleft<0) // time finished or starting overtime { if (this->isAbsoluteTiming() || this->inOvertime(col)) // time run out *timeleft=1; else // entering overtime { *timeleft+=base_overtime; *(this->stonesLeftForColor(col))=base_stones; } } else if (this->inOvertime(col)) { (*(this->stonesLeftForColor(col)))--; if (*(this->stonesLeftForColor(col))==0) { *timeleft=base_overtime; *(this->stonesLeftForColor(col))=base_stones; } } } } void Time::updateTimeLeft(Go::Color col, float time, int stones) { *(this->timeLeftForColor(col))=time; *(this->stonesLeftForColor(col))=stones; } float Time::getAllocatedTimeForNextTurn(Go::Color col) const { if (this->isNoTiming()) return 0; else { if (this->inOvertime(col)) { float time_per_move=((this->timeLeft(col)-params->time_buffer)/this->stonesLeft(col)); if (time_per_move<params->time_move_minimum) time_per_move=params->time_move_minimum; return time_per_move; } else { float time_left=this->timeLeft(col); time_left-=params->time_buffer; float time_per_move=time_left/params->time_k; //allow much more time in beginning if (time_per_move<params->time_move_minimum) time_per_move=params->time_move_minimum; return time_per_move; } } }
22.536585
92
0.65873
skroon
8a1c02917a8be16ab96fc64890730c6cee695f6a
554
cpp
C++
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
#include "../../../include/game_handler.h" void * game_handler::run() { game_msg * msg; std::string message; std::cout << "[+] Thread game_handler running " << self() << "\n"; for(int i = 0; ;i++) { msg = _msg_pool.remove(); message = msg->get_message(); game_player * user = msg->get_dest(); if(strcmp(message.c_str(),"EXIT") == 0) { std::cout << "[-] Thread game_handler " << self() << " terminating execution "<< "\n"; pthread_exit(NULL); } else user->send_message(message); } return NULL; }
19.785714
87
0.563177
mrbuzz
8a1ca7667f1c19acb49674d2687a78694185d17d
12,724
cpp
C++
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
4
2021-10-20T09:18:06.000Z
2022-03-27T05:08:26.000Z
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-11-05T03:28:41.000Z
2021-11-06T07:48:05.000Z
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-12-13T16:04:22.000Z
2021-12-13T16:04:22.000Z
/** * \file socket_manager.cpp * \brief 网络套接字管理类函数的实现 */ #include "pch.h" #include "socket_manager.h" #include "shstd.h" #include "system.pb.h" using namespace shstd::hashmap; /*#define SM_MAX_CONNECT_CNT (65000) //支持的最大连接数 static uint32 SMSocketHash(const int32 &nSock) { return (uint32)nSock; }*/ namespace network { /** * \brief 构造函数 */ CSocketManager::CSocketManager(void) { //m_pEventBase = NULL; } /** * \brief 析构函数 */ CSocketManager::~CSocketManager(void) { Release(); } /** * \brief 创建 * \param pEventBase 事件根基 * \return 创建成功返回true,否则返回false */ bool CSocketManager::Init(uint32 nLocalServerID, uint32 nTcpTimeOut, uint32 nSocketCnt, uint8 nLimitedLogEnable) { m_nLimitedLogEnable = nLimitedLogEnable; m_nSocketCnt = nSocketCnt; if(m_nSocketCnt > 0x7FFFF) { LOG(LT_ERROR, "Socket manager init| check socket count| cnt=%u", m_nSocketCnt); return false; } m_pSocket = new TcpSocket[m_nSocketCnt]; if(NULL == m_pSocket) { LOG(LT_ERROR, "Socket manager init| new tcp socket failed"); return false; } for(uint32 i = 0; i < m_nSocketCnt; i++) { m_pSocket[i].SetSocketManager(this); } m_nLocalServerID = nLocalServerID; m_nTcpTimeOut = nTcpTimeOut; LOG(LT_INFO, "Socket manager init succ| socket_cnt=%u| limited_log_enable=%d", m_nSocketCnt, m_nLimitedLogEnable); return true; } /** * \brief 释放 */ void CSocketManager::Release() { for(uint32 i = 0; i < m_nSocketCnt; i++) { m_pSocket[i].CloseConnect(); } } /** * \brief 开启服务器监听服务 * \param szAddr 监听IP地址 * \param nPort 监听端口 * \param pHandler 回调对象 * \return 开启成功返回true,失败返回false */ bool CSocketManager::Listen(const char *szAddr, uint16 nPort, bool bBinaryMode) { sockid nSockID = Socket::GlobalSocket(SOCK_STREAM, IPPROTO_TCP); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager listen failed| msg=%s", strerror(errno)); return false; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager listen| exceed socket| fd=%d", nSockID); close(nSockID); return false; } TcpSocket &oListener = m_pSocket[nSockID]; bool bSuccess = false; do { // 创建 if (!oListener.Create(nSockID)) { break; } // 保持连接 if (!oListener.SetKeepAlive(true)) { break; } // 不粘包 if (!oListener.SetNoDelay(true)) { break; } // 非阻塞模式 if (!oListener.SetNonBlock()) { break; } // 延时关闭 if (!oListener.SetLinger()) { break; } // 可重复使用 if (!oListener.SetReuse(true)) { break; } // 绑定 if (!oListener.Bind(szAddr, nPort)) { break; } // 开始监听 if (!oListener.Listen()) { break; } oListener.SetSocketHandler(NULL, bBinaryMode); CNotifyFd oNotify(NOTIFY_TYPE_LISTEN, oListener.GetSockID(), szAddr, nPort, "", 0, bBinaryMode, NULL); if(!CNetWorker::Instance()->GetAcceptThread()->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Listen failed| errno=%d| errmsg=%s|", errno, strerror(errno)); break; } bSuccess = true; } while (false); // 利用循环来处理判断 // 开启失败,关闭socket if (!bSuccess) { oListener.Close(); //不能调用Release, 导致多线程使用同一个event_base, 引起core return false; } LOG(LT_INFO, "Socket manager listen succ| fd=%d", oListener.GetSockID()); return true; } /** * \brief 连接服务器 * \param szAddr 服务器IP地址 * \param nPort 服务器端口 * \param pHandler 回调对象 * \return 连接成功返回true,失败返回false */ bool CSocketManager::Connect(const char *szAddr, uint16 nPort, ISocketHandler *pHandler, bool bBinaryMode) { sockid nSockID = Socket::GlobalSocket(SOCK_STREAM, IPPROTO_TCP); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager connect failed| msg=%s", strerror(errno)); return false; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager connect| exceed socket| fd=%d", nSockID); close(nSockID); return false; } CNotifyFd oNotify(NOTIFY_TYPE_CONNECT, nSockID, "", 0, szAddr, nPort, bBinaryMode, pHandler); if(!CNetWorker::Instance()->GetDataThread(nSockID)->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Socket manager accept new| notify failed| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); } else { LOG(LT_INFO, "Socket manager new connect| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); } return true; } /** * \brief 发送数据给单个连接对象 * \param pMsg 消息数据 * \param nLen 数据大小 * \param nRemoteFd 指定发送连接对象ID * \return 发送成功返回true,否则返回false */ void CSocketManager::Send(LISTSMG *p) { if(NULL == p) { return; } TcpSocket *pSocket = NULL; if(PKT_TYPE_DISCARD == p->cPacketType) { LOG(LT_INFO_TRANS, p->szTransID, "Socket manager send discard packet| fd=%d| unique_id=0x%x| pkt_type=%d", p->connfd, p->nUniqueID, p->cPacketType); } else if(NULL == (pSocket = GetTcpSocket(p->connfd))) { LOG(LT_ERROR_TRANS, p->szTransID, "Socket manager send| find socket failed| fd=%d| unique_id=0x%x", p->connfd, p->nUniqueID); } else if(!pSocket->SendMsg(p)) { LOG(LT_ERROR_TRANS, p->szTransID, "Socket manager send| do failed| fd=%d| unique_id=0x%x", p->connfd, p->nUniqueID); } CQUEUE_List::Instance()->SetNode(p, QUEUE_FREE); return; } /** * \brief 获得连接信息 * \param nFd 连接对象ID * \param strAddr 返回连接对象IP地址 * \param nPort 返回连接对象端口 * \param bLocal 是否获取本地连接信息 * \return 获取成功返回true,否则返回false */ bool CSocketManager::GetConnectInfo(int32 nFd, std::string &strAddr, uint16 &nPort) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } if(!pSocket->IsAcceptFd()) { strAddr = pSocket->GetLocalAddr(); nPort = pSocket->GetLocalPort(); } else { strAddr = pSocket->GetRemoteAddr(); nPort = pSocket->GetRemotePort(); } return true; } /** * \brief 设置连接对象消息回调 * \param nFd 连接ID * \param pHandler 回调对象 * \param bPkgLen 收发消息处理长度 */ void CSocketManager::SetSocketHandler(int32 nFd, ISocketHandler *pHandler, bool bPkgLen /*= true*/) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL != pSocket) { pSocket->SetSocketHandler(pHandler, bPkgLen); } } /** * \brief 判断指定连接是否处于连接状态 * \param nFd 连接ID * \return 连接中返回true,否则返回false */ bool CSocketManager::IsValidConnected(int32 nFd, uint32 nUniqueID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } if (!pSocket->IsValid()) { return false; } if(pSocket->GetUniqueID() != nUniqueID) { return false; } return true; } /** * \brief 关闭指定连接 * \param nFd 连接对象ID * \return 成功关闭返回true,否则返回false */ bool CSocketManager::CloseConnect(int32 nFd)//, uint32 nUniqueID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } /*else if(pSocket->GetUniqueID() != nUniqueID) { LOG(LT_ERROR, "Socket manager close check unique_id failed| fd=%d| close_unique_id=0x%x| unique_id=0x%x", nUniqueID, pSocket->GetUniqueID()); return false; }*/ pSocket->CloseConnect(); return true; } //获取连接的下一个TransID std::string CSocketManager::GetNextTransID(int32 nFd) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return std::string(""); } return pSocket->NextTransID(); } //设置注册ID bool CSocketManager::SetRemoteServerID(int32 nFd, uint32 nRemoteServerID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } pSocket->SetRemoteServerID(nRemoteServerID); return true; } /** * \brief 关闭所有连接 */ void CSocketManager::CloseAllConnect() { Lock l(&m_lock); for(uint32 i = 0; i < m_nSocketCnt; i++) { TcpSocket &oSocket = m_pSocket[i]; if(Socket::SOCK_STATE_LISTEN != oSocket.GetState()) { oSocket.CloseConnect(); } } } /** * \brief 获得连接 * \param nFd 连接ID * \return 连接对象 */ TcpSocket * CSocketManager::GetTcpSocket(int32 nFd) { if(nFd < 0 || (uint32)nFd >= m_nSocketCnt) { return NULL; } return &m_pSocket[nFd]; } /** * \brief 接收到新连接 * \param pListener 监听连接 * \return 新连接对象 */ void CSocketManager::OnAccept(TcpSocket *pListener) { assert(NULL != pListener); // 使用新的连接对象准备连接 sockaddr_in addrRemote; sockid nSockID = Socket::GlobalAccept(pListener->GetSockID(), addrRemote); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager accept failed| msg=%s", strerror(errno)); return ; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager accept| exceed socket| fd=%d", nSockID); close(nSockID); return; } CNotifyFd oNotify(NOTIFY_TYPE_ACCEPT, nSockID, pListener->GetLocalAddr().c_str(), pListener->GetLocalPort(), inet_ntoa(addrRemote.sin_addr), ntohs(addrRemote.sin_port), pListener->GetBinaryMode(), NULL); if(!CNetWorker::Instance()->GetDataThread(nSockID)->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Socket manager accept new| notify failed| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); close(nSockID); return; } LOG(LT_INFO, "Socket manager accept new socket| fd=%d| local_addr=%s:%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szLocalAddr, oNotify.m_nLocalPort, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); return; } /** * \brief 连接成功事件 * \param pSocket 连接成功的对象 * \return 成功返回true,否则返回false */ bool CSocketManager::OnConnect(TcpSocket *pSocket) { /*if (NULL == pSocket) { return false; } SERVERKEY sk(m_nLocalServerID); pSocket->SetUniqueID(GetSequence()); pSocket->SetTransID(sk.nType, sk.nInstID); */ return true; } /** * \brief 连接断开事件 * \param pSocket 断开连接的对象 * \return 成功返回true,否则返回false */ bool CSocketManager::OnClose(TcpSocket *pSocket) { if (NULL == pSocket) { return false; } LOG(LT_INFO, "Socket manager on close| fd=%d", pSocket->GetSockID()); return true; } uint32 CSocketManager::GetSequence() { uint32 nTime = time(NULL)%0xFFFF; Lock l(&m_lock); ++m_nSequence; return ((nTime << 16) + m_nSequence); } }
26.675052
160
0.530729
deeptexas-ai
8a1d20103c9724b90310138603b0ce1c0f513824
473
cpp
C++
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
101
2021-02-26T14:32:37.000Z
2022-03-16T18:46:37.000Z
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
null
null
null
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
30
2021-03-09T05:16:48.000Z
2022-03-16T21:16:33.000Z
class Solution { public: int numTilings(int n) { vector<long long> dp (n+1, 0); long long modulo=1000000007; dp[0]=1; dp[1]=1; for(int i=2; i<=n; i++){ dp[i]+=dp[i-1]; dp[i]%=modulo; dp[i]+=dp[i-2]; dp[i]%=modulo; for(int j=i-3; j>=0; j--){ dp[i]+=(2*dp[j]); dp[i]%=modulo; } } return dp[n]; } };
21.5
38
0.353066
bobsingh149
8a1e9c7a13fae2780526246fc2ed172f58ee3855
21,884
cpp
C++
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
#include "skpEvent.h" #include "skpEvent_p.h" #include "skpMallocPoolEx.h" #include "skpAutoFree.h" #include "skpLog.h" #define EPOLL_EVENT_LT 0 ///全部LT #define EPOLL_EVENT_ET 1 ///全部ET #define EPOLL_EVENT_LT_ET 2 ///LT ET一起支持 #define EPOLL_EVENT_TYPE EPOLL_EVENT_LT_ET #define NODE_TYPE_MAP 0 ///即使申请 #define NODE_TYPE_NODE 1 ///固定申请 #define NODE_TYPE_MORE 2 ///变长申请 #define NODE_TYPE NODE_TYPE_MORE #define IS_CHECK_ERROR 0 SkpEventPrivate::SkpEventPrivate() : SkpObjectDataPrivate() { skp_event_base_new(); } SkpEventPrivate::~SkpEventPrivate() { skp_event_base_free(); } void SkpEventPrivate::skp_event_base_new() { m_base.m_epfd = epoll_create(32000); SKP_ASSERT(m_base.m_epfd != -1); m_base.m_nodeSize = 0; m_base.m_nodeList = NULL; m_base.m_nodeChangeList = new SkpList(); m_base.m_nodeReadyList = new SkpList(); m_base.pool = new SkpMallocPoolEx(1024 * 1024); m_isThread = skp_false; } void SkpEventPrivate::skp_event_base_free() { ::close(m_base.m_epfd); skp_delete(m_base.m_nodeChangeList); skp_delete(m_base.m_nodeReadyList); m_base.m_nodeSize = 0; m_base.m_nodeList = NULL; skp_delete(m_base.pool); } void SkpEventPrivate::skp_event_base_loop() { skp_change_event(); int64 timer = 100; if(m_base.m_nodeReadyList->size() > 0) { timer = 0; } int nevents = 0; nevents = epoll_wait(m_base.m_epfd, m_base.m_events, sizeof(m_base.m_events) / sizeof(struct epoll_event), timer); if(!m_isThread) { skp_update_system_time_ms(skp_true); } for(int i = 0; i < nevents; ++i) { struct epoll_event *epollEvent = &m_base.m_events[i]; skp_epoll_node *node = (skp_epoll_node *)epollEvent->data.ptr; if ((epollEvent->events & (EPOLLERR|EPOLLHUP)) && (epollEvent->events & (EPOLLIN|EPOLLOUT)) == 0) { epollEvent->events |= EPOLLIN|EPOLLOUT; node->m_errorNumber++; } if(node->m_flags == EPOLLET) { skp_add_ready_node(node); if(epollEvent->events & EPOLLIN) { node->m_read.m_ready = 1; node->m_read.m_readyNumber++; } if(epollEvent->events & EPOLLOUT) { node->m_write.m_ready = 1; node->m_write.m_readyNumber++; } } else { if(epollEvent->events & EPOLLIN) { skp_epoll_data *read = &node->m_read; skp_event_callback(read); } if(epollEvent->events & EPOLLOUT) { skp_epoll_data *write = &node->m_write; skp_event_callback(write); } } } skp_ready_callback(); skp_min_tbtree(); } void SkpEventPrivate::skp_change_event() { skp_epoll_node *node = NULL; while((node = skp_remove_change_node())) { uint flags = 0; int op = 0; struct epoll_event ee; bool isDeleteNode = skp_false; if(node->m_read.m_state == skp::epoll_state_null && node->m_write.m_state == skp::epoll_state_null) { op = EPOLL_CTL_DEL; node->m_read.m_active = 0; node->m_write.m_active = 0; node->m_read.m_ready = 0; node->m_write.m_ready = 0; isDeleteNode = skp_true; } if(op != EPOLL_CTL_DEL) { if(node->m_read.m_active || node->m_write.m_active) { op = EPOLL_CTL_MOD; } else { op = EPOLL_CTL_ADD; } } if(node->m_read.m_state == skp::epoll_state_start) { flags |= EPOLLIN; node->m_read.m_active = skp_true; } else { node->m_read.m_ready = 0; } if(node->m_write.m_state == skp::epoll_state_start) { flags |= EPOLLOUT; node->m_write.m_active = skp_true; } else { node->m_write.m_ready = 0; } if(!node->m_read.m_ready && !node->m_write.m_ready) { skp_remove_ready_node(node); } flags |= node->m_flags; if(op != EPOLL_CTL_DEL) { if(node->m_oldFlags && node->m_oldFlags == flags) continue; node->m_oldFlags = flags; ee.events = flags; ee.data.ptr = node; } else { node->m_oldFlags = 0; ee.events = 0; ee.data.ptr = NULL; } int ret = epoll_ctl(m_base.m_epfd, op, node->m_fd, &ee); skpLogDebug_g("epoll change fd = %d, ret = %d\n", node->m_fd, ret); if(ret == -1) { if (op == EPOLL_CTL_MOD && errno == ENOENT) { skpLogError_g("epoll change EPOLL_CTL_ADD \n"); ret = epoll_ctl(m_base.m_epfd, EPOLL_CTL_ADD, node->m_fd, &ee); } else if (op == EPOLL_CTL_ADD && errno == EEXIST) { skpLogError_g("epoll change EPOLL_CTL_MOD \n"); ret = epoll_ctl(m_base.m_epfd, EPOLL_CTL_MOD, node->m_fd, &ee); } if(op != EPOLL_CTL_DEL) SKP_ASSERT(ret != -1); } if(isDeleteNode) { skp_remove_ready_node(node); skp_reset_node(node); } } } void SkpEventPrivate::skp_ready_callback() { if(!m_base.m_nodeReadyList->isEmpty()) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *node = (skp_epoll_node *)data; if(node->m_read.m_ready) { skp_epoll_data *read = &node->m_read; skp_event_callback(read); } if(node->m_write.m_ready) { skp_epoll_data *write = &node->m_write; skp_event_callback(write); } m_base.m_nodeReadyList->next(); if(!node->m_read.m_ready && !node->m_write.m_ready) { skp_remove_ready_node(node); } } } } void SkpEventPrivate::skp_event_callback(skp_epoll_data *data) { if(data->m_fd > 0 && (data->m_state == skp::epoll_state_start)) { data->m_callbackNumber++; data->m_updateTime = skp_get_system_time_ms(); if(!data->m_singleShot) { skp_delete_timeout(data); skp_event_delete(data); } (*(data->m_func))(data->m_fd, skp_false, data->m_arg); } } void SkpEventPrivate::skp_min_tbtree() { util_rbtree_node_t *rbNode = NULL; while((rbNode = m_base.m_rbtree.min()) && rbNode && rbNode->key <= skp_get_system_time_ms()) { skp_epoll_data *data = (skp_epoll_data *)rbNode->data; if(data->m_type != skp::epoll_type_timeout) { int64 key = data->m_rbNode->key; int64 updateTime = data->m_updateTime; int64 diff = key - updateTime; if(diff < 0) diff = 0; if(diff >= data->m_time) { skp_delete_timeout(data); if(data->m_singleShot) { skp_insert_timeout(data, data->m_time); } else { skp_event_delete(data); } if(data->m_fd > 0 && (data->m_state == skp::epoll_state_start)) { (*(data->m_func))(data->m_fd, skp_true, data->m_arg); } } else { int64 time = data->m_time - diff; skp_delete_timeout(data); skp_insert_timeout(data, time); data->m_updateTime = updateTime; } } else { skp_delete_timeout(data); if(data->m_singleShot) skp_insert_timeout(data, data->m_time); (*(data->m_func))(data->m_fd, skp_true, data->m_arg); } } } void SkpEventPrivate::skp_event_base_dispatch() { } void *SkpEventPrivate::skp_event_base_timeout(int64 time, skp_callback_function func, void *arg, bool singleShot) { SKP_ASSERT(time > 0); skp_epoll_data *timeout = skp_malloc_data(); timeout->m_type = skp::epoll_type_timeout; timeout->m_state = skp::epoll_state_start; timeout->m_time = time; timeout->m_func = func; timeout->m_arg = arg; timeout->m_singleShot = singleShot; skp_add_timeout(timeout); return timeout; } void *SkpEventPrivate::skp_event_base_read(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { skp_epoll_node *epollNode = skp_malloc_node(fd); if(epollNode->m_fd != 0 && epollNode->m_fd != fd) { SKP_ASSERT(skp_false); } SKP_ASSERT(epollNode->m_read.m_fd == 0); if(epollNode->m_fd == 0) { skp_reset_node(epollNode); epollNode->m_fd = fd; } if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT) { epollNode->m_flags = 0; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_ET) { epollNode->m_flags = EPOLLET; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT_ET) { if(isET) { epollNode->m_flags = EPOLLET; } } else { SKP_ASSERT(skp_false); } skp_add_change_node(epollNode); skp_epoll_data *read = &epollNode->m_read; read->m_type = skp::epoll_type_read; read->m_state = skp::epoll_state_start; read->m_fd = fd; read->m_time = time; read->m_func = func; read->m_arg = arg; read->m_singleShot = singleShot; skp_add_timeout(read); return read; } void *SkpEventPrivate::skp_event_base_write(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { skp_epoll_node *epollNode = skp_malloc_node(fd); if(epollNode->m_fd != 0 && epollNode->m_fd != fd) { SKP_ASSERT(skp_false); } SKP_ASSERT(epollNode->m_write.m_fd == 0); if(epollNode->m_fd == 0) { skp_reset_node(epollNode); epollNode->m_fd = fd; } if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT) { epollNode->m_flags = 0; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_ET) { epollNode->m_flags = EPOLLET; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT_ET) { if(isET) { epollNode->m_flags = EPOLLET; } } else { SKP_ASSERT(skp_false); } skp_add_change_node(epollNode); skp_epoll_data *write = &epollNode->m_write; write->m_type = skp::epoll_type_write; write->m_state = skp::epoll_state_start; write->m_fd = fd; write->m_time = time; write->m_func = func; write->m_arg = arg; write->m_singleShot = singleShot; skp_add_timeout(write); return write; } #define IS_ADD_TIMEOUT 0 void SkpEventPrivate::skp_event_delete(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_sub_timeout(event); } else { if(event->m_state != skp::epoll_state_stop) skp_change_node(event, skp::epoll_state_stop); #if IS_ADD_TIMEOUT skp_delete_timeout(event); #endif } } void SkpEventPrivate::skp_event_free(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_delete_timeout(event); skp_free_data(event); } else { if(event->m_state != skp::epoll_state_null) skp_change_node(event, skp::epoll_state_null); skp_delete_timeout(event); } } void SkpEventPrivate::skp_event_start(void *data, int64 time) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_UNUSED(time); SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_add_timeout(event); } else { if(event->m_state != skp::epoll_state_start) skp_change_node(event, skp::epoll_state_start); #if IS_ADD_TIMEOUT skp_add_timeout(event); #else if(event->m_time != time) { printf("event->m_time != time \n"); skp_delete_timeout(event); event->m_time = time; skp_add_timeout(event); } else { event->m_updateTime = skp_get_system_time_ms(); } #endif } } void SkpEventPrivate::skp_add_timeout(skp_epoll_data *event) { SKP_ASSERT(event); SKP_ASSERT(!event->m_rbNode); skp_insert_timeout(event, event->m_time); } void SkpEventPrivate::skp_sub_timeout(skp_epoll_data *event) { SKP_ASSERT(event); SKP_ASSERT(event->m_rbNode); skp_delete_timeout(event); } void SkpEventPrivate::skp_insert_timeout(skp_epoll_data *event, int64 time) { if(event->m_time > 0 && !event->m_rbNode) { event->m_updateTime = skp_get_system_time_ms(); int64 msec = skp_rbtree_time(event, time); util_rbtree_node_t *rbNode = m_base.m_rbtree.insert(msec, event); event->m_rbNode = rbNode; } } void SkpEventPrivate::skp_delete_timeout(skp_epoll_data *event) { if(event->m_rbNode) { m_base.m_rbtree.remove(event->m_rbNode); event->m_rbNode = NULL; } } int64 SkpEventPrivate::skp_rbtree_time(skp_epoll_data *event, int64 time) { SKP_UNUSED(event); int64 msec = time + skp_get_system_time_ms(); return msec; } bool SkpEventPrivate::skp_is_delete_timeout(skp_epoll_data *event) { if(event->m_rbNode) { int64 msec = skp_rbtree_time(event, event->m_time); if(msec != event->m_rbNode->key) return skp_true; } return skp_false; } void SkpEventPrivate::skp_change_node(skp_epoll_data *event, skp::epoll_state state) { skp_epoll_node *epollNode = event->m_node; if(!epollNode) { SKP_ASSERT(skp_false);; } skp_add_change_node(epollNode); event->m_state = state; } skp_epoll_data *SkpEventPrivate::skp_malloc_data() { skp_epoll_data *data = (skp_epoll_data *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_data)); return data; } skp_epoll_node *SkpEventPrivate::skp_malloc_node() { skp_epoll_node *node = (skp_epoll_node *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node)); return node; } skp_epoll_node *SkpEventPrivate::skp_malloc_node(int fd) { if (NODE_TYPE == NODE_TYPE_MAP) { skp_epoll_node *epollNode = NULL; auto iter = m_base.m_nodeMap.find(fd); if(iter != m_base.m_nodeMap.end()) { epollNode = iter->second; } else { epollNode = skp_malloc_node(); m_base.m_nodeMap.insert(std::pair<int, skp_epoll_node*>(fd, epollNode)); } return epollNode; } int size = m_base.m_nodeSize; if(m_base.m_nodeSize == 0) { if (NODE_TYPE == NODE_TYPE_NODE) { m_base.m_nodeSize = 1000; } else if (NODE_TYPE == NODE_TYPE_MORE) { m_base.m_nodeSize = 10000; } else { SKP_ASSERT(skp_false); return skp_null; } } if(fd >= m_base.m_nodeSize) { while(fd >= m_base.m_nodeSize) m_base.m_nodeSize = (m_base.m_nodeSize * 2); } if(m_base.m_nodeSize > size) { skp_epoll_node **nodeList = (skp_epoll_node **)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node *) * m_base.m_nodeSize); if(size > 0) { memcpy(nodeList, m_base.m_nodeList, sizeof(skp_epoll_node *) * size); skp_pool_free(m_base.pool, m_base.m_nodeList); } m_base.m_nodeList = nodeList; skp_epoll_node *node = (skp_epoll_node *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node) * (m_base.m_nodeSize - size)); int lenth = m_base.m_nodeSize - size; for(int i = 0; i < lenth; i++) { m_base.m_nodeList[i + size] = &node[i]; } } return m_base.m_nodeList[fd]; } void SkpEventPrivate::skp_free_data(skp_epoll_data *data) { if(data) { skp_pool_free(m_base.pool, data); } } void SkpEventPrivate::skp_free_node(skp_epoll_node *node) { if(node) { skp_pool_free(m_base.pool, node); } } void SkpEventPrivate::skp_reset_node(skp_epoll_node *node) { memset(node, 0x00, sizeof(skp_epoll_node)); node->m_read.m_node = node; node->m_write.m_node = node; } bool SkpEventPrivate::skp_add_change_node(skp_epoll_node *node) { SKP_ASSERT(node); if(!node->m_isChange) { node->m_isChange = skp_true; m_base.m_nodeChangeList->push_back(node, &node->m_nodeChange); return skp_true; } else { if(IS_CHECK_ERROR) { m_base.m_nodeChangeList->begin(); void *data = NULL; while((data = m_base.m_nodeChangeList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) return skp_false; m_base.m_nodeChangeList->next(); } SKP_ASSERT(skp_false); } } return skp_false; } skp_epoll_node *SkpEventPrivate::skp_remove_change_node() { if(m_base.m_nodeChangeList && !m_base.m_nodeChangeList->isEmpty()) { skp_epoll_node *node = (skp_epoll_node *)m_base.m_nodeChangeList->take_pop(); node->m_isChange = !node->m_isChange; return node; } return NULL; } void SkpEventPrivate::skp_add_ready_node(skp_epoll_node *node) { SKP_ASSERT(node); if(!node->m_isReady) { node->m_isReady = skp_true; m_base.m_nodeReadyList->push_pop(node, &node->m_nodeReady); } else { if(IS_CHECK_ERROR) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) return; m_base.m_nodeReadyList->next(); } SKP_ASSERT(skp_false); } } } void SkpEventPrivate::skp_remove_ready_node(skp_epoll_node *node) { SKP_ASSERT(node); if(node->m_isReady) { if(IS_CHECK_ERROR) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) break; m_base.m_nodeReadyList->next(); } if(!data) { SKP_ASSERT(skp_false); } } node->m_isReady = skp_false; m_base.m_nodeReadyList->remove(&node->m_nodeReady); } } void SkpEventPrivate::removeReadReady(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; if(event) { skp_epoll_node *node = event->m_node; if(node) node->m_read.m_ready = 0; } } void SkpEventPrivate::addReadReady(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; if(event) { skp_epoll_node *node = event->m_node; if(node) { skp_add_ready_node(node); node->m_read.m_ready = 1; } } } void SkpEventPrivate::skp_set_event_thread() { m_isThread = skp_true; } ///===========================SkpEvent SkpEvent::SkpEvent(SkpEventPrivate &d) : SkpObjectData(d) { } SkpEvent::~SkpEvent() { } void SkpEvent::loop() { SKP_D(SkpEvent); skpD->skp_event_base_loop(); } void SkpEvent::dispatch() { SKP_D(SkpEvent); skpD->skp_event_base_dispatch(); } void *SkpEvent::timeout(int64 time, skp_callback_function func, void *arg, bool singleShot) { SKP_D(SkpEvent); return skpD->skp_event_base_timeout(time, func, arg, singleShot); } void *SkpEvent::read(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { SKP_D(SkpEvent); return skpD->skp_event_base_read(fd, func, arg, singleShot, time, isET); } void * SkpEvent::write(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { SKP_D(SkpEvent); return skpD->skp_event_base_write(fd, func, arg, singleShot, time, isET); } void SkpEvent::stop(void *data) { SKP_D(SkpEvent); skpD->skp_event_delete(data); } void SkpEvent::free(void *data) { SKP_D(SkpEvent); skpD->skp_event_free(data); } void SkpEvent::start(void *data, int64 time) { SKP_D(SkpEvent); skpD->skp_event_start(data, time); } void SkpEvent::skp_break() { SKP_D(SkpEvent); skpD->skp_event_break(); } void *SkpEvent::skp_base() { SKP_D(SkpEvent); return skpD->skp_base(); } void SkpEvent::removeReadReady(void *data) { SKP_D(SkpEvent); skpD->removeReadReady(data); } void SkpEvent::addReadReady(void *data) { SKP_D(SkpEvent); skpD->addReadReady(data); } void SkpEvent::skp_set_event_thread() { SKP_D(SkpEvent); skpD->skp_set_event_thread(); }
27.218905
132
0.57919
yefy
8a21221e1ef0da6055b2f4d76c99b02d78331233
5,042
cpp
C++
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
// Copyright Ross MacGregor 2013 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "AsioExpress/pch.hpp" #include "AsioExpressConfig/config.hpp" #include "AsioExpress/Platform/DebugMessage.hpp" #include "AsioExpress/MessagePort/Ipc/ErrorCodes.hpp" #include "AsioExpress/MessagePort/Ipc/MessagePort.hpp" #include "AsioExpress/MessagePort/Ipc/private/IpcCommandConnect.hpp" #include "AsioExpress/MessagePort/Ipc/private/IpcCommandReceive.hpp" namespace AsioExpress { namespace MessagePort { namespace Ipc { MessagePort::MessagePort(boost::asio::io_service & ioService) : m_ioService(ioService) { } MessagePort::~MessagePort() { Disconnect(); } void MessagePort::Disconnect() { // Before allowing a disconnect, make sure any threads are completed. // if (m_receiveThread) m_receiveThread->Close(); if (m_sendThread) m_sendThread->Close(); // Queues can be just deleted and removed // if ( m_recvMessageQueue ) { m_recvMessageQueue.reset(); } if ( m_sendMessageQueue ) { m_recvMessageQueue.reset(); } // Delete the queues from the system // if ( !m_sendMessageQueueName.empty() ) { boost::interprocess::message_queue::remove(m_sendMessageQueueName.c_str()); m_sendMessageQueueName = ""; } if ( !m_recvMessageQueueName.empty() ) { boost::interprocess::message_queue::remove(m_recvMessageQueueName.c_str()); m_recvMessageQueueName = ""; } } void MessagePort::AsyncConnect( EndPoint endPoint, AsioExpress::CompletionHandler completionHandler) { IpcCommandConnect(endPoint, *this, completionHandler)(); } void MessagePort::AsyncSend( AsioExpress::MessagePort::DataBufferPointer buffer, AsioExpress::CompletionHandler completionHandler) { // Check that we're connected #ifdef DEBUG_IPC DebugMessage("MessagePort::AsyncSend: Sending message.\n"); #endif if ( !m_sendMessageQueue ) { #ifdef DEBUG_IPC DebugMessage("MessagePort::AsyncSend: No connection has been established!\n"); #endif AsioExpress::Error err( ErrorCode::Disconnected, "MessagePort::AsyncSend(): No connection has been established."); AsioExpress::CallCompletionHandler(m_ioService, completionHandler, err); return; } try { // Send the message or fail if queue is full m_sendThread->AsyncSend( buffer, 0, completionHandler); } catch(AsioExpress::CommonException const & e) { // Disconnect on serious send errors (other errors would result in errors // getting propagated back by completion handlers, but the connection still // being active) Disconnect(); // Call completion handler as it will not get called if exception is thrown AsioExpress::CallCompletionHandler(m_ioService, completionHandler, e.GetError()); } } void MessagePort::AsyncReceive( AsioExpress::MessagePort::DataBufferPointer buffer, AsioExpress::CompletionHandler completionHandler) { // Check that we're connected if ( !m_recvMessageQueue ) { AsioExpress::Error err( ErrorCode::Disconnected, "MessagePort::AsyncReceive(): No connection has been established."); AsioExpress::CallCompletionHandler(m_ioService, completionHandler, err); return; } // Receive the next message & copy to the buffer IpcCommandReceive(m_ioService, m_receiveThread, m_recvMessageQueue, buffer, completionHandler, 0)(); } AsioExpress::Error MessagePort::SetupWithMessageQueues(const std::string& sendQueue, const std::string& recvQueue) { Disconnect(); try { m_sendMessageQueueName = sendQueue; m_recvMessageQueueName = recvQueue; m_sendMessageQueue.reset(new boost::interprocess::message_queue(boost::interprocess::open_only, m_sendMessageQueueName.c_str())); m_recvMessageQueue.reset(new boost::interprocess::message_queue(boost::interprocess::open_only, m_recvMessageQueueName.c_str())); m_receiveThread.reset(new IpcReceiveThread(m_ioService, m_recvMessageQueue, IpcReceiveThread::EnablePing)); m_sendThread.reset(new IpcSendThread(m_ioService, m_sendMessageQueue, IpcSendThread::EnablePing)); } catch(boost::interprocess::interprocess_exception& ex) { Disconnect(); AsioExpress::Error err(boost::system::error_code( ex.get_native_error(), boost::system::get_system_category()), "MessagePort::SetupWithMessageQueues(): Unable to open client/server message queues."); return err; } return AsioExpress::Error(); } void MessagePort::SetMessagePortOptions() { } } // namespace Ipc } // namespace MessagePort } // namespace AsioExpress
28.011111
134
0.685244
suhao
8a21cf7896b3371bb278d275528697064f11dbae
5,784
cpp
C++
Source/bindings/v8/ScriptPromiseResolverTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Source/bindings/v8/ScriptPromiseResolverTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/bindings/v8/ScriptPromiseResolverTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/v8/ScriptPromiseResolver.h" #include "bindings/v8/ScriptPromise.h" #include "bindings/v8/V8Binding.h" #include <gtest/gtest.h> #include <v8.h> namespace WebCore { namespace { class Function : public ScriptFunction { public: static PassOwnPtr<Function> create(v8::Isolate* isolate, String* value) { return adoptPtr(new Function(isolate, value)); } virtual ScriptValue call(ScriptValue value) OVERRIDE { ASSERT(!value.isEmpty()); *m_value = toCoreString(value.v8Value()->ToString()); return value; } private: Function(v8::Isolate* isolate, String* value) : ScriptFunction(isolate), m_value(value) { } String* m_value; }; class ScriptPromiseResolverTest : public testing::Test { public: ScriptPromiseResolverTest() : m_scope(v8::Isolate::GetCurrent()) { m_resolver = ScriptPromiseResolver::create(m_scope.scriptState()); } virtual ~ScriptPromiseResolverTest() { // Run all pending microtasks here. isolate()->RunMicrotasks(); } v8::Isolate* isolate() { return m_scope.isolate(); } protected: RefPtr<ScriptPromiseResolver> m_resolver; V8TestingScope m_scope; }; TEST_F(ScriptPromiseResolverTest, initialState) { ScriptPromise promise = m_resolver->promise(); ASSERT_FALSE(promise.isEmpty()); String onFulfilled, onRejected; promise.then(Function::create(isolate(), &onFulfilled), Function::create(isolate(), &onRejected)); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); isolate()->RunMicrotasks(); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); } TEST_F(ScriptPromiseResolverTest, resolve) { ScriptPromise promise = m_resolver->promise(); ASSERT_FALSE(promise.isEmpty()); String onFulfilled, onRejected; promise.then(Function::create(isolate(), &onFulfilled), Function::create(isolate(), &onRejected)); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->resolve("hello"); EXPECT_TRUE(m_resolver->promise().isEmpty()); isolate()->RunMicrotasks(); EXPECT_EQ("hello", onFulfilled); EXPECT_EQ(String(), onRejected); } TEST_F(ScriptPromiseResolverTest, reject) { ScriptPromise promise = m_resolver->promise(); ASSERT_FALSE(promise.isEmpty()); String onFulfilled, onRejected; promise.then(Function::create(isolate(), &onFulfilled), Function::create(isolate(), &onRejected)); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->reject("hello"); EXPECT_TRUE(m_resolver->promise().isEmpty()); isolate()->RunMicrotasks(); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ("hello", onRejected); } TEST_F(ScriptPromiseResolverTest, resolveOverResolve) { ScriptPromise promise = m_resolver->promise(); ASSERT_FALSE(promise.isEmpty()); String onFulfilled, onRejected; promise.then(Function::create(isolate(), &onFulfilled), Function::create(isolate(), &onRejected)); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->resolve("hello"); EXPECT_TRUE(m_resolver->promise().isEmpty()); isolate()->RunMicrotasks(); EXPECT_EQ("hello", onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->resolve("world"); isolate()->RunMicrotasks(); EXPECT_EQ("hello", onFulfilled); EXPECT_EQ(String(), onRejected); } TEST_F(ScriptPromiseResolverTest, rejectOverResolve) { ScriptPromise promise = m_resolver->promise(); ASSERT_FALSE(promise.isEmpty()); String onFulfilled, onRejected; promise.then(Function::create(isolate(), &onFulfilled), Function::create(isolate(), &onRejected)); EXPECT_EQ(String(), onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->resolve("hello"); EXPECT_TRUE(m_resolver->promise().isEmpty()); isolate()->RunMicrotasks(); EXPECT_EQ("hello", onFulfilled); EXPECT_EQ(String(), onRejected); m_resolver->reject("world"); isolate()->RunMicrotasks(); EXPECT_EQ("hello", onFulfilled); EXPECT_EQ(String(), onRejected); } } // namespace } // namespace WebCore
30.765957
102
0.7111
quanganh2627
8a23faa51086448e9c124cfbce896418e4d8eaf3
31,397
cpp
C++
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
8d483a87d302370df770d47d311d16e95d6e3951
[ "MIT" ]
30
2021-09-18T15:50:30.000Z
2022-03-25T14:12:57.000Z
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
3fde017d67f6673205d0e7ff3de7cf2a572a6aec
[ "MIT" ]
3
2021-11-22T11:11:42.000Z
2021-12-11T12:28:26.000Z
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
8d483a87d302370df770d47d311d16e95d6e3951
[ "MIT" ]
2
2022-01-11T02:50:04.000Z
2022-01-22T14:04:33.000Z
#include "api/jsonutils.h" #include "api/message.h" #include "api/attachment.h" #include "api/user.h" #include "api/overwrite.h" #include "api/channel.h" #include "api/thread.h" #include "api/team.h" #include "api/application.h" #include "api/guildmember.h" #include "api/voice.h" #include "api/guild.h" #include "api/client.h" #include "api/presence.h" #include <string> #include <QJsonObject> namespace Api { std::string *getString(QJsonObject jsonObj, const char *key) { std::string str = jsonObj[QString(key)].toString().toUtf8().constData(); return new std::string(str); } std::vector<std::string> *getStringsFromJson(QJsonArray jsonArray) { std::vector<std::string> *strings = new std::vector<std::string>; // Filling the vector for (int i = 0 ; i < jsonArray.size() ; i++) { strings->push_back(jsonArray[i].toString().toUtf8().constData()); } return strings; } // All the specialization of 'unmarshal' template <> void unmarshal<User>(QJsonObject jsonObj, User **object) { *object = new User { getString(jsonObj, "username"), getString(jsonObj, "discriminator"), getString(jsonObj, "avatar"), getString(jsonObj, "locale"), getString(jsonObj, "email"), getString(jsonObj, "id"), jsonObj["flags"].toInt(-1), jsonObj["premium_type"].toInt(-1), jsonObj["public_flags"].toInt(-1), jsonObj["bot"].toBool(), jsonObj["system"].toBool(), jsonObj["mfa_enabled"].toBool(), jsonObj["verified"].toBool() }; } template <> void unmarshal<Overwrite>(QJsonObject jsonObj, Overwrite **object) { *object = new Overwrite { getString(jsonObj, "id"), getString(jsonObj, "allow"), getString(jsonObj, "deny"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<ThreadMember>(QJsonObject jsonObj, ThreadMember **object) { *object = new ThreadMember { getString(jsonObj, "join_timestamp"), getString(jsonObj, "id"), getString(jsonObj, "user_id"), jsonObj["flags"].toInt(-1) }; } template <> void unmarshal<ThreadMetadata>(QJsonObject jsonObj, ThreadMetadata **object) { *object = new ThreadMetadata { getString(jsonObj, "archive_timestamp"), jsonObj["auto_archive_duration"].toInt(-1), jsonObj["archived"].toBool(), jsonObj["locked"].toBool() }; } template <> void unmarshal<Channel>(QJsonObject jsonObj, Channel **object) { std::vector<User *> *recipients = new std::vector<User *>; std::vector<Overwrite *> *permissionOverwrites = new std::vector<Overwrite *>; ThreadMember *member = new ThreadMember; ThreadMetadata *threadMetadata = new ThreadMetadata; unmarshalMultiple<User>(jsonObj["recipients"].toArray(), &recipients); unmarshalMultiple<Overwrite>(jsonObj["permission_overwrites"].toArray(), &permissionOverwrites); unmarshal<ThreadMember>(jsonObj["member"].toObject(), &member); unmarshal<ThreadMetadata>(jsonObj["thread_metadata"].toObject(), &threadMetadata); *object = new Channel { recipients, permissionOverwrites, member, threadMetadata, getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "topic"), getString(jsonObj, "icon"), getString(jsonObj, "last_pin_timestamp"), getString(jsonObj, "rtc_region"), getString(jsonObj, "permissions"), getString(jsonObj, "guild_id"), getString(jsonObj, "last_message_id"), getString(jsonObj, "owner_id"), getString(jsonObj, "application_id"), getString(jsonObj, "parent_id"), jsonObj["type"].toInt(-1), jsonObj["position"].toInt(-1), jsonObj["bitrate"].toInt(-1), jsonObj["user_limit"].toInt(-1), jsonObj["rate_limit_per_user"].toInt(-1), jsonObj["video_quality_mode"].toInt(-1), jsonObj["message_count"].toInt(-1), jsonObj["member_count"].toInt(-1), jsonObj["default_auto_archive_duration"].toInt(-1), jsonObj["nsfw"].toBool() }; } template <> void unmarshal<PrivateChannel>(QJsonObject jsonObj, PrivateChannel **object) { *object = new PrivateChannel { getStringsFromJson(jsonObj["recipient_ids"].toArray()), getString(jsonObj, "icon"), getString(jsonObj, "id"), getString(jsonObj, "last_message_id"), getString(jsonObj, "name"), getString(jsonObj, "owner_id"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<TeamMember>(QJsonObject jsonObj, TeamMember **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new TeamMember { user, getStringsFromJson(jsonObj["permissions"].toArray()), getString(jsonObj, "team_id"), jsonObj["member_ship_state"].toInt(-1) }; } template <> void unmarshal<Team>(QJsonObject jsonObj, Team **object) { std::vector<TeamMember *> *members = new std::vector<TeamMember *>; unmarshalMultiple<TeamMember>(jsonObj, "members", &members); *object = new Team { members, getString(jsonObj, "icon"), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "owner_user_id") }; } template <> void unmarshal<Application>(QJsonObject jsonObj, Application **object) { User *owner = new User; Team *team = new Team; unmarshal<User>(jsonObj, "owner", &owner); unmarshal<Team>(jsonObj, "team", &team); *object = new Application { owner, team, getStringsFromJson(jsonObj["rpc_origins"].toArray()), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "icon"), getString(jsonObj, "description"), getString(jsonObj, "terms_of_service_url"), getString(jsonObj, "privacy_policy_url"), getString(jsonObj, "summary"), getString(jsonObj, "verify_key"), getString(jsonObj, "guild_id"), getString(jsonObj, "primary_sku_id"), getString(jsonObj, "slug"), getString(jsonObj, "cover_image"), jsonObj["flags"].toInt(-1), jsonObj["bot_public"].toBool(), jsonObj["bot_require_code_grant"].toBool() }; } template <> void unmarshal<MessageActivity>(QJsonObject jsonObj, MessageActivity **object) { *object = new MessageActivity { getString(jsonObj, "party_id"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<GuildMessageMember>(QJsonObject jsonObj, GuildMessageMember **object) { *object = new GuildMessageMember { getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "nick"), getString(jsonObj, "joined_at"), getString(jsonObj, "premium_since"), getString(jsonObj, "permissions"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["pending"].toBool() }; } template <> void unmarshal<MessageInteraction>(QJsonObject jsonObj, MessageInteraction **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new MessageInteraction { user, getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<Emoji>(QJsonObject jsonObj, Emoji **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new Emoji { user, getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["requireColons"].toBool(), jsonObj["managed"].toBool(), jsonObj["animated"].toBool(), jsonObj["available"].toBool() }; } template <> void unmarshal<Reaction>(QJsonObject jsonObj, Reaction **object) { Emoji *emoji = new Emoji; unmarshal<Emoji>(jsonObj, "emoji", &emoji); *object = new Reaction { emoji, jsonObj["count"].toInt(-1), jsonObj["me"].toBool() }; } template <> void unmarshal<EmbedField>(QJsonObject jsonObj, EmbedField **object) { *object = new EmbedField { getString(jsonObj, "name"), getString(jsonObj, "value"), jsonObj["inline"].toBool() }; } template <> void unmarshal<EmbedFooter>(QJsonObject jsonObj, EmbedFooter **object) { *object = new EmbedFooter { getString(jsonObj, "text"), getString(jsonObj, "icon_url"), getString(jsonObj, "proxy_icon_url"), }; } template <> void unmarshal<EmbedTVI>(QJsonObject jsonObj, EmbedTVI **object) { *object = new EmbedTVI { getString(jsonObj, "url"), getString(jsonObj, "proxy_url"), jsonObj["height"].toInt(-1), jsonObj["width"].toInt(-1) }; } template <> void unmarshal<EmbedProvider>(QJsonObject jsonObj, EmbedProvider **object) { *object = new EmbedProvider { getString(jsonObj, "name"), getString(jsonObj, "url"), }; } template <> void unmarshal<EmbedAuthor>(QJsonObject jsonObj, EmbedAuthor **object) { *object = new EmbedAuthor { getString(jsonObj, "name"), getString(jsonObj, "url"), getString(jsonObj, "icon_url"), getString(jsonObj, "proxy_icon_url") }; } template <> void unmarshal<Embed>(QJsonObject jsonObj, Embed **object) { std::vector<EmbedField *> *fields = new std::vector<EmbedField *>; EmbedFooter *footer = new EmbedFooter; EmbedTVI *image = new EmbedTVI; EmbedTVI *thumbnail = new EmbedTVI; EmbedTVI *video = new EmbedTVI; EmbedProvider *provider = new EmbedProvider; EmbedAuthor *author = new EmbedAuthor; unmarshalMultiple<EmbedField>(jsonObj, "fields", &fields); unmarshal<EmbedFooter>(jsonObj, "footer", &footer); unmarshal<EmbedTVI>(jsonObj, "image", &image); unmarshal<EmbedTVI>(jsonObj, "thumbnail", &thumbnail); unmarshal<EmbedTVI>(jsonObj, "video", &video); unmarshal<EmbedProvider>(jsonObj, "provider", &provider); unmarshal<EmbedAuthor>(jsonObj, "author", &author); *object = new Embed { fields, footer, image, thumbnail, video, provider, author, getString(jsonObj, "title"), getString(jsonObj, "type"), getString(jsonObj, "description"), getString(jsonObj, "url"), getString(jsonObj, "timestamp"), jsonObj["color"].toInt(-1) }; } template <> void unmarshal<Attachment>(QJsonObject jsonObj, Attachment **object) { *object = new Attachment { getString(jsonObj, "id"), getString(jsonObj, "filename"), getString(jsonObj, "content_type"), getString(jsonObj, "url"), getString(jsonObj, "proxy_url"), jsonObj["size"].toInt(-1), jsonObj["height"].toInt(-1), jsonObj["width"].toInt(-1) }; } template <> void unmarshal<ChannelMention>(QJsonObject jsonObj, ChannelMention **object) { *object = new ChannelMention { getString(jsonObj, "id"), getString(jsonObj, "guild_id"), getString(jsonObj, "name"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<SelectOption>(QJsonObject jsonObj, SelectOption **object) { Emoji *emoji = new Emoji; unmarshal<Emoji>(jsonObj, "emoji", &emoji); *object = new SelectOption { emoji, getString(jsonObj, "label"), getString(jsonObj, "value"), getString(jsonObj, "description"), jsonObj["default"].toBool() }; } template <> void unmarshal<MessageComponent>(QJsonObject jsonObj, MessageComponent **object) { Emoji *emoji = new Emoji; std::vector<SelectOption *> *components = new std::vector<SelectOption *>; unmarshal<Emoji>(jsonObj, "emoji", &emoji); unmarshalMultiple<SelectOption>(jsonObj, "components", &components); *object = new MessageComponent { emoji, components, nullptr, getString(jsonObj, "custom_id"), getString(jsonObj, "label"), getString(jsonObj, "url"), getString(jsonObj, "placeholder"), jsonObj["type"].toInt(-1), jsonObj["style"].toInt(-1), jsonObj["min_values"].toInt(-1), jsonObj["max_values"].toInt(-1), jsonObj["disabled"].toBool() }; } template <> void unmarshal<StickerItem>(QJsonObject jsonObj, StickerItem **object) { *object = new StickerItem { getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["format_type"].toInt(-1) }; } template <> void unmarshal<Sticker>(QJsonObject jsonObj, Sticker **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new Sticker { user, getString(jsonObj, "id"), getString(jsonObj, "pack_id"), getString(jsonObj, "name"), getString(jsonObj, "description"), getString(jsonObj, "tags"), getString(jsonObj, "asset"), getString(jsonObj, "guild_id"), jsonObj["type"].toInt(-1), jsonObj["format_type"].toInt(-1), jsonObj["sort_value"].toInt(-1), jsonObj["available"].toBool() }; } Message *getPartialMessage(QJsonObject jsonObj, const QString& key) { Application *application = new Application; User *author = new User; MessageActivity *activity = new MessageActivity; GuildMessageMember *member = new GuildMessageMember; Channel *thread = new Channel; MessageInteraction *interaction = new MessageInteraction; std::vector<Reaction *> *reactions = new std::vector<Reaction *>; std::vector<User *> *mentions = new std::vector<User *>; std::vector<Attachment *> *attachments = new std::vector<Attachment *>; std::vector<ChannelMention *> *mentionChannels = new std::vector<ChannelMention *>; std::vector<MessageComponent *> *components = new std::vector<MessageComponent *>; std::vector<StickerItem *> *stickerItems = new std::vector<StickerItem *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<Application>(jsonObj, "application", &application); unmarshal<User>(jsonObj, "author", &author); unmarshal<MessageActivity>(jsonObj, "activity", &activity); unmarshal<GuildMessageMember>(jsonObj, "member", &member); unmarshal<Channel>(jsonObj, "thread", &thread); unmarshal<MessageInteraction>(jsonObj, "interaction", &interaction); unmarshalMultiple<Reaction>(jsonObj, "reactions", &reactions); unmarshalMultiple<User>(jsonObj, "mentions", &mentions); unmarshalMultiple<Attachment>(jsonObj, "attachments", &attachments); unmarshalMultiple<ChannelMention>(jsonObj, "mention_channels", &mentionChannels); unmarshalMultiple<MessageComponent>(jsonObj, "components", &components); unmarshalMultiple<StickerItem>(jsonObj, "sticker_items", &stickerItems); unmarshalMultiple<Sticker>(jsonObj, "stickers", &stickers); if (key == QString("") && jsonObj[key].type() == QJsonValue::Undefined) { return nullptr; } jsonObj = key == QString("") ? jsonObj : jsonObj[key].toObject(); return new Message { application, author, activity, member, nullptr, thread, interaction, reactions, nullptr, mentions, attachments, mentionChannels, getStringsFromJson(jsonObj["mention_roles"].toArray()), components, stickerItems, stickers, getString(jsonObj, "id"), getString(jsonObj, "channel_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "content"), getString(jsonObj, "timestamp"), getString(jsonObj, "edited_timestamp"), getString(jsonObj, "webhook_id"), getString(jsonObj, "application_id"), getString(jsonObj, "nonce"), jsonObj["nonce"].toInt(-1), jsonObj["author_public_flags"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["tts"].toBool(), jsonObj["pinned"].toBool(), jsonObj["mention_everyone"].toBool() }; } template <> void unmarshal<Message>(QJsonObject jsonObj, Message **object) { Application *application = new Application; User *author = new User; MessageActivity *activity = new MessageActivity; GuildMessageMember *member = new GuildMessageMember; Channel *thread = new Channel; MessageInteraction *interaction = new MessageInteraction; std::vector<Reaction *> *reactions = new std::vector<Reaction *>; std::vector<User *> *mentions = new std::vector<User *>; std::vector<Attachment *> *attachments = new std::vector<Attachment *>; std::vector<ChannelMention *> *mentionChannels = new std::vector<ChannelMention *>; std::vector<MessageComponent *> *components = new std::vector<MessageComponent *>; std::vector<StickerItem *> *stickerItems = new std::vector<StickerItem *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<Application>(jsonObj, "application", &application); unmarshal<User>(jsonObj, "author", &author); unmarshal<MessageActivity>(jsonObj, "activity", &activity); unmarshal<GuildMessageMember>(jsonObj, "member", &member); unmarshal<Channel>(jsonObj, "thread", &thread); unmarshal<MessageInteraction>(jsonObj, "interaction", &interaction); unmarshalMultiple<Reaction>(jsonObj, "reactions", &reactions); unmarshalMultiple<User>(jsonObj, "mentions", &mentions); unmarshalMultiple<Attachment>(jsonObj, "attachments", &attachments); unmarshalMultiple<ChannelMention>(jsonObj, "mention_channels", &mentionChannels); unmarshalMultiple<MessageComponent>(jsonObj, "components", &components); unmarshalMultiple<StickerItem>(jsonObj, "sticker_items", &stickerItems); unmarshalMultiple<Sticker>(jsonObj, "stickers", &stickers); *object = new Message { application, author, activity, member, getPartialMessage(jsonObj, "referenced_message"), thread, interaction, reactions, nullptr, mentions, attachments, mentionChannels, getStringsFromJson(jsonObj["mention_roles"].toArray()), components, stickerItems, stickers, getString(jsonObj, "id"), getString(jsonObj, "channel_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "content"), getString(jsonObj, "timestamp"), getString(jsonObj, "edited_timestamp"), getString(jsonObj, "webhook_id"), getString(jsonObj, "application_id"), getString(jsonObj, "nonce"), jsonObj["nonce"].toInt(-1), jsonObj["author_public_flags"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["tts"].toBool(), jsonObj["pinned"].toBool(), jsonObj["mention_everyone"].toBool() }; } template <> void unmarshal<GuildMember>(QJsonObject jsonObj, GuildMember **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new GuildMember { user, getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "nick"), getString(jsonObj, "avatar"), getString(jsonObj, "joined_at"), getString(jsonObj, "premium_since"), getString(jsonObj, "permissions"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["pending"].toBool() }; } template <> void unmarshal<VoiceState>(QJsonObject jsonObj, VoiceState **object) { GuildMember *member = new GuildMember; unmarshal<GuildMember>(jsonObj, "member", &member); *object = new VoiceState { member, getString(jsonObj, "guild_id"), getString(jsonObj, "channel_id"), getString(jsonObj, "user_id"), getString(jsonObj, "session_id"), getString(jsonObj, "request_to_speak_timestamp"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["self_deaf"].toBool(), jsonObj["self_mute"].toBool(), jsonObj["self_stream"].toBool(), jsonObj["self_video"].toBool(), jsonObj["suppress"].toBool() }; } template <> void unmarshal<WelcomeScreenChannel>(QJsonObject jsonObj, WelcomeScreenChannel **object) { *object = new WelcomeScreenChannel { getString(jsonObj, "channel_id"), getString(jsonObj, "description"), getString(jsonObj, "emoji_id"), getString(jsonObj, "emoji_name"), }; } template <> void unmarshal<WelcomeScreen>(QJsonObject jsonObj, WelcomeScreen **object) { std::vector<WelcomeScreenChannel *> *welcomeChannels = new std::vector<WelcomeScreenChannel *>; unmarshalMultiple<WelcomeScreenChannel>(jsonObj, "welcome_channels", &welcomeChannels); *object = new WelcomeScreen { welcomeChannels, getString(jsonObj, "description"), }; } template <> void unmarshal<StageInstance>(QJsonObject jsonObj, StageInstance **object) { *object = new StageInstance { getString(jsonObj, "id"), getString(jsonObj, "guild_id"), getString(jsonObj, "channel_id"), getString(jsonObj, "topic"), jsonObj["privacy_level"].toInt(-1), jsonObj["discoverable_disabled"].toBool() }; } template <> void unmarshal<Guild>(QJsonObject jsonObj, Guild **object) { WelcomeScreen *welcomeScreen = new WelcomeScreen; std::vector<VoiceState *> *voiceStates = new std::vector<VoiceState *>; std::vector<GuildMember *> *members = new std::vector<GuildMember *>; std::vector<Channel *> *channels = new std::vector<Channel *>; std::vector<Channel *> *threads = new std::vector<Channel *>; std::vector<StageInstance *> *stageInstances = new std::vector<StageInstance *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<WelcomeScreen>(jsonObj["welcome_screen"].toObject(), &welcomeScreen); unmarshalMultiple<VoiceState>(jsonObj["voice_states"].toArray(), &voiceStates); unmarshalMultiple<GuildMember>(jsonObj["members"].toArray(), &members); unmarshalMultiple<Channel>(jsonObj["channels"].toArray(), &channels); unmarshalMultiple<Channel>(jsonObj["threads"].toArray(), &threads); unmarshalMultiple<StageInstance>(jsonObj["stage_instances"].toArray(), &stageInstances); unmarshalMultiple<Sticker>(jsonObj["stickers"].toArray(), &stickers); *object = new Guild { welcomeScreen, getStringsFromJson(jsonObj["guild_features"].toArray()), voiceStates, members, channels, threads, nullptr, stageInstances, stickers, getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "icon"), getString(jsonObj, "icon_hash"), getString(jsonObj, "splash"), getString(jsonObj, "discovery_splash"), getString(jsonObj, "owner_id"), getString(jsonObj, "permissions"), getString(jsonObj, "region"), getString(jsonObj, "afk_channel_id"), getString(jsonObj, "widget_channel_id"), getString(jsonObj, "application_id"), getString(jsonObj, "system_channel_id"), getString(jsonObj, "rules_channel_id"), getString(jsonObj, "joined_at"), getString(jsonObj, "vanity_url_code"), getString(jsonObj, "description"), getString(jsonObj, "banner"), getString(jsonObj, "preferred_locale"), getString(jsonObj, "public_updates_channel_id"), jsonObj["afk_timeout"].toInt(-1), jsonObj["verification_level"].toInt(-1), jsonObj["default_message_notifications"].toInt(-1), jsonObj["explicit_content_filter"].toInt(-1), jsonObj["mfa_level"].toInt(-1), jsonObj["system_channel_flags"].toInt(-1), jsonObj["member_count"].toInt(-1), jsonObj["max_presences"].toInt(-1), jsonObj["max_members"].toInt(-1), jsonObj["premium_tier"].toInt(-1), jsonObj["premium_subscription_count"].toInt(-1), jsonObj["max_video_channel_users"].toInt(-1), jsonObj["approximate_member_count"].toInt(-1), jsonObj["approximate_presence_count"].toInt(-1), jsonObj["nsfw_level"].toInt(-1), jsonObj["owner"].toBool(), jsonObj["widget_enabled"].toBool(), jsonObj["large"].toBool(), jsonObj["unavailable"].toBool() }; } template <> void unmarshal<CustomStatus>(QJsonObject jsonObj, CustomStatus **object) { *object = new CustomStatus { getString(jsonObj, "text"), getString(jsonObj, "expires_at"), getString(jsonObj, "emoji_name"), getString(jsonObj, "emoji_id") }; } template <> void unmarshal<FriendSourceFlags>(QJsonObject jsonObj, FriendSourceFlags **object) { *object = new FriendSourceFlags { jsonObj["all"].toBool(), jsonObj["mutual_friends"].toBool(), jsonObj["mutual_guilds"].toBool() }; } template <> void unmarshal<GuildFolder>(QJsonObject jsonObj, GuildFolder **object) { *object = new GuildFolder { getStringsFromJson(jsonObj["guild_ids"].toArray()), getString(jsonObj, "name"), jsonObj["id"].toInt(-1), jsonObj["color"].toInt(-1) }; } template <> void unmarshal<ClientSettings>(QJsonObject jsonObj, ClientSettings **object) { CustomStatus *customStatus = new CustomStatus; FriendSourceFlags *friendSourceFlags = new FriendSourceFlags; std::vector<GuildFolder *> *guildFolders = new std::vector<GuildFolder *>; unmarshal<CustomStatus>(jsonObj, "custom_status", &customStatus); unmarshal<FriendSourceFlags>(jsonObj, "friend_source_flags", &friendSourceFlags); unmarshalMultiple<GuildFolder>(jsonObj, "guild_folders", &guildFolders); *object = new ClientSettings { customStatus, friendSourceFlags, guildFolders, getStringsFromJson(jsonObj["guild_positions"].toArray()), getStringsFromJson(jsonObj["restricted_guilds"].toArray()), getString(jsonObj, "locale"), getString(jsonObj, "status"), getString(jsonObj, "theme"), jsonObj["afk_timeout"].toInt(-1), jsonObj["animate_stickers"].toInt(-1), jsonObj["explicit_content_filter"].toInt(-1), jsonObj["friend_discovery_flags"].toInt(-1), jsonObj["timezone_offset"].toInt(-1), jsonObj["allow_accessibility_detection"].toBool(), jsonObj["animate_emoji"].toBool(), jsonObj["contact_sync_enabled"].toBool(), jsonObj["convert_emoticons"].toBool(), jsonObj["default_guilds_restricted"].toBool(), jsonObj["detect_platform_accounts"].toBool(), jsonObj["developer_mode"].toBool(), jsonObj["disable_games_tab"].toBool(), jsonObj["enable_tts_command"].toBool(), jsonObj["gif_auto_play"].toBool(), jsonObj["inline_attachment_media"].toBool(), jsonObj["inline_embed_media"].toBool(), jsonObj["message_display_compact"].toBool(), jsonObj["native_phone_integration_enabled"].toBool(), jsonObj["render_embeds"].toBool(), jsonObj["render_reactions"].toBool(), jsonObj["show_current_game"].toBool(), jsonObj["stream_notifications_enabled"].toBool(), jsonObj["view_nsfw_guilds"].toBool() }; } template <> void unmarshal<Client>(QJsonObject jsonObj, Client **object) { *object = new Client { getString(jsonObj, "id"), getString(jsonObj, "username"), getString(jsonObj, "avatar"), getString(jsonObj, "discriminator"), getString(jsonObj, "banner"), getString(jsonObj, "bio"), getString(jsonObj, "locale"), getString(jsonObj, "email"), getString(jsonObj, "phone"), jsonObj["public_flags"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["purchased_flags"].toInt(-1), jsonObj["banner_color"].toInt(-1), jsonObj["accent_color"].toInt(-1), jsonObj["nsfw_allowed"].toBool(), jsonObj["mfa_enabled"].toBool(), jsonObj["verified"].toBool() }; } template <> void unmarshal<ActivityTimestamps>(QJsonObject jsonObj, ActivityTimestamps **object) { *object = new ActivityTimestamps { jsonObj["start"].toInt(-1), jsonObj["end"].toInt(-1) }; } template <> void unmarshal<ActivityAssets>(QJsonObject jsonObj, ActivityAssets **object) { *object = new ActivityAssets { getString(jsonObj, "large_image"), getString(jsonObj, "large_text"), getString(jsonObj, "small_image"), getString(jsonObj, "small_text") }; } template <> void unmarshal<PartySize>(QJsonObject jsonObj, PartySize **object) { *object = new PartySize { jsonObj["current_size"].toInt(-1), jsonObj["max_size"].toInt(-1) }; } template <> void unmarshal<ActivityParty>(QJsonObject jsonObj, ActivityParty **object) { PartySize *size = new PartySize; unmarshal<PartySize>(jsonObj, "size", &size); *object = new ActivityParty { size, getString(jsonObj, "id") }; } template <> void unmarshal<ActivitySecrets>(QJsonObject jsonObj, ActivitySecrets **object) { *object = new ActivitySecrets { getString(jsonObj, "match"), getString(jsonObj, "join"), getString(jsonObj, "spectate") }; } template <> void unmarshal<Activity>(QJsonObject jsonObj, Activity **object) { ActivityTimestamps *timestamps = new ActivityTimestamps; ActivityAssets *assets = new ActivityAssets; ActivityParty *party = new ActivityParty; ActivitySecrets *secrets = new ActivitySecrets; unmarshal<ActivityTimestamps>(jsonObj, "timestamps", &timestamps); unmarshal<ActivityAssets>(jsonObj, "assets", &assets); unmarshal<ActivityParty>(jsonObj, "party", &party); unmarshal<ActivitySecrets>(jsonObj, "secrets", &secrets); *object = new Activity { timestamps, assets, party, secrets, getString(jsonObj, "application_id"), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "state"), getString(jsonObj, "details"), jsonObj["created_at"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["instance"].toBool(false) }; } template <> void unmarshal<ClientStatus>(QJsonObject jsonObj, ClientStatus **object) { *object = new ClientStatus { getString(jsonObj, "desktop"), getString(jsonObj, "mobile"), getString(jsonObj, "web") }; } template <> void unmarshal<Presence>(QJsonObject jsonObj, Presence **object) { User *user = new User; ClientStatus *clientStatus = new ClientStatus; std::vector<Activity *> *activities = new std::vector<Activity *>; unmarshal<User>(jsonObj, "user", &user); unmarshal<ClientStatus>(jsonObj, "client_status", &clientStatus); unmarshalMultiple<Activity>(jsonObj, "activities", &activities); *object = new Presence { user, clientStatus, activities, getString(jsonObj, "user_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "status") }; } } // namespace Api
29.845057
100
0.640093
EnyoYoen
8a25a15875699117cf78c6bb32662737f6769a76
5,579
cc
C++
evaluation/semi_dense_optical_flow/KITTI.cc
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
evaluation/semi_dense_optical_flow/KITTI.cc
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
evaluation/semi_dense_optical_flow/KITTI.cc
jjzhang166/videopp
f1421b16b8ffcefb3d1697460940d868e31ba79d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#include <opencv2/highgui.hpp> #include <iod/parse_command_line.hh> #include <iod/timer.hh> #include <gpof/gpof_ios.hh> #include <vpp/vpp.hh> #include <vpp/algorithms/video_extruder.hh> #include <vpp/utils/opencv_bridge.hh> #include <vpp/utils/opencv_utils.hh> #include <vpp/draw/draw_trajectories.hh> #include <evaluation/utils/kitti.hh> #include "symbols.hh" using namespace iod; using namespace vpp; struct stats { stats() : min_(FLT_MAX), max_(FLT_MIN), cpt_(0.f), sum_(0.f) {} void take(float f) { min_ = std::min(min_, f); max_ = std::max(max_, f); cpt_++; sum_ += f; } float min() const { return min_; } float max() const { return max_; } float cpt() const { return cpt_; } float sum() const { return sum_; } float avg() const { return sum_ / cpt_; } float min_, max_, cpt_, sum_; }; inline auto display_flow(const image2d<vfloat3>& flow, std::string path) { image2d<vuchar3> rgb_flow(flow.domain()); fill(rgb_flow, vuchar3{0,0,0}); pixel_wise(rgb_flow, flow) | [] (vuchar3& rf, vfloat3 f3) { vfloat2 f = f3.segment<2>(0); if (f.norm() != 0.f) { float a = (M_PI + atan2(f[0], f[1])) * 180 / M_PI; float n = std::min(f.norm() / 30.f, 1.f); rf = hsv_to_rgb(a, n, 1.); } }; cv::imwrite(path, to_opencv(rgb_flow)); } void display_flow_errors(const image2d<vfloat3>& flow, const image2d<vfloat3>& ref_flow, const image2d<vuchar3>& i1, std::string path) { image2d<vuchar3> display(i1.domain()); copy(i1, display); for (vint2 p : flow.domain()) { if (!flow(p)[2]) continue; vfloat2 f = flow(p).segment<2>(0); vint2 p1 = p; vint2 p2 = (p.cast<float>() + f).cast<int>(); if (ref_flow(p)[2] > 0 and flow(p).norm() > 0.f and i1.has(p + f.cast<int>()) and (ref_flow(p).segment<2>(0) - f).norm() > 10) { display(p1) = vuchar3(0,0, 255); } else if (ref_flow(p)[2] > 0 and flow(p).norm() > 0.f and (ref_flow(p).segment<2>(0) - f).norm() > 3) { display(p1) = vuchar3(0,255, 255); } else if (ref_flow(p)[2] > 0 and flow(p).norm() > 0.f and (ref_flow(p).segment<2>(0) - f).norm() > 1) { display(p1) = vuchar3(255,255, 0); } else if (ref_flow(p)[2] > 0 and flow(p).norm() > 0.f and (ref_flow(p).segment<2>(0) - f).norm() <= 1) { display(p1) = vuchar3(0,255, 0); } } cv::imwrite(path, to_opencv(display)); } int main(int argc, const char* argv[]) { if (argc != 5) { std::cerr << "Usage: " << argv[0] << " kitti_root n_images config_file result_file" << std::endl; return 1; } auto params = gpof::read_parameters(argv[3], _nscales = 1, _winsize = 9, _propagation = 2, _min_scale = 0, _patchsize = 5, _detector_th = 10, _block_size = 10); int nframes = atoi(argv[2]); stats runtime_stats; stats error_stats; stats nkeypoints_stats; kitti::foreach_training_pair (argv[1], nframes, [&] (const image2d<vuchar3>& frame1, const image2d<vuchar3>& frame2, const image2d<vfloat3>& ref_flow) { image2d<uint8_t> i1_gl = rgb_to_graylevel<uint8_t>(frame1); image2d<uint8_t> i2_gl = rgb_to_graylevel<uint8_t>(frame2); i1_gl = clone(i1_gl, _border = params.winsize, _aligned = 128); i2_gl = clone(i2_gl, _border = params.winsize, _aligned = 128); // Detect keypoints auto keypoints = fast9(i1_gl, params.detector_th, _blockwise, _block_size = params.block_size); image2d<vfloat3> flow(frame1.domain()); fill(flow, vfloat3(0,0,0)); // Compute optical flow timer t; t.start(); // std::vector<vint2> next_kps; // video_extruder_optical_flow2 // (i1_gl, i2_gl, // keypoints, next_kps, // params.nscales, params.winsize, params.propagation); // for (int i = 0; i < next_kps.size(); i++) // { // if (next_kps[i][0] >= 0) // { // vint2 p1 = keypoints[i]; // vint2 p2 = next_kps[i]; // flow(p1).segment<2>(0) = (p2 - p1).cast<float>(); // flow(p1)[2] = 1.f; // } // } semi_dense_optical_flow (keypoints, [&] (int i, vint2 pos, int distance) { flow(keypoints[i])[2] = 1.f; flow(keypoints[i]).segment<2>(0) = vint2(pos - keypoints[i]).cast<float>(); }, i1_gl, i2_gl, _winsize = params.winsize, _propagation = params.propagation, _nscales = params.nscales, _patchsize = params.patchsize, _min_scale = params.min_scale); t.end(); auto flow_errors = kitti::flow_error_stats(flow, ref_flow); // display_flow_errors(flow, ref_flow, frame1, "errors.ppm"); // display_flow(flow, "flow.ppm"); runtime_stats.take(t.us()); error_stats.take(flow_errors.n3); nkeypoints_stats.take(keypoints.size()); }); gpof::write_results(argv[4], _runtime = runtime_stats.avg(), _errors = error_stats.avg(), _nkeypoints = nkeypoints_stats.avg()); }
28.610256
101
0.53325
jjzhang166
8a2705444d86f835b50e88630b346e54a9168b24
11,754
cpp
C++
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
491
2021-03-12T08:16:02.000Z
2022-03-30T02:25:18.000Z
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
26
2021-03-17T09:09:27.000Z
2022-01-23T01:49:55.000Z
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
67
2021-03-15T09:03:29.000Z
2022-03-30T04:19:02.000Z
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under // the License. // // ╔════════════════════════════════════════════════════════════════════════════════════════╗ // ║──█████████╗───███████╗───████████╗───██╗──────██╗───███████╗───████████╗───████████╗───║ // ║──██╔══════╝──██╔════██╗──██╔════██╗──██║──────██║──██╔════██╗──██╔════██╗──██╔════██╗──║ // ║──████████╗───██║────██║──████████╔╝──██║──█╗──██║──█████████║──████████╔╝──██║────██║──║ // ║──██╔═════╝───██║────██║──██╔════██╗──██║█████╗██║──██╔════██║──██╔════██╗──██║────██║──║ // ║──██║─────────╚███████╔╝──██║────██║──╚████╔████╔╝──██║────██║──██║────██║──████████╔╝──║ // ║──╚═╝──────────╚══════╝───╚═╝────╚═╝───╚═══╝╚═══╝───╚═╝────╚═╝──╚═╝────╚═╝──╚═══════╝───║ // ╚════════════════════════════════════════════════════════════════════════════════════════╝ // // Authors: Aster JIAN (asterjian@qq.com) // Yzx (yzxyzxyzx777@outlook.com) // Ao LI (346950981@qq.com) // Paul LU (lujq96@gmail.com) #include "trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.h" #include <cuda_fp16.h> #include "trt_engine/trt_network_crt/plugins/common/serialize.hpp" // #define ENABLE_GRID_SAMPLER_FLOAT16 FWD_TRT_NAMESPACE_BEGIN GridSamplerPlugin::GridSamplerPlugin(int interpolation_mode, int padding_mode, int align_corners, nvinfer1::DataType data_type) : interpolation_mode_(interpolation_mode), padding_mode_(padding_mode), align_corners_(align_corners), data_type_(data_type) {} GridSamplerPlugin::GridSamplerPlugin(void const* serialData, size_t serialLength) { deserialize_value(&serialData, &serialLength, &interpolation_mode_); deserialize_value(&serialData, &serialLength, &padding_mode_); deserialize_value(&serialData, &serialLength, &align_corners_); deserialize_value(&serialData, &serialLength, &data_type_); } GridSamplerPlugin::~GridSamplerPlugin() { terminate(); } int GridSamplerPlugin::getNbOutputs() const noexcept { return 1; } nvinfer1::DimsExprs GridSamplerPlugin::getOutputDimensions( int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) noexcept { // [N, C, H, W], [N, H', W', 2] -> [N, C, H', W'] ASSERT(nbInputs == 2); assert(inputs[0].nbDims == 4 || inputs[0].nbDims == 5); assert(inputs[1].nbDims == 4 || inputs[1].nbDims == 5); nvinfer1::DimsExprs output(inputs[0]); output.d[2] = inputs[1].d[1]; output.d[3] = inputs[1].d[2]; if (inputs[0].nbDims == 5) { // [N, C, D, H, W], [N, D', H', W', 2] -> [N, C, D', H', W'] output.d[4] = inputs[1].d[3]; } return output; } int GridSamplerPlugin::initialize() noexcept { return 0; } void GridSamplerPlugin::terminate() noexcept {} size_t GridSamplerPlugin::getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const noexcept { return 0; } int GridSamplerPlugin::enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept { #ifdef ENABLE_GRID_SAMPLER_FLOAT16 nvinfer1::DataType type = data_type_; #else nvinfer1::DataType type = inputDesc[0].type; #endif if (inputDesc[0].dims.nbDims == 4) { if (type == nvinfer1::DataType::kFLOAT) { TensorInfo<float> output_tensor{static_cast<float*>(outputs[0]), outputDesc[0].dims}; GridSampler2DCuda<float>({static_cast<const float*>(inputs[0]), inputDesc[0].dims}, {static_cast<const float*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else if (type == nvinfer1::DataType::kHALF) { TensorInfo<__half> output_tensor{static_cast<__half*>(outputs[0]), outputDesc[0].dims}; GridSampler2DCuda<__half>({static_cast<const __half*>(inputs[0]), inputDesc[0].dims}, {static_cast<const __half*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "[Grid Sampler] Unsupported input data type"); return -1; } } else if (inputDesc[0].dims.nbDims == 5) { if (type == nvinfer1::DataType::kFLOAT) { TensorInfo<float> output_tensor{static_cast<float*>(outputs[0]), outputDesc[0].dims}; GridSampler3DCuda<float>({static_cast<const float*>(inputs[0]), inputDesc[0].dims}, {static_cast<const float*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else if (type == nvinfer1::DataType::kHALF) { TensorInfo<__half> output_tensor{static_cast<__half*>(outputs[0]), outputDesc[0].dims}; GridSampler3DCuda<__half>({static_cast<const __half*>(inputs[0]), inputDesc[0].dims}, {static_cast<const __half*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "[Grid Sampler] Unsupported input data type"); return -1; } } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "GridSampler do not support input dims > 5"); return -1; } CUDA_CHECK(cudaGetLastError()); return 0; } size_t GridSamplerPlugin::getSerializationSize() const noexcept { return serialized_size(interpolation_mode_) + serialized_size(padding_mode_) + serialized_size(align_corners_) + serialized_size(data_type_); } void GridSamplerPlugin::serialize(void* buffer) const noexcept { serialize_value(&buffer, interpolation_mode_); serialize_value(&buffer, padding_mode_); serialize_value(&buffer, align_corners_); serialize_value(&buffer, data_type_); } bool GridSamplerPlugin::supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) noexcept { ASSERT(inOut && nbInputs == 2 && nbOutputs == 1 && pos < (nbInputs + nbOutputs)); #ifdef ENABLE_GRID_SAMPLER_FLOAT16 return ((inOut[pos].type == nvinfer1::DataType::kFLOAT || inOut[pos].type == nvinfer1::DataType::kHALF) && inOut[pos].format == nvinfer1::TensorFormat::kLINEAR); #else return (inOut[pos].type == nvinfer1::DataType::kFLOAT && inOut[pos].format == nvinfer1::TensorFormat::kLINEAR); #endif } const char* GridSamplerPlugin::getPluginType() const noexcept { return GRID_SAMPLER_PLUGIN_NAME; } const char* GridSamplerPlugin::getPluginVersion() const noexcept { return GRID_SAMPLER_PLUGIN_VERSION; } void GridSamplerPlugin::destroy() noexcept { delete this; } nvinfer1::IPluginV2DynamicExt* GridSamplerPlugin::clone() const noexcept { return new GridSamplerPlugin{interpolation_mode_, padding_mode_, align_corners_, data_type_}; } void GridSamplerPlugin::setPluginNamespace(const char* pluginNamespace) noexcept { mPluginNamespace = pluginNamespace; } const char* GridSamplerPlugin::getPluginNamespace() const noexcept { return mPluginNamespace; } nvinfer1::DataType GridSamplerPlugin::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const noexcept { ASSERT(inputTypes && nbInputs > 0 && index == 0); return inputTypes[0]; } void GridSamplerPlugin::configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) noexcept { // for (int i = 0; i < nbInputs; i++) { // for (int j = 0; j < in[i].desc.dims.nbDims; j++) { // // Do not support dynamic dimensions // ASSERT(in[i].desc.dims.d[j] != -1); // } // } } GridSamplerPluginCreator::GridSamplerPluginCreator() { mPluginAttributes.emplace_back( nvinfer1::PluginField("interpolation_mode", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("padding_mode", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("align_corners", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("data_type", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } const char* GridSamplerPluginCreator::getPluginName() const noexcept { return GRID_SAMPLER_PLUGIN_NAME; } const char* GridSamplerPluginCreator::getPluginVersion() const noexcept { return GRID_SAMPLER_PLUGIN_VERSION; } const nvinfer1::PluginFieldCollection* GridSamplerPluginCreator::getFieldNames() noexcept { return &mFC; } nvinfer1::IPluginV2DynamicExt* GridSamplerPluginCreator::createPlugin( const char* name, const nvinfer1::PluginFieldCollection* fc) noexcept { int interpolation_mode{}, padding_mode{}, align_corners{}; const nvinfer1::PluginField* fields = fc->fields; int data_type = 0; for (int i = 0; i < fc->nbFields; ++i) { const char* attrName = fields[i].name; if (!strcmp(attrName, "interpolation_mode")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); interpolation_mode = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "padding_mode")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); padding_mode = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "align_corners")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); align_corners = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "data_type")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); data_type = *(static_cast<const int*>(fields[i].data)); } else { ASSERT(false); } } auto obj = new GridSamplerPlugin(interpolation_mode, padding_mode, align_corners, static_cast<nvinfer1::DataType>(data_type)); obj->setPluginNamespace(mNamespace.c_str()); return obj; } nvinfer1::IPluginV2DynamicExt* GridSamplerPluginCreator::deserializePlugin( const char* name, const void* serialData, size_t serialLength) noexcept { auto* obj = new GridSamplerPlugin{serialData, serialLength}; obj->setPluginNamespace(mNamespace.c_str()); return obj; } FWD_TRT_NAMESPACE_END
43.858209
100
0.623022
jinyouzhi
8a2d54b489bc1e899c9ffa6a8b293b8a74bd565f
619
hpp
C++
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
null
null
null
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
10
2018-02-06T14:46:36.000Z
2018-03-20T13:37:20.000Z
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
1
2021-11-26T10:59:09.000Z
2021-11-26T10:59:09.000Z
#pragma once #include <bunsan/pm/repository.hpp> #include <bunsan/tempfile.hpp> #include <bunsan/utility/custom_resolver.hpp> #include <boost/noncopyable.hpp> namespace bunsan::pm { class repository::local_system : private boost::noncopyable { public: local_system(repository &self, const local_system_config &config); utility::resolver &resolver(); /// Empty dir for possibly large files. tempfile tempdir_for_build(); /// Empty file. tempfile small_tempfile(); private: repository &m_self; local_system_config m_config; utility::custom_resolver m_resolver; }; } // namespace bunsan::pm
19.967742
68
0.746365
bacsorg
8a3ab2bd30c7966be5148e16b3be5507d2109b73
22,929
cpp
C++
_dropped/cs2420-c++/assignment_04/assignment_04.cpp
clmay/school
a4780ca6f517614ab5a5d9a44d0c6d8bc00783b6
[ "MIT" ]
null
null
null
_dropped/cs2420-c++/assignment_04/assignment_04.cpp
clmay/school
a4780ca6f517614ab5a5d9a44d0c6d8bc00783b6
[ "MIT" ]
null
null
null
_dropped/cs2420-c++/assignment_04/assignment_04.cpp
clmay/school
a4780ca6f517614ab5a5d9a44d0c6d8bc00783b6
[ "MIT" ]
1
2019-12-26T20:32:31.000Z
2019-12-26T20:32:31.000Z
// Copyright 2020, Bradley Peterson, Weber State University, All rights reserved. #include <chrono> #include <iostream> #include <map> #include <sstream> using std::cerr; using std::cin; using std::cout; using std::endl; using std::string; using std::stringstream; //************************************************************************ // A class I designed to help keep track of how much memory you allocate // Do not modify, this is not part of your assignment, it just helps test it. // For this to work, a class needs to inherit off of this one. // Then this does the rest of the work, since it // overloads new, new[], delete, and delete[]. //************************************************************************ class ManageMemory { public: static std::size_t getTotalSize() { std::size_t total = 0; std::map<void*, std::size_t>::iterator iter; for (iter = mapOfAllocations.begin(); iter != mapOfAllocations.end(); ++iter) { total += iter->second; } return total; } // I overloaded the new and delete keywords so I could manually track allocated memory. void* operator new(std::size_t x) { void* ptr = ::operator new(x); mapOfAllocations[ptr] = x; return ptr; } void* operator new[](std::size_t x) { void* ptr = ::operator new[](x); mapOfAllocations[ptr] = x; return ptr; } void operator delete(void* x) { mapOfAllocations.erase(x); ::operator delete(x); } void operator delete[](void* x) { mapOfAllocations.erase(x); ::operator delete[](x); } private: static std::map<void*, std::size_t> mapOfAllocations; }; std::map<void*, std::size_t> ManageMemory::mapOfAllocations; //****************** // The node class //****************** template <typename T> class Node : public ManageMemory { public: T data{}; Node<T>* backward{ nullptr }; Node<T>* forward{ nullptr }; }; //****************** // The linked list base class // This contains within it a class declaration for an iterator //****************** template <typename T> class BaseDoublyLinkedList : public ManageMemory { public: // public members of the DoublyLinkedList class ~BaseDoublyLinkedList(); string getListAsString(); string getListBackwardsAsString(); void insertFirst(const T&); void insertLast(const T&); T get(const unsigned int index) const { cerr << "Error: You didn't override this base class method yet" << endl; T temp{}; return temp; } T& operator[](const unsigned int index) const { cerr << "Error: You didn't override this base class method yet" << endl; T temp{}; return temp; } void insert(const unsigned int index, const T& value) { cerr << "Error: You didn't override this base class method yet" << endl; } void remove(const unsigned int index) { cerr << "Error: You didn't override this base class method yet" << endl; } void removeAllInstances(const T& value) { cerr << "Error: You didn't override this base class method yet" << endl; } protected: Node<T>* first{ nullptr }; Node<T>* last{ nullptr }; }; template <typename T> // destructor BaseDoublyLinkedList<T>::~BaseDoublyLinkedList() { Node<T>* temp = this->first; while (first) { first = first->forward; delete temp; temp = first; } } template <typename T> void BaseDoublyLinkedList<T>::insertFirst(const T& item) { Node<T>* temp = new Node<T>(); temp->data = item; if (!first) { // Scenario: List is empty last = temp; } else { first->backward = temp; temp->forward = first; } first = temp; } template <typename T> void BaseDoublyLinkedList<T>::insertLast(const T& item) { Node<T>* temp = new Node<T>(); temp->data = item; if (!first) { // Scenario: List is empty first = temp; } else { last->forward = temp; temp->backward = last; } last = temp; } // This method helps return a string representation of all nodes in the linked list, do not modify. template <typename T> string BaseDoublyLinkedList<T>::getListAsString() { stringstream ss; if (!first) { ss << "The list is empty."; } else { Node<T>* currentNode{ first }; ss << currentNode->data; currentNode = currentNode->forward; while (currentNode) { ss << " " << currentNode->data; currentNode = currentNode->forward; }; } return ss.str(); } // This method helps return a string representation of all nodes in the linked list, do not modify. template <typename T> string BaseDoublyLinkedList<T>::getListBackwardsAsString() { stringstream ss; if (!first) { ss << "The list is empty."; } else { Node<T>* currentNode{ last }; ss << currentNode->data; currentNode = currentNode->backward; while (currentNode) { ss << " " << currentNode->data; currentNode = currentNode->backward; }; } return ss.str(); } // Copyright 2020, Bradley Peterson, Weber State University, All rights reserved. (2/20) //********************************** // Write your code below here //********************************** template <typename T> class DoublyLinkedList : public BaseDoublyLinkedList<T> { public: T get(const unsigned int) const; T& operator[](const unsigned int) const; void insert(const unsigned int, const T&); void remove(const unsigned int); void removeAllInstances(const T&); }; template <typename T> T DoublyLinkedList<T>::get(const unsigned int index) const { if (this->first == nullptr) { throw 1; } Node<T>* currentNode = this->first; unsigned int position = 0; while (currentNode->forward != nullptr) { if (position == index) { break; } currentNode = currentNode->forward; position++; } if (position < index) { throw 1; } return currentNode->data; } template <typename T> T& DoublyLinkedList<T>::operator[](const unsigned int index) const { if (this->first == nullptr) { throw 1; } Node<T>* currentNode = this->first; unsigned int position = 0; while (currentNode->forward != nullptr) { if (position == index) { break; } currentNode = currentNode->forward; position++; } if (position < index) { throw 1; } return currentNode->data; } template <typename T> void DoublyLinkedList<T>::insert(const unsigned int index, const T& value) { Node<T>* newNode = new Node<T>(); newNode->data = value; if (index == 0) { if (this->first == nullptr && this->last == nullptr) { this->first = newNode; this->last = newNode; } else { newNode->forward = this->first; this->first->backward = newNode; this->first = newNode; } return; } Node<T>* currentNode = this->first; unsigned int position = 0; while (currentNode->forward != nullptr) { if (position == index) { break; } currentNode = currentNode->forward; position++; } if (currentNode == this->last) { newNode->backward = currentNode; currentNode->forward = newNode; this->last = newNode; } else { currentNode->backward->forward = newNode; newNode->backward = currentNode->backward; newNode->forward = currentNode; currentNode->backward = newNode; } } template <typename T> void DoublyLinkedList<T>::remove(const unsigned int index) { if (this->first == nullptr) { return; } Node<T>* currentNode = this->first; if (index == 0 && this->first == this->last) { this->first = nullptr; this->last = nullptr; delete currentNode; return; } else if (index == 0) { currentNode->forward->backward = nullptr; this->first = currentNode->forward; delete currentNode; return; } unsigned int position = 0; while (currentNode->forward != nullptr) { if (position == index) { break; } currentNode = currentNode->forward; position++; } if (position < index) { return; } if (currentNode == this->last) { currentNode->backward->forward = nullptr; this->last = currentNode->backward; delete currentNode; } else { currentNode->backward->forward = currentNode->forward; currentNode->forward->backward = currentNode->backward; delete currentNode; } } template <typename T> void DoublyLinkedList<T>::removeAllInstances(const T& value) { if (this->first == nullptr) { return; } Node<T>* currentNode = this->first; if (currentNode == this->first && this->first == this->last) { this->first = nullptr; this->last = nullptr; delete currentNode; return; } while (currentNode != nullptr) { if (currentNode->data == value) { if (currentNode == this->first) { currentNode->forward->backward = nullptr; this->first = currentNode->forward; } else if (currentNode == this->last) { currentNode->backward->forward = nullptr; this->last = currentNode->backward; } else { currentNode->backward->forward = currentNode->forward; currentNode->forward->backward = currentNode->backward; } Node<T>* nodeToDelete = currentNode; delete nodeToDelete; } currentNode = currentNode->forward; } } //********************************** // Write your code above here //********************************** // This helps with testing, do not modify. bool checkTest(string testName, string whatItShouldBe, string whatItIs) { if (whatItShouldBe == whatItIs) { cout << "Passed " << testName << endl; return true; } else { cout << "****** Failed test " << testName << " ****** " << endl << " Output was: " << whatItIs << endl << " Output should be: " << whatItShouldBe << endl; return false; } } // This helps with testing, do not modify. bool checkTest(string testName, int whatItShouldBe, int whatItIs) { if (whatItShouldBe == whatItIs) { cout << "Passed " << testName << endl; return true; } else { cout << "****** Failed test " << testName << " ****** " << endl << " Output was: " << whatItIs << endl << " Output should be: " << whatItShouldBe << endl; return false; } } // This helps with testing, do not modify. bool checkTestMemory(string testName, int whatItShouldBe, int whatItIs) { if (whatItShouldBe == whatItIs) { cout << "Passed " << testName << endl; return true; } else { cout << "***Failed test " << testName << " *** " << endl << " You lost track of " << whatItIs << " bytes in memory!" << endl; return false; } } // This helps with testing, do not modify. void testGet() { DoublyLinkedList<int>* d = new DoublyLinkedList<int>; for (int i = 10; i < 20; i++) { d->insertLast(i); } // Test just to make sure the data went in the list. checkTest("testGet #1", "10 11 12 13 14 15 16 17 18 19", d->getListAsString()); checkTest("testGet #2", "19 18 17 16 15 14 13 12 11 10", d->getListBackwardsAsString()); // Test retrieving items. int item = d->get(0); checkTest("testGet #3", 10, item); item = d->get(5); checkTest("testGet #4", 15, item); item = d->get(9); checkTest("testGet #5", 19, item); // Make sure the list was undisturbed during this time checkTest("testGet #6", "10 11 12 13 14 15 16 17 18 19", d->getListAsString()); // Try to access out of bounds. string caughtError = ""; try { int item = d->get(-1); } catch (int) { caughtError = "caught"; } checkTest("testGet #7", "caught", caughtError); try { int item = d->get(100); } catch (int) { caughtError = "caught"; } checkTest("testGet #8", "caught", caughtError); delete d; d = new DoublyLinkedList<int>; d->insertLast(18); item = d->get(0); checkTest("testGet #9", 18, item); delete d; } // This helps with testing, do not modify. void testSquareBrackets() { DoublyLinkedList<int> d; for (int i = 10; i < 20; i++) { d.insertLast(i); } // Test just to make sure the data went in the list. checkTest("testSquareBrackets #1", "10 11 12 13 14 15 16 17 18 19", d.getListAsString()); checkTest("testSquareBrackets #2", "19 18 17 16 15 14 13 12 11 10", d.getListBackwardsAsString()); // Test retrieving items. int item = d[0]; checkTest("testSquareBrackets #3", 10, item); item = d[5]; checkTest("testSquareBrackets #4", 15, item); item = d[9]; checkTest("testSquareBrackets #5", 19, item); // Make sure the list was undisturbed during this time checkTest("testSquareBrackets #6", "10 11 12 13 14 15 16 17 18 19", d.getListAsString()); checkTest("testSquareBrackets #7", "19 18 17 16 15 14 13 12 11 10", d.getListBackwardsAsString()); // now test the return by reference d[1] = 1000; checkTest("testSquareBrackets #8", "10 1000 12 13 14 15 16 17 18 19", d.getListAsString()); checkTest("testSquareBrackets #9", "19 18 17 16 15 14 13 12 1000 10", d.getListBackwardsAsString()); // Try to access out of bounds. string caughtError = ""; try { int item = d[-1]; } catch (int) { caughtError = "caught"; } checkTest("testSquareBrackets #10", "caught", caughtError); try { int item = d[100]; } catch (int) { caughtError = "caught"; } checkTest("testSquareBrackets #11", "caught", caughtError); } // This helps with testing, do not modify. void testInsert() { DoublyLinkedList<int>* s = new DoublyLinkedList<int>(); for (int i = 10; i < 20; i++) { s->insertLast(i); } // Test just to make sure the data went in the list. checkTest("testInsert #1", "10 11 12 13 14 15 16 17 18 19", s->getListAsString()); checkTest("testInsert #2", "19 18 17 16 15 14 13 12 11 10", s->getListBackwardsAsString()); s->insert(3, 33); checkTest("testInsert #3", "10 11 12 33 13 14 15 16 17 18 19", s->getListAsString()); checkTest("testInsert #4", "19 18 17 16 15 14 13 33 12 11 10", s->getListBackwardsAsString()); s->insert(0, 9); checkTest("testInsert #5", "9 10 11 12 33 13 14 15 16 17 18 19", s->getListAsString()); checkTest("testInsert #6", "19 18 17 16 15 14 13 33 12 11 10 9", s->getListBackwardsAsString()); s->insert(12, 20); checkTest("testInsert #7", "9 10 11 12 33 13 14 15 16 17 18 19 20", s->getListAsString()); checkTest("testInsert #8", "20 19 18 17 16 15 14 13 33 12 11 10 9", s->getListBackwardsAsString()); delete s; s = new DoublyLinkedList<int>(); s->insert(0, 42); checkTest("testInsert #9", "42", s->getListAsString()); checkTest("testInsert #10", "42", s->getListBackwardsAsString()); s->insert(1, 82); checkTest("testInsert #11", "42 82", s->getListAsString()); checkTest("testInsert #12", "82 42", s->getListBackwardsAsString()); delete s; } // This helps with testing, do not modify. void testRemove() { DoublyLinkedList<int>* d = new DoublyLinkedList<int>; for (int i = 10; i < 17; i++) { d->insertLast(i); } // Test just to make sure the data went in the list. checkTest("testRemove #1", "10 11 12 13 14 15 16", d->getListAsString()); checkTest("testRemove #2", "16 15 14 13 12 11 10", d->getListBackwardsAsString()); // Test deleting first items. d->remove(0); checkTest("testRemove #3", "11 12 13 14 15 16", d->getListAsString()); checkTest("testRemove #4", "16 15 14 13 12 11", d->getListBackwardsAsString()); d->remove(0); checkTest("testRemove #5", "12 13 14 15 16", d->getListAsString()); checkTest("testRemove #6", "16 15 14 13 12", d->getListBackwardsAsString()); // Test deleting a middle item d->remove(2); checkTest("testRemove #7", "12 13 15 16", d->getListAsString()); checkTest("testRemove #8", "16 15 13 12", d->getListBackwardsAsString()); // Test deleting last itmes d->remove(3); checkTest("testRemove #9", "12 13 15", d->getListAsString()); checkTest("testRemove #10", "15 13 12", d->getListBackwardsAsString()); d->remove(2); checkTest("testRemove #11", "12 13", d->getListAsString()); checkTest("testRemove #12", "13 12", d->getListBackwardsAsString()); // Test deleting a Kth element that doesn't exist. d->remove(500); checkTest("testRemove #13", "12 13", d->getListAsString()); checkTest("testRemove #14", "13 12", d->getListBackwardsAsString()); // Test deleting a last item d->remove(1); checkTest("testRemove #15", "12", d->getListAsString()); checkTest("testRemove #16", "12", d->getListBackwardsAsString()); // Test deleting item that doesn't exist d->remove(1); checkTest("testRemove #17", "12", d->getListAsString()); checkTest("testRemove #18", "12", d->getListBackwardsAsString()); // Test deleting item on the first d->remove(0); checkTest("testRemove #19", "The list is empty.", d->getListAsString()); // Test attempting to delete from an empty list d->remove(0); checkTest("testRemove #20", "The list is empty.", d->getListAsString()); delete d; } // This helps with testing, do not modify. void testRemoveAllInstances() { DoublyLinkedList<int>* d = new DoublyLinkedList<int>; d->insertLast(4); d->insertLast(2); d->insertLast(6); d->insertLast(5); d->insertLast(6); d->insertLast(9); // Do a delete, test it. d->removeAllInstances(6); checkTest("testRemoveAllInstances #1", "4 2 5 9", d->getListAsString()); checkTest("testRemoveAllInstances #2", "9 5 2 4", d->getListBackwardsAsString()); delete d; d = new DoublyLinkedList<int>; d->insertLast(4); d->insertLast(2); d->insertLast(3); d->insertLast(4); d->insertLast(4); d->insertLast(4); d->insertLast(9); d->removeAllInstances(4); checkTest("testRemoveAllInstances #3", "2 3 9", d->getListAsString()); checkTest("testRemoveAllInstances #4", "9 3 2", d->getListBackwardsAsString()); delete d; d = new DoublyLinkedList<int>; d->insertLast(3); d->insertLast(3); d->insertLast(3); d->insertLast(8); d->insertLast(2); d->insertLast(3); d->insertLast(3); d->insertLast(3); d->removeAllInstances(3); checkTest("testRemoveAllInstances #5", "8 2", d->getListAsString()); checkTest("testRemoveAllInstances #6", "2 8", d->getListBackwardsAsString()); delete d; d = new DoublyLinkedList<int>; d->insertLast(9); d->insertLast(9); d->insertLast(4); d->insertLast(2); d->insertLast(9); d->insertLast(9); d->insertLast(5); d->insertLast(1); d->insertLast(9); d->insertLast(2); d->insertLast(9); d->insertLast(9); // Do a delete, test it. d->removeAllInstances(9); checkTest("testRemoveAllInstances #7", "4 2 5 1 2", d->getListAsString()); checkTest("testRemoveAllInstances #8", "2 1 5 2 4", d->getListBackwardsAsString()); // Test deleting something that doesn't exist d->removeAllInstances(7); checkTest("testRemoveAllInstances #9", "4 2 5 1 2", d->getListAsString()); checkTest("testRemoveAllInstances #10", "2 1 5 2 4", d->getListBackwardsAsString()); // A few more tests d->removeAllInstances(2); checkTest("testRemoveAllInstances #11", "4 5 1", d->getListAsString()); checkTest("testRemoveAllInstances #12", "1 5 4", d->getListBackwardsAsString()); d->removeAllInstances(4); checkTest("testRemoveAllInstances #13", "5 1", d->getListAsString()); checkTest("testRemoveAllInstances #14", "1 5", d->getListBackwardsAsString()); d->removeAllInstances(5); checkTest("testRemoveAllInstances #15", "1", d->getListAsString()); d->removeAllInstances(1); checkTest("testRemoveAllInstances #16", "The list is empty.", d->getListAsString()); // retest deleting something that doesn't exist. d->removeAllInstances(7); checkTest("testRemoveAllInstances #17", "The list is empty.", d->getListAsString()); delete d; // Now ramp it up and do some huge tests. Start by timing how long a smaller approach takes. d = new DoublyLinkedList<int>; // Fill the list with a pattern of //1 2 2 3 3 3 4 4 4 4 1 2 2 3 3 3 4 4 4 4 ... cout << endl << "Preparing for testRemoveAllInstances #18, placing 50,000 numbers into the linked list to see how long things take." << endl; for (int i = 0; i < 20000; i++) { for (int j = 0; j < i % 4 + 1; j++) { d->insertLast(i % 4 + 1); } } cout << " Calling removeAllInstances to remove 15,000 3s in the list." << endl; // delete all the 3s. auto start = std::chrono::high_resolution_clock::now(); d->removeAllInstances(3); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::micro> diff = end - start; double benchmarkTime = diff.count() / 1000.0; cout << " Removing 15,000 3s took " << benchmarkTime << " milliseconds." << endl; cout << " So we will assume removing 30,000 3s then should be double that..." << endl; cout << " about " << benchmarkTime << " * 2 = " << (benchmarkTime * 2) << " milliseconds if done correctly." << endl; delete d; cout << "Starting testRemoveAllInstances #18, filling in 100,000 numbers into the linked list to get it started." << endl; d = new DoublyLinkedList<int>; // Fill the list with a pattern of //1 2 2 3 3 3 4 4 4 4 1 2 2 3 3 3 4 4 4 4 ... for (int i = 0; i < 40000; i++) { for (int j = 0; j < i % 4 + 1; j++) { d->insertLast(i % 4 + 1); } } cout << " Finished inserting 100,000 numbers." << endl; cout << " Calling removeAllInstances to remove 30,000 3s. This should take about " << (benchmarkTime * 2) << " milliseconds." << endl; // delete all the 3s. start = std::chrono::high_resolution_clock::now(); d->removeAllInstances(3); end = std::chrono::high_resolution_clock::now(); diff = end - start; double actualTime = diff.count() / 1000.0; if (actualTime < (benchmarkTime * 2 * 1.5)) { // The 1.5 gives an extra 50% wiggle room cout << "Passed testRemoveAllInstances #18, completed removeAllInstances in " << actualTime << " milliseconds." << endl; } else { cout << "*** Failed testRemoveAllInstances #18, removeAllInstances took " << actualTime << " milliseconds." << endl; cout << "*** This which is much worse than the expected " << (benchmarkTime * 2) << " milliseconds." << endl; } delete d; } //911 void pressAnyKeyToContinue() { cout << "Press enter to continue..."; cin.get(); } int main() { // For your assignment, write the code to make these three methods work // You should not modify the code here in main. checkTestMemory("Memory Leak/Allocation Test #1", 0, ManageMemory::getTotalSize()); testGet(); checkTestMemory("Memory Leak/Allocation Test #2", 0, ManageMemory::getTotalSize()); pressAnyKeyToContinue(); testSquareBrackets(); checkTestMemory("Memory Leak/Allocation Test #3", 0, ManageMemory::getTotalSize()); pressAnyKeyToContinue(); testInsert(); checkTestMemory("Memory Leak/Allocation Test #4", 0, ManageMemory::getTotalSize()); pressAnyKeyToContinue(); testRemove(); checkTestMemory("Memory Leak/Allocation Test #5", 0, ManageMemory::getTotalSize()); pressAnyKeyToContinue(); testRemoveAllInstances(); checkTestMemory("Memory Leak/Allocation Test #6", 0, ManageMemory::getTotalSize()); pressAnyKeyToContinue(); return 0; }
30.2893
140
0.636094
clmay
8a3c87ddccb84137c5be1b49b56b7da005308f96
5,312
cpp
C++
message_sync/src/sync_visible.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
message_sync/src/sync_visible.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
message_sync/src/sync_visible.cpp
l756302098/ros_practice
4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7
[ "MIT" ]
null
null
null
#include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include "sensor_msgs/CompressedImage.h" #include "nav_msgs/Odometry.h" #include "std_msgs/String.h" #include "yidamsg/pointcloud_color.h" #include "boost/thread/thread.hpp" #include "boost/bind.hpp" #include "boost/thread/mutex.hpp" #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include <vector> #include <iostream> #include "base64.h" using namespace std; class message_sync_ros_node { private: ros::NodeHandle node_; ros::Publisher rgb_pub; typedef message_filters::sync_policies::ApproximateTime<nav_msgs::Odometry, sensor_msgs::Image, nav_msgs::Odometry> slamSyncPolicy; message_filters::Subscriber<nav_msgs::Odometry> *odom_sub_; message_filters::Subscriber<sensor_msgs::Image> *visible_sub_; message_filters::Subscriber<nav_msgs::Odometry> *yt_sub_; message_filters::Synchronizer<slamSyncPolicy> *sync_; std::string odom_topic; std::string visible_topic; std::string thermal_topic; std::string yt_topic; public: message_sync_ros_node(); ~message_sync_ros_node(); void callback(const nav_msgs::Odometry::ConstPtr &odom_data, const sensor_msgs::Image::ConstPtr &visible_image, const nav_msgs::Odometry::ConstPtr &yt_data); void update(); }; message_sync_ros_node::message_sync_ros_node() { ros::param::get("~/odom_topic", odom_topic); ros::param::get("~/visible_topic", visible_topic); ros::param::get("~/thermal_topic", thermal_topic); ros::param::get("~/yt_topic", yt_topic); std::cout << "odom_topic:" << odom_topic << std::endl; std::cout << "visible_topic:" << visible_topic << std::endl; std::cout << "thermal_topic:" << thermal_topic << std::endl; std::cout << "yt_topic:" << yt_topic << std::endl; rgb_pub = node_.advertise<yidamsg::pointcloud_color>("/yd/pointcloud/vt", 10); odom_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(node_, odom_topic, 1); visible_sub_ = new message_filters::Subscriber<sensor_msgs::Image>(node_, visible_topic, 1); yt_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(node_, yt_topic, 1); sync_ = new message_filters::Synchronizer<slamSyncPolicy>(slamSyncPolicy(20), *odom_sub_, *visible_sub_, *yt_sub_); sync_->registerCallback(boost::bind(&message_sync_ros_node::callback, this, _1, _2, _3)); } message_sync_ros_node::~message_sync_ros_node() { } void message_sync_ros_node::update() { } void message_sync_ros_node::callback(const nav_msgs::Odometry::ConstPtr &odom_data, const sensor_msgs::Image::ConstPtr &visible_image, const nav_msgs::Odometry::ConstPtr &yt_data) { // Test start // cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(visible_image, sensor_msgs::image_encodings::BGR8); // cv::Mat img = cv_ptr->image; // vector<uchar> vecImg; //Mat 图片数据转换为vector<uchar> // vector<int> vecCompression_params; // vecCompression_params.push_back(CV_IMWRITE_JPEG_QUALITY); // vecCompression_params.push_back(90); // imencode(".jpg", img, vecImg, vecCompression_params); // string imgbase64 = base64_encode(vecImg.data(), vecImg.size()); //实现图片的base64编码 // cout << imgbase64 << endl; // cout << "========================================" << endl; // string s_mat = base64_decode(imgbase64.data()); // std::vector<char> base64_img(s_mat.begin(), s_mat.end()); // img = cv::imdecode(base64_img, CV_LOAD_IMAGE_COLOR); // Test end nav_msgs::Odometry current_pose; current_pose = *odom_data; sensor_msgs::Image v_img; v_img = *visible_image; nav_msgs::Odometry yt_pose; yt_pose = *yt_data; yidamsg::pointcloud_color data; data.version = 1; data.v_format = ".jpg"; data.v_data = v_img.data; //data.pose = pose->pose; data.pos_x = current_pose.pose.pose.position.x; data.pos_y = current_pose.pose.pose.position.y; data.pos_z = current_pose.pose.pose.position.z; data.qua_x = current_pose.pose.pose.orientation.x; data.qua_y = current_pose.pose.pose.orientation.y; data.qua_z = current_pose.pose.pose.orientation.z; data.qua_w = current_pose.pose.pose.orientation.w; data.horizontal = yt_pose.pose.pose.position.x; data.vertical = yt_pose.pose.pose.position.z; rgb_pub.publish(data); std::cout << "callback +1 " << std::endl; } void callback1(const sensor_msgs::CompressedImage::ConstPtr &image1, const sensor_msgs::CompressedImage::ConstPtr &image2, const nav_msgs::Odometry::ConstPtr &data) { // Solve all of perception here... std::cout << "sync message" << std::endl; } void callback2(const sensor_msgs::CompressedImage::ConstPtr &image1, const sensor_msgs::CompressedImage::ConstPtr &image2, const nav_msgs::Odometry::ConstPtr &odom_data, const std_msgs::String::ConstPtr &yuntai_data) { // Solve all of perception here... std::cout << "sync message" << std::endl; } int main(int argc, char **argv) { ros::init(argc, argv, "message_sync_node"); message_sync_ros_node node; ROS_INFO("message_sync_node node started..."); ros::Rate rate(10); while (ros::ok()) { //node.update(); ros::spinOnce(); rate.sleep(); } return 0; }
35.651007
216
0.704443
l756302098
8a454539e831ef699299d1f035c75bf42a7977fc
1,285
cpp
C++
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
#include <bonsai_types.h> #include <tests/test_utils.cpp> s32 main(s32 ArgCount, const char** Args) { TestSuiteBegin("RNG", ArgCount, Args); #if 0 random_series Entropy = {43215426453}; const u32 TableSize = 256; u32 HitTable[TableSize] = {}; u32 MaxValue = 0; memory_arena* Memory = AllocateArena(Megabytes(8)); ansi_stream WordStream = AnsiStreamFromFile(CS(TEST_FIXTURES_PATH "/words.txt"), Memory); while (Remaining(&WordStream)) { counted_string Word = PopWordCounted(&WordStream); u32 HashValue = Hash(&Word) % TableSize; ++HitTable[HashValue]; if (HitTable[HashValue] > MaxValue) { MaxValue = HitTable[HashValue]; } } Log("Max: %u\n", MaxValue); u32 MappedRowSize = 128; for (u32 TableIndex = 0; TableIndex < TableSize; ++TableIndex) { u32 TableValue = HitTable[TableIndex]; r32 Value = (r32)TableValue / (r32)MaxValue; u32 Mapped = MapValueToRange(0, Value, MappedRowSize); for (u32 ValueIndex = 0; ValueIndex < MappedRowSize; ++ValueIndex) { if (ValueIndex < Mapped) { Log("."); } else { Log(" "); } } Log(" | (%u %u) \n", TableValue, Mapped); } #endif TestSuiteEnd(); exit(TestsFailed); }
19.469697
91
0.61323
jjbandit
8a45467f15bcfd2ae5452ce0bf768fb34d811ea3
1,764
cpp
C++
Gems/Atom/RPI/Code/Source/RPI.Builders/BuilderModule.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RPI/Code/Source/RPI.Builders/BuilderModule.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RPI/Code/Source/RPI.Builders/BuilderModule.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/RTTI/RTTI.h> #include <AzCore/Module/Module.h> #include <Model/ModelExporterComponent.h> #include <Model/ModelAssetBuilderComponent.h> #include <Model/MaterialAssetBuilderComponent.h> #include <BuilderComponent.h> namespace AZ { namespace RPI { /** * @class BuilderModule * @brief Exposes Atom Building components to the Asset Processor */ class BuilderModule final : public AZ::Module { public: AZ_RTTI(BuilderModule, "{CA15BD7F-01B4-4959-BEF2-81FA3AD2C834}", AZ::Module); BuilderModule() { m_descriptors.push_back(ModelExporterComponent::CreateDescriptor()); m_descriptors.push_back(ModelAssetBuilderComponent::CreateDescriptor()); m_descriptors.push_back(MaterialAssetBuilderComponent::CreateDescriptor()); m_descriptors.push_back(MaterialAssetDependenciesComponent::CreateDescriptor()); m_descriptors.push_back(BuilderComponent::CreateDescriptor()); } AZ::ComponentTypeList GetRequiredSystemComponents() const override { return AZ::ComponentTypeList(); } }; } // namespace RPI } // namespace AZ // DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM // The first parameter should be GemName_GemIdLower // The second should be the fully qualified name of the class above AZ_DECLARE_MODULE_CLASS(Gem_Atom_RPI_Edit_Builders, AZ::RPI::BuilderModule);
33.923077
100
0.672336
cypherdotXd
8a48d3123adb1a0ef856e62372e4ac7e6c70e767
1,135
cpp
C++
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
// // ex11_09.cpp // Exercise 11.09 // // Created by yG620 on 20/9/16 // // @Brief > Define a map that associates words with a list of line // numbers on which the word might occur. // // @KeyPoint 1. bug: error: expected unqualified-id before ‘[’ token // fix: using WordLineNo = map<string, list<int>>; WordLineNo can not be used directly. #include <iostream> #include <fstream> #include <sstream> #include <map> #include <list> #include <string> #include <algorithm> using namespace std; using WordLineNo = map<string, list<int>>; int main(int argc, char *argv[]) { ifstream ifs(argv[1]); string line; string word; int lineno = 0; WordLineNo Words; while (getline(ifs, line)) { ++lineno; istringstream word_line(line); while (word_line >> word) { Words[word].push_back(lineno); } } for (const auto &word : Words) { cout << word.first << " is on the "; for (const auto & lineno : word.second) cout << lineno << " line." << endl; } return 0; }
23.163265
103
0.570044
yG620
8a4c4a694e4d71b62c94db219088095f88468dfb
1,057
cc
C++
src/ballistica/media/component/collide_model.cc
Benefit-Zebra/ballistica
eb85df82cff22038e74a2d93abdcbe9cd755d782
[ "MIT" ]
317
2020-04-04T00:33:10.000Z
2022-03-28T01:07:09.000Z
src/ballistica/media/component/collide_model.cc
Alshahriah/ballistica
326f6677a0118667e93ce9034849622ebef706fa
[ "MIT" ]
315
2020-04-04T22:33:10.000Z
2022-03-31T22:50:02.000Z
src/ballistica/media/component/collide_model.cc
Alshahriah/ballistica
326f6677a0118667e93ce9034849622ebef706fa
[ "MIT" ]
97
2020-04-04T01:32:17.000Z
2022-03-16T19:02:59.000Z
// Released under the MIT License. See LICENSE for details. #include "ballistica/media/component/collide_model.h" #include "ballistica/game/game_stream.h" #include "ballistica/python/class/python_class_collide_model.h" #include "ballistica/scene/scene.h" namespace ballistica { CollideModel::CollideModel(const std::string& name, Scene* scene) : MediaComponent(name, scene), dead_(false) { assert(InGameThread()); if (scene) { if (GameStream* os = scene->GetGameStream()) { os->AddCollideModel(this); } } { Media::MediaListsLock lock; collide_model_data_ = g_media->GetCollideModelData(name); } assert(collide_model_data_.exists()); } CollideModel::~CollideModel() { MarkDead(); } void CollideModel::MarkDead() { if (dead_) { return; } if (Scene* s = scene()) { if (GameStream* os = s->GetGameStream()) { os->RemoveCollideModel(this); } } dead_ = true; } auto CollideModel::CreatePyObject() -> PyObject* { return PythonClassCollideModel::Create(this); } } // namespace ballistica
23.488889
65
0.69158
Benefit-Zebra
8a4e26a8e4cf447fdc5689bdf4642f807eb67c7b
2,379
cpp
C++
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
#include "Debug.h" Debug::Debug() { } Debug::~Debug() { } void Debug::init(SDL_Renderer* renderer, int windowWidth, int windowHeight) { if (TTF_Init() == -1) { printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); } m_blendedRect = createDebugRect(windowWidth, windowHeight, renderer); m_font = TTF_OpenFont("Assets/font.ttf", 20); m_textColor = { 255, 255, 255 }; m_posXLabel.loadFromRenderedText("X: ", m_textColor, m_font, renderer); m_posYLabel.loadFromRenderedText("Y: ", m_textColor, m_font, renderer); m_appleCountLabel.loadFromRenderedText("Apples Left: ", m_textColor, m_font, renderer); m_fpsLabel.loadFromRenderedText("FPS: ", m_textColor, m_font, renderer); m_fire.init(25, 25); m_fire.loadAnim("Assets/fire.png", renderer, 4, 0.08f, 0.2f); } void Debug::draw(SDL_Renderer* renderer, int windowWidth, int windowHeight, int posX, int posY, int appleNum, float fps) { SDL_Rect debugPanel = { 0, 0, windowWidth / 4, windowHeight }; SDL_RenderCopy(renderer, m_blendedRect, NULL, &debugPanel); m_posXLabel.draw(50, 50, renderer, NULL, 0.0); m_posYLabel.draw(50, 75, renderer, NULL, 0.0); m_appleCountLabel.draw(50, 100, renderer, NULL, 0.0); m_fpsLabel.draw(50, 125, renderer, NULL, 0); m_playerPosX.loadFromRenderedText(std::to_string(posX), m_textColor, m_font, renderer); m_playerPosY.loadFromRenderedText(std::to_string(posY), m_textColor, m_font, renderer); m_appleCount.loadFromRenderedText(std::to_string(appleNum), m_textColor, m_font, renderer); m_fpsValue.loadFromRenderedText(std::to_string(fps), m_textColor, m_font, renderer); m_playerPosX.draw(75, 50, renderer, NULL, 0.0); m_playerPosY.draw(75, 75, renderer, NULL, 0.0); m_appleCount.draw(175, 100, renderer, NULL, 0.0); m_fpsValue.draw(115, 125, renderer, NULL, 0.0); m_fire.draw(renderer); } SDL_Texture* Debug::createDebugRect(int windowWidth, int windowHeight, SDL_Renderer* renderer) { SDL_Surface* rect = NULL; SDL_Texture* blendedTex = NULL; rect = SDL_CreateRGBSurface(0, windowWidth, windowHeight, 32, 0, 0, 0, 0); if (rect == NULL) { printf("%s", SDL_GetError()); } blendedTex = SDL_CreateTextureFromSurface(renderer, rect); if (blendedTex == NULL) { printf("%s", SDL_GetError()); } SDL_SetTextureBlendMode(blendedTex, SDL_BLENDMODE_BLEND); SDL_SetTextureAlphaMod(blendedTex, 150); return blendedTex; }
29.012195
120
0.733922
GeraldBostock
8a4e6c5abfd83ae41c2ef4295e4459fc715167db
547
cpp
C++
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
23
2020-07-19T23:03:01.000Z
2022-03-07T15:06:26.000Z
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
1
2021-01-26T16:53:16.000Z
2021-01-26T23:20:54.000Z
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
4
2021-03-04T14:03:28.000Z
2021-05-27T05:36:40.000Z
#include <pybind11/pybind11.h> #include <iostream> #include "darray.hpp" #include "def_core.hpp" #include "def_darray.hpp" #include "def_kd_tree.hpp" PYBIND11_MODULE(_pyco_tree, m) { m.doc() = "PicoTree is a module for nearest neighbor searches and range searches " "using a KdTree. It wraps the C++ PicoTree library."; // Registered dtypes. PYBIND11_NUMPY_DTYPE(pyco_tree::Neighborf, index, distance); PYBIND11_NUMPY_DTYPE(pyco_tree::Neighbord, index, distance); pyco_tree::DefDArray(&m); pyco_tree::DefKdTree(&m); }
24.863636
78
0.725777
Jaybro
8a4f9ad140ed626e48096d30ccba9b6293f3575b
311
cpp
C++
code/controller/src/input/buttonEdge.cpp
ksmonkey123/moba3
77d5dbba528da391d82b8710fc4ce0959a031815
[ "MIT" ]
null
null
null
code/controller/src/input/buttonEdge.cpp
ksmonkey123/moba3
77d5dbba528da391d82b8710fc4ce0959a031815
[ "MIT" ]
11
2021-09-07T10:31:35.000Z
2021-11-01T18:19:12.000Z
code/controller/src/input/buttonEdge.cpp
ksmonkey123/moba3
77d5dbba528da391d82b8710fc4ce0959a031815
[ "MIT" ]
null
null
null
#include "buttonEdge.h" #include "buttons.h" ButtonEdge::ButtonEdge(byte buttonId) { this->buttonId = buttonId; } boolean ButtonEdge::test() { if (this->triggered != Buttons::read(this->buttonId)) { this->triggered = !this->triggered; return this->triggered; } return false; }
20.733333
59
0.643087
ksmonkey123
8a52f8bbfc86473a4bbca1b74a930f7e4cc77dcf
2,999
cpp
C++
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "modelitem.h" #include <algorithm> namespace LeechCraft { namespace Util { ModelItem::ModelItem () : Model_ { nullptr } { } ModelItem::ModelItem (QAbstractItemModel *model, const QModelIndex& idx, const ModelItem_wtr& parent) : ModelItemBase { parent } , Model_ { model } , SrcIdx_ { idx } { } ModelItem* ModelItem::EnsureChild (int row) { if (Children_.value (row)) return Children_.at (row).get (); if (Children_.size () <= row) Children_.resize (row + 1); const auto& childIdx = Model_->index (row, 0, SrcIdx_); Children_ [row] = std::make_shared<ModelItem> (Model_, childIdx, shared_from_this ()); return Children_.at (row).get (); } const QModelIndex& ModelItem::GetIndex () const { return SrcIdx_; } void ModelItem::RefreshIndex (int modelStartingRow) { if (SrcIdx_.isValid ()) SrcIdx_ = Model_->index (GetRow () - modelStartingRow, 0, Parent_.lock ()->GetIndex ()); } QAbstractItemModel* ModelItem::GetModel () const { return Model_; } ModelItem_ptr ModelItem::FindChild (QModelIndex index) const { index = index.sibling (index.row (), 0); const auto pos = std::find_if (Children_.begin (), Children_.end (), [&index] (const ModelItem_ptr& item) { return item->GetIndex () == index; }); return pos == Children_.end () ? ModelItem_ptr {} : *pos; } } }
34.079545
102
0.687229
MellonQ
a437049631a5705c20e9dfdabb0254f5fc0d7722
618
hpp
C++
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
1
2021-11-05T08:14:37.000Z
2021-11-05T08:14:37.000Z
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
null
null
null
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
null
null
null
// Exercise 7.3 - STL Algorithms // // by Scott Sidoli // // 5-28-19 // // lessThan.hpp // // lessThan class with global function and function object. #ifndef lessThan_hpp #define lessThan_hpp extern double threshold; class lessThan { private: double boundary; // Threshold value public: lessThan(double value); // Constructor with a threshold value ~lessThan(); // Destructor bool operator () (double value); // Overloaded operator }; // Global function template template <typename T> bool less_than(const T& value) { return (value < threshold); } #endif
16.702703
66
0.658576
scottsidoli
a437b643959e89e896b98d0db8a85b7ed6181114
638
cpp
C++
003_CodeForces/Theatre_Square.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
003_CodeForces/Theatre_Square.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
003_CodeForces/Theatre_Square.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { long long int n, m, a; cin >> n >> m >> a; long long int res = 1; long long int left = (n / a); long long int top = (m / a); if(a==1) { res=(n*m); cout<<res; } else if (n * m <= a * a) cout << 1; else { res = res * left * top; if (n % a != 0) { if (m % a != 0) { res = res + top + left + 1; } else res += top; } else res += left; cout << res; } return 0; }
15.95
43
0.336991
Sahil1515
a439385e0bbb111129b6abaf7205130a96182ba2
1,835
cpp
C++
RenderCore/render/core/rendering/RenderScrollView.cpp
gubaojian/weexuikit
2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213
[ "Apache-2.0" ]
46
2019-06-25T11:05:49.000Z
2021-12-31T04:47:53.000Z
RenderCore/render/core/rendering/RenderScrollView.cpp
gubaojian/weexuikit
2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213
[ "Apache-2.0" ]
5
2019-10-16T06:54:37.000Z
2020-02-06T08:22:40.000Z
RenderCore/render/core/rendering/RenderScrollView.cpp
gubaojian/weexuikit
2eaf54e4c1f4a1c94398b0990ad9767e3ffb9213
[ "Apache-2.0" ]
18
2019-05-22T09:29:23.000Z
2021-04-28T02:12:42.000Z
// // Created by furture on 2018/10/29. // #include <render/platform/common/log.h> #include <render/platform/transforms/TranslateTransformOperation.h> #include "RenderScrollView.h" #include "RenderLayer.h" #include "RenderSliverBody.h" namespace blink{ RenderScrollView::RenderScrollView() { mRenderScrollBody = new RenderSliverBody(); addChild(mRenderScrollBody); onUpdateScrollDirection(); } RenderScrollView::~RenderScrollView() { if(mRenderScrollBody != nullptr){ mRenderScrollBody = nullptr; } } const char* RenderScrollView::renderName() const { return "RenderScrollView"; } void RenderScrollView::onUpdateScrollDirection(){ if(getScrollDirection() == ScrollDirection::Vertical){ mRenderScrollBody->style()->setFlexDirection(blink::EFlexDirection::FlowColumn); mRenderScrollBody->style()->setLogicalHeight(blink::LengthType::MinContent); mRenderScrollBody->style()->setLogicalWidth(blink::LengthType::Auto); }else{ mRenderScrollBody->style()->setFlexDirection(blink::EFlexDirection::FlowRow); mRenderScrollBody->style()->setLogicalWidth(blink::LengthType::MinContent); mRenderScrollBody->style()->setLogicalHeight(blink::LengthType::Auto); } } void RenderScrollView::layoutSliver() { if(getScrollDirection() == ScrollDirection::Vertical){ mRenderScrollBody->setLogicalWidth(availableLogicalWidth()); }else{ mRenderScrollBody->setLogicalHeight(availableLogicalHeight(AvailableLogicalHeightType::ExcludeMarginBorderPadding)); } mRenderScrollBody->setScrollOffset(getScrollOffset().x(), getScrollOffset().y()); mRenderScrollBody->layoutBody(); } }
29.126984
128
0.679019
gubaojian
a43a1975be6bc1664f07c5d1eea75494fde1e886
334
cpp
C++
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
8
2018-11-13T14:33:26.000Z
2018-11-23T18:01:38.000Z
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
2
2019-08-05T07:21:28.000Z
2019-08-23T06:24:23.000Z
/* # main routines # # This file is part of SMosMod. # Copyright (c) 2017-2018, Imperial College London # For licensing information, see the LICENSE file distributed with the SMosMod # software package. */ #include <iostream> #include "world.hpp" #include "agent.hpp" int main() { std::cout << "Hi Ben\n"; return 0; }
15.904762
79
0.676647
kaidokert
a43f462c5aab064b525b2a0f5661660a93c41e94
670
cpp
C++
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; bool breaksDirection(int direction, int previousInt, int currentInt) { int difference = currentInt - previousInt; if(direction > 0){ return direction < 0; } return direction >0; } // Time Complexity - O(N) // Space Complexity - O(1) bool isMonotonic(vector<int> array) { if(array.size() <= 2) { return true; } int direction = array[1] - array[0]; for(int i=2; i<array.size(); i++) { if(direction == 0) { direction = array[i] - array[i - 1]; continue; } if(breaksDirection(direction, array[i-1], array[i])) return false; } return true; }
18.611111
68
0.656716
jabbala-ai
a44378ec6a223a5b951c8fbc990324f48cbecfe6
1,366
cpp
C++
test/unit-tests/metafs/mim/mdpage_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
test/unit-tests/metafs/mim/mdpage_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
test/unit-tests/metafs/mim/mdpage_test.cpp
YongJin-Cho/poseidonos
c07a0240316d4536aa09f22d7977604f3650d752
[ "BSD-3-Clause" ]
null
null
null
#include "src/metafs/include/metafs_service.h" #include "src/metafs/mim/mdpage.h" #include "src/include/memory.h" #include "test/unit-tests/array_models/interface/i_array_info_mock.h" #include "test/unit-tests/metafs/include/metafs_mock.h" #include <gtest/gtest.h> namespace pos { TEST(MDPage, Mdpage_Normal) { const size_t TEST_PAGE_SIZE = 4096; const MetaLpnType lpn = 10; const FileDescriptorType fd = 9; void* buf = pos::Memory<TEST_PAGE_SIZE>::Alloc(1); bool result = false; MockIArrayInfo* info = new MockIArrayInfo(); EXPECT_CALL(*info, GetName()).Times(2); MockMetaFs* metaFs = new MockMetaFs(info, false); EXPECT_CALL(*metaFs, GetEpochSignature()).Times(2); MDPage* page = new MDPage(buf); EXPECT_NE(page->GetDataBuf(), nullptr); std::string arrayName = info->GetName(); page->Make(lpn, fd, arrayName); uint32_t signature = page->GetMfsSignature(); EXPECT_NE(signature, 0); result = page->CheckFileMismatch(fd); EXPECT_EQ(result, true); result = page->CheckLpnMismatch(lpn); EXPECT_EQ(result, true); result = page->CheckValid(arrayName); EXPECT_EQ(result, true); // null check page->AttachControlInfo(); page->ClearCtrlInfo(); delete metaFs; delete info; delete page; pos::Memory<TEST_PAGE_SIZE>::Free(buf); } } // namespace pos
23.964912
69
0.685212
YongJin-Cho
a444168398f0f4149c70f26a6f2627bf0e3bec2f
3,239
cc
C++
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // Extract trajectories from the G4 internals and add them to the event. // Skip trajectories with too few points. // // $Id: addPointTrajectories.cc,v 1.5 2014/01/18 04:31:53 kutschke Exp $ // $Author: kutschke $ // $Date: 2014/01/18 04:31:53 $ // // Original author Rob Kutschke // // Notes: // 1) The data product is filled via two phase construction. // This avoids extra copies of the (often long) vector of points. // If and when we get move aware STL libraries we can go back // to single phase construction. // #include "G4AttDef.hh" #include "G4Event.hh" #include "G4TrajectoryContainer.hh" #include "G4TrajectoryPoint.hh" #include "Mu2eG4/inc/addPointTrajectories.hh" #include "Mu2eG4/inc/SimParticleHelper.hh" #include <iostream> #include <map> using namespace std; namespace mu2e{ void addPointTrajectories ( const G4Event* g4event, PointTrajectoryCollection& pointTrajectories, const SimParticleHelper& spHelper, CLHEP::Hep3Vector const& mu2eOriginInWorld, int minSteps ){ typedef PointTrajectoryCollection::key_type key_type; typedef PointTrajectoryCollection::mapped_type mapped_type; typedef std::map<key_type,mapped_type> map_type; // Check that there is information to be copied. G4TrajectoryContainer const* trajectories = g4event->GetTrajectoryContainer(); if ( !trajectories ) return; TrajectoryVector const& vect = *trajectories->GetVector(); if ( vect.empty() ) return; // Need to pre-sort before insertion into the collection; do it using this map. map_type tempMap; // Insert mostly empty PointTrajecotry objects into the temporary map. These contain // only the ID and an empty std::vector so they are small. for ( size_t i=0; i<vect.size(); ++i){ G4VTrajectory const& traj = *vect[i]; key_type kid(spHelper.particleKeyFromG4TrackID(traj.GetTrackID())); // Cut if too few points. Need to make this a variable. if ( traj.GetPointEntries() < minSteps ) { continue; } tempMap[kid] = PointTrajectory(kid.asInt()); } // Phase 1 of construction of the data product. See note 1. pointTrajectories.insert( tempMap.begin(), tempMap.end() ); // Phase 2 of construction. Add the vector of points. for ( size_t i=0; i<vect.size(); ++i){ G4VTrajectory const& traj = *vect[i]; // Which trajectory are we looking for? key_type kid(spHelper.particleKeyFromG4TrackID(traj.GetTrackID())); // Locate this trajectory in the data product. // It is OK if we do not find it since we applied cuts above. PointTrajectoryCollection::iterator iter = pointTrajectories.find(kid); if ( iter == pointTrajectories.end() ){ continue; } PointTrajectory& ptraj = iter->second; // Add the points. for ( int j=0; j<traj.GetPointEntries(); ++j){ G4VTrajectoryPoint const& pt = *traj.GetPoint(j); ptraj.addPoint( pt.GetPosition()-mu2eOriginInWorld ); } } // end phase 2 } // end addPointTrajectories. } // end namespace mu2e
34.457447
89
0.654523
bonventre
a44480c119d80f046701fd4b6879a11dfcfc7a66
1,252
hpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-dbus-monitor/1.0+gitAUTOINC+92907da08e-r1/git/src/watch.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-dbus-monitor/1.0+gitAUTOINC+92907da08e-r1/git/src/watch.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
4
2018-08-22T12:27:38.000Z
2022-03-04T06:44:48.000Z
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/phosphor-dbus-monitor/1.0+gitAUTOINC+92907da08e-r1/git/src/watch.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
#pragma once #include "data_types.hpp" namespace phosphor { namespace dbus { namespace monitoring { /** @class Watch * @brief Watch interface. * * The start method is invoked by main() on all watches of any type * at application startup, to allow watches to perform custom setup * or initialization. Typical implementations might register dbus * callbacks or perform queries. * * The callback method is invoked by main() on all watches of any * type at application startup, after all watches have performed * their setup. Typical implementations will forward the call * to their associated callback. */ class Watch { public: Watch() = default; Watch(const Watch&) = default; Watch(Watch&&) = default; Watch& operator=(const Watch&) = default; Watch& operator=(Watch&&) = default; virtual ~Watch() = default; /** @brief Start the watch. */ virtual void start() = 0; /** @brief Invoke the callback associated with the watch. */ virtual void callback(Context ctx) = 0; /** @brief Invoke the callback associated with the watch. */ virtual void callback(Context ctx, sdbusplus::message::message& msg){}; }; } // namespace monitoring } // namespace dbus } // namespace phosphor
26.083333
75
0.691693
sotaoverride
a4448ded5c325147709398d0e9fec5960b2e9246
221
cpp
C++
cf/1140/a.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
2
2021-06-09T12:27:07.000Z
2021-06-11T12:02:03.000Z
cf/1140/a.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
1
2021-09-08T12:00:05.000Z
2021-09-08T14:52:30.000Z
cf/1140/a.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int ans, n, a, mx; int main() { scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d", &a); mx = max(mx, a); ans += i == mx; } printf("%d\n", ans); return 0; }
15.785714
30
0.484163
tusikalanse
a449dffe39d6b571b1878899ab40bf9a94d50dc9
3,293
hpp
C++
src/motioncore/utility/fiber_thread_pool/singleton_pooled_fixedsize_stack.hpp
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
6
2021-11-05T00:39:47.000Z
2022-02-26T16:42:55.000Z
src/motioncore/utility/fiber_thread_pool/singleton_pooled_fixedsize_stack.hpp
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
7
2021-11-07T06:53:00.000Z
2022-03-23T11:46:40.000Z
src/motioncore/utility/fiber_thread_pool/singleton_pooled_fixedsize_stack.hpp
Udbhavbisarya23/MOTION2NX
eb26f639d8c1729cebfa85dd3bf41b770cebe92b
[ "MIT" ]
7
2021-11-04T12:01:07.000Z
2022-03-29T12:15:23.000Z
// This file is adapted from context/pooled_fixedsize_stack.hpp of Boost 1.72.0. // Copyright Oliver Kowalke 2014 / Lennart Braun 2020 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SINGLETON_POOLED_FIXEDSIZE_STACK_H #define SINGLETON_POOLED_FIXEDSIZE_STACK_H #include <atomic> #include <boost/pool/poolfwd.hpp> #include <cstddef> #include <cstdlib> #include <new> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/pool/singleton_pool.hpp> #include <boost/context/detail/config.hpp> #include <boost/context/stack_context.hpp> #include <boost/context/stack_traits.hpp> template<std::size_t stack_size, typename traitsT > class basic_singleton_pooled_fixedsize_stack { private: class storage { private: std::atomic< std::size_t > use_count_; struct pool_tag {}; typedef boost::singleton_pool<pool_tag, stack_size, boost::default_user_allocator_malloc_free> storage_pool; public: storage() : use_count_( 0) { BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= stack_size) ); } boost::context::stack_context allocate() { void * vp = storage_pool::malloc(); if ( ! vp) { throw std::bad_alloc(); } boost::context::stack_context sctx; sctx.size = stack_size; sctx.sp = static_cast< char * >( vp) + sctx.size; #if defined(BOOST_USE_VALGRIND) sctx.valgrind_stack_id = VALGRIND_STACK_REGISTER( sctx.sp, vp); #endif return sctx; } void deallocate( boost::context::stack_context & sctx) BOOST_NOEXCEPT_OR_NOTHROW { BOOST_ASSERT( sctx.sp); BOOST_ASSERT( traits_type::is_unbounded() || ( traits_type::maximum_size() >= sctx.size) ); #if defined(BOOST_USE_VALGRIND) VALGRIND_STACK_DEREGISTER( sctx.valgrind_stack_id); #endif void * vp = static_cast< char * >( sctx.sp) - sctx.size; storage_pool::free( vp); } friend void intrusive_ptr_add_ref( storage * s) noexcept { ++s->use_count_; } friend void intrusive_ptr_release( storage * s) noexcept { if ( 0 == --s->use_count_) { delete s; } } }; boost::intrusive_ptr< storage > storage_; public: typedef traitsT traits_type; // parameters are kept for compatibility of interface basic_singleton_pooled_fixedsize_stack( std::size_t = 0, std::size_t = 0, std::size_t = 0) BOOST_NOEXCEPT_OR_NOTHROW : storage_( new storage() ) { } boost::context::stack_context allocate() { return storage_->allocate(); } void deallocate( boost::context::stack_context & sctx) BOOST_NOEXCEPT_OR_NOTHROW { storage_->deallocate( sctx); } }; template <std::size_t stack_size> using singleton_pooled_fixedsize_stack = basic_singleton_pooled_fixedsize_stack<stack_size, boost::context::stack_traits>; #endif // SINGLETON_POOLED_FIXEDSIZE_STACK_H
31.970874
116
0.645308
Udbhavbisarya23
a44b6796e9dc3bb76fb39df63a71aca44cadcb98
475
cpp
C++
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
1,403
2016-09-28T21:48:07.000Z
2022-03-31T23:58:57.000Z
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
70
2016-10-13T20:15:58.000Z
2022-01-12T23:51:12.000Z
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
122
2016-10-23T15:33:44.000Z
2022-03-07T07:41:23.000Z
/* * GLCoreExtensions.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLCoreExtensions.h" namespace LLGL { #define LLGL_DEF_GL_EXT_PROCS // Include inline header for object definitions #include "GLCoreExtensionsDecl.inl" #undef LLGL_DEF_GL_EXT_PROCS } // /namespace LLGL // ================================================================================
16.964286
86
0.606316
beldenfox
a44b8dc645cbe205aea2d0de308e8afefcf2b52d
3,302
cpp
C++
Source/VirtualMachine/Values/NumberValue.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
1
2021-06-19T05:53:35.000Z
2021-06-19T05:53:35.000Z
Source/VirtualMachine/Values/NumberValue.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
6
2021-07-29T05:44:03.000Z
2021-07-29T05:56:58.000Z
Source/VirtualMachine/Values/NumberValue.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
null
null
null
#include "NumberValue.h" #include "UndefinedValue.h" #include "StringValue.h" #include "StringFormat.h" #include "BooleanValue.h" namespace Powder { NumberValue::NumberValue() { this->number = 0.0; } NumberValue::NumberValue(double number) { this->number = number; } /*virtual*/ NumberValue::~NumberValue() { } /*virtual*/ Value* NumberValue::Copy() const { return new NumberValue(this->number); } /*virtual*/ Value* NumberValue::CombineWith(const Value* value, MathInstruction::MathOp mathOp, Executor* executor) const { switch (mathOp) { case MathInstruction::MathOp::FACTORIAL: { // TODO: There is actually a factorial for non-integers, and why not support it? It might not be trivial to calculate, though. double rounded = double(uint32_t(this->number)); double factorial = 1.0; while (rounded-- > 0.0) factorial *= rounded; return new NumberValue(factorial); } case MathInstruction::MathOp::NEGATE: { return new NumberValue(-this->number); } } const NumberValue* numberValue = dynamic_cast<const NumberValue*>(value); if (numberValue) { switch (mathOp) { case MathInstruction::MathOp::ADD: { return new NumberValue(this->number + numberValue->number); } case MathInstruction::MathOp::SUBTRACT: { return new NumberValue(this->number - numberValue->number); } case MathInstruction::MathOp::MULTIPLY: { return new NumberValue(this->number * numberValue->number); } case MathInstruction::MathOp::DIVIDE: { return new NumberValue(this->number / numberValue->number); } case MathInstruction::MathOp::MODULUS: { return new NumberValue(::fmod(this->number, numberValue->number)); } case MathInstruction::MathOp::EQUAL: { return new BooleanValue(this->number == numberValue->number); } case MathInstruction::MathOp::NOT_EQUAL: { return new BooleanValue(this->number != numberValue->number); } case MathInstruction::MathOp::LESS_THAN: { return new BooleanValue(this->number < numberValue->number); } case MathInstruction::MathOp::LESS_THAN_OR_EQUAL: { return new BooleanValue(this->number <= numberValue->number); } case MathInstruction::MathOp::GREATER_THAN: { return new BooleanValue(this->number > numberValue->number); } case MathInstruction::MathOp::GREATER_THAN_OR_EQUAL: { return new BooleanValue(this->number >= numberValue->number); } } return new UndefinedValue(); } if (mathOp == MathInstruction::MathOp::ADD) { const StringValue* stringValue = dynamic_cast<const StringValue*>(value); if (stringValue) return new StringValue(this->ToString() + stringValue->ToString()); } return new UndefinedValue(); } /*virtual*/ std::string NumberValue::ToString() const { return FormatString("%f", this->number); } /*virtual*/ bool NumberValue::FromString(const std::string& str) { char* endPtr = nullptr; this->number = ::strtod(str.c_str(), &endPtr); if (endPtr == str.c_str()) return false; return true; } /*virtual*/ bool NumberValue::AsBoolean() const { return this->number != 0.0; } /*virtual*/ double NumberValue::AsNumber() const { return this->number; } }
24.641791
131
0.668686
spencerparkin
a44d08b1a745b64adf235c554bf2802622cad15e
686
cc
C++
mediastreamtrack.cc
Step7750/go-webrtc
373c85055825f2668d4ae0e9d7e80a4f0952bde1
[ "BSD-3-Clause" ]
null
null
null
mediastreamtrack.cc
Step7750/go-webrtc
373c85055825f2668d4ae0e9d7e80a4f0952bde1
[ "BSD-3-Clause" ]
2
2019-03-13T05:28:30.000Z
2019-03-13T05:29:12.000Z
mediastreamtrack.cc
Step7750/go-webrtc
373c85055825f2668d4ae0e9d7e80a4f0952bde1
[ "BSD-3-Clause" ]
null
null
null
#include <_cgo_export.h> // Allow calling certain Go functions. #include "mediastreamtrack.h" #include "webrtc/api/mediastreaminterface.h" using namespace webrtc; const char* CGO_MediaStreamTrack_ID(CGO_MediaStreamTrack t) { return ((MediaStreamTrackInterface*)t)->id().c_str(); } bool CGO_MediaStreamTrack_Enabled(CGO_MediaStreamTrack t) { return ((MediaStreamTrackInterface*)t)->enabled(); } void CGO_MediaStreamTrack_SetEnabled(CGO_MediaStreamTrack t, bool x) { ((MediaStreamTrackInterface*)t)->set_enabled(x); } bool CGO_MediaStreamTrack_Ended(CGO_MediaStreamTrack t) { return ((MediaStreamTrackInterface*)t)->state() == MediaStreamTrackInterface::TrackState::kEnded; }
28.583333
98
0.790087
Step7750
a4569a35daa91f7a3d46db798aea0e059fe962fc
989
cc
C++
examples/string.cc
knocknote/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
7
2019-08-29T05:22:05.000Z
2020-07-07T15:35:50.000Z
examples/string.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-07-12T09:43:31.000Z
2019-09-10T03:36:45.000Z
examples/string.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-10-25T05:35:30.000Z
2020-07-21T21:40:52.000Z
#include "libhtml5.h" static void stringTest() { { html5::string s = "hello world"; std::cout << s << std::endl; html5::console->log(s); } { std::string s = "hello"; html5::string s2 = s; s2 += "world"; std::cout << s2 << std::endl; } { html5::string a = "hello"; html5::string b = "world"; html5::string c = a + b; std::cout << c << std::endl; } { html5::string s = "hello world"; for (const auto &splitted : s.split(" ")) { html5::string v = splitted; std::cout << v << std::endl; std::cout << "includes h? " << v.includes("h") << std::endl; } } { html5::string s = "0123456789abcdef"; std::string primitiveStr = s.substr(1, 10).toUpperCase(); std::cout << primitiveStr << std::endl; } } EMSCRIPTEN_BINDINGS(string) { emscripten::function("stringTest", &stringTest); }
24.725
72
0.484328
knocknote
a45dbe8adcc031b4731466ff2dbd9a407a60b83f
4,144
cpp
C++
cmake/tests/cxx11_std_type_traits.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
3
2017-04-06T16:36:38.000Z
2018-05-19T11:28:54.000Z
cmake/tests/cxx11_std_type_traits.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
1
2018-08-13T17:42:55.000Z
2018-08-13T18:20:23.000Z
cmake/tests/cxx11_std_type_traits.cpp
brycelelbach/hpx
94582f5dc26e889cdcf80913975ff33b7f975285
[ "BSL-1.0" ]
2
2018-05-25T06:33:50.000Z
2019-02-25T20:09:13.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2015 Agustin Berge // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #include <type_traits> struct callable { callable() {} explicit callable(int) {} int operator()(){ return 0; } }; enum enum_type { enum_value = 0 }; union union_type { int i; double d; }; int main() { using namespace std; int x = 0; add_const<int>::type* rc = &x; decay<int const&>::type* d = &x; result_of<callable()>::type* ro = &x; is_convertible<int, long>::type ic; is_constructible<callable, int>::type icc; true_type tt; false_type ft; integral_constant<bool, false>::type icb; bool_constant<false>::type bc; is_void<void>::type iv; is_null_pointer<nullptr_t>::type inp; is_integral<int>::type ii; is_floating_point<double>::type ifp; is_array<int[]>::type ia; is_enum<enum_type>::type ie; is_union<union_type>::type ut; is_class<callable>::type icall; is_function<void()>::type ift; is_pointer<int*>::type ip; is_lvalue_reference<int&>::type ilr; is_rvalue_reference<int&&>::type irr; is_member_object_pointer<int>::type imop; is_member_function_pointer<int>::type imfp; is_fundamental<int>::type ifund; is_arithmetic<int>::type iar; is_scalar<int>::type isc; is_object<int>::type io; is_compound<int>::type icomp; is_reference<int&>::type ir; is_member_pointer<int>::type imp; is_const<int const>::type iconst; is_volatile<int volatile>::type ivol; is_trivial<int>::type itr; is_trivially_copyable<int>::type icpy; is_standard_layout<int>::type ilay; is_pod<int>::type ipd; is_literal_type<int>::type ilit; is_empty<int>::type iempty; is_polymorphic<int>::type ipoly; is_abstract<int>::type iabst; is_signed<int>::type isign; is_unsigned<int>::type iusign; is_trivially_constructible<int>::type itctr; is_nothrow_constructible<int>::type intctr; is_default_constructible<int>::type idctr; is_trivially_default_constructible<int>::type itdctr; is_nothrow_default_constructible<int>::type indctr; is_copy_constructible<int>::type icctr; is_trivially_copy_constructible<int>::type itcctr; is_nothrow_copy_constructible<int>::type incctr; is_move_constructible<int>::type imctr; is_trivially_move_constructible<int>::type itmctr; is_nothrow_move_constructible<int>::type inmctr; is_assignable<int, double>::type iass; is_trivially_assignable<int, double>::type itass; is_nothrow_assignable<int, double>::type inass; is_copy_assignable<int>::type icass; is_trivially_copy_assignable<int>::type itcass; is_nothrow_copy_assignable<int>::type incass; is_move_assignable<int>::type imass; is_trivially_move_assignable<int>::type itmass; is_nothrow_move_assignable<int>::type inmass; is_destructible<int>::type idtr; is_trivially_destructible<int>::type itdtr; is_nothrow_destructible<int>::type indtr; alignment_of<int>::type algn; rank<int>::type rnk; extent<int>::type ext; is_same<int, double>::type same; is_base_of<int, double>::type ibo; remove_cv<int const>::type rcv; remove_const<int const>::type rconst; remove_volatile<int volatile>::type rv; add_cv<int>::type acv = 0; add_volatile<int>::type av; remove_reference<int&>::type rref; add_lvalue_reference<int>::type alref = x; add_rvalue_reference<int>::type arref = int(); remove_pointer<int*>::type rptr; add_pointer<int>::type aptr; make_signed<unsigned int>::type msign; make_unsigned<int>::type musign; remove_extent<int[1]>::type rext; remove_all_extents<int[1]>::type raext; aligned_storage<1, 2>::type aligns; enable_if<true, int>::type eif; conditional<true, int, double>::type cond; underlying_type<enum_type>::type utyp; }
33.152
80
0.669884
brycelelbach
a46099fe7b14fd6177cedd9034bd22c05d0a0431
826
hpp
C++
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T02:32:49.000Z
2018-10-16T02:32:49.000Z
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
13
2018-10-23T20:35:10.000Z
2018-11-23T22:44:32.000Z
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T03:11:39.000Z
2018-10-16T03:11:39.000Z
#ifndef MUTILS_H #define MUTILS_H #ifndef M_PI #define M_PI 3.1415926535 #endif struct Mat3f { float data[9]; }; void mat3f_zero_inplace(Mat3f* mat); Mat3f mat3f_zero_copy(); void mat3f_identity_inplace(Mat3f* mat); Mat3f mat3f_identity_copy(); void mat3f_projection_inplace(Mat3f* mat, float left, float right, float top, float bottom); Mat3f mat3f_projection_copy(float left, float right, float top, float bottom); void mat3f_transformation_inplace(Mat3f* mat, float scale, float angle, float transx, float transy); Mat3f mat3f_transformation_copy(float scale, float angle, float transx, float transy); Mat3f mat3f_camera_copy(float scalex, float scaley, float angle, float transx, float transy); void mat3f_camera_inplace(Mat3f* mat, float scalex, float scaley, float angle, float transx, float transy); #endif
29.5
107
0.789346
2535Rover
a46133e620f6a02c50affc1241cc1d7f8eb65411
13,049
cpp
C++
services/camera/libcameraservice/hidl/HidlCameraService.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
services/camera/libcameraservice/hidl/HidlCameraService.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
services/camera/libcameraservice/hidl/HidlCameraService.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hidl/Convert.h> #include <hidl/HidlCameraService.h> #include <hidl/HidlCameraDeviceUser.h> #include <hidl/AidlCameraDeviceCallbacks.h> #include <hidl/AidlCameraServiceListener.h> #include <hidl/HidlTransportSupport.h> namespace android { namespace frameworks { namespace cameraservice { namespace service { namespace V2_0 { namespace implementation { using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService; using hardware::hidl_vec; using hardware::cameraservice::utils::conversion::convertToHidl; using hardware::cameraservice::utils::conversion::B2HStatus; using hardware::Void; using device::V2_0::implementation::H2BCameraDeviceCallbacks; using device::V2_0::implementation::HidlCameraDeviceUser; using service::V2_0::implementation::H2BCameraServiceListener; using HCameraMetadataType = frameworks::cameraservice::common::V2_0::CameraMetadataType; using HVendorTag = frameworks::cameraservice::common::V2_0::VendorTag; using HVendorTagSection = frameworks::cameraservice::common::V2_0::VendorTagSection; using HProviderIdAndVendorTagSections = frameworks::cameraservice::common::V2_0::ProviderIdAndVendorTagSections; sp<HidlCameraService> gHidlCameraService; sp<HidlCameraService> HidlCameraService::getInstance(android::CameraService *cs) { gHidlCameraService = new HidlCameraService(cs); return gHidlCameraService; } Return<void> HidlCameraService::getCameraCharacteristics(const hidl_string& cameraId, getCameraCharacteristics_cb _hidl_cb) { android::CameraMetadata cameraMetadata; HStatus status = HStatus::NO_ERROR; binder::Status serviceRet = mAidlICameraService->getCameraCharacteristics(String16(cameraId.c_str()), &cameraMetadata); HCameraMetadata hidlMetadata; if (!serviceRet.isOk()) { switch(serviceRet.serviceSpecificErrorCode()) { // No ERROR_CAMERA_DISCONNECTED since we're in the same process. case hardware::ICameraService::ERROR_ILLEGAL_ARGUMENT: ALOGE("%s: Camera ID %s does not exist!", __FUNCTION__, cameraId.c_str()); status = HStatus::ILLEGAL_ARGUMENT; break; default: ALOGE("Get camera characteristics from camera service failed: %s", serviceRet.toString8().string()); status = B2HStatus(serviceRet); } _hidl_cb(status, hidlMetadata); return Void(); } const camera_metadata_t *rawMetadata = cameraMetadata.getAndLock(); convertToHidl(rawMetadata, &hidlMetadata); _hidl_cb(status, hidlMetadata); cameraMetadata.unlock(rawMetadata); return Void(); } Return<void> HidlCameraService::connectDevice(const sp<HCameraDeviceCallback>& hCallback, const hidl_string& cameraId, connectDevice_cb _hidl_cb) { // Here, we first get ICameraDeviceUser from mAidlICameraService, then save // that interface in the newly created HidlCameraDeviceUser impl class. if (mAidlICameraService == nullptr) { _hidl_cb(HStatus::UNKNOWN_ERROR, nullptr); return Void(); } sp<hardware::camera2::ICameraDeviceUser> deviceRemote = nullptr; // Create a hardware::camera2::ICameraDeviceCallback object which internally // calls callback functions passed through hCallback. sp<H2BCameraDeviceCallbacks> hybridCallbacks = new H2BCameraDeviceCallbacks(hCallback); if (!hybridCallbacks->initializeLooper()) { ALOGE("Unable to handle callbacks on device, cannot connect"); _hidl_cb(HStatus::UNKNOWN_ERROR, nullptr); return Void(); } sp<hardware::camera2::ICameraDeviceCallbacks> callbacks = hybridCallbacks; binder::Status serviceRet = mAidlICameraService->connectDevice( callbacks, String16(cameraId.c_str()), String16(""), std::unique_ptr<String16>(), hardware::ICameraService::USE_CALLING_UID, /*out*/&deviceRemote); HStatus status = HStatus::NO_ERROR; if (!serviceRet.isOk()) { ALOGE("%s: Unable to connect to camera device", __FUNCTION__); status = B2HStatus(serviceRet); _hidl_cb(status, nullptr); return Void(); } // Now we create a HidlCameraDeviceUser class, store the deviceRemote in it, // and return that back. All calls on that interface will be forwarded to // the AIDL interface. sp<HidlCameraDeviceUser> hDeviceRemote = new HidlCameraDeviceUser(deviceRemote); if (!hDeviceRemote->initStatus()) { ALOGE("%s: Unable to initialize camera device HIDL wrapper", __FUNCTION__); _hidl_cb(HStatus::UNKNOWN_ERROR, nullptr); return Void(); } hybridCallbacks->setCaptureResultMetadataQueue(hDeviceRemote->getCaptureResultMetadataQueue()); _hidl_cb(status, hDeviceRemote); return Void(); } void HidlCameraService::addToListenerCacheLocked(sp<HCameraServiceListener> hListener, sp<hardware::ICameraServiceListener> csListener) { mListeners.emplace_back(std::make_pair(hListener, csListener)); } sp<hardware::ICameraServiceListener> HidlCameraService::searchListenerCacheLocked(sp<HCameraServiceListener> hListener, bool shouldRemove) { // Go through the mListeners list and compare the listener with the HIDL // listener registered. auto it = mListeners.begin(); sp<ICameraServiceListener> csListener = nullptr; for (;it != mListeners.end(); it++) { if (hardware::interfacesEqual(it->first, hListener)) { break; } } if (it != mListeners.end()) { csListener = it->second; if (shouldRemove) { mListeners.erase(it); } } return csListener; } Return<void> HidlCameraService::addListener(const sp<HCameraServiceListener>& hCsListener, addListener_cb _hidl_cb) { std::vector<hardware::CameraStatus> cameraStatusAndIds{}; HStatus status = addListenerInternal<HCameraServiceListener>( hCsListener, &cameraStatusAndIds); if (status != HStatus::NO_ERROR) { _hidl_cb(status, {}); return Void(); } hidl_vec<HCameraStatusAndId> hCameraStatusAndIds; //Convert cameraStatusAndIds to HIDL and call callback convertToHidl(cameraStatusAndIds, &hCameraStatusAndIds); _hidl_cb(status, hCameraStatusAndIds); return Void(); } Return<void> HidlCameraService::addListener_2_1(const sp<HCameraServiceListener2_1>& hCsListener, addListener_2_1_cb _hidl_cb) { std::vector<hardware::CameraStatus> cameraStatusAndIds{}; HStatus status = addListenerInternal<HCameraServiceListener2_1>( hCsListener, &cameraStatusAndIds); if (status != HStatus::NO_ERROR) { _hidl_cb(status, {}); return Void(); } hidl_vec<frameworks::cameraservice::service::V2_1::CameraStatusAndId> hCameraStatusAndIds; //Convert cameraStatusAndIds to HIDL and call callback convertToHidl(cameraStatusAndIds, &hCameraStatusAndIds); _hidl_cb(status, hCameraStatusAndIds); return Void(); } template<class T> HStatus HidlCameraService::addListenerInternal(const sp<T>& hCsListener, std::vector<hardware::CameraStatus>* cameraStatusAndIds) { if (mAidlICameraService == nullptr) { return HStatus::UNKNOWN_ERROR; } if (hCsListener == nullptr || cameraStatusAndIds == nullptr) { ALOGE("%s listener and cameraStatusAndIds must not be NULL", __FUNCTION__); return HStatus::ILLEGAL_ARGUMENT; } sp<hardware::ICameraServiceListener> csListener = nullptr; // Check the cache for previously registered callbacks { Mutex::Autolock l(mListenerListLock); csListener = searchListenerCacheLocked(hCsListener); if (csListener == nullptr) { // Wrap an hCsListener with AidlCameraServiceListener and pass it to // CameraService. csListener = new H2BCameraServiceListener(hCsListener); // Add to cache addToListenerCacheLocked(hCsListener, csListener); } else { ALOGE("%s: Trying to add a listener %p already registered", __FUNCTION__, hCsListener.get()); return HStatus::ILLEGAL_ARGUMENT; } } binder::Status serviceRet = mAidlICameraService->addListenerHelper(csListener, cameraStatusAndIds, true); HStatus status = HStatus::NO_ERROR; if (!serviceRet.isOk()) { ALOGE("%s: Unable to add camera device status listener", __FUNCTION__); status = B2HStatus(serviceRet); return status; } cameraStatusAndIds->erase(std::remove_if(cameraStatusAndIds->begin(), cameraStatusAndIds->end(), [this](const hardware::CameraStatus& s) { bool supportsHAL3 = false; binder::Status sRet = mAidlICameraService->supportsCameraApi(String16(s.cameraId), hardware::ICameraService::API_VERSION_2, &supportsHAL3); return !sRet.isOk() || !supportsHAL3; }), cameraStatusAndIds->end()); return HStatus::NO_ERROR; } Return<HStatus> HidlCameraService::removeListener(const sp<HCameraServiceListener>& hCsListener) { if (hCsListener == nullptr) { ALOGE("%s listener must not be NULL", __FUNCTION__); return HStatus::ILLEGAL_ARGUMENT; } sp<ICameraServiceListener> csListener = nullptr; { Mutex::Autolock l(mListenerListLock); csListener = searchListenerCacheLocked(hCsListener, /*removeIfFound*/true); } if (csListener != nullptr) { mAidlICameraService->removeListener(csListener); } else { ALOGE("%s Removing unregistered listener %p", __FUNCTION__, hCsListener.get()); return HStatus::ILLEGAL_ARGUMENT; } return HStatus::NO_ERROR; } Return<void> HidlCameraService::getCameraVendorTagSections(getCameraVendorTagSections_cb _hidl_cb) { sp<VendorTagDescriptorCache> gCache = VendorTagDescriptorCache::getGlobalVendorTagCache(); if (gCache == nullptr) { _hidl_cb(HStatus::UNKNOWN_ERROR, {}); return Void(); } const std::unordered_map<metadata_vendor_id_t, sp<android::VendorTagDescriptor>> &vendorIdsAndTagDescs = gCache->getVendorIdsAndTagDescriptors(); if (vendorIdsAndTagDescs.size() == 0) { _hidl_cb(HStatus::UNKNOWN_ERROR, {}); return Void(); } hidl_vec<HProviderIdAndVendorTagSections> hTagIdsAndVendorTagSections; hTagIdsAndVendorTagSections.resize(vendorIdsAndTagDescs.size()); size_t j = 0; for (auto &vendorIdAndTagDescs : vendorIdsAndTagDescs) { hidl_vec<HVendorTagSection> hVendorTagSections; sp<VendorTagDescriptor> desc = vendorIdAndTagDescs.second; const SortedVector<String8>* sectionNames = desc->getAllSectionNames(); size_t numSections = sectionNames->size(); std::vector<std::vector<HVendorTag>> tagsBySection(numSections); int tagCount = desc->getTagCount(); std::vector<uint32_t> tags(tagCount); desc->getTagArray(tags.data()); for (int i = 0; i < tagCount; i++) { HVendorTag vt; vt.tagId = tags[i]; vt.tagName = desc->getTagName(tags[i]); vt.tagType = (HCameraMetadataType) desc->getTagType(tags[i]); ssize_t sectionIdx = desc->getSectionIndex(tags[i]); tagsBySection[sectionIdx].push_back(vt); } hVendorTagSections.resize(numSections); for (size_t s = 0; s < numSections; s++) { hVendorTagSections[s].sectionName = (*sectionNames)[s].string(); hVendorTagSections[s].tags = tagsBySection[s]; } HProviderIdAndVendorTagSections &hProviderIdAndVendorTagSections = hTagIdsAndVendorTagSections[j]; hProviderIdAndVendorTagSections.providerId = vendorIdAndTagDescs.first; hProviderIdAndVendorTagSections.vendorTagSections = std::move(hVendorTagSections); j++; } _hidl_cb(HStatus::NO_ERROR, hTagIdsAndVendorTagSections); return Void(); } } // implementation } // V2_0 } // service } // cameraservice } // frameworks } // android
41.823718
100
0.681278
Dreadwyrm
a462f206ae2aef8aadf617dcbb48b77567d6b1c9
18,876
cpp
C++
projects/physics/shape/shapepolytope.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
projects/physics/shape/shapepolytope.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
projects/physics/shape/shapepolytope.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
//********************************************* // Physics engine // Copyright (c) Rylogic Ltd 2006 //********************************************* #include "physics/utility/stdafx.h" #include "pr/physics/shape/shapepolytope.h" #include "pr/physics/shape/shape.h" #include "pr/physics/collision/contactmanifold.h" #include "physics/utility/profile.h" #define PR_PH_DBG_SUPVERT 0 using namespace pr; using namespace pr::ph; // Construct the shape ShapePolytope& ShapePolytope::set(std::size_t vert_count, std::size_t face_count, std::size_t size_in_bytes, m4x4 const& shape_to_model, MaterialId material_id, uint flags) { m_base.set(EShape_Polytope, size_in_bytes, shape_to_model, material_id, flags); m_vert_count = static_cast<uint>(vert_count); m_face_count = static_cast<uint>(face_count); CalcBBox(*this, m_base.m_bbox); return *this; } // Return the volume of the polytope float pr::ph::CalcVolume(ShapePolytope const& shape) { float volume = 0; for (ShapePolyFace const* f = shape.face_begin(), *f_end = shape.face_end(); f != f_end; ++f) { v4 const& a = shape.vertex(f->m_index[0]); v4 const& b = shape.vertex(f->m_index[1]); v4 const& c = shape.vertex(f->m_index[2]); volume += Triple(a, b, c); // Triple product is volume x 6 } if (volume < maths::tinyf) { PR_INFO(PR_DBG_PHYSICS, FmtS("PRPhysics: Shape %s with volume = %f\n", GetShapeTypeStr(shape.m_base.m_type), volume)); volume = maths::tinyf; } return volume / 6.0f; } // Return the centre of mass position of the polytope v4 pr::ph::CalcCentreOfMass(ShapePolytope const& shape) { float volume = 0; v4 centre_of_mass = v4Zero; for (ShapePolyFace const* f = shape.face_begin(), *f_end = shape.face_end(); f != f_end; ++f) { v4 const& a = shape.vertex(f->m_index[0]); v4 const& b = shape.vertex(f->m_index[1]); v4 const& c = shape.vertex(f->m_index[2]); float vol_x6 = Triple(a, b, c); // Triple product is volume x 6 centre_of_mass += vol_x6 * (a + b + c); // Divide by 4 at end volume += vol_x6; } if (volume < maths::tinyf) { PR_INFO(PR_DBG_PHYSICS, FmtS("PRPhysics: Shape %s with volume = %f\n", GetShapeTypeStr(shape.m_base.m_type), volume)); volume = Abs(volume + maths::tinyf); } centre_of_mass /= volume * 4.0f; centre_of_mass.w = 0.0f; // 'centre_of_mass' is an offset from the current model origin return centre_of_mass; } // Shift the verts of the polytope so they are centred on a new position void pr::ph::ShiftCentre(ShapePolytope& shape, v4& shift) { PR_ASSERT(PR_DBG_PHYSICS, shift.w == 0.0f, ""); if( FEql(shift,pr::v4Zero) ) return; for( v4 *v = shape.vert_begin(), *v_end = shape.vert_end(); v != v_end; ++v ) *v -= shift; shape.m_base.m_shape_to_model.pos += shift; shift = pr::v4Zero; } // Return the bounding box for a polytope BBox& pr::ph::CalcBBox(ShapePolytope const& shape, BBox& bbox) { bbox.reset(); for( v4 const *v = shape.vert_begin(), *v_end = shape.vert_end(); v != v_end; ++v ) Grow(bbox, *v); return bbox; } // Return the inertia tensor for the polytope. // Note: The polytope must be in the correct space before calculating its inertia // (i.e. at the centre of mass, or not). Calculating the inertia then translating // it does not give the same result (with this code at least). m3x4 pr::ph::CalcInertiaTensor(ShapePolytope const& shape) { // Assume mass == 1.0, you can multiply by mass later. // For improved accuracy the next 3 variables, the determinant vol, and its calculation should be changed to double float volume = 0; // Technically this variable accumulates the volume times 6 v4 diagonal_integrals = v4Zero; // Accumulate matrix main diagonal integrals [x*x, y*y, z*z] v4 off_diagonal_integrals = v4Zero; // Accumulate matrix off-diagonal integrals [y*z, x*z, x*y] for (ShapePolyFace const* f = shape.face_begin(), *f_end = shape.face_end(); f != f_end; ++f) { v4 const& a = shape.vertex(f->m_index[0]); v4 const& b = shape.vertex(f->m_index[1]); v4 const& c = shape.vertex(f->m_index[2]); float vol_x6 = Triple(a, b, c); // Triple product is volume x 6 volume += vol_x6; for (int i = 0, j = 1, k = 2; i != 3; ++i, (++j) %= 3, (++k) %= 3) { diagonal_integrals[i] += ( a[i] * b[i] + b[i] * c[i] + c[i] * a[i] + a[i] * a[i] + b[i] * b[i] + c[i] * c[i] ) * vol_x6; // Divide by 60.0f later off_diagonal_integrals[i] += ( a[j] * b[k] + b[j] * c[k] + c[j] * a[k] + a[j] * c[k] + b[j] * a[k] + c[j] * b[k] + a[j] * a[k] * 2.0f + b[j] * b[k] * 2.0f + c[j] * c[k] * 2.0f ) * vol_x6; // Divide by 120.0f later } } if (volume < maths::tinyf) { PR_INFO(PR_DBG_PHYSICS, FmtS("PRPhysics: Shape %s with volume = %f\n", GetShapeTypeStr(shape.m_base.m_type), volume)); volume = maths::tinyf; } volume /= 6.0f; diagonal_integrals /= volume * 60.0f; // Divide by total volume off_diagonal_integrals /= volume * 120.0f; return m3x4( v4(diagonal_integrals.y + diagonal_integrals.z, -off_diagonal_integrals.z, -off_diagonal_integrals.y, 0), v4(-off_diagonal_integrals.z, diagonal_integrals.x + diagonal_integrals.z, -off_diagonal_integrals.x, 0), v4(-off_diagonal_integrals.y, -off_diagonal_integrals.x, diagonal_integrals.x + diagonal_integrals.y, 0)); } // Return mass properties for the polytope MassProperties& pr::ph::CalcMassProperties(ShapePolytope const& shape, float density, MassProperties& mp) { mp.m_centre_of_mass = CalcCentreOfMass(shape); mp.m_mass = CalcVolume(shape) * density; mp.m_os_inertia_tensor = CalcInertiaTensor(shape); return mp; } // Return a support vertex for a polytope v4 pr::ph::SupportVertex(ShapePolytope const& shape, v4 const& direction, std::size_t hint_vert_id, std::size_t& sup_vert_id) { PR_DECLARE_PROFILE(PR_PROFILE_SUPPORT_VERTS, phSupVertPoly); PR_PROFILE_SCOPE(PR_PROFILE_SUPPORT_VERTS, phSupVertPoly); PR_ASSERT(PR_DBG_PHYSICS, hint_vert_id < shape.m_vert_count, "Invalid hint vertex index"); PR_ASSERT(PR_DBG_PHYSICS, Length(direction) > maths::tinyf, "Direction is too short"); PR_EXPAND(PR_PH_DBG_SUPVERT, StartFile("C:/DeleteMe/collision_supverttrace.pr_script");) PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::PhShape("polytope", "8000FF00", shape, m4x4Identity);) PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Line("sup_direction", "FFFFFF00", v4Origin, direction);) PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::GroupStart("SupportVertexTrace");) // Find the support vertex using a 'hill-climbing' search // Start at the hint vertex and look for a neighbour that is more extreme in the // support direction. When no neighbours are closer we've found the support vertex sup_vert_id = (hint_vert_id < shape.m_vert_count) * hint_vert_id; // Make sure we don't get an invalid id to start with v4 const* support_vertex = &shape.vertex(sup_vert_id); v4 const* nearest_vertex; float sup_dist = Dot3(*support_vertex, direction); bool use_first_nbr = true; PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Box("start", "FF00FFFF", *support_vertex, 0.05f);) do { nearest_vertex = support_vertex; ShapePolyNbrs const& nbrhdr = shape.nbr(sup_vert_id); for( uint8 const *n = nbrhdr.begin() + !use_first_nbr, *n_end = nbrhdr.end(); n != n_end; ++n ) { // There are two possible ways we can do this, either by moving to the // first neighbour that is more extreme or by testing all neighbours. // The disadvantages are searching a non-optimal path to the support // vertex or searching excessive neighbours respectively. // Test in batches of 4 as a trade off if( use_first_nbr || n_end - n < 4 ) { use_first_nbr = false; float dist = Dot3(shape.vertex(*n), direction); if( dist > sup_dist + maths::tinyf ) { sup_vert_id = *n; sup_dist = dist; support_vertex = &shape.vertex(sup_vert_id); PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Line("to", "FF0000FF", *nearest_vertex, *support_vertex);) PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Box("v", "FF0000FF", *support_vertex, 0.05f);) break; } } else { m4x4 nbrs; nbrs.x = shape.vertex(*(n )); nbrs.y = shape.vertex(*(n + 1)); nbrs.z = shape.vertex(*(n + 2)); nbrs.w = shape.vertex(*(n + 3)); nbrs = Transpose4x4(nbrs); v4 dots = nbrs * direction; std::size_t id = sup_vert_id; if( dots.x > sup_dist ) { sup_dist = dots.x; sup_vert_id = *(n + 0); } if( dots.y > sup_dist ) { sup_dist = dots.y; sup_vert_id = *(n + 1); } if( dots.z > sup_dist ) { sup_dist = dots.z; sup_vert_id = *(n + 2); } if( dots.w > sup_dist ) { sup_dist = dots.w; sup_vert_id = *(n + 3); } if( sup_vert_id != id ) { support_vertex = &shape.vertex(sup_vert_id); PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Line("to", "FF0000FF", *nearest_vertex, *support_vertex);) PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::Box("v", "FF0000FF", *support_vertex, 0.05f);) break; } n += 3; } } } while( support_vertex != nearest_vertex ); PR_EXPAND(PR_PH_DBG_SUPVERT, ldr::GroupEnd();) PR_EXPAND(PR_PH_DBG_SUPVERT, EndFile();) //// Check that we've found the most extreme vertex //#if PR_DBG_PHYSICS == 1 //v4 const* sup_vert = support_vertex; //for( v4 const *v = shape.vert_begin(), *v_end = shape.vert_end(); v != v_end; ++v ) // if( Dot3(*v - *sup_vert, direction) > maths::tinyf ) // sup_vert = v; //PR_ASSERT(PR_DBG_PHYSICS, support_vertex == sup_vert); //#endif//PR_DBG_PHYSICS == 1 return *support_vertex; } // Returns the longest/shortest axis of a polytope in 'direction' (in polytope space) // Searching starts at 'hint_vert_id'. The spanning vertices are 'vert_id0' and 'vert_id1' // 'major' is true for the longest axis, false for the shortest axis void pr::ph::GetAxis(ShapePolytope const& shape, v4& direction, std::size_t hint_vert_id, std::size_t& vert_id0, std::size_t& vert_id1, bool major) { PR_ASSERT(PR_DBG_PHYSICS, hint_vert_id < shape.m_vert_count, ""); float eps = major ? maths::tinyf : -maths::tinyf; vert_id0 = hint_vert_id; v4 const* V1 = &shape.vertex(vert_id0); v4 const* V2 = &shape.vertex(*shape.nbr(vert_id0).begin()); // The first neighbour is always the most distant direction = *V1 - *V2; float span_lenSq = LengthSq(direction); do { hint_vert_id = vert_id0; // Look for a neighbour with a longer span ShapePolyNbrs const& nbr = shape.nbr(vert_id0); for( uint8 const *n = nbr.begin() + 1, *n_end = nbr.end(); n < n_end; ++n ) { v4 const* v1 = &shape.vertex(*n); v4 const* v2 = &shape.vertex(*shape.nbr(*n).begin()); v4 span = *v1 - *v2; float lenSq = LengthSq(span); if( (lenSq > span_lenSq + eps) == major ) { span_lenSq = lenSq; direction = span; vert_id0 = *n; break; } } } while( hint_vert_id != vert_id0 ); vert_id1 = *shape.nbr(vert_id0).begin(); } // Return the number of vertices in a polytope uint pr::ph::VertCount(ShapePolytope const& shape) { return shape.m_vert_count; } // Return the number of edges in a polytope uint pr::ph::EdgeCount(ShapePolytope const& shape) { // The number of edges in the polytope is the number of // neighbours minus the artificial neighbours over 2. uint nbr_count = 0; for( ShapePolyNbrs const* n = shape.nbr_begin(), *n_end = shape.nbr_end(); n != n_end; ++n ) nbr_count += n->m_count; return (nbr_count - shape.m_vert_count) / 2; } // Return the number of faces in a polytope uint pr::ph::FaceCount(ShapePolytope const& shape) { // Use Euler's formula: F - E + V = 2. => F = 2 + E - V return 2 + EdgeCount(shape) - shape.m_vert_count; } // Generate the verts of a polytope. 'verts' should point to a buffer of v4's with // a length equal to the value returned from 'VertCount' void pr::ph::GenerateVerts(ShapePolytope const& shape, v4* verts, v4* verts_end) { PR_ASSERT(PR_DBG_PHYSICS, uint(verts_end - verts) >= VertCount(shape), "Vert buffer too small"); (void)verts_end; memcpy(verts, shape.vert_begin(), sizeof(v4) * shape.m_vert_count); } // Generate the edges of a polytope from the verts and their neighbours. 'edges' should // point to a buffer of 2*the number of edges returned from 'EdgeCount' void pr::ph::GenerateEdges(ShapePolytope const& shape, v4* edges, v4* edges_end) { PR_ASSERT(PR_DBG_PHYSICS, uint(edges_end - edges) >= 2 * EdgeCount(shape), "Edge buffer too small"); uint vert_index = 0; uint nbr_index = 1; ShapePolyNbrs const* nbrs = &shape.nbr(vert_index); while( vert_index < shape.m_vert_count && edges + 2 <= edges_end ) { *edges++ = shape.vertex(vert_index); *edges++ = shape.vertex(nbrs->begin()[nbr_index]); // Increment 'vert_index' and 'nbr_index' to refer // to the next edge. Only consider edges for which // the neighbouring vertex has a higher value. This // ensures we only add each edge once. do { if( ++nbr_index == nbrs->m_count ) { if( ++vert_index == shape.m_vert_count ) break; nbrs = &shape.nbr(vert_index); nbr_index = 1; } } while( nbrs->begin()[nbr_index] < vert_index ); } } namespace { struct Edge { uint m_i0, m_i1; }; inline bool operator == (Edge const& lhs, Edge const& rhs) { return (lhs.m_i0 == rhs.m_i0 && lhs.m_i1 == rhs.m_i1) || (lhs.m_i0 == rhs.m_i1 && lhs.m_i1 == rhs.m_i0); } }//namespace polytope // Generate faces for a polytope from the verts and their neighbours. void pr::ph::GenerateFaces(ShapePolytope const& shape, uint* faces, uint* faces_end) { // Helper object to fill the remaining faces with degenerates. // Since the verts of the polytope may not all be on the convex hull we may // generate less faces than 'faces_end - faces' struct FillRemaining { uint *&m_faces, *m_faces_end; FillRemaining& operator = (FillRemaining const&) {return *this;}// no copying FillRemaining(uint*& faces, uint* faces_end) : m_faces(faces), m_faces_end(faces_end) { if( m_faces != m_faces_end ) *m_faces = 0; } ~FillRemaining() // Fill the remaining faces with degenerates { while( m_faces != m_faces_end ) *m_faces++ = 0; } } fill_remaining(faces, faces_end); // Record the start address uint* faces_start = faces; // Create the starting faces and handle cases for polys with less than 3 verts for( uint i = 0; i != 3; ++i ) { if( faces == faces_end || i == shape.m_vert_count ) return; *faces++ = i; } for( uint i = 3; i-- != 0; ) { if( faces == faces_end ) return; *faces++ = i; } uint const edge_stack_size = 50; pr::Stack<Edge, edge_stack_size> edges; // Generate the convex hull for( uint i = 3; i != shape.m_vert_count; ++i ) { v4 const& v = shape.vertex(i); for( uint* f = faces_start, *f_end = faces; f != f_end; f += 3 ) { v4 const& a = shape.vertex(*(f + 0)); v4 const& b = shape.vertex(*(f + 1)); v4 const& c = shape.vertex(*(f + 2)); // If 'v' is in front of this face add its edges to the edge stack and remove the face if( Triple(v - a, b - a, c - a) >= 0.0f ) { // Add the edges of this face to the edge stack (remove duplicates) Edge ed = {*(f + 2), *(f + 0)}; for( uint j = 0; j != 3; ++j, ed.m_i0 = ed.m_i1, ed.m_i1 = *(f + j) ) { // Look for this edge in the stack Edge* e = edges.begin(); for( ; e != edges.end() && !(*e == ed); ++e ) {} if( e == edges.end() ) edges.push(ed); // Add the unique edge else *e = edges.pop(); // Erase the duplicate if( edges.size() == edge_stack_size ) { PR_ASSERT(PR_DBG_PHYSICS, false, "Edge stack not big enough. GenerateFaces aborted early"); return; } } // Remove the face faces -= 3; *(f + 0) = *(faces + 0); *(f + 1) = *(faces + 1); *(f + 2) = *(faces + 2); f -= 3; f_end -= 3; } } // Add new faces for any edges that are in the edge stack while( !edges.empty() ) { if( faces + 3 > faces_end ) return; Edge e = edges.pop(); *faces++ = i; *faces++ = e.m_i0; *faces++ = e.m_i1; } } } // Remove the face data from a polytope void pr::ph::StripFaces(ShapePolytope& shape) { if( shape.m_face_count == 0 ) return; uint8* base = reinterpret_cast<uint8*>(&shape); uint8* src = reinterpret_cast<uint8*>(&shape.nbr(0)); uint8* dst = reinterpret_cast<uint8*>( shape.face_begin()); std::size_t size = shape.m_base.m_size; std::size_t bytes_to_move = size - (src - base); std::size_t bytes_removed = shape.m_face_count * sizeof(ShapePolyFace); // Move the remainder of the polytope data back over the face data. memmove(dst, src, bytes_to_move); shape.m_base.m_size -= bytes_removed; shape.m_face_count = 0; } // Validate a polytope. Always returns true but performs assert checks bool pr::ph::Validate(ShapePolytope const& shape, bool check_com) { shape;check_com; #if PR_DBG_PHYSICS uint num_real_nbrs = 0; for( uint i = 0; i != shape.m_vert_count; ++i ) { // Check the neighbours of each vertex. ShapePolyNbrs const& nbrs = shape.nbr(i); // All polytope verts should have an artifical neighbour plus >0 real neighbours PR_ASSERT(PR_DBG_PHYSICS, nbrs.m_count > 1, ""); // Count the number of real neighbours in the polytope num_real_nbrs += (nbrs.m_count - 1); // Check each neighbour for( PolyIdx const *j = nbrs.begin(); j != nbrs.end(); ++j ) { // Check that the neighbour refers to a vert in the polytope PR_ASSERT(PR_DBG_PHYSICS, *j < shape.m_vert_count, ""); // Check that the neighbour refers to a different vert in the polytope PR_ASSERT(PR_DBG_PHYSICS, *j != i, ""); // Check that there is a neighbour in both directions between 'i' and 'j' ShapePolyNbrs const& nbr_nbrs = shape.nbr(*j); bool found = j == nbrs.begin();// artificial neighbours don't point back for( PolyIdx const *k = nbr_nbrs.begin(); k != nbr_nbrs.end() && !found; ++k ) { found = *k == i; } PR_ASSERT(PR_DBG_PHYSICS, found, ""); // Check that all neighbours (apart from the artifical neighbour) are unique if( j != nbrs.begin() ) { for( PolyIdx const* k = j + 1; k != nbrs.end(); ++k ) { PR_ASSERT(PR_DBG_PHYSICS, *k != *j, ""); } } } } // Check the polytope describes a closed polyhedron if( shape.m_face_count != 0 ) { PR_ASSERT(PR_DBG_PHYSICS, shape.m_face_count - (num_real_nbrs / 2) + shape.m_vert_count == 2, "The polytope is not a closed polyhedron!"); } // Check the polytope is in centre of mass frame if( check_com ) { //m3x4 inertia = CalcInertiaTensor(shape); } #endif//PR_DBG_PHYSICS return true; }
36.16092
173
0.645211
psryland
a463c9f976c318b6903977d5688ed16e88207e0d
5,030
cpp
C++
NitroXMR/src/miner/crypto/CryptoNight.cpp
quartz010/XMR
bf9f462662ad80e7a7361c9844b02ef520b90431
[ "MIT" ]
4
2017-10-25T05:16:33.000Z
2018-10-25T14:22:30.000Z
NitroXMR/src/miner/crypto/CryptoNight.cpp
quartz010/XMR
bf9f462662ad80e7a7361c9844b02ef520b90431
[ "MIT" ]
null
null
null
NitroXMR/src/miner/crypto/CryptoNight.cpp
quartz010/XMR
bf9f462662ad80e7a7361c9844b02ef520b90431
[ "MIT" ]
3
2018-04-05T14:25:50.000Z
2018-10-25T14:22:32.000Z
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2016-2017 XMRig <support@xmrig.com> * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "crypto/CryptoNight.h" #include "crypto/CryptoNight_p.h" #include "crypto/CryptoNight_test.h" #include "net/Job.h" #include "net/JobResult.h" #include "Options.h" void (*cryptonight_hash_ctx)(const void *input, size_t size, void *output, cryptonight_ctx *ctx) = nullptr; static void cryptonight_av1_aesni(const void *input, size_t size, void *output, struct cryptonight_ctx *ctx) { cryptonight_hash<0x80000, MEMORY, 0x1FFFF0, false>(input, size, output, ctx); } static void cryptonight_av2_aesni_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x80000, MEMORY, 0x1FFFF0, false>(input, size, output, ctx); } static void cryptonight_av3_softaes(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_hash<0x80000, MEMORY, 0x1FFFF0, true>(input, size, output, ctx); } static void cryptonight_av4_softaes_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x80000, MEMORY, 0x1FFFF0, true>(input, size, output, ctx); } #ifndef XMRIG_NO_AEON static void cryptonight_lite_av1_aesni(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_hash<0x40000, MEMORY_LITE, 0xFFFF0, false>(input, size, output, ctx); } static void cryptonight_lite_av2_aesni_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x40000, MEMORY_LITE, 0xFFFF0, false>(input, size, output, ctx); } static void cryptonight_lite_av3_softaes(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_hash<0x40000, MEMORY_LITE, 0xFFFF0, true>(input, size, output, ctx); } static void cryptonight_lite_av4_softaes_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x40000, MEMORY_LITE, 0xFFFF0, true>(input, size, output, ctx); } void (*cryptonight_variations[8])(const void *input, size_t size, void *output, cryptonight_ctx *ctx) = { cryptonight_av1_aesni, cryptonight_av2_aesni_double, cryptonight_av3_softaes, cryptonight_av4_softaes_double, cryptonight_lite_av1_aesni, cryptonight_lite_av2_aesni_double, cryptonight_lite_av3_softaes, cryptonight_lite_av4_softaes_double }; #else void (*cryptonight_variations[4])(const void *input, size_t size, void *output, cryptonight_ctx *ctx) = { cryptonight_av1_aesni, cryptonight_av2_aesni_double, cryptonight_av3_softaes, cryptonight_av4_softaes_double }; #endif bool CryptoNight::hash(const Job &job, JobResult &result, cryptonight_ctx *ctx) { cryptonight_hash_ctx(job.blob(), job.size(), result.result, ctx); return *reinterpret_cast<uint64_t*>(result.result + 24) < job.target(); } bool CryptoNight::init(int algo, int variant) { if (variant < 1 || variant > 4) { return false; } # ifndef XMRIG_NO_AEON const int index = algo == Options::ALGO_CRYPTONIGHT_LITE ? (variant + 3) : (variant - 1); # else const int index = variant - 1; # endif cryptonight_hash_ctx = cryptonight_variations[index]; return selfTest(algo); } void CryptoNight::hash(const uint8_t *input, size_t size, uint8_t *output, cryptonight_ctx *ctx) { cryptonight_hash_ctx(input, size, output, ctx); } bool CryptoNight::selfTest(int algo) { if (cryptonight_hash_ctx == nullptr) { return false; } char output[64]; struct cryptonight_ctx *ctx = (struct cryptonight_ctx*) _mm_malloc(sizeof(struct cryptonight_ctx), 16); ctx->memory = (uint8_t *) _mm_malloc(MEMORY * 2, 16); cryptonight_hash_ctx(test_input, 76, output, ctx); _mm_free(ctx->memory); _mm_free(ctx); return memcmp(output, algo == Options::ALGO_CRYPTONIGHT_LITE ? test_output1 : test_output0, (Options::i()->doubleHash() ? 64 : 32)) == 0; }
34.689655
141
0.716103
quartz010
a468ecf79ee24066e45867ca1d343e8bf12e8017
1,405
cpp
C++
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const void *a, const void *b) { if (*((int*)a + 1) != *((int*)b + 1)) return -( *((int*)a + 1) - *((int*)b + 1) ); else { int na = *(int*)a; int nb = *(int*)b; char sa[15], sb[15]; int i = 0; while(na) { sa[i++] = na % 10 + '0'; na /= 10; } sa[i] = '\0'; for (int j = 0; j <= (i - 1) / 2; j++) { char temp = sa[j]; sa[j] = sa[i - 1 - j]; sa[i - 1 - j] = temp; } //printf ("%s\n", sa); i = 0; while(nb) { sb[i++] = nb % 10 + '0'; nb /= 10; } sb[i]= '\0'; for (int j = 0; j <= (i - 1) / 2; j++) { char temp = sb[j]; sb[j] = sb[i - 1 - j]; sb[i - 1 - j] = temp; } int len1 = strlen(sa), len2 = strlen(sb); if (len1 != len2) return len1 - len2; else return strcmp(sa, sb); } } int a[1000005][2]; int main() { char name[20]; gets(name); FILE * fp; fp = fopen(name, "r"); int T; fscanf (fp, "%d", &T); while(T--) { int n, i = 0; memset(a, 0, sizeof(a)); fscanf (fp, "%d", &n); int tmp = n; while(!feof(fp) && tmp--) { fscanf (fp, "%d %d", &a[i][0], &a[i][1]); i++; } qsort(a, n, sizeof(int)*2, cmp); if (a[0][1] < 100) printf ("This OJ is too easy for PQ Dashen!\n"); else { int i = 0; while(a[i][1] >= 100) { printf ("%d\n", a[i][0]); i++; } } if (T > 0) printf ("\n"); } fclose(fp); }
16.927711
83
0.427758
xiabee
a46964e68b1f23bacee69105f0c84c5a0ef5168e
512
cpp
C++
20181002/G.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
20181002/G.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
20181002/G.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ifstream cin("G.in"); vector<int> F(1, 1); for (int i = 2; i <= 9; i++) { F.push_back(F[F.size() - 1] * i); } // for (int i = 0; i < 9; i++) cout << F[i] << endl; int T; cin >> T; while (T--) { int n; cin >> n; for (int i = F.size() - 1; i >= 0; i--) { if (F[i] <= n) { n -= F[i]; } } if (n == 0) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
18.285714
54
0.386719
webturing
a46d3da945cf26cea99d3ae1b42a5dcc459a2b7e
103
hpp
C++
SWB/Projekt-SWB-ALL/Projekt-SWB/lib/src/EURtoPLN.hpp
Mikbac/Engineering-studies
348e29ef0418d44dd0fc99cdb6c7883e2694bb30
[ "BSD-3-Clause" ]
null
null
null
SWB/Projekt-SWB-ALL/Projekt-SWB/lib/src/EURtoPLN.hpp
Mikbac/Engineering-studies
348e29ef0418d44dd0fc99cdb6c7883e2694bb30
[ "BSD-3-Clause" ]
null
null
null
SWB/Projekt-SWB-ALL/Projekt-SWB/lib/src/EURtoPLN.hpp
Mikbac/Engineering-studies
348e29ef0418d44dd0fc99cdb6c7883e2694bb30
[ "BSD-3-Clause" ]
null
null
null
#ifndef __EURTOPLN_HPP #define __EURTOPLN_HPP void printExchangeRateEURtoPLN(double value); #endif
11.444444
45
0.825243
Mikbac