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
425c44c6ab3335b2a34784926aa7d93aff2771dd
189
cc
C++
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
2
2021-10-08T00:50:26.000Z
2021-12-17T07:18:15.000Z
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
1
2021-09-29T07:21:20.000Z
2021-09-29T07:21:20.000Z
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
1
2021-10-12T09:02:40.000Z
2021-10-12T09:02:40.000Z
#include <seadsa/support/Debug.h> std::set<std::string> seadsa::SeaDsaLog; void seadsa::SeaDsaEnableLog (std::string x) { if (x.empty()) return; seadsa::SeaDsaLog.insert (x); }
13.5
46
0.671958
wenhuizhang
4263fd30955386762c18b28f158d1a0ba1ab0767
647
cpp
C++
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
31
2021-05-14T03:37:24.000Z
2022-03-13T17:38:32.000Z
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
// Exercise 5.47 - Statistics: Compute mean and standard deviation #include <iostream> #include <cmath> int main() { std::cout << "Enter ten numbers: "; int count = 0; double num, sum = 0.0, squareSum, sumSquare = 0, mean, deviation; while (count < 10) { std::cin >> num; sum += num; sumSquare += std::pow(num, 2); count++; } mean = sum / 10.0; squareSum = std::pow(sum, 2); deviation = std::sqrt((sumSquare - (squareSum / 10)) / 9); std::cout << "The mean is " << mean << std::endl; std::cout << "The standard deviation is " << deviation << std::endl; return 0; }
25.88
72
0.554869
Kevin-Oudai
426414a602d2273e98bb37e0867cc6d70faec56d
3,812
cpp
C++
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
#include "SkyBox.h" #include <iostream> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "ShaderProgram.h" using namespace cs557; SkyBox::SkyBox(string left, string right, string up, string down, string front, string back, ShaderFiles skybox_shader_files) { vector<string> faces { left, right, up, down, front, back }; skyBox_program = LoadAndCreateShaderProgram(skybox_shader_files.vertex_shader, skybox_shader_files.fragment_shader); cubemapTexture = loadCubemap(faces); createCube(); } SkyBox::SkyBox() { } unsigned int SkyBox::loadCubemap(vector<std::string> faces) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); int width, height, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return textureID; } void SkyBox::createCube() { float skyboxVertices[] = { -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f }; glGenVertexArrays(1, &sky_VAO); glBindVertexArray(sky_VAO); glGenBuffers(1, &sky_VBO); glBindBuffer(GL_ARRAY_BUFFER, sky_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), skyboxVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); skyBoxViewMatrixLocation = glGetUniformLocation(skyBox_program, "view"); skyBoxProjMatrixLocation = glGetUniformLocation(skyBox_program, "projection"); } void SkyBox::Draw(mat4 projectionMatrix, mat4 viewMatrix) { glDepthFunc(GL_LEQUAL); glUseProgram(skyBox_program); mat4 skyBoxView = mat4(mat3(viewMatrix)); glUniform1i(glGetUniformLocation(skyBox_program, "skybox"), 0); glUniformMatrix4fv(skyBoxViewMatrixLocation, 1, GL_FALSE, &skyBoxView[0][0]); glUniformMatrix4fv(skyBoxProjMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); glBindVertexArray(sky_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glUseProgram(0); glDepthFunc(GL_LESS); } unsigned SkyBox::GetCubeMap() const { return cubemapTexture; }
26.289655
125
0.705666
Guarionex
42670b3adde45ea4712819604d9f4ffe20d97c8c
1,918
cpp
C++
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Leet Code */ /* Title - Word Break II */ /* Created By - Akash Modak */ /* Date - 30/7/2020 */ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. // Note: // The same word in the dictionary may be reused multiple times in the segmentation. // You may assume the dictionary does not contain duplicate words. // Example 1: // Input: // s = "catsanddog" // wordDict = ["cat", "cats", "and", "sand", "dog"] // Output: // [ // "cats and dog", // "cat sand dog" // ] // Example 2: // Input: // s = "pineapplepenapple" // wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] // Output: // [ // "pine apple pen apple", // "pineapple pen apple", // "pine applepen apple" // ] // Explanation: Note that you are allowed to reuse a dictionary word. // Example 3: // Input: // s = "catsandog" // wordDict = ["cats", "dog", "sand", "and", "cat"] // Output: // [] class Solution { public: unordered_map<string, vector<string>> dp; vector<string> util(string s, vector<string>& wordDict){ if(s.empty()) return {""}; if(dp.find(s)!=dp.end()) return dp[s]; vector<string>sub,whole; for(string word : wordDict){ string igot = s.substr(0,word.length()); if(igot != word){ continue ; }else{ sub = util(s.substr(word.length()) , wordDict); } for(string ans : sub){ string space = ans.length()==0 ? "" : " "; whole.push_back(word+space+ans); } } return dp[s] = whole; } vector<string> wordBreak(string s, vector<string>& wordDict) { dp.clear(); return util(s,wordDict); } };
24.909091
214
0.55318
Shubhrmcf07
4269616c992300e60e21a3675c0f8141b9005ac5
1,371
cpp
C++
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
1
2021-04-17T22:38:25.000Z
2021-04-18T00:43:15.000Z
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2021 the Urho3D project // Copyright (c) 2021 проект Dviglo // Лицензия: MIT #include "../Precompiled.h" #include "../Core/Context.h" #include "../Urho2D/StretchableSprite2D.h" #include "../Urho2D/AnimatedSprite2D.h" #include "../Urho2D/AnimationSet2D.h" #include "../Urho2D/ParticleEffect2D.h" #include "../Urho2D/ParticleEmitter2D.h" #include "../Urho2D/Renderer2D.h" #include "../Urho2D/Sprite2D.h" #include "../Urho2D/SpriteSheet2D.h" #include "../Urho2D/TileMap2D.h" #include "../Urho2D/TileMapLayer2D.h" #include "../Urho2D/TmxFile2D.h" #include "../Urho2D/Urho2D.h" #include "../DebugNew.h" namespace Dviglo { const char* URHO2D_CATEGORY = "Urho2D"; void RegisterUrho2DLibrary(Context* context) { Renderer2D::RegisterObject(context); Sprite2D::RegisterObject(context); SpriteSheet2D::RegisterObject(context); // Must register objects from base to derived order Drawable2D::RegisterObject(context); StaticSprite2D::RegisterObject(context); StretchableSprite2D::RegisterObject(context); AnimationSet2D::RegisterObject(context); AnimatedSprite2D::RegisterObject(context); ParticleEffect2D::RegisterObject(context); ParticleEmitter2D::RegisterObject(context); TmxFile2D::RegisterObject(context); TileMap2D::RegisterObject(context); TileMapLayer2D::RegisterObject(context); } }
25.867925
55
0.737418
1vanK
f119e3f1a982e20ceda42c3237315147eded3850
2,960
hpp
C++
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
null
null
null
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
2
2016-05-19T11:54:58.000Z
2016-05-19T12:31:25.000Z
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
null
null
null
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #pragma once extern "C" { #include "sc_memory_headers.h" } #include "sc_types.hpp" #include "sc_utils.hpp" namespace sc { class IStream { public: _SC_EXTERN virtual bool isValid() const = 0; _SC_EXTERN virtual bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const = 0; _SC_EXTERN virtual bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes) = 0; _SC_EXTERN virtual bool seek(sc_stream_seek_origin origin, sc_uint32 offset) = 0; //! Check if current position at the end of file _SC_EXTERN virtual bool eof() const = 0; //! Returns lenght of stream in bytes _SC_EXTERN virtual sc_uint32 size() const = 0; //! Returns current position of stream _SC_EXTERN virtual sc_uint32 pos() const = 0; //! Check if stream has a specified flag _SC_EXTERN virtual bool hasFlag(sc_uint8 flag) = 0; }; class Stream : public IStream { friend class MemoryContext; public: _SC_EXTERN explicit Stream(); _SC_EXTERN explicit Stream(sc_stream * stream); _SC_EXTERN explicit Stream(std::string const & fileName, sc_uint8 flags); _SC_EXTERN explicit Stream(sc_char * buffer, sc_uint32 bufferSize, sc_uint8 flags); _SC_EXTERN explicit Stream(sc_char const * buffer, sc_uint32 bufferSize, sc_uint8 flags); _SC_EXTERN ~Stream(); _SC_EXTERN void reset(); _SC_EXTERN bool isValid() const; _SC_EXTERN bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const; _SC_EXTERN bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes); _SC_EXTERN bool seek(sc_stream_seek_origin origin, sc_uint32 offset); //! Check if current position at the end of file _SC_EXTERN bool eof() const; //! Returns lenght of stream in bytes _SC_EXTERN sc_uint32 size() const; //! Returns current position of stream _SC_EXTERN sc_uint32 pos() const; //! Check if stream has a specified flag _SC_EXTERN bool hasFlag(sc_uint8 flag); protected: //! Init with new stream object. Used by MemoryContext::getLinkContent void init(sc_stream * stream); protected: sc_stream * mStream; }; class StreamMemory : public IStream { public: _SC_EXTERN explicit StreamMemory(MemoryBufferPtr const & buff); _SC_EXTERN virtual ~StreamMemory(); _SC_EXTERN bool isValid() const; _SC_EXTERN bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const; _SC_EXTERN bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes); _SC_EXTERN bool seek(sc_stream_seek_origin origin, sc_uint32 offset); _SC_EXTERN bool eof() const; _SC_EXTERN sc_uint32 size() const; _SC_EXTERN sc_uint32 pos() const; _SC_EXTERN bool hasFlag(sc_uint8 flag); private: MemoryBufferPtr mBuffer; mutable sc_uint32 mPos; }; SHARED_PTR_TYPE(IStream) }
26.19469
98
0.753378
AbaevTM
f11a018f0c555085ba4418b893b7a855262dca93
24,586
cpp
C++
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
2
2020-01-02T16:07:51.000Z
2020-01-12T17:55:13.000Z
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
3
2020-01-12T19:44:56.000Z
2020-01-17T05:40:41.000Z
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
1
2020-01-12T17:55:40.000Z
2020-01-12T17:55:40.000Z
/*Copyright (c) 2019 The Paradox Game Converters Project 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 "gtest/gtest.h" #include "../EU4toV2/Source/Mappers/Ideas/IdeaEffectMapper.h" #include <sstream> TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaReturnsEmptyForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getEnforceFromIdea("missingIdea", 1); ASSERT_EQ(investment, ""); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaDefaultsToEmpty) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 1), ""); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tenforce = absolute_monarchy"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 7), "absolute_monarchy"); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tenforce = absolute_monarchy"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 4), ""); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getArmyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tarmy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tarmy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getNavyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tnavy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tnavy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getCommerceFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tcommerce = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tcommerce = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getCultureFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tculture = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tculture = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getIndustryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tindustry = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tindustry = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLibertyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberty = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberty = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getEqualityFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tequality = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tequality = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getOrderFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\torder = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\torder = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLiteracyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliteracy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliteracy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLiberalFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberal = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberal = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getReactionaryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\treactionary = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\treactionary = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getSlaveryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tslavery = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tslavery = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getUpper_house_compositionFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tupper_house_composition = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tupper_house_composition = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getVote_franchiseFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvote_franchise = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvote_franchise = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getVoting_systemFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvoting_system = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvoting_system = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPublic_meetingsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpublic_meetings = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpublic_meetings = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPress_rightsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpress_rights = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpress_rights = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getTrade_unionsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\ttrade_unions = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\ttrade_unions = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPolitical_partiesFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPolitical_partiesFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpolitical_parties = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPolitical_partiesFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpolitical_parties = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 4), 5); }
26.465016
99
0.770194
Clonefusion
f11ecf0a20e614fa71f7e065d98200cc38c2c0ef
1,668
cpp
C++
third_party/WebKit/Source/modules/indexeddb/IndexedDBClient.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/indexeddb/IndexedDBClient.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/indexeddb/IndexedDBClient.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/indexeddb/IndexedDBClient.h" #include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" #include "core/frame/LocalFrame.h" #include "core/workers/WorkerClients.h" #include "core/workers/WorkerGlobalScope.h" namespace blink { IndexedDBClient::IndexedDBClient(LocalFrame& frame) : Supplement<LocalFrame>(frame) {} IndexedDBClient::IndexedDBClient(WorkerClients& clients) : Supplement<WorkerClients>(clients) {} IndexedDBClient* IndexedDBClient::From(ExecutionContext* context) { if (context->IsDocument()) return static_cast<IndexedDBClient*>(Supplement<LocalFrame>::From( ToDocument(*context).GetFrame(), SupplementName())); WorkerClients* clients = ToWorkerGlobalScope(*context).Clients(); DCHECK(clients); return static_cast<IndexedDBClient*>( Supplement<WorkerClients>::From(clients, SupplementName())); } const char* IndexedDBClient::SupplementName() { return "IndexedDBClient"; } DEFINE_TRACE(IndexedDBClient) { Supplement<LocalFrame>::Trace(visitor); Supplement<WorkerClients>::Trace(visitor); } void ProvideIndexedDBClientTo(LocalFrame& frame, IndexedDBClient* client) { Supplement<LocalFrame>::ProvideTo(frame, IndexedDBClient::SupplementName(), client); } void ProvideIndexedDBClientToWorker(WorkerClients* clients, IndexedDBClient* client) { clients->ProvideSupplement(IndexedDBClient::SupplementName(), client); } } // namespace blink
32.076923
77
0.736211
metux
f1200f6d1d40423723ee2962e0c49ba2c3bbe553
6,478
cpp
C++
lepra/src/des.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
9
2019-09-03T18:33:31.000Z
2022-02-04T04:00:02.000Z
lepra/src/des.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
lepra/src/des.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
/* Class: Checksum Author: Jonas Byström Copyright (c) Pixel Doctrine */ #include "pch.h" #include "../include/lepraassert.h" #include <memory.h> #include "../include/des.h" namespace lepra { #define GETBIT(a, array) ((uint8)((a>>array)&1)) #define SETBIT(a, array) (a |= ((uint64)1<<array)) #define CLRBIT(a, array) (a &= (~((uint64)1<<array))) #define PUTBIT(a, array, c) (c? SETBIT(a, array) : CLRBIT(a, array)) #define STIRBITS(a, array, c, d) { d = 0; for (int ii = 0; ii < array; ii++) PUTBIT(d, ii, GETBIT(a, c[ii])); } void DES::SetKey(uint64 key) { uint64 c = 0; uint64 d = 0; for (int k = 0; k < 28; k++) { PUTBIT(c, k, GETBIT(key, k_p1_[k])); PUTBIT(d, k, GETBIT(key, k_p1_[k+28])); } for (int q = 0; q < 16; q++) { c = (c>>shift_[q]) | ((c&mask_[q]) << (28-shift_[q])); d = (d>>shift_[q]) | ((d&mask_[q]) << (28-shift_[q])); uint64 t = ((uint64)d << 28) | c; STIRBITS(t, 48, k_p2_, key_[q]); /*{ key_[q] = 0; for (int ii = 0; ii < 48; ii++) { uint8 a = GETBIT(t, k_p2_[ii]); PUTBIT(key_[q], ii, a); } }*/ } c = d = key = 0; // Swipe stack. } void DES::Encrypt(uint8* data, unsigned length) const { deb_assert(length%8 == 0); length >>= 3; uint64* block = (uint64*)data; unsigned u; for (u = 0; u < length; ++u) { block[u] = Crypt(block[u], true); } } void DES::Decrypt(uint8* data, unsigned length) const { deb_assert(length%8 == 0); length >>= 3; uint64* block = (uint64*)data; for (unsigned u = 0; u < length; ++u) { block[u] = Crypt(block[u], false); } } uint64 DES::Crypt(uint64 data, bool forward) const { uint64 a; uint64 array; STIRBITS(data, 64, i_p1_, a); uint32 r = (uint32)(a>>32); uint32 l = (uint32)a; uint32 temp; for (int idx = 0; idx <= 15; ++idx) { STIRBITS(r, 48, expansion_, a); if (forward) { array = a ^ key_[idx]; } else { array = a ^ key_[15 - idx]; } a = 0; for (int j = 0; j <= 7; ++j) { a <<= 4; a |= s_box_[j][(array>>((7-j)*6)) & 0x3f]; } STIRBITS(a, 32, p_box_, array); temp = r; r = l^(uint32)array; l = temp; } a = ((uint64)l<<32)|r; STIRBITS(a, 64, i_p2_, data); /*{ data = 0; for (int ii = 0; ii < 64; ii++) PUTBIT(data, ii, GETBIT(a, i_p2_[ii])); }*/ a = array = r = l = temp = 0; // Swipe stack. return (data); } // S-box permutation. Even small modifications to the S-box could significantly weaken DES. const uint8 DES::s_box_[8][64] = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }, { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }, { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }, { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }, { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }, { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }, { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }, { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 }, }; // Bit-mask used in key-making. const uint8 DES::mask_[16] = { 1, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1 }; // Bit-shifts used in key-making. const uint8 DES::shift_[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // Key permutation. const uint8 DES::k_p1_[56] = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 }; // Key compression permutation. const uint8 DES::k_p2_[48] = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 }; // Initial permutation IP. const uint8 DES::i_p1_[64] = { 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6 }; // Final permutation IP. const uint8 DES::i_p2_[64] = { 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24 }; // Expansion permutation. const uint8 DES::expansion_[48] = { 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0 }; // P-box permutation. const uint8 DES::p_box_[32] = { 15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23, 13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24 }; }
26.016064
111
0.458629
highfestiva
f120f54376574b04555e03aced6de9a09795958b
151
cpp
C++
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(){ int n; vector<int> text; while(cin >> n) text.push_back(n); return 0; }
10.785714
20
0.655629
Links789
f12100d477533cdb67ef25f744c45d68316ad4b7
89,565
cpp
C++
interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "napi_data_ability_helper.h" #include "data_ability_helper.h" #include "uri.h" #include <cstring> #include <vector> #include <uv.h> #include "securec.h" #include "hilog_wrapper.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; namespace OHOS { namespace AppExecFwk { napi_value g_dataAbilityHelper; std::list<std::shared_ptr<DataAbilityHelper>> g_dataAbilityHelperList; /** * @brief DataAbilityHelper NAPI module registration. * * @param env The environment that the Node-API call is invoked under. * @param exports An empty object via the exports parameter as a convenience. * * @return The return value from Init is treated as the exports object for the module. */ napi_value DataAbilityHelperInit(napi_env env, napi_value exports) { HILOG_INFO("%{public}s,called", __func__); napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), DECLARE_NAPI_FUNCTION("query", NAPI_Query), DECLARE_NAPI_FUNCTION("update", NAPI_Update), DECLARE_NAPI_FUNCTION("batchInsert", NAPI_BatchInsert), DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), DECLARE_NAPI_FUNCTION("getType", NAPI_GetType), DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetFileTypes), DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_NormalizeUri), DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_DenormalizeUri), DECLARE_NAPI_FUNCTION("release", NAPI_Release), }; NAPI_CALL(env, napi_define_class(env, "dataAbilityHelper", NAPI_AUTO_LENGTH, DataAbilityHelperConstructor, nullptr, sizeof(properties) / sizeof(*properties), properties, &g_dataAbilityHelper)); g_dataAbilityHelperList.clear(); return exports; } napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); size_t argc = 1; napi_value argv[1]; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); std::string strUri = NapiValueToStringUtf8(env, argv[0]); HILOG_INFO("%{public}s,strUri = %{public}s", __func__, strUri.c_str()); napi_value global = nullptr; NAPI_CALL(env, napi_get_global(env, &global)); napi_value abilityObj = nullptr; NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); Ability *ability = nullptr; NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); HILOG_INFO("ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); HILOG_INFO("g_dataAbilityHelperList.size = %{public}zu", g_dataAbilityHelperList.size()); std::shared_ptr<DataAbilityHelper> dataAbilityHelper = DataAbilityHelper::Creator(ability->GetContext(), std::make_shared<Uri>(strUri)); HILOG_INFO("dataAbilityHelper = %{public}p", dataAbilityHelper.get()); g_dataAbilityHelperList.emplace_back(dataAbilityHelper); HILOG_INFO("g_dataAbilityHelperList.size = %{public}zu", g_dataAbilityHelperList.size()); napi_wrap( env, thisVar, dataAbilityHelper.get(), [](napi_env env, void *data, void *hint) { DataAbilityHelper *objectInfo = (DataAbilityHelper *)data; HILOG_INFO("DataAbilityHelper finalize_cb objectInfo = %{public}p", objectInfo); HILOG_INFO( "DataAbilityHelper finalize_cb registerInstances_.size = %{public}zu", registerInstances_.size()); auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), [&objectInfo](const DAHelperOnOffCB *helper) { return helper->dataAbilityHelper == objectInfo; }); if (helper != registerInstances_.end()) { HILOG_INFO("DataAbilityHelper finalize_cb find helper"); (*helper)->dataAbilityHelper->Release(); delete *helper; registerInstances_.erase(helper); } HILOG_INFO( "DataAbilityHelper finalize_cb registerInstances_.size = %{public}zu", registerInstances_.size()); HILOG_INFO("DataAbilityHelper finalize_cb g_dataAbilityHelperList.size = %{public}zu", g_dataAbilityHelperList.size()); g_dataAbilityHelperList.remove_if( [objectInfo](const std::shared_ptr<DataAbilityHelper> &dataAbilityHelper) { return objectInfo == dataAbilityHelper.get(); }); HILOG_INFO("DataAbilityHelper finalize_cb g_dataAbilityHelperList.size = %{public}zu", g_dataAbilityHelperList.size()); HILOG_INFO("DataAbilityHelper finalize_cb end."); }, nullptr, nullptr); HILOG_INFO("%{public}s,called end", __func__); return thisVar; } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_Insert(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperInsertCB *insertCB = new (std::nothrow) DAHelperInsertCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; if (insertCB == nullptr) { HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); return WrapVoidToJS(env); } napi_value ret = InsertWrap(env, info, insertCB); if (ret == nullptr) { HILOG_ERROR("%{public}s, ret == nullptr.", __func__); if (insertCB != nullptr) { delete insertCB; insertCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,called end", __func__); return ret; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *insertCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { insertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); return nullptr; } std::string strValue; UnwrapValuesBucket(strValue, env, args[PARAM1]); HILOG_INFO("%{public}s,valueBucket=%{public}s", __func__, strValue.c_str()); ValuesBucket valueBucket(strValue); insertCB->valueBucket = ValuesBucket(valueBucket); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); insertCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = InsertAsync(env, args, argcAsync, argcPromise, insertCB); } else { ret = InsertPromise(env, insertCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value InsertAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperInsertCB *insertCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || insertCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &insertCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, InsertExecuteCB, InsertAsyncCompleteCB, (void *)insertCB, &insertCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } napi_value InsertPromise(napi_env env, DAHelperInsertCB *insertCB) { HILOG_INFO("%{public}s, promise.", __func__); if (insertCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); insertCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, InsertExecuteCB, InsertPromiseCompleteCB, (void *)insertCB, &insertCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end", __func__); return promise; } void InsertExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Insert, worker pool thread execute."); DAHelperInsertCB *insertCB = (DAHelperInsertCB *)data; if (insertCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(insertCB->uri); insertCB->result = insertCB->dataAbilityHelper->Insert(uri, insertCB->valueBucket); } else { HILOG_ERROR("NAPI_Insert, dataAbilityHelper == nullptr."); } HILOG_INFO("NAPI_Insert, worker pool thread execute end."); } void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Insert, main event thread complete."); DAHelperInsertCB *insertCB = (DAHelperInsertCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, insertCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (insertCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; HILOG_INFO("NAPI_Insert, main event thread complete end."); } void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Insert, main event thread complete."); DAHelperInsertCB *insertCB = (DAHelperInsertCB *)data; napi_value result = nullptr; napi_create_int32(env, insertCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; HILOG_INFO("NAPI_Insert, main event thread complete end."); } /** * @brief Parse the ValuesBucket parameters. * * @param param Indicates the want parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. * @param args Indicates the arguments passed into the callback. * * @return The return value from NAPI C++ to JS for the module. */ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) { HILOG_INFO("%{public}s,called", __func__); napi_valuetype valueType = napi_undefined; napi_typeof(env, args, &valueType); if (valueType != napi_object) { HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); return nullptr; } std::string strValue = ""; if (UnwrapStringByPropertyName(env, args, "value", strValue)) { HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); value = strValue; } else { HILOG_ERROR("%{public}s, value == nullptr.", __func__); return nullptr; } napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); HILOG_INFO("%{public}s,end", __func__); return result; } napi_value NAPI_GetType(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperGetTypeCB *gettypeCB = new (std::nothrow) DAHelperGetTypeCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = GetTypeWrap(env, info, gettypeCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (gettypeCB != nullptr) { delete gettypeCB; gettypeCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value GetTypeWrap(napi_env env, napi_callback_info info, DAHelperGetTypeCB *gettypeCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_TWO; const size_t argcPromise = ARGS_ONE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { gettypeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); return nullptr; } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); gettypeCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = GetTypeAsync(env, args, argcAsync, argcPromise, gettypeCB); } else { ret = GetTypePromise(env, gettypeCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value GetTypeAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetTypeCB *gettypeCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || gettypeCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &gettypeCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, GetTypeExecuteCB, GetTypeAsyncCompleteCB, (void *)gettypeCB, &gettypeCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end", __func__); return result; } napi_value GetTypePromise(napi_env env, DAHelperGetTypeCB *gettypeCB) { HILOG_INFO("%{public}s, promise.", __func__); if (gettypeCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); gettypeCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, GetTypeExecuteCB, GetTypePromiseCompleteCB, (void *)gettypeCB, &gettypeCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void GetTypeExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_GetType, worker pool thread execute."); DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; if (gettypeCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(gettypeCB->uri); gettypeCB->result = gettypeCB->dataAbilityHelper->GetType(uri); } else { HILOG_ERROR("NAPI_GetType, dataAbilityHelper == nullptr."); } HILOG_INFO("NAPI_GetType, worker pool thread execute end."); } void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_GetType, main event thread complete."); DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (gettypeCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, gettypeCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); delete gettypeCB; gettypeCB = nullptr; HILOG_INFO("NAPI_GetType, main event thread complete end."); } void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_GetType, main event thread complete."); DAHelperGetTypeCB *gettypeCB = (DAHelperGetTypeCB *)data; napi_value result = nullptr; NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, gettypeCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); delete gettypeCB; gettypeCB = nullptr; HILOG_INFO("NAPI_GetType, main event thread complete end."); } napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperGetFileTypesCB *getfiletypesCB = new (std::nothrow) DAHelperGetFileTypesCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = GetFileTypesWrap(env, info, getfiletypesCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (getfiletypesCB != nullptr) { delete getfiletypesCB; getfiletypesCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DAHelperGetFileTypesCB *getfiletypesCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { getfiletypesCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, getfiletypesCB->uri.c_str()); } NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); if (valuetype == napi_string) { getfiletypesCB->mimeTypeFilter = NapiValueToStringUtf8(env, args[PARAM1]); HILOG_INFO("%{public}s,mimeTypeFilter=%{public}s", __func__, getfiletypesCB->mimeTypeFilter.c_str()); } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); getfiletypesCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = GetFileTypesAsync(env, args, argcAsync, argcPromise, getfiletypesCB); } else { ret = GetFileTypesPromise(env, getfiletypesCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value GetFileTypesAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperGetFileTypesCB *getfiletypesCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || getfiletypesCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &getfiletypesCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, GetFileTypesExecuteCB, GetFileTypesAsyncCompleteCB, (void *)getfiletypesCB, &getfiletypesCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value GetFileTypesPromise(napi_env env, DAHelperGetFileTypesCB *getfiletypesCB) { HILOG_INFO("%{public}s, promise.", __func__); if (getfiletypesCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); getfiletypesCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, GetFileTypesExecuteCB, GetFileTypesPromiseCompleteCB, (void *)getfiletypesCB, &getfiletypesCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void GetFileTypesExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; if (getfiletypesCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(getfiletypesCB->uri); HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); getfiletypesCB->result = getfiletypesCB->dataAbilityHelper->GetFileTypes(uri, getfiletypesCB->mimeTypeFilter); } else { HILOG_INFO("NAPI_GetFileTypes, dataAbilityHelper == nullptr."); } HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute end."); } void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (getfiletypesCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getfiletypesCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); delete getfiletypesCB; getfiletypesCB = nullptr; HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); } napi_value WrapGetFileTypesCB(napi_env env, const DAHelperGetFileTypesCB &getfiletypesCB) { HILOG_INFO("WrapGetFileTypesCB, called."); HILOG_INFO("NAPI_GetFileTypes, result.size:%{public}zu", getfiletypesCB.result.size()); for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { HILOG_INFO("NAPI_GetFileTypes, result[%{public}zu]:%{public}s", i, getfiletypesCB.result.at(i).c_str()); } napi_value proValue = nullptr; napi_value jsArrayresult = nullptr; NAPI_CALL(env, napi_create_array(env, &jsArrayresult)); for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { proValue = nullptr; NAPI_CALL(env, napi_create_string_utf8(env, getfiletypesCB.result.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_element(env, jsArrayresult, i, proValue)); } HILOG_INFO("WrapGetFileTypesCB, end."); return jsArrayresult; } void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); DAHelperGetFileTypesCB *getfiletypesCB = (DAHelperGetFileTypesCB *)data; napi_value result = nullptr; result = WrapGetFileTypesCB(env, *getfiletypesCB); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getfiletypesCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); delete getfiletypesCB; getfiletypesCB = nullptr; HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); } napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperNormalizeUriCB *normalizeuriCB = new (std::nothrow) DAHelperNormalizeUriCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = NormalizeUriWrap(env, info, normalizeuriCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (normalizeuriCB != nullptr) { delete normalizeuriCB; normalizeuriCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperNormalizeUriCB *normalizeuriCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_TWO; const size_t argcPromise = ARGS_ONE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { normalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, normalizeuriCB->uri.c_str()); } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); normalizeuriCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = NormalizeUriAsync(env, args, argcAsync, argcPromise, normalizeuriCB); } else { ret = NormalizeUriPromise(env, normalizeuriCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value NormalizeUriAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperNormalizeUriCB *normalizeuriCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || normalizeuriCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &normalizeuriCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, NormalizeUriExecuteCB, NormalizeUriAsyncCompleteCB, (void *)normalizeuriCB, &normalizeuriCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value NormalizeUriPromise(napi_env env, DAHelperNormalizeUriCB *normalizeuriCB) { HILOG_INFO("%{public}s, promise.", __func__); if (normalizeuriCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); normalizeuriCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, NormalizeUriExecuteCB, NormalizeUriPromiseCompleteCB, (void *)normalizeuriCB, &normalizeuriCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void NormalizeUriExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute."); DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; Uri uriValue(normalizeuriCB->uri); if (normalizeuriCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(normalizeuriCB->uri); uriValue = normalizeuriCB->dataAbilityHelper->NormalizeUri(uri); normalizeuriCB->result = uriValue.ToString(); } else { HILOG_INFO("NAPI_NormalizeUri, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute end."); } void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); NAPI_CALL_RETURN_VOID( env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (normalizeuriCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, normalizeuriCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); delete normalizeuriCB; normalizeuriCB = nullptr; HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); } void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); DAHelperNormalizeUriCB *normalizeuriCB = (DAHelperNormalizeUriCB *)data; napi_value result = nullptr; NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, normalizeuriCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); delete normalizeuriCB; normalizeuriCB = nullptr; HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); } napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperDenormalizeUriCB *denormalizeuriCB = new (std::nothrow) DAHelperDenormalizeUriCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = DenormalizeUriWrap(env, info, denormalizeuriCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (denormalizeuriCB != nullptr) { delete denormalizeuriCB; denormalizeuriCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DAHelperDenormalizeUriCB *denormalizeuriCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_TWO; const size_t argcPromise = ARGS_ONE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { denormalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, denormalizeuriCB->uri.c_str()); } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); denormalizeuriCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = DenormalizeUriAsync(env, args, argcAsync, argcPromise, denormalizeuriCB); } else { ret = DenormalizeUriPromise(env, denormalizeuriCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value DenormalizeUriAsync(napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperDenormalizeUriCB *denormalizeuriCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || denormalizeuriCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &denormalizeuriCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, DenormalizeUriExecuteCB, DenormalizeUriAsyncCompleteCB, (void *)denormalizeuriCB, &denormalizeuriCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value DenormalizeUriPromise(napi_env env, DAHelperDenormalizeUriCB *denormalizeuriCB) { HILOG_INFO("%{public}s, promise.", __func__); if (denormalizeuriCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); denormalizeuriCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, DenormalizeUriExecuteCB, DenormalizeUriPromiseCompleteCB, (void *)denormalizeuriCB, &denormalizeuriCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void DenormalizeUriExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute."); DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; Uri uriValue(denormalizeuriCB->uri); if (denormalizeuriCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(denormalizeuriCB->uri); uriValue = denormalizeuriCB->dataAbilityHelper->DenormalizeUri(uri); denormalizeuriCB->result = uriValue.ToString(); } else { HILOG_ERROR("NAPI_DenormalizeUri, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute end."); } void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); NAPI_CALL_RETURN_VOID( env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (denormalizeuriCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, denormalizeuriCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); delete denormalizeuriCB; denormalizeuriCB = nullptr; HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); } void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); DAHelperDenormalizeUriCB *denormalizeuriCB = (DAHelperDenormalizeUriCB *)data; napi_value result = nullptr; NAPI_CALL_RETURN_VOID( env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, denormalizeuriCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); delete denormalizeuriCB; denormalizeuriCB = nullptr; HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); } napi_value UnwrapDataAbilityPredicates(std::string &value, napi_env env, napi_value args) { HILOG_INFO("%{public}s,called", __func__); napi_valuetype valueType = napi_undefined; napi_typeof(env, args, &valueType); if (valueType != napi_object) { HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); return nullptr; } std::string strValue = ""; if (UnwrapStringByPropertyName(env, args, "value", strValue)) { HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); value = strValue; } else { HILOG_ERROR("%{public}s, value == nullptr.", __func__); return nullptr; } napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); HILOG_INFO("%{public}s,end", __func__); return result; } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_Delete(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperDeleteCB *deleteCB = new (std::nothrow) DAHelperDeleteCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = DeleteWrap(env, info, deleteCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (deleteCB != nullptr) { delete deleteCB; deleteCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value DeleteWrap(napi_env env, napi_callback_info info, DAHelperDeleteCB *deleteCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); } std::string strValue; UnwrapDataAbilityPredicates(strValue, env, args[PARAM1]); HILOG_INFO("%{public}s,valueBucket=%{public}s", __func__, strValue.c_str()); DataAbilityPredicates dataAbpredicates(strValue); deleteCB->predicates = DataAbilityPredicates(dataAbpredicates); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); deleteCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = DeleteAsync(env, args, argcAsync, argcPromise, deleteCB); } else { ret = DeletePromise(env, deleteCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value DeleteAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperDeleteCB *deleteCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || deleteCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &deleteCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, DeleteExecuteCB, DeleteAsyncCompleteCB, (void *)deleteCB, &deleteCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value DeletePromise(napi_env env, DAHelperDeleteCB *deleteCB) { HILOG_INFO("%{public}s, promise.", __func__); if (deleteCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); deleteCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, DeleteExecuteCB, DeletePromiseCompleteCB, (void *)deleteCB, &deleteCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void DeleteExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Delete, worker pool thread execute."); DAHelperDeleteCB *deleteCB = (DAHelperDeleteCB *)data; if (deleteCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(deleteCB->uri); deleteCB->result = deleteCB->dataAbilityHelper->Delete(uri, deleteCB->predicates); } else { HILOG_ERROR("NAPI_Delete, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Delete, worker pool thread execute end."); } void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Delete, main event thread complete."); DAHelperDeleteCB *DeleteCB = (DAHelperDeleteCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, DeleteCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (DeleteCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); delete DeleteCB; DeleteCB = nullptr; HILOG_INFO("NAPI_Delete, main event thread complete end."); } void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Delete, main event thread complete."); DAHelperDeleteCB *DeleteCB = (DAHelperDeleteCB *)data; napi_value result = nullptr; napi_create_int32(env, DeleteCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); delete DeleteCB; DeleteCB = nullptr; HILOG_INFO("NAPI_Delete, main event thread complete end."); } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_Update(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperUpdateCB *updateCB = new (std::nothrow) DAHelperUpdateCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = UpdateWrap(env, info, updateCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (updateCB != nullptr) { delete updateCB; updateCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value UpdateWrap(napi_env env, napi_callback_info info, DAHelperUpdateCB *updateCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_FOUR; const size_t argcPromise = ARGS_THREE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); } std::string strValue; UnwrapValuesBucket(strValue, env, args[PARAM1]); HILOG_INFO("%{public}s,ValuesBucket=%{public}s", __func__, strValue.c_str()); ValuesBucket valueBucket(strValue); updateCB->valueBucket = ValuesBucket(valueBucket); std::string strValue2; UnwrapDataAbilityPredicates(strValue2, env, args[PARAM2]); HILOG_INFO("%{public}s,DataAbilityPredicates=%{public}s", __func__, strValue2.c_str()); DataAbilityPredicates dataAbpredicates(strValue2); updateCB->predicates = DataAbilityPredicates(dataAbpredicates); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); updateCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = UpdateAsync(env, args, argcAsync, argcPromise, updateCB); } else { ret = UpdatePromise(env, updateCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value UpdateAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperUpdateCB *updateCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || updateCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &updateCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, UpdateExecuteCB, UpdateAsyncCompleteCB, (void *)updateCB, &updateCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value UpdatePromise(napi_env env, DAHelperUpdateCB *updateCB) { HILOG_INFO("%{public}s, promise.", __func__); if (updateCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); updateCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, UpdateExecuteCB, UpdatePromiseCompleteCB, (void *)updateCB, &updateCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void UpdateExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Update, worker pool thread execute."); DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; if (updateCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(updateCB->uri); updateCB->result = updateCB->dataAbilityHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); } else { HILOG_ERROR("NAPI_Update, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Update, worker pool thread execute end."); } void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Update, main event thread complete."); DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, updateCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (updateCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); delete updateCB; updateCB = nullptr; HILOG_INFO("NAPI_Update, main event thread complete end."); } void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Update, main event thread complete."); DAHelperUpdateCB *updateCB = (DAHelperUpdateCB *)data; napi_value result = nullptr; napi_create_int32(env, updateCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); delete updateCB; updateCB = nullptr; HILOG_INFO("NAPI_Update, main event thread complete end."); } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperOpenFileCB *openFileCB = new (std::nothrow) DAHelperOpenFileCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = OpenFileWrap(env, info, openFileCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (openFileCB != nullptr) { delete openFileCB; openFileCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value OpenFileWrap(napi_env env, napi_callback_info info, DAHelperOpenFileCB *openFileCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, openFileCB->uri.c_str()); } NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); if (valuetype == napi_string) { openFileCB->mode = NapiValueToStringUtf8(env, args[PARAM1]); HILOG_INFO("%{public}s,mode=%{public}s", __func__, openFileCB->mode.c_str()); } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); openFileCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = OpenFileAsync(env, args, argcAsync, argcPromise, openFileCB); } else { ret = OpenFilePromise(env, openFileCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value OpenFileAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperOpenFileCB *openFileCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || openFileCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &openFileCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, OpenFileExecuteCB, OpenFileAsyncCompleteCB, (void *)openFileCB, &openFileCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value OpenFilePromise(napi_env env, DAHelperOpenFileCB *openFileCB) { HILOG_INFO("%{public}s, promise.", __func__); if (openFileCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); openFileCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, OpenFileExecuteCB, OpenFilePromiseCompleteCB, (void *)openFileCB, &openFileCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void OpenFileExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; if (OpenFileCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(OpenFileCB->uri); OpenFileCB->result = OpenFileCB->dataAbilityHelper->OpenFile(uri, OpenFileCB->mode); } else { HILOG_ERROR("NAPI_OpenFile, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_OpenFile, worker pool thread execute end."); } void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_OpenFile, main event thread complete."); DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (OpenFileCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, OpenFileCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); delete OpenFileCB; OpenFileCB = nullptr; HILOG_INFO("NAPI_OpenFile, main event thread complete end."); } void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_OpenFileCB, main event thread complete."); DAHelperOpenFileCB *OpenFileCB = (DAHelperOpenFileCB *)data; napi_value result = nullptr; napi_create_int32(env, OpenFileCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, OpenFileCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); delete OpenFileCB; OpenFileCB = nullptr; HILOG_INFO("NAPI_OpenFileCB, main event thread complete end."); } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperBatchInsertCB *BatchInsertCB = new (std::nothrow) DAHelperBatchInsertCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = BatchInsertWrap(env, info, BatchInsertCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (BatchInsertCB != nullptr) { delete BatchInsertCB; BatchInsertCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } std::vector<ValuesBucket> NapiValueObject(napi_env env, napi_value param) { HILOG_INFO("%{public}s,called", __func__); std::vector<ValuesBucket> result; UnwrapArrayObjectFromJS(env, param, result); return result; } bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector<ValuesBucket> &value) { HILOG_INFO("%{public}s,called", __func__); uint32_t arraySize = 0; napi_value jsValue = nullptr; std::string strValue = ""; if (!IsArrayForNapiValue(env, param, arraySize)) { HILOG_INFO("%{public}s, IsArrayForNapiValue is false", __func__); return false; } value.clear(); for (uint32_t i = 0; i < arraySize; i++) { jsValue = nullptr; strValue = ""; if (napi_get_element(env, param, i, &jsValue) != napi_ok) { HILOG_INFO("%{public}s, napi_get_element is false", __func__); return false; } UnwrapValuesBucket(strValue, env, jsValue); ValuesBucket valueBucket(strValue); value.push_back(valueBucket); } HILOG_INFO("%{public}s,end", __func__); return true; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DAHelperBatchInsertCB *batchInsertCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_THREE; const size_t argcPromise = ARGS_TWO; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { batchInsertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, batchInsertCB->uri.c_str()); } batchInsertCB->values = NapiValueObject(env, args[PARAM1]); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); batchInsertCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = BatchInsertAsync(env, args, argcAsync, argcPromise, batchInsertCB); } else { ret = BatchInsertPromise(env, batchInsertCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value BatchInsertAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperBatchInsertCB *batchInsertCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || batchInsertCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &batchInsertCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, BatchInsertExecuteCB, BatchInsertAsyncCompleteCB, (void *)batchInsertCB, &batchInsertCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value BatchInsertPromise(napi_env env, DAHelperBatchInsertCB *batchInsertCB) { HILOG_INFO("%{public}s, promise.", __func__); if (batchInsertCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); batchInsertCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, BatchInsertExecuteCB, BatchInsertPromiseCompleteCB, (void *)batchInsertCB, &batchInsertCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void BatchInsertExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); DAHelperBatchInsertCB *batchInsertCB = (DAHelperBatchInsertCB *)data; if (batchInsertCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(batchInsertCB->uri); batchInsertCB->result = batchInsertCB->dataAbilityHelper->BatchInsert(uri, batchInsertCB->values); } else { HILOG_ERROR("NAPI_BatchInsert, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_BatchInsert, worker pool thread execute end."); } void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_BatchInsert, main event thread complete."); DAHelperBatchInsertCB *BatchInsertCB = (DAHelperBatchInsertCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (BatchInsertCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, BatchInsertCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); delete BatchInsertCB; BatchInsertCB = nullptr; HILOG_INFO("NAPI_BatchInsert, main event thread complete end."); } void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_BatchInsertCB, main event thread complete."); DAHelperBatchInsertCB *BatchInsertCB = (DAHelperBatchInsertCB *)data; napi_value result = nullptr; napi_create_int32(env, BatchInsertCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, BatchInsertCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); delete BatchInsertCB; BatchInsertCB = nullptr; HILOG_INFO("NAPI_BatchInsertCB, main event thread complete end."); } /** * @brief DataAbilityHelper NAPI method : insert. * * @param env The environment that the Node-API call is invoked under. * @param info The callback info passed into the callback function. * * @return The return value from NAPI C++ to JS for the module. */ napi_value NAPI_Query(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperQueryCB *QueryCB = new (std::nothrow) DAHelperQueryCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, .cbBase.ability = nullptr, }; napi_value ret = QueryWrap(env, info, QueryCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (QueryCB != nullptr) { delete QueryCB; QueryCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } /** * @brief Insert processing function. * * @param env The environment that the Node-API call is invoked under. * @param insertCB Process data asynchronously. * * @return Return JS data successfully, otherwise return nullptr. */ napi_value QueryWrap(napi_env env, napi_callback_info info, DAHelperQueryCB *queryCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_FOUR; const size_t argcPromise = ARGS_THREE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = 0; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); } std::vector<std::string> result; bool arrayStringbool = false; arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); if (arrayStringbool == false) { HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); return nullptr; } queryCB->columns = result; for (size_t i = 0; i < queryCB->columns.size(); i++) { HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); } std::string strValue; UnwrapDataAbilityPredicates(strValue, env, args[PARAM2]); HILOG_INFO("%{public}s,dataAbilityPredicates=%{public}s", __func__, strValue.c_str()); DataAbilityPredicates dataAbilityPredicates(strValue); queryCB->predicates = DataAbilityPredicates(dataAbilityPredicates); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); queryCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = QueryAsync(env, args, argcAsync, argcPromise, queryCB); } else { ret = QueryPromise(env, queryCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value QueryAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperQueryCB *queryCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || queryCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &queryCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, QueryExecuteCB, QueryAsyncCompleteCB, (void *)queryCB, &queryCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value QueryPromise(napi_env env, DAHelperQueryCB *queryCB) { HILOG_INFO("%{public}s, promise.", __func__); if (queryCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); queryCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, QueryExecuteCB, QueryPromiseCompleteCB, (void *)queryCB, &queryCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete."); DAHelperQueryCB *QueryCB = (DAHelperQueryCB *)data; napi_value result = nullptr; result = WrapResultSet(env, QueryCB->result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); delete QueryCB; QueryCB = nullptr; HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete end."); } void QueryExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Query, worker pool thread execute."); DAHelperQueryCB *queryCB = (DAHelperQueryCB *)data; std::shared_ptr<ResultSet> resultset = nullptr; if (queryCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(queryCB->uri); resultset = queryCB->dataAbilityHelper->Query(uri, queryCB->columns, queryCB->predicates); if (resultset != nullptr) { queryCB->result.testInf_ = resultset->testInf_; } else { HILOG_INFO("NAPI_Query, resultset == nullptr."); } } else { HILOG_ERROR("NAPI_Query, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Query, worker pool thread execute end."); } void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Query, main event thread complete."); DAHelperQueryCB *queryCB = (DAHelperQueryCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapResultSet(env, queryCB->result); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (queryCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); delete queryCB; queryCB = nullptr; HILOG_INFO("NAPI_Query, main event thread complete end."); } napi_value WrapResultSet(napi_env env, const ResultSet &resultSet) { HILOG_INFO("%{public}s,called", __func__); napi_value result = nullptr; napi_value proValue = nullptr; NAPI_CALL(env, napi_create_object(env, &result)); NAPI_CALL(env, napi_create_string_utf8(env, resultSet.testInf_.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "value", proValue)); HILOG_INFO("%{public}s,end", __func__); return result; } napi_value NAPI_Release(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); DAHelperReleaseCB *releaseCB = new (std::nothrow) DAHelperReleaseCB{ .cbBase.cbInfo.env = env, .cbBase.asyncWork = nullptr, .cbBase.deferred = nullptr, }; napi_value ret = ReleaseWrap(env, info, releaseCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (releaseCB != nullptr) { delete releaseCB; releaseCB = nullptr; } ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value ReleaseWrap(napi_env env, napi_callback_info info, DAHelperReleaseCB *releaseCB) { HILOG_INFO("%{public}s,called", __func__); size_t argcAsync = ARGS_TWO; const size_t argcPromise = ARGS_ONE; const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value ret = nullptr; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); HILOG_INFO("DataAbilityHelper ReleaseWrap objectInfo = %{public}p", objectInfo); releaseCB->dataAbilityHelper = objectInfo; if (argcAsync > argcPromise) { ret = ReleaseAsync(env, args, argcAsync, argcPromise, releaseCB); } else { ret = ReleasePromise(env, releaseCB); } HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value ReleaseAsync( napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DAHelperReleaseCB *releaseCB) { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || releaseCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); if (valuetype == napi_function) { NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &releaseCB->cbBase.cbInfo.callback)); } NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, ReleaseExecuteCB, ReleaseAsyncCompleteCB, (void *)releaseCB, &releaseCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); napi_value result = 0; NAPI_CALL(env, napi_get_null(env, &result)); HILOG_INFO("%{public}s, asyncCallback end.", __func__); return result; } napi_value ReleasePromise(napi_env env, DAHelperReleaseCB *releaseCB) { HILOG_INFO("%{public}s, promise.", __func__); if (releaseCB == nullptr) { HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); napi_deferred deferred; napi_value promise = 0; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); releaseCB->cbBase.deferred = deferred; NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, ReleaseExecuteCB, ReleasePromiseCompleteCB, (void *)releaseCB, &releaseCB->cbBase.asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); HILOG_INFO("%{public}s, promise end.", __func__); return promise; } void ReleaseExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Release, worker pool thread execute."); DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; if (releaseCB->dataAbilityHelper != nullptr) { releaseCB->result = releaseCB->dataAbilityHelper->Release(); } else { HILOG_ERROR("NAPI_Release, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Release, worker pool thread execute end."); } void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Release, main event thread complete."); DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, releaseCB->cbBase.cbInfo.callback, &callback)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_get_boolean(env, releaseCB->result, &result[PARAM1]); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (releaseCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, releaseCB->cbBase.cbInfo.callback)); } NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); delete releaseCB; releaseCB = nullptr; HILOG_INFO("NAPI_Release, main event thread complete end."); } void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Release, main event thread complete."); DAHelperReleaseCB *releaseCB = (DAHelperReleaseCB *)data; napi_value result = nullptr; napi_get_boolean(env, releaseCB->result, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, releaseCB->cbBase.deferred, result)); NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); delete releaseCB; releaseCB = nullptr; HILOG_INFO("NAPI_Release, main event thread complete end."); } } // namespace AppExecFwk } // namespace OHOS
39.026144
120
0.69401
openharmony-sig-ci
f12140cf8f7044579afd21a45ce104c8c7dc38bc
23,576
cpp
C++
indra/llmath/tests/mathmisc_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/llmath/tests/mathmisc_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
indra/llmath/tests/mathmisc_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file math.cpp * @author Phoenix * @date 2005-09-26 * @brief Tests for the llmath library. * * $LicenseInfo:firstyear=2005&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "../test/lltut.h" #include "llcrc.h" #include "llrand.h" #include "lluuid.h" #include "../llline.h" #include "../llmath.h" #include "../llsphere.h" #include "../v3math.h" namespace tut { struct math_data { }; typedef test_group<math_data> math_test; typedef math_test::object math_object; tut::math_test tm("BasicLindenMath"); template<> template<> void math_object::test<1>() { S32 val = 89543; val = llabs(val); ensure("integer absolute value 1", (89543 == val)); val = -500; val = llabs(val); ensure("integer absolute value 2", (500 == val)); } template<> template<> void math_object::test<2>() { F32 val = -2583.4f; val = llabs(val); ensure("float absolute value 1", (2583.4f == val)); val = 430903.f; val = llabs(val); ensure("float absolute value 2", (430903.f == val)); } template<> template<> void math_object::test<3>() { F64 val = 387439393.987329839; val = llabs(val); ensure("double absolute value 1", (387439393.987329839 == val)); val = -8937843.9394878; val = llabs(val); ensure("double absolute value 2", (8937843.9394878 == val)); } template<> template<> void math_object::test<4>() { F32 val = 430903.9f; S32 val1 = lltrunc(val); ensure("float truncate value 1", (430903 == val1)); val = -2303.9f; val1 = lltrunc(val); ensure("float truncate value 2", (-2303 == val1)); } template<> template<> void math_object::test<5>() { F64 val = 387439393.987329839 ; S32 val1 = lltrunc(val); ensure("float truncate value 1", (387439393 == val1)); val = -387439393.987329839; val1 = lltrunc(val); ensure("float truncate value 2", (-387439393 == val1)); } template<> template<> void math_object::test<6>() { F32 val = 430903.2f; S32 val1 = llfloor(val); ensure("float llfloor value 1", (430903 == val1)); val = -430903.9f; val1 = llfloor(val); ensure("float llfloor value 2", (-430904 == val1)); } template<> template<> void math_object::test<7>() { F32 val = 430903.2f; S32 val1 = llceil(val); ensure("float llceil value 1", (430904 == val1)); val = -430903.9f; val1 = llceil(val); ensure("float llceil value 2", (-430903 == val1)); } template<> template<> void math_object::test<8>() { F32 val = 430903.2f; S32 val1 = ll_round(val); ensure("float ll_round value 1", (430903 == val1)); val = -430903.9f; val1 = ll_round(val); ensure("float ll_round value 2", (-430904 == val1)); } template<> template<> void math_object::test<9>() { F32 val = 430905.2654f, nearest = 100.f; val = ll_round(val, nearest); ensure("float ll_round value 1", (430900 == val)); val = -430905.2654f, nearest = 10.f; val = ll_round(val, nearest); ensure("float ll_round value 1", (-430910 == val)); } template<> template<> void math_object::test<10>() { F64 val = 430905.2654, nearest = 100.0; val = ll_round(val, nearest); ensure("double ll_round value 1", (430900 == val)); val = -430905.2654, nearest = 10.0; val = ll_round(val, nearest); ensure("double ll_round value 1", (-430910.00000 == val)); } template<> template<> void math_object::test<11>() { const F32 F_PI = 3.1415926535897932384626433832795f; F32 angle = 3506.f; angle = llsimple_angle(angle); ensure("llsimple_angle value 1", (angle <=F_PI && angle >= -F_PI)); angle = -431.f; angle = llsimple_angle(angle); ensure("llsimple_angle value 1", (angle <=F_PI && angle >= -F_PI)); } } namespace tut { struct uuid_data { LLUUID id; }; typedef test_group<uuid_data> uuid_test; typedef uuid_test::object uuid_object; tut::uuid_test tu("LLUUID"); template<> template<> void uuid_object::test<1>() { ensure("uuid null", id.isNull()); id.generate(); ensure("generate not null", id.notNull()); id.setNull(); ensure("set null", id.isNull()); } template<> template<> void uuid_object::test<2>() { id.generate(); LLUUID a(id); ensure_equals("copy equal", id, a); a.generate(); ensure_not_equals("generate not equal", id, a); a = id; ensure_equals("assignment equal", id, a); } template<> template<> void uuid_object::test<3>() { id.generate(); LLUUID copy(id); LLUUID mask; mask.generate(); copy ^= mask; ensure_not_equals("mask not equal", id, copy); copy ^= mask; ensure_equals("mask back", id, copy); } template<> template<> void uuid_object::test<4>() { id.generate(); std::string id_str = id.asString(); LLUUID copy(id_str.c_str()); ensure_equals("string serialization", id, copy); } } namespace tut { struct crc_data { }; typedef test_group<crc_data> crc_test; typedef crc_test::object crc_object; tut::crc_test tc("LLCrc"); template<> template<> void crc_object::test<1>() { /* Test buffer update and individual char update */ const char TEST_BUFFER[] = "hello &#$)$&Nd0"; LLCRC c1, c2; c1.update((U8*)TEST_BUFFER, sizeof(TEST_BUFFER) - 1); char* rh = (char*)TEST_BUFFER; while(*rh != '\0') { c2.update(*rh); ++rh; } ensure_equals("crc update 1", c1.getCRC(), c2.getCRC()); } template<> template<> void crc_object::test<2>() { /* Test mixing of buffer and individual char update */ const char TEST_BUFFER1[] = "Split Buffer one $^%$%#@$"; const char TEST_BUFFER2[] = "Split Buffer two )(8723#5dsds"; LLCRC c1, c2; c1.update((U8*)TEST_BUFFER1, sizeof(TEST_BUFFER1) - 1); char* rh = (char*)TEST_BUFFER2; while(*rh != '\0') { c1.update(*rh); ++rh; } rh = (char*)TEST_BUFFER1; while(*rh != '\0') { c2.update(*rh); ++rh; } c2.update((U8*)TEST_BUFFER2, sizeof(TEST_BUFFER2) - 1); ensure_equals("crc update 2", c1.getCRC(), c2.getCRC()); } } namespace tut { struct sphere_data { }; typedef test_group<sphere_data> sphere_test; typedef sphere_test::object sphere_object; tut::sphere_test tsphere("LLSphere"); template<> template<> void sphere_object::test<1>() { // test LLSphere::contains() and ::overlaps() S32 number_of_tests = 10; for (S32 test = 0; test < number_of_tests; ++test) { LLVector3 first_center(1.f, 1.f, 1.f); F32 first_radius = 3.f; LLSphere first_sphere( first_center, first_radius ); F32 half_millimeter = 0.0005f; LLVector3 direction( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); direction.normalize(); F32 distance = ll_frand(first_radius - 2.f * half_millimeter); LLVector3 second_center = first_center + distance * direction; F32 second_radius = first_radius - distance - half_millimeter; LLSphere second_sphere( second_center, second_radius ); ensure("first sphere should contain the second", first_sphere.contains(second_sphere)); ensure("first sphere should overlap the second", first_sphere.overlaps(second_sphere)); distance = first_radius + ll_frand(first_radius); second_center = first_center + distance * direction; second_radius = distance - first_radius + half_millimeter; second_sphere.set( second_center, second_radius ); ensure("first sphere should NOT contain the second", !first_sphere.contains(second_sphere)); ensure("first sphere should overlap the second", first_sphere.overlaps(second_sphere)); distance = first_radius + ll_frand(first_radius) + half_millimeter; second_center = first_center + distance * direction; second_radius = distance - first_radius - half_millimeter; second_sphere.set( second_center, second_radius ); ensure("first sphere should NOT contain the second", !first_sphere.contains(second_sphere)); ensure("first sphere should NOT overlap the second", !first_sphere.overlaps(second_sphere)); } } template<> template<> void sphere_object::test<2>() { skip("See SNOW-620. Neither the test nor the code being tested seem good. Also sim-only."); // test LLSphere::getBoundingSphere() S32 number_of_tests = 100; S32 number_of_spheres = 10; F32 sphere_center_range = 32.f; F32 sphere_radius_range = 5.f; for (S32 test = 0; test < number_of_tests; ++test) { // gegnerate a bunch of random sphere std::vector< LLSphere > sphere_list; for (S32 sphere_count=0; sphere_count < number_of_spheres; ++sphere_count) { LLVector3 direction( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); direction.normalize(); F32 distance = ll_frand(sphere_center_range); LLVector3 center = distance * direction; F32 radius = ll_frand(sphere_radius_range); LLSphere sphere( center, radius ); sphere_list.push_back(sphere); } // compute the bounding sphere LLSphere bounding_sphere = LLSphere::getBoundingSphere(sphere_list); // make sure all spheres are inside the bounding sphere { std::vector< LLSphere >::const_iterator sphere_itr; for (sphere_itr = sphere_list.begin(); sphere_itr != sphere_list.end(); ++sphere_itr) { ensure("sphere should be contained by the bounding sphere", bounding_sphere.contains(*sphere_itr)); } } // TODO -- improve LLSphere::getBoundingSphere() to the point where // we can reduce the 'expansion' in the two tests below to about // 2 mm or less F32 expansion = 0.005f; // move all spheres out a little bit // and count how many are NOT contained { std::vector< LLVector3 > uncontained_directions; std::vector< LLSphere >::iterator sphere_itr; for (sphere_itr = sphere_list.begin(); sphere_itr != sphere_list.end(); ++sphere_itr) { LLVector3 direction = sphere_itr->getCenter() - bounding_sphere.getCenter(); direction.normalize(); sphere_itr->setCenter( sphere_itr->getCenter() + expansion * direction ); if (! bounding_sphere.contains( *sphere_itr ) ) { uncontained_directions.push_back(direction); } } ensure("when moving spheres out there should be at least two uncontained spheres", uncontained_directions.size() > 1); /* TODO -- when the bounding sphere algorithm is improved we can open up this test * at the moment it occasionally fails when the sphere collection is tight and small * (2 meters or less) if (2 == uncontained_directions.size() ) { // if there were only two uncontained spheres then // the two directions should be nearly opposite F32 dir_dot = uncontained_directions[0] * uncontained_directions[1]; ensure("two uncontained spheres should lie opposite the bounding center", dir_dot < -0.95f); } */ } // compute the new bounding sphere bounding_sphere = LLSphere::getBoundingSphere(sphere_list); // increase the size of all spheres a little bit // and count how many are NOT contained { std::vector< LLVector3 > uncontained_directions; std::vector< LLSphere >::iterator sphere_itr; for (sphere_itr = sphere_list.begin(); sphere_itr != sphere_list.end(); ++sphere_itr) { LLVector3 direction = sphere_itr->getCenter() - bounding_sphere.getCenter(); direction.normalize(); sphere_itr->setRadius( sphere_itr->getRadius() + expansion ); if (! bounding_sphere.contains( *sphere_itr ) ) { uncontained_directions.push_back(direction); } } ensure("when boosting sphere radii there should be at least two uncontained spheres", uncontained_directions.size() > 1); /* TODO -- when the bounding sphere algorithm is improved we can open up this test * at the moment it occasionally fails when the sphere collection is tight and small * (2 meters or less) if (2 == uncontained_directions.size() ) { // if there were only two uncontained spheres then // the two directions should be nearly opposite F32 dir_dot = uncontained_directions[0] * uncontained_directions[1]; ensure("two uncontained spheres should lie opposite the bounding center", dir_dot < -0.95f); } */ } } } } namespace tut { F32 SMALL_RADIUS = 1.0f; F32 MEDIUM_RADIUS = 5.0f; F32 LARGE_RADIUS = 10.0f; struct line_data { }; typedef test_group<line_data> line_test; typedef line_test::object line_object; tut::line_test tline("LLLine"); template<> template<> void line_object::test<1>() { // this is a test for LLLine::intersects(point) which returns TRUE // if the line passes within some tolerance of point // these tests will have some floating point error, // so we need to specify how much error is ok F32 allowable_relative_error = 0.00001f; S32 number_of_tests = 100; for (S32 test = 0; test < number_of_tests; ++test) { // generate some random point to be on the line LLVector3 point_on_line( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); point_on_line.normalize(); point_on_line *= ll_frand(LARGE_RADIUS); // generate some random point to "intersect" LLVector3 random_direction ( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); random_direction.normalize(); LLVector3 random_offset( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); random_offset.normalize(); random_offset *= ll_frand(SMALL_RADIUS); LLVector3 point = point_on_line + MEDIUM_RADIUS * random_direction + random_offset; // compute the axis of approach (a unit vector between the points) LLVector3 axis_of_approach = point - point_on_line; axis_of_approach.normalize(); // compute the direction of the the first line (perp to axis_of_approach) LLVector3 first_dir( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); first_dir.normalize(); F32 dot = first_dir * axis_of_approach; first_dir -= dot * axis_of_approach; // subtract component parallel to axis first_dir.normalize(); // construct the line LLVector3 another_point_on_line = point_on_line + ll_frand(LARGE_RADIUS) * first_dir; LLLine line(another_point_on_line, point_on_line); // test that the intersection point is within MEDIUM_RADIUS + SMALL_RADIUS F32 test_radius = MEDIUM_RADIUS + SMALL_RADIUS; test_radius += (LARGE_RADIUS * allowable_relative_error); ensure("line should pass near intersection point", line.intersects(point, test_radius)); test_radius = allowable_relative_error * (point - point_on_line).length(); ensure("line should intersect point used to define it", line.intersects(point_on_line, test_radius)); } } template<> template<> void line_object::test<2>() { /* These tests fail intermittently on all platforms - see DEV-16600 Commenting this out until dev has time to investigate. // this is a test for LLLine::nearestApproach(LLLIne) method // which computes the point on a line nearest another line // these tests will have some floating point error, // so we need to specify how much error is ok // TODO -- make nearestApproach() algorithm more accurate so // we can tighten the allowable_error. Most tests are tighter // than one milimeter, however when doing randomized testing // you can walk into inaccurate cases. F32 allowable_relative_error = 0.001f; S32 number_of_tests = 100; for (S32 test = 0; test < number_of_tests; ++test) { // generate two points to be our known nearest approaches LLVector3 some_point( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); some_point.normalize(); some_point *= ll_frand(LARGE_RADIUS); LLVector3 another_point( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); another_point.normalize(); another_point *= ll_frand(LARGE_RADIUS); // compute the axis of approach (a unit vector between the points) LLVector3 axis_of_approach = another_point - some_point; axis_of_approach.normalize(); // compute the direction of the the first line (perp to axis_of_approach) LLVector3 first_dir( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); F32 dot = first_dir * axis_of_approach; first_dir -= dot * axis_of_approach; // subtract component parallel to axis first_dir.normalize(); // normalize // compute the direction of the the second line LLVector3 second_dir( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); dot = second_dir * axis_of_approach; second_dir -= dot * axis_of_approach; second_dir.normalize(); // make sure the lines aren't too parallel, dot = fabsf(first_dir * second_dir); if (dot > 0.99f) { // skip this test, we're not interested in testing // the intractible cases continue; } // construct the lines LLVector3 first_point = some_point + ll_frand(LARGE_RADIUS) * first_dir; LLLine first_line(first_point, some_point); LLVector3 second_point = another_point + ll_frand(LARGE_RADIUS) * second_dir; LLLine second_line(second_point, another_point); // compute the points of nearest approach LLVector3 some_computed_point = first_line.nearestApproach(second_line); LLVector3 another_computed_point = second_line.nearestApproach(first_line); // compute the error F32 first_error = (some_point - some_computed_point).length(); F32 scale = llmax((some_point - another_point).length(), some_point.length()); scale = llmax(scale, another_point.length()); scale = llmax(scale, 1.f); F32 first_relative_error = first_error / scale; F32 second_error = (another_point - another_computed_point).length(); F32 second_relative_error = second_error / scale; //if (first_relative_error > allowable_relative_error) //{ // std::cout << "first_error = " << first_error // << " first_relative_error = " << first_relative_error // << " scale = " << scale // << " dir_dot = " << (first_dir * second_dir) // << std::endl; //} //if (second_relative_error > allowable_relative_error) //{ // std::cout << "second_error = " << second_error // << " second_relative_error = " << second_relative_error // << " scale = " << scale // << " dist = " << (some_point - another_point).length() // << " dir_dot = " << (first_dir * second_dir) // << std::endl; //} // test that the errors are small ensure("first line should accurately compute its closest approach", first_relative_error <= allowable_relative_error); ensure("second line should accurately compute its closest approach", second_relative_error <= allowable_relative_error); } */ } F32 ALMOST_PARALLEL = 0.99f; template<> template<> void line_object::test<3>() { // this is a test for LLLine::getIntersectionBetweenTwoPlanes() method // first some known tests LLLine xy_plane(LLVector3(0.f, 0.f, 2.f), LLVector3(0.f, 0.f, 3.f)); LLLine yz_plane(LLVector3(2.f, 0.f, 0.f), LLVector3(3.f, 0.f, 0.f)); LLLine zx_plane(LLVector3(0.f, 2.f, 0.f), LLVector3(0.f, 3.f, 0.f)); LLLine x_line; LLLine y_line; LLLine z_line; bool x_success = LLLine::getIntersectionBetweenTwoPlanes(x_line, xy_plane, zx_plane); bool y_success = LLLine::getIntersectionBetweenTwoPlanes(y_line, yz_plane, xy_plane); bool z_success = LLLine::getIntersectionBetweenTwoPlanes(z_line, zx_plane, yz_plane); ensure("xy and zx planes should intersect", x_success); ensure("yz and xy planes should intersect", y_success); ensure("zx and yz planes should intersect", z_success); LLVector3 direction = x_line.getDirection(); ensure("x_line should be parallel to x_axis", fabs(direction.mV[VX]) == 1.f && 0.f == direction.mV[VY] && 0.f == direction.mV[VZ] ); direction = y_line.getDirection(); ensure("y_line should be parallel to y_axis", 0.f == direction.mV[VX] && fabs(direction.mV[VY]) == 1.f && 0.f == direction.mV[VZ] ); direction = z_line.getDirection(); ensure("z_line should be parallel to z_axis", 0.f == direction.mV[VX] && 0.f == direction.mV[VY] && fabs(direction.mV[VZ]) == 1.f ); // next some random tests F32 allowable_relative_error = 0.0001f; S32 number_of_tests = 20; for (S32 test = 0; test < number_of_tests; ++test) { // generate the known line LLVector3 some_point( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); some_point.normalize(); some_point *= ll_frand(LARGE_RADIUS); LLVector3 another_point( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); another_point.normalize(); another_point *= ll_frand(LARGE_RADIUS); LLLine known_intersection(some_point, another_point); // compute a plane that intersect the line LLVector3 point_on_plane( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); point_on_plane.normalize(); point_on_plane *= ll_frand(LARGE_RADIUS); LLVector3 plane_normal = (point_on_plane - some_point) % known_intersection.getDirection(); plane_normal.normalize(); LLLine first_plane(point_on_plane, point_on_plane + plane_normal); // compute a different plane that intersect the line LLVector3 point_on_different_plane( ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); point_on_different_plane.normalize(); point_on_different_plane *= ll_frand(LARGE_RADIUS); LLVector3 different_plane_normal = (point_on_different_plane - another_point) % known_intersection.getDirection(); different_plane_normal.normalize(); LLLine second_plane(point_on_different_plane, point_on_different_plane + different_plane_normal); if (fabs(plane_normal * different_plane_normal) > ALMOST_PARALLEL) { // the two planes are approximately parallel, so we won't test this case continue; } LLLine measured_intersection; bool success = LLLine::getIntersectionBetweenTwoPlanes( measured_intersection, first_plane, second_plane); ensure("plane intersection should succeed", success); F32 dot = fabs(known_intersection.getDirection() * measured_intersection.getDirection()); ensure("measured intersection should be parallel to known intersection", dot > ALMOST_PARALLEL); ensure("measured intersection should pass near known point", measured_intersection.intersects(some_point, LARGE_RADIUS * allowable_relative_error)); } } }
32.563536
117
0.672506
SaladDais
f1215ca40d4a6d21eafb106a07b2584254f51045
528
hpp
C++
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
1
2019-07-19T03:37:33.000Z
2019-07-19T03:37:33.000Z
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
#include <vector> #include "common.h" #ifndef __WRAPSTRINGVECTOR_H__ #define __WRAPSTRINGVECTOR_H__ #ifdef __cplusplus extern "C" { #endif DLL_PUBLIC wrapStringVector_t* wrapStringVector_create(std::vector<wrapString_t*> vector); DLL_PUBLIC void wrapStringVector_destroy(wrapStringVector_t* dm); DLL_PUBLIC uint64_t wrapStringVector_getSize(wrapStringVector_t* dm); DLL_PUBLIC wrapString_t* wrapStringVector_getAt(wrapStringVector_t* dm, uint64_t position); #ifdef __cplusplus } #endif #endif /* __WRAPSTRINGVECTOR_H__ */
22.956522
91
0.827652
LAGonauta
f1255f51472524661b626032a25cffd65da87655
697
cpp
C++
src/historypanel.cpp
SilangQuan/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
99
2015-01-14T01:10:37.000Z
2021-07-29T07:30:14.000Z
src/historypanel.cpp
sahwar/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
1
2019-08-07T13:06:31.000Z
2019-08-07T13:06:31.000Z
src/historypanel.cpp
sahwar/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
22
2015-01-19T14:53:22.000Z
2021-08-18T04:38:12.000Z
#include "historypanel.h" HistoryPanel::HistoryPanel(QUndoStack *stack,QWidget *parent) : QDockWidget(parent), undoView(stack) { this->setFeatures(QDockWidget::DockWidgetFloatable | \ QDockWidget::DockWidgetMovable | \ QDockWidget::DockWidgetClosable); this->setAttribute(Qt::WA_QuitOnClose, false); undoView.setBackgroundRole(QPalette::Dark); undoView.setFrameShape(QFrame::NoFrame); this->setWidget(&undoView); connect(&undoView, SIGNAL(pressed(const QModelIndex &)), this, SLOT(itemClickedSlot(const QModelIndex &))); } HistoryPanel::~HistoryPanel() { } void HistoryPanel::itemClickedSlot(const QModelIndex &index) { qDebug() << "itemClickedSlot"; emit historyTriggered(); }
24.034483
108
0.764706
SilangQuan
f12b50c6e5504105ae446094d24ead16c47e2710
5,616
cc
C++
src/cc/emulator/rebalanceexecutor_main.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
358
2015-01-04T14:04:51.000Z
2022-03-25T09:36:01.000Z
src/cc/emulator/rebalanceexecutor_main.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
167
2015-02-09T23:09:42.000Z
2022-02-17T02:47:40.000Z
src/cc/emulator/rebalanceexecutor_main.cc
kristi/qfs
1360c6b987d1888ab9f509d79a7abbfedf3e6bbb
[ "Apache-2.0" ]
124
2015-01-12T13:54:36.000Z
2022-03-04T16:34:24.000Z
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2008/08/27 // // Author: Sriram Rao // // Copyright 2008-2012,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Driver program to run the meta server in emulator mode and // executes the plan for re-balancing blocks. // Might be used for "off-line" debugging meta server layout emulation code, // and / or the re-balance plan / off-line re-balancer. // //---------------------------------------------------------------------------- #include "LayoutEmulator.h" #include "emulator_setup.h" #include "common/MsgLogger.h" #include "common/Properties.h" #include "common/MdStream.h" #include "kfsio/SslFilter.h" #include "meta/AuditLog.h" #include <unistd.h> #include <stdlib.h> using std::string; using std::cout; using std::cerr; using namespace KFS; int main(int argc, char** argv) { string rebalancePlanFn("rebalanceplan.txt"); string logdir("kfslog"); string cpdir("kfscp"); string networkFn; string chunkmapFn("chunkmap.txt"); string propsFn; string chunkMapDir; int64_t chunkServerTotalSpace = -1; int optchar; bool helpFlag = false; bool debugFlag = false; while ((optchar = getopt(argc, argv, "c:l:n:b:r:hdp:o:S:")) != -1) { switch (optchar) { case 'l': logdir = optarg; break; case 'c': cpdir = optarg; break; case 'n': networkFn = optarg; break; case 'b': chunkmapFn = optarg; break; case 'r': rebalancePlanFn = optarg; break; case 'h': helpFlag = true; break; case 'd': debugFlag = true; break; case 'p': propsFn = optarg; break; case 'o': chunkMapDir = optarg; break; case 'S': chunkServerTotalSpace = (int64_t)atof(optarg); break; default: helpFlag = true; break; } } if (helpFlag || rebalancePlanFn.empty()) { cout << "Usage: " << argv[0] << "\n" "[-l <log directory> (default " << logdir << ")]\n" "[-c <checkpoint directory> (default " << cpdir << ")]\n" "[-n <network definition file name> (default none, i.e. empty)" " without definition file chunk servers and chunk map from" " checkpoint transaction log replay are used]\n" "[-b <chunkmap file> (default " << chunkmapFn << ")]\n" "[-r <re-balance plan file> (default" << rebalancePlanFn << ")]\n" "[-p <configuration file> (default none)]\n" "[-o <new chunk map output directory> (default none)]\n" "[-d debug -- print chunk into stdout layout before and after]\n" "[-S <num> -- chunk server total space (default is -1)" " this value has effect without network definition file" " if set to negative value, then number of chunks multiplied" " by max. chunk size (64M) divided by the number of chunk servers" " plus 20% is used]\n" ; return 1; } MdStream::Init(); SslFilter::Error sslErr = SslFilter::Initialize(); if (sslErr) { cerr << "failed to initialize ssl: " << " error: " << sslErr << " " << SslFilter::GetErrorMsg(sslErr) << "\n"; return 1; } MsgLogger::Init(0, MsgLogger::kLogLevelINFO); LayoutEmulator& emulator = LayoutEmulator::Instance(); int status = 0; Properties props; if ((propsFn.empty() || (status = props.loadProperties(propsFn.c_str(), char('='))) == 0)) { emulator.SetParameters(props); if ((status = EmulatorSetup( emulator, logdir, cpdir, networkFn, chunkmapFn, -1, false, chunkServerTotalSpace)) == 0 && (status = emulator.LoadRebalancePlan(rebalancePlanFn)) == 0) { if (debugFlag) { emulator.PrintChunkserverBlockCount(cout); } emulator.ExecuteRebalancePlan(); if (! chunkMapDir.empty()) { emulator.DumpChunkToServerMap(chunkMapDir); } if (debugFlag) { emulator.PrintChunkserverBlockCount(cout); } } } AuditLog::Stop(); sslErr = SslFilter::Cleanup(); if (sslErr) { KFS_LOG_STREAM_ERROR << "failed to cleanup ssl: " << " error: " << sslErr << " " << SslFilter::GetErrorMsg(sslErr) << KFS_LOG_EOM; } MsgLogger::Stop(); MdStream::Cleanup(); return (status == 0 ? 0 : 1); }
32.275862
82
0.529736
kristi
f12c9971493d54340d32f72eca1df09d36601c94
16,931
inl
C++
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
1
2022-02-25T08:14:55.000Z
2022-02-25T08:14:55.000Z
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
null
null
null
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2010 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ // do not attempt to compile this file with any other compiler #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC // to configure launch parameters #include <thrust/detail/device/cuda/arch.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/device/cuda/block/reduce.h> #include <thrust/detail/device/cuda/extern_shared_ptr.h> #include <thrust/detail/device/cuda/dispatch/reduce.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/functional.h> #include <thrust/detail/device/cuda/synchronize.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { /* * Reduce a vector of n elements using binary_op() * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputIterator, typename OutputType, typename BinaryFunction, typename SharedArray> __device__ void reduce_n_device(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op, SharedArray shared_array) { // perform one level of reduction, writing per-block results to // global memory for subsequent processing (e.g. second level reduction) const unsigned int grid_size = blockDim.x * gridDim.x; unsigned int i = blockDim.x * blockIdx.x + threadIdx.x; // advance input input += i; if (i < n) { // initialize local sum OutputType sum = thrust::detail::device::dereference(input); i += grid_size; input += grid_size; // accumulate local sum while (i < n) { OutputType val = thrust::detail::device::dereference(input); sum = binary_op(sum, val); i += grid_size; input += grid_size; } // copy local sum to shared memory shared_array[threadIdx.x] = sum; } __syncthreads(); // compute reduction across block thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = shared_array[threadIdx.x]; } // end reduce_n_device() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_smem(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr; OutputType *shared_array = shared_ptr; reduce_n_device(input, n, block_results, binary_op, shared_array); } // end reduce_n_kernel() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_gmem(InputIterator input, const unsigned int n, OutputType * block_results, OutputType * shared_array, BinaryFunction binary_op) { reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x); } // end reduce_n_kernel() template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType> struct wide_unary_op : public thrust::unary_function<WideType,OutputType> { BinaryFunction binary_op; __host__ __device__ wide_unary_op(BinaryFunction binary_op) : binary_op(binary_op) {} __host__ __device__ OutputType operator()(WideType x) { WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1; OutputType sum = static_cast<InputType>(x & mask); for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++) sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) ); return sum; } }; #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // temporarily disable 'possible loss of data' warnings on MSVC #pragma warning(push) #pragma warning(disable : 4244 4267) #endif template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result, thrust::detail::true_type) // reduce in shared memory { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; // determine launch parameters const size_t smem_per_thread = sizeof(OutputType); const size_t block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<RandomAccessIterator1, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; // reduce input to per-block sums reduce_n_smem<<<num_blocks, block_size, smem_size>>>(first, n, thrust::raw_pointer_cast(&*result), binary_op); synchronize_if_enabled("reduce_n_smem"); } // end unordered_blocked_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result, thrust::detail::false_type) // reduce in global memory { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; const size_t block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<RandomAccessIterator1, OutputType, BinaryFunction>, 0); // allocate storage for shared array thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks); // reduce input to per-block sums detail::reduce_n_gmem<<<num_blocks, block_size>>>(first, n, raw_pointer_cast(&*result), raw_pointer_cast(&shared_array[0]), binary_op); synchronize_if_enabled("reduce_n_gmem"); } // end unordered_blocked_reduce_n() template<typename Iterator, typename InputType = typename thrust::iterator_value<Iterator>::type> struct use_wide_reduction : thrust::detail::integral_constant< bool, thrust::detail::is_pod<InputType>::value && thrust::detail::is_trivial_iterator<Iterator>::value && (sizeof(InputType) == 1 || sizeof(InputType) == 2) > {}; } // end namespace detail #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // reenable 'possible loss of data' warnings #pragma warning(pop) #endif template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_wide_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // "wide" reduction for small types like char, short, etc. typedef typename thrust::iterator_traits<RandomAccessIterator>::value_type InputType; typedef unsigned int WideType; const size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); const size_t n_wide = n / input_type_per_wide_type; thrust::device_ptr<const WideType> wide_first = thrust::device_pointer_cast(reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first))); thrust::transform_iterator< detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>, thrust::device_ptr<const WideType> > xfrm_wide_first = thrust::make_transform_iterator(wide_first, detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)); const size_t num_blocks_from_wide_part = thrust::detail::device::cuda::get_unordered_blocked_standard_reduce_n_schedule(xfrm_wide_first, n_wide, init, binary_op); // add one block to reduce the tail (if there is one) RandomAccessIterator tail_first = first + n_wide * input_type_per_wide_type; const size_t n_tail = n - (tail_first - first); return num_blocks_from_wide_part + ((n_tail > 0) ? 1 : 0); } template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_standard_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // decide whether or not we will use smem size_t smem_per_thread = 0; if(sizeof(OutputType) <= 64) { smem_per_thread = sizeof(OutputType); } // choose block_size size_t block_size = 0; if(smem_per_thread > 0) { block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(detail::reduce_n_smem<RandomAccessIterator, OutputType, BinaryFunction>, smem_per_thread); } else { block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(detail::reduce_n_gmem<RandomAccessIterator, OutputType, BinaryFunction>, smem_per_thread); } const size_t smem_size = block_size * smem_per_thread; // choose the maximum number of blocks we can launch size_t max_blocks = 0; if(smem_per_thread > 0) { max_blocks = thrust::detail::device::cuda::arch::max_active_blocks(detail::reduce_n_smem<RandomAccessIterator, OutputType, BinaryFunction>, block_size, smem_size); } else { max_blocks = thrust::detail::device::cuda::arch::max_active_blocks(detail::reduce_n_gmem<RandomAccessIterator, OutputType, BinaryFunction>, block_size, smem_size); } // finalize the number of blocks to launch const size_t num_blocks = std::min<size_t>(max_blocks, (n + (block_size - 1)) / block_size); return num_blocks; } // TODO add runtime switch for SizeType vs. unsigned int // TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes) template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_wide_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { // XXX this implementation is incredibly ugly // if we only received one output block, use the standard reduction if(num_blocks < 2) { thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(first, n, num_blocks, binary_op, result); } // end if else { // break the reduction into a "wide" body and the "tail" // this assumes we have at least two output blocks to work with // "wide" reduction for small types like char, short, etc. typedef typename thrust::iterator_traits<RandomAccessIterator1>::value_type InputType; typedef typename thrust::iterator_traits<RandomAccessIterator2>::value_type OutputType; typedef unsigned int WideType; // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType * // TODO use simple threshold and ensure alignment of wide_first // process first part const size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); const size_t n_wide = n / input_type_per_wide_type; thrust::device_ptr<const WideType> wide_first(reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first))); thrust::transform_iterator< detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>, thrust::device_ptr<const WideType> > xfrm_wide_first = thrust::make_transform_iterator(wide_first, detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)); // compute where the tail is RandomAccessIterator1 tail_first = first + n_wide * input_type_per_wide_type; const size_t n_tail = n - (tail_first - first); // count the number of results to produce from the widened input size_t num_wide_results = num_blocks; // reserve one of the results for the tail, if there is one if(n_tail > 0) { --num_wide_results; } // process the wide body thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(xfrm_wide_first, n_wide, num_wide_results, binary_op, result); // process tail thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(tail_first, n_tail, (size_t)1u, binary_op, result + num_wide_results); } // end else } // end unordered_blocked_wide_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_standard_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; // handle zero length input or output if(n == 0 || num_blocks == 0) return; // whether to perform blockwise reductions in shared memory or global memory thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem; return detail::unordered_blocked_reduce_n(first, n, num_blocks, binary_op, result, use_smem); } // end unordered_standard_blocked_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { // dispatch on whether or not to use a wide reduction return thrust::detail::device::cuda::dispatch::unordered_blocked_reduce_n(first, n, num_blocks, binary_op, result, typename detail::use_wide_reduction<RandomAccessIterator1>::type()); } // end unordered_blocked_reduce_n() template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // dispatch on whether or not to use the wide reduction return thrust::detail::device::cuda::dispatch::get_unordered_blocked_reduce_n_schedule(first, n, init, binary_op, typename detail::use_wide_reduction<RandomAccessIterator>::type()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC
36.967249
184
0.677396
ismagarcia
f131ae22b89d5264c17c140348cdd0fdc264b00a
4,000
cpp
C++
myutils/myutils_lib/src/myutils/myutils_cpp/io_util.cpp
juanbarrios/multimedia_tools
91fe64779168c3dd3ad4e51e089df9ccad5f176b
[ "BSD-2-Clause" ]
6
2015-09-08T00:14:59.000Z
2018-09-11T09:46:40.000Z
myutils/myutils_lib/src/myutils/myutils_cpp/io_util.cpp
juanbarrios/multimedia_tools
91fe64779168c3dd3ad4e51e089df9ccad5f176b
[ "BSD-2-Clause" ]
null
null
null
myutils/myutils_lib/src/myutils/myutils_cpp/io_util.cpp
juanbarrios/multimedia_tools
91fe64779168c3dd3ad4e51e089df9ccad5f176b
[ "BSD-2-Clause" ]
1
2020-11-13T15:55:30.000Z
2020-11-13T15:55:30.000Z
/* * Copyright (C) 2012-2015, Juan Manuel Barrios <http://juan.cl/> * All rights reserved. * * This file is part of MultimediaTools. https://github.com/juanbarrios/multimedia_tools * MultimediaTools is made available under the terms of the BSD 2-Clause License. */ #include "io_util.hpp" #include "../myutils_c.h" #include <fstream> using namespace my; static std::vector<std::string> TOV(MyVectorString *list) { std::vector<std::string> vector; for (long long i = 0; i < my_vectorString_size(list); ++i) { char *value = my_vectorString_get(list, i); if (value != NULL) vector.push_back(std::string(value)); } my_vectorString_release(list, true); return vector; } static MyVectorString *TOMY(std::vector<std::string> vector) { MyVectorString *list = my_vectorString_new(); for (size_t i = 0; i < vector.size(); ++i) { std::string value = vector[i]; my_vectorString_add(list, (char*) value.c_str()); } return list; } static std::string TOS(char *string) { std::string s(string); free(string); return s; } std::string io::getFilename(std::string filePath) { return TOS(my_io_getFilename(filePath.c_str())); } std::string io::getFilenameWithoutExtension(std::string filePath) { return TOS(my_io_getFilenameWithoutExtension(filePath.c_str())); } std::string io::getFilenameExtension(std::string filePath) { return TOS(my_io_getFilenameExtension(filePath.c_str())); } std::string io::getDirname(std::string filePath) { return TOS(my_io_getDirname(filePath.c_str())); } std::string io::getAbsolutPath(std::string relativePath) { return TOS(my_io_getAbsolutPath(relativePath.c_str())); } bool io::deleteFile(std::string filename, bool fail) { return my_io_deleteFile(filename.c_str(), fail); } bool io::moveFile(std::string filenameOrig, std::string filenameDest, bool fail) { return my_io_moveFile(filenameOrig.c_str(), filenameDest.c_str(), fail); } void io::copyFile(std::string filenameOrig, std::string filenameDest) { my_io_copyFile(filenameOrig.c_str(), filenameDest.c_str()); } bool io::existsFile(std::string filename) { return my_io_existsFile(filename.c_str()); } bool io::existsDir(std::string dirname) { return my_io_existsDir(dirname.c_str()); } bool io::notExists(std::string filename) { return my_io_notExists(filename.c_str()); } long long io::getFilesize(std::string filename) { return my_io_getFilesize(filename.c_str()); } void io::createDir(std::string path, bool fail) { my_io_createDir(path.c_str(), fail); } void io::createParentDir(std::string file_path) { my_io_createParentDir(file_path.c_str()); } std::vector<std::string> io::listFilesInDir(std::string path_dir) { return TOV(my_io_listFilesInDir(path_dir.c_str())); } std::vector<std::string> io::listFilesWithSuffix(std::string path_dir, std::string suffix) { return TOV(my_io_listFilesWithSuffix(path_dir.c_str(), suffix.c_str())); } void io::loadFileBytes(std::string filename, std::vector<char> &file_bytes) { std::ifstream ifs(filename, std::ios::binary | std::ios::ate); std::ifstream::pos_type pos = ifs.tellg(); file_bytes.reserve(pos); ifs.seekg(0, std::ios::beg); ifs.read(&file_bytes[0], pos); } void io::loadLinesFile(std::string filename, std::vector<std::string> &file_lines, bool ignoreComments) { std::ifstream ifs(filename); for (std::string line; std::getline(ifs, line);) { if (!ignoreComments || !my::string::startsWith(line, "#")) file_lines.push_back(line); } } void io::saveLinesFile(std::string filename, const std::vector<std::string> &lines) { MyVectorString *list = TOMY(lines); my_io_saveLinesFile(filename.c_str(), list); my_vectorString_release(list, false); } void io::saveTextFile(std::string filename, const std::string &text) { my_io_saveTextFile(filename.c_str(), text.c_str()); } void io::saveBytesFile(std::string filename, const void *buffer, long long num_bytes) { my_io_saveBytesFile(filename.c_str(), buffer, num_bytes); } int io::system(std::string command) { return my_io_system(command.c_str()); }
31.25
88
0.73175
juanbarrios
f133403a74e5e48ac921b67904eee315e55ce2ce
362
cpp
C++
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
145
2015-02-14T09:32:04.000Z
2022-01-21T21:17:27.000Z
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
80
2015-01-01T03:28:49.000Z
2021-04-03T09:08:54.000Z
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
74
2015-01-11T16:23:57.000Z
2021-12-22T07:16:13.000Z
#include "ofMain.h" #include "ofApp.h" //-------------------------------------------------------------- int main(){ #ifdef USE_PROGRAMMABLE_PIPELINE ofGLWindowSettings settings; settings.setGLVersion(4,3); settings.width = 1024; settings.height = 768; ofCreateWindow(settings); #else ofSetupOpenGL(1024, 768, OF_WINDOW); #endif ofRunApp(new ofApp()); }
20.111111
64
0.61326
syeminpark
f133d2a074c29505599e68d75668d881a126e20e
530
cpp
C++
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
3
2019-10-20T18:46:08.000Z
2022-02-12T20:39:53.000Z
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
null
null
null
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
1
2021-04-12T09:00:07.000Z
2021-04-12T09:00:07.000Z
#include "Action.h" namespace fluentBehaviorTree { Node * Action::copy() { Action* newNode = new Action(this->getName(), this->mAction); return newNode; } //Action::Action(std::string name, EStatus(*f)()) Action::Action(std::string name, std::function<EStatus()> f) { this->setName(name); mAction = f; } // Return result of action EStatus Action::tickNode() { try { this->setResult(mAction()); } catch (std::exception& e) { this->setResult(EStatus::ERROR); } return this->getResult(); } }
17.096774
63
0.637736
JuanFerrer
f133d7087112d40f2ca9b96a2d04587509da3332
8,609
cxx
C++
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
#include "mock_sdl.hxx" #include "native.hxx" #include "default_colors.hxx" #include <cassert> #include <filesystem> struct SDL_Window { char const * title; int x, y, w, h; std::uint32_t flags; SDL_DisplayMode mode; }; namespace snake::client { template <MockPolicy policy> int MockSDL<policy>::getCallCount(Mock mock) const { auto const it = m_callCounts.find(mock); return it == m_callCounts.end() ? 0 : it->second; } template <MockPolicy policy> int MockSDL<policy>::init(std::uint32_t features) { ++m_callCounts[Mock::Init]; auto const & impl = getMock<Mock::Init>().impl; if (impl) return impl(features); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::init(features); } template <MockPolicy policy> void MockSDL<policy>::quit() { ++m_callCounts[Mock::Quit]; auto const & impl = getMock<Mock::Quit>().impl; if (impl) impl(); else if constexpr (policy == MockPolicy::CallOriginal) ActualSDL::quit(); } template <MockPolicy policy> char const * MockSDL<policy>::getError() { ++m_callCounts[Mock::GetError]; auto const & impl = getMock<Mock::GetError>().impl; if (impl) return impl(); else if constexpr (policy == MockPolicy::Stub) return ""; else return ActualSDL::getError(); } template <MockPolicy policy> std::uint32_t MockSDL<policy>::wasInit(std::uint32_t features) { ++m_callCounts[Mock::WasInit]; auto const & impl = getMock<Mock::WasInit>().impl; if (impl) return impl(features); else if constexpr (policy == MockPolicy::Stub) return features; else return ActualSDL::wasInit(features); } template <MockPolicy policy> SDL_Window * MockSDL<policy>::createWindow(char const * title, int x, int y, int w, int h, std::uint32_t flags) { ++m_callCounts[Mock::CreateWindow]; auto const & impl = getMock<Mock::CreateWindow>().impl; if (impl) return impl(title, x, y, w, h, flags); else if constexpr (policy == MockPolicy::Stub) return new SDL_Window{title, x, y, w, h, flags}; else return ActualSDL::createWindow(title, x, y, w, h, flags); } template <MockPolicy policy> void MockSDL<policy>::destroyWindow(SDL_Window * window) { ++m_callCounts[Mock::DestroyWindow]; auto const & impl = getMock<Mock::DestroyWindow>().impl; if (impl) impl(window); else if constexpr (policy == MockPolicy::Stub) delete window; else ActualSDL::destroyWindow(window); } template <MockPolicy policy> int MockSDL<policy>::setWindowDisplayMode(SDL_Window * window, SDL_DisplayMode const * mode) { ++m_callCounts[Mock::SetWindowDisplayMode]; auto const & impl = getMock<Mock::SetWindowDisplayMode>().impl; if (impl) return impl(window, mode); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); assert(mode != nullptr); window->mode = *mode; return 0; } else return ActualSDL::setWindowDisplayMode(window, mode); } template <MockPolicy policy> int MockSDL<policy>::getWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode) { ++m_callCounts[Mock::GetWindowDisplayMode]; auto const & impl = getMock<Mock::GetWindowDisplayMode>().impl; if (impl) return impl(window, mode); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); assert(mode != nullptr); *mode = window->mode; return 0; } else return ActualSDL::getWindowDisplayMode(window, mode); } template <MockPolicy policy> int MockSDL<policy>::pollEvent(SDL_Event * event) { ++m_callCounts[Mock::PollEvent]; auto const & impl = getMock<Mock::PollEvent>().impl; if (impl) return impl(event); else if constexpr (policy == MockPolicy::Stub) { assert(event != nullptr); return 0; } else return ActualSDL::pollEvent(event); } template <MockPolicy policy> int MockSDL<policy>::pushEvent(SDL_Event * event) { ++m_callCounts[Mock::PushEvent]; auto const & impl = getMock<Mock::PushEvent>().impl; if (impl) return impl(event); else if constexpr (policy == MockPolicy::Stub) { assert(event != nullptr); return 0; } else return ActualSDL::pushEvent(event); } template <MockPolicy policy> void MockSDL<policy>::useEventQueue(std::deque<SDL_Event> & queue) { mockFunction<Mock::PushEvent>([&queue](SDL_Event * event) { assert(event != nullptr); queue.push_back(*event); return 1; }); mockFunction<Mock::PollEvent>([&queue](SDL_Event * event) { assert(event != nullptr); if (queue.empty()) return 0; else { *event = queue.front(); queue.pop_front(); return 1; } }); } SDL_Event event_helpers::makeQuitEvent(std::uint32_t timestamp) { SDL_Event result{}; result.quit = SDL_QuitEvent{SDL_QUIT, timestamp}; return result; } template <MockPolicy policy> SDL_Surface * MockSDL<policy>::getWindowSurface(SDL_Window * window) { ++m_callCounts[Mock::GetWindowSurface]; auto const & impl = getMock<Mock::GetWindowSurface>().impl; if (impl) return impl(window); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); return nullptr; } else return ActualSDL::getWindowSurface(window); } template <MockPolicy policy> void MockSDL<policy>::freeSurface(SDL_Surface * surface) { ++m_callCounts[Mock::FreeSurface]; auto const & impl = getMock<Mock::FreeSurface>().impl; if (impl) impl(surface); else if constexpr (policy == MockPolicy::Stub) delete surface; else ActualSDL::freeSurface(surface); } template <MockPolicy policy> int MockSDL<policy>::fillRect(SDL_Surface * destination, SDL_Rect const * rect, std::uint32_t color) { ++m_callCounts[Mock::FillRect]; auto const & impl = getMock<Mock::FillRect>().impl; if (impl) return impl(destination, rect, color); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::fillRect(destination, rect, color); } template <MockPolicy policy> uint32_t MockSDL<policy>::mapRGBA(SDL_PixelFormat const * format, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a) { ++m_callCounts[Mock::MapRGBA]; auto const & impl = getMock<Mock::MapRGBA>().impl; if (impl) return impl(format, r, g, b, a); else if constexpr (policy == MockPolicy::Stub) return colors::colorToRGBA({r, g, b, a}); else return ActualSDL::mapRGBA(format, r, g, b, a); } template <MockPolicy policy> int MockSDL<policy>::updateWindowSurface(SDL_Window * window) { ++m_callCounts[Mock::UpdateWindowSurface]; auto const & impl = getMock<Mock::UpdateWindowSurface>().impl; if (impl) return impl(window); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::updateWindowSurface(window); } template <MockPolicy policy> std::string MockSDL<policy>::getBasePath() { ++m_callCounts[Mock::GetBasePath]; auto const & impl = getMock<Mock::GetBasePath>().impl; if (impl) return impl(); else if constexpr (policy == MockPolicy::Stub) return native::getExePath().parent_path(); else return ActualSDL::getBasePath(); } template <MockPolicy policy> std::string MockSDL<policy>::getPrefPath(char const * organizationName, char const * applicationName) { ++m_callCounts[Mock::GetPrefPath]; auto const & impl = getMock<Mock::GetPrefPath>().impl; if (impl) return impl(organizationName, applicationName); else if constexpr (policy == MockPolicy::Stub) return std::filesystem::temp_directory_path(); else return ActualSDL::getPrefPath(organizationName, applicationName); } template <MockPolicy policy> SDL_Surface * MockSDL<policy>::createRGBSurfaceWithFormat(std::uint32_t flags, int width, int height, int depth, std::uint32_t format) { ++m_callCounts[Mock::CreateRGBSurfaceWithFormat]; auto const & impl = getMock<Mock::CreateRGBSurfaceWithFormat>().impl; if (impl) return impl(flags, width, height, depth, format); else if constexpr (policy == MockPolicy::Stub) return new SDL_Surface{flags, nullptr, width, height}; else return ActualSDL::createRGBSurfaceWithFormat(flags, width, height, depth, format); } template class MockSDL<MockPolicy::Stub>; template class MockSDL<MockPolicy::CallOriginal>; }
31.305455
114
0.663956
Drako
f1363e9b219963d000f28531bfbc954a6c2e19c6
981
cpp
C++
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
1
2021-09-30T10:02:35.000Z
2021-09-30T10:02:35.000Z
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
null
null
null
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
null
null
null
//C++ 11 #include<iostream> #include<vector> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int row=-1,col=-1; for(int i=0; i<matrix.size(); i++){ for(int j=0; j<matrix[i].size(); j++){ if(i==j){ if(target==matrix[i][j]) return true; else if(target<matrix[i][j] && i>0 && j>0){ row=i-1; col=j-1; break; } } } } if(row!=-1 && col!=-1){ for(int i=row; i<matrix.size(); i++){ if(target==matrix[i][col]) return true; } for(int j=col; j<matrix[row].size(); j++){ if(target==matrix[row][j]) return true; } } return false; } }; int main(){ vector<vector<int>> V = {{1,4},{2,5}}; //{{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}}; Solution Obj; cout<<Obj.searchMatrix(V,2); return 0; }
22.295455
80
0.474006
anubhavnandan
f1368af0b8f2b7466ea7f18c8e33951f47157d5a
391
hpp
C++
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
null
null
null
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
null
null
null
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
1
2020-11-03T14:51:43.000Z
2020-11-03T14:51:43.000Z
// // Created by System Administrator on 2019-08-02. // #ifndef HEARTBEAT_PARAMETERS_UTILS_T_HPP #define HEARTBEAT_PARAMETERS_UTILS_T_HPP #include <cstdint> namespace utils{ extern uint16_t default_sport; extern uint16_t default_dport; extern uint32_t default_dst_ip; extern int default_1_round_flows; extern int max_ttl; } #endif //HEARTBEAT_PARAMETERS_UTILS_T_HPP
19.55
49
0.785166
dioptra-io
f138c5e88387d953e4170e678fab7166a67c5055
4,516
cpp
C++
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
1
2020-12-03T20:26:48.000Z
2020-12-03T20:26:48.000Z
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
null
null
null
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
null
null
null
#include "SSRPump.hpp" #include "helpers.hpp" static void timer_callback(void); static SSRPump *instance = nullptr; SSRPump::SSRPump(uint8_t ctrl_pin, int32_t timer_id, uint32_t timer_period_us) : SSR(ctrl_pin), timer_pwm_(nullptr), pwm_percent_(PWM_0_PERCENT), time_on_(0) { if (instance) { Serial.println("ERROR: more than one pumps generated"); ESP.restart(); return; } timer_pwm_ = timerBegin(timer_id, 80, true); timerAttachInterrupt(timer_pwm_, &timer_callback, true); timerAlarmWrite(timer_pwm_, timer_period_us, true); timerAlarmEnable(timer_pwm_); instance = this; } SSRPump* SSRPump::getInstance() { return instance; } void SSRPump::setPWM(uint8_t percent) { if (!enabled_ || timer_pwm_ == nullptr) return; if (percent < 5) { if (pwm_percent_ != PWM_0_PERCENT && systime_ms() - time_on_ > 3000) { // if (SHOT_getState() != SHOT_PAUSE) // PID_override(0.0f, PID_OVERRIDE_CNT); } pwm_percent_ = PWM_0_PERCENT; } else { if (pwm_percent_ == PWM_0_PERCENT) time_on_ = systime_ms(); if (percent < 15) pwm_percent_ = PWM_10_PERCENT; else if (percent < 25) pwm_percent_ = PWM_20_PERCENT; else if (percent < 35) pwm_percent_ = PWM_30_PERCENT; else if (percent < 45) pwm_percent_ = PWM_40_PERCENT; else if (percent < 55) pwm_percent_ = PWM_50_PERCENT; else if (percent < 65) pwm_percent_ = PWM_60_PERCENT; else if (percent < 75) pwm_percent_ = PWM_70_PERCENT; else if (percent < 85) pwm_percent_ = PWM_80_PERCENT; else if (percent < 95) pwm_percent_ = PWM_90_PERCENT; else if (percent <= 100) pwm_percent_ = PWM_100_PERCENT; else { Serial.print("SSRPump: pump pwm percent not valid! "); Serial.println(percent); pwm_percent_ = PWM_0_PERCENT; return; } } } PWM_Percent_t IRAM_ATTR SSRPump::getPWM() { return pwm_percent_; } static void IRAM_ATTR timer_callback(void) { static uint32_t pwm_period_counter_ = 0; // elapsed periods if (instance == nullptr) return; if (!instance->isEnabled()) { pwm_period_counter_ = 0; instance->off(); return; } // called every 20ms == full sine period switch (instance->getPWM()) { case PWM_0_PERCENT: instance->off(); pwm_period_counter_ = 0; break; case PWM_10_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_20_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_30_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 3) pwm_period_counter_ = 0; break; case PWM_40_PERCENT: if (pwm_period_counter_ == 0 || pwm_period_counter_ == 2) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_50_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 2) pwm_period_counter_ = 0; break; case PWM_60_PERCENT: if (pwm_period_counter_ == 0 || pwm_period_counter_ == 1 || pwm_period_counter_ == 3) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_70_PERCENT: if (pwm_period_counter_ == 3 || pwm_period_counter_ == 6 || pwm_period_counter_ == 9) instance->off(); else instance->on(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_80_PERCENT: if (pwm_period_counter_ < 4) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_90_PERCENT: if (pwm_period_counter_ < 9) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_100_PERCENT: instance->on(); pwm_period_counter_ = 0; break; default: instance->off(); } }
24.021277
95
0.608725
solderdev
f13b47a006cdb1e6a82dc982ad4580ebb457e364
5,850
cc
C++
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
18
2018-01-31T02:47:39.000Z
2021-03-13T15:17:45.000Z
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
2
2017-12-03T08:05:40.000Z
2018-06-13T22:05:37.000Z
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
null
null
null
#include <cassert> #include <regex> #include "h5s3/private/s3_driver.h" namespace h5s3::s3_driver { const char* s3_kv_store::name = "h5s3"; s3_kv_store::s3_kv_store(const std::string& host, bool use_tls, const std::string& bucket, const std::string& path, const std::string& access_key, const std::string& secret_key, const std::string& region, const std::size_t page_size) : m_host(host), m_use_tls(use_tls), m_bucket(bucket), m_path(path), m_notary(region, access_key, secret_key), m_allocated_pages(0), m_page_size(page_size) { try { std::string result = s3::get_object(m_notary, m_bucket, path + "/.meta", m_host, m_use_tls); std::regex metadata_regex("page_size=([0-9]+)\n" "allocated_pages=([0-9]+)\n" "invalid_pages=\\{(([0-9]+ )*[0-9]*)\\}\n"); std::smatch match; if (!std::regex_match(result, match, metadata_regex)) { std::stringstream s; s << "failed to parse metadata from .meta file:\n" << result; throw std::runtime_error(s.str()); } { std::size_t metadata_page_size; std::stringstream s(match[1].str()); s >> metadata_page_size; if (m_page_size != 0 && metadata_page_size != m_page_size) { std::stringstream s; s << "passed page size does not match existing page size: " << m_page_size << " != " << metadata_page_size; throw std::runtime_error(s.str()); } m_page_size = metadata_page_size; } { std::stringstream s(match[2].str()); s >> m_allocated_pages; } { std::stringstream s(match[3].str()); page::id page_id; while (s >> page_id) { m_invalid_pages.insert(page_id); } } } catch (const curl::http_error& e) { if (e.code != 404) { throw; } } } s3_kv_store s3_kv_store::from_params(const std::string_view& uri_view, unsigned int, // TODO: Use this? std::size_t page_size, const char* access_key, const char* secret_key, const char* region, const char* host, bool use_tls) { std::string uri(uri_view); std::regex url_regex("s3://(.+)/(.+)"); std::smatch match; if (!std::regex_match(uri, match, url_regex)) { throw std::runtime_error(uri); } std::string bucket = match[1].str(); std::string path = match[2].str(); // Trim trailing slashes. while (path.back() == '/') { path.pop_back(); } // TODO: Allow anonymous usage without either key. // TODO: Validate that these are valid keys if possible. if (!access_key) { throw std::runtime_error("Access Key is Required."); } if (!secret_key) { throw std::runtime_error("Secret Key is Required."); } if (!region) { region = "us-east-1"; } if (!page_size) { using utils::operator""_MB; page_size = 2_MB; } std::string host_string; if (!host) { host_string = s3::default_host; } else { host_string = host; } return {host, use_tls, bucket, path, access_key, secret_key, region, page_size}; } void s3_kv_store::max_page(page::id max_page) { for (page::id page_id = max_page + 1; page_id < m_allocated_pages; ++page_id) { m_invalid_pages.insert(page_id); } m_allocated_pages = max_page + 1; } void s3_kv_store::read(page::id page_id, utils::out_buffer& out) const { assert(out.size() == m_page_size); if (page_id > max_page() || m_invalid_pages.find(page_id) != m_invalid_pages.end()) { std::memset(out.data(), 0, m_page_size); } std::string keyname(m_path + "/" + std::to_string(page_id)); try { std::size_t size = s3::get_object(out, m_notary, m_bucket, keyname, m_host, m_use_tls); if (size != m_page_size) { throw std::runtime_error("page was smaller than the page_size"); } return; } catch (const curl::http_error& e) { if (e.code != 404) { throw; } } std::memset(out.data(), 0, m_page_size); } void s3_kv_store::write(page::id page_id, const std::string_view& data) { std::string keyname(m_path + "/" + std::to_string(page_id)); s3::set_object(m_notary, m_bucket, keyname, data, m_host, m_use_tls); m_allocated_pages = std::max(m_allocated_pages, page_id + 1); m_invalid_pages.erase(page_id); } void s3_kv_store::flush() { std::stringstream formatter; formatter << "page_size=" << m_page_size << '\n' << "allocated_pages" << m_allocated_pages << '\n' << "invalid_pages={"; for (page::id page_id : m_invalid_pages) { formatter << page_id << ','; } if (m_invalid_pages.size()) { // consume the trailing comma formatter.get(); } formatter << "}\n"; s3::set_object(m_notary, m_bucket, m_path + "/.meta", formatter.str(), m_host, m_use_tls); } } // namespace h5s3::s3_driver // declare storage for the static member m_class in this TU template<> H5FD_class_t h5s3::s3_driver::s3_driver::m_class{};
30.46875
90
0.524786
h5s3
f13d2da4aaf99d31083e4bf11ede8a42d3a5278b
1,247
cpp
C++
src/nbind/Vector2.cpp
tyduptyler13/MyEngine
6081686eb0f3357b9046f82a7aecafa691c3b05b
[ "MIT" ]
7
2018-10-27T02:55:07.000Z
2021-12-31T20:20:33.000Z
src/nbind/Vector2.cpp
MyUPlay/MyEngine
6081686eb0f3357b9046f82a7aecafa691c3b05b
[ "MIT" ]
2
2016-12-12T21:00:31.000Z
2018-02-12T00:43:02.000Z
src/nbind/Vector2.cpp
tyduptyler13/MyEngine
6081686eb0f3357b9046f82a7aecafa691c3b05b
[ "MIT" ]
2
2018-08-30T05:47:09.000Z
2021-03-03T05:37:35.000Z
#include "Vector2.hpp" #include "nbind/nbind.h" using namespace MyEngine; NBIND_CLASS(Vector2f, Vector2) { construct<>(); construct<float, float>(); construct<Vector2f>(); getset(getX, setX); getset(getY, setY); multimethod(set, args(float, float)); multimethod(add, args(const Vector2f&)); multimethod(add, args(float), "addScalar"); method(addVectors); multimethod(sub, args(const Vector2f&)); multimethod(sub, args(float), "subScalar"); method(subVectors); multimethod(multiply, args(const Vector2f&)); multimethod(multiply, args(float), "multiplyScalar"); //method(multiplyVectors); //multimethod(divide, args(const Vector2f&)); multimethod(divide, args(float), "divideScalar"); //method(divideVectors); Missing? method(min); method(max); method(clamp); method(clampScalar); method(floor); method(ceil); method(round); method(roundToZero); method(negate); method(dot); method(lengthSq); method(length); method(lengthManhattan); method(normalize); method(setLength); method(lerp); method(lerpVectors); method(distanceTo); method(distanceToSquared); //method(setFromMatrixPosition); //method(setFromMatrixScale); //method(setFromMatrixColumn); method(equals); //toArray and fromArray??? }
20.112903
54
0.725742
tyduptyler13
f1402f69ee26471fd5e5f671470bf25e21306cbf
1,082
hpp
C++
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
/*----------------------------------------------------------------------------/ Lovyan GFX library - LCD graphics library . support platform: ESP32 (SPI/I2S) with Arduino/ESP-IDF ATSAMD51 (SPI) with Arduino Original Source: https://github.com/lovyan03/LovyanGFX/ Licence: [BSD](https://github.com/lovyan03/LovyanGFX/blob/master/license.txt) Author: [lovyan03](https://twitter.com/lovyan03) Contributors: [ciniml](https://github.com/ciniml) [mongonta0716](https://github.com/mongonta0716) [tobozo](https://github.com/tobozo) /----------------------------------------------------------------------------*/ #ifndef LOVYANGFX_HPP_ #define LOVYANGFX_HPP_ #ifdef setFont #undef setFont #endif #if __has_include("lgfx/v1_init.hpp") && ( defined ( LGFX_USE_V1 ) || !__has_include("lgfx/v0_init.hpp") ) #include "lgfx/v1_init.hpp" #if defined ( LGFX_AUTODETECT ) #include "LGFX_AUTODETECT.hpp" #endif #else // if defined ( LGFX_USE_V0 ) #if __has_include("lgfx/v0_init.hpp") #include "lgfx/v0_init.hpp" #endif #endif #endif
22.541667
106
0.601664
Mchaney3
f140458f3f6808294f359bada3c654ccfcbe456d
4,022
cpp
C++
src/Utils.cpp
PeriodicSeizures/Alchyme
68b034ec4c2111c52e9b15540b3d8323482b164c
[ "MIT" ]
null
null
null
src/Utils.cpp
PeriodicSeizures/Alchyme
68b034ec4c2111c52e9b15540b3d8323482b164c
[ "MIT" ]
1
2021-09-21T01:37:43.000Z
2021-09-21T01:37:43.000Z
src/Utils.cpp
PeriodicSeizures/Alchyme
68b034ec4c2111c52e9b15540b3d8323482b164c
[ "MIT" ]
null
null
null
#include "Utils.hpp" // https://stackoverflow.com/a/17350413 // Colors for output #define RESET "\033[0m" #define BLACK "\033[30m" #define RED "\033[31m" #define GREEN "\033[32m" #define GOLD "\033[33m" #define BLUE "\033[34m" #define PURPLE "\033[35m" #define CYAN "\033[36m" #define WHITE "\033[37m" #define GRAY "\033[90m" namespace Alchyme { namespace Utils { void initLogger() { el::Configurations loggerConfiguration; //el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%startTime", std::bind(getTimeSinceProgramStart))); //std::string format = "%s [%startTime][%level][%thread][%fbase]: %msg"; // https://github.com/amrayn/easyloggingpp#datetime-format-specifiers // [%fbase:L%line] std::string format = "[%datetime{%H:%m:%s.%g}] [%thread thread/%level]: %msg"; loggerConfiguration.set(el::Level::Info, el::ConfigurationType::Format, format); loggerConfiguration.set(el::Level::Error, el::ConfigurationType::Format, RED + format + RESET); loggerConfiguration.set(el::Level::Fatal, el::ConfigurationType::Format, RED + format + RESET); loggerConfiguration.set(el::Level::Warning, el::ConfigurationType::Format, GOLD + format + RESET); loggerConfiguration.set(el::Level::Debug, el::ConfigurationType::Format, GOLD + format + RESET); el::Helpers::setThreadName("main"); el::Loggers::reconfigureAllLoggers(loggerConfiguration); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); //el::Loggers::file LOG(INFO) << "Logger is configured"; } UID stringToUID(std::string_view sv) { std::string s(sv); std::stringstream ss(s); UID uid; ss >> uid; return uid; } bool isAddress(std::string_view s) { //address make_address(const char* str, // asio::error_code & ec) ASIO_NOEXCEPT asio::error_code ec; asio::ip::make_address(s, ec); return ec ? false : true; } std::string join(std::vector<std::string_view>& strings) { std::string result; for (auto& s : strings) { result += s; } return result; } std::vector<std::string_view> split(std::string_view s, char ch) { //std::string s = "scott>=tiger>=mushroom"; // split in Java appears to be a recursive decay function (for the pattern) int off = 0; int next = 0; std::vector<std::string_view> list; while ((next = s.find(ch, off)) != std::string::npos) { list.push_back(s.substr(off, next)); off = next + 1; } // If no match was found, return this if (off == 0) return { s }; // Add remaining segment list.push_back(s.substr(off)); // Construct result int resultSize = list.size(); while (resultSize > 0 && list[resultSize - 1].empty()) { resultSize--; } return std::vector<std::string_view>(list.begin(), list.begin() + resultSize); //std::vector<std::string_view> res; // //size_t pos = 0; //while ((pos = s.find(delimiter)) != std::string::npos) { // //std::cout << token << std::endl; // res.push_back(s.substr(0, pos)); // //s.erase(0, pos + delimiter.length()); // if (pos + delimiter.length() == s.length()) // s = s.substr(pos + delimiter.length()); // else s = s.substr(pos + delimiter.length()); //} //if (res.empty()) // res.push_back(s); ////std::cout << s << std::endl; //return res; } } }
35.910714
134
0.529836
PeriodicSeizures
f1422934b9420423c0c048dd11e80b33032672ea
1,259
cpp
C++
movie.cpp
msk610/MovieGrossPredictor
90720a152aef69a955d3519a735fcd0c3d9e06dd
[ "MIT" ]
14
2016-12-16T16:42:32.000Z
2017-08-16T19:42:04.000Z
movie.cpp
msk610/MovieGrossPredictor
90720a152aef69a955d3519a735fcd0c3d9e06dd
[ "MIT" ]
null
null
null
movie.cpp
msk610/MovieGrossPredictor
90720a152aef69a955d3519a735fcd0c3d9e06dd
[ "MIT" ]
null
null
null
// // movie.cpp // MovieGross // // // Copyright © 2016 ArsenKevinMD. All rights reserved. // #include <stdio.h> #include <stdio.h> #include "movie.h" #include <math.h> using namespace std; using namespace CsvProc; //MovieData definitions namespace MovieData{ //constructor Movie::Movie(vector<float>data){ attr = data; } //method to normalize the data void Movie::normalize(Csv&csv){ //iterate and use normalizing formula for(int i = 0; i < attr.size(); ++i){ attr[i] = (attr[i] - csv.MIN[i])/(csv.MAX[i]-csv.MIN[i]); } } //Operator to return attribute value float Movie::operator[](int index){ return attr[index]; } //Operator to return eucledian distance float Movie::operator-(Movie& aMovie){ float dist = 0; for(int i = 0; i < attr.size(); ++i){ if(i != GROSS) dist += powf(attr[i]-aMovie[i], 2); } return sqrtf(dist); } //Operator to return whether two Movies are the same bool Movie::operator==(Movie& aMovie){ for(int i = 0; i < attr.size(); ++i){ if(attr[i] != aMovie[i]) return false; } return true; } }
21.338983
69
0.545671
msk610
f1456eab5f4f2ff70ba6e238c9809508a19d1053
2,842
cc
C++
src/attributes/WrepRootNodeAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/WrepRootNodeAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/WrepRootNodeAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file WrepRootNodeAttributes.h \\brief Definition of WrepRootNode Attributes class. This file is automatically generated. Do Not Edit! */ #include "WrepRootNodeAttributes.h" #include "MagicsParameter.h" #include "ParameterSettings.h" using namespace magics; WrepRootNodeAttributes::WrepRootNodeAttributes(): pixel_width_(ParameterManager::getDouble("wrep_node_width")), pixel_height_(ParameterManager::getDouble("wrep_node_height")), anchor_(ParameterManager::getString("wrep_node_mapping_anchor")) { } WrepRootNodeAttributes::~WrepRootNodeAttributes() { } void WrepRootNodeAttributes::set(const std::map<string, string>& params) { vector<string> prefix(1); int i = 0; prefix[i++] = "wrep_node"; setAttribute(prefix, "wrep_node_width", pixel_width_, params); setAttribute(prefix, "wrep_node_height", pixel_height_, params); setAttribute(prefix, "wrep_node_mapping_anchor", anchor_, params); } void WrepRootNodeAttributes::copy(const WrepRootNodeAttributes& other) { pixel_width_ = other.pixel_width_; pixel_height_ = other.pixel_height_; anchor_ = other.anchor_; } bool WrepRootNodeAttributes::accept(const string& node) { if ( magCompare(node, "magics") ) return true; return false; } void WrepRootNodeAttributes::set(const XmlNode& node) { bool apply = false; if ( this->accept(node.name()) == false ) return; if ( magCompare(node.name(), "magics") ) apply = true; if ( apply ) set(node.attributes()); else { } for (auto &elt : node.elements()) { } } void WrepRootNodeAttributes::print(ostream& out) const { out << "Attributes["; out << " pixel_width = " << pixel_width_; out << " pixel_height = " << pixel_height_; out << " anchor = " << anchor_; out << "]" << "\n"; } void WrepRootNodeAttributes::toxml(ostream& out) const { out << "\"magics\""; out << ", \"wrep_node_width\":"; niceprint(out,pixel_width_); out << ", \"wrep_node_height\":"; niceprint(out,pixel_height_); out << ", \"wrep_node_mapping_anchor\":"; niceprint(out,anchor_); } static MagicsParameter<double> wrep_node_width("wrep_node_width", 800); static MagicsParameter<double> wrep_node_height("wrep_node_height", 400); static MagicsParameter<string> wrep_node_mapping_anchor("wrep_node_mapping_anchor", "centre");
23.487603
94
0.6886
b8raoult
f148aa47d8075c1bdd4a1ab2bf50402a8c02fc3a
13,896
cpp
C++
gvsoc/gvsoc/models/devices/gpio/fxl6408.cpp
gemenerik/gap_sdk
afae64d239db6d73f79c90c2ca2c832b6361f109
[ "Apache-2.0" ]
null
null
null
gvsoc/gvsoc/models/devices/gpio/fxl6408.cpp
gemenerik/gap_sdk
afae64d239db6d73f79c90c2ca2c832b6361f109
[ "Apache-2.0" ]
null
null
null
gvsoc/gvsoc/models/devices/gpio/fxl6408.cpp
gemenerik/gap_sdk
afae64d239db6d73f79c90c2ca2c832b6361f109
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 GreenWaves Technologies * * 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: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com) */ #include <vp/vp.hpp> #include <vp/itf/i2c.hpp> typedef enum { I2C_STATE_WAIT_START, I2C_STATE_WAIT_ADDRESS, I2C_STATE_GET_DATA, I2C_STATE_SAMPLE_DATA, I2C_STATE_ACK, I2C_STATE_READ_ACK } I2c_state_e; class Fxl6408 : public vp::component { public: Fxl6408(js::config *config); int build(); protected: static void i2c_sync(void *__this, int scl, int sda); void i2c_start(unsigned int address, bool is_read); void i2c_handle_byte(uint8_t byte); void i2c_stop(); void i2c_get_data(); void i2c_send_byte(uint8_t byte); void handle_reg_write(uint8_t address, uint8_t value); uint8_t handle_reg_read(uint8_t address); void start(); vp::trace trace; vp::i2c_master i2c_itf; unsigned int device_address; bool i2c_being_addressed; unsigned int i2c_address; uint8_t i2c_pending_data; bool i2c_is_read; I2c_state_e i2c_state; int i2c_pending_bits; int i2c_prev_sda; int i2c_prev_scl; unsigned int i2c_pending_send_byte; uint8_t reg_address; bool waiting_reg_address; uint8_t device_id; uint8_t io_dir; uint8_t output_state; uint8_t output_high_z; uint8_t input_default_state; uint8_t pull_enable; uint8_t pull_down_up; uint8_t input_status; uint8_t interrupt_mask; uint8_t interrupt_status; }; Fxl6408::Fxl6408(js::config *config) : vp::component(config) { } void Fxl6408::start() { this->i2c_itf.sync(1, 1); } void Fxl6408::i2c_sync(void *__this, int scl, int sda) { Fxl6408 *_this = (Fxl6408 *)__this; _this->trace.msg(vp::trace::LEVEL_TRACE, "I2C sync (scl: %d, sda: %d)\n", scl, sda); int sdo = 1; if (scl == 1 && _this->i2c_prev_sda != sda) { if (_this->i2c_prev_sda == 1) { _this->trace.msg(vp::trace::LEVEL_TRACE, "Detected start\n"); _this->i2c_state = I2C_STATE_WAIT_ADDRESS; _this->i2c_address = 0; _this->i2c_pending_bits = 8; } else { _this->i2c_state = I2C_STATE_WAIT_START; _this->i2c_stop(); } goto end; } if (!_this->i2c_prev_scl && scl) { switch (_this->i2c_state) { case I2C_STATE_WAIT_START: { sdo = 1; break; } case I2C_STATE_WAIT_ADDRESS: { if (_this->i2c_pending_bits > 1) { _this->i2c_address = (_this->i2c_address << 1) | sda; _this->trace.msg(vp::trace::LEVEL_TRACE, "Received address bit (bit: %d, address: 0x%x, pending_bits: %d)\n", sda, _this->i2c_address, _this->i2c_pending_bits); } else { _this->i2c_is_read = sda; } _this->i2c_pending_bits--; if (_this->i2c_pending_bits == 0) { _this->i2c_start(_this->i2c_address, _this->i2c_is_read); _this->i2c_state = I2C_STATE_ACK; _this->i2c_pending_bits = 8; } break; } case I2C_STATE_SAMPLE_DATA: { _this->i2c_pending_data = (_this->i2c_pending_data << 1) | sda; _this->trace.msg(vp::trace::LEVEL_TRACE, "Sampling data (bit: %d, pending_value: 0x%x, pending_bits: %d)\n", sda, _this->i2c_pending_data, _this->i2c_pending_bits); _this->i2c_pending_bits--; if (_this->i2c_pending_bits == 0) { _this->i2c_pending_bits = 8; _this->i2c_handle_byte(_this->i2c_pending_data); _this->i2c_state = I2C_STATE_ACK; } break; } case I2C_STATE_ACK: { _this->trace.msg(vp::trace::LEVEL_TRACE, "Ack (being_addressed: %d)\n", _this->i2c_being_addressed); if (_this->i2c_being_addressed) { if (_this->i2c_is_read) { _this->i2c_state = I2C_STATE_GET_DATA; _this->i2c_pending_bits = 8; _this->i2c_get_data(); } else { _this->i2c_state = I2C_STATE_SAMPLE_DATA; } } else { _this->i2c_state = I2C_STATE_WAIT_START; } break; } case I2C_STATE_READ_ACK: { _this->i2c_state = I2C_STATE_WAIT_START; break; } } } if (_this->i2c_prev_scl && !scl) { switch (_this->i2c_state) { case I2C_STATE_ACK: { _this->trace.msg(vp::trace::LEVEL_TRACE, "Ack (being_addressed: %d)\n", _this->i2c_being_addressed); sdo = !_this->i2c_being_addressed; break; } case I2C_STATE_READ_ACK: { _this->trace.msg(vp::trace::LEVEL_TRACE, "Read ack\n"); sdo = 0; break; } case I2C_STATE_GET_DATA: { sdo = (_this->i2c_pending_send_byte >> 7) & 1; _this->trace.msg(vp::trace::LEVEL_TRACE, "Sending bit (bit: %d, pending_value: 0x%x, pending_bits: %d)\n", sdo, _this->i2c_pending_send_byte, _this->i2c_pending_bits); _this->i2c_pending_send_byte <<= 1; _this->i2c_pending_bits--; if (_this->i2c_pending_bits == 0) { _this->i2c_state = I2C_STATE_READ_ACK; } break; } } } end: if (_this->i2c_prev_scl && !scl) { _this->trace.msg(vp::trace::LEVEL_TRACE, "Sync sda (value: %d)\n", sdo); _this->i2c_itf.sync(1, sdo); } _this->i2c_prev_sda = sda; _this->i2c_prev_scl = scl; } void Fxl6408::i2c_start(unsigned int address, bool is_read) { this->trace.msg(vp::trace::LEVEL_TRACE, "Received header (address: 0x%x, is_read: %d)\n", address, is_read); this->i2c_being_addressed = address == this->device_address; if (this->i2c_being_addressed && is_read) { this->i2c_send_byte(this->handle_reg_read(this->reg_address)); } } void Fxl6408::i2c_handle_byte(uint8_t byte) { this->trace.msg(vp::trace::LEVEL_TRACE, "Handle byte (value: 0x%x)\n", byte); if (this->waiting_reg_address) { this->reg_address = byte; this->waiting_reg_address = false; } else { this->handle_reg_write(this->reg_address, byte); this->waiting_reg_address = true; } } void Fxl6408::i2c_stop() { this->trace.msg(vp::trace::LEVEL_TRACE, "Received stop bit\n"); } void Fxl6408::i2c_get_data() { this->trace.msg(vp::trace::LEVEL_TRACE, "Getting data\n"); } void Fxl6408::i2c_send_byte(uint8_t byte) { this->i2c_pending_send_byte = byte; } void Fxl6408::handle_reg_write(uint8_t address, uint8_t value) { this->trace.msg(vp::trace::LEVEL_TRACE, "Register write (address: 0x%x, value: 0x%x)\n", address, value); switch (address) { case 0x01: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Device ID & Ctrl", value); this->device_id = value; break; } case 0x03: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "IO Direction", value); this->io_dir = value; break; } case 0x05: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Output State", value); this->output_state = value; break; } case 0x07: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Output High-Z", value); this->output_high_z = value; break; } case 0x09: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Input Default State", value); this->input_default_state = value; break; } case 0x0B: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Pull Enable", value); this->pull_enable = value; break; } case 0x0D: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Pull-Down/Pull-Up", value); this->pull_down_up = value; break; } case 0x0F: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Input Status", value); this->input_status = value; break; } case 0x11: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "Interrupt Mask", value); this->interrupt_mask = value; break; } case 0x13: { this->trace.msg(vp::trace::LEVEL_INFO, "Writing register (name: %s, value: 0x%x)\n", "interrupt Status", value); this->interrupt_status = value; break; } default: this->trace.force_warning("Writing invalid register (address: 0x%x)\n", address); break; } } uint8_t Fxl6408::handle_reg_read(uint8_t address) { this->trace.msg(vp::trace::LEVEL_DEBUG, "Register read (address: 0x%x)\n", address); uint8_t value = 0xFF; switch (address) { case 0x01: { value = this->device_id; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Device ID & Ctrl", value); break; } case 0x03: { value = this->io_dir; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "IO Direction", value); break; } case 0x05: { value = this->output_state; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Output State", value); break; } case 0x07: { value = this->output_high_z; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Output High-Z", value); break; } case 0x09: { value = this->input_default_state; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Input Default State", value); break; } case 0x0B: { value = this->pull_enable; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Pull Enable", value); break; } case 0x0D: { value = this->pull_down_up; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Pull-Down/Pull-Up", value); break; } case 0x0F: { value = this->input_status; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Input Status", value); break; } case 0x11: { value = this->interrupt_mask; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Interrupt Mask", value); break; } case 0x13: { value = this->interrupt_status; this->trace.msg(vp::trace::LEVEL_INFO, "Reading register (name: %s, value: 0x%x)\n", "Interrupt Status", value); break; } default: this->trace.force_warning("Reading invalid register (address: 0x%x)\n", address); break; } return value; } int Fxl6408::build() { traces.new_trace("trace", &trace, vp::DEBUG); this->i2c_itf.set_sync_meth(&Fxl6408::i2c_sync); this->new_master_port("i2c", &this->i2c_itf); this->i2c_state = I2C_STATE_WAIT_START; this->i2c_prev_sda = 1; this->i2c_prev_scl = 1; this->i2c_being_addressed = false; this->device_address = 0x43; this->waiting_reg_address = true; this->device_id = 0xC2; this->io_dir = 0x00; this->output_state = 0x00; this->output_high_z = 0xFF; this->input_default_state = 0x00; this->pull_enable = 0xFF; this->pull_down_up = 0x00; this->input_status = 0xFF; this->interrupt_mask = 0x00; this->interrupt_status = 0xFF; return 0; } extern "C" vp::component *vp_constructor(js::config *config) { return new Fxl6408(config); }
29.440678
183
0.544905
gemenerik
f14c0c480f4ef7280d98c05f6d35414e04452e82
3,443
cpp
C++
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
1
2020-08-31T13:44:12.000Z
2020-08-31T13:44:12.000Z
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
null
null
null
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
2
2020-03-25T09:23:24.000Z
2020-08-31T14:29:29.000Z
/* * Copyright (c) 2017 Robert Shaw * This file is a part of Libecpint. * * 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 "ecp.hpp" #include <cmath> #include <iostream> #include <algorithm> namespace libecpint { // GaussianECP constructor and copy constructor GaussianECP::GaussianECP() : n(0), l(0), a(0), d(0) {} GaussianECP::GaussianECP(int _n, int _l, double _a, double _d) : n(_n-2), l(_l), a(_a), d(_d) {} GaussianECP::GaussianECP(const GaussianECP& other) : n(other.n), l(other.l), a(other.a), d(other.d) {} // class ECP ECP::ECP() : N(0), L(-1), nCore(0) { center_[0] = center_[1] = center_[2] = 0.0; } ECP::ECP(const double *_center) : N(0), L(-1), nCore(0) { center_[0] = _center[0]; center_[1] = _center[1]; center_[2] = _center[2]; } ECP::ECP(const ECP &other) { gaussians = other.gaussians; N = other.N; L = other.L; nCore = other.nCore; center_ = other.center_; } void ECP::addPrimitive(int n, int l, double a, double d, bool needSort) { GaussianECP newEcp(n, l, a, d); gaussians.push_back(newEcp); N++; L = l > L ? l : L; if (needSort) sort(); } void ECP::sort() { std::sort(gaussians.begin(), gaussians.end(), [&] (const GaussianECP& g1, const GaussianECP& g2) {return (g1.l < g2.l);}); } bool ECP::noType1() const { bool zero = true; for (auto& g : gaussians) if (g.l == L && fabs(g.d) > 1e-12) zero = false; return zero; } // Evaluate U_l(r), assuming that gaussians sorted by angular momentum double ECP::evaluate(double r, int l) { double value = 0.0; int am = 0; double r2 = r*r; for (int i = 0; i < N; i++) { if (gaussians[i].l == l) // Only evaluate if in correct shell value += pow(r, gaussians[i].n) * gaussians[i].d * exp(-gaussians[i].a * r2); } return value; } void ECP::setPos(double x, double y, double z) { center_[0] = x; center_[1] = y; center_[2] = z; } ECPBasis::ECPBasis() : N(0), maxL(-1) {} void ECPBasis::addECP(ECP &U, int atom) { basis.push_back(U); atomList.push_back(atom); N++; maxL = U.getL() > maxL ? U.getL() : maxL; } ECP& ECPBasis::getECP(int i) { return basis[i]; } int ECPBasis::getECPCore(int q) { int core = 0; auto it = core_electrons.find(q); if (it != core_electrons.end()) core = it->second; return core; } }
30.201754
103
0.637816
peterbygrave
f14da6f1979d7bbe5eff5c16b0f1c2c828667448
1,319
cpp
C++
UVA/vol-108/10898-2.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
3
2017-05-12T14:45:37.000Z
2020-01-18T16:51:25.000Z
UVA/vol-108/10898-2.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
UVA/vol-108/10898-2.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define INF 67108864 using namespace std; int Ci[143][6], Cp[143], csz, S[10][10][10][10][10][10], DP[10][10][10][10][10][10], cse; int rec(int r0, int r1, int r2, int r3, int r4, int r5) { if (r0<0 || r1<0 || r2<0 || r3<0 || r4<0 || r5<0) return INF; int &ss = S[r0][r1][r2][r3][r4][r5]; if (ss == cse) return DP[r0][r1][r2][r3][r4][r5]; int mn = INF; for (int i=0; i<csz; ++i) mn = min(mn, rec(r0-Ci[i][0], r1-Ci[i][1], r2-Ci[i][2], r3-Ci[i][3], r4-Ci[i][4], r5-Ci[i][5]) + Cp[i]); ss = cse; return DP[r0][r1][r2][r3][r4][r5] = mn; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n, m; for (cse=1; cin >> n && n; ++cse) { S[0][0][0][0][0][0] = cse; csz = 0; for (int i=0; i<n; ++i) { memset(Ci[csz], 0, 24); Ci[csz][i] = 1; cin >> Cp[csz++]; } cin >> m; while (m--) { memset(Ci[csz], 0, 24); for (int i=0; i<n; ++i) cin >> Ci[csz][i]; cin >> Cp[csz++]; } cin >> m; while (m--) { int R[6] = {}; for (int i=0; i<n; ++i) cin >> R[i]; cout << rec(R[0], R[1], R[2], R[3], R[4], R[5]) << endl; } } }
24.886792
112
0.395754
arash16
f1550eb2c5d62e06ae8ab1c834700832abcaba7f
1,399
cpp
C++
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
null
null
null
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
null
null
null
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
4
2020-11-30T04:38:58.000Z
2021-10-05T15:25:38.000Z
class Solution { public: int ans(string w1, string w2){ string s=w1+w2; string t=s; reverse(t.begin(),t.end()); int n=(int)s.size(); int dp[n+1][n+1]; memset(dp,0,sizeof(dp)); int f=0; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(s[i-1]==t[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; } int longestPalindrome(string w1, string w2) { int m=0,mr=0; vector<bool> v(26,0); for(int i=0;i<w1.size();i++){ if(v[w1[i]-'a']){ continue; } v[w1[i]-'a']=1; for(int j=w2.size()-1;j>=0;j--){ if(w1[i]==w2[j]){ if(mr>j){ break; } if(m>(w1.size()-i+1+j)){ break; } // v[i]=1; m=max(m,ans(w1.substr(i,w1.size()-i),w2.substr(0,j+1))); mr=j; break; } } } return m; } };
26.396226
77
0.2802
hunt-s7
f1560e367521bbc28fd25bdd19ec1abf439c67ae
779
hpp
C++
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "LolGameSettingsLoginSessionStates.hpp" namespace lol { struct LolGameSettingsLoginSession { LolGameSettingsLoginSessionStates state; uint64_t summonerId; uint64_t accountId; json gasToken; }; inline void to_json(json& j, const LolGameSettingsLoginSession& v) { j["state"] = v.state; j["summonerId"] = v.summonerId; j["accountId"] = v.accountId; j["gasToken"] = v.gasToken; } inline void from_json(const json& j, LolGameSettingsLoginSession& v) { v.state = j.at("state").get<LolGameSettingsLoginSessionStates>(); v.summonerId = j.at("summonerId").get<uint64_t>(); v.accountId = j.at("accountId").get<uint64_t>(); v.gasToken = j.at("gasToken").get<json>(); } }
33.869565
72
0.680359
Maufeat
f15704af65edf9cb9856d1dc391a1b14924bc61f
3,808
cc
C++
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
/****************************************************************************** Copyright 2014 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. This work is open source software, licensed under the terms of the BSD license as described in the LICENSE file in the top-level directory. *******************************************************************************/ #include <PCU.h> #include "apfPM.h" #include <apf.h> #include <pcu_util.h> namespace apf { // the following three functions are for exclusive use by pumi_mesh_loadAll // the last arg "owner" is used only if a new pmodel entity is created PME* getPMent(PM& ps, apf::Parts const& pids, int owner) { APF_ITERATE(PM, ps, it) { bool equal=true; APF_ITERATE(Parts,pids,pit) { bool found=false; for (size_t i = 0; i < (*it).ids.size(); ++i) if ((*it).ids[i]==*pit) found=true; if (!found) { equal=false; break; } } if (equal) { PME& p = const_cast<PME&>(*it); ++(p.refs); return &p; } } static int pme_id=ps.size(); PME *pme = new PME(pme_id++, pids, owner); ps.insert(*pme); ++(pme->refs); return pme; } // the partition classification of mesh entities has to be updated separately void deletePM(PM& ps) { APF_ITERATE(PM, ps, it) ps.erase(*it); } void deletePMent(PM& ps, PME* p) { ps.erase(*p); } typedef std::map<int,size_t> CountMap; PME* getPME(PM& ps, apf::Parts const& ids) { PME const& cp = *(ps.insert(PME(ps.size(), ids, -1)).first); /* always annoyed by this flaw in std::set */ PME& p = const_cast<PME&>(cp); ++(p.refs); return &p; } void putPME(PM& ps, PME* p) { --(p->refs); if (!(p->refs)) ps.erase(*p); } static void getAdjacentParts(apf::Mesh* m, PM& ps, apf::Parts& ids) { APF_ITERATE(PM, ps, it) { std::vector<int> const& rp = it->ids; ids.insert(rp.begin(), rp.end()); } ids.erase(m->getId()); } static void getCountMap(apf::Mesh* m, PM& ps, CountMap& mp) { apf::Parts peers; size_t n; getAdjacentParts(m, ps, peers); n = m->count(m->getDimension()); PCU_Comm_Begin(); APF_ITERATE(apf::Parts, peers, it) PCU_COMM_PACK(*it, n); PCU_Comm_Send(); mp[m->getId()] = n; while (PCU_Comm_Listen()) { PCU_COMM_UNPACK(n); mp[PCU_Comm_Sender()] = n; } } static void setOwners(PM& ps, CountMap& mp) { APF_ITERATE(PM, ps, it) { PME const& cp = *it; PME& p = const_cast<PME&>(cp); /* again with the silly */ std::vector<int> const& ids = p.ids; PCU_ALWAYS_ASSERT(ids.size()); int owner = ids[0]; // PCU_ALWAYS_ASSERT(mp.count(owner)); // seol - this doesn't work for ghost copy for (size_t i = 1; i < ids.size(); ++i) { // PCU_ALWAYS_ASSERT(mp.count(ids[i])); // seol - this doesn't work for ghost copy if (mp[ids[i]] < mp[owner]) owner = ids[i]; } p.owner = owner; } } void updateOwners(apf::Mesh* m, PM& ps) { CountMap mp; getCountMap(m, ps, mp); setOwners(ps, mp); } void remapPM(PM& pm, int (*map)(int, void*), void* user) { APF_ITERATE(PM, pm, it) { PME const& cp = *it; PME& p = const_cast<PME&>(cp); /* yep */ p.owner = map(p.owner, user); std::vector<int>& ids = p.ids; /* note: we can only do this because operator<(std::vector<T>...) uses lexicographical comparison, and so for vectors A and B, A < B does not change if all the elements of A and B are multiplied or divided by a constant factor, so long as the resulting ids are also unique. any map which changes the results of lexicographical comparison breaks the ordering of PME's in the PM. */ for (size_t i = 0; i < ids.size(); ++i) ids[i] = map(ids[i], user); } } }
24.254777
88
0.581408
Thomas-Ulrich
f15851af613c1682d8d1920f3264480f9bf4a9ec
1,094
cpp
C++
Online Judges/CSES/CourseSchedule.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/CSES/CourseSchedule.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/CSES/CourseSchedule.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> #include <queue> using namespace std; vector<vector<int> >gr; vector<int>in; void top() { // taking all vextex with indegree 0 queue<int>q; for (int i = 1; i < (int)gr.size(); i++) { if (in[i] == 0) { q.push(i); } } // ans is going to store topologic sort int ans[100001] = {0}; int t = 0; while(!q.empty()) { int v = q.front(); ans[t++] = v; q.pop(); for(int i = 0; i < (int)gr[v].size(); i++) { in[gr[v][i]]--; if (in[gr[v][i]] == 0) { q.push(gr[v][i]); } } } // there's no cycle if (t + 1 == (int)gr.size()) { for (int i = 0; i < t; i++) { cout << ans[i] << " "; } } else { cout << "IMPOSSIBLE\n"; } } int main() { int n, m, a, b; cin >> n >> m; gr.assign(n+1, vector<int>()); in.assign(n + 1, 0); while(m--) { cin >> a >> b; gr[a].push_back(b); in[b]++; } top(); return 0; }
19.192982
52
0.394881
AnneLivia
f15e1f812ae414005e155ef8c02ba896a7eebcb2
11,013
cc
C++
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseMonitor.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseMonitor.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DPGAnalysis/SiStripTools/plugins/APVCyclePhaseMonitor.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // // Package: SiStripTools // Class: APVCyclePhaseMonitor // /**\class APVCyclePhaseMonitor APVCyclePhaseMonitor.cc DPGAnalysis/SiStripTools/plugins/APVCyclePhaseMonitor.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Andrea Venturi // Created: Tue Jul 19 11:56:00 CEST 2009 // // // system include files #include <memory> // user include files #include "TH1F.h" #include "TProfile.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "FWCore/Utilities/interface/InputTag.h" #include "DPGAnalysis/SiStripTools/interface/APVCyclePhaseCollection.h" #include "DPGAnalysis/SiStripTools/interface/RunHistogramManager.h" // // class decleration // class APVCyclePhaseMonitor : public edm::EDAnalyzer { public: explicit APVCyclePhaseMonitor(const edm::ParameterSet&); ~APVCyclePhaseMonitor() override; private: void beginJob() override; void beginRun(const edm::Run&, const edm::EventSetup&) override; void endRun(const edm::Run&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; void endJob() override; // ----------member data --------------------------- edm::EDGetTokenT<APVCyclePhaseCollection> _apvphasecollectionToken; std::vector<std::string> _selectedparts; std::vector<std::string> _selectedvectorparts; const unsigned int m_maxLS; const unsigned int m_LSfrac; RunHistogramManager m_rhm; std::map<std::string, TH1F*> _hphases; std::map<std::string, TH1F**> _hselectedphases; std::map<std::string, TH1F**> _hselectedphasesvector; std::map<std::string, TH1F**> _hselectedphasessize; std::map<std::string, TProfile*> _hphasevsorbit; std::map<std::string, TProfile**> _hselectedphasevsorbit; std::map<std::string, TProfile**> _hselectedphasevectorvsorbit; unsigned int _nevents; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // APVCyclePhaseMonitor::APVCyclePhaseMonitor(const edm::ParameterSet& iConfig) : _apvphasecollectionToken( consumes<APVCyclePhaseCollection>(iConfig.getParameter<edm::InputTag>("apvCyclePhaseCollection"))), _selectedparts( iConfig.getUntrackedParameter<std::vector<std::string> >("selectedPartitions", std::vector<std::string>())), _selectedvectorparts(iConfig.getUntrackedParameter<std::vector<std::string> >("selectedVectorPartitions", std::vector<std::string>())), m_maxLS(iConfig.getUntrackedParameter<unsigned int>("maxLSBeforeRebin", 125)), m_LSfrac(iConfig.getUntrackedParameter<unsigned int>("startingLSFraction", 16)), m_rhm(consumesCollector()), _hphases(), _hselectedphases(), _hselectedphasesvector(), _hselectedphasessize(), _hphasevsorbit(), _hselectedphasevsorbit(), _hselectedphasevectorvsorbit(), _nevents(0) { //now do what ever initialization is needed edm::LogInfo("UsedAPVCyclePhaseCollection") << " APVCyclePhaseCollection " << iConfig.getParameter<edm::InputTag>("apvCyclePhaseCollection") << " used"; for (std::vector<std::string>::const_iterator part = _selectedparts.begin(); part != _selectedparts.end(); ++part) { char hname[300]; sprintf(hname, "selected_phase_%s", part->c_str()); edm::LogInfo("SelectedTH1FBeingBooked") << "TH1F " << hname << " being booked"; _hselectedphases[*part] = m_rhm.makeTH1F(hname, hname, 70, -0.5, 69.5); sprintf(hname, "selected_phasevsorbit_%s", part->c_str()); edm::LogInfo("SelectedTProfileBeingBooked") << "TProfile " << hname << " being booked"; _hselectedphasevsorbit[*part] = m_rhm.makeTProfile(hname, hname, m_LSfrac * m_maxLS, 0, m_maxLS * 262144); } for (std::vector<std::string>::const_iterator part = _selectedvectorparts.begin(); part != _selectedvectorparts.end(); ++part) { char hname[300]; sprintf(hname, "selected_phase_vector_%s", part->c_str()); edm::LogInfo("SelectedVectTH1FBeingBooked") << "TH1F " << hname << " being booked"; _hselectedphasesvector[*part] = m_rhm.makeTH1F(hname, hname, 70, -0.5, 69.5); sprintf(hname, "selected_phase_size_%s", part->c_str()); edm::LogInfo("SelectedVectSizeTH1FBeingBooked") << "TH1F " << hname << " being booked"; _hselectedphasessize[*part] = m_rhm.makeTH1F(hname, hname, 10, -0.5, 9.5); sprintf(hname, "selected_phasevectorvsorbit_%s", part->c_str()); edm::LogInfo("SelectedVectTProfileBeingBooked") << "TProfile " << hname << " being booked"; _hselectedphasevectorvsorbit[*part] = m_rhm.makeTProfile(hname, hname, m_LSfrac * m_maxLS, 0, m_maxLS * 262144); } } APVCyclePhaseMonitor::~APVCyclePhaseMonitor() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to for each event ------------ void APVCyclePhaseMonitor::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; _nevents++; edm::Handle<APVCyclePhaseCollection> apvphases; iEvent.getByToken(_apvphasecollectionToken, apvphases); // improve the matchin between default and actual partitions edm::Service<TFileService> tfserv; for (std::map<std::string, int>::const_iterator phase = apvphases->get().begin(); phase != apvphases->get().end(); ++phase) { if (_hphases.find(phase->first) == _hphases.end()) { char dirname[300]; sprintf(dirname, "run_%d", iEvent.run()); TFileDirectory subrun = tfserv->mkdir(dirname); char hname[300]; sprintf(hname, "phase_%s", phase->first.c_str()); edm::LogInfo("TH1FBeingBooked") << "TH1F " << hname << " being booked"; _hphases[phase->first] = subrun.make<TH1F>(hname, hname, 70, -0.5, 69.5); _hphases[phase->first]->GetXaxis()->SetTitle("BX mod 70"); _hphases[phase->first]->GetYaxis()->SetTitle("Events"); sprintf(hname, "phasevsorbit_%s", phase->first.c_str()); edm::LogInfo("TProfileBeingBooked") << "TProfile " << hname << " being booked"; _hphasevsorbit[phase->first] = subrun.make<TProfile>(hname, hname, m_LSfrac * m_maxLS, 0, m_maxLS * 262144); _hphasevsorbit[phase->first]->SetCanExtend(TH1::kXaxis); _hphasevsorbit[phase->first]->GetXaxis()->SetTitle("time [orbit#]"); _hphasevsorbit[phase->first]->GetYaxis()->SetTitle("Phase"); } _hphases[phase->first]->Fill(phase->second); _hphasevsorbit[phase->first]->Fill(iEvent.orbitNumber(), phase->second); } // selected partitions for (std::vector<std::string>::const_iterator part = _selectedparts.begin(); part != _selectedparts.end(); ++part) { if (_hselectedphases.find(*part) != _hselectedphases.end() && _hselectedphases[*part] && *_hselectedphases[*part]) { (*_hselectedphases[*part])->Fill(apvphases->getPhase(*part)); } if (_hselectedphasevsorbit.find(*part) != _hselectedphasevsorbit.end() && _hselectedphasevsorbit[*part] && *_hselectedphasevsorbit[*part]) { (*_hselectedphasevsorbit[*part])->Fill(iEvent.orbitNumber(), apvphases->getPhase(*part)); } } for (std::vector<std::string>::const_iterator part = _selectedvectorparts.begin(); part != _selectedvectorparts.end(); ++part) { const std::vector<int> phases = apvphases->getPhases(*part); if (_hselectedphasessize.find(*part) != _hselectedphasessize.end() && _hselectedphasessize[*part] && *_hselectedphasessize[*part]) { (*_hselectedphasessize[*part])->Fill(phases.size()); } for (std::vector<int>::const_iterator phase = phases.begin(); phase != phases.end(); ++phase) { if (_hselectedphasesvector.find(*part) != _hselectedphasesvector.end() && _hselectedphasesvector[*part] && *_hselectedphasesvector[*part]) { (*_hselectedphasesvector[*part])->Fill(*phase); } if (_hselectedphasevectorvsorbit.find(*part) != _hselectedphasevectorvsorbit.end() && _hselectedphasevectorvsorbit[*part] && *_hselectedphasevectorvsorbit[*part]) { (*_hselectedphasevectorvsorbit[*part])->Fill(iEvent.orbitNumber(), *phase); } } } } void APVCyclePhaseMonitor::beginRun(const edm::Run& iRun, const edm::EventSetup&) { _hphases.clear(); _hphasevsorbit.clear(); m_rhm.beginRun(iRun); for (std::map<std::string, TH1F**>::const_iterator hist = _hselectedphases.begin(); hist != _hselectedphases.end(); ++hist) { if (*(hist->second)) { (*(hist->second))->GetXaxis()->SetTitle("BX mod 70"); (*(hist->second))->GetYaxis()->SetTitle("Events"); } } for (std::map<std::string, TProfile**>::const_iterator prof = _hselectedphasevsorbit.begin(); prof != _hselectedphasevsorbit.end(); ++prof) { if (*(prof->second)) { (*(prof->second))->SetCanExtend(TH1::kXaxis); (*(prof->second))->GetXaxis()->SetTitle("time [orbit#]"); (*(prof->second))->GetYaxis()->SetTitle("Phase"); } } for (std::map<std::string, TH1F**>::const_iterator hist = _hselectedphasesvector.begin(); hist != _hselectedphasesvector.end(); ++hist) { if (*(hist->second)) { (*(hist->second))->GetXaxis()->SetTitle("BX mod 70"); (*(hist->second))->GetYaxis()->SetTitle("Events"); } } for (std::map<std::string, TH1F**>::const_iterator hist = _hselectedphasessize.begin(); hist != _hselectedphasessize.end(); ++hist) { if (*(hist->second)) { (*(hist->second))->GetXaxis()->SetTitle("Number of Phases"); (*(hist->second))->GetYaxis()->SetTitle("Events"); } } for (std::map<std::string, TProfile**>::const_iterator prof = _hselectedphasevectorvsorbit.begin(); prof != _hselectedphasevectorvsorbit.end(); ++prof) { if (*(prof->second)) { (*(prof->second))->SetCanExtend(TH1::kXaxis); (*(prof->second))->GetXaxis()->SetTitle("time [orbit#]"); (*(prof->second))->GetYaxis()->SetTitle("Phase"); } } } void APVCyclePhaseMonitor::endRun(const edm::Run& iRun, const edm::EventSetup&) {} // ------------ method called once each job just before starting event loop ------------ void APVCyclePhaseMonitor::beginJob() {} // ------------ method called once each job just after ending the event loop ------------ void APVCyclePhaseMonitor::endJob() { edm::LogInfo("EndOfJob") << _nevents << " analyzed events"; } //define this as a plug-in DEFINE_FWK_MODULE(APVCyclePhaseMonitor);
38.642105
120
0.672932
ckamtsikis
f160b5fd8f6455f5ca65f73e02002c2a311c3f84
6,406
cpp
C++
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
#include "Components/Transform.h" #include "Log/Log.h" Transform::Transform() { isDirty = true; position = Vector3::zero; rotation = Quaternion::identity; scale = Vector3::one; gameObject = NULL; } Transform::Transform(const Vector3& _position, const Quaternion& _rotation, const Vector3& _scale) :position(_position),rotation(_rotation), scale(_scale), isDirty(true) { gameObject = NULL; } Transform::~Transform() { } void Transform::AttachToGameObject(GameObject* _gameObject) { gameObject = _gameObject; } GameObject* Transform::GetGameObject() { return gameObject; } Matrix4x4 Transform::GetLocalToWorldMatrix() { if (isDirty) { Matrix4x4 transMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x, position.y, position.z, 1); Matrix4x4 scaleMatrix(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1); localToWorldMatrix = transMatrix * rotation.GetRotMatrix() * scaleMatrix; isDirty = false; } return localToWorldMatrix; } void Transform::Translate(const Vector3 &delta) { position.x += delta.x; position.y += delta.y; position.z += delta.z; isDirty = true; /* Matrix4x4 mInv(1, 0, 0, -delta.x, 0, 1, 0, -delta.y, 0, 0, 1, -delta.z, 0, 0, 0, 1);*/ } void Transform::RotateAxis(Vector3 axis, float _rotation) { rotation = rotation * Quaternion(0.01f, 0.02f, 0, 1); isDirty = true; } void Transform::Rotate(float xRot, float yRot, float zRot) { rotation = rotation * Quaternion::Euler(xRot, yRot, zRot); isDirty = true; } Vector3 Transform::GetForward() { return rotation * Vector3::forward; } Vector3 Transform::GetRight() { return rotation * Vector3::right; } Vector3 Transform::GetUp() { return rotation * Vector3::up; } void Transform::SetDirty(bool inIsDirty) { isDirty = inIsDirty; } void MatrixToQuaternion(const Matrix3& kRot, Quaternion& q) { // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes // article "Quaternionf Calculus and Fast Animation". float fTrace = kRot.Get(0, 0) + kRot.Get(1, 1) + kRot.Get(2, 2); float fRoot; if (fTrace > 0.0f) { // |w| > 1/2, may as well choose w > 1/2 fRoot = std::sqrt(fTrace + 1.0f); // 2w q.w = 0.5f * fRoot; fRoot = 0.5f / fRoot; // 1/(4w) q.x = (kRot.Get(2, 1) - kRot.Get(1, 2)) * fRoot; q.y = (kRot.Get(0, 2) - kRot.Get(2, 0)) * fRoot; q.z = (kRot.Get(1, 0) - kRot.Get(0, 1)) * fRoot; } else { // |w| <= 1/2 int s_iNext[3] = { 1, 2, 0 }; int i = 0; if (kRot.Get(1, 1) > kRot.Get(0, 0)) i = 1; if (kRot.Get(2, 2) > kRot.Get(i, i)) i = 2; int j = s_iNext[i]; int k = s_iNext[j]; fRoot = std::sqrt(kRot.Get(i, i) - kRot.Get(j, j) - kRot.Get(k, k) + 1.0f); float* apkQuat[3] = { &q.x, &q.y, &q.z }; //Assert(fRoot >= Vector3f::epsilon); *apkQuat[i] = 0.5f * fRoot; fRoot = 0.5f / fRoot; q.w = (kRot.Get(k, j) - kRot.Get(j, k)) * fRoot; *apkQuat[j] = (kRot.Get(j, i) + kRot.Get(i, j)) * fRoot; *apkQuat[k] = (kRot.Get(k, i) + kRot.Get(i, k)) * fRoot; } q = Quaternion::Normalize(q); } bool LookRotationToQuaternion(const Vector3& viewVec, const Vector3& upVec, Quaternion* res) { Matrix3 m; if (!Matrix3::LookRotationToMatrix(viewVec, upVec, &m)) return false; MatrixToQuaternion(m, *res); return true; } void Transform :: LookAt(const Vector3& targetPosition, const Vector3& worldUp) { Vector3 forward = targetPosition - position; Quaternion q = Quaternion::identity; if (LookRotationToQuaternion(forward, worldUp, &q)) { rotation = q; isDirty = true; } else { //float mag = forward.magnitude(); //if (mag > Mathf::EPSILON) //{ // Matrix3 m; // m.SetFromToRotation(Vector3::zAxis, forward / mag); // MatrixToQuaternion(m, q); // rotation = q; // isDirty = true; //} } } Matrix4x4 Transform::FPSView(const Vector3& eye, Quaternion rotation) { Matrix4x4 rotMatrix = rotation.GetRotMatrix().transpose(); Vector3 x(rotMatrix[0], rotMatrix[4], rotMatrix[8]); Vector3 y(rotMatrix[1], rotMatrix[5], rotMatrix[9]); Vector3 z(-rotMatrix[2], -rotMatrix[6], -rotMatrix[10]); Matrix4x4 result; result[0] = x.x; result[4] = x.y; result[8] = x.z; result[12] = -Vector3::Dot(x, eye); result[1] = y.x; result[5] = y.y; result[9] = y.z; result[13] = -Vector3::Dot(y, eye); result[2] = z.x; result[6] = z.y; result[10] = z.z; result[14] = -Vector3::Dot(z, eye); result[3] = result[7] = result[11] = 0.0f; result[15] = 1.0f; return result; } Matrix4x4 Transform::Perspective(float fovy, float aspect, float zNear, float zFar) { float tanHalfFovy = tan(Mathf::Deg2Rad * fovy / 2); Matrix4x4 result(0.0f); result[0 * 4 + 0] = 1.0f / (aspect * tanHalfFovy); result[1 * 4 + 1] = 1.0f / (tanHalfFovy); result[2 * 4 + 3] = -1.0f; result[2 * 4 + 2] = -(zFar + zNear) / (zFar - zNear); result[3 * 4 + 2] = -(2.0f * zFar * zNear) / (zFar - zNear); return result; } Matrix4x4 Transform::Frustum(float l, float r, float b, float t, float zNear, float zFar) { Matrix4x4 result(0.0f); result[0] = 2 * zNear / (r - l); result[8] = (r + l) / (r - l); result[5] = 2 * zNear / (t - b); result[9] = (t + b) / (t - b); result[10] = -(zFar + zNear) / (zFar - zNear); result[14] = -(2 * zFar * zNear) / (zFar - zNear); result[11] = -1; result[15] = 0; return result; } Matrix4x4 Transform::OrthoFrustum(float l, float r, float b, float t, float zNear, float zFar) { Matrix4x4 result(0.0f); result[0] = 2 / (r - l); result[5] = 2 / (t - b); result[10] = -2 / (zFar - zNear); result[15] = 1; //result[12] = -(r + l) / (r - l); //result[13] = -(t + b) / (t - b); result[14] = -(zFar + zNear) / (zFar - zNear); return result; } Vector3 Transform::TranslateToNDC(const Vector4& clipVector) { float inveW = 1.0f / clipVector.w; return Vector3(clipVector.x * inveW, clipVector.y * inveW, clipVector.z * inveW); } void Transform::TranslateToScreenCoord(const int screenWidth, const int screenHeight, Vector3& ndcCoord) { int w = screenWidth; int h = screenHeight; ndcCoord.x = 0.5f * w + 0.5f *ndcCoord.x * w; ndcCoord.y = 0.5f * h + 0.5f *ndcCoord.y * h; } void Transform::Scale(const Vector3 &_scale) { scale = _scale; isDirty = true; } /* int Transform::CheckCvv(const Vector3& vec) { float w = v->w; int check = 0; if (v->z < 0.0f) check |= 1; if (v->z > w) check |= 2; if (v->x < -w) check |= 4; if (v->x > w) check |= 8; if (v->y < -w) check |= 16; if (v->y > w) check |= 32; return check; } */
22.320557
104
0.622697
SilangQuan
f1612d8dc9bb9598c66fb44659837df1b056c88a
17,620
hpp
C++
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
18
2015-02-12T04:41:22.000Z
2018-08-22T07:44:13.000Z
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
null
null
null
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
13
2015-05-24T12:24:46.000Z
2021-01-05T10:59:40.000Z
#ifndef __nark_fstring_hpp__ #define __nark_fstring_hpp__ #include <assert.h> #include <stddef.h> #include <string.h> #include <iterator> #include <string> #include <iosfwd> #include <utility> #include <algorithm> #include <string.h> #include "config.hpp" #include "stdtypes.hpp" #include "util/throw.hpp" #include "bits_rotate.hpp" //#include <boost/static_assert.hpp> #include <boost/utility/enable_if.hpp> namespace nark { #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__) #define HSM_FORCE_INLINE __attribute__((always_inline)) #elif defined(_MSC_VER) #define HSM_FORCE_INLINE __forceinline #else #define HSM_FORCE_INLINE inline #endif // Why name it SP_ALIGN? It is: String Pool/Pointer Align // // to disable align, define SP_ALIGN as 0 // otherwise, it will guess and use the best alignment #ifdef SP_ALIGN #if SP_ALIGN == 0 #undef SP_ALIGN #define SP_ALIGN 1 #endif #elif defined(NARK_WORD_BITS) #if 64 == NARK_WORD_BITS #define SP_ALIGN 8 #elif 32 == NARK_WORD_BITS #define SP_ALIGN 4 #else #error NARK_WORD_BITS is invalid #endif #else #error NARK_WORD_BITS is not defined #endif #if SP_ALIGN == 4 // typedef uint32_t align_type; typedef unsigned align_type; typedef size_t HSM_HashTp; #elif SP_ALIGN == 8 // typedef uint64_t align_type; typedef unsigned long long align_type; typedef unsigned long long HSM_HashTp; #elif SP_ALIGN == 1 typedef unsigned char align_type; typedef size_t HSM_HashTp; #else #error "SP_ALIGN defined but is not 0, 1, 4 or 8" #endif #if SP_ALIGN == 4 && UINT_MAX != 0xFFFFFFFF #error "sizeof(unsigned) must be 4" #elif SP_ALIGN == 8 && ULLONG_MAX != 0xFFFFFFFFFFFFFFFFull #error "sizeof(unsigned long long) must be 8" #endif BOOST_STATIC_ASSERT(sizeof(align_type) == SP_ALIGN); #if SP_ALIGN == 1 #define LOAD_OFFSET(x) size_t(x) #define SAVE_OFFSET(x) LinkTp(x) #define IF_SP_ALIGN(Then, Else) Else #else // on 64 bit system, make it to support larger strpool, up to 8*4G = 32G #define LOAD_OFFSET(x) (size_t(x) * SP_ALIGN) #define SAVE_OFFSET(x) LinkTp((x) / SP_ALIGN) #define IF_SP_ALIGN(Then, Else) Then #endif inline size_t nark_fstrlen(const char* s) { return strlen(s); } inline size_t nark_fstrlen(const uint16_t* s) { size_t n = 0; while (s[n]) ++n; return n; } #ifdef _MSC_VER NARK_DLL_EXPORT char* nark_fstrstr(const char* haystack, size_t haystack_len , const char* needle , size_t needle_len); #else inline char* nark_fstrstr(const char* haystack, size_t haystack_len , const char* needle , size_t needle_len) { return (char*)memmem(haystack, haystack_len, needle, needle_len); } #endif NARK_DLL_EXPORT uint16_t* nark_fstrstr(const uint16_t* haystack, size_t haystack_len , const uint16_t* needle , size_t needle_len); template<class Char> struct nark_get_uchar_type; template<>struct nark_get_uchar_type<char>{typedef unsigned char type;}; template<>struct nark_get_uchar_type<uint16_t>{typedef uint16_t type;}; // Fast String: shallow copy, simple, just has char* and length // May be short name of: Febird String template<class Char> struct basic_fstring { // BOOST_STATIC_ASSERT(sizeof(Char) <= 2); typedef std::basic_string<Char> std_string; const Char* p; ptrdiff_t n; basic_fstring() : p(NULL), n(0) {} basic_fstring(const std_string& x) : p(x.data()), n(x.size()) {} #ifdef NDEBUG // let compiler compute strlen(string literal) at compilation time basic_fstring(const Char* x) : p(x), n(nark_fstrlen(x)) {} #else basic_fstring(const Char* x) { assert(NULL != x); p = x; n = nark_fstrlen(x); } #endif basic_fstring(const Char* x, ptrdiff_t l) : p(x), n(l ) { assert(l >= 0); } basic_fstring(const Char* x, const Char* y) : p(x), n(y-x) { assert(y >= x); } #define fstring_enable_if_same_size(C) typename boost::enable_if_c<sizeof(C)==sizeof(Char)>::type* = NULL template<class C> basic_fstring(const C* x, fstring_enable_if_same_size(C)) { assert(NULL != x); p = (const Char*)x; n = nark_fstrlen((const Char*)x); } template<class C> basic_fstring(const C* x, ptrdiff_t l, fstring_enable_if_same_size(C)) : p((const Char*)x), n(l ) { assert(l >= 0); } template<class C> basic_fstring(const C* x, const C* y, fstring_enable_if_same_size(C)) : p((const Char*)x), n(y-x) { assert(y >= x); } #undef fstring_enable_if_same_size basic_fstring(const std::pair<Char*, Char*>& rng) : p(rng.first), n(rng.second - rng.first) { assert(n >= 0); } basic_fstring(const std::pair<const Char*, const Char*>& rng) : p(rng.first), n(rng.second - rng.first) { assert(n >= 0); } template<class CharVec> basic_fstring(const CharVec& chvec, typename CharVec::const_iterator** =NULL) { BOOST_STATIC_ASSERT(sizeof(*chvec.begin()) == sizeof(Char)); p = (const Char*)&*chvec.begin(); n = chvec.size(); #if !defined(NDEBUG) && 0 if (chvec.size() > 1) { assert(&chvec[0]+1 == &chvec[1]); assert(&chvec[0]+n-1 == &chvec[n-1]); } #endif } const std::pair<const Char*, const Char*> range() const { return std::make_pair(p, p+n); } typedef ptrdiff_t difference_type; typedef size_t size_type; typedef const Char value_type; typedef const Char &reference, &const_reference; typedef const Char *iterator, *const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator, const_reverse_iterator; typedef typename nark_get_uchar_type<Char>::type uc_t; iterator begin() const { return p; } iterator cbegin() const { return p; } iterator end() const { return p + n; } iterator cend() const { return p + n; } reverse_iterator rbegin() const { return reverse_iterator(p + n); } reverse_iterator crbegin() const { return reverse_iterator(p + n); } reverse_iterator rend() const { return reverse_iterator(p); } reverse_iterator crend() const { return reverse_iterator(p); } uc_t ende(ptrdiff_t off) const { assert(off <= n); assert(off >= 1); return p[n-off]; } std_string str() const { assert(0==n || (p && n) ); return std_string(p, n); } const Char* c_str() const { assert(p && '\0' == p[n]); return p; } const Char* data() const { return p; } const uc_t* udata() const { return (const uc_t*)p; } size_t size() const { return n; } int ilen() const { return (int)n; } // for printf: "%.*s" uc_t operator[](ptrdiff_t i)const{assert(i>=0);assert(i<n);assert(p);return p[i];} uc_t uch(ptrdiff_t i)const{assert(i>=0);assert(i<n);assert(p);return p[i];} bool empty() const { return 0 == n; } void chomp(); void trim(); basic_fstring substr(size_t pos, size_t len) const { assert(pos <= size()); assert(len <= size()); // if (pos > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd pos=%zd", size(), pos); // } if (pos + len > size()) len = size() - pos; return basic_fstring(p+pos, len); } basic_fstring substr(size_t pos) const { assert(pos <= size()); // if (pos > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd pos=%zd", size(), pos); // } return basic_fstring(p+pos, n-pos); } basic_fstring substrBegEnd(size_t Beg, size_t End) const { assert(Beg <= End); assert(End <= size()); // if (End > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd End=%zd", size(), End); // } return basic_fstring(p+Beg, End-Beg); } bool match_at(ptrdiff_t pos, Char ch) const { assert(pos >= 0); assert(pos <= n); return pos < n && p[pos] == ch; } bool match_at(ptrdiff_t pos, basic_fstring needle) const { assert(pos >= 0); assert(pos <= n); if (pos + needle.n > n) return false; return memcmp(p + pos, needle.p, sizeof(Char) * needle.size()) == 0; } const Char* strstr(basic_fstring needle) const { assert(needle.n > 0); return this->strstr(0, needle); } const Char* strstr(ptrdiff_t pos, basic_fstring needle) const { assert(pos >= 0); assert(pos <= n); assert(needle.n > 0); if (pos + needle.n > n) return NULL; return nark_fstrstr(p, n, needle.p, needle.n); } bool startsWith(basic_fstring x) const { assert(x.n > 0); if (x.n > n) return false; return memcmp(p, x.p, sizeof(Char)*x.n) == 0; } bool endsWith(basic_fstring x) const { assert(x.n > 0); if (x.n > n) return false; return memcmp(p+n - x.n, x.p, sizeof(Char)*x.n) == 0; } size_t commonPrefixLen(basic_fstring y) const { size_t minlen = n < y.n ? n : y.n; for (size_t i = 0; i < minlen; ++i) if (p[i] != y.p[i]) return i; return minlen; } template<class Vec> size_t split(const Char delim, Vec* F, size_t max_fields = ~size_t(0)) const { // assert(n >= 0); F->resize(0); if (' ' == delim) { // same as awk, skip first blank field, and skip dup blanks const Char *col = p, *End = p + n; while (col < End && isspace((unsigned char)(*col))) ++col; // skip first blank field while (col < End && F->size()+1 < max_fields) { const Char* next = col; while (next < End && !isspace((unsigned char)(*next))) ++next; F->push_back(typename Vec::value_type(col, next)); while (next < End && isspace(*next)) ++next; // skip blanks col = next; } if (col < End) F->push_back(typename Vec::value_type(col, End)); } else { const Char *col = p, *End = p + n; while (col <= End && F->size()+1 < max_fields) { const Char* next = col; while (next < End && delim != *next) ++next; F->push_back(typename Vec::value_type(col, next)); col = next + 1; } if (col <= End) F->push_back(typename Vec::value_type(col, End)); } return F->size(); } /// split into fields template<class Vec> size_t split(const Char* delims, Vec* F, size_t max_fields = ~size_t(0)) { assert(n >= 0); size_t dlen = nark_fstrlen(delims); if (0 == dlen) // empty delims redirect to blank delim return split(' ', F); if (1 == dlen) return split(delims[0], F); F->resize(0); const Char *col = p, *End = p + n; while (col <= End && F->size()+1 < max_fields) { const Char* next = nark_fstrstr(col, End-col, delims, dlen); if (NULL == next) next = End; F->push_back(typename Vec::value_type(col, next)); col = next + dlen; } if (col <= End) F->push_back(typename Vec::value_type(col, End)); return F->size(); } }; template<class DataIO, class Char> void DataIO_saveObject(DataIO& dio, basic_fstring<Char> s) { dio << typename DataIO::my_var_uint64_t(s.n); dio.ensureWrite(s.p, sizeof(Char) * s.n); } typedef basic_fstring<char> fstring; typedef basic_fstring<uint16_t> fstring16; template<class Char> struct char_to_fstring; template<> struct char_to_fstring<char> { typedef fstring type; }; template<> struct char_to_fstring<unsigned char> { typedef fstring type; }; template<> struct char_to_fstring<uint16_t> { typedef fstring16 type; }; NARK_DLL_EXPORT std::string operator+(fstring x, fstring y); inline std::string operator+(fstring x, const char* y) {return x+fstring(y);} inline std::string operator+(const char* x, fstring y) {return fstring(x)+y;} #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L inline std::string operator+(std::string&& x, fstring y) { return x.append( y.p, y.n); } inline std::string operator+(fstring x, std::string&& y) { return y.insert(0, x.p, x.n); } #endif NARK_DLL_EXPORT bool operator==(fstring x, fstring y); NARK_DLL_EXPORT bool operator!=(fstring x, fstring y); NARK_DLL_EXPORT bool operator<(fstring x, fstring y); NARK_DLL_EXPORT bool operator>(fstring x, fstring y); NARK_DLL_EXPORT bool operator<=(fstring x, fstring y); NARK_DLL_EXPORT bool operator>=(fstring x, fstring y); NARK_DLL_EXPORT std::ostream& operator<<(std::ostream& os, fstring s); // fstring16 NARK_DLL_EXPORT bool operator==(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator!=(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator<(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator>(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator<=(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator>=(fstring16 x, fstring16 y); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// struct fstring_func { // 3-way compare class prefix_compare3 { ptrdiff_t plen; public: int operator()(fstring x, fstring y) const { using namespace std; const ptrdiff_t lmin = min(x.n, y.n); const ptrdiff_t clen = min(lmin, plen); for (ptrdiff_t i = 0; i < clen; ++i) if (x.p[i] != y.p[i]) // char diff doesn't exceed INT_MAX return (unsigned char)x.p[i] - (unsigned char)y.p[i]; if (plen < lmin) return 0; // all prefix are same else return int(x.n - y.n); // length diff couldn't exceed INT_MAX } prefix_compare3(ptrdiff_t prelen) : plen(prelen) {} }; // 3-way compare class compare3 { public: int operator()(fstring x, fstring y) const { using namespace std; int ret = memcmp(x.p, y.p, min(x.n, y.n)); if (ret != 0) return ret; return int(x.n - y.n); // length diff couldn't exceed INT_MAX } }; struct less_unalign { bool operator()(const fstring& x, const fstring& y) const { int ret = memcmp(x.p, y.p, x.n < y.n ? x.n : y.n); if (ret != 0) return ret < 0; else return x.n < y.n; } }; struct hash_unalign { HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { HSM_HashTp h = 2134173 + k.n * 31; for (ptrdiff_t i = 0; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; struct equal_unalign { bool operator()(const fstring x, const fstring y) const { return x.n == y.n && memcmp(x.p, y.p, x.n) == 0; } }; static size_t align_to(size_t x) { return (x + SP_ALIGN-1) & ~(intptr_t)(SP_ALIGN-1); } #if SP_ALIGN != 1 struct less_align { HSM_FORCE_INLINE bool operator()(const fstring& x, const fstring& y) const { ptrdiff_t n = x.n < y.n ? x.n : y.n; ptrdiff_t c = n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) break; for (; i < n; ++i) if (x.p[i] != y.p[i]) return (unsigned char)x.p[i] < (unsigned char)y.p[i]; return x.n < y.n; } }; struct Less { HSM_FORCE_INLINE bool operator()(const fstring& x, const fstring& y) const { if (((intptr_t(x.p) | intptr_t(y.p)) & (SP_ALIGN-1)) == 0) return less_align()(x, y); else return less_unalign()(x, y); } }; struct hash_align { HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { BOOST_STATIC_ASSERT(SP_ALIGN <= sizeof(HSM_HashTp)); HSM_HashTp h = 2134173 + k.n * 31; ptrdiff_t c = k.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) h = BitsRotateLeft(h, 5) + h + *reinterpret_cast<const align_type*>(k.p + i); for (; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; // make it easier to enable or disable X86 judgment #if 1 && ( \ defined(__i386__) || defined(__i386) || defined(_M_IX86) || \ defined(__X86__) || defined(_X86_) || \ defined(__THW_INTEL__) || defined(__I86__) || \ defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) \ ) // don't care pointer align, overhead of x86 align fault is slightly enough typedef hash_align hash; #else struct hash { // align or not align HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { HSM_HashTp h = 2134173 + k.n * 31; ptrdiff_t c = k.n - (SP_ALIGN-1); ptrdiff_t i = 0; if ((intptr_t(k.p) & (SP_ALIGN-1)) == 0) { // aligned for (; i < c; i += SP_ALIGN) h = BitsRotateLeft(h, 5) + h + *reinterpret_cast<const align_type*>(k.p + i); } else { // not aligned for (; i < c; i += SP_ALIGN) { align_type word; // compiler could generate unaligned load instruction // for fixed size(SP_ALIGN) object, word may be a register memcpy(&word, k.p + i, SP_ALIGN); h = BitsRotateLeft(h, 5) + h + word; } } for (; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; #endif // X86 struct equal_align { HSM_FORCE_INLINE bool operator()(const fstring x, const fstring y) const { if (nark_unlikely(x.n != y.n)) return false; ptrdiff_t c = x.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) return false; for (; i < x.n; ++i) if (x.p[i] != y.p[i]) return false; return true; } }; struct equal { // align or not align HSM_FORCE_INLINE bool operator()(const fstring x, const fstring y) const { if (nark_unlikely(x.n != y.n)) return false; if (((intptr_t(x.p) | intptr_t(y.p)) & (SP_ALIGN-1)) == 0) { ptrdiff_t c = x.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) return false; for (; i < x.n; ++i) if (x.p[i] != y.p[i]) return false; return true; } else return memcmp(x.p, y.p, x.n) == 0; } }; #else typedef less_unalign less_align; typedef hash_unalign hash_align; typedef equal_unalign equal_align; typedef less_unalign Less; typedef hash_unalign hash; typedef equal_unalign equal; #endif // SP_ALIGN }; NARK_DLL_EXPORT extern unsigned char gtab_ascii_tolower[256]; NARK_DLL_EXPORT extern unsigned char gtab_ascii_tolower[256]; } // namespace nark #endif // __nark_fstring_hpp__
31.862568
153
0.651305
rockeet
f162a01105bc84fa0207b807e0fcaf2c1502226c
4,019
cpp
C++
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
nagestx/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
3
2018-12-15T14:07:12.000Z
2020-07-19T23:18:09.000Z
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
// Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. // // Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. // // Example:  // // // You may serialize the following tree: // // 1 // / \ // 2 3 // / \ // 4 5 // // as "[1,2,3,null,null,4,5]" // // // Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. // // Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. // class Codec { private: int str2int(string str){ int res = 0; if(str[0] == '-'){ for(int i = 1; i < str.size(); ++ i){ res = 10 * res + (str[i] - '0'); } res *= -1; }else{ for(int i = 0; i < str.size(); ++ i){ res = 10 * res + (str[i] - '0'); } } return res; } vector<string> split(string &str, char ch){ vector<string> res; string tmp; for(auto &s: str){ if(s != ch){ tmp += s; }else{ res.push_back(tmp); tmp.clear(); } } if(!tmp.empty()) res.push_back(tmp); return res; } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string null = "null"; if(!root) return "[" + null + "]"; string res; vector<string> r; queue<TreeNode*> que; que.push(root); while(!que.empty()){ queue<TreeNode*> p; while(!que.empty()){ auto top = que.front(); que.pop(); if(top){ r.push_back(to_string(top->val)); p.push(top->left); p.push(top->right); }else{ r.push_back(null); } } while(!p.empty()){ que.push(p.front()); p.pop(); } } res += "["; for(int i = 0; i < r.size(); ++ i){ res += r[i]; if(i < r.size() - 1) res += ","; } res += "]"; return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data.empty() || data == "[null]") return nullptr; string str(data.begin() + 1, data.end() - 1); auto arr = split(str, ','); size_t size = arr.size(); TreeNode * root = new TreeNode(str2int(arr[0])); queue<TreeNode*> que; que.push(root); for(size_t i = 1; i < size;){ auto top = que.front(); que.pop(); if(top){ if(arr[i] != "null") top->left = new TreeNode(str2int(arr[i])); else top->left = nullptr; ++ i; if(i < size){ if(arr[i] != "null") top->right = new TreeNode(str2int(arr[i])); else top->right = nullptr; ++ i; } if(top->left) que.push(top->left); if(top->right) que.push(top->right); } } return root; } };
30.679389
297
0.458821
nagestx
f162ca37067f2ed70fb29fca4a46cc97b00e010d
771
cpp
C++
Vijos/1011.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Vijos/1011.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Vijos/1011.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <stdio.h> int i, j, n, m, ma; int a[1005][1005], f[1005][1005]; int max(int a, int b) { if (a > b) return a; else return b; } int dfs(int x, int y) { if (f[x][y] != -1) return f[x][y]; f[x][y] = 0; if (a[x - 1][y] > a[x][y]) f[x][y] = max(f[x][y], dfs(x - 1, y)); if (a[x + 1][y] > a[x][y]) f[x][y] = max(f[x][y], dfs(x + 1, y)); if (a[x][y - 1] > a[x][y]) f[x][y] = max(f[x][y], dfs(x, y - 1)); if (a[x][y + 1] > a[x][y]) f[x][y] = max(f[x][y], dfs(x, y + 1)); f[x][y]++; return f[x][y]; } int main() { scanf("%d %d", &n, &m); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { scanf("%d", &a[i][j]); f[i][j] = -1; } for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) ma = max(ma, dfs(i, j)); printf("%d\n", ma); return 0; }
19.769231
66
0.402075
HeRaNO
f166887dde80662470403f8f73282e67f8e6fc23
953
cpp
C++
client/src/main/game/guns/rocket_launcher.cpp
JulianBiancardi/Wolfenstein-Taller1
28e72ce8438264919586785aa09ce9b0a5de222b
[ "MIT" ]
1
2021-04-23T19:57:40.000Z
2021-04-23T19:57:40.000Z
client/src/main/game/guns/rocket_launcher.cpp
JulianBiancardi/Wolfenstein-Taller1
28e72ce8438264919586785aa09ce9b0a5de222b
[ "MIT" ]
null
null
null
client/src/main/game/guns/rocket_launcher.cpp
JulianBiancardi/Wolfenstein-Taller1
28e72ce8438264919586785aa09ce9b0a5de222b
[ "MIT" ]
null
null
null
#include "rocket_launcher.h" #include "../../../../../common/src/main/ids/gun_ids.h" Hit RocketLauncher::shoot( Object& player, BaseMap& map, std::vector<std::weak_ptr<IdentifiableObject>>& players) { return std::move(Hit(ROCKET_LAUNCHER_ID, 0, 0, true)); } RocketLauncher::RocketLauncher(unsigned int resource_id) : Gun(0, 0, resource_id) {} RocketLauncher::~RocketLauncher() {} Hit RocketLauncher::update( Object& player, bool trigger, BaseMap& map, std::vector<std::weak_ptr<IdentifiableObject>>& players) { if (!trigger) { shot = false; state.update(false); return std::move(Hit(ROCKET_LAUNCHER_ID, 0, 0, false)); } if (shot) { state.update(false); return std::move(Hit(ROCKET_LAUNCHER_ID, 0, 0, false)); } shot = true; state.update(true); return std::move(shoot(player, map, players)); } SDL_Rect* RocketLauncher::get_slice(void* extra) { state.set_slice(slice); return &slice; }
24.435897
62
0.674711
JulianBiancardi
f166915e6aac8affdffeb774bf0270bd2edcbbfb
111
cpp
C++
command/src/light_on_command.cpp
hexu1985/design_pattern
f03963ef1a478763f87f37de1f5e9f18f0b0b988
[ "MIT" ]
null
null
null
command/src/light_on_command.cpp
hexu1985/design_pattern
f03963ef1a478763f87f37de1f5e9f18f0b0b988
[ "MIT" ]
null
null
null
command/src/light_on_command.cpp
hexu1985/design_pattern
f03963ef1a478763f87f37de1f5e9f18f0b0b988
[ "MIT" ]
1
2019-12-03T08:44:11.000Z
2019-12-03T08:44:11.000Z
#include "light_source.h" #include "light_on_command.h" void LightOnCommand::execute() { light->on(); }
12.333333
31
0.684685
hexu1985
f16d41e4d89e0b34a2a6424646cfe4b73a80f668
1,066
cpp
C++
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
/** * @file test.feature.cpp * @author Team Rogue++ * @date December 08, 2016 * * @brief Member definitions for the FeatureTest class */ #include <exception> #include <iostream> #include <string> #include <vector> #include "include/feature.h" #include "test.testable.h" /** * @brief Tests the Feature class. */ class FeatureTest : public Testable { public: FeatureTest(){} void test(){ comment("Commencing Feature tests..."); try { Feature feature = Feature('~', Coord(0,0), false, TCODColor::white); assert(true, "Created Feature"); } catch (const std::exception& e) { assert(false, "Failure creating Feature"); } Feature feature = Feature('~', Coord(0,0), false, TCODColor::white); assert(feature.getSymbol() == '~', "Feature Symbol Check"); assert(!feature.getVisible(), "Feature Visible Check"); feature.setVisible(true); assert(feature.getVisible(), "Feature Visible Check"); assert(feature.getLocation() == Coord(0,0), "Feature Location Check"); comment("Finished Feature tests."); } };
24.227273
73
0.659475
prinsij
f16ec3dc35ce3fb4a90566bce1bbd9d355b2f750
9,392
cpp
C++
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#include "../thirdparty/catch2/catch.hpp" #include <iostream> #include "../elona/spec.hpp" using namespace std::literals::string_literals; using namespace elona; class TestSpec : public spec::Object { public: TestSpec() : spec::Object("test") { } }; namespace { TestSpec load(const std::string& str) { TestSpec def; std::stringstream ss(str); REQUIRE_NOTHROW(def.load(ss, "spec_test.hcl", "spec_test")); return def; } bool load_fails(const std::string& str) { TestSpec def; std::stringstream ss(str); try { def.load(ss, "spec_test.hcl", "spec_test"); } catch (...) { return true; } return false; } } // namespace TEST_CASE("Test invalid spec format", "[Spec: Definition]") { REQUIRE(load_fails(R"( blah = 4 )")); } TEST_CASE("Test invalid spec object name", "[Spec: Definition]") { REQUIRE(load_fails(R"( config {} )")); } TEST_CASE("Test loading blank spec", "[Spec: Definition]") { REQUIRE_FALSE(load_fails(R"( test {} )")); } TEST_CASE("testining boolean config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = true } )"); REQUIRE(def.is<spec::BoolDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<bool>()); REQUIRE(def.get_default("spec_test.foo").as<bool>() == true); } TEST_CASE("testining integer config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = 42 min = 0 max = 0 } } )"); REQUIRE(def.is<spec::IntDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<int>()); REQUIRE(def.get_default("spec_test.foo").as<int>() == 42); } TEST_CASE("testining bare integer", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 } )")); } TEST_CASE("testining integer without min", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 max = 100 } )")); } TEST_CASE("testining integer without max", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 min = 0 } )")); } TEST_CASE("testining string config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = "bar" } )"); REQUIRE(def.is<spec::StringDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "bar"); } TEST_CASE("testining list config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = ["bar", "baz", "quux"] } )"); REQUIRE(def.is<spec::ListDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<hcl::List>()); auto list = def.get_default("spec_test.foo").as<hcl::List>(); REQUIRE(list.at(0).as<std::string>() == "bar"); REQUIRE(list.at(1).as<std::string>() == "baz"); REQUIRE(list.at(2).as<std::string>() == "quux"); } TEST_CASE("testining enum config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } } )"); REQUIRE(def.is<spec::EnumDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "baz"); } TEST_CASE("Test not providing enum variants", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" default = "baz" } } )")); } TEST_CASE("Test not providing enum default", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] } } )")); } TEST_CASE("Test providing non-existent enum default", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "hoge" } } )")); } TEST_CASE("Test providing non-string enum variant", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", 42] default = "bar" } } )")); } TEST_CASE( "Test providing non-string default value in enum", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = 42 } } )")); } TEST_CASE("Test providing non-list variants in enum", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = 42 default = "foo" } } )")); } TEST_CASE("testining runtime enum config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "runtime_enum" } bar = "baz" } )"); REQUIRE(def.is<spec::EnumDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE( def.get_default("spec_test.foo").as<std::string>() == "__unknown__"); REQUIRE(def.get_variants("spec_test.foo").size() == 1); REQUIRE_NOTHROW( def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "baz")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "baz"); auto variants = def.get_variants("spec_test.foo"); REQUIRE(variants.size() == 4); REQUIRE(variants.at(0) == "__unknown__"); REQUIRE(variants.at(1) == "foo"); REQUIRE(variants.at(2) == "bar"); REQUIRE(variants.at(3) == "baz"); REQUIRE_THROWS( def.inject_enum("spec_test.bar", {"foo", "bar", "baz"}, "bar")); } TEST_CASE( "Test providing invalid default index in injected enum", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "runtime_enum" } } )"); REQUIRE_THROWS( def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "asdfg")); REQUIRE_THROWS(def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "")); } TEST_CASE("Test error when injecting non-runtime enum", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["foo", "bar", "baz"] default = "bar" } } )"); REQUIRE_THROWS(def.inject_enum("spec_test.foo", {"quux"}, "quux")); } TEST_CASE("testining config section", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "section" options = { bar = false baz = "quux" } } } )"); REQUIRE_THROWS(def.get_default("spec_test.foo")); } TEST_CASE("testining config section with no options", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "section" } } )")); } TEST_CASE("testining config section with invalid options", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "section" options = "foo" } } )")); } TEST_CASE("testining invalid type", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "bar" default = 42 } } )")); } TEST_CASE("Test get_variants", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } hoge = "piyo" } )"); auto variants = def.get_variants("spec_test.foo"); REQUIRE(variants.size() == 3); REQUIRE(variants.at(0) == "bar"); REQUIRE(variants.at(1) == "baz"); REQUIRE(variants.at(2) == "quux"); REQUIRE_THROWS(def.get_variants("spec_test.hoge")); } TEST_CASE("Test get_children", "[Spec: Definition]") { TestSpec def = load(R"( test { foo { type = "section" options = { bar = false baz = "quux" hoge = "fuga" piyo = true } } } )"); auto children = def.get_children("spec_test.foo"); REQUIRE(children.size() == 4); REQUIRE(children.at(0) == "bar"); REQUIRE(children.at(1) == "baz"); REQUIRE(children.at(2) == "hoge"); REQUIRE(children.at(3) == "piyo"); REQUIRE_THROWS(def.get_children("spec_test.hoge")); } TEST_CASE("Test get_max/get_min (integer)", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = 42 min = 0 max = 100 } hoge = "piyo" } )"); REQUIRE(def.get_min("spec_test.foo") == 0); REQUIRE(def.get_max("spec_test.foo") == 100); REQUIRE_THROWS(def.get_min("spec_test.hoge")); REQUIRE_THROWS(def.get_max("spec_test.hoge")); } TEST_CASE("Test get_max/get_min (enum)", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } } )"); REQUIRE(def.get_min("spec_test.foo") == 0); REQUIRE(def.get_max("spec_test.foo") == 2); } TEST_CASE("testinition with extended syntax", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = "bar" } } )"); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "bar"); } TEST_CASE("Test exists", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = "bar" } )"); REQUIRE(def.exists("spec_test.foo") == true); REQUIRE(def.exists("spec_test.baz") == false); }
19.689727
80
0.569101
XrosFade
f16eca469e5ae8883211bc620ed2a8b9a7695c73
2,530
cpp
C++
implicitsurfacegenerator.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
implicitsurfacegenerator.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
implicitsurfacegenerator.cpp
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
#include "implicitsurfacegenerator.h" namespace imt{ namespace volume{ ImplicitFunction::ImplicitFunction() { } short ImplicitFunction::value(int x, int y, int z) { int coeff = 1; mWidth = 512 * coeff; mHeight = 512 * coeff; mDepth = 512 * coeff; int center = mWidth / 2; int r = (128 + 64 + 32) * coeff, r1 = 64 * coeff, r2 = 64 * coeff; short v = 0; if (z > mDepth - 20 * coeff || z < 20 * coeff) { return v; } int val = 0 ; int iso = 5000; float x1 = 128 * coeff, y1 = 256 * coeff, x2 = (256 + 128) * coeff, y2 = 256 * coeff; Eigen::Vector2f centerPoint(256 * coeff, 256 * coeff); Eigen::Vector2f centerPoint1(x1, y1), centerPoint2(x2, y2); Eigen::Vector2f pt( x , y ); float d = (centerPoint - pt).norm(); float d1 = (centerPoint1 - centerPoint).norm() - r1; float d2 = (centerPoint1 - pt).norm(); float d3 = (centerPoint2 - pt).norm(); float rd = (d1 + 2 * r1 + +r) / 2; if ( d <= d1 && d2 < r1 ) { val = iso + 4 * (d1 - d); } else if ( d2 > r1 && d3 > r1 && d < rd ) { val = iso + 4 * std::min( d2 , d3 ); } else if ( d >= rd && d <= r ) { val = iso + 4 * (r - d); } else { val = 0; } v = val; return v; } Eigen::Vector3f ImplicitFunction::getNormal( const Eigen::Vector3f& point ) { Eigen::Vector3f n; float x1 = 128, y1 = 256, x2 = 256 + 128, y2 = 256; Eigen::Vector2f centerPoint(256, 256); Eigen::Vector2f centerPoint1(x1, y1), centerPoint2(x2, y2); float zDiff1 = std::abs( point.z() - mDepth + 20 ); float zDiff2 = std::abs( point.z() - 20 ); Eigen::Vector2f pt(point(0), point(1)); int r = 128 + 64 + 32, r1 = 64, r2 = 64; float d = (centerPoint - pt).norm(); float d1 = (centerPoint1 - centerPoint).norm() - r1; float d2 = (centerPoint1 - pt).norm(); float d3 = (centerPoint2 - pt).norm(); if ( zDiff1 < 2 || zDiff1 < 2 ) { } return n; } short ImplicitFunction::isoValue() { short iv = 0; return iv; } ImplicitSurfaceGenerator::ImplicitSurfaceGenerator() { } void ImplicitSurfaceGenerator::setImplicitFunction( ImplicitFunction *imf ) { mImplicitFunction = imf; } void ImplicitSurfaceGenerator::generate( int sizeX, int sizeY, int sizeZ ) { ImplicitFunction imf; } void ImplicitSurfaceGenerator::getSurface( std::vector< Eigen::Vector3f >& vertices, std::vector< unsigned int >& indices ) { } } }
16.535948
124
0.559684
avinfinity
f170413e9e63a0f8a01a12645f5ba620ebfe83b1
1,314
cpp
C++
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <image_transport/image_transport.h> //package.xml에 추가. 이미지데이터를 받고 보내기위해 사용. #include <cv_bridge/cv_bridge.h> //package.xml에 추가 #include <sensor_msgs/image_encodings.h> //package.xml에 추가. cv_bridge::CvImagePtr에 값을 대입하기 위한 인자로 사용된다. #include <opencv2/imgproc/imgproc.hpp> //OpenCV's image processing를 사용하기위해 필요하다. #include <opencv2/highgui/highgui.hpp> //OpenCV's GUI modules를 사용하기위해 필요하다. (cv::namedWindow(OPENCV_WINDOW);) int count=1; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; cv_bridge::CvImagePtr cv_ptr; cv::Mat img; public: ImageConverter(): it_(nh_) //it_에 nh_을 대입한다. { image_sub_ = it_.subscribe("/camera/color/image_raw", 1, &ImageConverter::imageCb, this); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); img=cv_ptr->image; char buff[256]; sprintf(buff,"/home/sdg/catkin_ws/src/make_training_set/dataset/num%d.jpg",count); cv::imwrite(buff,img); count++; } }; int main(int argc, char** argv) { ros::init(argc, argv, "make_training_set"); ImageConverter ic; ros::spin(); return 0; }
30.55814
115
0.681887
songdaegeun
f170d78ec28855bde965adc8dc4814a4c46fd7bc
1,497
cpp
C++
Exercise_4/4.8_PowerFunctionOverloading.cpp
YJDave/balagurusamy_solution_cpp
cc528dd99a1517706e9ee6560593e3c37251e443
[ "MIT" ]
21
2017-12-11T07:24:57.000Z
2022-03-17T08:43:24.000Z
Exercise_4/4.8_PowerFunctionOverloading.cpp
YJDave/balagurusamy_solution_cpp
cc528dd99a1517706e9ee6560593e3c37251e443
[ "MIT" ]
4
2017-12-12T16:36:46.000Z
2020-06-21T22:54:18.000Z
Exercise_4/4.8_PowerFunctionOverloading.cpp
YJDave/balagurusamy_solution_cpp
cc528dd99a1517706e9ee6560593e3c37251e443
[ "MIT" ]
19
2017-09-23T13:50:25.000Z
2021-11-16T08:20:19.000Z
/* */ #ifdef _WIN32 #include<iostream.h> #include<cmath.h> #endif #ifdef linux #include<iostream> #include<cmath> #endif #include<stdio.h> using std::cout; using std::cin; //method to perform power function using recursive formula //double m-first method double power(double m,int n=2) { //base condition for recursion if (n<0) n=0-n; if (n==0) return 1; //recursion //changed m = m*power(m,n-1); return m; } //same method but type of argument is different //int m-second method double power(int m,int n=2) { //base condition for recursion if (n<0) n=0-n; if (n==0) return 1; //recursion //changed m = m*power(m,n-1); return m; } int main() { //m1 double value and m2 int value to implement both function int n; double m,ans1,ans2; cout<<"\nEnter the value : "; cin>>m; cout<<"Enter the power of this value : "; cin>>n; //method overloading ans1 = power(m,n); //calling first method ans2 = power((int)m,n); //calling second method if (n<0) ans2 = 1/ans2; //Changed cout<<"\nCalling function 1(double m): "<<m<<" ^ "<<n<<" = "; printf("%.8f",ans1); cout<<"\n\nCalling function 2(int m): "<<m<<" ^ "<<n<<" = "<<ans2; return 0; } //suppose user have entered 3.23288 for value of m //then first function will give more accurate answer than second function //because second function takes int argument which convert 3.23288 into 3
20.506849
73
0.606546
YJDave
f171b6e634745ebb61d3cfff2dc827bd659f13bf
2,099
cc
C++
caffe2/sgd/lars_op.cc
chocjy/caffe2
1a6cef392495d969d135945d6749e6b99b37d4d9
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/sgd/lars_op.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
23
2015-08-30T11:54:51.000Z
2017-03-06T03:01:07.000Z
caffe2/sgd/lars_op.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "caffe2/sgd/lars_op.h" #include <math.h> #include "caffe2/utils/math.h" namespace caffe2 { template <> void LarsOp<float, CPUContext>::Compute( TIndex N, const float* X_data, const float* dX_data, float offset, float* lr_rescale_data) { *lr_rescale_data = 1.0; float X_norm = sqrtf((ConstEigenVectorMap<float>(X_data, N).array()).square().sum()); if (X_norm > 0) { float dX_norm = sqrtf((ConstEigenVectorMap<float>(dX_data, N).array()).square().sum()); *lr_rescale_data /= (dX_norm / X_norm + offset); } } REGISTER_CPU_OPERATOR(Lars, LarsOp<float, CPUContext>); OPERATOR_SCHEMA(Lars) .NumInputs(2) .NumOutputs(1) .SetDoc(R"DOC( Implement Layer-wise Adaptive Rate Scaling (LARS) as in https://arxiv.org/abs/1708.03888. Without weight decay, given a global learning rate lr, parameter tensor X and its gradient dX, the local learning rate for X will be local_lr = lr * norm(X) / ( norm(dX) + offset * norm(X) ) = lr / ( norm(dX) / norm(X) + offset ), where offset is a preset hyper-parameter to avoid numerical issue. In this implementation, we uses l2 norm and output the rescaling factor 1 / ( norm(dX) / norm(X) + offset ). )DOC") .Input(0, "X", "Parameter tensor") .Input(1, "dX", "Gradient tensor") .Output(0, "lr_rescale", "Local learning rate rescaling factor") .Arg("offset", "rescaling offset parameter"); SHOULD_NOT_DO_GRADIENT(Lars); } // namespace caffe2
29.985714
79
0.686994
chocjy
f1782813f62c67f347d3e33e2359d3ddb33a8a8d
11,504
cpp
C++
runtime/vm/vm/sys_runtime.cpp
fanx-dev/fanx
902128c44b4b5c236a8b0a49986569097c7ca0aa
[ "AFL-3.0" ]
146
2019-03-18T14:09:46.000Z
2022-01-22T21:58:22.000Z
runtime/vm/vm/sys_runtime.cpp
chunquedong/FanCore
4d5dfb06f4c7d0fe0272c4238529e42950531d3b
[ "AFL-3.0" ]
11
2019-11-27T19:00:22.000Z
2022-03-24T02:15:46.000Z
runtime/vm/vm/sys_runtime.cpp
chunquedong/FanCore
4d5dfb06f4c7d0fe0272c4238529e42950531d3b
[ "AFL-3.0" ]
12
2019-06-03T05:06:49.000Z
2021-09-09T05:59:30.000Z
// // ObjFactory.cpp // vm // // Created by yangjiandong on 15/10/4. // Copyright (c) 2015, yangjiandong. All rights reserved. // #include "sys_runtime.h" #include "Env.h" //#include "StackFrame.h" #ifdef __cplusplus extern "C" { #endif //////////////////////////////////////////////////////////////// // Alloc //////////////////////////////////////////////////////////////// FObj* fr_allocObj_(Env* env, FType* type, int size) { if (!type) { printf("WAIN: allocObj with null type"); return NULL; } FType* ftype = type; env->podManager->initTypeAllocSize(env, ftype); if (ftype->c_allocSize > size) { size = ftype->c_allocSize; } GcObj* obj = (GcObj*)env->vm->gc->alloc(ftype, size + sizeof(struct GcObj_)); //env->printStackTrace(); printf("\n"); return fr_fromGcObj(obj); } //////////////////////////////////////////////////////////////// // Error //////////////////////////////////////////////////////////////// FObj* fr_makeNPE_(Env *env) { FObj* str = fr_newStrUtf8_(env, "null pointer"); fr_TagValue entry; entry.any.o = str; entry.type = fr_vtObj; env->push(&entry); entry.any.o = 0; env->push(&entry); FType* type = env->podManager->getNpeType(env); //FMethod *ctor = type->c_methodMap["make"]; auto itr = type->c_methodMap.find("make"); if (itr == type->c_methodMap.end()) { abort(); } FMethod* ctor = itr->second; env->newObj(type, ctor, 2); fr_TagValue error = *env->peek(); return (FObj*)error.any.o; } FObj* fr_makeErr_(Env* env, const char* podName, const char* typeName, const char* msg) { FObj* str = fr_newStrUtf8_(env, msg); fr_TagValue entry; entry.any.o = str; entry.type = fr_vtObj; env->push(&entry); entry.any.o = 0; env->push(&entry); env->newObjByName(podName, typeName, "make", 2); fr_TagValue error = *env->peek(); return (FObj*)error.any.o; } FObj* fr_makeCastError_(Env* env) { return fr_makeErr_(env, "sys", "CastErr", ""); } FObj* fr_makeIndexError_(Env* env, fr_Int index, fr_Int limit) { char buf[128] = { 0 }; snprintf(buf, 128, "index (%d) out of bounds (%d)", (int)index, (int)limit); return fr_makeErr_(env, "sys", "CastErr", buf); } void fr_printError_(Env* env, FObj * err) { FType* ftype = fr_getFType((fr_Env)env, err); std::string& name = ftype->c_name; printf("uncatch error: %s\n", name.c_str()); FMethod* method = env->podManager->findMethod(env, "sys", "Err", "trace", 0); fr_TagValue val; val.any.o = err; val.type = fr_vtObj; env->push(&val); env->callVirtual(method, 0); env->pop(&val); } //////////////////////////////////////////////////////////////// // Other //////////////////////////////////////////////////////////////// fr_Array* fr_arrayNew_(Env *env, FType* elemType, int32_t elemSize, size_t size) { if (size > INT32_MAX) { fr_throwNew((fr_Env)env, "sys", "ArgErr", "alloc size < 0"); return NULL; } if (elemSize <= 0) elemSize = sizeof(void*); FType* arrayType = env->findType("sys", "Array"); size_t allocSize = sizeof(fr_Array) + (elemSize * (size + 1)); fr_Array* a = (fr_Array*)fr_allocObj_(env, arrayType, (int)allocSize); a->elemType = fr_fromFType((fr_Env)env, elemType); a->elemSize = elemSize; a->valueType = env->podManager->getValueTypeByType(env, elemType); a->size = size; return a; } //////////////////////////////////////////////////////////////// // String //////////////////////////////////////////////////////////////// FObj * fr_newStrUtf8N_(Env* e, const char *cstr, ssize_t size) { static FMethod *m = NULL; if (!m) { m = e->findMethod("sys", "Str", "fromCStr"); } fr_TagValue args[2]; if (size == -1) size = strlen(cstr); args[0].type = fr_vtPtr; args[0].any.p = (void*)cstr; args[1].type = fr_vtInt; args[1].any.i = size; e->push(&args[0]); e->push(&args[1]); e->call(m, 2); fr_TagValue ret; e->pop(&ret); return (FObj*)ret.any.o; } FObj* fr_newStrUtf8_(Env* e, const char* cstr) { return fr_newStrUtf8N_(e, cstr, -1); } char * fr_getStrUtf8_(Env* e, FObj * self__) { static FMethod *m = NULL; if (!m) { m = e->findMethod("sys", "Str", "toUtf8"); } fr_TagValue args[2]; args[0].type = fr_vtObj; args[0].any.o = self__; e->push(&args[0]); e->call(m, 0); fr_TagValue ret; e->pop(&ret); fr_Array *a = (fr_Array*)ret.any.o; return (char*)a->data; } FObj* fr_getConstString_(Env* env, FPod* curPod, uint16_t sid) { if (curPod->constantas.c_strings.size() != curPod->constantas.strings.size()) { curPod->constantas.c_strings.resize(curPod->constantas.strings.size()); } FObj* objRef = (FObj*)curPod->constantas.c_strings[sid]; if (objRef) { return objRef; } const std::string& utf8 = curPod->constantas.strings[sid]; FObj* obj = (FObj*)fr_newStrUtf8_(env, utf8.c_str()); env->vm->gc->pinObj(fr_toGcObj(obj)); curPod->constantas.c_strings[sid] = (void*)obj; return obj; } FObj* fr_getConstUri_(Env* env, FPod* curPod, uint16_t sid) { if (curPod->constantas.c_uris.size() != curPod->constantas.uris.size()) { curPod->constantas.c_uris.resize(curPod->constantas.uris.size()); } FObj* objRef = (FObj*)curPod->constantas.c_uris[sid]; if (objRef) { return objRef; } const std::string& utf8 = curPod->constantas.uris[sid]; FObj* str = (FObj*)fr_newStrUtf8_(env, utf8.c_str()); static FMethod* m = NULL; if (!m) { m = env->findMethod("std", "Uri", "fromStr", 1); } fr_TagValue args[2]; args[0].type = fr_vtObj; args[0].any.o = str; env->push(&args[0]); env->call(m, 1); fr_TagValue ret; env->pop(&ret); FObj* obj = (FObj*)ret.any.o; env->vm->gc->pinObj(fr_toGcObj(obj)); curPod->constantas.c_uris[sid] = (void*)obj; return obj; } FObj* fr_getTypeLiteral_(Env* e, FPod* curPod, uint16_t sid) { FTypeRef &typeRef = curPod->typeRefs[sid]; std::string qname = curPod->names[typeRef.podName] + "::" + curPod->names[typeRef.typeName]; FObj *qnameObj = fr_newStrUtf8_(e, qname.c_str()); static FMethod* m = NULL; if (!m) { m = e->findMethod("std", "Type", "find", 1); } fr_TagValue args[2]; args[0].type = fr_vtObj; args[0].any.o = qnameObj; e->push(&args[0]); e->call(m, 1); fr_TagValue ret; e->pop(&ret); return (FObj*)ret.any.o; } FObj* fr_getFieldLiteral_(Env* e, FPod* curPod, uint16_t sid) { FFieldRef& f = curPod->fieldRefs[sid]; FObj* type = fr_getTypeLiteral_(e, curPod, f.parent); FObj* nameObj = fr_newStrUtf8_(e, curPod->names[f.name].c_str()); static FMethod* m = NULL; if (!m) { m = e->findMethod("std", "Type", "field", 1); } fr_TagValue args[2]; args[0].type = fr_vtObj; args[0].any.o = type; args[1].type = fr_vtObj; args[1].any.o = nameObj; e->push(&args[0]); e->push(&args[1]); e->call(m, 1); fr_TagValue ret; e->pop(&ret); return (FObj*)ret.any.o; } FObj* fr_getMethodLiteral_(Env* e, FPod* curPod, uint16_t sid) { FMethodRef& f = curPod->methodRefs[sid]; FObj* type = fr_getTypeLiteral_(e, curPod, f.parent); FObj* nameObj = fr_newStrUtf8_(e, curPod->names[f.name].c_str()); static FMethod* m = NULL; if (!m) { m = e->findMethod("std", "Type", "method", 1); } fr_TagValue args[2]; args[0].type = fr_vtObj; args[0].any.o = type; args[1].type = fr_vtObj; args[1].any.o = nameObj; e->push(&args[0]); e->push(&args[1]); e->call(m, 1); fr_TagValue ret; e->pop(&ret); return (FObj*)ret.any.o; } //////////////////////////////////////////////////////////////// // Boxing //////////////////////////////////////////////////////////////// FObj* sys_Int_doBox_(Env* e, fr_Int i) { FType* type = e->toType(fr_vtInt); int size = sizeof(fr_Int); FObj* obj = fr_allocObj_(e, type, size); fr_Int* val = (fr_Int*)(((char*)obj)); *val = i; return obj; } FObj * fr_box_int_(Env* e, fr_Int i) { FObj* obj; static FObj *map[515]; static const fr_Int sys_Int_minVal = -9223372036854775807LL-1; static const fr_Int sys_Int_maxVal = 9223372036854775807LL; int index; if (i < 256 && i >= -256) { index = i + 256; } else if (i == sys_Int_maxVal) index = 513; else if (i == sys_Int_minVal) index = 514; else { return sys_Int_doBox_(e, i); } obj = map[index]; if (obj) return obj; obj = sys_Int_doBox_(e, i); e->vm->gc->pinObj(fr_toGcObj(obj)); map[index] = obj; return obj; } FObj * sys_Float_doBox_(Env* e, fr_Float i) { FType *type = e->toType(fr_vtFloat); int size = sizeof(fr_Float); FObj * obj = fr_allocObj_(e, type, size); fr_Float *val = (fr_Float*)(((char*)obj)); *val = i; return obj; } FObj* fr_box_float_(Env* e, fr_Float val) { FObj* obj; static FObj* map[8]; static const fr_Float sys_Float_e = 2.71828182845904509080; static const fr_Float sys_Float_pi = 3.14159265358979311600; int index; if (val == 0) index = 0; if (val == 1) index = 1; if (val == -1) index = 2; if (val == 0.5) index = 3; if (val == sys_Float_e) index = 4; if (val == sys_Float_pi) index = 5; if (val == -INFINITY) index = 6; if (val == INFINITY) index = 7; else { obj = sys_Float_doBox_(e, val); return obj; } obj = map[index]; if (obj) return obj; obj = sys_Float_doBox_(e, val); e->vm->gc->pinObj(fr_toGcObj(obj)); map[index] = obj; return obj; } FObj* sys_Bool_doBox_(Env* e, fr_Bool i) { FType* type = e->toType(fr_vtBool); int size = sizeof(fr_Bool); FObj* obj = fr_allocObj_(e, type, size); fr_Bool* val = (fr_Bool*)(((char*)obj)); *val = i; return obj; } FObj * fr_box_bool_(Env* e, fr_Bool i) { static FObj* trueObj = NULL; static FObj* falseObj = NULL; if (!trueObj) { //std::lock_guard<std::mutex> lock(pool_mutex); trueObj = sys_Bool_doBox_(e, true); falseObj = sys_Bool_doBox_(e, false); e->vm->gc->pinObj(fr_toGcObj(trueObj)); e->vm->gc->pinObj(fr_toGcObj(falseObj)); } return i ? trueObj : falseObj; } FObj * fr_box_(Env *env, fr_Value &any, fr_ValueType vtype) { FObj * obj = nullptr; switch (vtype) { case fr_vtInt: obj = fr_box_int_(env, any.i); break; case fr_vtFloat: obj = fr_box_float_(env, any.f); break; case fr_vtBool: obj = fr_box_bool_(env, any.b); break; default: obj = (FObj*)any.o; break; } return obj; } fr_ValueType fr_unbox_(Env *env, FObj * obj, fr_Value &value) { fr_ValueType type = env->podManager->getValueTypeByType(env, fr_getFType((fr_Env)env, obj)); if (type == fr_vtInt) { fr_Int* val = (fr_Int*)(((char*)obj)); value.i = *val; } else if (type == fr_vtFloat) { fr_Float* val = (fr_Float*)(((char*)obj)); value.f = *val; } else if (type == fr_vtBool) { fr_Bool* val = (fr_Bool*)(((char*)obj)); value.b = *val; } else { value.o = obj; } //value.type = type; return type; } #ifdef __cplusplus }//extern "C" #endif
26.324943
96
0.55346
fanx-dev
f178d496f3db84c78105b0501e91a10aef1f8576
404
cpp
C++
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
/* g++ GotW1.cpp -omain -std=c++11 */ #include <iostream> int main() { int ival1 = 13; int ival2{14}; // C++11 int ival3(15); int ival4; int ival5(); // it's a function declaration std::cout << ival1 <<std::endl; std::cout << ival2 <<std::endl; std::cout << ival3 <<std::endl; std::cout << ival4 <<std::endl; std::cout << ival5 <<std::endl; return 0; }
16.833333
47
0.534653
straceX
f17b283c2d2aa63ae9ed1fe0cd097f0cebde5804
6,172
cpp
C++
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
#include <cinttypes> #include <regex> #include <thread> #include <random> #include "common.h" #include "rpc_global.h" #include "rpc_insert.h" #include "cjson/cjson.h" #include "str/strtools.h" #include "sba/sba.h" #include "oloop_insert.h" #include "asyncpool.h" #include "sentinel.h" #include "sidelog.h" #include "database.h" #include "result.h" #include "table.h" #include "tablepartitioned.h" #include "errors.h" #include "internoderouter.h" #include "http_serve.h" using namespace std; using namespace openset::comms; using namespace openset::async; using namespace openset::comms; using namespace openset::db; using namespace openset::result; void RpcInsert::insertRetry(const openset::web::MessagePtr& message, const RpcMapping& matches, const int retryCount) { const auto database = openset::globals::database; const auto partitions = openset::globals::async; const auto request = message->getJSON(); const auto tableName = matches.find("table"s)->second; const auto isFork = message->getParamBool("fork"); /* const auto relayString = message->getParamString("relay"); const auto relayParts = split(relayString, ':'); std::unordered_set<int64_t> alreadyRelayed; alreadyRelayed.insert(openset::globals::running->nodeId); for (const auto &relay : relayParts) { alreadyRelayed.insert(stoll(relay)); } if (!partitions->getPartitionMax()) { RpcError( openset::errors::Error{ openset::errors::errorClass_e::insert, openset::errors::errorCode_e::route_error, "node not initialized" }, message); return; } */ auto table = database->getTable(tableName); if (!table || table->deleted) { RpcError( openset::errors::Error{ openset::errors::errorClass_e::insert, openset::errors::errorCode_e::general_error, "missing or invalid table name" }, message); return; } //auto clusterErrors = false; const auto startTime = Now(); // a cluster error (missing partition, etc), or a map changed happened // during this insert, then re-insert if (openset::globals::sentinel->wasDuringMapChange(startTime - 500, startTime)) { const auto backOff = (retryCount * retryCount) * 20; ThreadSleep(backOff < 10000 ? backOff : 10000); insertRetry(message, matches, retryCount + 1); return; } auto rows = request.getNodes(); Logger::get().info("Inserting " + to_string(rows.size()) + " events."); // vectors go gather locally inserted, or remotely distributed events from this set //std::unordered_map<int, std::vector<char*>> localGather; //std::unordered_map<int64_t, std::vector<char*>> remoteGather; SideLog::getSideLog().lock(); for (auto row : rows) { const auto personNode = row->xPath("/id"); if (!personNode || (personNode->type() != cjson::Types_e::INT && personNode->type() != cjson::Types_e::STR)) continue; // straight up numeric ID nodes don't need hashing, actually hashing would be very bad. // We can use numeric IDs (i.e. a customer id) directly. int64_t uuid = 0; if (personNode->type() == cjson::Types_e::STR) { auto uuString = personNode->getString(); toLower(uuString); if (uuString.length()) uuid = MakeHash(uuString); } else uuid = personNode->getInt(); const auto destination = cast<int32_t>((std::abs(uuid) % 13337) % partitions->getPartitionMax()); int64_t len; SideLog::getSideLog().add(table.get(), destination, cjson::stringifyCstr(row, len)); } SideLog::getSideLog().unlock(); const auto localEndTime = Now(); if (!isFork && openset::globals::mapper->countActiveRoutes() > 1) { if (openset::globals::sentinel->wasDuringMapChange(startTime, localEndTime)) ThreadSleep(1000); const auto method = message->getMethod(); const auto path = message->getPath(); auto newParams = message->getQuery(); newParams.emplace("fork", "true"); const auto payloadLength = message->getPayloadLength(); const auto payload = static_cast<char*>(PoolMem::getPool().getPtr(payloadLength)); memcpy(payload, message->getPayload(), payloadLength); std::thread t([=](){ while (true) { auto result = openset::globals::mapper->dispatchCluster( method, path, newParams, payload, payloadLength, false); const auto isGood = !result.routeError; openset::globals::mapper->releaseResponses(result); if (isGood) break; } PoolMem::getPool().freePtr(payload); }); t.detach(); } cjson response; response.set("message", "yummy"); // broadcast active nodes to caller - they may round-robin to these auto routesList = response.setArray("routes"); { csLock lock(openset::globals::mapper->cs); auto routes = openset::globals::mapper->routes; for (const auto &r : routes) { if (r.first == globals::running->nodeId) // fix for broadcast bug shouting local host and port routesList->push(globals::running->hostExternal + ":" + to_string(globals::running->portExternal)); else routesList->push(r.second.first + ":" + to_string(r.second.second)); } } message->reply(http::StatusCode::success_ok, response); } void RpcInsert::insert(const openset::web::MessagePtr& message, const RpcMapping& matches) { insertRetry(message, matches, 1); }
31.489796
118
0.585386
ashcharles
f183b21e8834fbcd5865232637146d734e99ad61
2,867
cpp
C++
tests/controlmode_test.cpp
adityab/hybrid-automaton-library
b67a5d5291c86920b3d441d0714cb895b92609d0
[ "BSD-2-Clause" ]
5
2017-02-14T12:26:53.000Z
2020-05-09T06:37:37.000Z
tests/controlmode_test.cpp
adityab/hybrid-automaton-library
b67a5d5291c86920b3d441d0714cb895b92609d0
[ "BSD-2-Clause" ]
1
2019-07-11T16:06:04.000Z
2019-07-11T16:06:04.000Z
tests/controlmode_test.cpp
adityab/hybrid-automaton-library
b67a5d5291c86920b3d441d0714cb895b92609d0
[ "BSD-2-Clause" ]
5
2017-11-23T12:46:41.000Z
2021-06-10T15:36:02.000Z
#include "gtest/gtest.h" #include "gmock/gmock.h" #include <string> #include "hybrid_automaton/HybridAutomaton.h" #include "hybrid_automaton/DescriptionTreeNode.h" #include "tests/MockDescriptionTree.h" #include "tests/MockDescriptionTreeNode.h" using ::testing::Return; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::AtLeast; using ::testing::_; using namespace ::ha; namespace ControlModeSerialization1 { class MockSerializableControlSet : public ha::ControlSet { public: MOCK_CONST_METHOD1(serialize, DescriptionTreeNode::Ptr (const DescriptionTree::ConstPtr& factory) ); MOCK_CONST_METHOD1(deserialize, void (const ha::DescriptionTreeNode::ConstPtr& tree) ); HA_CONTROLSET_INSTANCE(node, system, ha) { return ControlSet::Ptr(new MockSerializableControlSet); } }; HA_CONTROLSET_REGISTER("MockSerializableControlSet", MockSerializableControlSet); } TEST(ControlMode, Serialization) { using namespace ha; using namespace std; string ctrlSetType("MockSerializableControlSet"); //------- // Serialized and deserialized control set ControlModeSerialization1::MockSerializableControlSet* _cs = new ControlModeSerialization1::MockSerializableControlSet; ControlSet::Ptr cs(_cs); cs->setName("myCS"); // Mocked description returned by control set MockDescriptionTreeNode* _cs_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr cs_node(_cs_node); EXPECT_CALL(*_cs_node, getType()).WillRepeatedly(Return("ControlSet")); EXPECT_CALL(*_cs_node, getAttributeString(_, _)) .WillRepeatedly(DoAll(SetArgReferee<1>(""),Return(true))); EXPECT_CALL(*_cs, serialize(_)) .WillRepeatedly(Return(cs_node)); //------- // TEST ControlMode // Mocked tree factory MockDescriptionTree* _tree = new MockDescriptionTree; MockDescriptionTree::Ptr tree(_tree); ControlMode* _cm1 = new ControlMode; ControlMode::Ptr cm1(_cm1); cm1->setName("myCM1"); MockDescriptionTreeNode::Ptr cm1_node_faulty(new MockDescriptionTreeNode); EXPECT_CALL(*cm1_node_faulty, setAttributeString(_,_)) .Times(AtLeast(0)); // assert throwing of exception if no control set has been set EXPECT_CALL(*_tree, createNode("ControlMode")) .WillOnce(Return(cm1_node_faulty)); ASSERT_ANY_THROW(cm1->serialize(tree)); cm1->setControlSet(cs); // this will be the node "generated" by the tree MockDescriptionTreeNode* _cm1_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr cm1_node(_cm1_node); EXPECT_CALL(*_tree, createNode("ControlMode")) .WillOnce(Return(cm1_node)); // Expect that exactly one child node = cs will be added as child node EXPECT_CALL(*_cm1_node, addChildNode(cs_node)) .WillOnce(Return()); // -> some properties (don't care) EXPECT_CALL(*_cm1_node, setAttributeString(_,_)) .Times(AtLeast(0)); DescriptionTreeNode::Ptr cm_serialized; cm_serialized = cm1->serialize(tree); }
29.864583
120
0.769445
adityab
f184cb107e9537b5c4396f7ecc52e3025c1cbf84
16,373
cpp
C++
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
15
2021-01-24T11:59:04.000Z
2022-03-23T07:23:44.000Z
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
8
2021-05-24T18:22:45.000Z
2022-03-11T09:48:05.000Z
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
4
2021-01-26T19:18:21.000Z
2021-12-07T17:02:34.000Z
#include <sstream> #include "Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.hpp" namespace py = pybind11; using namespace py::literals; using namespace aff3ct; using namespace aff3ct::module; using namespace aff3ct::tools; using namespace aff3ct::wrapper; Wrapper_Sparse_matrix ::Wrapper_Sparse_matrix(py::module_& scope) : Wrapper_py(), py::class_<aff3ct::tools::Sparse_matrix>(scope, "array") { py::module_ alist = scope.def_submodule("alist"); alist.def("read", [](const std::string& path){ std::filebuf fb; if (fb.open (path,std::ios::in)) { std::istream stream(&fb); aff3ct::tools::Sparse_matrix ret = aff3ct::tools::AList::read(stream); return ret; } else { std::stringstream message; message << "Can't open '" + path + "' file."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } }, py::return_value_policy::copy); py::module_ qc = scope.def_submodule("qc"); qc.def("read", [](const std::string& path){ std::filebuf fb; if (fb.open (path,std::ios::in)) { std::istream stream(&fb); aff3ct::tools::Sparse_matrix ret = aff3ct::tools::QC::read(stream); return ret; } else { std::stringstream message; message << "Can't open '" + path + "' file."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } }, py::return_value_policy::copy); scope.def("eye", [](const size_t &size, const int64_t &d){ aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(size, size); for (size_t i = 0; i<size; i++) if (i-d >= 0 && i-d < size) H->add_connection(i-d,i); return H; }, py::return_value_policy::take_ownership); scope.def("ones", [](py::tuple& shape){ if (shape.size() != 2 ) { std::stringstream message; message << "the created array should be 2-dimensional, but " << shape.size() << " indexes were given."; throw py::index_error(message.str()); } int n_rows; try { n_rows = shape[0].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } int n_cols; try { n_cols = shape[1].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(n_rows, n_cols); for (size_t i = 0; i<n_rows; i++) for (size_t j = 0; j<n_cols; j++) H->add_connection(i,j); return H; }, py::return_value_policy::take_ownership); scope.def("zeros", [](py::tuple& shape){ if (shape.size() != 2 ) { std::stringstream message; message << "the created array should be 2-dimensional, but " << shape.size() << " indexes were given."; throw py::index_error(message.str()); } int n_rows; try { n_rows = shape[0].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } int n_cols; try { n_cols = shape[1].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(n_rows, n_cols); return H; }, py::return_value_policy::take_ownership); scope.def("concatenate", [](py::tuple& arrays, size_t axis){ aff3ct::tools::Sparse_matrix* H; try { H = new aff3ct::tools::Sparse_matrix(arrays[0].cast<aff3ct::tools::Sparse_matrix>()); } catch(...) { std::stringstream message; message << "Item 0 of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } size_t n_rows = H->get_n_rows(); size_t n_cols = H->get_n_cols(); if (axis == 0) { for (size_t i =1; i<arrays.size(); i++) { aff3ct::tools::Sparse_matrix* H_; try { H_ = arrays[i].cast<aff3ct::tools::Sparse_matrix*>(); } catch(...) { std::stringstream message; message << "Item " << i << " of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } int old_n_rows = n_rows; n_rows += H_->get_n_rows(); if (H_->get_n_cols() != n_cols) { std::stringstream message; message << "all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index " << i << " has size " << H_->get_n_cols() << " and the array at index " << i - 1 << " has size " << n_cols << "."; throw py::value_error(message.str()); } H->self_resize(n_rows, n_cols, aff3ct::tools::Matrix::Origin::TOP_LEFT); for (size_t i = 0; i < H_->get_n_rows(); i++) for (size_t j = 0; j < H_->get_n_cols(); j++) if(H_->at(i,j) && !H->at(old_n_rows+i,j)) H->add_connection(old_n_rows+i,j); else if(!H_->at(i,j) && H->at(old_n_rows+i,j)) H->rm_connection(old_n_rows+i,j); } } else if (axis == 1) { for (size_t i =1; i<arrays.size(); i++) { aff3ct::tools::Sparse_matrix* H_; try { H_ = arrays[i].cast<aff3ct::tools::Sparse_matrix*>(); } catch(...) { std::stringstream message; message << "Item " << i << " of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } int old_n_cols = n_cols; n_cols += H_->get_n_cols(); if (H_->get_n_rows() != n_rows) { std::stringstream message; message << "all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index " << i << " has size " << H_->get_n_rows() << " and the array at index " << i - 1 << " has size " << n_rows << "."; throw py::value_error(message.str()); } H->self_resize(n_rows, n_cols, aff3ct::tools::Matrix::Origin::TOP_LEFT); for (size_t i = 0; i < H_->get_n_rows(); i++) for (size_t j = 0; j < H_->get_n_cols(); j++) if(H_->at(i,j) && !H->at(i,old_n_cols + j)) H->add_connection(i,old_n_cols + j); else if(!H_->at(i,j) && H->at(i,old_n_cols + j)) H->rm_connection(i,old_n_cols + j); } } return H; }, "arrays"_a, "axis"_a=0, py::return_value_policy::take_ownership); } void Wrapper_Sparse_matrix ::definitions() { this->def(py::init<const size_t, const size_t>(),"n_rows"_a = 0, "n_cols"_a = 1, R"pbdoc()pbdoc", py::return_value_policy::take_ownership); this->def(py::init([](py::array_t<bool> &array){ if (array.ndim() == 2) { size_t n_rows = array.shape(0); size_t n_cols = array.shape(1); tools::Sparse_matrix* ret_spm = new tools::Sparse_matrix(n_rows,n_cols); for (size_t i = 0; i < n_rows ; ++i) for (size_t j = 0; j < n_cols ; ++j) if(array.at(i,j)) ret_spm->add_connection(i,j); return ret_spm; } else { throw std::runtime_error("Sparse_Matrix can only be built from a 2-dimensional boolean array."); } }), "array"_a = 1, R"pbdoc()pbdoc", py::return_value_policy::take_ownership); this->def("full", [](aff3ct::tools::Sparse_matrix& self) { auto arr = py::array_t<bool, py::array::c_style>({ self.get_n_rows(), self.get_n_cols() }); auto f_arr = arr.mutable_unchecked<2>(); for (size_t i = 0; i<self.get_n_rows(); i++ ) for (size_t j = 0; j<self.get_n_cols(); j++ ) f_arr(i,j) = self.at(i,j); return arr; },py::return_value_policy::copy); this->def("__getitem__", [](const aff3ct::tools::Sparse_matrix& self, const size_t& index) { aff3ct::tools::Sparse_matrix* ret_spm = new aff3ct::tools::Sparse_matrix(1, self.get_n_cols()); for (size_t j = 0; j < self.get_n_cols(); ++j) if (self.at(index, j)) ret_spm->add_connection(0,j); return ret_spm; }, py::return_value_policy::take_ownership); this->def("__getitem__", [](const aff3ct::tools::Sparse_matrix& self, const py::tuple& index) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); aff3ct::tools::Sparse_matrix* ret_spm = new aff3ct::tools::Sparse_matrix(slicelengthi, slicelengthj); size_t read_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t read_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (self.at(read_i, read_j)) ret_spm->add_connection(i,j); read_j += stepj; } read_i += stepi; } return ret_spm; }, py::return_value_policy::take_ownership); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const size_t& index, const aff3ct::tools::Sparse_matrix& value) { for (size_t j = 0; j < self.get_n_cols(); ++j) { if (value.at(0,j) && !self.at(index, j)) self.add_connection(index, j); else if (!value.at(0,j) && self.at(index, j)) self.rm_connection(index, j); } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const aff3ct::tools::Sparse_matrix& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); if (value.get_n_rows() != slicelengthi || value.get_n_cols() != slicelengthj) { std::stringstream message; message << " could not broadcast input array from shape (" << value.get_n_rows() << "," << value.get_n_cols() <<") into shape (" << slicelengthi << "," << slicelengthj << ")."; throw py::index_error(message.str()); } size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value.at(i,j)) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const py::array_t<bool>& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); if (value.shape(0) != slicelengthi || value.shape(1) != slicelengthj) { std::stringstream message; message << " could not broadcast input array from shape (" << value.shape(0) << "," << value.shape(1) <<") into shape (" << slicelengthi << "," << slicelengthj << ")."; throw py::index_error(message.str()); } size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value.at(i,j)) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const bool& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__str__",[](aff3ct::tools::Sparse_matrix& self){ std::stringstream message; message << "Sparse_matrix of size " << self.get_n_rows() << "x" << self.get_n_cols()<<".\nConnections:\n"; for (size_t i = 0; i < self.get_n_rows(); ++i) for (size_t j = 0; j < self.get_n_cols(); ++j) if (self.at(i,j)) message << "\t(" << i <<","<< j <<")\n"; return message.str(); }); this->def("transpose",[](const aff3ct::tools::Sparse_matrix& self){ return self.transpose(); }); this->def_property_readonly("shape", [](const aff3ct::tools::Sparse_matrix& self){ return py::make_tuple(self.get_n_rows(),self.get_n_cols()); }); } py::slice Wrapper_Sparse_matrix ::get_slice(const py::object& obj, const size_t len) { if (py::isinstance<py::int_>(obj)) { int i_sj = obj.cast<int>(); size_t ui_sj; if ( i_sj < 0 ) ui_sj = len - (abs(i_sj) % len); else ui_sj = i_sj % len; py::slice sjj = py::slice(ui_sj, ui_sj+1, 1); return sjj; } else if(py::isinstance<py::slice>(obj)) { return py::slice(obj); } else { throw std::runtime_error("Sparse_Matrix only accepts integer or slice indexing."); } }
30.776316
253
0.62658
aff3ct
f185b91419a8f37e1852f41137f6cfbdb311659a
892
hpp
C++
pnpbridge/src/adapters/src/mqtt_pnp/mqtt_pnp.hpp
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
29
2020-09-30T19:20:07.000Z
2022-02-24T16:28:02.000Z
pnpbridge/src/adapters/src/mqtt_pnp/mqtt_pnp.hpp
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
28
2020-09-30T21:05:11.000Z
2021-11-10T19:06:29.000Z
pnpbridge/src/adapters/src/mqtt_pnp/mqtt_pnp.hpp
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
15
2020-10-18T12:46:30.000Z
2021-12-26T02:17:15.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include "mqtt_protocol_handler.hpp" #include <pnpadapter_api.h> #include <nosal.h> #ifdef __cplusplus extern "C" { #endif extern PNP_ADAPTER MqttPnpInterface; #ifdef __cplusplus } #endif class MqttPnpInstance { public: MqttPnpInstance( const std::string& componentName); MqttConnectionManager s_ConnectionManager; MqttProtocolHandler* s_ProtocolHandler; std::string s_ComponentName; }; // MQTT Adapter Config #define PNP_CONFIG_ADAPTER_MQTT_IDENTITY "mqtt_identity" #define PNP_CONFIG_ADAPTER_MQTT_PROTOCOL "mqtt_protocol" #define PNP_CONFIG_ADAPTER_MQTT_SERVER "mqtt_server" #define PNP_CONFIG_ADAPTER_MQTT_PORT "mqtt_port" #define PNP_CONFIG_ADAPTER_MQTT_SUPPORTED_CONFIG "json_rpc_1"
27.030303
101
0.793722
daisukeiot
f18661d5b42ddec21ee89bb630335b003b927da0
557
cpp
C++
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
10
2017-07-04T03:05:42.000Z
2022-01-20T17:37:06.000Z
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
2
2020-06-29T13:32:15.000Z
2021-12-22T23:04:43.000Z
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
5
2021-08-28T02:21:56.000Z
2022-01-16T21:39:16.000Z
/** @file main.c * Entry point of p/emu */ #include <SDL.h> #include <SDL_thread.h> int main_event_loop(void); #ifdef __linux__ int main(int argc, char** argv) #else int SDL_main(int argc, char** argv) #endif { SDL_Init(SDL_INIT_EVERYTHING); SDL_SetVideoMode(128 * 2, 88 * 2, 32, SDL_HWSURFACE); main_event_loop(); SDL_Quit(); return 0; } int main_event_loop(void) { SDL_Event event; while(1) { while(SDL_WaitEvent(&event)) { switch(event.type) { case SDL_QUIT: return 0; } } } return 0; }
12.953488
55
0.624776
autch
f18c14013c9b6cd736a3fed6920eb508781f94dc
1,189
hpp
C++
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
/* ** BENSUPERPC PROJECT, 2020 ** Crypto ** Source: https://stackoverflow.com/questions/178265/what-is-the-most-hard-to-understand-piece-of-c-code-you-know https://cs.uwaterloo.ca/~m32rober/rsqrt.pdf https://github.com/bavlayan/Encrypt-Decrypt-with-OpenSSL---RSA https://stackoverflow.com/a/5580881/10152334 ** crypto.cpp */ #ifndef CRYPTO_AES_HPP_ #define CRYPTO_AES_HPP_ // For AES #include <openssl/aes.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <string.h> #define BUFFSIZE 16384 namespace my { namespace crypto { int Decrypt_AES(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv, unsigned char *plaintext); int Encrypt_AES(unsigned char *plaintext, int plaintext_len, unsigned char *aad, int aad_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext, unsigned char *tag); int Rand_Key_AES(unsigned char *key); int Rand_IV_AES(unsigned char *iv); __attribute__((__noreturn__)) void handleErrors(); } // namespace crypto } // namespace my // https://www.quora.com/How-can-I-get-the-MD5-or-SHA-hash-of-a-file-in-C #endif
27.651163
159
0.751051
Pcornat
f18d508bae1985750279537e79e5227e9be8ec86
98
cpp
C++
Testbed/AGF/src/events.cpp
abel1502/mipt_4s
c31a4bb82dfd147fa16407800e749bbad166d27d
[ "MIT" ]
2
2021-10-16T10:58:26.000Z
2021-12-22T22:18:37.000Z
VS/AGF/src/events.cpp
abel1502/mipt_3s
10efc85371e53a0780302763c409cde2158f81fc
[ "MIT" ]
null
null
null
VS/AGF/src/events.cpp
abel1502/mipt_3s
10efc85371e53a0780302763c409cde2158f81fc
[ "MIT" ]
null
null
null
#include <AGF/llgui.h> #include <AGF/events.h> namespace abel::gui { // Empty, apparently }
8.166667
23
0.653061
abel1502
f19495cde7f0bc68d9e7149f659ec842064151f1
951
cpp
C++
test_package/test_Util.cpp
odant/conan-poco
ded0aa51acac42f47f52b7ee1d1eba0e5550823e
[ "MIT" ]
null
null
null
test_package/test_Util.cpp
odant/conan-poco
ded0aa51acac42f47f52b7ee1d1eba0e5550823e
[ "MIT" ]
null
null
null
test_package/test_Util.cpp
odant/conan-poco
ded0aa51acac42f47f52b7ee1d1eba0e5550823e
[ "MIT" ]
null
null
null
// Test for Poco Conan package // Dmitriy Vetutnev, Odant, 2018 #include <Poco/AutoPtr.h> #include <Poco/Util/SystemConfiguration.h> #include <iostream> #include <cstdlib> using Poco::AutoPtr; using Poco::Util::SystemConfiguration; int main(int, char**) { AutoPtr<SystemConfiguration> systemConfig = new SystemConfiguration; std::cout << "system.osName: " << systemConfig->getString("system.osName") << std::endl; std::cout << "system.osVersion: " << systemConfig->getString("system.osVersion") << std::endl; std::cout << "system.osArchitecture: " << systemConfig->getString("system.osArchitecture") << std::endl; std::cout << "system.currentDir: " << systemConfig->getString("system.currentDir") << std::endl; std::cout << "system.dateTime: " << systemConfig->getString("system.dateTime") << std::endl; std::cout << "system.pid: " << systemConfig->getUInt("system.pid") << std::endl; return EXIT_SUCCESS; }
31.7
108
0.683491
odant
f197bf6ee3216d0ade2497e1f115756a814b2b9b
3,473
cpp
C++
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
#include <mbed.h> // #include "encoder_implementation/own_rotary.hpp" #include "motor_implementation/own_open_loop/open_loop.hpp" #include "motor_implementation/closed_loop/closed_loop.hpp" class Encoder { public: Encoder(); ~Encoder(); int32_t get_rotary_angle(void); void reset_rotary_angle(void); private: void rise_A(void); void rise_B(void); void fall_A(void); void fall_B(void); private: InterruptIn rotary_encoderA; InterruptIn rotary_encoderB; // Timeout synchronous_rpm; volatile int32_t m_rotary_angle; volatile bool voltage_level_a; volatile bool voltage_level_b; // _interrupt.rise(callback(this, &Encoder::change_angle)); }; void Encoder::rise_A(void) { voltage_level_a = 1; if (voltage_level_b == 1) { m_rotary_angle = m_rotary_angle +1; } else { --m_rotary_angle; } } void Encoder::fall_A(void) { voltage_level_a = 0; if (voltage_level_b == 1) { // --Encoder::rotary_angle; --m_rotary_angle; } else { ++m_rotary_angle; } } void Encoder::rise_B(void) { voltage_level_b = 1; if (voltage_level_a == 1) { --m_rotary_angle; } else { ++m_rotary_angle; } } void Encoder::fall_B(void) { voltage_level_b = 0; if (voltage_level_a == 1) { ++m_rotary_angle; } else { --m_rotary_angle; } } int32_t Encoder::get_rotary_angle(void) { return this->m_rotary_angle; } void Encoder::reset_rotary_angle(void) { m_rotary_angle = 0; } Encoder::Encoder() :rotary_encoderA(D12), rotary_encoderB(PA_11), m_rotary_angle(0) { rotary_encoderA.rise(callback(this, &Encoder::rise_A)); rotary_encoderA.fall(callback(this, &Encoder::fall_A)); rotary_encoderB.rise(callback(this, &Encoder::rise_B)); rotary_encoderB.fall(callback(this, &Encoder::fall_B)); } #define MAXIMUM_BUFFER_SIZE 32 Motor_Implementation *MotorControl; // Encoder *Rotary_Encoder; InterruptIn button_stop(D7); // Stop Taster, Falling Edge glaub ich InterruptIn button_start(D8); // Start Taster, Falling Edge bool stop_motor = 0; void start_button_press(void) { // delete MotorControl; // if (button_start.read() == 0) // { // MotorControl = new Own_Closed_Loop(); // } // else // { // MotorControl = new Own_Open_Loop(); // } // MotorControl->start_motor_control(); } void stop_button_press(void) { stop_motor = 1; } // Create a BufferedSerial object with a default baud rate. static BufferedSerial serial_port(USBTX, USBRX); int main() { // Set desired properties (9600-8-N-1). serial_port.set_baud(9600); serial_port.set_format( /* bits */ 8, /* parity */ BufferedSerial::None, /* stop bit */ 1 ); char buf[MAXIMUM_BUFFER_SIZE] = {0}; // button_start.fall(&start_button_press); button_stop.fall(&stop_button_press); Encoder Rotary_Encoder; // MotorControl = new Own_Closed_Loop(); if (button_start.read() == 0) { MotorControl = new Own_Closed_Loop(); } else { MotorControl = new Own_Open_Loop(); } // serial_port.write(buf, periodlength); while(1) { if (stop_motor == 1) { Rotary_Encoder.reset_rotary_angle(); stop_motor = 0; } int32_t rotary_angle = Rotary_Encoder.get_rotary_angle(); MotorControl->control_motor(rotary_angle); // serial_port.write(buf, periodlength); // put your main code here, to run repeatedly: ThisThread::sleep_for(20); } }
18.875
68
0.669738
chris3069
f1980c0fbbaf792c3ca69e0114e61712dfea79de
3,825
cpp
C++
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
3
2019-04-08T05:13:00.000Z
2020-01-02T05:40:03.000Z
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
null
null
null
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
2
2018-07-06T05:22:01.000Z
2021-12-26T12:45:34.000Z
#include <iostream> #include <stdio.h> #ifdef _WIN32 #include <Windows.h> #endif #include <osgViewer/Viewer> #include <osg/Node> #include <osg/ShapeDrawable> #include <osgDB/WriteFile> #include <osgGA/EventHandler> #include <osg/Switch> #include "libPTFTube/PTFTube.h" const int OSG_WIDTH = 900; const int OSG_HEIGHT = 900; osg::Node* createReferenceShape() { osg::Cylinder* cylinder = new osg::Cylinder(osg::Vec3( 0.f, 0.f, 0.f ), 0.5f, 2.f); osg::ShapeDrawable* sd = new osg::ShapeDrawable( cylinder ); sd->setColor( osg::Vec4( 0.8f, 0.5f, 0.2f, 1.f ) ); osg::Geode* geode = new osg::Geode; geode->addDrawable(sd); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::ON); return geode; } std::vector<osg::Vec3f> createLinePoints3d() { std::vector<osg::Vec3f> points3d; int angle = 0; float z=0.f; float pi = 3.141592f; for (angle; angle<=360*2; angle+=10, z+=0.3f){ float rad = angle*pi/180.f; float dx=0, dy=0, dz=0; dx = std::sin(rad)*2.f; dy = std::cos(rad)*4.f; dz = z; points3d.push_back(osg::Vec3f(dx,dy,dz)); } return points3d; } class Switch : public osg::Switch { public: Switch(const PTFTube& extrusion) : osg::Switch() { osg::ref_ptr<osg::Node> path = extrusion.generatePath(); osg::ref_ptr<osg::Node> mesh = extrusion.generateTriMesh(); osg::ref_ptr<osg::Node> slices = extrusion.generateFrameSlices(1.f); osg::ref_ptr<osg::Node> wire = extrusion.generateWireFrame(); this->addChild(path.get(), false); this->addChild(wire.get(), false); this->addChild(slices.get(), false); this->addChild(mesh.get(), true); } }; class EventHandler : public osgGA::GUIEventHandler { public: EventHandler(Switch* all) : osgGA::GUIEventHandler() , m_root(all) { } virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { unsigned int index = 3; switch (ea.getEventType()){ case (osgGA::GUIEventAdapter::KEYUP): switch (ea.getKey()){ case '0': std::cout << "Original path display.\n"; index = 0; break; case '1': std::cout << "Wire frame display.\n"; index = 1; break; case '2': std::cout << "Frame slice display.\n"; index = 2; break; case '3': std::cout << "Triangular mesh display.\n"; index = 3; break; default: for (unsigned int i=0; i<m_root->getNumChildren(); ++i){ if (m_root->getValue(i)) index = i; } break; } for (unsigned int i=0; i< m_root->getNumChildren(); ++i){ if (i == index) m_root->setValue(i, true); else m_root->setValue(i, false); } default: break; } return false; } private: osg::observer_ptr<Switch> m_root; }; int main(int, char**) { #ifdef _WIN32 ::SetProcessDPIAware(); #endif osgViewer::Viewer viewer; viewer.setUpViewInWindow(100,100,OSG_WIDTH, OSG_HEIGHT); osg::ref_ptr<osg::Group> root = new osg::Group(); // root->addChild(createReferenceShape()); PTFTube extrusion(createLinePoints3d(), 0.5, 5); extrusion.build(); Switch* geometries = new Switch(extrusion); root->addChild(geometries); viewer.setSceneData(root.get()); EventHandler* EH = new EventHandler(geometries); viewer.addEventHandler(EH); return viewer.run(); }
26.020408
87
0.55268
vicrucann
1af59ea57267148ad5f341cb5e044326fa1762e4
2,895
cxx
C++
Qt/Core/pqFlatTreeViewEventTranslator.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Qt/Core/pqFlatTreeViewEventTranslator.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Qt/Core/pqFlatTreeViewEventTranslator.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: ParaView Module: $RCSfile: pqFlatTreeViewEventTranslator.cxx,v $ Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.1. See License_v1.1.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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 "pqFlatTreeViewEventTranslator.h" #include "pqFlatTreeView.h" #include <QItemSelectionModel> #include <QEvent> static const QString str(const QModelIndex& index) { QString result; for(QModelIndex i = index; i.isValid(); i = i.parent()) { result = "/" + QString().setNum(i.row()) + result; } if(index.isValid()) { result = result + "|" + QString().setNum(index.column()); } return result; } pqFlatTreeViewEventTranslator::pqFlatTreeViewEventTranslator(QObject* p) : pqWidgetEventTranslator(p), CurrentObject(0) { } bool pqFlatTreeViewEventTranslator::translateEvent(QObject* Object, QEvent* Event, bool& /*Error*/) { pqFlatTreeView* const object = qobject_cast<pqFlatTreeView*>(Object); if(!object) return false; switch(Event->type()) { case QEvent::Enter: this->CurrentObject = object; connect(object->getSelectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(onCurrentChanged(const QModelIndex&, const QModelIndex&))); return true; break; case QEvent::Leave: disconnect(Object, 0, this, 0); disconnect(object->getSelectionModel(), 0, this, 0); this->CurrentObject = 0; return true; break; default: break; } return false; } void pqFlatTreeViewEventTranslator::onCurrentChanged(const QModelIndex& current, const QModelIndex& /*previous*/) { emit recordEvent(this->CurrentObject, "currentChanged", str(current)); }
31.467391
177
0.687047
certik
1af5e2ad3934fffc83afe5deeeef978bf8aaa137
28
cc
C++
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
#include "../EventChain.h"
9.333333
26
0.642857
AndreyGFranca
1af89491d668dbc03b504016b5cb75522b473b31
2,599
cpp
C++
Hackerrank/c++/factorialtrailingzeroes.cpp
ajeet1308/code_problems
5d99839b6319295c6d81dd86775c46a536e7a1ca
[ "MIT" ]
61
2020-09-26T19:57:44.000Z
2022-03-09T18:51:44.000Z
Hackerrank/c++/factorialtrailingzeroes.cpp
ajeet1308/code_problems
5d99839b6319295c6d81dd86775c46a536e7a1ca
[ "MIT" ]
88
2020-09-19T20:00:27.000Z
2021-10-31T09:41:57.000Z
Hackerrank/c++/factorialtrailingzeroes.cpp
ajeet1308/code_problems
5d99839b6319295c6d81dd86775c46a536e7a1ca
[ "MIT" ]
218
2020-09-20T08:18:03.000Z
2022-01-30T23:13:16.000Z
class Solution { public: map<vector<int>, vector<vector<int>>> graph; map<int, vector<vector<int>>> nodes_in_comp; set<vector<int>> visited; bool overlap(vector<int>& a, vector<int>& b) { return a[0] <= b[1] and b[0] <= a[1]; } // build a graph where an undirected edge between intervals u and v exists // iff u and v overlap. void buildGraph(vector<vector<int>>& intervals) { for (auto interval1 : intervals) { for (auto interval2 : intervals) { if (overlap(interval1, interval2)) { graph[interval1].push_back(interval2); graph[interval2].push_back(interval1); } } } } // merges all of the nodes in this connected component into one interval. vector<int> mergeNodes(vector<vector<int>>& nodes) { int min_start = nodes[0][0]; for (auto node : nodes) { min_start = min(min_start, node[0]); } int max_end = nodes[0][1]; for (auto node : nodes) { max_end = max(max_end, node[1]); } return {min_start, max_end}; } // use depth-first search to mark all nodes in the same connected component // with the same integer. void markComponentDFS(vector<int>& start, int comp_number) { stack<vector<int>> stk; stk.push(start); while (!stk.empty()) { vector<int> node = stk.top(); stk.pop(); // not found if (visited.find(node) == visited.end()) { visited.insert(node); nodes_in_comp[comp_number].push_back(node); for (auto child : graph[node]) { stk.push(child); } } } } // gets the connected components of the interval overlap graph. void buildComponents(vector<vector<int>>& intervals) { int comp_number = 0; for (auto interval : intervals) { if (visited.find(interval) == visited.end()) { markComponentDFS(interval, comp_number); comp_number++; } } } vector<vector<int>> merge(vector<vector<int>>& intervals) { buildGraph(intervals); buildComponents(intervals); // for each component, merge all intervals into one interval. vector<vector<int>> merged; for (size_t comp = 0; comp < nodes_in_comp.size(); comp++) { merged.push_back(mergeNodes(nodes_in_comp[comp])); } return merged; } };
29.873563
79
0.544055
ajeet1308
1afab343c93e5de1f73a6dbfd41cdfe39584c228
425
hpp
C++
library/ATF/__dummy_block.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/__dummy_block.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/__dummy_block.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_dummy_position.hpp> START_ATF_NAMESPACE struct __dummy_block { char *pszBlockName; int nSubDummyNum; _dummy_position *pSubDummy[32]; public: __dummy_block(); void ctor___dummy_block(); }; END_ATF_NAMESPACE
22.368421
108
0.689412
lemkova
1afb3aca1df77617428d489f057e69b9afdbb31c
3,513
cpp
C++
src/30-days-challenge/week-4/24_lru_cache.cpp
Elzawawy/ProblemsPlayground
81d969e88bf248b30b915c62c60f14738c5191ff
[ "MIT" ]
null
null
null
src/30-days-challenge/week-4/24_lru_cache.cpp
Elzawawy/ProblemsPlayground
81d969e88bf248b30b915c62c60f14738c5191ff
[ "MIT" ]
null
null
null
src/30-days-challenge/week-4/24_lru_cache.cpp
Elzawawy/ProblemsPlayground
81d969e88bf248b30b915c62c60f14738c5191ff
[ "MIT" ]
null
null
null
/** * Author: Amr Elzawawy * Date: 24-4-2020 * Problem Name: LRUCache, Day 24 on the 30-Days LeetCode Challenge. */ /* ### Problem Design and implement a data structure for [Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU). It should support the following operations: `get` and `put`. `get(key)` - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. `put(key, value)` - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. The cache is initialized with a **positive** capacity. ### Reference Link [https://leetcode.com/problems/lru-cache/](https://leetcode.com/problems/lru-cache/) ### Solution Use a Hashtable that keeps track of the keys and its values in the double linked list. Why use List (not say vector) ? --> iterators are never invalidated by modifiers (unless erasing the element itself). --> In addition, it takes constant time to add and remove nodes from the head or tail. --> we store the iterator to the corresponding LRU queue in the values of the hash map. --> since using erase on a list with an iterator takes constant time, all operations of the LRU cache run in constant time. */ #include <map> #include <vector> #include <list> typedef std::pair<int, int> pairii; class LRUCache { /** * Your LRUCache object should be instantiated and called/used as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */ private: int max_capacity_; int curr_capacity_; std::list<pairii> items_; std::map<int, std::list<pairii>::iterator> cache_; public: explicit LRUCache(int max_capacity_) :max_capacity_(max_capacity_), curr_capacity_(0) { } int get(int key) { // if the key doesn't exist in the cache if (!cache_.count(key)) return -1; // transfers only the element pointed by cache_[key] from items_ // into the container items_ into position specified by items_.begin() items_.splice(items_.begin(), items_, cache_[key]); return cache_[key]->second; } void put(int key, int value) { // insert if the key is not already present if (!cache_.count(key)) { // if cache reached capacity, invalidate the LRU before insertion. if (curr_capacity_ == max_capacity_) evictLRU(); insertCache(key, value); } // set the key to new value if already present else updateCache(key, value); } private: void evictLRU() { curr_capacity_--; cache_.erase(items_.back().first); items_.pop_back(); } void updateCache(int key, int new_value) { //update value associated with key with new value. cache_[key]->second = new_value; // transfers only the element pointed by cache_[key] from items_ // into the container items_ into position specified by items_.begin() items_.splice(items_.begin(), items_, cache_[key]); } void insertCache(int key, int value) { curr_capacity_++; // insert new element at the beginning of the items list. items_.emplace_front(key, value); // assign in the cache with the begin() iterator value. cache_[key] = items_.begin(); } };
33.778846
203
0.660404
Elzawawy
1afc4ec5b99ad983400a0ba147a1929f1774be8b
2,401
hpp
C++
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
39
2019-03-26T08:03:44.000Z
2022-02-13T09:06:48.000Z
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
10
2019-04-08T22:18:10.000Z
2021-10-04T04:11:00.000Z
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
26
2019-03-26T08:13:42.000Z
2022-03-15T04:51:39.000Z
#pragma once #include <spdlog/spdlog.h> namespace timax { class log { public: static log& get() { static log _log; return _log; } bool init(const std::string& file_name) { try { log_ = spdlog::rotating_logger_mt("logger", file_name, 1024 * 1024 * 50, 2); console_log_ = spdlog::stdout_logger_mt("console"); } catch (std::exception&) { return false; } catch (...) { return false; } return true; } std::shared_ptr<spdlog::logger> get_log() { return log_; } std::shared_ptr<spdlog::logger> get_console_log() { return console_log_; } private: log() = default; log(const log&) = delete; log(log&&) = delete; std::shared_ptr<spdlog::logger> log_; std::shared_ptr<spdlog::logger> console_log_; }; template<typename... Args> static inline void SPD_LOG_TRACE(const char* fmt, const Args&... args) { log::get().get_log()->trace(fmt, args...); } template<typename... Args> static inline void SPD_LOG_INFO(const char* fmt, const Args&... args) { log::get().get_log()->info(fmt, args...); } //template<typename... Args> //static inline void SPD_LOG_NOTICE(const char* fmt, const Args&... args) //{ // log::get().get_log()->notice(fmt, args...); //} template<typename... Args> static inline void SPD_LOG_WARN(const char* fmt, const Args&... args) { log::get().get_log()->warn(fmt, args...); } template<typename... Args> static inline void SPD_LOG_ERROR(const char* fmt, const Args&... args) { log::get().get_log()->error(fmt, args...); } template<typename... Args> static inline void SPD_LOG_CRITICAL(const char* fmt, const Args&... args) { log::get().get_log()->critical(fmt, args...); } //template<typename... Args> //static inline void SPD_LOG_ALERT(const char* fmt, const Args&... args) //{ // log::get().get_log()->alert(fmt, args...); //} //template<typename... Args> //static inline void SPD_LOG_EMERG(const char* fmt, const Args&... args) //{ // log::get().get_log()->emerg(fmt, args...); //} template<typename... Args> static inline void SPD_LOG_DEBUG(const char* fmt, const Args&... args) { #ifdef NDEBUG #else log::get().get_log()->set_level(spdlog::level::debug); log::get().get_log()->debug(fmt, args...); log::get().get_console_log()->set_level(spdlog::level::debug); log::get().get_console_log()->debug(fmt, args...); #endif } }
21.061404
80
0.63307
emogua
1afc9e058ad577eb8042e5b5f792d339fda27820
4,922
cpp
C++
plugin/al/plugin/AL_USDMayaTestPlugin/AL/usdmaya/fileio/test_activeInActiveTranslators.cpp
goodbyekansas/maya-usd
648df109398e2f82b4be3def4dad241ad74fe961
[ "Apache-2.0" ]
null
null
null
plugin/al/plugin/AL_USDMayaTestPlugin/AL/usdmaya/fileio/test_activeInActiveTranslators.cpp
goodbyekansas/maya-usd
648df109398e2f82b4be3def4dad241ad74fe961
[ "Apache-2.0" ]
1
2019-11-22T14:38:00.000Z
2019-11-22T14:38:00.000Z
plugin/al/plugin/AL_USDMayaTestPlugin/AL/usdmaya/fileio/test_activeInActiveTranslators.cpp
goodbyekansas/maya-usd
648df109398e2f82b4be3def4dad241ad74fe961
[ "Apache-2.0" ]
null
null
null
// // Copyright 2019 Animal Logic // // 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 <maya/MGlobal.h> #include <maya/MFileIO.h> #include <maya/MString.h> #include "test_usdmaya.h" #include <pxr/usd/sdf/types.h> #include <pxr/usd/usd/attribute.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/usdaFileFormat.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <pxr/usd/usdGeom/mesh.h> using AL::maya::test::buildTempPath; // export a poly cube with all translators disabled, and no TEST(PluginTranslators, activeInactive1) { MFileIO::newFile(true); const char* const create_cmd = "polyCube;"; std::string export_cmd = R"( file -force -options "Merge_Transforms=1;Animation=0;Export_At_Which_Time=2;Export_In_World_Space=1;Activate_all_Plugin_Translators=0;Active_Translator_List=;Meshes=1;Mesh_Face_Connects=1;Mesh_Points=1;Mesh_UV_Only=0;" -typ "AL usdmaya export" -pr -es )"; auto path = buildTempPath("AL_USDMayaTests_ativeInactiveTranslators1.usda"); export_cmd += "\""; export_cmd += path; export_cmd += "\""; MGlobal::executeCommand(create_cmd); MGlobal::executeCommand(export_cmd.c_str()); UsdStageRefPtr stage = UsdStage::Open(path); EXPECT_TRUE(stage); // resulting prim should exist (as a transform), but will not be a mesh. UsdPrim prim = stage->GetPrimAtPath(SdfPath("/pCube1")); EXPECT_TRUE(prim.IsValid()); EXPECT_FALSE(prim.IsA<UsdGeomMesh>()); } // export a polyCube with all translators disabled, but with the mesh translator enabled. TEST(PluginTranslators, activeInactive2) { MFileIO::newFile(true); const char* const create_cmd = "polyCube;"; std::string export_cmd = R"( file -force -options "Merge_Transforms=1;Animation=0;Export_At_Which_Time=2;Export_In_World_Space=1;Activate_all_Plugin_Translators=0;Active_Translator_List=UsdGeomMesh;Meshes=1;Mesh_Face_Connects=1;Mesh_Points=1;Mesh_UV_Only=0;" -typ "AL usdmaya export" -pr -es )"; auto path = buildTempPath("AL_USDMayaTests_ativeInactiveTranslators2.usda"); export_cmd += "\""; export_cmd += path; export_cmd += "\""; MGlobal::executeCommand(create_cmd); MGlobal::executeCommand(export_cmd.c_str()); UsdStageRefPtr stage = UsdStage::Open(path); EXPECT_TRUE(stage); UsdPrim prim = stage->GetPrimAtPath(SdfPath("/pCube1")); EXPECT_TRUE(prim.IsValid()); EXPECT_TRUE(prim.IsA<UsdGeomMesh>()); } // export a polyCube with all translators enabled, but with the mesh translator disabled. TEST(PluginTranslators, activeInactive3) { MFileIO::newFile(true); const char* const create_cmd = "polyCube;"; std::string export_cmd = R"( file -force -options "Merge_Transforms=1;Animation=0;Export_At_Which_Time=2;Export_In_World_Space=1;Activate_all_Plugin_Translators=1;Active_Translator_List=;Inactive_Translator_List=;Meshes=1;Mesh_Face_Connects=1;Mesh_Points=1;Mesh_UV_Only=0;" -typ "AL usdmaya export" -pr -es )"; auto path = buildTempPath("AL_USDMayaTests_ativeInactiveTranslators3.usda"); export_cmd += "\""; export_cmd += path; export_cmd += "\""; MGlobal::executeCommand(create_cmd); MGlobal::executeCommand(export_cmd.c_str()); UsdStageRefPtr stage = UsdStage::Open(path); EXPECT_TRUE(stage); // resulting prim should exist (as a transform), but will not be a mesh. UsdPrim prim = stage->GetPrimAtPath(SdfPath("/pCube1")); EXPECT_TRUE(prim.IsValid()); EXPECT_TRUE(prim.IsA<UsdGeomMesh>()); } // export a poly cube with all translators enabled, and no optionally disabled translators TEST(PluginTranslators, activeInactive4) { MFileIO::newFile(true); const char* const create_cmd = "polyCube;"; std::string export_cmd = R"( file -force -options "Merge_Transforms=1;Animation=0;Export_At_Which_Time=2;Export_In_World_Space=1;Activate_all_Plugin_Translators=1;Active_Translator_List=;Inactive_Translator_List=UsdGeomMesh;Meshes=1;Mesh_Face_Connects=1;Mesh_Points=1;Mesh_UV_Only=0;" -typ "AL usdmaya export" -pr -es )"; auto path = buildTempPath("AL_USDMayaTests_ativeInactiveTranslators4.usda"); export_cmd += "\""; export_cmd += path; export_cmd += "\""; MGlobal::executeCommand(create_cmd); MGlobal::executeCommand(export_cmd.c_str()); UsdStageRefPtr stage = UsdStage::Open(path); EXPECT_TRUE(stage); UsdPrim prim = stage->GetPrimAtPath(SdfPath("/pCube1")); EXPECT_TRUE(prim.IsValid()); EXPECT_FALSE(prim.IsA<UsdGeomMesh>()); }
37.861538
290
0.750508
goodbyekansas
1afee429b5d65373d88f8a49dce90955d4c0967d
2,024
cpp
C++
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #include "NstInpDevice.hpp" #include "NstInpPokkunMoguraa.hpp" namespace Nes { namespace Core { namespace Input { #ifdef NST_MSVC_OPTIMIZE #pragma optimize("s", on) #endif PokkunMoguraa::PokkunMoguraa(const Cpu& c) : Device(c,Api::Input::POKKUNMOGURAA) { PokkunMoguraa::Reset(); } void PokkunMoguraa::Reset() { state = 0x1E; } void PokkunMoguraa::SaveState(State::Saver& saver,const byte id) const { saver.Begin( AsciiId<'P','M'>::R(0,0,id) ).End(); } #ifdef NST_MSVC_OPTIMIZE #pragma optimize("", on) #endif void PokkunMoguraa::Poke(const uint data) { if (input) { Controllers::PokkunMoguraa::callback( input->pokkunMoguraa, ~data & 0x7 ); state = ~input->pokkunMoguraa.buttons & 0x1E; } else { state = 0x1E; } } uint PokkunMoguraa::Peek(const uint port) { return port ? state : 0; } } } }
25.948718
89
0.585968
slajerek
210094eb13c78b6fa92ded5a7ea07a13661ae517
887
cxx
C++
FastCaloSimAnalyzer/FastCaloGpu/src/Rand4Hits_cpu.cxx
atif4461/FCS-GPU
181865f55d299287873f99c777aad2ef9404e961
[ "Apache-2.0" ]
2
2022-01-25T20:32:53.000Z
2022-02-16T01:15:47.000Z
FastCaloSimAnalyzer/FastCaloGpu/src/Rand4Hits_cpu.cxx
atif4461/FCS-GPU
181865f55d299287873f99c777aad2ef9404e961
[ "Apache-2.0" ]
null
null
null
FastCaloSimAnalyzer/FastCaloGpu/src/Rand4Hits_cpu.cxx
atif4461/FCS-GPU
181865f55d299287873f99c777aad2ef9404e961
[ "Apache-2.0" ]
1
2022-02-11T15:54:10.000Z
2022-02-11T15:54:10.000Z
/* Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration */ #include <random> #include <vector> #include <algorithm> #define cpu_randgen_t std::mt19937 void Rand4Hits::createCPUGen( unsigned long long seed ) { cpu_randgen_t* eng = new cpu_randgen_t( seed ); m_gen = (void*)eng; } void Rand4Hits::destroyCPUGen() { if ( m_gen ) { delete (cpu_randgen_t*)m_gen; } } float* Rand4Hits::genCPU( size_t num ) { m_rnd_cpu.resize( num ); cpu_randgen_t* eng = (cpu_randgen_t*)( m_gen ); auto RNG = [eng]( float low, float high ) { auto randomFunc = [distribution_ = std::uniform_real_distribution<float>( low, high ), random_engine_ = *eng]() mutable { return distribution_( random_engine_ ); }; return randomFunc; }; std::generate_n( m_rnd_cpu.begin(), num, RNG( 0.f, 1.f ) ); return m_rnd_cpu.data(); }
25.342857
100
0.657272
atif4461
210474d24dfa9b30f862bc59e3d3dfcb4995fb91
2,771
cpp
C++
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
/******************************************************************************/ /*! @file Bullet.cpp @brief 弾クラス実装ファイル *******************************************************************************/ #include "Bullet.h" #include <DxLib.h> using namespace Shooting2D; /******************************************************************************/ /*! コンストラクタ *******************************************************************************/ CBullet::CBullet() : CGameObject() , m_SpeedX(0.0f) , m_SpeedY(0.0f) , m_Angle(0.0f) , m_Image(-1) { } /******************************************************************************/ /*! デストラクタ *******************************************************************************/ CBullet::~CBullet() { } /******************************************************************************/ /*! 弾の初期化 @param[in] px 初期位置X @param[in] py 初期位置Y @param[in] sx スピードX @param[in] sy スピードY @param[in] iw 画像幅 @param[in] ih 画像高さ @param[in] img 画像ID @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Initialize(MyFloat px, MyFloat py, MyFloat sx, MyFloat sy, MyS32 iw, MyS32 ih, MyInt img) { m_bShow = true; m_PosX = px; m_PosY = py; m_SpeedX = sx; m_SpeedY = sy; m_Angle = atan2f(sy, sx) + ToRadian(90); m_Width = iw; m_Height = ih; m_Image = img; m_Radius = 4; return k_Success; } /******************************************************************************/ /*! 弾の更新 @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Update() { // 非表示のため動作なし if (!m_bShow) { return k_Success; } // 速度で等速移動 m_PosX += m_SpeedX; m_PosY += m_SpeedY; // 画面外で消去 if (m_PosX < -m_Width || m_PosY < -m_Height || m_PosX > k_SceneWidth + m_Width || m_PosY > k_SceneHeight + m_Height) { m_bShow = false; } return k_Success; } /******************************************************************************/ /*! 弾の描画 @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Draw() { // 非表示のため描画なし if (!m_bShow) { return k_Success; } MyInt drawPosX = k_SceneOffsetX + m_PosX + k_BulletDrawOffsetX; MyInt drawPosY = k_SceneOffsetY + m_PosY + k_BulletDrawOffsetY; DxLib::DrawRotaGraph(drawPosX, drawPosY, 1.0f, m_Angle, m_Image, true); #ifdef MY_DEBUG DxLib::DrawCircle(m_PosX, m_PosY, m_Radius, DxLib::GetColor(0, 0, 0)); #endif //MY_DEBUG return k_Success; }
29.478723
104
0.381451
KoreanGinseng
2105620576082643d5af067788e47a9e9b9caba9
2,367
cpp
C++
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
2
2018-06-06T02:01:08.000Z
2020-07-25T18:10:32.000Z
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
10
2018-07-27T01:56:45.000Z
2019-02-23T01:49:36.000Z
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
null
null
null
#include "TextureAtlasController.hpp" /* MIT License Copyright (c) 2018 Scott Bengs 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. */ TextureAtlasController::TextureAtlasController() { index_size = 0; } void TextureAtlasController::addAtlas(TextureAtlas& atlas) { atlases.push_back(atlas); if (getSize() == 1) { starts.push_back(0); //number of textures in the atlas * index size //so for example, using rectangles you need 24 bytes per texture * atlas size //24 = 6 index * 4 bytes each(unsigned int) } else { unsigned int total = 0; for (unsigned int n = 0; n < getSize()-1; n++) { total += total + atlases.at(n).getAtlasSize(); } starts.push_back(total * getIndexSize()); } } TextureAtlas& TextureAtlasController::modifyAtlas(unsigned int index) { return atlases.at(index); } //gets const TextureAtlas& TextureAtlasController::getAtlas(unsigned int index) { return atlases.at(index); } unsigned int TextureAtlasController::getAtlasStart(unsigned int index) const { return starts.at(index); } unsigned int TextureAtlasController::getIndexSize() const { return index_size; } unsigned int TextureAtlasController::getSize() const { return atlases.size(); } //sets void TextureAtlasController::setIndexSize(unsigned int size) { index_size = size; }
28.178571
85
0.73215
swbengs
210a5846b9aeda6a95bb7e9f8ff061231fd32f4b
19,206
cpp
C++
MultiWii/Telemetry.cpp
RocketRedNeck/ArduinoPlayground
13998ba6f5809bccd57a37cbd62720b8a075a0e1
[ "MIT" ]
null
null
null
MultiWii/Telemetry.cpp
RocketRedNeck/ArduinoPlayground
13998ba6f5809bccd57a37cbd62720b8a075a0e1
[ "MIT" ]
10
2018-09-16T04:54:52.000Z
2018-10-24T11:03:49.000Z
MultiWii/Telemetry.cpp
RocketRedNeck/ArduinoPlayground
13998ba6f5809bccd57a37cbd62720b8a075a0e1
[ "MIT" ]
1
2018-09-22T06:52:10.000Z
2018-09-22T06:52:10.000Z
// **************************************************************** // FrSky telemetry // Version: 0.4.0 - by QuadBow // Changes: V0.4.0: - supports 2.4 with new features added // device specific selection of data to be sent // different ways for displaying // different ways to present data // Version: 0.3.0 // Changes: V0.3.0: - new structure with cpp/h-files // Date 20/09/2012 // Changes: V0.2.1: - make it work with 2.1 (shared dev) // Date: 14/08/2012 // Changes: V0.2: - Byte stuffing added // - vBat will be send, if "#define FAS_100" is comment out // V0.1: - First release // **************************************************************** #include "Arduino.h" #include "config.h" #include "def.h" #include "types.h" #include "MultiWii.h" #include "Sensors.h" #include "Serial.h" #include "Telemetry.h" #if defined(FRSKY_TELEMETRY) void init_telemetry(void) { SerialOpen(TELEMETRY_SERIAL,TELEMETRY_BAUD); } void write_FrSky8(uint8_t Data) { SerialWrite(TELEMETRY_SERIAL, Data); } void check_FrSky_stuffing(uint8_t Data) //byte stuffing { if (Data == 0x5E) { write_FrSky8(0x5D); write_FrSky8(0x3E); } else if (Data == 0x5D) { write_FrSky8(0x5D); write_FrSky8(0x3D); } else { write_FrSky8(Data); } } void write_FrSky16(uint16_t Data) { uint8_t Data_send; Data_send = Data; check_FrSky_stuffing(Data_send); Data_send = Data >> 8 & 0xff; check_FrSky_stuffing(Data_send); } static void sendDataHead(uint8_t Data_id) { write_FrSky8(Protocol_Header); write_FrSky8(Data_id); } static void sendDataTail(void) { write_FrSky8(Protocol_Tail); } //********************************************************************************* //----------------- Telemetrie Data ------------------------------------------ //********************************************************************************* // Temperature and NumSats void inline send_Temperature(void) { #if BARO int16_t Data_Temperature1; Data_Temperature1 = (baroTemperature + 50) / 100; sendDataHead(ID_Temperature1); write_FrSky16(Data_Temperature1); #endif #if GPS int16_t Data_NumSats; if (f.GPS_FIX && GPS_numSat >= 4) { Data_NumSats = GPS_numSat; sendDataHead(ID_Temperature2); write_FrSky16(Data_NumSats); } #endif } // RPM is interpreted as Return distance to home Position in Meter void inline send_RPM(void) { #if GPS uint16_t Data_RPM; if (f.GPS_FIX && GPS_numSat >= 4) { Data_RPM = GPS_distanceToHome; // Distance to home alias RPM sendDataHead(ID_RPM); write_FrSky16(Data_RPM); } #endif } // Fuel level void inline send_Fuel(void) { #if defined(POWERMETER) uint16_t Data_Fuel; if ((pMeter[PMOTOR_SUM] < (pAlarm / 4)) || (pAlarm == 0)) Data_Fuel = 100; else if (pMeter[PMOTOR_SUM] < (pAlarm / 2)) Data_Fuel = 75; else if (pMeter[PMOTOR_SUM] < (3 * pAlarm / 4)) Data_Fuel = 50; else if (pMeter[PMOTOR_SUM] < pAlarm) Data_Fuel = 25; else Data_Fuel = 0; sendDataHead(ID_Fuel_level); write_FrSky16(Data_Fuel); #endif } // Cell voltage void inline send_cell_volt(void) // Data compatibel to FrSky FLVS-01 voltage sensor { #if defined(VBAT_CELLS) uint16_t Data_Volt; uint16_t temp; static uint8_t cell_counter = 0; // the resolution of analog.vbatcells results in only one decimal (eg 3.70V or 3.80V and nothing in between) // TODO: improve resolution of analog.vbatcells temp = 50 * analog.vbatcells[cell_counter]; Data_Volt = (temp << 8) + (temp >> 8) + (cell_counter << 4); if (++cell_counter >= VBAT_CELLS_NUM) cell_counter = 0; sendDataHead(ID_Volt); write_FrSky16(Data_Volt); #endif } // Altitude void inline send_Altitude(void) { #if defined(TELEMETRY_ALT_BARO) and BARO #if defined(FRSKY_FLD02) int16_t Data_altitude; Data_altitude = (alt.EstAlt + 50) / 100; sendDataHead(ID_Altitude_bp); write_FrSky16(Data_altitude); #endif #if defined OPENTX int16_t Data_altitude_bp, Data_altitude_ap; Data_altitude_bp = alt.EstAlt / 100; sendDataHead(ID_Altitude_bp); write_FrSky16(Data_altitude_bp); Data_altitude_ap = alt.EstAlt - Data_altitude_bp * 100; sendDataHead(ID_Altitude_ap); write_FrSky16(Data_altitude_ap); #endif #endif #if defined(TELEMETRY_ALT_GPS) and GPS #if defined(FRSKY_FLD02) #if not defined(TELEMETRY_ALT_BARO) int16_t Data_altitude; if (f.GPS_FIX && GPS_numSat >= 4) { Data_altitude = GPS_altitude; sendDataHead(ID_Altitude_bp); write_FrSky16(Data_altitude); } #endif #else int16_t Data_GPS_altitude_bp; uint16_t Data_GPS_altitude_ap; if (f.GPS_FIX && GPS_numSat >= 4) { Data_GPS_altitude_bp = GPS_altitude; Data_GPS_altitude_ap = 0; sendDataHead(ID_GPS_Altitude_bp); write_FrSky16(Data_GPS_altitude_bp); sendDataHead(ID_GPS_Altitude_ap); write_FrSky16(Data_GPS_altitude_ap); } #endif #endif } // Course void inline send_Course(void) { #if not defined(FRSKY_FLD02) #if defined TELEMETRY_COURSE_GPS and GPS uint16_t Data_Course_bp; uint16_t Data_Course_ap; if (f.GPS_FIX && GPS_numSat >= 4) { Data_Course_bp = GPS_ground_course / 10; Data_Course_ap = GPS_ground_course - Data_Course_bp * 10; sendDataHead(ID_Course_bp); write_FrSky16(Data_Course_bp); sendDataHead(ID_Course_ap); write_FrSky16(Data_Course_ap); } #elif defined TELEMETRY_COURSE_MAG and MAG uint16_t Data_Course_bp; uint16_t Data_Course_ap; Data_Course_bp = att.heading; Data_Course_ap = 0; sendDataHead(ID_Course_bp); write_FrSky16(Data_Course_bp); sendDataHead(ID_Course_ap); write_FrSky16(Data_Course_ap); #endif #endif } // GPS speed void inline send_GPS_speed(void) { #if GPS uint16_t Data_GPS_speed_bp; uint16_t Data_GPS_speed_ap; uint16_t temp; if (f.GPS_FIX && GPS_numSat >= 4) { #if defined KILOMETER_HOUR // OPENTX specific format in kilometers per hour => factor 36/100 (will be devided by 10 later) temp = (GPS_speed * 36) / 10; #else // FRSKY specific format in knots => factor ~50 (will be devided by 10 later) temp = (GPS_speed * 40) / 203; #endif Data_GPS_speed_bp = temp / 10; // here comes the devision by 10 Data_GPS_speed_ap = temp - Data_GPS_speed_bp * 10; sendDataHead(ID_GPS_speed_bp); write_FrSky16(Data_GPS_speed_bp); sendDataHead(ID_GPS_speed_ap); write_FrSky16(Data_GPS_speed_ap); } #endif } // GPS position void inline send_GPS_longitude(void) { #if GPS uint16_t Data_Longitude_bp; uint16_t Data_Longitude_ap; uint16_t Data_E_W; uint32_t temp, rest, decimal; if (f.GPS_FIX && GPS_numSat >= 4) { temp = abs(GPS_coord[LON]); #if defined(COORDFORMAT_DECIMALMINUTES) decimal = temp / 10000000; temp -= decimal * 10000000; temp *= 6; rest = temp; temp /= 1000000; rest -= temp * 1000000; Data_Longitude_bp = decimal * 100 + temp; Data_Longitude_ap = rest / 100; #else decimal = temp / 100000; rest = temp - decimal * 100000; Data_Longitude_bp = decimal; Data_Longitude_ap = rest / 100; #endif Data_E_W = GPS_coord[LON] < 0 ? 'W' : 'E'; sendDataHead(ID_Longitude_bp); write_FrSky16(Data_Longitude_bp); sendDataHead(ID_Longitude_ap); write_FrSky16(Data_Longitude_ap); sendDataHead(ID_E_W); write_FrSky16(Data_E_W); } #endif } void inline send_GPS_latitude(void) { #if GPS uint16_t Data_Latitude_bp; uint16_t Data_Latitude_ap; uint16_t Data_N_S; uint32_t temp, rest, decimal; if (f.GPS_FIX && GPS_numSat >= 4) { temp = abs(GPS_coord[LAT]); #if defined(COORDFORMAT_DECIMALMINUTES) decimal = temp / 10000000; temp -= decimal * 10000000; temp *= 6; rest = temp; temp /= 1000000; rest -= temp * 1000000; Data_Latitude_bp = decimal * 100 + temp; Data_Latitude_ap = rest / 100; #else decimal = temp / 100000; rest = temp - decimal * 100000; Data_Latitude_bp = decimal * 100 + temp; Data_Latitude_ap = rest / 100; #endif Data_N_S = GPS_coord[LAT] < 0 ? 'S' : 'N'; sendDataHead(ID_Latitude_bp); write_FrSky16(Data_Latitude_bp); sendDataHead(ID_Latitude_ap); write_FrSky16(Data_Latitude_ap); sendDataHead(ID_N_S); write_FrSky16(Data_N_S); } #endif } // Time of arming void inline send_Time(void) { uint16_t seconds_since_start; uint16_t Data_rest; uint16_t Data_hours; uint16_t Data_minutes; uint16_t Data_seconds; if (f.ARMED) { seconds_since_start = armedTime / 1000000; Data_hours = seconds_since_start / 3600; Data_rest = seconds_since_start - Data_hours * 3600; Data_minutes = Data_rest / 60; Data_seconds = Data_rest - Data_minutes * 60; sendDataHead(ID_Hour_Minute); write_FrSky16(Data_hours + Data_minutes * 256); sendDataHead(ID_Second); write_FrSky16(Data_seconds); } } // ACC void inline send_Accel(void) { #if ACC int16_t Data_Acc_X; int16_t Data_Acc_Y; int16_t Data_Acc_Z; Data_Acc_X = ((float)imu.accSmooth[0] / ACC_1G) * 1000; Data_Acc_Y = ((float)imu.accSmooth[1] / ACC_1G) * 1000; Data_Acc_Z = ((float)imu.accSmooth[2] / ACC_1G) * 1000; sendDataHead(ID_Acc_X); write_FrSky16(Data_Acc_X); sendDataHead(ID_Acc_Y); write_FrSky16(Data_Acc_Y); sendDataHead(ID_Acc_Z); write_FrSky16(Data_Acc_Z); #endif } // Voltage (Ampere Sensor) void inline send_Voltage_ampere(void) // Data compatibel to FrSky FAS-100 voltage sensor, FLD-02 uses only analog data A1 and A2 { #if defined (VBAT) and not defined(FRSKY_FLD02) #if defined OPENTX uint16_t voltage; voltage = analog.vbat * 10; // for OpenTX send the number of 1/10th of volt sendDataHead(ID_VFAS); write_FrSky16(voltage); #else uint16_t voltage; uint16_t Data_Voltage_vBat_bp; uint16_t Data_Voltage_vBat_ap; voltage = ((analog.vbat * 110) / 21); Data_Voltage_vBat_bp = voltage / 100; sendDataHead(ID_Voltage_Amp_bp); write_FrSky16(Data_Voltage_vBat_bp); Data_Voltage_vBat_ap = ((voltage % 100) + 5) / 10; sendDataHead(ID_Voltage_Amp_ap); write_FrSky16(Data_Voltage_vBat_ap); #endif #endif #if defined(POWERMETER) uint16_t Data_Voltage_I_Motor; Data_Voltage_I_Motor = analog.amperage; sendDataHead(ID_Current); write_FrSky16(Data_Voltage_I_Motor); #endif } // Main function FrSky telemetry void run_telemetry(void) { static uint32_t lastTime; static uint8_t tele_loop; if ((millis() - lastTime) > 125) { // Data sent every 125ms due to scheduler lastTime = millis(); tele_loop++; switch (tele_loop) { case 1: send_Voltage_ampere(); send_Accel(); break; case 2: send_Fuel(); send_GPS_longitude(); break; case 3: send_Temperature(); send_Accel(); break; case 4: send_Altitude(); send_GPS_speed(); send_Course(); break; case 5: send_Voltage_ampere(); send_Accel(); break; case 6: send_RPM(); send_GPS_latitude(); break; case 7: send_GPS_speed(); send_Accel(); send_cell_volt(); break; default: send_Altitude(); send_Time(); tele_loop = 0; break; } sendDataTail(); } } #endif // FRSKY telemetry #if defined(SPORT_TELEMETRY) static short _FrSkySport_crc; static short _currentGPSValue; void FrSkySport_sendByte(uint8_t byte) { // CRC update _FrSkySport_crc += byte; //0-1FF _FrSkySport_crc += _FrSkySport_crc >> 8; //0-100 _FrSkySport_crc &= 0x00ff; _FrSkySport_crc += _FrSkySport_crc >> 8; //0-0FF _FrSkySport_crc &= 0x00ff; if ( (byte == FRSKY_START_STOP) || (byte == FRSKY_BYTESTUFF) ) { SerialWrite(TELEMETRY_SERIAL, FRSKY_BYTESTUFF); byte &= ~FRSKY_STUFF_MASK; } SerialWrite(TELEMETRY_SERIAL, byte); } void FrSkySport_sendCrc() { FrSkySport_sendByte(0xFF - _FrSkySport_crc); } void FrSkySport_sendValue(uint16_t id, uint32_t value) { _FrSkySport_crc = 0; // Reset CRC FrSkySport_sendByte(0x10); // DATA_FRAME uint8_t *bytes = (uint8_t*)&id; FrSkySport_sendByte(bytes[0]); FrSkySport_sendByte(bytes[1]); bytes = (uint8_t*)&value; FrSkySport_sendByte(bytes[0]); FrSkySport_sendByte(bytes[1]); FrSkySport_sendByte(bytes[2]); FrSkySport_sendByte(bytes[3]); FrSkySport_sendCrc(); } void FrSkySport_sendA2voltage() { #ifdef VBAT uint32_t opentx_val = (255.0 * (float)(analog.vbat / (float)FRSKY_SPORT_A2_MAX)); FrSkySport_sendValue(FRSKY_SPORT_ADC2_ID, (opentx_val)); #endif } uint32_t FrSkySport_EncodeCoordinate(float latLon, bool isLat) { #if GPS uint32_t otx_coord = 0; if (!isLat) { otx_coord = abs(latLon); // now we have unsigned value and one bit to spare otx_coord = (otx_coord + otx_coord / 2) / 25 | 0x80000000; // 6/100 = 1.5/25, division by power of 2 is fast if (latLon < 0) otx_coord |= 0x40000000; } else { otx_coord = abs(latLon); // now we have unsigned value and one bit to spare otx_coord = (otx_coord + otx_coord / 2) / 25; // 6/100 = 1.5/25, division by power of 2 is fast if (latLon < 0) otx_coord |= 0x40000000; } return otx_coord; #endif } void FrSkySport_sendGPSCoordinate() { #if GPS uint32_t GPSValueToSend = 0; if (f.GPS_FIX && GPS_numSat >= 4) { switch (_currentGPSValue) { case 0: GPSValueToSend = FrSkySport_EncodeCoordinate(GPS_coord[LON], false); _currentGPSValue = 1; break; case 1: GPSValueToSend = FrSkySport_EncodeCoordinate(GPS_coord[LAT], true); _currentGPSValue = 0; break; } FrSkySport_sendValue(FRSKY_SPORT_GPS_LONG_LATI_ID, GPSValueToSend); } #endif } void FrSkySport_sendGPSAltitude() { #if defined(TELEMETRY_ALT_GPS) and GPS if (f.GPS_FIX && GPS_numSat >= 4) { FrSkySport_sendValue(FRSKY_SPORT_GPS_ALT_ID, (int32_t)(GPS_altitude)); // m??? } #endif } void FrSkySport_sendGPSSpeed() { #if GPS if (f.GPS_FIX && GPS_numSat >= 4) { uint32_t speed = ((float)GPS_speed * 100); FrSkySport_sendValue(FRSKY_SPORT_GPS_SPEED_ID, speed); // unknown unit, just a guess } #endif } void FrSkySport_sendAltitude() { #if defined(TELEMETRY_ALT_BARO) and BARO FrSkySport_sendValue(FRSKY_SPORT_ALT_ID, (int32_t)(alt.EstAlt) * 100); // cm #endif } void FrSkySport_sendHeading() { #if defined(TELEMETRY_COURSE_MAG) or (defined(TELEMETRY_COURSE_GPS) and GPS) #if defined(TELEMETRY_COURSE_MAG) uint32_t otx_heading = (uint32_t)(att.heading + 360) % 360 * 100; FrSkySport_sendValue(FRSKY_SPORT_GPS_COURS_ID, otx_heading); // 1 deg = 100, 0 - 359000 #elif defined(TELEMETRY_COURSE_GPS) && defined(GPS) if (f.GPS_FIX && GPS_numSat >= 4) { uint32_t otx_heading = (uint32_t)(GPS_ground_course + 360) % 360 * 100; FrSkySport_sendValue(FRSKY_SPORT_GPS_COURS_ID, otx_heading); // 1 deg = 100, 0 - 359000 } #endif #endif } void FrSkySport_sendACCX() { #ifdef ACC FrSkySport_sendValue(FRSKY_SPORT_ACCX_ID, imu.accSmooth[0] / 5); // unknown unit #endif } void FrSkySport_sendACCY() { #ifdef ACC FrSkySport_sendValue(FRSKY_SPORT_ACCY_ID, imu.accSmooth[1] / 5); // unknown unit #endif } void FrSkySport_sendACCZ() { #ifdef ACC FrSkySport_sendValue(FRSKY_SPORT_ACCZ_ID, imu.accSmooth[2] / 5); // unknown unit #endif } void FrSkySport_sendAltVario() { #ifdef VARIOMETER FrSkySport_sendValue(FRSKY_SPORT_VARIO_ID, ((uint32_t)alt.vario)); // unknown unit #endif } void init_telemetry(void) { _currentGPSValue = 0; SerialOpen(TELEMETRY_SERIAL,TELEMETRY_BAUD); } void run_telemetry(void) { static uint8_t lastRx = 0; uint8_t c = SerialAvailable(TELEMETRY_SERIAL); while (c--) { int rx = SerialRead(TELEMETRY_SERIAL); if (lastRx == FRSKY_START_STOP) { debug[1] = rx; switch (rx) { case FRSKY_SPORT_DEVICE_4: FrSkySport_sendA2voltage(); break; case FRSKY_SPORT_DEVICE_8: FrSkySport_sendACCX(); break; case FRSKY_SPORT_DEVICE_9: FrSkySport_sendACCY(); break; case FRSKY_SPORT_DEVICE_10: FrSkySport_sendACCZ(); break; case FRSKY_SPORT_DEVICE_11: FrSkySport_sendAltitude(); break; case FRSKY_SPORT_DEVICE_12: FrSkySport_sendAltVario(); break; case FRSKY_SPORT_DEVICE_13: FrSkySport_sendHeading(); break; case FRSKY_SPORT_DEVICE_14: FrSkySport_sendGPSSpeed(); break; case FRSKY_SPORT_DEVICE_15: FrSkySport_sendGPSAltitude(); break; case FRSKY_SPORT_DEVICE_16: FrSkySport_sendGPSCoordinate(); break; } } lastRx = rx; } } #endif // S.PORT telemetry
29.322137
170
0.585494
RocketRedNeck
210a6386dbb89d43f1738b76a6cc3b55bac54390
1,170
cpp
C++
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
4
2016-08-22T21:06:46.000Z
2021-02-28T02:06:52.000Z
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
null
null
null
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
null
null
null
#include "sense-hat-sim.h" #include <memory> SenseHAT::ISenseHAT *HATInstance = nullptr; SenseHAT::SenseHATSim::SenseHATSim() : ISenseHAT() { LEDMatrix = std::make_unique<SenseHAT::SenseHATLedMatrixSim>(); } double SenseHAT::SenseHATSim::get_humidity() { return 0.0; } double SenseHAT::SenseHATSim::get_pressure() { return 0.0; } SenseHAT::d3 SenseHAT::SenseHATSim::get_gyro() { return{ 0, 0, 0, true }; } SenseHAT::d3 SenseHAT::SenseHATSim::get_accel() { return{ 0, 0, 0, true }; } SenseHAT::d3 SenseHAT::SenseHATSim::get_magno() { return{ 0, 0, 0, true }; } SenseHAT::ISenseHAT * SenseHAT::SenseHATSim::Instance() { if (HATInstance == nullptr) { HATInstance = new SenseHAT::SenseHATSim(); } return HATInstance; } SenseHAT::d3 SenseHAT::SenseHATSim::get_temperature() { return {0,0,0,true}; } SenseHAT::SenseHATLedMatrixSim::SenseHATLedMatrixSim() : ISenseHATLEDMatrix() { } void SenseHAT::SenseHATLedMatrixSim::Clear() { } void SenseHAT::SenseHATLedMatrixSim::SetPixel(int x, int y, uint8_t r, uint8_t g, uint8_t b) { } void SenseHAT::SenseHATLedMatrixSim::SetFromRgbaMatrix(const SenseHATColor_t matrix[8][8]) { }
17.727273
92
0.702564
partouf
210b0a849964627fdfa84cf20b6d61a947dd059e
185
hpp
C++
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "length.hpp" #include "agl/glsl/vec/vec.hpp" namespace agl { template<std::size_t N> Vec<float, N> normalize(Vec<float, N> v) { return v / length(v); } }
12.333333
42
0.654054
the-last-willy
2111129de076626ac8aaf1ebd0cf388996581daf
809
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_TypeParam.cpp // #include "smtc_TypeParam.h" #ifndef LZZ_ENABLE_INLINE #include "smtc_TypeParam.inl" #endif // semantic #include "smtc_NameToString.h" // util #include "util_AppendWithSpace.h" #define LZZ_INLINE inline namespace smtc { TypeParam::TypeParam (NamePtr const & name, CvType const & def_type) : Param (name), m_def_type (def_type) {} } namespace smtc { TypeParam::~ TypeParam () {} } namespace smtc { util::String TypeParam::toString (bool is_decl) const { using namespace util; String str = "typename"; appendWithSpace (str, nameToString (getName ())); if (is_decl && m_def_type.isSet ()) { appendWithSpace (str, '='); appendWithSpace (str, m_def_type.toString ()); } return str; } } #undef LZZ_INLINE
19.731707
70
0.657602
SuperDizor
21124349da68be1962e218b0f535e63536a9d0c0
1,965
cpp
C++
2017.7.31/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.7.31/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.7.31/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<stack> using namespace std; const int maxn=1e7+5; int cnt; struct node{ node *next[26]; node *fail; int sum; }; node *root; char key[70]; node *q[maxn]; int head,tail; node *newnode; char pattern[maxn]; int N; void Insert(char *s){ node *p=root; for(int i=0;s[i]!='\0';i++){ int x=s[i]-'a'; if(p->next[x]==NULL){ newnode=(struct node *)malloc(sizeof(struct node)); for(int j=0;j<26;j++){ newnode->next[j]=0; } newnode->fail=0; newnode->sum=0; p->next[x]=newnode; } p=p->next[x]; } p->sum++; } void build_fail_pointer(){ head=0; tail=1; q[head]=root; node *p; node *temp; while(head<tail){ temp=q[head]; head++; for(int i=0;i<26;i++){ if(temp->next[i]){ if(temp==root){ temp->next[i]->fail=root; } else{ p=temp->fail; while(p){ if(p->next[i]){ temp->next[i]->fail=p->next[i]; break; } p=p->fail; } if(p==NULL)temp->next[i]->fail=root; } q[tail]=temp->next[i]; tail++; } } } } void ac_automation(char *ch){ node *p=root; int len=strlen(ch); for(int i=0;i<len;i++){ int x=ch[i]-'a'; while(!p->next[x]&&p!=root)p=p->fail; p=p->next[x]; if(!p)p=root; node *temp=p; while(temp!=root){ if(temp->sum>=0){ cnt+=temp->sum; temp->sum=-1; } else break; temp=temp->fail; } } } int main(){ freopen("test.txt","r",stdin); int i,j; int t; scanf("%d",&t); while(t--){ root=(struct node *)malloc(sizeof(struct node)); for(i=0;i<26;i++){ root->next[i]=0; } root->sum=0; root->fail=0; scanf("%d",&N); //getchar(); while(N--){ scanf("%s",key); Insert(key); } scanf("%s",pattern); cnt=0; build_fail_pointer(); ac_automation(pattern); printf("%d\n",cnt); } return 0; }
16.239669
54
0.557761
1980744819
21142c439651ee57d4aca1b25a5ba4d9f24fbb36
887
cpp
C++
ace/tests/classix/CLASSIX_OS_Test.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tests/classix/CLASSIX_OS_Test.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tests/classix/CLASSIX_OS_Test.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* -*- C++ -*- */ // CLASSIX_OS_Test.cpp,v 1.1 1998/06/24 10:37:45 wchiang Exp // ============================================================================ // // = LIBRARY // tests // // = FILENAME // CLASSIX_OS_Test.cpp // // = DESCRIPTION // This is a test of the <ACE_CLASSIX_OS> class. // // = AUTHOR // Wei Chiang // // ============================================================================ #include "tests/test_config.h" #include "ace/CLASSIX/CLASSIX_OS.h" int main (int, char *[]) { ACE_START_TEST ("CLASSIX_OS_Test"); ACE_DEBUG((LM_INFO, "Empty Message\n")); ACE_CLASSIX_Msg msg1; msg1.dump(); char buf[] ="This is a test message"; int size = sizeof (buf); ACE_DEBUG((LM_INFO, "%s(size = %d)\n", buf, size)); ACE_CLASSIX_Msg msg2(buf, size); msg2.dump(); ACE_END_TEST; return 0; }
20.159091
80
0.473506
tharindusathis
211a85061c2c3645b2fe2bfce6e336d32c8dba7a
1,735
hpp
C++
stapl_release/benchmarks/data_mining/frequent_itemset/algo.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/data_mining/frequent_itemset/algo.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/benchmarks/data_mining/frequent_itemset/algo.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
#include <stapl/runtime.hpp> template<typename Predicate> class Find_map { private: Predicate m_pred; public: Find_map(Predicate const& pred) : m_pred(pred) { } template<typename Ref> Ref operator()(Ref elem) const { if (m_pred(elem)) { return elem; } else { return Ref(stapl::null_reference()); } } void define_type(stapl::typer& t) { t.member(m_pred); } }; class Find_reduce { public: template<typename Ref1, typename Ref2> Ref1 operator()(Ref1 lhs, Ref2 rhs) const { if (!is_null_reference(lhs)) { return lhs; } else { return rhs; } } }; template<typename View, typename Predicate> typename View::reference Find_if (View const& view, Predicate const& pred) { auto x= stapl::map_reduce(Find_map<Predicate>(pred), Find_reduce(), view); return x; } template<typename View, typename T> typename View::reference Find(View const& view, T const& value) { auto x= Find_if (view, stapl::bind2nd(stapl::equal_to<T>(), value)); return x; } /////////////////////////////////////////////////////////////////////////////// #if 0 struct match_cont_wf { template<typename View1, typename View2> result_type operator()(View1 left, View2 right) { #if 0 auto neq_values = stapl::mismatch(left,right); if (stapl::is_null_reference(neq_values.first) ) { return left; } else { return View1::reference(stapl::null_reference()); } #endif } typedef View1::reference result_type; }; #endif template<typename View1, typename View2> typename View1::reference match_cont(View1 const& view1, View2 const& view2) { //stapl::map_reduce( match_cont_wf(), Find_reduce(), view1, view1); //stapl::make_repeat_view(view2) ); }
19.494382
79
0.643804
parasol-ppl
211cdf229a7c191a6a1590ec3c715754336f1887
1,916
cpp
C++
src/cpp/SPL/Core/TransportStatModelImpl.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/cpp/SPL/Core/TransportStatModelImpl.cpp
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/cpp/SPL/Core/TransportStatModelImpl.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <SPL/Core/TransportStatModelImpl.h> using namespace std; using namespace std::tr1; using namespace SPL; using namespace SPL::TransportStat; using boost::shared_ptr; TransportStatModel::TransportStatModel(const transportStatModelType& xml) : productVersion_(xml.productVersion()) , cpuKind_(xml.cpuKind()) , bogoMips_(xml.bogoMips()) { typedef transportStatModelType::transportProfile_sequence::const_iterator myiter; myiter itbeg = xml.transportProfile().begin(); myiter itend = xml.transportProfile().end(); for (myiter it = itbeg; it != itend; ++it) { TransportProfilePtr tpptr(new TransportProfile(*it)); transportProfiles_.push_back(tpptr); } } TransportProfile::TransportProfile(const transportProfileType& xml) { transportKind_.reset(new TransportKindType(xml.transportKind())); typedef transportProfileType::tuplePerf_sequence::const_iterator myiter; myiter itbeg = xml.tuplePerf().begin(); myiter itend = xml.tuplePerf().end(); for (myiter it = itbeg; it != itend; ++it) { TuplePerfPtr tpptr(new TuplePerf(*it)); tuplePerfs_.push_back(tpptr); } } TuplePerf::TuplePerf(const tuplePerfType& xml) : size_(xml.size()) , rate_(xml.rate()) , senderUtil_(xml.senderUtil()) , receiverUtil_(xml.receiverUtil()) {}
33.614035
85
0.727557
IBMStreams
211e7f65be16fae090457534fa702e196d5f8188
829
cpp
C++
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <fstream> #include <string.h> #include <ctime> using namespace std; // seguridad para iniciar el sistema bool login() { setlocale(LC_CTYPE,"spanish"); string usuario = ""; string password = ""; bool acceso = false; int intentos = 0; while(intentos <= 3) { system("cls"); if(intentos == 3) { cout << " NO SE PUDO VALIDAR SU PASSWORD, "<< endl; cout << " Por favor pongase en contacto con el,"<<endl; cout << " administrador del systema " << endl; return false; } cout << " Ingrese su Usuario : "; cin >> usuario; cout << " Ingrese su clave : "; cin >> password; if(usuario == "admin" && password == "admin") { system("cls"); return true; } intentos++; } }
18.021739
59
0.557298
Maldanar201
2123419ecedb22992456a7c3cf3caf7672cc90ba
526
cpp
C++
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
1
2021-07-24T06:36:25.000Z
2021-07-24T06:36:25.000Z
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
9
2019-07-04T02:35:34.000Z
2019-07-09T03:00:21.000Z
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
null
null
null
#include "piece.h" Piece::Piece(char s, int v, bool white, int q){ this->symbol = s; this->value = v; this->white = white; this->quantity = this->alive = q; this->moved = false; } Piece::~Piece(){} char Piece::getSymbol(){ return this->symbol; } int Piece::getValue(){ return this->value; } bool Piece::isWhite(){ return this->white; } int Piece::getQuantity(){ return this->quantity; } void Piece::captured(){ this->alive--; } int Piece::getAlive(){ return this->alive; }
14.216216
47
0.60076
0xkalvin
2124fe39abdaac1984e9e6d4fc09a80fe0af8725
790
cpp
C++
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
#include "stdio.h" int main(int argc, char* argv[]) { if ( argc <= 1) { printf("CompileToCppVariable <Filename> [VariableName]\n"); return 1; } if ( argc > 2) { printf ("const char %s[] = {\n", argv[2]); } FILE* fp = fopen(argv[1],"rb"); if (fp == NULL) { printf ("Could not open file %s\n", argv[1]); return 2; } fseek(fp,0,SEEK_END); long size = ftell(fp); unsigned char* buffer = new unsigned char[size]; fseek(fp,0,SEEK_SET); fread(buffer,sizeof(char),size,fp); for (long i = 0 ; i < size ; i++) { printf("0x%02hhx,",buffer[i]); if ((i % 20)==19) { printf("\n"); } } printf ("0x%02hhx\n",(const unsigned char)(0)); if ( argc > 2) { printf ("};\n"); } fclose(fp); return 0; }
15.490196
62
0.516456
ShaiRoitman
2125e54de619aa2bfdbd0f8403008d8517f92445
1,002
cpp
C++
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
#include "MultiPaddle/WindowManager.h" WindowManager::WindowManager(const char* windowTitle) { if(SDL_Init(SDL_INIT_VIDEO) < 0){ std::cerr << "Could not initialise sdl2: " << SDL_GetError() << std::endl; return; } window = SDL_CreateWindow( windowTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if(window == nullptr){ std::cerr << "Could not create window: " << SDL_GetError() << std::endl; return; } this->screenSurface = SDL_GetWindowSurface(window); this->sdlRenderer = SDL_CreateRenderer(window, -1, 0); this->ready = true; } bool WindowManager::isReady() const { return this->ready; } SDL_Renderer * WindowManager::getRenderer() { return this->sdlRenderer; } int WindowManager::handleEvents() { SDL_Event event; SDL_WaitEventTimeout(&event, 10); switch(event.type){ case SDL_QUIT: SDL_Quit(); return 1; default: ; // std::cout << "Event Type: " << event.type << std::endl; } return 0; }
22.266667
76
0.697605
ToxicFrazzles
2127fbdf3c872ac273b82f3bc0a60356869d7b94
3,422
cpp
C++
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
/* * The Sink Record class reads, prints, and writes information related to sink data * read directly from the checkpoint files. The ctor should be passed a filename. */ #include "RossGlobals.h" #include "HDFIO.h" #include "Sink.hpp" #include "SinkRecord.hpp" #include <iostream> using std::cout; using std::endl; SinkRecord::SinkRecord(const std::string fname): Filename(fname), has_been_allocated(false) { resetFromFile(); } void SinkRecord::resetFromFile() { InOut.open(Filename, 'r'); data_dims = InOut.getDims("sink particle data"); data_size = InOut.getSize("sink particle data"); num_sinks = data_dims[0]; num_attributes = data_dims[1]; // Probably superfluous, but these should always be the same? assert( (num_sinks*num_attributes) == data_size ); cout << "Sink Data dimensions: "; print_container( data_dims ); cout << "Data size: " << data_size << endl; // Global function sets global var: HDFDataType CheckMachineForLittleBigEndianNumerics(); if (has_been_allocated) { delete [] DataPointer; } DataPointer = new float[data_size]; has_been_allocated = true; InOut.read(DataPointer, "sink particle data", ::HDFDataType); InOut.close(); unsigned int i; for (i = 0; i < num_sinks; i++) { // call Sink ctor and push onto mySinks mySinks.push_back( Sink( &DataPointer[i*num_attributes] ) ); } // sorts the sinks by formation times, so they always have the same ID std::sort( mySinks.begin(), mySinks.end() ); // give the sinks a unique int ID from sorted order for (i = 0; i < num_sinks; i++) { mySinks[i].setID(i); } } float SinkRecord::getAttribute(const unsigned int sink_id, const unsigned int attr_id) const { if (attr_id >= num_attributes) { cout << "Warning: attribute index must be less than the number of attributes" << " to avoid errors" << endl << "You passed: " << attr_id << endl << "Number of attributes: " << num_attributes << endl; return 1; } else if (sink_id >= num_sinks) { cout << "Error --> passed sink_id: " << sink_id << " with num_sinks: " << num_sinks << endl; return 1; } else { return this->DataPointer[sink_id * num_attributes + attr_id]; } } // For writing meta info to file adjacent to extracted datasets // -- might not need this, just run everything from one main and // give reference to SinkRecord to CoreAnalyzer? void WriteSinkRecord(const int sink_id, const std::string outfile_name) { } void SinkRecord::writeAllScripts() const { cout << "SinkRecord::writeAllScripts() called..." << endl << endl; std::string baseDir("/data1/r900-1/rossm/QuickFlash-1.0.0/core_code"); std::vector< Sink >::const_iterator it; for (it = mySinks.begin(); it != mySinks.end(); ++it) { int chk_num = 66; // needs to be more general it->writeExtractorScript(baseDir, chk_num, Filename); } } void SinkRecord::printAllData(void) { for (int i = 0; i < data_size; i++) { cout << DataPointer[i] << endl; if (i % (num_attributes-1) == 0){ cout << endl; } } } void SinkRecord::printAllSinks(void) { cout << endl; std::vector< Sink >::iterator it; for (it = mySinks.begin(); it != mySinks.end(); ++it) { it->printMe(); } }
27.596774
92
0.630333
rgmyr
212fd3aade032f8c38368735341efb8378ad50a2
394
cpp
C++
src/main.cpp
TheLogicMaster/ofFlappyBird
28b5df427c70b327e7e9524231b22ad78e18b828
[ "MIT" ]
1
2021-07-14T10:50:21.000Z
2021-07-14T10:50:21.000Z
src/main.cpp
TheLogicMaster/ofFlappyBird
28b5df427c70b327e7e9524231b22ad78e18b828
[ "MIT" ]
null
null
null
src/main.cpp
TheLogicMaster/ofFlappyBird
28b5df427c70b327e7e9524231b22ad78e18b828
[ "MIT" ]
null
null
null
#include "ofMain.h" #include "ofApp.h" //======================================================================== int main( ){ #ifdef TARGET_LINUX ofGLFWWindowSettings settings; settings.resizable = false; settings.title = "ofFlappyBird"; settings.setSize(288, 512); ofCreateWindow(settings); #else ofSetupOpenGL(288, 512, OF_WINDOW); #endif ofRunApp( new ofApp()); }
23.176471
74
0.563452
TheLogicMaster
213462e5b7ee9ce3764fb3f2ba53bf474d245624
5,421
cpp
C++
applications/PfemSolidMechanicsApplication/custom_constitutive/custom_yield_criteria/new_tresca_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/PfemSolidMechanicsApplication/custom_constitutive/custom_yield_criteria/new_tresca_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/PfemSolidMechanicsApplication/custom_constitutive/custom_yield_criteria/new_tresca_yield_criterion.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// // Project Name: KratosPfemSolidMechanicsApplication $ // Created by: $Author: LMonforte $ // Last modified by: $Co-Author: $ // Date: $Date: July 2015 $ // Revision: $Revision: 0.0 $ // // // System includes #include <string> #include <iostream> // External includes // Project includes #include "includes/define.h" #include "custom_constitutive/custom_yield_criteria/new_tresca_yield_criterion.hpp" #include "pfem_solid_mechanics_application_variables.h" namespace Kratos { //*******************************CONSTRUCTOR****************************************** //************************************************************************************ NewTrescaYieldCriterion::NewTrescaYieldCriterion() :TrescaYieldCriterion() { } //*****************************INITIALIZATION CONSTRUCTOR***************************** //************************************************************************************ NewTrescaYieldCriterion::NewTrescaYieldCriterion(HardeningLawPointer pHardeningLaw) :TrescaYieldCriterion(pHardeningLaw) { } //*******************************ASSIGMENT OPERATOR*********************************** //************************************************************************************ NewTrescaYieldCriterion& NewTrescaYieldCriterion::operator=(NewTrescaYieldCriterion const& rOther) { TrescaYieldCriterion::operator=(rOther); return *this; } //*******************************COPY CONSTRUCTOR************************************* //************************************************************************************ NewTrescaYieldCriterion::NewTrescaYieldCriterion(NewTrescaYieldCriterion const& rOther) :TrescaYieldCriterion(rOther) { } //********************************DESTRUCTOR****************************************** //************************************************************************************ NewTrescaYieldCriterion::~NewTrescaYieldCriterion() { } //************************* CALCULATE YIELD FUNCTION ****************** //********************************************************************** double& NewTrescaYieldCriterion::CalculateYieldCondition(double& rStateFunction, const Vector& rStressVector, const double& rAlpha) { KRATOS_TRY double Su = this->GetHardeningLaw().GetProperties()[YIELD_STRESS]; double AlphaS = this->GetHardeningLaw().GetProperties()[LAMBDA]; // quotient between the compression and extension undrained shear strenght if ( AlphaS < 1.0 || AlphaS > 2.0) AlphaS = 1.0; double smoothing = 10.0; // to smooth the sharp corners Matrix StressMatrix = MathUtils<double>::StressVectorToTensor( rStressVector); TrescaStressInvariants StressInvariants; this->CalculateStressInvariants( rStressVector, StressInvariants); double J2 = StressInvariants.J2InvSQ; J2 = pow(J2, 2); double lode = -StressInvariants.LodeAngle; double t2 = sqrt(3.0); double t3 = sin(lode); double t4 = AlphaS*3.0; double t5 = t4-3.0; double t6 = t3*t5; double t7 = cos(lode); double t8 = AlphaS+1.0; double t9 = t2*t7*t8; double t10 = 3.141592653589793*(2.0/3.0); double t11 = lode+t10; double t13 = 3.141592653589793*(1.0/3.0); double t12 = lode-t13; double t14 = lode+t13; double t15 = 3.141592653589793*(4.0/3.0); double t16 = lode+t15; double t0 = -Su+(sqrt(J2)*t2*log(exp(smoothing*(t5*sin(t11)+t2*t8*cos(t11)))+exp(-smoothing*(t5*sin(t12)-t2*t8*cos(t12)))+exp(-smoothing*(t5*sin(t14)-t2*t8*cos(t14)))+exp(smoothing*(t5*sin(t16)+t2*t8*cos(t16)))+exp(smoothing*(t6+t9))+exp(smoothing*(t6-t9)))*(1.0/6.0))/smoothing; rStateFunction = t0; return rStateFunction; KRATOS_CATCH("") } //************************* YIELD FUNCTION DERIVATIVE ****************** //********************************************************************** void NewTrescaYieldCriterion::CalculateYieldFunctionDerivative(const Vector& rStressVector, Vector& rYieldFunctionD, const double& rAlpha) { KRATOS_TRY double pertur = pow(2, -25); rYieldFunctionD = ZeroVector(6); Vector Stress1 = ZeroVector(6); Vector Stress2 = ZeroVector(6); double F1, F2; for (unsigned int i = 0; i < 6; i++) { Stress1 = rStressVector; Stress1(i) += pertur; F1 = this->CalculateYieldCondition( F1, Stress1, rAlpha); Stress2 = rStressVector; Stress2(i) -= pertur; F2 = this->CalculateYieldCondition( F2, Stress2, rAlpha); double denominador = Stress1(i)-Stress2(i); rYieldFunctionD(i) = (F1-F2)/(denominador); } for (unsigned int i = 3; i <6; i++) rYieldFunctionD(i) *= 2.0; KRATOS_CATCH("") } void NewTrescaYieldCriterion::save( Serializer& rSerializer ) const { KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, TrescaYieldCriterion ) } void NewTrescaYieldCriterion::load( Serializer& rSerializer ) { KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, TrescaYieldCriterion ) } } // namespace Kratos.
32.461078
288
0.517801
lkusch
213a28e46e103703dbaa1d3cc80c9a5dbeadbe04
26,341
cc
C++
pmlc/dialect/tile/builder.cc
redoclag/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
4,535
2017-10-20T05:03:57.000Z
2022-03-30T15:42:33.000Z
pmlc/dialect/tile/builder.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
984
2017-10-20T17:16:09.000Z
2022-03-30T05:43:18.000Z
pmlc/dialect/tile/builder.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
492
2017-10-20T18:22:32.000Z
2022-03-30T09:00:05.000Z
// Copyright 2019, Intel Corporation #include "pmlc/dialect/tile/builder.h" #include <map> #include <queue> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "llvm/ADT/SetVector.h" #include "llvm/Support/FormatVariadic.h" #include "mlir/Analysis/Verifier.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Function.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/Module.h" #include "mlir/IR/Operation.h" #include "mlir/IR/Value.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/DebugStringHelper.h" #include "mlir/Transforms/Passes.h" #include "base/util/env.h" #include "base/util/logging.h" #include "pmlc/dialect/eltwise/ir/dialect.h" #include "pmlc/dialect/eltwise/ir/ops.h" #include "pmlc/dialect/tile/gradient.h" #include "pmlc/dialect/tile/ir/dialect.h" #include "pmlc/dialect/tile/ir/ops.h" #include "pmlc/dialect/tile/program.h" #include "pmlc/util/slice.h" #include "pmlc/util/util.h" namespace pmlc::dialect::tile { using eltwise::ScalarConstantOp; using eltwise::ScalarType; using llvm::ArrayRef; using llvm::SmallVector; using llvm::StringRef; using mlir::Block; using mlir::BlockAndValueMapping; using mlir::MLIRContext; using mlir::ModuleOp; using mlir::OpBuilder; using mlir::RankedTensorType; using mlir::Type; using mlir::UnknownLoc; using mlir::Value; using util::AggregationKind; using util::CombinationKind; using vertexai::tile::BufferPtr; struct DomainInfo { BlockAndValueMapping mapping; }; struct TileBuilder::Impl { MLIRContext context; ModuleOp module; OpBuilder builder; llvm::DenseMap<Value, Value> implicitUpdates; llvm::DenseMap<Value, BufferPtr> implicitBindings; llvm::DenseMap<Value, RankedTensorType> shapeCache; NoneOp noneOp; Value defaultInit; Location loc; unsigned idxCounter = 0; Impl() : module(ModuleOp::create(UnknownLoc::get(&context))), // builder(module.getBody()), loc(builder.getUnknownLoc()) { builder.setInsertionPointToStart(module.getBody()); defaultInit = makeScalarConstantOp(0.0); } Type inferElementType(ArrayRef<Type> types) { DataType ret = DataType::INVALID; for (auto type : types) { auto rankedTensorType = eltwise::getRankedTensorType(type); auto dtype = rankedTensorType.getElementType().cast<ScalarType>().type(); ret = CommonSupertype(ret, dtype); } return builder.getType<ScalarType>(ret); } const mlir::AbstractOperation* lookupOperation(StringRef op) { auto opName = eltwise::Dialect::getCanonicalOpName(op); auto abstractOp = mlir::AbstractOperation::lookup(opName, &context); if (!abstractOp) { opName = tile::Dialect::getCanonicalOpName(op); abstractOp = mlir::AbstractOperation::lookup(opName, &context); if (!abstractOp) { throw std::runtime_error("Unknown op: " + op.str()); } } return abstractOp; } std::vector<Value> getBackwardSliceOfAffine(const llvm::SetVector<Value>& values) { return util::getBackwardSlice(values, false, [](Value value) { if (auto scalarType = value->getType().dyn_cast<ScalarType>()) { return scalarType.type() == DataType::INT32; } return false; }); } Value makeIndexOp(StringRef fn, ArrayRef<Value> args) { if (args.size() != 2) { throw std::runtime_error("index op expects 2 operands"); } auto tensor = args[0]; auto dim = args[1]; auto resultType = IndexOp::getResultType(args.take_front()); IntegerAttr dimAttr; if (!m_Constant(&dimAttr).match(dim->getDefiningOp())) { throw std::runtime_error("index op expect argument 2 to be a constant integer"); } auto op = builder.create<IndexOp>(loc, resultType, tensor, dimAttr); return op.result(); } Value makePrngOp(StringRef fn, ArrayRef<Value> args) { if (args.size() < 1) { throw std::runtime_error("prng op expects at least one operand"); } auto state = args.front(); auto dims = args.drop_front(); auto resultType = PrngOp::getResultType(args); auto elementType = builder.getType<ScalarType>(DataType::UINT32); auto stateType = RankedTensorType::get({3, 2048}, elementType); auto op = builder.create<PrngOp>(loc, resultType, stateType, state, dims); implicitUpdates.insert(std::make_pair(op.new_state(), op.state())); return op.result(); } Value makeScalarConstantOp(double value) { auto type = builder.getType<ScalarType>(DataType::FLOAT32); return builder.create<ScalarConstantOp>(loc, type, value).result(); } }; TileBuilder::TileBuilder() : impl(new Impl) {} TileBuilder::~TileBuilder() = default; void TileBuilder::Destroy(Value value) { IVLOG(5, "TileBuilder::Destroy> value"); // impl->implicitBindings.erase(value); // TODO: fix memory mgmt issues, once purely MLIR path is complete // if (value && value->use_empty()) { // auto op = value->getDefiningOp(); // if (op && op->use_empty()) { // op->erase(); // } // } } stripe::TensorType TileBuilder::MakeTensorType( // DataType dtype, // llvm::ArrayRef<int64_t> sizes, // llvm::ArrayRef<int64_t> strides) { auto cls = mlir::Identifier::get(stripe::kAddressClassIdentifier, &impl->context); llvm::SmallVector<stripe::TensorDim, 4> dims; for (unsigned i = 0; i < sizes.size(); i++) { dims.emplace_back(stripe::TensorDim{sizes[i], strides[i], cls}); } auto elementType = impl->builder.getType<ScalarType>(dtype); return stripe::TensorType::get(elementType, dims, stripe::OffsetsMap{}, false); } stripe::TensorType TileBuilder::IntoTensorType(RankedTensorType type) { auto shape = type.getShape(); auto cls = mlir::Identifier::get(stripe::kAddressClassIdentifier, type.getContext()); llvm::SmallVector<stripe::TensorDim, 4> newShape(shape.size(), stripe::TensorDim{0, 0, cls}); int64_t stride = 1; for (int i = shape.size() - 1; i >= 0; i--) { newShape[i].stride = stride; newShape[i].size = shape[i]; stride *= shape[i]; } return stripe::TensorType::get(type.getElementType(), newShape, stripe::OffsetsMap{}, false); } void TileBuilder::BindShape(Value tensor, RankedTensorType type) { IVLOG(5, "TileBuilder::BindShape>"); tensor->setType(type); } void TileBuilder::BindBuffer(Value tensor, BufferPtr buffer) { IVLOG(5, "TileBuilder::BindBuffer>"); impl->implicitBindings[tensor] = buffer; } void TileBuilder::BindTensorDims(Value from, ArrayRef<Value*> intos) { if (!from) { throw std::runtime_error("BindTensorDim: from == nullptr"); } IVLOG(5, "TileBuilder::BindTensorDim> from: " << mlir::debugString(from)); for (unsigned i = 0; i < intos.size(); i++) { auto into = intos[i]; if (!into) { throw std::runtime_error("BindTensorDim: into == nullptr"); } if (*into) { IVLOG(6, "into: " << mlir::debugString(*into)); auto fromType = from->getType().dyn_cast<RankedTensorType>(); if (!fromType) { throw std::runtime_error("Unexpected type"); } auto fromSize = fromType.getDimSize(i); if (!mlir::ShapedType::isDynamic(fromSize)) { auto op = (*into)->getDefiningOp(); if (!op) { throw std::runtime_error("No defining op"); } if (auto const_op = llvm::dyn_cast<AffineConstantOp>(op)) { auto attr = const_op.getValue().dyn_cast<IntegerAttr>(); if (!attr) { throw std::runtime_error("Expected IntegerAttr for value of AffineConstantOp"); } IVLOG(6, "dim: " << i << ", from: " << fromSize << ", into: " << attr.getInt()); if (fromSize != attr.getInt()) { std::string str; llvm::raw_string_ostream os(str); os << llvm::formatv("bind_dims() mismatch on dim {0}. from: {1}, into: {2}", i, fromSize, attr.getInt()); throw std::runtime_error(os.str()); } } } } *into = MakeDimOp(from, i); } } RankedTensorType TileBuilder::ComputeShape(Value tensor) { IVLOG(5, "TileBuilder::ComputeShape>"); auto type = eltwise::getRankedTensorType(tensor->getType()); if (type.hasStaticShape()) { return type; } auto it = impl->shapeCache.find(tensor); if (it != impl->shapeCache.end()) { return it->second; } ProgramMutations mutations; mutations.outputs.emplace_back(tensor); auto program = MakeProgram("compute_shape", mutations); auto shape = program->outputs[0]->getType().dyn_cast<RankedTensorType>(); impl->shapeCache.insert(std::make_pair(tensor, shape)); return shape; } Value TileBuilder::MakeCastOp(Value tensor, DataType dtype) { IVLOG(5, "TileBuilder::MakeCastOp> " << to_string(dtype)); IVLOG(6, " arg: " << mlir::debugString(tensor)); auto elementType = impl->builder.getType<ScalarType>(dtype); auto tensorType = eltwise::getRankedTensorType(tensor->getType()); auto resultType = RankedTensorType::get(tensorType.getShape(), elementType); return impl->builder.create<eltwise::CastOp>(impl->loc, resultType, tensor).result(); } Value TileBuilder::MakePrimitiveOp(StringRef fn, ArrayRef<Value> args) { using PrimitiveBuilder = Value (Impl::*)(StringRef fn, ArrayRef<Value> args); static std::map<StringRef, PrimitiveBuilder> primitives = { {"index", &Impl::makeIndexOp}, {"prng", &Impl::makePrngOp}, }; IVLOG(5, "TileBuilder::MakePrimitiveOp> " << fn.str()); for (auto arg : args) { IVLOG(6, " arg: " << mlir::debugString(arg)); } auto it = primitives.find(fn); if (it != primitives.end()) { return (impl.get()->*it->second)(fn, args); } auto abstractOp = impl->lookupOperation(fn); auto genericBuilder = abstractOp->getInterface<util::GenericBuilder>(); if (!genericBuilder) { throw std::runtime_error("Unknown intrinsic: " + fn.str()); } auto type = impl->builder.getType<ScalarType>(DataType::FLOAT32); // TODO auto op = genericBuilder->create(&impl->builder, impl->loc, type, args); return op->getResult(0); } Value TileBuilder::Clone(Value value) { IVLOG(5, "TileBuilder::Clone> " << mlir::debugString(value)); return impl->builder.clone(*value->getDefiningOp())->getResult(0); } Value TileBuilder::MakeNoneOp() { IVLOG(5, "TileBuilder::MakeNoneOp>"); if (!impl->noneOp) { auto type = impl->builder.getNoneType(); impl->noneOp = impl->builder.create<NoneOp>(impl->loc, type); } return impl->noneOp.result(); } Value TileBuilder::MakeStringOp(StringRef value) { IVLOG(5, "TileBuilder::MakeStringOp> " << value.str()); auto type = StringType::get(&impl->context); auto attr = impl->builder.getStringAttr(value); return impl->builder.create<StringOp>(impl->loc, type, attr).result(); } llvm::StringRef TileBuilder::GetStringValue(Value value) { if (auto op = llvm::dyn_cast_or_null<StringOp>(value->getDefiningOp())) { return op.getValue().getValue(); } throw std::runtime_error("Expected StringOp"); } Value TileBuilder::MakeTupleOp(ArrayRef<Value> elts) { IVLOG(5, "TileBuilder::MakeTupleOp> elts: " << elts.size()); std::vector<Type> types; for (auto elt : elts) { types.push_back(elt->getType()); } auto tupleType = impl->builder.getTupleType(types); return impl->builder.create<TupleOp>(impl->loc, tupleType, elts).result(); } std::vector<Value> TileBuilder::GetTupleElements(Value value) { IVLOG(5, "TileBuilder::GetTupleElements> " << mlir::debugString(value)); if (auto op = llvm::dyn_cast_or_null<TupleOp>(value->getDefiningOp())) { return std::vector<Value>(op.elts().begin(), op.elts().end()); } throw std::runtime_error("Expected TupleOp"); } Value TileBuilder::MakeScalarConstantOp(int64_t value) { IVLOG(5, "TileBuilder::MakeScalarConstantOp> " << value); auto type = impl->builder.getType<ScalarType>(DataType::INT32); return impl->builder.create<ScalarConstantOp>(impl->loc, type, value).result(); } int64_t TileBuilder::GetIntegerValue(Value value) { if (auto op = llvm::dyn_cast_or_null<ScalarConstantOp>(value->getDefiningOp())) { return op.getIntAttr().getInt(); } throw std::runtime_error("Expected ScalarConstantOp"); } Value TileBuilder::MakeScalarConstantOp(double value) { IVLOG(5, "TileBuilder::MakeScalarConstantOp> " << value); return impl->makeScalarConstantOp(value); } double TileBuilder::GetFloatValue(Value value) { if (auto op = llvm::dyn_cast_or_null<ScalarConstantOp>(value->getDefiningOp())) { return op.getFloatAttr().getValueAsDouble(); } throw std::runtime_error("Expected ScalarConstantOp"); } Value TileBuilder::MakeDimOp(Value tensor, unsigned dim) { IVLOG(5, "TileBuilder::MakeDimOp> tensor: " << mlir::debugString(tensor) << ", dim: " << dim); return impl->builder.create<DimOp>(impl->loc, tensor, dim).result(); } RankedTensorType TileBuilder::MakeRankedTensorType(DataType dtype, ArrayRef<int64_t> dims) { IVLOG(5, "TileBuilder::MakeRankedTensorType> " << to_string(dtype)); auto elementType = impl->builder.getType<ScalarType>(dtype); // Convert dims: PlaidML semantics use 0 for unknown size, MLIR uses -1. SmallVector<int64_t, 4> shape(dims.begin(), dims.end()); for (auto& dim : shape) { if (dim == 0) { dim = -1; } } return RankedTensorType::get(shape, elementType); } Value TileBuilder::MakePlaceholderOp(RankedTensorType type, BufferPtr buffer, StringRef name) { IVLOG(5, "TileBuilder::MakePlaceholderOp> " << name.str() << ": " << mlir::debugString(type)); auto op = impl->builder.create<PlaceholderOp>(impl->loc, type); if (!name.empty()) { op.setAttr("name", impl->builder.getStringAttr(name)); } if (buffer) { impl->implicitBindings[op.result()] = buffer; } return op.result(); } Value TileBuilder::MakeAffineConstantOp(int64_t value) { IVLOG(5, "TileBuilder::MakeAffineConstantOp> " << value); return impl->builder.create<AffineConstantOp>(impl->loc, value).result(); } Value TileBuilder::MakeAffineIndexOp(StringRef name) { IVLOG(5, "TileBuilder::MakeAffineIndexOp> " << name.str()); return impl->builder.create<AffineIndexOp>(impl->loc, impl->idxCounter++, name).result(); } Value TileBuilder::MakeAffineAddOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineAddOp>"); return impl->builder.create<AffineAddOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineSubOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineSubOp>"); return impl->builder.create<AffineSubOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineMulOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineMulOp>"); return impl->builder.create<AffineMulOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineDivOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineDivOp>"); return impl->builder.create<AffineDivOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineNegOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineNegOp>"); return impl->builder.create<AffineNegOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineMaxOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineMaxOp>"); return impl->builder.create<AffineMaxOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineMinOp(ArrayRef<Value> args) { IVLOG(5, "TileBuilder::MakeAffineMinOp>"); return impl->builder.create<AffineMinOp>(impl->loc, args).result(); } Value TileBuilder::MakeAffineSourceIndexMapOp(Value tensor, ArrayRef<Value> idxs) { IVLOG(5, "TileBuilder::MakeAffineSourceIndexMapOp>"); return impl->builder.create<AffineTensorMapOp>(impl->loc, tensor, idxs).result(); } Value TileBuilder::MakeAffineSinkIndexMapOp(ArrayRef<Value> idxs) { IVLOG(5, "TileBuilder::MakeAffineSinkIndexMapOp>"); return impl->builder.create<AffineMapOp>(impl->loc, idxs).result(); } Value TileBuilder::MakeAffineSizeMapOp(ArrayRef<Value> sizes) { IVLOG(5, "TileBuilder::MakeAffineSizeMapOp>"); return impl->builder.create<AffineMapOp>(impl->loc, sizes).result(); } void TileBuilder::AddConstraint(Value cion, Value lhs, Value rhs) { IVLOG(5, "TileBuilder::AddConstraint>"); auto op = cion->getDefiningOp(); auto cionOp = llvm::dyn_cast_or_null<SymbolicContractionOp>(op); if (!cionOp) { throw std::runtime_error("add_constraint can only be specified on a contraction."); } auto consOp = llvm::cast<AffineConstraintsOp>(cionOp.cons()->getDefiningOp()); SmallVector<Value, 6> pairs{consOp.pairs()}; pairs.emplace_back(lhs); pairs.emplace_back(rhs); consOp.getOperation()->setOperands(pairs); } void TileBuilder::SetUseDefault(Value cion, Value init) { IVLOG(2, "TileBuilder::SetUseDefault>"); auto op = cion->getDefiningOp(); auto cionOp = llvm::dyn_cast_or_null<SymbolicContractionOp>(op); if (!cionOp) { throw std::runtime_error("no_reduce can only be specified on a contraction."); } cionOp.setOperand(0, init); } void TileBuilder::SetNoReduce(Value cion, bool no_reduce) { IVLOG(2, "TileBuilder::SetNoReduce> " << no_reduce); auto op = cion->getDefiningOp(); auto cionOp = llvm::dyn_cast_or_null<SymbolicContractionOp>(op); if (!cionOp) { throw std::runtime_error("no_reduce can only be specified on a contraction."); } if (no_reduce) { cionOp.setAttr("no_reduce", impl->builder.getUnitAttr()); } else { cionOp.removeAttr("no_reduce"); } } Value TileBuilder::MakeContractionOp( // util::AggregationKind agg, // util::CombinationKind combo, // ArrayRef<Value> srcs, // Value sink, // Value sizes, // StringRef name) { IVLOG(5, "TileBuilder::MakeContractionOp> " << util::stringifyAggregationKind(agg).str() << ":" << util::stringifyCombinationKind(combo).str() << ", name: " << name.str()); IVLOG(5, mlir::debugString(impl->module)); // TODO: handle names (and idx_names) // Compute the sink shape of the contraction SmallVector<Type, 3> types; for (auto src : srcs) { auto mapOp = llvm::cast<AffineTensorMapOp>(src->getDefiningOp()); types.push_back(mapOp.tensor()->getType()); } Type elementType; if (combo == CombinationKind::eq) { elementType = ScalarType::get(&impl->context, DataType::BOOLEAN); } else if (combo == CombinationKind::cond) { auto rankedTensorType = eltwise::getRankedTensorType(types[2]); elementType = rankedTensorType.getElementType(); } else { elementType = impl->inferElementType(types); } auto sizeMapOp = llvm::cast<AffineMapOp>(sizes->getDefiningOp()); SmallVector<Value, 4> sizeDims(sizeMapOp.dims()); auto shape = eltwise::ComputeShape(sizeDims); StringAttr nameAttr; if (name.size()) { nameAttr = impl->builder.getStringAttr(name); } auto op = impl->builder.create<SymbolicContractionOp>( // impl->loc, // RankedTensorType::get(shape, elementType), // impl->defaultInit, // impl->builder.create<AffineConstraintsOp>(impl->loc), // sizes, // sink, // srcs, // impl->builder.getI64IntegerAttr(static_cast<int64_t>(agg)), // impl->builder.getI64IntegerAttr(static_cast<int64_t>(combo)), // UnitAttr{}, // nameAttr); return op.result(); } std::shared_ptr<TileProgram> TileBuilder::MakeProgram(StringRef name, const ProgramMutations& mutations) { if (name.empty()) { name = "noname"; } IVLOG(1, "TileBuilder::MakeProgram> " << name.str()); IVLOG(6, mlir::debugString(impl->module)); // Wrap duplicate outputs and outputs that directly refer to inputs llvm::SetVector<Value> outputs; for (auto output : mutations.outputs) { if (!output) { throw std::runtime_error("Invalid output"); } if (outputs.count(output) || llvm::isa<PlaceholderOp>(output->getDefiningOp())) { outputs.insert(MakePrimitiveOp("ident", {output})); } else { outputs.insert(output); } } for (const auto& update : mutations.updates) { outputs.insert(update.source); } auto slice = util::getBackwardSlice(outputs, true); // Compute the input types std::vector<Type> inputTypes; for (auto value : slice) { auto op = value->getDefiningOp(); if (auto placeholderOp = llvm::dyn_cast_or_null<PlaceholderOp>(op)) { inputTypes.push_back(placeholderOp.result()->getType()); } } // Construct a module auto loc = mlir::UnknownLoc::get(&impl->context); auto module = ModuleOp::create(loc); auto program = std::make_shared<TileProgram>(module); program->entry = name; // Construct a function to represent the entire program auto initialFuncType = mlir::FunctionType::get(inputTypes, {}, &impl->context); auto funcOp = mlir::FuncOp::create(loc, name, initialFuncType, {}); funcOp.addEntryBlock(); OpBuilder builder(funcOp.getBody()); std::set<std::string> names; auto attrName = Dialect::getDialectAttrName("name"); unsigned argcnt = 0; std::map<Operation*, Operation*> opMap; BlockAndValueMapping mapper; for (auto value : slice) { auto op = value->getDefiningOp(); // Only copy over top-level ops (those owned by the workspace module) if (op && op->getBlock() == impl->module.getBody()) { if (auto placeholderOp = llvm::dyn_cast<PlaceholderOp>(op)) { // Replace placeholders with block arguments auto blockArg = funcOp.getArgument(argcnt++); if (auto attr = placeholderOp.getAttrOfType<StringAttr>("name")) { auto uniqueName = util::getUniqueName(&names, attr.getValue()); auto uniqueAttr = builder.getStringAttr(uniqueName); funcOp.setArgAttr(blockArg->getArgNumber(), attrName, uniqueAttr); } IVLOG(5, "BlockArgument mapping: " << value << " -> " << blockArg); mapper.map(value, blockArg); ProgramArgument programArg{true, value, value->getType().cast<RankedTensorType>()}; auto itBinding = impl->implicitBindings.find(value); if (itBinding != impl->implicitBindings.end()) { programArg.buffer = itBinding->second; } program->arguments.emplace_back(programArg); } else { Operation* newOp; auto it = opMap.find(op); if (it != opMap.end()) { newOp = it->second; } else { newOp = builder.clone(*op, mapper); opMap.emplace(op, newOp); } for (unsigned i = 0; i < op->getNumResults(); i++) { auto oldResult = op->getResult(i); auto newResult = newOp->getResult(i); if (oldResult == value) { IVLOG(5, "mapping: " << value << " -> " << newResult); IVLOG(6, "value: " << mlir::debugString(value)); IVLOG(6, "newResult: " << mlir::debugString(newResult)); mapper.map(value, newResult); } else { auto itUpdate = impl->implicitUpdates.find(oldResult); if (itUpdate != impl->implicitUpdates.end()) { mapper.map(oldResult, newResult); outputs.insert(oldResult); } } } } } } // Add a final ReturnOp std::vector<Value> returnOperands; std::vector<Type> resultTypes; for (auto output : outputs) { auto value = mapper.lookupOrNull(output); if (!value) { throw std::runtime_error("Output not found in mapper"); } resultTypes.emplace_back(value->getType()); returnOperands.emplace_back(value); } auto returnOp = builder.create<mlir::ReturnOp>(loc, returnOperands); // compute final function type auto finalFuncType = mlir::FunctionType::get(inputTypes, resultTypes, &impl->context); funcOp.setType(finalFuncType); // Attach the function to the module module.push_back(funcOp); IVLOG(5, mlir::debugString(module)); if (failed(mlir::verify(module))) { throw std::runtime_error("Module verification error"); } // Do some optimization passes mlir::PassManager pm(&impl->context); pm.addPass(mlir::createCanonicalizerPass()); pm.addPass(mlir::createCSEPass()); auto result = pm.run(module); if (failed(result)) { IVLOG(1, mlir::debugString(module)); throw std::runtime_error("Optimization passes failure"); } for (unsigned i = 0; i < returnOp.getNumOperands(); i++) { auto userValue = outputs[i]; auto finalValue = returnOp.getOperand(i); auto itUpdate = impl->implicitUpdates.find(outputs[i]); if (itUpdate != impl->implicitUpdates.end()) { userValue = itUpdate->second; } ProgramArgument programArg{false, userValue, finalValue->getType().cast<RankedTensorType>()}; auto itBinding = impl->implicitBindings.find(finalValue); if (itBinding != impl->implicitBindings.end()) { programArg.buffer = itBinding->second; } program->arguments.emplace_back(programArg); program->outputs.emplace_back(finalValue); } IVLOG(2, "TileBuilder::MakeProgram>" << mlir::debugString(module)); return program; } std::vector<Value> TileBuilder::ComputeGradients(ArrayRef<Value> wrt, Value loss) { IVLOG(2, "TileBuilder::ComputeGradients>"); auto value = loss; auto ndims = ComputeShape(loss).getShape().size(); if (ndims) { std::vector<Value> src_idxs; for (size_t i = 0; i < ndims; ++i) { src_idxs.emplace_back(MakeAffineIndexOp("")); } ArrayRef<Value> srcs{MakeAffineSourceIndexMapOp(loss, src_idxs)}; auto sink = MakeAffineSinkIndexMapOp(ArrayRef<Value>{}); auto sizes = MakeAffineSizeMapOp(ArrayRef<Value>{}); auto cion = MakeContractionOp(util::AggregationKind::add, util::CombinationKind::none, srcs, sink, sizes, "net_loss"); value = cion; } Gradient grad(value, this); std::vector<Value> ret(wrt.size()); for (size_t i = 0; i < wrt.size(); i++) { ret[i] = grad.GetDerivative(wrt[i]); } return ret; } void TileBuilder::Dump() { // IVLOG(5, mlir::debugString(impl->module)); } } // namespace pmlc::dialect::tile
36.789106
117
0.663756
redoclag
213c0e17b38e1be807df4b4db3900054ee3b14b9
17,381
hpp
C++
plugins/community/repos/EH_modules/src/FV1emu.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/EH_modules/src/FV1emu.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/EH_modules/src/FV1emu.hpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
/* FV1 Emulator * Copyright (C)2018 - Eduard Heidt * * 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 <vector> #include <iostream> #include <string> #include <sstream> #include <map> #include <regex> #include <functional> #include <algorithm> #include <assert.h> #include <fstream> #include <memory> #include <codecvt> #include "FV1.hpp" namespace rack_plugin_EH_modules { class FV1emu { private: int ParseFloat(const std::string &param, std::map<std::string, int> &vars) { if (vars.find(param) == vars.end()) { if (param.find('/') != std::string::npos) { std::stringstream ss(param); std::string tmp; std::getline(ss, tmp, '/'); auto a = (float)ParseFloat(tmp, vars) / FixedPoint::F; while (std::getline(ss, tmp, '/')) a = a / ((float)ParseFloat(tmp, vars) / FixedPoint::F); return a * FixedPoint::F; } else { //assert(std::regex_match(param, std::regex("[+-]?([0-9]*[.])?[0-9]+"))); float f = 0; std::istringstream istr(param); istr.imbue(std::locale("C")); istr >> f; return f * FixedPoint::F; } } else return vars[param]; } int ParseInt(const std::string &param, std::map<std::string, int> &vars) { if (vars.find(param) == vars.end()) { std::string tmp; if (param.find('/') != std::string::npos) { assert(!"ParseInt Devision"); return 0; } else if (param.find('+') != std::string::npos) { std::stringstream ss(param); std::string tmp; auto a = 0; while (std::getline(ss, tmp, '+')) a += ParseInt(tmp, vars); return a; } else if (param.find('-') != std::string::npos) { std::stringstream ss(param); std::string tmp; auto a = 0; while (std::getline(ss, tmp, '-')) a -= ParseInt(tmp, vars); return a; } else if (param.find('|') != std::string::npos) { std::stringstream ss(param); std::string tmp; auto a = 0; while (std::getline(ss, tmp, '|')) a |= ParseInt(tmp, vars); return a; } else if (param.find('X') != std::string::npos) { return std::stoul(param, nullptr, 16); } else if (param.find('$') != std::string::npos) { tmp = param; replaceAll(tmp, "$", "0x"); return std::stoul(tmp, nullptr, 16); } else if (param.find('%') != std::string::npos) { tmp = param; replaceAll(tmp, "%", ""); replaceAll(tmp, "_", ""); return std::stoul(tmp, nullptr, 2); } else { int i = 0; std::istringstream istr(param); istr.imbue(std::locale("C")); istr >> i; return i; } } else return vars[param]; } void replaceAll(std::string &str, const std::string &from, const std::string &to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } start_pos = 0; } } void trim(std::string &str, const std::string &chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); str.erase(str.find_last_not_of(chars) + 1); } void toupper(std::string &str) { for (auto &c : str) c = ::toupper(c); } void ReadLine(std::string line, std::string &op, std::string &paramA, std::string &paramB, std::string &paramC, std::string &paramD) { std::stringstream a(line); std::getline(a, line, ';'); trim(line); replaceAll(line, " ", "\t"); replaceAll(line, ",,", ",0,"); replaceAll(line, ",", "\t"); replaceAll(line, "\t\t", "\t"); replaceAll(line, "\t|", "|"); replaceAll(line, "|\t", "|"); std::stringstream ss(line); std::getline(ss, op, '\t'); trim(op); toupper(op); std::getline(ss, paramA, '\t'); std::getline(ss, paramB, '\t'); std::getline(ss, paramC, '\t'); std::getline(ss, paramD, '\t'); trim(paramA); trim(paramB); trim(paramC); trim(paramD); toupper(paramA); toupper(paramB); toupper(paramC); toupper(paramD); } template <typename A, typename B, typename C> void DEBUG(int i, const std::string &op, const A &p1, const B &p2, const C &p3, const std::string &line) { std::ostringstream tmp; //out << std::string("\nP2 ") << std::hex << this->getRegVal(POT2) << " DACL " << std::hex << this->getRegVal(DACL); tmp << i << ":"; while (tmp.tellp() < 4) tmp << " "; tmp << op << " " << p1 << " " << p2 << " " << p3; while (tmp.tellp() < 40) tmp << " "; tmp << line << std::endl; std::cout << tmp.str(); } template <typename A, typename B> void DEBUG(int i, const std::string &op, const A &p1, const B &p2, const std::string &line) { DEBUG(i, op, p1, p2, "", line); } template <typename A> void DEBUG(int i, const std::string &op, const A &p1, const std::string &line) { DEBUG(i, op, p1, "", "", line); } std::string basename(const std::string &pathname) { return {std::find_if(pathname.rbegin(), pathname.rend(), [](char c) { return c == '/' || c == '\\'; }).base(), pathname.end()}; } inline int S114(const std::string &param, std::map<std::string, int> &vars) //16BIT => -2 to 2 { auto fp = ParseFloat(param, vars); return (fp / FixedPoint::S) & 0xffffff00; } inline int S19(const std::string &param, std::map<std::string, int> &vars) //11BIT => -2 to 2 { auto fp = ParseFloat(param, vars); return (fp / FixedPoint::S) & 0xffffe000; } inline int S10(const std::string &param, std::map<std::string, int> &vars) //11BIT => -1 to 1 { auto fp = ParseFloat(param, vars); return fp & 0xffffff00; } inline int S15(const std::string &param, std::map<std::string, int> &vars) //16 BIT => -1 to 1 { auto fp = ParseFloat(param, vars); return fp & 0xffffe000; } inline int LFO1(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); return fp & 0x1; } inline int LFO2(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); return fp & 0x7; } inline int REGADDR(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); assert(fp <= 0x3F); return fp & 0x3F; } inline int DELADDR(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); assert(fp <= 0x7FFF); return fp & 0x7FFF; } inline int MASK(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); assert(fp <= 0x00FFFFFF); return fp & 0x00FFFFFF; } inline int INT(const std::string &param, std::map<std::string, int> &vars) { auto fp = ParseInt(param, vars); return fp; } FV1 fv1; std::string display; std::string fxcode; public: std::string getDisplay() { return this->display; } std::string getCode() { return this->fxcode; } std::string dumpState(const std::string endl = "") { std::string tmp; this->fv1.dump(tmp, endl); return tmp; } void load(const std::string &file) { std::vector<std::vector<int>> fx; std::ifstream infile(file); std::stringstream stream; if (infile.good()) { std::string line; while (std::getline(infile, line)) { bool isComment = false; for (auto &c : line) { if (c != 0 && isascii(c)) { stream << (char)c; if (c == ';') isComment = true; if (isComment == false && c == ':') stream << std::endl; } } stream << std::endl; } this->display = basename(file); toupper(display); } else { #ifdef TEST stream << file; #else display = basename(file); toupper(display); display += "\n Error: File not found!"; fv1.loadFx(fx); return; #endif } fxcode = stream.str(); replaceAll(fxcode, "&#58;", ":"); stream = std::stringstream(); stream << fxcode; #ifndef TEST struct CoutRedirect { std::streambuf *old; CoutRedirect(std::streambuf *to) : old(0) { // empty old = std::cout.rdbuf(to); } ~CoutRedirect() { if (old != 0) { std::cout.rdbuf(old); } } }; auto logFile = file + ".log"; std::ofstream log(logFile, std::ios::out); CoutRedirect pipe(log.rdbuf()); #endif //stream.clear(); stream.seekg(0, std::ios::beg); std::map<std::string, int> VAR; VAR[""] = 0; VAR["RUN"] = SKP_RUN; VAR["GEZ"] = SKP_GEZ; VAR["NEG"] = SKP_NEG; VAR["ZRC"] = SKP_ZRC; VAR["ZRO"] = SKP_ZRO; for (int i = 0; i < (REG31 - REG0); i++) VAR[std::string("REG") + std::to_string(i)] = REG0 + i; VAR["ADDR_PTR"] = ADDR_PTR; VAR["RMP0_RATE"] = RMP0_RATE; VAR["RMP0_RANGE"] = RMP0_RANGE; VAR["RMP1_RATE"] = RMP1_RATE; VAR["RMP1_RANGE"] = RMP1_RANGE; VAR["SIN0_RATE"] = SIN0_RATE; VAR["SIN0_RANGE"] = SIN0_RANGE; VAR["SIN1_RATE"] = SIN1_RATE; VAR["SIN1_RANGE"] = SIN1_RANGE; VAR["POT0"] = POT0; VAR["POT1"] = POT1; VAR["POT2"] = POT2; VAR["ADCL"] = ADCL; VAR["ADCR"] = ADCR; VAR["DACL"] = DACL; VAR["DACR"] = DACR; VAR["RMP0"] = CHO_LFO_RMP0; VAR["RMP1"] = CHO_LFO_RMP1; VAR["SIN0"] = CHO_LFO_SIN0; VAR["SIN1"] = CHO_LFO_SIN1; VAR["COS0"] = CHO_LFO_COS0; VAR["COS1"] = CHO_LFO_COS1; VAR["REG"] = CHO_REG; VAR["SIN"] = CHO_SIN; VAR["COS"] = CHO_COS; VAR["COMPC"] = CHO_COMPC; VAR["COMPA"] = CHO_COMPA; VAR["RPTR2"] = CHO_RPTR2; VAR["NA"] = CHO_NA; int nextDelayAddress = 0; std::string line; int i = 1; int d = 0; while (std::getline(stream, line)) { std::string op, paramA, paramB, paramC, paramD; ReadLine(line, op, paramA, paramB, paramC, paramD); //DEBUG(i, op, paramA, paramB, paramC, line); auto tmp = line; toupper(tmp); auto pos = tmp.find("POT"); if (pos != std::string::npos && d < 3) { display += "\n"; display += line.substr(pos, std::min(line.size() - pos - 1, (size_t)24)); d++; } if (op.length() > 0 && *op.rbegin() == ':') //GOTO { replaceAll(op, ":", ""); VAR[op] = i; DEBUG(-1, op, i, line); } else if (op == "EQU" || paramA == "EQU" || op == "MEM" || paramA == "MEM" || op.length() == 0 || op[0] == ';' || op[0] == 13 || op[0] == 0) { //Comment } else { i++; } } stream.clear(); stream.seekg(0, std::ios::beg); i = 1; while (std::getline(stream, line)) { std::string op, paramA, paramB, paramC, paramD; ReadLine(line, op, paramA, paramB, paramC, paramD); //DEBUG(i, op, paramA, paramB, paramC, line); if (op.length() > 0 && *op.rbegin() == ':') { //GOTO REF DEBUG(0, op, paramA, paramB, paramC, line); } else if (op == "SKP") { auto a = INT(paramA, VAR); auto b = INT(paramB, VAR); if (VAR.find(paramB) != VAR.end()) b -= (int)fx.size() + 2; fx.push_back({OP_SKP, a, b}); DEBUG(i++, op, a, b, line); } else if (op.length() == 0 || op[0] == ';' || op[0] == 13 || op[0] == 0) { //Comment DEBUG(0, op, paramA, paramB, paramC, line); } else if (op == "EQU" || paramA == "EQU") { auto a = op == "EQU" ? paramA : op; if (paramB.find('.') != std::string::npos) { auto b = ParseFloat(paramB, VAR); DEBUG(0, op, paramA, b, line); VAR[a] = b; VAR[std::string("-") + a] = -b; } else { auto b = INT(paramB, VAR); DEBUG(0, op, paramA, b, line); VAR[a] = b; VAR[std::string("-") + a] = -b; } } else if (op == "CLR") { fx.push_back({OP_AND, 0}); DEBUG(i++, op, paramA, paramB, paramC, line); } else if (op == "NOT") { fx.push_back({OP_XOR, 0x00FFFFFF}); DEBUG(i++, op, paramA, paramB, paramC, line); } else if (op == "ABSA") { fx.push_back({OP_MAXX, 0, 0}); DEBUG(i++, op, paramA, paramB, paramC, line); } else if (op == "SOF") { auto a = S114(paramA, VAR); auto b = S10(paramB, VAR); fx.push_back({OP_SOF, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "AND") { auto a = MASK(paramA, VAR); fx.push_back({OP_AND, a}); DEBUG(i++, op, a, line); } else if (op == "OR") { auto a = MASK(paramA, VAR); fx.push_back({OP_OR, a}); DEBUG(i++, op, a, line); } else if (op == "XOR") { auto a = MASK(paramA, VAR); fx.push_back({OP_XOR, a}); DEBUG(i++, op, a, line); } else if (op == "LOG") { auto a = S114(paramA, VAR); auto b = S10(paramB, VAR); fx.push_back({OP_LOG, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "EXP") { auto a = S114(paramA, VAR); auto b = S10(paramB, VAR); fx.push_back({OP_EXP, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "WRAX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_WRAX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "MAXX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_MAXX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "RDAX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_RDAX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "LDAX") { auto a = REGADDR(paramA, VAR); fx.push_back({OP_RDFX, a, 0}); DEBUG(i++, op, a, line); } else if (op == "RDFX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_RDFX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "WRLX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_WRLX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "WRHX") { auto a = REGADDR(paramA, VAR); auto b = S114(paramB, VAR); fx.push_back({OP_WRHX, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "MULX") { auto a = REGADDR(paramA, VAR); fx.push_back({OP_MULX, a}); DEBUG(i++, op, a, line); } else if (op == "WLDS") { auto a = LFO1(paramA, VAR); auto b = INT(paramB, VAR) & 0x1ff; auto c = INT(paramC, VAR) & 0x7fff; fx.push_back({OP_WLDS, a, b, c}); DEBUG(i++, op, a, b, c, line); } else if (op == "WLDR") { auto a = LFO1(paramA, VAR); auto b = INT(paramB, VAR); auto c = INT(paramC, VAR); if (c == 512) c = 0x03 << RampLFO::AMP_OFFSET; else if (c == 1024) c = 0x02 << RampLFO::AMP_OFFSET; else if (c == 2048) c = 0x01 << RampLFO::AMP_OFFSET; else // 4096 c = 0; fx.push_back({OP_WLDR, a, b, c}); DEBUG(i++, op, a, b, c, line); } else if (op == "JAM") { auto a = LFO1(paramA, VAR); fx.push_back({OP_JAM, a}); DEBUG(i++, op, a, line); } else if (op == "MEM" || paramA == "MEM") { if (paramA == "MEM") paramA = op; auto address = nextDelayAddress; auto len = DELADDR(paramB, VAR); VAR[paramA] = address; VAR[paramA + "#"] = address + len; VAR[paramA + "^"] = address + (len / 2); nextDelayAddress += len + 1; DEBUG(0, op, address, len, line); } else if (op == "RDA") { auto a = DELADDR(paramA, VAR); auto b = S19(paramB, VAR); fx.push_back({OP_RDA, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "RMPA") { auto a = S19(paramA, VAR); fx.push_back({OP_RMPA, a}); DEBUG(i++, op, a, line); } else if (op == "WRA") { auto a = DELADDR(paramA, VAR); auto b = S19(paramB, VAR); fx.push_back({OP_WRA, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "WRAP") { auto a = DELADDR(paramA, VAR); auto b = S19(paramB, VAR); fx.push_back({OP_WRAP, a, b}); DEBUG(i++, op, a, b, line); } else if (op == "CHO" && paramA == "RDA") { auto a = LFO2(paramB, VAR); auto b = INT(paramC, VAR); auto c = DELADDR(paramD, VAR); fx.push_back({OP_CHO_RDA, a, b, c}); DEBUG(i++, op + "-" + paramA, a, b, c, line); } else if (op == "CHO" && paramA == "SOF") { auto a = LFO2(paramB, VAR); auto b = INT(paramC, VAR); auto c = S15(paramD, VAR); fx.push_back({OP_CHO_SOF, a, b, c}); DEBUG(i++, op + "-" + paramA, a, b, c, line); } else if (op == "CHO" && paramA == "RDAL") { auto a = LFO2(paramB, VAR); fx.push_back({OP_CHO_RDAL, a}); DEBUG(i++, op + "-" + paramA, a, line); } else { //DEBUG(i++, op, paramA, paramB, paramC, line); DEBUG(i, "#####FAIL ", op, line); assert(!line.c_str()); } } fv1.loadFx(fx); } void run(float inL, float inR, float pot0, float pot1, float pot2, float &outL, float &outR) { fv1.execute(inL, inR, pot0, pot1, pot2, outL, outR); } }; } // namespace rack_plugin_EH_modules
21.72625
142
0.54922
guillaume-plantevin
213e85ee0ff56ef4f0fcfa43aa93573e4a46321c
229
cpp
C++
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
#include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <stack> #include <map> #include <utility> using namespace std; class Solution { public: }; int main() { Solution s; return 0; }
9.956522
20
0.663755
5ooo
213f686c659be9ddcbabed25563e8468288e3adf
38,954
cpp
C++
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
/* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net * Project: Vulture(c) * Author : Andrea Nardinocchi * eMail : andrea@nardinan.it * * 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 "PVGroups.h" int PVgroup::build(char *string) { if (infos.player->logics.hascategory("GROUP") != 0) { if (groups.hasvalue(string) != 0) { if (groups.addvalue(string, 1) > 0) LOG_ERROR("Unable to add GROUP->%s Logic", message); else { if (infos.player->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (infos.player->logics.addvalue("GROUP", "Admin", 1) > 0) LOG_ERROR("Unable to add GROUP->Admin Logic"); else if (infos.player->logics.addvalue("GROUP", "Capo", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->logics.addvalue("GROUP", string, 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]hai fondato il gruppo \"%s\"[n]", string) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]esiste gia' un'altro gruppo con lo stesso nome![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]fai gia' parte di un gruppo![n]") > 0) return 1; return 0; } int PVgroup::add(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; char *charactername = NULL; if (string) { if ((player = pvulture.characters.getplayer(string, infos.player->position))) { if (infos.player->getID() != player->getID()) { if (player->logics.hascategory("GROUP") != 0) { if (player->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (player->logics.addvalue("GROUP", infos.player->logics.getvalue("GROUP", 3), 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (player->logics.addvalue("GROUP", "Membro", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][green]sei ora membro del gruppo \"%s\"[n]", infos.player->logics.getvalue("GROUP", 3)) > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]%s e' ora un membro del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]fa gia' parte di un'altro gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if ((mob = pvulture.characters.getmob(string, infos.player->position))) { if (mob->logics.hascategory("GROUP") != 0) { if (mob->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (mob->logics.addvalue("GROUP", infos.player->logics.getvalue("GROUP", 3), 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (mob->logics.addvalue("GROUP", "Membro", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]%s e' ora un membro del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]fa gia' parte di un'altro gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; return 0; } int PVgroup::rule(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; char *message = NULL, *pointer = NULL, *rule = NULL; if (string) { if ((message = (char *) pvmalloc(strlen(string) + 1))) { strcpy(message, string); message[strlen(string)] = '\0'; if ((pointer = strchr(message, ':'))) { for (rule = pointer + 1; *rule == ' '; rule++); do { *pointer-- = '\0'; } while ((pointer > message) && (*pointer == ' ')); if ((strlen(rule) > 0) && (strlen(message) > 0)) { if ((player = pvulture.characters.getplayer(message, infos.player->position))) { value = this->rule(player, rule); } else if ((mob = pvulture.characters.getmob(message, infos.player->position))) { value = this->rule(mob, rule); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare almeno un ruolo[n]") > 0) return 1; } else { value = this->rule(infos.player, message); } } else return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare almeno un ruolo[n]") > 0) return 1; if (message) { pvfree(message); message = NULL; } return value; } int PVgroup::rule(Cplayer *player, char *string) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) || (player->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0)) { if (player->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (player->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP RULE->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][green]sei ora nel gruppo con il ruolo di \"%s\"[n]", string) > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]%s ora ha il ruolo di \"%s\"[n]", charactername = pvulture.characters.gettargetname(player, infos.player), string) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else { if (infos.player->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (infos.player->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo ruolo in \"%s\"[n]", message) > 0) return 1; } return 0; } int PVgroup::rule(Cmob *mob, char *string) { char *charactername = NULL; if ((mob->logics.hascategory("GROUP") == 0) || (mob->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0)) { if (mob->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (mob->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][green]%s ora ha il ruolo di \"%s\"[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), string) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; return 0; } int PVgroup::exit(void) { if (infos.player->logics.hasvalue("GROUP", "Admin") != 0) { if (infos.player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else if (infos.player->pvsend(pvulture.server, "[reset][red]hai abbandonato il gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]prima di abbandonare devi cedere il trono, o sciogliere direttamente il gruppo[n]") > 0) return 1; return 0; } int PVgroup::kick(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; char *charactername = string; if ((player = pvulture.characters.getplayer(charactername, infos.player->position))) { value = kick(player); } else if ((mob = pvulture.characters.getmob(charactername, infos.player->position))) { value = kick(mob); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return value; } int PVgroup::kick(Cplayer *player) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if (player->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0) { if ((player->logics.hasvalue("GROUP", "Admin") != 0) && ((player->logics.hasvalue("GROUP", "Moderator") != 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") != 0))) { if (player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non fa piu' parte del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->pvsend(pvulture.server, "[reset][n][blue]sei stato cacciato dal gruppo da %s[n]", charactername = pvulture.characters.gettargetname(infos.player, player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]non hai sufficienti privilegi![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]%s non fa parte del tuo gruppo![n]", (player->getsex() != MALE) ? "lei" : "lui") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; return 0; } int PVgroup::kick(Cmob *mob) { char *charactername = NULL; if (mob->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0) { if ((mob->logics.hasvalue("GROUP", "Moderator") != 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") != 0)) { if (mob->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non fa piu' parte del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non hai sufficienti privilegi![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]%s non fa parte del tuo gruppo![n]", (mob->getsex() != MALE) ? "lei" : "lui") > 0) return 1; return 0; } int PVgroup::transfer(char *string) { Cplayer *player = NULL; char *charactername = string; if ((player = pvulture.characters.getplayer(charactername, infos.player->position))) { if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), player->logics.getvalue("GROUP", 3)) == 0)) { player->logics.delvalue("GROUP", "Moderator"); player->logics.delvalue("GROUP", "User"); if ((player->logics.addvalue("GROUP", "Admin", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Capitano", 2) > 0)) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if ((infos.player->logics.delvalue("GROUP", "Admin") > 0) || (infos.player->logics.addvalue("GROUP", "User", 1) > 0) || (infos.player->logics.delvalue("GROUP", 2) > 0) || (infos.player->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][blue]sei diventat%s l'admin del gruppo![n]", (player->getsex() != MALE) ? "a" : "o") > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][blue]hai ceduto la tua carica di admin a %s[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return 0; } int PVgroup::moderator(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; if ((player = pvulture.characters.getplayer(string, infos.player->position))) { value = moderator(player); } else if ((mob = pvulture.characters.getmob(string, infos.player->position))) { value = moderator(mob); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return value; } int PVgroup::moderator(Cplayer *player) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), player->logics.getvalue("GROUP", 3)) == 0)) { if (player->logics.hasvalue("GROUP", "Moderator") != 0) { player->logics.delvalue("GROUP", "User"); if ((player->logics.addvalue("GROUP", "Moderator", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Vice", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s e' ora un vice[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (player->pvsend(pvulture.server, "[reset][n][blue]sei diventat%s vice del gruppo![n]", (player->getsex() != MALE) ? "a una" : "o un") > 0) return 1; if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else { player->logics.delvalue("GROUP", "Moderator"); if ((player->logics.addvalue("GROUP", "User", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non e' piu' %s vice[n]", charactername = pvulture.characters.gettargetname(player, infos.player), (player->getsex() != MALE) ? "una" : "un") > 0) return 1; if (player->pvsend(pvulture.server, "[reset][n][blue]l'incarico di vice ti e' stato tolto![n]") > 0) return 1; if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } return 0; } int PVgroup::moderator(Cmob *mob) { char *charactername = NULL; if ((mob->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), mob->logics.getvalue("GROUP", 3)) == 0)) { if (mob->logics.hasvalue("GROUP", "Moderator") != 0) { mob->logics.delvalue("GROUP", "User"); if ((mob->logics.addvalue("GROUP", "Moderator", 1) > 0) || (mob->logics.delvalue("GROUP", 2) > 0) || (mob->logics.addvalue("GROUP", "Vice", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][blue]%s e' ora %s vice[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), (mob->getsex() != MALE) ? "una" : "un") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } else { mob->logics.delvalue("GROUP", "Moderator"); if ((mob->logics.addvalue("GROUP", "User", 1) > 0) || (mob->logics.delvalue("GROUP", 2) > 0) || (mob->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non e' piu' %s vice[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), (mob->getsex() != MALE) ? "una" : "un") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; return 0; } int PVgroup::bounce(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; if ((player = pvulture.characters.getplayer(string)) && (player->position)) { if (infos.player->getID() != player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(player->logics.getvalue("GROUP", 3), infos.player->logics.getvalue("GROUP", 3)) == 0)) { if ((infos.player->position->getID() != player->position->getID()) || (infos.player->position->getzoneID() != player->position->getzoneID())) { if (infos.player->position->getplayer(infos.player->getID())) { if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1; } if (infos.player->pvsend(pvulture.server, "[reset][green]ti muovi presso %s[n]", string) > 0) return 1; if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) { if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (spvsend(pvulture.server, player->position, "[reset][n][yellow]$name appare da una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1; if (player->position->spvsend(pvulture.server, sshell) > 0) return 1; } if (player->position->addplayer(infos.player) > 0) return 1; if (environmentcommands.lookenvironment() > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]si trova proprio qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if ((mob = pvulture.characters.getmob(message)) && (mob->position)) { if ((mob->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(mob->logics.getvalue("GROUP", 3), infos.player->logics.getvalue("GROUP", 3)) == 0)) { if ((infos.player->position->getID() != mob->position->getID()) || (infos.player->position->getzoneID() != mob->position->getzoneID())) { if (infos.player->position->getplayer(infos.player->getID())) { if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1; } if (infos.player->pvsend(pvulture.server, "[reset][green]ti muovi presso %s[n]", string) > 0) return 1; if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) { if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (spvsend(pvulture.server, player->position, "[reset][n][yellow]$name appare da una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1; if (mob->position->spvsend(pvulture.server, sshell) > 0) return 1; } if (mob->position->addplayer(infos.player) > 0) return 1; if (environmentcommands.lookenvironment() > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]si trova proprio qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non c'e' nessuno con quel nome in questo mondo![n]") > 0) return 1; return 0; } int PVgroup::chat(char *string) { playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3), *charactername = NULL, *emoticon = NULL, *message = NULL; if ((message = (char *) pvmalloc(strlen(string) + 1))) { strcpy(message, string); message[strlen(string)] = '\0'; emoticon = getemoticon(&message); if (message) { while (player) { if ((infos.player->getID() != player->player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->pvsend(pvulture.server, "[n][reset][blue]%s vi dice %s: \"%s\"[reset][n]", charactername = pvulture.characters.gettargetname(infos.player, player->player), (emoticon) ? emoticon : "", message) > 0) return 1; if (player->player->spvsend(pvulture.server, sshell) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } player = player->next; } if (infos.player->pvsend(pvulture.server, "[reset][blue]dici al tuo gruppo %s: \"%s\"[reset][n]", (emoticon) ? emoticon : "", message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un messaggio![n]") > 0) return 1; } else return 1; if (emoticon) { pvfree(emoticon); emoticon = NULL; } if (message) { pvfree(message); message = NULL; } return 0; } int PVgroup::list(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3); if (infos.player->pvsend(pvulture.server, "membri del gruppo \"[bold]%s[reset]\" ora collegati:[n]", groupname) > 0) return 1; while (player) { if ((player->player->getID() != infos.player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->logics.hasvalue("STATUS", "Password") != 0) { if (infos.player->pvsend(pvulture.server, "\t[reset][green](online)[reset]%s(%d) %s[n]", ((player->player->logics.hasvalue("GROUP", "Admin") != 0) ? ((player->player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]") : "[green]"), player->player->getID(), pvulture.characters.getsimplename(player->player)) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "\t[reset][yellow](passwd)[reset]%s(%d) %s[n]", ((player->player->logics.hasvalue("GROUP", "Admin") != 0) ? ((player->player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]") : "[green]"), player->player->getID(), pvulture.characters.getsimplename(player->player)) > 0) return 1; } player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) if (infos.player->pvsend(pvulture.server, "\t[reset][green](online)[reset]%s(%d) %s[n]", (infos.player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]", mob->mob->getID(), pvulture.characters.getsimplename(mob->mob)) > 0) return 1; mob = mob->next; } return 0; } int PVgroup::destroy(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3); if (groups.delvalue(groupname) > 0) LOG_ERROR("Unable to delete GROUPS->%s Logic", groupname); while (player) { if ((infos.player->getID() != player->player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); if (player->player->pvsend(pvulture.server, "[n][blue]Il tuo gruppo e' stato sciolto![n]") > 0) return 1; if (player->player->spvsend(pvulture.server, sshell) > 0) return 1; } player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) { if (player->player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); } mob = mob->next; } if (infos.player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); return 0; } int PVgroup::information(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; int index = 0; char *groupname = infos.player->logics.getvalue("GROUP", 3); while (player) { if (player->player->logics.hasvalue("GROUP", groupname) == 0) index++; player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) index++; mob = mob->next; } if (infos.player->pvsend(pvulture.server, "[reset]fai parte del gruppo [blue]\"[bold]%s[reset][blue]\"[reset]", infos.player->logics.getvalue("GROUP", 3)) > 0) return 1; if (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 1), "Admin") == 0) { if (infos.player->pvsend(pvulture.server, " (di cui sei [green]il capo[reset]) ") > 0) return 1; } else if (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 1), "Moderator") == 0) { if (infos.player->pvsend(pvulture.server, " (di cui sei [yellow]un vice[reset]) ") > 0) return 1; } if (infos.player->pvsend(pvulture.server, "che conta %d membri![n]\t[reset]il tuo ruolo e' [blue]\"[bold]%s[reset][blue]\"[reset][n]", index, infos.player->logics.getvalue("GROUP", 2)) > 0) return 1; return 0; } PVgroup groupcommands; int group(void) { char *message = NULL, *command = NULL, *subcommand = NULL; if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) { strcpy(message, infos.message); message[strlen(infos.message)] = '\0'; if ((command = strings.vpop(&message)) && (subcommand = strings.vpop(&message))) { if (compare.vcmpcase(subcommand, CSTRSIZE("crea")) == 0) { if (message) { if (groupcommands.build(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (infos.player->logics.hascategory("GROUP") == 0) { if (compare.vcmpcase(subcommand, CSTRSIZE("abbandona")) == 0) { if (groupcommands.exit() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("lista")) == 0) { if (groupcommands.list() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("info")) == 0) { if (groupcommands.information() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("di")) == 0) { if (message) { if (groupcommands.chat(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un messaggio![n]") > 0) return 1; } else if ((infos.player->logics.hasvalue("GROUP", "Admin") == 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") == 0)) { if (compare.vcmpcase(subcommand, CSTRSIZE("caccia")) == 0) { if (message) { if (groupcommands.kick(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("aggiungi")) == 0) { if (message) { if (groupcommands.add(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (infos.player->logics.hasvalue("GROUP", "Admin") == 0) { if (compare.vcmpcase(subcommand, CSTRSIZE("ruolo")) == 0) { if (message) { if (groupcommands.rule(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un ruolo![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("moderatore")) == 0) { if (message) { if (groupcommands.moderator(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("cedi")) == 0) { if (message) { if (groupcommands.transfer(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("vai")) == 0) { if (message) { if (groupcommands.bounce(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("sciogli")) == 0) { if (groupcommands.destroy() > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]hai sciolto il tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]prego?[n]") > 0) return 1; } else return 1; if (subcommand) { pvfree(subcommand); subcommand = NULL; } if (command) { pvfree(command); command = NULL; } if (message) { pvfree(message); message = NULL; } return 0; }
54.178025
193
0.507753
nardinan
21462d66e49eaeaa64b3b399bc64b9b1e175fbd7
28,371
cpp
C++
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
1
2021-07-21T00:58:45.000Z
2021-07-21T00:58:45.000Z
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> #include <tchar.h> #include <crass_types.h> #include <acui.h> #include <cui.h> #include <package.h> #include <resource.h> #include <cui_error.h> #include <stdio.h> #include <crass/locale.h> #include <utility.h> #include <vector> #include <string> #include <xerisa.h> /* 【game参数游戏支持列表】 ·ドS姉とボクの放尿関係 game=ane ·要!エプロン着用 体验版 game=ApronedOnly ·いろは ~秋の夕日に影ふみを~ 体験版 game=rural ·Alea -アレア- 紅き月を遙かに望み 体験版 game=Alea ·donor[ドナー] 体験版 game=donor ·絶対女子寮域!体験版 game=aftrial ·淫乳ファミレス ~深夜の母乳サービスはいかが? game=fami ·隣り妻2 ~淫惑の閨房~ 体験版 game=NWives2 ·アメサラサ ~雨と不思議な君に、恋をする 体験版 game=ame Chanter(シャンテ) -キミの歌がとどいたら-.rar [081205]ヨスガノソラ 搜索密码: C源码 00405060 /$ 83EC 10 SUB ESP,10 ; dec 00405063 |. 53 PUSH EBX 00405064 |. 55 PUSH EBP 00405065 |. 8BE9 MOV EBP,ECX ; cxt0 00405067 |. 56 PUSH ESI 00405068 |. 57 PUSH EDI 00405069 |. 8B4D 14 MOV ECX,DWORD PTR SS:[EBP+14] ; (0)i? 0040506C |. 8D41 01 LEA EAX,DWORD PTR DS:[ECX+1] ; ++i 0040506F |. 8945 14 MOV DWORD PTR SS:[EBP+14],EAX 00405072 |. 8B5D 0C MOV EBX,DWORD PTR SS:[EBP+C] ; (0x20)ERISADecodeContextLength 00405075 |. 8B55 08 MOV EDX,DWORD PTR SS:[EBP+8] ; 113fa90? ERISADecodeContext 00405078 |. 3BC3 CMP EAX,EBX ; orig_i VS ERISADecodeContextLength 0040507A |. 895C24 18 MOV DWORD PTR SS:[ESP+18],EBX ; save ERISADecodeContextLength 0040507E |. 895424 1C MOV DWORD PTR SS:[ESP+1C],EDX ; ERISADecodeContext <-- 查看这个buffer 00405082 |. 7C 07 JL SHORT noa32c.0040508B 00405084 |. C745 14 00000>MOV DWORD PTR SS:[EBP+14],0 ; i = 0 0040508B |> 8D7D 58 LEA EDI,DWORD PTR SS:[EBP+58] ; array32_1 0040508E |. BA A8FFFFFF MOV EDX,-58 ; -58 <---关键字 00405093 |. 8BC7 MOV EAX,EDI ; array32_1 00405095 |. 2BD5 SUB EDX,EBP ; -58 - obj 00405097 |> C640 C0 00 /MOV BYTE PTR DS:[EAX-40],0 ; memset(array32_0, 0, 32) 0040509B |. C600 00 |MOV BYTE PTR DS:[EAX],0 ; memset(array32_1, 0, 32) 汇编: ERIBshfBuffer@@DecodeBuffer PROC NEAR32 SYSCALL USES ebx esi edi mov ebx, ecx ASSUME ebx:PTR ERIBshfBuffer ; ; 復号の準備 ; mov eax, [ebx].m_dwPassOffset mov esi, eax ; esi = iPos inc eax xor edx, edx .IF eax >= [ebx].m_strPassword.m_nLength xor eax, eax .ENDIF mov [ebx].m_dwPassOffset, eax ; xor ecx, ecx .REPEAT mov DWORD PTR [ebx].m_bufBSHF[ecx], edx mov DWORD PTR [ebx].m_maskBSHF[ecx], edx add ecx, 4 .UNTIL ecx >= 32 ; ; 暗号を復号 ; xor edi, edi ; edi = iBit mov edx, [ebx].m_strPassword.m_pszString 《---密码 push ebp mov ebp, 256 .REPEAT movzx eax, BYTE PTR [edx + esi] inc esi add edi, eax cmp esi, [ebx].m_strPassword.m_nLength sbb edx, edx and edi, 0FFH mov eax, edi mov ecx, edi shr eax, 3 and esi, edx mov dl, 80H and ecx, 07H shr dl, cl ; .WHILE [ebx].m_maskBSHF[eax] == 0FFH inc eax add edi, 8 and eax, 1FH 《-- 关键指令 and edi, 0FFH .ENDW 断点挺直后,搜索内存,关键字key=,然后dump这段内存,保存的就是xml数据 */ /* exe内藏加密资源型密码分析用: M:\Program Files\highsox\愨懳彈巕椌堟両 懱尡斉 exe内藏加密资源型密码测试用: Q:\Program Files\highsox\SpycyTrial exe加壳,密码未知: Q:\[unpack]\[noa](18禁ゲーム)すぺ~す☆とらぶる */ using namespace std; using std::vector; static int debug; static int EntisGLS_locale_id; static const TCHAR *simplified_chinese_strings[] = { _T("%s: crc校验失败(0x%08x), 应该是0x%08x.\n"), _T("%s: 指定的exe文件不存在, 请在exe=的后面用\"\"把路径信息括起来.\n"), }; static const TCHAR *traditional_chinese_strings[] = { _T("%s: crc校驗失敗(0x%08x), 應該是0x%08x.\n"), _T("%s: 指定的exe文件不存在, 請在exe=的後面用\"\"把路徑信息括起來.\n"), }; static const TCHAR *japanese_strings[] = { _T("%s: crcチェック失敗(0x%08x)、もとい0x%08x。\n"), _T("%s: 指定されたexeファイルは存在しません、exe=の後に\"\"でパスメッセージを括ってください。\n"), }; static const TCHAR *default_strings[] = { _T("%s: crc error(0x%08x), shoule be 0x%08x.\n"), _T("%s: the exe file specified doesn't exist, please add \"\" pair to surond the path information behind exe=.\n"), }; static struct locale_configuration EntisGLS_locale_configurations[4] = { { 936, simplified_chinese_strings, 2 }, { 950, traditional_chinese_strings, 2 }, { 932, japanese_strings, 2 }, { 0, default_strings, 2 }, }; /* 接口数据结构: 表示cui插件的一般信息 */ struct acui_information EntisGLS_cui_information = { _T("Leshade Entis, Entis-soft."), /* copyright */ _T("Entis Generalized Library Set version 3"), /* system */ _T(".noa .dat .arc"), /* package */ _T("0.5.0"), /* revision */ _T("痴漢公賊"), /* author */ _T("2009-5-2 17:08"), /* date */ NULL, /* notion */ ACUI_ATTRIBUTE_LEVEL_DEVELOP }; /* 所有的封包特定的数据结构都要放在这个#pragma段里 */ #pragma pack (1) typedef struct { s8 header_code[8]; // "Entis\x1a\x00\x00" /* erisafile.h: fidArchive = 0x02000400, fidRasterizedImage = 0x03000100, fidEGL3DSurface = 0x03001100, fidEGL3DModel = 0x03001200, fidUndefinedEMC = -1 */ u32 file_id; u32 reserved; // 0 s8 format_desc[40]; u32 record_len_lo; u32 record_len_hi; } noa_header_t; typedef struct { s8 dir_record_code[8]; // "DirEntry" u32 dir_record_len_lo; u32 dir_record_len_hi; //u32 index_entries; // 包含在dir_record_len } noa_dir_record_t; typedef struct { u32 data_len_lo; // 原始长度 u32 data_len_hi; /* erisafile.h: attrNormal = 0x00000000, attrReadOnly = 0x00000001, attrHidden = 0x00000002, attrSystem = 0x00000004, attrDirectory = 0x00000010, attrEndOfDirectory = 0x00000020, attrNextDirectory = 0x00000040 */ u32 attribute; /* erisafile.h: etRaw = 0x00000000, // /raw etERISACode = 0x80000010, // default or /r etBSHFCrypt = 0x40000000, // /bshf etERISACrypt = 0xC0000010 */ u32 encode_type; u32 data_offset_lo; // 相对于目录项 u32 data_offset_hi; u8 second; u8 minute; u8 hour; u8 week; u8 day; u8 month; u16 year; u32 extra_info_len; u8 *extra_info; u32 name_len; u8 *name; } noa_dir_record_info_t; typedef struct { s8 file_record_code[8]; // "filedata" u32 file_record_len_lo; u32 file_record_len_hi; } noa_file_record_t; #pragma pack () typedef struct { char path[MAX_PATH]; u64 offset; u64 length; u32 extra_info_len; u8 *extra_info; u32 encode_type; u32 attr; } my_noa_entry_t; struct game_key_sub_table { char path[32]; // 封包名 char password[256]; }; struct game_key_table { char caption[128]; // 游戏名 unsigned int number; struct game_key_sub_table sub_table[32]; }; static struct game_key_table default_key_table = { "default", 1, { { "", " " }, } }; // 对于exe不能提取的游戏(比如exe加壳),使用game参数 static struct game_key_table game_key_table_list[] = { #if 0 /* 要!エプロン着用 体验版(临时用) */ { "ApronedOnly", 1, { { "ContainerB.noa", "7DQ1Xm7ZahIv1ZwlFgyMTMryKC6OP9V6cAgL64WD5JLyvmeEyqTSA5rUbRigOtebnnK4MuOptwsbOf4K8UBDH4kpAUOQgB71Qr1qxtHGxQl8KZKj6WIYWpPh0G3JOJat" } } }, /* Alea -アレア- 紅き月を遙かに望み 体験版(临时用) */ { "Alea", 1, { { "Data2.noa", "faTSgh75PfbZHctOvW3hHphnA7LEaa8gm5qMcI5Bn4eZa3bzbRwA8E4CnNocr2pG16KMdhSyZSiRJ1b27ECw2RSsIyfxsgFyworNlq6q7qYnqZ9SO2cnQws4hFGjb9Dl" } } }, /* donor[ドナー] 体験版(临时用) */ { "donor", 2, { { "data1.noa", "vfhvbqwydyqgbpv6teq" }, { "data3.noa", "vdsygo3423byfwo" } } }, /* 絶対女子寮域!体験版(临时用) */ { "aftrial", 1, { "ContainerB.noa", "XFwcnU1Qn3mUICUv" "pw1KgEuc9eVRZWQz" "DtKgf9dSQSNcnB6O" "YvntbzwULCU81Lvx" "WLJFX64NvGPKMUPx" "lKrUVJaNHCzfdkCQ" "wXYp7rI6fsi4T1nV" "4rg75JoiXnTbkQFM" } }, /* ドS姉とボクの放尿関係(临时用) */ { "ane", 2, { { "d02.dat", "vwerc7s65r21bnfu" }, { "d03.dat", "ctfvgbhnj67y8u" } } }, { "SpaceTrouble", 1, #if 0 { "PtOJsyBhKoZHH4Lm" "9trW0EAhVWc5ufMR" "Xl7MoYsnOHfhRyRN" "n4ka4q9SddgGCVL2" "tPbIrLLTgejeSbnA" "UYVYYUY2YV12YVU9" "IF09IV32IV31NV12" "RAW8DXT1DXT2DXT3" "DXT4DXT5NVHSNVHU" "NVCSNVBF" "Z062D9322446GM" } #endif }, /* 淫乳ファミレス~深夜の母乳サービスはいかが?(临时用) */ { "fami", 2, { { "d01.dat", "vdiu$43AfUCfh9aksf" }, { "d03.dat", "gaivnwq7365e021gf" }, } }, /* 隣り妻2 体験版(临时用) */ { "NWives2", 2, { { "Data6.noa", "ahyohsimohfaish1ao6ohh6edoh1yeezooDooj4Eabie0Aik4neeJohl0doo6fie2Iedao4poh9ahMoothohm3ba5LieC2beeba3hiyu1wit2fachae2Eecheed5kahc" }, { "Data7.noa", "fee4Thaixuol2siema2azeiha7Quek2Egh5soov1soich1haeShu2Vuashai6ba1Gejei0eonooz0cooliciexoh1WohmaBaemaezieraibeevohjeceiT5eecogh1eo" }, } }, /* アメサラサ ~雨と不思議な君に、恋をする 体験版(临时用) */ { "ame", 1, { { "system.noa", "lipsync" } } }, /* いろは ~秋の夕日に影ふみを~ 体験版(临时用) */ { "rural", 2, { { "scenario.noa", "0XT9ORIT0WlIl7U16yjKxTCyUOYZoN1cL7FxrBTiuvi0EY50b7Pu8uvLVlX0opOU5ash97Bkkqq" }, { "graphics02.noa", "2o3bZEwqb9JMfkU4CYv2BaAD2sSdyUxtiAR4IQWG8UP6EmWkN0JcA9nmV6MAHH3AspaGBUqib3i" } } }, #endif /* 终止项 */ { "", 0, } }; /* 包含运行时需要的所有可能的tbl */ static vector<struct game_key_table> runtime_game_key_table; static struct game_key_sub_table *cur_sub_table; //static BYTE BshfCode[512]; //static DWORD BshfCodePos; //static DWORD BshfCodeLen; static u32 ERISACrc(BYTE *data, DWORD data_len) { BYTE crc[4] = { 0, 0, 0, 0 }; for (DWORD i = 0; i < data_len; ++i) crc[i & 3] ^= data[i]; return crc[0] | (crc[1] << 8) | (crc[2] << 16) | (crc[3] << 24); } #if 0 static void ERIBshfDecodeInit(const char *password) { int len; if (!password) password = " "; len = strlen(password); strcpy((char *)BshfCode, password); if (len < 32) { BshfCode[len++] = 0x1b; for (DWORD i = len; i < 32; ++i) BshfCode[i] = BshfCode[i - 1] + BshfCode[i % len]; len = 32; } BshfCodeLen = len; BshfCodePos = 0; if (debug) { printf("Dump BshfCode (%d bytes)\n", len); printf("Use password: \"%s\"\n", password); for (DWORD i = 0; i < len; ++i) printf("0x%02x ", BshfCode[i]); printf("\n"); } } static int __ERIBshfDecode(BYTE *BSHF_dst, DWORD BSHF_dst_len, BYTE *BSHF_src, DWORD BSHF_src_len) { DWORD act_BSHF_dst_len = 0; u32 crc = *(u32 *)&BSHF_src[BSHF_src_len - 4]; for (DWORD i = 0; i < BSHF_src_len / 32; ++i) { BYTE BSHF_mask[32]; BYTE BSHF_buf[32]; BYTE bit = 0; BYTE cur = i; memset(BSHF_mask, 0, sizeof(BSHF_mask)); memset(BSHF_buf, 0, sizeof(BSHF_buf)); for (DWORD k = 0; k < 256; ++k) { bit += BshfCode[cur++ % BshfCodeLen]; BYTE mask = 0x80 >> (bit & 7); while (BSHF_mask[bit / 8] == 0xff) bit += 8; while (BSHF_mask[bit / 8] & mask) { ++bit; mask >>= 1; if (!mask) { bit += 8; mask = 0x80; } } BSHF_mask[bit / 8] |= mask; if (BSHF_src[k / 8] & (0x80 >> (k & 7))) BSHF_buf[bit / 8] |= mask; } BSHF_src += 32; for (k = 0; k < 32; ++k) { BSHF_dst[act_BSHF_dst_len++] = BSHF_buf[k]; if (act_BSHF_dst_len >= BSHF_dst_len) goto out; } } out: return ERISACrc(BSHF_dst, act_BSHF_dst_len, crc); } #endif #if 1 static int ERIBSHFDecode(BYTE *dec, DWORD dec_len, BYTE *enc, DWORD enc_len, char *pwd) { EMemoryFile DEC; DEC.Open(enc, enc_len); ESLFileObject *file = DEC.Duplicate(); ERISADecodeContext BSHF(dec_len); BSHF.AttachInputFile(file); BSHF.PrepareToDecodeBSHFCode(pwd); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(dec_len); int ret = BSHF.DecodeBSHFCodeBytes((SBYTE *)ptrBuf, dec_len); if (ret > 0) memcpy(dec, ptrBuf, dec_len); delete file; return ret; } #else static int ERIBshfDecode(BYTE *BSHF_dst, DWORD BSHF_dst_len, BYTE *BSHF_src, DWORD BSHF_src_len) { int ret = __ERIBshfDecode(BSHF_dst, BSHF_dst_len, BSHF_src, BSHF_src_len); if (!ret) { for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { struct game_key_table &tbl = runtime_game_key_table[i]; for (DWORD k = 0; k < tbl.number; ++k) { if (cur_sub_table && cur_sub_table == &tbl.sub_table[k]) continue; ERIBshfDecodeInit(tbl.sub_table[k].password); ret = __ERIBshfDecode(BSHF_dst, BSHF_dst_len, BSHF_src, BSHF_src_len); if (ret) { cur_sub_table = &tbl.sub_table[k]; return 1; } } } } cur_sub_table = default_key_table.sub_table; return ret; } #endif static void parse_xml_data(char *xml_cfg) { string xml = xml_cfg; string::size_type begin, end; char game[256] = "no_name"; int game_name_len = strlen(game); struct game_key_table entry; unsigned int &i = entry.number; begin = xml.find("<display caption=\"", 0); if (begin != string::npos) { begin += strlen("<display caption=\""); end = xml.find("\"", begin); if (end == string::npos) return; memcpy(game, &xml[begin], end - begin); game_name_len = end - begin; } begin = 0; i = 0; while ((begin = xml.find("<archive ", begin)) != string::npos) { end = xml.find("/>", begin); if (end == string::npos) break; string::size_type path = xml.find("path=", begin); if (path == string::npos || path >= end) break; string::size_type key = xml.find("key=", begin); if (key == string::npos || key >= end) { begin = end + 2; continue; } memset(entry.sub_table[i].password, 0, sizeof(entry.sub_table[i].password)); memcpy(entry.sub_table[i].password, &xml[key + 5] /* "key=\"" */, end - key - 5 /* "key=\"" */ - 1 /* "\"" */); memset(entry.sub_table[i].path, 0, sizeof(entry.sub_table[i].path)); string::size_type dim; dim = xml.rfind("\\", key - 1); if (dim == string::npos || dim <= path) dim = path + 6 /* "path=\"" */; else ++dim; // 通常情况,xml里会对加密的noa所在光盘和硬盘上不同的位置有 // 2组key,内容都一样,所以这里进行检查,不加入重复的key。 for (DWORD k = 0; k < i; ++k) { if (!strcmp(entry.sub_table[k].path, &xml[dim])) goto not_insert; } memcpy(entry.sub_table[i].path, &xml[dim], key - 1 /* " " */ - dim - 1 /* "\"" */); not_insert: begin = end + 2; ++i; } if (i) { game[game_name_len] = 0; strcpy(entry.caption, game); runtime_game_key_table.push_back(entry); } } static int load_exe_xml(const char *exe_file) { if (!exe_file) return 0; HMODULE exe = LoadLibraryA(exe_file); if ((DWORD)exe > 31) { HRSRC code = FindResourceA(exe, "IDR_COTOMI", (const char *)RT_RCDATA); if (code) { DWORD sz = SizeofResource(exe, code); HGLOBAL hsrc = LoadResource(exe, code); if (hsrc) { LPVOID cipher = LockResource(hsrc); if (cipher) { EMemoryFile xml; xml.Open(cipher, sz); ERISADecodeContext ERISA(0x10000); ESLFileObject *dup = xml.Duplicate(); ERISA.AttachInputFile(dup); ERISA.PrepareToDecodeERISANCode(); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(0x10000); unsigned int Result = ERISA.DecodeERISANCodeBytes((SBYTE *)ptrBuf, 0x10000); if (debug) MySaveFile(_T("exe.xml"), ptrBuf, Result); parse_xml_data((char *)ptrBuf); delete dup; return runtime_game_key_table.size(); } FreeResource(hsrc); } } FreeLibrary(exe); } else { TCHAR exe_path[MAX_PATH]; acp2unicode(exe_file, -1, exe_path, MAX_PATH); locale_app_printf(EntisGLS_locale_id, 1, exe_path); } return 0; } /********************* noa *********************/ /* 封包匹配回调函数 */ static int EntisGLS_noa_match(struct package *pkg) { noa_header_t noa_header; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, &noa_header, sizeof(noa_header))) { pkg->pio->close(pkg); return -CUI_EREAD; } if (memcmp(noa_header.header_code, "Entis\x1a\x00\x00", 8) || noa_header.file_id != 0x02000400 || noa_header.reserved) { pkg->pio->close(pkg); return -CUI_EMATCH; } //BshfCodePos = 0; return 0; } static int noa_dir_record_process(struct package *pkg, vector<my_noa_entry_t> &my_noa_index, char *path_name) { u64 base_offset; pkg->pio->locate64(pkg, (u32 *)&base_offset, ((u32 *)&base_offset) + 1); noa_dir_record_t dir_rec; if (pkg->pio->read(pkg, &dir_rec, sizeof(dir_rec))) return -CUI_EREAD; if (strncmp(dir_rec.dir_record_code, "DirEntry", sizeof(dir_rec.dir_record_code))) return -CUI_EMATCH; BYTE *dir_rec_info = new BYTE[dir_rec.dir_record_len_lo]; if (!dir_rec_info) return -CUI_EMEM; if (pkg->pio->read(pkg, dir_rec_info, dir_rec.dir_record_len_lo)) { delete [] dir_rec_info; return -CUI_EREAD; } BYTE *p_dir = dir_rec_info; u32 index_entries = *(u32 *)p_dir; p_dir += 4; int ret = 0; for (DWORD i = 0; i < index_entries; ++i) { my_noa_entry_t entry; entry.length = *(u64 *)p_dir; p_dir += 8; u32 attr = *(u32 *)p_dir; p_dir += 4; entry.attr = attr; entry.encode_type = *(u32 *)p_dir; p_dir += 4; entry.offset = *(u64 *)p_dir + base_offset; p_dir += 16; // bypass filetime entry.extra_info_len = *(u32 *)p_dir; p_dir += 4; if (entry.extra_info_len) { entry.extra_info = new BYTE[entry.extra_info_len]; if (!entry.extra_info) break; } else entry.extra_info = NULL; p_dir += entry.extra_info_len; sprintf(entry.path, "%s\\%s", path_name, (char *)p_dir + 4); p_dir += 4 + *(u32 *)p_dir; my_noa_index.push_back(entry); if (attr == 0x00000010) { // attrDirectory noa_file_record_t file_rec; // 目录项也是个filedata if (pkg->pio->readvec64(pkg, &file_rec, sizeof(file_rec), 0, (u32)entry.offset, (u32)(entry.offset >> 32), IO_SEEK_SET)) { ret = -CUI_EREADVEC; break; } ret = noa_dir_record_process(pkg, my_noa_index, entry.path); if (ret) break; } else if (attr == 0x00000020) { // attrEndOfDirectory printf("attrEndOfDirectory!!\n");exit(0); } else if (attr == 0x00000040) { // attrNextDirectory printf("attrNextDirectory!!\n");exit(0); } } delete [] dir_rec_info; return ret; } /* 封包索引目录提取函数 */ static int EntisGLS_noa_extract_directory(struct package *pkg, struct package_directory *pkg_dir) { vector<my_noa_entry_t> my_noa_index; int ret; my_noa_entry_t root_dir; memset(&root_dir, 0, sizeof(root_dir)); root_dir.attr = 0x00000010; my_noa_index.push_back(root_dir); ret = noa_dir_record_process(pkg, my_noa_index, "."); if (ret) return ret; DWORD index_entries = 0; for (DWORD i = 0; i < my_noa_index.size(); ++i) { // printf("%d %s %x %x %x\n", i, my_noa_index[i].path, // my_noa_index[i].attr, my_noa_index[i].offset, // (u32)my_noa_index[i].length); if (my_noa_index[i].attr != 0x00000010 && my_noa_index[i].attr != 0x00000020 && my_noa_index[i].attr != 0x00000040) ++index_entries; } my_noa_entry_t *index = new my_noa_entry_t[index_entries]; if (!index) return -CUI_EMEM; DWORD k = 0; for (i = 0; i < my_noa_index.size(); ++i) { if (my_noa_index[i].attr == 0x00000010) { // attrDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; } else if (my_noa_index[i].attr == 0x00000020) { // attrEndOfDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; printf("attrEndOfDirectory!!\n");exit(0); } else if (my_noa_index[i].attr == 0x00000040) { // attrNextDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; printf("attrNextDirectory!!\n");exit(0); } else index[k++] = my_noa_index[i]; } pkg_dir->index_entries = index_entries; pkg_dir->directory = index; pkg_dir->directory_length = index_entries * sizeof(my_noa_entry_t); pkg_dir->index_entry_length = sizeof(my_noa_entry_t); pkg_dir->flags = PKG_DIR_FLAG_SKIP0; return 0; } /* 封包索引项解析函数 */ static int EntisGLS_noa_parse_resource_info(struct package *pkg, struct package_resource *pkg_res) { my_noa_entry_t *my_noa_entry; my_noa_entry = (my_noa_entry_t *)pkg_res->actual_index_entry; strcpy(pkg_res->name, my_noa_entry->path); pkg_res->name_length = -1; /* -1表示名称以NULL结尾 */ pkg_res->raw_data_length = (u32)my_noa_entry->length; pkg_res->actual_data_length = (u32)my_noa_entry->length; pkg_res->offset = (u32)my_noa_entry->offset; return 0; } /* 封包资源提取函数 */ static int EntisGLS_noa_extract_resource(struct package *pkg, struct package_resource *pkg_res) { my_noa_entry_t *my_noa_entry = (my_noa_entry_t *)pkg_res->actual_index_entry; noa_file_record_t file_rec; u64 offset = my_noa_entry->offset; if (pkg->pio->readvec64(pkg, &file_rec, sizeof(file_rec), 0, (u32)offset, (u32)(offset >> 32), IO_SEEK_SET)) return -CUI_EREADVEC; u64 raw_len = (u64)file_rec.file_record_len_lo | ((u64)file_rec.file_record_len_hi << 32); BYTE *raw = new BYTE[(u32)raw_len]; if (!raw) return -CUI_EMEM; offset += sizeof(file_rec); if (pkg->pio->readvec64(pkg, raw, (u32)raw_len, (u32)(raw_len >> 32), (u32)offset, (u32)(offset >> 32), IO_SEEK_SET)) { delete [] raw; return -CUI_EREADVEC; } pkg_res->raw_data_length = raw_len; pkg_res->actual_data_length = my_noa_entry->length; if (my_noa_entry->encode_type == 0x00000000) // etRaw pkg_res->raw_data = raw; else if (my_noa_entry->encode_type == 0x80000010) { // etERISACode EMemoryFile dec; dec.Open(raw, pkg_res->raw_data_length); ERISADecodeContext ERISA(pkg_res->actual_data_length); ESLFileObject *dup = dec.Duplicate(); ERISA.AttachInputFile(dup); ERISA.PrepareToDecodeERISANCode(); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(pkg_res->actual_data_length); pkg_res->actual_data_length = ERISA.DecodeERISANCodeBytes((SBYTE *)ptrBuf, pkg_res->actual_data_length); BYTE *act = new BYTE[pkg_res->actual_data_length]; if (!act) { delete [] raw; return -CUI_EMEM; } memcpy(act, ptrBuf, pkg_res->actual_data_length); delete dup; pkg_res->raw_data = raw; pkg_res->actual_data = act; } else if (my_noa_entry->encode_type == 0x40000000) { // etBSHFCrypt #if 1 BYTE *act = new BYTE[pkg_res->actual_data_length]; if (!act) { delete [] raw; return -CUI_EMEM; } char pkg_name[MAX_PATH]; unicode2acp(pkg_name, MAX_PATH, pkg->name, -1); for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { struct game_key_table &tbl = runtime_game_key_table[i]; for (DWORD k = 0; k < tbl.number; ++k) { if (tbl.sub_table[k].path[0] && strcmpi(pkg_name, tbl.sub_table[k].path)) continue; if (!pkg_res->index_number && debug) { printf("%s: using password \"%s\"", pkg_name, tbl.sub_table[k].password); if (tbl.sub_table[k].path[0]) printf(" for %s\n\n", tbl.sub_table[k].path); } int act_len = ERIBSHFDecode(act, pkg_res->actual_data_length, raw, pkg_res->raw_data_length-4, tbl.sub_table[k].password); if (act_len <= 0) { delete [] act; delete [] raw; return -CUI_EUNCOMPR; } u32 crc = *(u32 *)&raw[pkg_res->raw_data_length-4]; u32 act_crc = ERISACrc(act, act_len); if (crc != act_crc) { WCHAR res_name[MAX_PATH]; acp2unicode(pkg_res->name, -1, res_name, MAX_PATH); locale_app_printf(EntisGLS_locale_id, 0, res_name, crc, act_crc); delete [] act; delete [] raw; return -CUI_EMATCH; } else { pkg_res->actual_data_length = act_len; goto out; } } } out: pkg_res->raw_data = raw; pkg_res->actual_data = act; #else BYTE *dec = new BYTE[pkg_res->actual_data_length]; if (!dec) { delete [] raw; return -CUI_EMEM; } if (!ERIBshfDecode(dec, pkg_res->actual_data_length, raw, raw_len)) { printf("%s: crc不正确, 可能是文件损坏或者需要指定正确的exe/game/pwd参数提供密码.\n", pkg_res->name); printf("%s: crc is incorrect, maybe the data is corrupt or need correct parameter exe/game/pwd to provide the password.\n", pkg_res->name); delete [] dec; delete [] raw; return -CUI_EMATCH; } delete [] raw; pkg_res->actual_data = dec; #endif } else if (my_noa_entry->encode_type == 0xC0000010) { // etERISACrypt printf("unsupport type etERISACrypt\n"); pkg_res->raw_data = raw; } else { printf("unsupport type unknown\n"); pkg_res->raw_data = raw; } return 0; } /* 资源保存函数 */ static int EntisGLS_noa_save_resource(struct resource *res, struct package_resource *pkg_res) { if (res->rio->create(res)) return -CUI_ECREATE; if (pkg_res->actual_data && pkg_res->actual_data_length) { if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } else if (pkg_res->raw_data && pkg_res->raw_data_length) { if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } res->rio->close(res); return 0; } /* 封包资源释放函数 */ static void EntisGLS_noa_release_resource(struct package *pkg, struct package_resource *pkg_res) { if (pkg_res->actual_data) { delete [] pkg_res->actual_data; pkg_res->actual_data = NULL; } if (pkg_res->raw_data) { delete [] pkg_res->raw_data; pkg_res->raw_data = NULL; } } /* 封包卸载函数 */ static void EntisGLS_noa_release(struct package *pkg, struct package_directory *pkg_dir) { if (pkg_dir->directory) { my_noa_entry_t *index = (my_noa_entry_t *)pkg_dir->directory; for (DWORD i = 0; i < pkg_dir->index_entries; ++i) delete [] index[i].extra_info; delete [] pkg_dir->directory; pkg_dir->directory = NULL; } pkg->pio->close(pkg); } /* 封包处理回调函数集合 */ static cui_ext_operation EntisGLS_noa_operation = { EntisGLS_noa_match, /* match */ EntisGLS_noa_extract_directory, /* extract_directory */ EntisGLS_noa_parse_resource_info, /* parse_resource_info */ EntisGLS_noa_extract_resource, /* extract_resource */ EntisGLS_noa_save_resource, /* save_resource */ EntisGLS_noa_release_resource, /* release_resource */ EntisGLS_noa_release /* release */ }; /* 接口函数: 向cui_core注册支持的封包类型 */ int CALLBACK EntisGLS_register_cui(struct cui_register_callback *callback) { if (callback->add_extension(callback->cui, _T(".noa"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; if (callback->add_extension(callback->cui, _T(".dat"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; if (callback->add_extension(callback->cui, _T(".arc"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; #if 0 if (callback->add_extension(callback->cui, _T(".eri"), NULL, _T("Entis Rasterized Image - 1(エリちゃん)"), &EntisGLS_eri_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; if (callback->add_extension(callback->cui, _T(".mio"), NULL, _T("Music Interleaved and Orthogonal transformaed(ミーオ)"), &EntisGLS_mio_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; if (callback->add_extension(callback->cui, _T(".csx"), NULL, _T("Cotopha Image file"), &EntisGLS_csx_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; #endif EntisGLS_locale_id = locale_app_register(EntisGLS_locale_configurations, 3); debug = !!(unsigned long)get_options("debug"); const char *exe = get_options("exe"); const char *game = get_options("game"); if (!load_exe_xml(exe) && game) { for (DWORD i = 0; game_key_table_list[i].caption[0]; ++i) { if (!strcmpi(game_key_table_list[i].caption, game)) break; } if (game_key_table_list[i].caption[0]) runtime_game_key_table.push_back(game_key_table_list[i]); } const char *password = get_options("pwd"); if (!runtime_game_key_table.size() && password) { struct game_key_table pwd_game; strcpy(pwd_game.caption, "password"); pwd_game.number = 1; strcpy(pwd_game.sub_table[0].password, password); strcpy(pwd_game.sub_table[0].path, ""); runtime_game_key_table.push_back(pwd_game); } else runtime_game_key_table.push_back(default_key_table); //ERIBshfDecodeInit(password); if (debug) { printf("Dump key ring (%d):\n", runtime_game_key_table.size()); for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { printf("%2d) game \"%s\" (%d)\n", i, runtime_game_key_table[i].caption, runtime_game_key_table[i].number); for (DWORD k = 0; k < runtime_game_key_table[i].number; ++k) { printf("\t%2d> path \"%s\", password \"%s\"\n", k, runtime_game_key_table[i].sub_table[k].path, runtime_game_key_table[i].sub_table[k].password); } } } return 0; } }
25.675113
142
0.65715
MaiReo
214812db54c0b4b2b26f8f42362c8ef34cfa8abe
481
cpp
C++
monet/lm_ops/lravg.cpp
stjordanis/MONeT-1
98a5c7d149ca19c8c64069dbd8f27ce7f97bf3af
[ "MIT" ]
161
2020-10-28T02:21:50.000Z
2022-03-11T05:06:16.000Z
monet/lm_ops/lravg.cpp
kiminh/MONeT
83302c12e8fd3d1c8b2496928c843f0e84226cc8
[ "MIT" ]
4
2020-10-28T02:27:43.000Z
2021-03-31T00:04:43.000Z
monet/lm_ops/lravg.cpp
kiminh/MONeT
83302c12e8fd3d1c8b2496928c843f0e84226cc8
[ "MIT" ]
15
2020-10-28T02:32:12.000Z
2021-12-23T13:20:23.000Z
#include <torch/extension.h> #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CONTIGUOUS(x) torch::Tensor lr_adaptive_avg_pool_backward(const torch::Tensor& grad, const torch::Tensor& self) { return at::native::adaptive_avg_pool2d_backward_cuda(grad, self); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("lr_adaptive_avg_pool_backward", &lr_adaptive_avg_pool_backward, "Adaptive Avg Pool Backward"); }
34.357143
105
0.785863
stjordanis
214b1db4ef1ec19536ed20b51bd277b7c928162f
1,143
hpp
C++
include/lexy/_detail/detect.hpp
clayne/lexy
af01ecd0aa8b774b9de62e6d12b9d69a1060ad20
[ "BSL-1.0" ]
null
null
null
include/lexy/_detail/detect.hpp
clayne/lexy
af01ecd0aa8b774b9de62e6d12b9d69a1060ad20
[ "BSL-1.0" ]
null
null
null
include/lexy/_detail/detect.hpp
clayne/lexy
af01ecd0aa8b774b9de62e6d12b9d69a1060ad20
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020-2021 Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_DETAIL_DETECT_HPP_INCLUDED #define LEXY_DETAIL_DETECT_HPP_INCLUDED #include <lexy/_detail/config.hpp> namespace lexy::_detail { template <typename... Args> using void_t = void; template <template <typename...> typename Op, typename Void, typename... Args> struct _detector : std::false_type { template <typename Fallback> using type_or = Fallback; }; template <template <typename...> typename Op, typename... Args> struct _detector<Op, void_t<Op<Args...>>, Args...> : std::true_type { template <typename Fallback> using type_or = Op<Args...>; }; template <template <typename...> typename Op, typename... Args> constexpr bool is_detected = _detector<Op, void, Args...>::value; template <typename Fallback, template <typename...> typename Op, typename... Args> using detected_or = typename _detector<Op, void, Args...>::template type_or<Fallback>; } // namespace lexy::_detail #endif // LEXY_DETAIL_DETECT_HPP_INCLUDED
30.891892
86
0.736658
clayne
2152ab9673f96e552f74c04242c24df2224dd22c
4,692
cpp
C++
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_lime_graphics_opengl_ext_EXT_texture_type_2_10_10_10_REV #include <lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_d9ba4fd59f8a4b9b_9_new,"lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV","new",0x9147d7a3,"lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV.new","lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.hx",9,0x0a1a4a4f) namespace lime{ namespace graphics{ namespace opengl{ namespace ext{ void EXT_texture_type_2_10_10_10_REV_obj::__construct(){ HX_STACKFRAME(&_hx_pos_d9ba4fd59f8a4b9b_9_new) HXDLIN( 9) this->UNSIGNED_INT_2_10_10_10_REV_EXT = (int)33640; } Dynamic EXT_texture_type_2_10_10_10_REV_obj::__CreateEmpty() { return new EXT_texture_type_2_10_10_10_REV_obj; } void *EXT_texture_type_2_10_10_10_REV_obj::_hx_vtable = 0; Dynamic EXT_texture_type_2_10_10_10_REV_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< EXT_texture_type_2_10_10_10_REV_obj > _hx_result = new EXT_texture_type_2_10_10_10_REV_obj(); _hx_result->__construct(); return _hx_result; } bool EXT_texture_type_2_10_10_10_REV_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6d989885; } EXT_texture_type_2_10_10_10_REV_obj::EXT_texture_type_2_10_10_10_REV_obj() { } hx::Val EXT_texture_type_2_10_10_10_REV_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 31: if (HX_FIELD_EQ(inName,"UNSIGNED_INT_2_10_10_10_REV_EXT") ) { return hx::Val( UNSIGNED_INT_2_10_10_10_REV_EXT ); } } return super::__Field(inName,inCallProp); } hx::Val EXT_texture_type_2_10_10_10_REV_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 31: if (HX_FIELD_EQ(inName,"UNSIGNED_INT_2_10_10_10_REV_EXT") ) { UNSIGNED_INT_2_10_10_10_REV_EXT=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EXT_texture_type_2_10_10_10_REV_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo EXT_texture_type_2_10_10_10_REV_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(EXT_texture_type_2_10_10_10_REV_obj,UNSIGNED_INT_2_10_10_10_REV_EXT),HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *EXT_texture_type_2_10_10_10_REV_obj_sStaticStorageInfo = 0; #endif static ::String EXT_texture_type_2_10_10_10_REV_obj_sMemberFields[] = { HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89"), ::String(null()) }; static void EXT_texture_type_2_10_10_10_REV_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(EXT_texture_type_2_10_10_10_REV_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void EXT_texture_type_2_10_10_10_REV_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(EXT_texture_type_2_10_10_10_REV_obj::__mClass,"__mClass"); }; #endif hx::Class EXT_texture_type_2_10_10_10_REV_obj::__mClass; void EXT_texture_type_2_10_10_10_REV_obj::__register() { hx::Object *dummy = new EXT_texture_type_2_10_10_10_REV_obj; EXT_texture_type_2_10_10_10_REV_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV","\x31","\xca","\xbc","\x3c"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = EXT_texture_type_2_10_10_10_REV_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(EXT_texture_type_2_10_10_10_REV_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< EXT_texture_type_2_10_10_10_REV_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = EXT_texture_type_2_10_10_10_REV_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EXT_texture_type_2_10_10_10_REV_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EXT_texture_type_2_10_10_10_REV_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace graphics } // end namespace opengl } // end namespace ext
39.428571
267
0.808184
seanbashaw
21567baf916fa34ae5e2c1f7b4af21b5ab57ddb6
5,356
cc
C++
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
/******************************************************************************* Project Name: WEB_CAM.cprj Required Libs's: IntFunc_lib.cc Files: CAMERA_CJ_OV528.cc, SD.Lib.cc Writer: CCPRO-TEAM Date: 10.05.2015 Function: Demonstrates the Grove Camera_CJ_OV528 with Webserver ------------------------------------------------------------------------------ AVR32 Serie: ------------ Required the C-Control PRO AVR32-Bit UNIT Conrad BN: 192573 Applicationboard Conrad BN: 192587 Or Mainboard Conrad BN: 192702 Connection: ----------- - Connect the sensor red wire to +5V (AVR32) the Camers dosn't work with 3,3V! - Connect the sensor black wire to GND - Connect the sensor yellow wire (UART-RxD) P37 - Connect the sensor white wire (UART-TxD) P36 HTTP-Webserver: --------------- http://localhost Copy the "Webroot" files to the microSD-Card (main directory) Start the program with F10 (or the yellow flash icon) for debug outputs! ------------------------------------------------------------------------------ Note: ----- Source: http://www.seeedstudio.com/depot/Grove-Serial-Camera-Kit-p-1608.html Grove - Serial Camera Kit includes one control board and two interchangeble lenses, one is standard lens and the other is wide-angle lens. To make it more fun and playable, lenses of two specs are shipped in this kit. The standard one is for common photo shots and the wide-angle one is specially suitable for monitoring projects. Specifications: --------------- * Input Voltage: 5V * Pixel: 300,000 * Resolution: 640*480, 320*240, 160*120 * Uart Baud Rate: 9600~115200 * Communication: RS485 and RS232 * Photo JPEG compression, high, medium and low grades Optional * AGC * Auto Exposure Event Control * Automatic White Balance Control * Focus adjustable *******************************************************************************/ // Only for the C-Control PRO AVR32 #ifdef AVR32 // Webserver user variables #define WEB_VAR_CNT 1 // Webserver byte webmem[WEB_BUF(WEB_VAR_CNT)]; byte ip_info[6]; int cmd; // Str_Printf char text[80]; /*------------------------------------------------------------------------------ Main loop ------------------------------------------------------------------------------*/ void main(void) { // Webserver request variable byte req_id; int counter; counter=0; cmd=0; // Live LED init Port_Attribute(PORT_LED2, PORT_ATTR_OUTPUT | PORT_ATTR_INIT_LOW); // SD WRITE LED Port_Attribute(PORT_LED1,PORT_ATTR_OUTPUT|PORT_ATTR_DRIVE_MIN); Port_WriteBit(PORT_LED1,0); // SD and Camera initialize Msg_WriteText("Camera initialize...\r"); SD_INIT(); CAMERA_INIT(); CAMERA_SIZE_BAUD_FRAM(); // HTTP Webserver debug output ETH_GetIPInfo(EI_IP_ADDR, ip_info); Str_Printf(text, "IP-Adresse: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); ETH_GetIPInfo(EI_NETMASK, ip_info); Str_Printf(text, "IP-Netmask: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); ETH_GetIPInfo(EI_GATEWAY, ip_info); Str_Printf(text, "IP-Gateway: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); // Start the HTTP Websever as port 80 WEB_StartServer(80, webmem, WEB_VAR_CNT, 0); // Set the HTTP Webserver variables WEB_SetDynVar(0, cmd, DYN_INT, DYN_CGIVAR, 0); // Here start the endless loop while(1) { // Received the request variable req_id=WEB_GetRequest(); if(req_id!=0) { Str_Printf(text, "req_id:%d hash:%x cmd:%d\r", req_id, WEB_GetFileHash(req_id), cmd); Msg_WriteText(text); if(cmd==1) { // Save the Camera Picture SNAP(); } // Clear the request variable and send infomation to Website cmd=0; WEB_ReleaseRequest(req_id); } // Toggle "Live LED" if(counter==1000) { Port_ToggleBit(PORT_LED2); counter=0; } counter++; } } /*------------------------------------------------------------------------------ SNAP PIC ------------------------------------------------------------------------------*/ void SNAP(void) { // Save the Camera Picture SD_OPEN_FILE("bild.jpg"); GET_PIC(); CAMERA_SAVE_PIC(); } #else #error "Only C-Control PRO AVR32-Bit" #endif /******************************************************************************* * Info ******************************************************************************* * Changelog: * - * ******************************************************************************* * Bugs, feedback, questions and modifications can be posted on the * C-Control Forum on http://www.c-control.de * Of course you can also write us an e-mail to: webmaster@c-control.de * We publish updates from time to time on www.c-control.de! /******************************************************************************/ // EOF
29.921788
98
0.510456
frankyhub
2156fd6f438f31b4b0cb776986a1edbba761198c
24,067
cpp
C++
NuclearSegmentation/Nuclear_Association/AssociationAuxFns.cpp
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
NuclearSegmentation/Nuclear_Association/AssociationAuxFns.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
NuclearSegmentation/Nuclear_Association/AssociationAuxFns.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
/* * Copyright 2009 Rensselaer Polytechnic Institute * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*========================================================================= Program: Farsight Biological Image Segmentation and Visualization Toolkit Language: C++ Date: $Date: $ Version: $Revision: 0.00 $ =========================================================================*/ #ifndef _ASC_FEAT_AUX_FN_CPP_ #define _ASC_FEAT_AUX_FN_CPP_ #define _USE_MATH_DEFINES #include <math.h> #include <algorithm> #include "itkImage.h" #include "itkIntTypes.h" #include "itkScalarImageToHistogramGenerator.h" #include "itkBinaryThresholdImageFilter.h" #include "itkNumericTraits.h" #include "itkExtractImageFilter.h" #include "itkOtsuMultipleThresholdsCalculator.h" #include "itkSignedDanielssonDistanceMapImageFilter.h" #include "vnl/vnl_matrix.h" #include "vnl/vnl_real.h" #include "vnl/algo/vnl_real_eigensystem.h" #include "vnl/vnl_double_3x3.h" #include "itkLabelGeometryImageFilter.h" #include "NuclearSegmentation/CytoplasmSegmentation/whole_cell.h" #include "ftkNuclearAssociationRules.h" typedef unsigned short USPixelType; typedef itk::Image< USPixelType, 3 > USImageType; typedef float FloatPixelType; typedef itk::Image< FloatPixelType, 3 > FloatImageType; std::vector<float> compute_ec_features( USImageType::Pointer input_image, USImageType::Pointer inp_labeled, int number_of_rois, unsigned short thresh, int surr_dist, int inside_dist ){ std::vector< float > qfied_num; std::vector< USImageType::PixelType > labelsList; std::vector< double > quantified_numbers_cell; typedef itk::ExtractImageFilter< USImageType, UShortImageType > LabelExtractType; typedef itk::ImageRegionConstIterator< UShortImageType > ConstIteratorType; typedef itk::ImageRegionIteratorWithIndex< USImageType > IteratorType; typedef itk::SignedDanielssonDistanceMapImageFilter<FloatImageType, FloatImageType > DTFilter; typedef itk::ImageRegionIteratorWithIndex< FloatImageType > IteratorTypeFloat; typedef itk::LabelGeometryImageFilter< USImageType > GeometryFilterType; typedef GeometryFilterType::LabelIndicesType labelindicestype; itk::SizeValueType sz_x, sz_y, sz_z; sz_x = input_image->GetLargestPossibleRegion().GetSize()[0]; sz_y = input_image->GetLargestPossibleRegion().GetSize()[1]; sz_z = input_image->GetLargestPossibleRegion().GetSize()[2]; if( sz_x==1 || sz_y==1 || sz_z==1 ){ LabelExtractType::Pointer deFilter = LabelExtractType::New(); USImageType::RegionType dRegion = inp_labeled->GetLargestPossibleRegion(); dRegion.SetSize(2,0); deFilter->SetExtractionRegion(dRegion); deFilter->SetInput( inp_labeled ); deFilter->SetDirectionCollapseToIdentity(); try{ deFilter->Update(); } catch( itk::ExceptionObject & excep ){ std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } //Dialate input first WholeCellSeg *dialate_filter = new WholeCellSeg; dialate_filter->set_nuc_img( deFilter->GetOutput() ); dialate_filter->set_radius( surr_dist ); dialate_filter->RunSegmentation(); UShortImageType::Pointer input_lab = dialate_filter->getSegPointer(); USImageType::Pointer input_labeled = USImageType::New(); USImageType::PointType origint; origint[0] = 0; origint[1] = 0; origint[2] = 0; input_labeled->SetOrigin( origint ); USImageType::IndexType startt; startt[0] = 0; // first index on X startt[1] = 0; // first index on Y startt[2] = 0; // first index on Z USImageType::SizeType sizet; sizet[0] = inp_labeled->GetLargestPossibleRegion().GetSize()[0]; // size along X sizet[1] = inp_labeled->GetLargestPossibleRegion().GetSize()[1]; // size along Y sizet[2] = inp_labeled->GetLargestPossibleRegion().GetSize()[2]; // size along Z USImageType::RegionType regiont; regiont.SetSize( sizet ); regiont.SetIndex( startt ); input_labeled->SetRegions( regiont ); input_labeled->Allocate(); input_labeled->FillBuffer(0); input_labeled->Update(); ConstIteratorType pix_buf1( input_lab, input_lab->GetRequestedRegion() ); IteratorType iterator2 ( input_labeled, input_labeled->GetRequestedRegion() ); iterator2.GoToBegin(); for ( pix_buf1.GoToBegin(); !pix_buf1.IsAtEnd(); ++pix_buf1 ){ iterator2.Set( pix_buf1.Get() ); ++iterator2; } std::vector< float > quantified_numbers; typedef itk::LabelGeometryImageFilter< USImageType > GeometryFilterType; typedef GeometryFilterType::LabelIndicesType labelindicestype; GeometryFilterType::Pointer geomfilt1 = GeometryFilterType::New(); geomfilt1->SetInput( input_labeled ); geomfilt1->SetCalculatePixelIndices( true ); geomfilt1->Update(); labelsList = geomfilt1->GetLabels(); bool zp=false; for( USImageType::PixelType i=0; i < labelsList.size(); ++i ){ if( labelsList[i] == 0 ){ zp=true; continue; } std::vector<float> quantified_numbers_cell; for( unsigned j=0; j<number_of_rois; ++j ) quantified_numbers_cell.push_back((float)0.0); double centroid_x = geomfilt1->GetCentroid(labelsList[i])[0]; double centroid_y = geomfilt1->GetCentroid(labelsList[i])[1]; labelindicestype indices1; indices1 = geomfilt1->GetPixelIndices(labelsList[i]); for( labelindicestype::iterator itPixind = indices1.begin(); itPixind!=indices1.end(); ++itPixind ){ IteratorType iterator1 ( input_image, input_image->GetRequestedRegion() ); iterator1.SetIndex( *itPixind ); if( iterator1.Get() < thresh ) continue; double x = iterator1.GetIndex()[0]; double y = iterator1.GetIndex()[1]; double angle = atan2((centroid_y-y),fabs(centroid_x-x)); if( (centroid_x-x)>0 ) angle += M_PI_2; else angle = M_PI+M_PI-(angle+M_PI_2); angle = ((number_of_rois-1)*angle)/(2*M_PI); double angle_fraction[1]; unsigned angular_index; if( modf( angle, angle_fraction ) > 0.5 ) angular_index = ceil( angle ); else angular_index = floor( angle ); quantified_numbers_cell[angular_index] += iterator1.Get(); } for( unsigned j=0; j<number_of_rois; ++j ) quantified_numbers.push_back(quantified_numbers_cell[j]); } unsigned qnum_sz = zp? (labelsList.size()-1) : (labelsList.size()); for( unsigned i=0; i<qnum_sz; ++i ){ unsigned counter=0; for( unsigned j=0; j<number_of_rois; ++j ){ if( quantified_numbers[(i*number_of_rois+j)] > (255.0*surr_dist) ) ++counter; } qfied_num.push_back(counter); } } else{ GeometryFilterType::Pointer geomfilt1 = GeometryFilterType::New(); geomfilt1->SetInput( inp_labeled ); geomfilt1->SetCalculatePixelIndices( true ); geomfilt1->Update(); labelsList = geomfilt1->GetLabels(); std::cout<<std::endl<<"The size is: "<<labelsList.size(); if( labelsList.size() == 1 ) { qfied_num.clear(); return qfied_num; } bool zp=false; USPixelType zero; //Check if the background is also included for( USPixelType i=0; i<labelsList.size(); ++i ) if( labelsList[i] == 0 ){ zp=true; zero = i; } USImageType::SizeType sizee; sizee[0] = inp_labeled->GetLargestPossibleRegion().GetSize()[0]; // size along X sizee[1] = inp_labeled->GetLargestPossibleRegion().GetSize()[1]; // size along Y sizee[2] = inp_labeled->GetLargestPossibleRegion().GetSize()[2]; // size along Z itk::SizeValueType roi_list_size = zp ? ((itk::SizeValueType)number_of_rois*(labelsList.size()-1)*2) : ((itk::SizeValueType)number_of_rois*labelsList.size()*2); std::vector<double> quantified_numbers_cell((roi_list_size),0.0 ); std::cout<<"Bounding boxes computed"<<std::endl; #ifdef _OPENMP itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); #pragma omp parallel for #if _OPENMP < 200805L for( int i=0; i<labelsList.size(); ++i ) #else for( USImageType::PixelType i=0; i<labelsList.size(); ++i ) #endif #else for( USImageType::PixelType i=0; i<labelsList.size(); ++i ) #endif { itk::SizeValueType ind; if( zp && (zero==i) ) continue; if( zp && (i>zero) ) ind = i-1; else ind = i; //Get label indices labelindicestype indices1; double centroid_x,centroid_y,centroid_z; GeometryFilterType::BoundingBoxType boundbox; #pragma omp critical { indices1 = geomfilt1->GetPixelIndices(labelsList[i]); //Get Centroid centroid_x = geomfilt1->GetCentroid(labelsList[i])[0]; centroid_y = geomfilt1->GetCentroid(labelsList[i])[1]; centroid_z = geomfilt1->GetCentroid(labelsList[i])[2]; //Create an image with bounding box + 2 * outside distance + 2 //and get distance map for the label boundbox = geomfilt1->GetBoundingBox(labelsList[i]); } //Create vnl array 3xN( label indicies ) vnl_matrix<double> B(3,indices1.size()); FloatImageType::Pointer inp_lab = FloatImageType::New(); FloatImageType::PointType origint; origint[0] = 0; origint[1] = 0; origint[2] = 0; inp_lab->SetOrigin( origint ); FloatImageType::IndexType startt; startt[0] = 0; // first index on X startt[1] = 0; // first index on Y startt[2] = 0; // first index on Z FloatImageType::SizeType sizet; sizet[0] = boundbox[1]-boundbox[0]+2*surr_dist+2; // size along X sizet[1] = boundbox[3]-boundbox[2]+2*surr_dist+2; // size along Y sizet[2] = boundbox[5]-boundbox[4]+2*surr_dist+2; // size along Z FloatImageType::RegionType regiont; regiont.SetSize( sizet ); regiont.SetIndex( startt ); inp_lab->SetRegions( regiont ); inp_lab->Allocate(); inp_lab->FillBuffer(0.0); inp_lab->Update(); IteratorTypeFloat iterator444 ( inp_lab, inp_lab->GetRequestedRegion() ); //Populate matrix with deviations from the centroid for principal axes and //at the same time set up distance-transform computation itk::SizeValueType ind1=0; for( labelindicestype::iterator itPixind = indices1.begin(); itPixind!=indices1.end(); ++itPixind ){ IteratorType iterator3( input_image, input_image->GetRequestedRegion() ); iterator3.SetIndex( *itPixind ); B(0,(ind1)) = iterator3.GetIndex()[0]-centroid_x; B(1,(ind1)) = iterator3.GetIndex()[1]-centroid_y; B(2,(ind1)) = iterator3.GetIndex()[2]-centroid_z; FloatImageType::IndexType cur_in; cur_in[0] = iterator3.GetIndex()[0]-boundbox[0]+1+surr_dist; cur_in[1] = iterator3.GetIndex()[1]-boundbox[2]+1+surr_dist; cur_in[2] = iterator3.GetIndex()[2]-boundbox[4]+1+surr_dist; iterator444.SetIndex( cur_in ); iterator444.Set( 255.0 ); ++ind1; } //Compute distance transform for the current object DTFilter::Pointer dt_obj= DTFilter::New() ; dt_obj->SetInput( inp_lab ); dt_obj->SquaredDistanceOff(); dt_obj->InsideIsPositiveOff(); try{ dt_obj->Update() ; } catch( itk::ExceptionObject & err ){ std::cerr << "Error in Distance Transform: " << err << std::endl; } FloatImageType::Pointer dist_im = dt_obj->GetOutput(); //Use KLT to compute pricipal axes vnl_matrix<double> B_transp((int)indices1.size(),3); B_transp = B.transpose(); vnl_matrix<double> COV(3,3); COV = B * B_transp; double norm = 1.0/(double)indices1.size(); COV = COV * norm; //Eigen decomposition vnl_real_eigensystem Eyegun( COV ); vnl_matrix<vcl_complex<double> > EVals = Eyegun.D; double Eval1 = vnl_real(EVals)(0,0); double Eval2 = vnl_real(EVals)(1,1); double Eval3 = vnl_real(EVals)(2,2); vnl_double_3x3 EVectMat = Eyegun.Vreal; double V1[3],V2[3],EP_norm[3]; if( Eval1 >= Eval3 && Eval2 >= Eval3 ){ if( Eval1 >= Eval2 ){ V1[0] = EVectMat(0,0); V1[1] = EVectMat(1,0); V1[2] = EVectMat(2,0); V2[0] = EVectMat(0,1); V2[1] = EVectMat(1,1); V2[2] = EVectMat(2,1); } else { V2[0] = EVectMat(0,0); V2[1] = EVectMat(1,0); V2[2] = EVectMat(2,0); V1[0] = EVectMat(0,1); V1[1] = EVectMat(1,1); V1[2] = EVectMat(2,1); } } else if( Eval1 >= Eval2 && Eval3 >= Eval2 ) { if( Eval1 >= Eval3 ){ V1[0] = EVectMat(0,0); V1[1] = EVectMat(1,0); V1[2] = EVectMat(2,0); V2[0] = EVectMat(0,2); V2[1] = EVectMat(1,2); V2[2] = EVectMat(2,2); } else { V2[0] = EVectMat(0,0); V2[1] = EVectMat(1,0); V2[2] = EVectMat(2,0); V1[0] = EVectMat(0,2); V1[1] = EVectMat(1,2); V1[2] = EVectMat(2,2); } } else { if( Eval2 >= Eval3 ){ V1[0] = EVectMat(0,1); V1[1] = EVectMat(1,1); V1[2] = EVectMat(2,1); V2[0] = EVectMat(0,2); V2[1] = EVectMat(1,2); V2[2] = EVectMat(2,2); } else { V2[0] = EVectMat(0,1); V2[1] = EVectMat(1,1); V2[2] = EVectMat(2,1); V1[0] = EVectMat(0,2); V1[1] = EVectMat(1,2); V1[2] = EVectMat(2,2); } } double n_sum = sqrt( V1[0]*V1[0]+V1[1]*V1[1]+V1[2]*V1[2] ); V1[0] /= n_sum; V1[1] /= n_sum; V1[2] /= n_sum; n_sum = sqrt( V2[0]*V2[0]+V2[1]*V2[1]+V2[2]*V2[2] ); V2[0] /= n_sum; V2[1] /= n_sum; V2[2] /= n_sum; //Get the normal to the plane formed by the biggest two EVs EP_norm[0] = V1[1]*V2[2]-V1[2]*V2[1]; EP_norm[1] = V1[2]*V2[0]-V1[0]*V2[2]; EP_norm[2] = V1[0]*V2[1]-V1[1]*V2[0]; //Reassign V2 so that it is orthogonal to both EP_norm and V1 V2[0] = V1[1]*EP_norm[2]-V1[2]*EP_norm[1]; V2[1] = V1[2]*EP_norm[0]-V1[0]*EP_norm[2]; V2[2] = V1[0]*EP_norm[1]-V1[1]*EP_norm[0]; //Now we have the point normal form; EP_norm is the normal and //centroid_x, centroid_y, centroid_z is the point //The equation to the plane is EP_norm[0](x-centroid_x)+EP_norm[1](y-centroid_y)+EP_norm[2](z-centroid_z)=0 double dee = (centroid_x*EP_norm[0]+centroid_y*EP_norm[1]+centroid_z*EP_norm[2])*(-1.00); //Iterate through and assign values to each region typedef itk::ImageRegionConstIterator< FloatImageType > ConstIteratorTypeFloat; ConstIteratorTypeFloat pix_buf2( dist_im, dist_im->GetRequestedRegion() ); IteratorType iterator44( input_image, input_image->GetRequestedRegion() ); for ( pix_buf2.GoToBegin(); !pix_buf2.IsAtEnd(); ++pix_buf2 ){ //Use pixels that are only within the defined radius from the nucleus double current_distance = pix_buf2.Get(); if( (current_distance <= (double)surr_dist) && (current_distance>=(-1*inside_dist)) ){ USImageType::IndexType cur_in;//,cur_in_cpy; double n_vec[3]; cur_in[0] = pix_buf2.GetIndex()[0]+boundbox[0]-1-surr_dist; cur_in[1] = pix_buf2.GetIndex()[1]+boundbox[2]-1-surr_dist; cur_in[2] = pix_buf2.GetIndex()[2]+boundbox[4]-1-surr_dist; //cur_in_cpy[0] = cur_in[0]; cur_in_cpy[1] = cur_in[1]; cur_in_cpy[2] = cur_in[2]; if( cur_in[0] < 0 || cur_in[1] < 0 || cur_in[2] < 0 ) continue; if( cur_in[0] >= sizee[0] || cur_in[1] >= sizee[1] || cur_in[2] >= sizee[2] ) continue; iterator44.SetIndex( cur_in ); USImageType::PixelType pixel_intensity; pixel_intensity = iterator44.Get(); if( pixel_intensity < thresh ) continue; //The projection of the point on the plane formed by the fist two major axes double xxx, yyy, zzz; xxx = cur_in[0] - EP_norm[0]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); yyy = cur_in[1] - EP_norm[1]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); zzz = cur_in[2] - EP_norm[2]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); //The vector from the centroid to the projected point n_vec[0] = centroid_x-xxx; n_vec[1] = centroid_y-yyy; n_vec[2] = centroid_z-zzz; n_sum = sqrt( n_vec[0]*n_vec[0] + n_vec[1]*n_vec[1] + n_vec[2]*n_vec[2] ); n_vec[0] /= n_sum; n_vec[1] /= n_sum; n_vec[2] /= n_sum; //n_vec is the normalized vect in the direction of the projected point //V1 is the largest eigenvector //Get the dot and cross product between the two double doooot, crooos,fin_est_angle; doooot = n_vec[0]*V1[0]+n_vec[1]*V1[1]+n_vec[2]*V1[2]; crooos = n_vec[0]*V2[0]+n_vec[1]*V2[1]+n_vec[2]*V2[2]; fin_est_angle = atan2( crooos, doooot ); USPixelType bin_num; //Compute bin num if( fin_est_angle<0 ) fin_est_angle += (2*M_PI); bin_num = floor(fin_est_angle*number_of_rois/(2*M_PI)); //Check which side of the plane the point lies on double v_norm = (cur_in[0]-centroid_x)*(cur_in[0]-centroid_x) +(cur_in[1]-centroid_y)*(cur_in[1]-centroid_y) +(cur_in[2]-centroid_z)*(cur_in[2]-centroid_z); v_norm = sqrt( v_norm ); double doot = (cur_in[0]-centroid_x)*EP_norm[0]/v_norm + (cur_in[1]-centroid_y)*EP_norm[1]/v_norm + (cur_in[2]-centroid_z)*EP_norm[2]/v_norm; if( doot<0 ) bin_num += number_of_rois; quantified_numbers_cell.at((ind*(2*number_of_rois)+bin_num)) += pixel_intensity; } } } number_of_rois = number_of_rois*2; if( labelsList.size() == 1 ) { qfied_num.clear(); return qfied_num; } std::vector<double> quantified_numbers_cell_cpy(roi_list_size); std::copy(quantified_numbers_cell.begin(), quantified_numbers_cell.end(), quantified_numbers_cell_cpy.begin() ); //Run k-means //Most of the code is adapted from mul/mbl/mbl_k_means.cxx std::sort(quantified_numbers_cell.begin(), quantified_numbers_cell.end()); bool skipKmeans; double Positive_thresh; if( quantified_numbers_cell.at(0) == quantified_numbers_cell.at(quantified_numbers_cell.size()-1) ) skipKmeans = true; if( !skipKmeans ){ std::cout<<"Starting k-means\n"; std::cout<<"First:"<<quantified_numbers_cell.at(0)<<" Last:"<<quantified_numbers_cell.at(quantified_numbers_cell.size()-1)<<std::endl; unsigned k = 2; //Vectors and matrices for k-means std::vector< USImageType::PixelType > partition( roi_list_size, 0 ); std::vector< double > sums ( k, 0.0 ); std::vector< double > centers( k, 0.0 ); std::vector< USImageType::PixelType > nNearest( k, 0 ); //Use the elements that are evenly spaced to get the intial centers for( unsigned i=0; i<k; ++i ){ double index = ((double)(i)*roi_list_size)/(k+1); centers.at(i) = quantified_numbers_cell.at((itk::SizeValueType)index); bool duplicated; std::cout<<"Initializing centers\n"<<std::flush; if(i){ if( centers.at((i-1)) == centers.at(i) ){ duplicated = true; itk::SizeValueType ind=i+1; while( centers.at((i-1))==quantified_numbers_cell.at(ind) ) ++ind; centers.at(i) = quantified_numbers_cell.at(ind); sums.at(i) = quantified_numbers_cell.at(ind); } } if(!duplicated) sums.at(i) = quantified_numbers_cell.at((i+1)/(k+1)); ++nNearest[i]; } bool changed = true; std::cout<<"Waiting for kmeans to converge\n"<<std::flush; while(changed){ changed = false; for(itk::SizeValueType i=0; i<roi_list_size; ++i){ unsigned bestCentre = 0; double bestDist = fabs((centers.at(0)-quantified_numbers_cell.at(i))); for(unsigned j=1; j<k; ++j){ double dist = fabs((centers.at(j)-quantified_numbers_cell.at(i))); if( dist < bestDist ){ bestDist = dist; bestCentre = j; } } sums[bestCentre] += quantified_numbers_cell.at(i); ++ nNearest[bestCentre]; if( bestCentre != partition.at(i) ){ changed = true; partition.at(i) = bestCentre; } } for( unsigned j=0; j<k; ++j) centers.at(j) = sums.at(j)/nNearest.at(j); for( unsigned j=0; j<k; ++j) sums.at(j) = 0; for( unsigned j=0; j<k; ++j) nNearest.at(j) = 0; } for( unsigned i=0; i<k; ++i ) std::cout<<"Center "<<i<<" "<<centers.at(i)<<"\n"; Positive_thresh = ((centers.at(0)+centers.at(1))/2) < (255.0*thresh)? ((centers.at(0)+centers.at(1))/2) : (255.0*thresh); //Arbitrary upper thresh } else Positive_thresh = 255.0*thresh; std::cout<<"Positive_thresh "<<Positive_thresh<<"\n"; std::cout<<"Done k-means\n"; itk::SizeValueType ind = 0; for( USPixelType i=0; i<labelsList.size(); ++i ){ if( zp && (zero==i) ) continue; int num_positive_rois = 0; for( unsigned j=0; j<number_of_rois; ++j ){ itk::SizeValueType index_of_roi = ind*number_of_rois+j; if( quantified_numbers_cell_cpy.at(index_of_roi)>Positive_thresh ) ++num_positive_rois; } qfied_num.push_back(num_positive_rois); ++ind; } } std::cout<<"Done surroundedness\n"<<std::flush; return qfied_num; } USImageType::PixelType returnthresh( itk::SmartPointer<USImageType> input_image, int num_bin_levs, int num_in_fg ){ //Instantiate the different image and filter types that will be used typedef itk::ImageRegionConstIterator< USImageType > ConstIteratorType; typedef itk::Statistics::Histogram< float > HistogramType; typedef itk::OtsuMultipleThresholdsCalculator< HistogramType > CalculatorType; std::cout<<"Starting threshold computation\n"; //Create a temporary histogram container: const int numBins = itk::NumericTraits<USImageType::PixelType>::max(); double *tempHist; tempHist = (double*) malloc( sizeof(double) * numBins ); for(USImageType::PixelType i=0; i<numBins; ++i) tempHist[i] = 0; USImageType::PixelType maxval = itk::NumericTraits<USImageType::PixelType>::ZeroValue(); USImageType::PixelType minval = itk::NumericTraits<USImageType::PixelType>::max(); //Populate the histogram (assume pixel type is actually is some integer type): ConstIteratorType it( input_image, input_image->GetRequestedRegion() ); for ( it.GoToBegin(); !it.IsAtEnd(); ++it ){ USImageType::PixelType pix = it.Get(); ++tempHist[pix]; if( pix > maxval ) maxval = pix; if( pix < minval ) minval = pix; } //return max of type if there is no variation in the staining if( (maxval-minval)<3 ) return itk::NumericTraits<USImageType::PixelType>::max(); const USImageType::PixelType numBinsPresent = maxval+1; //Find max value in the histogram double floatIntegerMax = itk::NumericTraits<USImageType::PixelType>::max(); double max = 0.0; for(USImageType::PixelType i=0; i<numBinsPresent; ++i) if( tempHist[i] > max ) max = tempHist[i]; double scaleFactor = 1; if(max >= floatIntegerMax) scaleFactor = floatIntegerMax / max; HistogramType::Pointer histogram = HistogramType::New() ; // initialize histogram HistogramType::SizeType size; HistogramType::MeasurementVectorType lowerBound; HistogramType::MeasurementVectorType upperBound; lowerBound.SetSize(1); upperBound.SetSize(1); size.SetSize(1); lowerBound.Fill(0.0); upperBound.Fill((double)maxval); size.Fill(numBinsPresent); histogram->SetMeasurementVectorSize(1); histogram->Initialize(size, lowerBound, upperBound ) ; USImageType::PixelType i=0; for (HistogramType::Iterator iter = histogram->Begin(); iter != histogram->End(); ++iter ){ float norm_freq = (float)(tempHist[i] * scaleFactor); iter.SetFrequency(norm_freq); ++i; } std::cout<<"Histogram computed\n"; CalculatorType::Pointer calculator = CalculatorType::New(); calculator->SetNumberOfThresholds( num_bin_levs ); calculator->SetInputHistogram( histogram ); calculator->Update(); const CalculatorType::OutputType &thresholdVector = calculator->GetOutput(); CalculatorType::OutputType::const_iterator itNum = thresholdVector.begin(); float thresh; for(USImageType::PixelType i=0; i < num_in_fg; ++itNum, ++i) thresh = (static_cast<float>(*itNum)); std::cout<<"Threshold computed: "<<thresh<<std::endl; return (USImageType::PixelType)(thresh+0.5); } #endif
40.178631
185
0.67952
tostathaina
215910b672deb5fd314958592ff7d14ad68d0d36
3,770
cpp
C++
engine/source/component/behaviors/behaviorInstance.cpp
Sednari/twitch-tutorial-flappy-birds
9aaed1cea2ef24ef6a5212c3350db17a017142fe
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/component/behaviors/behaviorInstance.cpp
Sednari/twitch-tutorial-flappy-birds
9aaed1cea2ef24ef6a5212c3350db17a017142fe
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/component/behaviors/behaviorInstance.cpp
Sednari/twitch-tutorial-flappy-birds
9aaed1cea2ef24ef6a5212c3350db17a017142fe
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "component/behaviors/behaviorInstance.h" #include "component/behaviors/behaviorTemplate.h" #include "console/consoleTypes.h" #include "console/consoleInternal.h" #include "io/stream.h" // Script bindings. #include "behaviorInstance_ScriptBinding.h" //----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT(BehaviorInstance); //----------------------------------------------------------------------------- BehaviorInstance::BehaviorInstance( BehaviorTemplate* pTemplate ) : mTemplate( pTemplate ), mBehaviorOwner( NULL ), mBehaviorId( 0 ) { if ( pTemplate != NULL ) { // Fetch field prototype count. const U32 fieldCount = pTemplate->getBehaviorFieldCount(); // Set field prototypes. for( U32 index = 0; index < fieldCount; ++index ) { // Fetch fields. BehaviorTemplate::BehaviorField* pField = pTemplate->getBehaviorField( index ); // Set cloned field. setDataField( pField->mName, NULL, pField->mDefaultValue ); } } } //----------------------------------------------------------------------------- bool BehaviorInstance::onAdd() { if(! Parent::onAdd()) return false; // Store this object's namespace mNameSpace = Namespace::global()->find( getTemplateName() ); return true; } //----------------------------------------------------------------------------- void BehaviorInstance::onRemove() { Parent::onRemove(); } //----------------------------------------------------------------------------- void BehaviorInstance::initPersistFields() { addGroup("Behavior"); addField("template", TypeSimObjectName, Offset(mTemplate, BehaviorInstance), "Template this instance was created from."); addProtectedField( "Owner", TypeSimObjectPtr, Offset(mBehaviorOwner, BehaviorInstance), &setOwner, &defaultProtectedGetFn, "Behavior component owner." ); endGroup("Behavior"); Parent::initPersistFields(); } //----------------------------------------------------------------------------- const char* BehaviorInstance::getTemplateName( void ) { return mTemplate ? mTemplate->getName() : NULL; } // Get template. const char* BehaviorInstance::getTemplate(void* obj, const char* data) { return static_cast<BehaviorInstance*>(obj)->getTemplate()->getIdString(); }
36.25
160
0.574271
Sednari
215955a3532cb8d5bc4afef8b65931fe7552bed7
1,368
hpp
C++
include/sprout/algorithm/fit/results.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/algorithm/fit/results.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/algorithm/fit/results.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_ALGORITHM_FIT_RESULTS_HPP #define SPROUT_ALGORITHM_FIT_RESULTS_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/container/traits.hpp> #include <sprout/container/metafunctions.hpp> #include <sprout/algorithm/fixed/results.hpp> #include <sprout/sub_array/sub_array.hpp> namespace sprout { namespace fit { namespace results { // // algorithm // template<typename Result> struct algorithm { public: typedef sprout::sub_array< typename std::decay< typename sprout::containers::internal< typename sprout::fixed::results::algorithm<Result>::type >::type >::type > type; }; #if SPROUT_USE_TEMPLATE_ALIASES template<typename Result> using algorithm_t = typename sprout::fit::results::algorithm<Result>::type; #endif // #if SPROUT_USE_TEMPLATE_ALIASES } // namespace results } // namespace fit } // namespace sprout #endif // #ifndef SPROUT_ALGORITHM_FIT_RESULTS_HPP
30.4
79
0.652047
thinkoid
215d3d1e4bb9ee62f05c5266e44c2a6d0fd1c418
1,272
cpp
C++
interpreter-for-cpp/src/Runtime/Executer.cpp
Jenocn/PeakScript
444ba5f9d0062989d8beca0d76415961f1ae2922
[ "MIT" ]
1
2020-05-21T09:02:19.000Z
2020-05-21T09:02:19.000Z
interpreter-for-cpp/src/Runtime/Executer.cpp
Jenocn/PeakScript
444ba5f9d0062989d8beca0d76415961f1ae2922
[ "MIT" ]
8
2020-05-29T14:12:00.000Z
2022-01-22T09:08:47.000Z
interpreter-for-cpp/src/Runtime/Executer.cpp
Jenocn/PeakScript
444ba5f9d0062989d8beca0d76415961f1ae2922
[ "MIT" ]
null
null
null
#include "Executer.h" #include "../Grammar/ParseTool.h" #include "Sentence/Sentence.h" #include "Space.h" using namespace peak::interpreter; std::shared_ptr<Executer> Executer::Create(const std::string& src) { if (src.empty()) { return nullptr; } auto parseData = ParseTool::Load(src); if (!parseData->bSuccess) { return nullptr; } return std::shared_ptr<Executer>(new Executer(parseData)); } Executer::Executer(std::shared_ptr<ParseData> data) : _parseData(data) { _space = std::shared_ptr<Space>(new Space(SpaceType::None)); _outsideSpace = std::shared_ptr<Space>(new Space(SpaceType::None)); } Executer::~Executer() { _space->Clear(); _outsideSpace->Clear(); } bool Executer::Execute() { _space->Clear(); _space->AddSpaceOfUsing(_outsideSpace); for (auto sentence : _parseData->sentenceList) { if (!Sentence::IsSuccess(sentence->Execute(_space))) { return false; } } return true; } std::shared_ptr<Space> Executer::GetSpace() const { return _space; } std::shared_ptr<Variable> Executer::FindVariable(const std::string& name) const { return _space->FindVariable(name); } bool Executer::AddVariable(std::shared_ptr<Variable> variable) { return _outsideSpace->AddVariable(variable); }
24.941176
82
0.693396
Jenocn