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
5d9c7d7a913afeb9727e54b28667784ea8069fbf
576
hpp
C++
Code/Asset/IAsset.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
167
2020-06-17T06:09:41.000Z
2022-03-13T20:31:26.000Z
Code/Asset/IAsset.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
2
2020-07-11T15:12:50.000Z
2021-06-01T01:45:49.000Z
Code/Asset/IAsset.hpp
Mu-L/Luna-Engine-0.6
05ae1037f0d173589a535eb6ec2964f20d80e5c1
[ "MIT" ]
22
2020-06-12T02:26:10.000Z
2022-01-02T14:04:32.000Z
// Copyright 2018-2020 JXMaster. All rights reserved. /* * @file IAsset.cpp * @author JXMaster * @date 2020/4/15 */ #pragma once #include <Core/Core.hpp> namespace Luna { namespace Asset { struct IAssetMeta; //! @interface IAsset //! @threadsafe //! Implement this interface to define your own asset object type. struct IAsset : public IObject { luiid("{f99ee83a-8c39-4355-96af-3c6fe5c454f9}"); //! Gets the asset meta object of this asset. The asset object always keep a strong reference to the meta object. virtual IAssetMeta* meta() = 0; }; } }
21.333333
116
0.694444
Mu-L
5d9f9f81221136850585ba427482db4aef9ce359
3,499
cpp
C++
MasterServer/LMasterServer_PacketProcess_Proc.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
5
2018-04-02T07:16:20.000Z
2021-08-01T05:25:37.000Z
MasterServer/LMasterServer_PacketProcess_Proc.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
null
null
null
MasterServer/LMasterServer_PacketProcess_Proc.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
2
2015-08-21T07:31:41.000Z
2018-05-10T12:36:32.000Z
/* The MIT License (MIT) Copyright (c) <2010-2020> <wenshengming> 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 "LMasterServer_PacketProcess_Proc.h" #include "../NetWork/LPacketSingle.h" #include "LMainLogicThread.h" #include "../include/Server_To_Server_Packet_Define.h" LMasterServerPacketProcessProc::LMasterServerPacketProcessProc() { m_pMainLogicThread = NULL; } LMasterServerPacketProcessProc::~LMasterServerPacketProcessProc() { } void LMasterServerPacketProcessProc::SetMainLogicThread(LMainLogicThread* pmlt) { m_pMainLogicThread = pmlt; } LMainLogicThread* LMasterServerPacketProcessProc::GetMainLogicThread() { return m_pMainLogicThread; } bool LMasterServerPacketProcessProc::Initialize() { if (m_pMainLogicThread == NULL) { return false; } REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Start_Req); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Register_Server_Req1); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Will_Connect_Req); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Will_Connect_Res); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_SS_Server_Current_Serve_Count); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_L2M_USER_ONLINE); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_WILL_LOGIN); ; REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_GATESERVER_OFFLINE); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_USER_GATESERVER_ONLINE); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_GA2M_SELECT_LOBBYSERVER); REGISTER_MASTERSERVER_PACKET_PROCESS_PROC(Packet_LB2M_NOTIFY_USER_WILL_ONLINE); return true; } // 注册函数 bool LMasterServerPacketProcessProc::Register(unsigned int unPacketID, MASTERSERVER_PACKET_PROCESS_PROC pProc) { if (pProc == NULL) { return false; } map<unsigned int, MASTERSERVER_PACKET_PROCESS_PROC>::iterator _ito = m_mapPacketProcessProcManager.find(unPacketID); if (_ito != m_mapPacketProcessProcManager.end()) { return false; } m_mapPacketProcessProcManager[unPacketID] = pProc; return true; } // 派遣处理函数 void LMasterServerPacketProcessProc::DispatchMessageProcess(uint64_t u64SessionID, LPacketSingle* pPacket) { if (pPacket == NULL) { return ; } unsigned int unPacketID = pPacket->GetPacketID(); map<unsigned int, MASTERSERVER_PACKET_PROCESS_PROC>::iterator _ito = m_mapPacketProcessProcManager.find(unPacketID); if (_ito == m_mapPacketProcessProcManager.end()) { // error return; } _ito->second(this, u64SessionID, pPacket); }
31.809091
117
0.823092
MBeanwenshengming
5d9fab6a54e7d2c6017976ec01cdc88f65ce58df
638
cpp
C++
examples/wx/full_demo.cpp
JiveHelix/pex
d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6
[ "MIT" ]
null
null
null
examples/wx/full_demo.cpp
JiveHelix/pex
d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6
[ "MIT" ]
null
null
null
examples/wx/full_demo.cpp
JiveHelix/pex
d3cbe0e437e803fb4af6fe153de0cf3f61a3a6d6
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <bitset> #include <array> #include "tau/angles.h" #include "fields/fields.h" #include "pex/signal.h" #include "pex/value.h" #include "pex/initialize.h" #include "pex/range.h" #include "pex/chooser.h" #include "pex/converter.h" #include "pex/wx/wxshim.h" #include "pex/wx/labeled_widget.h" #include "pex/wx/view.h" #include "pex/wx/field.h" #include "pex/wx/button.h" #include "pex/wx/check_box.h" #include "pex/wx/combo_box.h" #include "pex/wx/radio_box.h" #include "pex/wx/slider.h" #include "pex/wx/spin_control_double.h" #include "pex/wx/shortcut.h" #include "pex/detail/filters.h"
20.580645
39
0.721003
JiveHelix
5da1aa668d1af27127b8511fba239273f559a099
1,972
cpp
C++
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
tests/src/test_BedWriter.cpp
bio-nim/pbbam
d3bf59e90865ef3b39bf50f19fd846db42bb0fe1
[ "BSD-3-Clause-Clear" ]
null
null
null
// Author: Derek Barnett #include <pbbam/bed/BedWriter.h> #include <cstdio> #include <algorithm> #include <string> #include <vector> #include <gtest/gtest.h> #include <pbbam/FormatUtils.h> #include <pbbam/GenomicInterval.h> #include <pbbam/bed/BedReader.h> #include "PbbamTestData.h" using BedReader = PacBio::BED::BedReader; using BedWriter = PacBio::BED::BedWriter; using GenomicInterval = PacBio::BAM::GenomicInterval; using HtslibCompression = PacBio::BAM::HtslibCompression; namespace BedWriterTests { const std::vector<GenomicInterval> Intervals{ {"chr1", 213941196, 213942363}, {"chr1", 213942363, 213943530}, {"chr1", 213943530, 213944697}, {"chr2", 158364697, 158365864}, {"chr2", 158365864, 158367031}, {"chr3", 127477031, 127478198}, {"chr3", 127478198, 127479365}, {"chr3", 127479365, 127480532}, {"chr3", 127480532, 127481699}}; void CheckRoundTrip(const std::string& outFn, const HtslibCompression compressionType) { { BedWriter writer{outFn}; for (const auto& interval : BedWriterTests::Intervals) writer.Write(interval); } EXPECT_EQ(compressionType, PacBio::BAM::FormatUtils::CompressionType(outFn)); const auto contents = BedReader::ReadAll(outFn); EXPECT_TRUE(std::equal(BedWriterTests::Intervals.cbegin(), BedWriterTests::Intervals.cend(), contents.cbegin())); remove(outFn.c_str()); } } // namespace BedWriterTests TEST(BAM_BedWriter, throws_on_empty_filename) { EXPECT_THROW(BedWriter writer{""}, std::runtime_error); } TEST(BAM_BedWriter, can_write_plain_text) { const std::string outFn = PacBio::BAM::PbbamTestsConfig::GeneratedData_Dir + "/out.bed"; BedWriterTests::CheckRoundTrip(outFn, HtslibCompression::NONE); } TEST(BAM_BedWriter, can_write_gzipped_text) { const std::string outFn = PacBio::BAM::PbbamTestsConfig::GeneratedData_Dir + "/out.bed.gz"; BedWriterTests::CheckRoundTrip(outFn, HtslibCompression::GZIP); }
30.338462
100
0.719574
bio-nim
5da40434f93e40fac22f2e9e9ea7bee7395e3bcd
1,761
hpp
C++
RType.Server/Headers/TCPServer.hpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
RType.Server/Headers/TCPServer.hpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
RType.Server/Headers/TCPServer.hpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
#pragma once #include <memory> #include <vector> #include <optional> #include <thread> #include <string> #include <Network/IPacketManager.hpp> #include <Network/ITCPNetwork.hpp> #include <Network/Connection.hpp> #include <Lobby.hpp> namespace RType { class TCPServer : public ITCPNetwork { public: TCPServer(const std::int32_t& port); public: void Start() final; void Stop() final; void CheckClosedConnection(); void WriteAsync(const std::string& ip, const RType::RTypePack& p); void StartGame() override {} void CreateRoom(const std::uint32_t& maxPlayer) override {} void JoinRoom(const std::string& roomId) override {} void LeaveRoom(const std::string& roomId) override {} public: void AddLobby(Shared<Lobby> lobby); void RemoveLobby(const std::string &lobbyId); Shared<Lobby> GetLobby(const std::string& id); private: void StartAccept(); void OnAccept(Connection::ConnectionPtr socket, const boost::system::error_code& error); public: [[nodiscard]] boost::asio::io_context& GetIoContext() { return m_IoContext; } [[nodiscard]] std::optional<std::string> GetServerIp() const; [[nodiscard]] std::optional<Connection::ConnectionPtr> GetConnectionFromIp(const std::string& ip); [[nodiscard]] Shared<RType::IUDPNetwork> GetUdpNetwork() const override { return {}; } private: std::vector<Shared<Lobby>> m_Rooms; boost::asio::io_context m_IoContext; boost::asio::ip::tcp::acceptor m_Acceptor; std::vector<Connection::ConnectionPtr> m_Connections; std::thread m_Thread; bool m_IsRunning; Unique<IPacketManager> m_PacketManager; }; }
32.611111
106
0.664395
Mikyan0207
5da496eebeeeeb43539356f89eea88dbfb4bdc94
2,413
cpp
C++
cpp/daal/src/algorithms/normalization/minmax/minmax_fpt.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
169
2020-03-30T09:13:05.000Z
2022-03-15T11:12:36.000Z
cpp/daal/src/algorithms/normalization/minmax/minmax_fpt.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
cpp/daal/src/algorithms/normalization/minmax/minmax_fpt.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
75
2020-03-30T11:39:58.000Z
2022-03-26T05:16:20.000Z
/* file: minmax_fpt.cpp */ /******************************************************************************* * Copyright 2014-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of minmax algorithm and types methods. //-- */ #include "algorithms/normalization/minmax_types.h" #include "src/services/daal_strings.h" using namespace daal::data_management; using namespace daal::services; namespace daal { namespace algorithms { namespace normalization { namespace minmax { namespace interface1 { /** * Allocates memory to store the result of the minmax normalization algorithm * \param[in] input %Input object for the minmax normalization algorithm * \param[in] par %Parameter of the minmax normalization algorithm * \param[in] method Computation method of the minmax normalization algorithm */ template <typename algorithmFPType> DAAL_EXPORT Status Result::allocate(const daal::algorithms::Input * input, int method) { DAAL_CHECK(input, ErrorNullInput); const Input * algInput = static_cast<const Input *>(input); NumericTablePtr dataTable = algInput->get(data); Status s; DAAL_CHECK_STATUS(s, checkNumericTable(dataTable.get(), dataStr())); const size_t nRows = dataTable->getNumberOfRows(); const size_t nColumns = dataTable->getNumberOfColumns(); NumericTablePtr normalizedDataTable = HomogenNumericTable<algorithmFPType>::create(nColumns, nRows, NumericTable::doAllocate, &s); DAAL_CHECK_STATUS_VAR(s); set(normalizedData, normalizedDataTable); return s; } template DAAL_EXPORT Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input * input, int method); } // namespace interface1 } // namespace minmax } // namespace normalization } // namespace algorithms } // namespace daal
33.513889
134
0.695814
cmsxbc
5da4c4c25c5180de10e006f11ebaa79e2b4777e8
4,925
cpp
C++
Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp
bojosos/Nworc
a59cb18412a45a101f877caedf6ed0025a9e44a9
[ "MIT" ]
2
2021-05-13T17:57:04.000Z
2021-10-04T07:07:01.000Z
Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp
bojosos/Crowny
5aef056d2c95e04870d2372a87257ad9dccf168a
[ "MIT" ]
null
null
null
Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp
bojosos/Crowny
5aef056d2c95e04870d2372a87257ad9dccf168a
[ "MIT" ]
null
null
null
#include "cwpch.h" #include "Crowny/Scripting/Mono/MonoClass.h" #include "Crowny/Scripting/Mono/MonoManager.h" #include "Crowny/Scripting/Mono/MonoMethod.h" #include "Crowny/Scripting/Mono/MonoUtils.h" #include <mono/metadata/attrdefs.h> #include <mono/metadata/debug-helpers.h> #include <mono/metadata/loader.h> #include <mono/metadata/object.h> #include <mono/metadata/reflection.h> namespace Crowny { MonoMethod::MonoMethod(::MonoMethod* method) : m_Method(method), m_CachedParams(nullptr), m_CachedReturnType(nullptr), m_HasCachedSignature(false), m_CachedNumParams(0) { m_Name = mono_method_get_name(m_Method); m_FullDeclName = CrownyMonoVisibilityToString(GetVisibility()) + (IsStatic() ? " static " : " ") + mono_method_full_name(m_Method, true); } MonoClass* MonoMethod::GetParameterType(uint32_t idx) const { if (!m_HasCachedSignature) CacheSignature(); if (idx >= m_CachedNumParams) { CW_ENGINE_ERROR("Param index out of range."); return nullptr; } return m_CachedParams[idx]; } MonoObject* MonoMethod::Invoke(MonoObject* instance, void** params) { MonoObject* exception = nullptr; MonoObject* ret = mono_runtime_invoke(m_Method, instance, params, &exception); MonoUtils::CheckException(exception); return ret; } void* MonoMethod::GetThunk() const { return mono_method_get_unmanaged_thunk(m_Method); } bool MonoMethod::HasAttribute(MonoClass* monoClass) const { MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method); if (info == nullptr) return false; bool hasAttrs = mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr()) != 0; mono_custom_attrs_free(info); return hasAttrs; } MonoObject* MonoMethod::GetAttribute(MonoClass* monoClass) const { MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method); if (info == nullptr) return nullptr; MonoObject* attrs = nullptr; if (mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr())) { attrs = mono_custom_attrs_get_attr(info, monoClass->GetInternalPtr()); } mono_custom_attrs_free(info); return attrs; } bool MonoMethod::IsStatic() const { if (!m_HasCachedSignature) CacheSignature(); return m_IsStatic; } MonoClass* MonoMethod::GetReturnType() const { if (!m_HasCachedSignature) CacheSignature(); return m_CachedReturnType; } void MonoMethod::CacheSignature() const { MonoMethodSignature* signature = mono_method_signature(m_Method); MonoType* returnType = mono_signature_get_return_type(signature); if (returnType != nullptr) { ::MonoClass* returnTypeClass = mono_class_from_mono_type(returnType); if (returnTypeClass != nullptr) m_CachedReturnType = MonoManager::Get().FindClass(returnTypeClass); } m_CachedNumParams = (uint32_t)mono_signature_get_param_count(signature); if (m_CachedParams != nullptr) { delete[] m_CachedParams; m_CachedParams = nullptr; } if (m_CachedNumParams > 0) { m_CachedParams = new MonoClass*[m_CachedNumParams]; void* iter = nullptr; for (uint32_t i = 0; i < m_CachedNumParams; i++) { MonoType* curParamType = mono_signature_get_params(signature, &iter); ::MonoClass* returnTypeClass = mono_class_from_mono_type(curParamType); m_CachedParams[i] = MonoManager::Get().FindClass(returnTypeClass); } } m_IsStatic = !mono_signature_is_instance(signature); m_HasCachedSignature = true; } uint32_t MonoMethod::GetNumParams() const { if (!m_HasCachedSignature) CacheSignature(); return m_CachedNumParams; } CrownyMonoVisibility MonoMethod::GetVisibility() { uint32_t flags = mono_method_get_flags(m_Method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK; switch (flags) { case (MONO_METHOD_ATTR_PRIVATE): return CrownyMonoVisibility::Private; case (MONO_METHOD_ATTR_FAM_AND_ASSEM): return CrownyMonoVisibility::ProtectedInternal; case (MONO_METHOD_ATTR_ASSEM): return CrownyMonoVisibility::Internal; case (MONO_METHOD_ATTR_FAMILY): return CrownyMonoVisibility::Protected; case (MONO_METHOD_ATTR_PUBLIC): return CrownyMonoVisibility::Public; } CW_ENGINE_ASSERT(false, "Unknown visibility."); return CrownyMonoVisibility::Private; } } // namespace Crowny
32.615894
108
0.643249
bojosos
5da760efdd8c8eaa8b7bff8dbd6d3dc1c382a22f
4,019
cpp
C++
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/MatrixBuilder/SleMatrixBuilder.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "SleMatrixBuilder.h" namespace fvmsolver { SleMatrixBuilder::SleMatrixBuilder( AbstractCoeffsCalculator& coeffsCalculator, uPtrDataPort spData) : spDataPort_(std::move(spData)), dataPort_(*spDataPort_), coeffsCalculator_(coeffsCalculator), aP_(dataPort_.getAp()), aW_(dataPort_.getAw()), aE_(dataPort_.getAe()), aN_(dataPort_.getAn()), aS_(dataPort_.getAs()) { } void SleMatrixBuilder::build(std::shared_ptr<SleSolver> sleSolver) { pSleSolver_ = sleSolver; createMatrixAndVectors(); buildInterior(); buildBoundary(); } void SleMatrixBuilder::buildInterior() { size_t domainParts = dataPort_.getInteriorPartsAmount(); for (size_t partId = 0; partId < domainParts; partId++) { std::string name = dataPort_.getInteriorName(partId); coeffsCalculator_.chooseActualDomainPart(name); size_t partCells = dataPort_.getPartCellsAmount(name); for (size_t i = 0; i < partCells; i++) { coeffsCalculator_.calculateInterior(i); placeAllCoeffs(); } } } void SleMatrixBuilder::buildBoundary() { size_t domainParts = dataPort_.getBcPartsAmount(); for (size_t partId = 0; partId < domainParts; partId++) { std::string name = dataPort_.getBoundaryName(partId); coeffsCalculator_.chooseActualDomainPart(name); size_t partCells = dataPort_.getPartCellsAmount(name); for (size_t i = 0; i < partCells; i++) { coeffsCalculator_.calculateBoundary(i); placeAllCoeffs(); } } } void SleMatrixBuilder::placeAllCoeffs() { double a_w = coeffsCalculator_.getAw(); double a_e = coeffsCalculator_.getAe(); double a_n = coeffsCalculator_.getAn(); double a_s = coeffsCalculator_.getAs(); double a_p = coeffsCalculator_.getAp(); size_t posW_ = coeffsCalculator_.get_wNum(); size_t posE_ = coeffsCalculator_.get_eNum(); size_t posN_ = coeffsCalculator_.get_nNum(); size_t posS_ = coeffsCalculator_.get_sNum(); size_t posP_ = coeffsCalculator_.get_pNum() - 1; bool isInteriorW_ = coeffsCalculator_.is_wInterior(); bool isInteriorE_ = coeffsCalculator_.is_eInterior(); bool isInteriorN_ = coeffsCalculator_.is_nInterior(); bool isInteriorS_ = coeffsCalculator_.is_sInterior(); placeCoeffsOtherDiags(posP_, posW_, -a_w, isInteriorW_); placeCoeffsOtherDiags(posP_, posE_, -a_e, isInteriorE_); placeCoeffsOtherDiags(posP_, posN_, -a_n, isInteriorN_); placeCoeffsOtherDiags(posP_, posS_, -a_s, isInteriorS_); placeCoeffsMainDiag(posP_, posP_, a_p); pSleSolver_->placeRhsValue(posP_, coeffsCalculator_.getRHS()); aP_[posP_] = a_p; dataPort_.setRhs(posP_, coeffsCalculator_.getRHS()); dataPort_.set_b(posP_, coeffsCalculator_.get_b()); saveCoeff(posW_, a_w, aW_); saveCoeff(posE_, a_e, aE_); saveCoeff(posN_, a_n, aN_); saveCoeff(posS_, a_s, aS_); } void SleMatrixBuilder::placeCoeffsMainDiag(size_t rowNum, size_t colNum, double value) { pSleSolver_->placeCoeff(rowNum, colNum, value); } void SleMatrixBuilder::placeCoeffsOtherDiags(size_t rowNum, size_t colNum, double value, bool isInteriorCell) { if (isInteriorCell) { pSleSolver_->placeCoeff(rowNum, colNum - 1, value); } } void SleMatrixBuilder::createMatrixAndVectors() { size_t matrixDimention_ = dataPort_.getAllCellsAmount(); pSleSolver_->createContainers(matrixDimention_); } void SleMatrixBuilder::saveCoeff(size_t pos, double value, std::vector<double>& coeff) { if (0 < pos) { coeff.at(pos - 1) = value; } } }
33.491667
91
0.631003
artvns
5da8da04f30037a3ebffb28d5b021149c11fed2d
951
cpp
C++
2017-08-19/C.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
3
2018-04-02T06:00:51.000Z
2018-05-29T04:46:29.000Z
2017-08-19/C.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-03-31T17:54:30.000Z
2018-05-02T11:31:06.000Z
2017-08-19/C.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-10-07T00:08:06.000Z
2021-06-28T11:02:59.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; const int NMAX = 31; int T, N; int adj[NMAX][NMAX]; int main() { int i, j, k, t; bool flag; scanf("%d", &T); for(t = 0;t < T;t += 1) { flag = true; scanf("%d", &N); if(N >= 6) { for(i = 1;i <= N;i += 1) { for(j = 1;j <= N - i;j += 1) scanf("%*d"); } } else { for(i = 1;i <= N;i += 1) { for(j = 1;j <= N - i;j += 1) { scanf("%d", &adj[i][i + j]); adj[i + j][i] = adj[i][i + j]; } } } if(N >= 6) printf("Bad Team!\n"); else { for(i = 1;i <= N;i += 1) { for(j = i + 1;j <= N;j += 1) { for(k = j + 1;k <= N;k += 1) { if((adj[i][j] && adj[j][k] && adj[k][i]) || (!adj[i][j] && !adj[j][k] && !adj[k][i])) flag = false; } } } if(flag) printf("Great Team!\n"); else printf("Bad Team!\n"); } } exit(0); }
14.630769
51
0.392219
tangjz
5daa35f4e79a8828c2318ae5eb271a8db9a6d1ab
1,742
cpp
C++
PE/ch14/14.2/winei.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
PE/ch14/14.2/winei.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
PE/ch14/14.2/winei.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
#include <iostream> #include "winei.h" using std::cin; using std::cout; using std::cerr; using std::endl; using std::string; Wine::Wine(const char * l, int y, const int yr[], const int bot[]) : string(l), years(y), PairArray(ArrayInt(yr,y),ArrayInt(bot,y)) { } Wine::Wine(const char * l, const ArrayInt & yr, const ArrayInt & bot) : string(l), years(yr.size()), PairArray(ArrayInt(yr), ArrayInt(yr)) { if (yr.size() != bot.size()) { cerr << "Year data, bottle data mismatch! Array set to 0 size.\n"; years = 0; PairArray::operator=(PairArray(ArrayInt(),ArrayInt())); } else { PairArray::first() = yr; PairArray::second() = bot; } } Wine::Wine(const char * l, const PairArray & yr_bot) : string(l), years(yr_bot.first().size()), PairArray(yr_bot) { } Wine::Wine(const char * l, int y) : string(l), years(y), PairArray(ArrayInt(0,y),ArrayInt(0,y)) { } void Wine::GetBottles() { if (years < 1) { cout << "No space to get data\n"; return; } cout << "Enter " << Label() << " data for " << years << " year(s):\n"; for (int i = 0; i < years; i++) { cout << "Enter year: "; cin >> PairArray::first()[i]; cout << "Enter bottles for that year: "; cin >> PairArray::second()[i]; } } void Wine::Show() const { cout << "Wine: " << Label() << endl; cout << "\tYear\tBottles\n"; for (int i = 0; i < years; i++) { cout << "\t" << PairArray::first()[i]; cout << "\t" << PairArray::second()[i] << endl; } } const string & Wine::Label() const { return (const string &)(*this); } int Wine::sum() const { return PairArray::second().sum(); }
21.775
74
0.538462
DustOfStars
5dacb2657b4b72c1f174c12be72a8cc9e8347f3b
194
hpp
C++
include/mruby_integration/models/colour.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
40
2021-05-25T04:21:49.000Z
2022-02-19T05:05:45.000Z
include/mruby_integration/models/colour.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
4
2021-09-17T06:52:35.000Z
2021-12-29T23:07:18.000Z
include/mruby_integration/models/colour.hpp
HellRok/Taylor
aa9d901b4db77395a0bde896500016353adcd73b
[ "MIT" ]
1
2021-12-23T00:59:27.000Z
2021-12-23T00:59:27.000Z
#pragma once #include "mruby.h" #include "raylib.h" extern RClass *Colour_class; void setup_Colour(mrb_state*, mrb_value, Color*, int, int, int, int); void append_models_Colour(mrb_state*);
17.636364
69
0.747423
HellRok
5dad76ffbddaefea91423f5e315c49c177c7cac1
2,745
cpp
C++
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
3
2020-11-16T08:58:30.000Z
2020-11-16T08:58:33.000Z
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
图论/差分约束/acwing_1170.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i = a; i< n; i++) #define per(i,a,n) for(int i=n-1; i>=a; i--) #define pb push_back #define mp make_pair #define all(x) (x).begin(), (x).end() #define x first #define y second #define sz(x) ((int)(x).size()) typedef vector<int> vi; typedef long long ll; typedef pair<int, int> pii; mt19937 mrand(random_device{}()); const ll mod = 1000000007; int rnd(int x) { return mrand() % x;} ll mulmod(ll a, ll b) {ll res=0;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=(res+a)%mod;a=2*a%mod;}return res;} ll powmod(ll a, ll b) {ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;} //snippet-head //第一个就是判负环 全部加入队列跑一次SPFA即可 //所有奶牛的距离都是相对距离,所以需要虚拟原点,假设所有牛都在数轴的正半轴 所有点都在x0的左边 也就是说x0是最右边的 //对于第二个要求 直接把1号点固定在0 也就是 x1 = 0 因为都是相对距离 不影响距离 最后看一下xn是不是可以无限大 这也等价于1号点到其他点的最短距离 //但是虚拟原点 不需要实现 实际上 在判断负环的时候所有点都已经入队 可以起到同样的效果 //求一下xn的最长路 如果无穷大 就是无穷大 否则就是最大值 //约束条件:xi <= x[i+1] + 0, xb <= xa + l, xa <= xb - d const int INF = 0x3f3f3f3f; const int N = 1010, M = 21010; //边数判断就是满足条件的类 每类需要多少点 全部加起来 //因为加边 的时候 会满足所有条件 也就是说每个条件 都要单独加边 int q[N], h[N], e[M], ne[M], idx, w[M], cnt[N], dist[N]; bool st[N]; int n, m1, m2; void add(int a, int b, int c){ e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx ++; } bool spfa(int sz){ memset(dist, 0x3f, sizeof dist); memset(st, 0, sizeof st); memset(cnt, 0, sizeof cnt); int hh = 0, tt = 1; for(int i = 1; i <= sz; i++){ //加入队列 求负环 dist[i] = 0; q[tt++] = i; st[i] = true; } while(hh != tt){ int t = q[hh++]; if(hh == N) hh = 0; st[t] = false; for(int i = h[t]; i != -1; i = ne[i]){ int j = e[i]; if(dist[j] > dist[t] + w[i]){ dist[j] = dist[t] + w[i]; cnt[j] = cnt[t] + 1; if(cnt[j] >= n) return false; if(!st[j]){ q[tt++] = j; if(tt == N) tt = 0; st[j] = true; } } } } return true; } int main(){ memset(h, -1, sizeof h); scanf("%d%d%d", &n, &m1, &m2); for(int i = 1; i < n; i++) add(i + 1, i, 0); while(m1 --){ int a, b, c; scanf("%d%d%d", &a, &b, &c); if(b < a ) swap(a, b); add(a, b, c); } while(m2 --){ int a,b ,c; scanf("%d%d%d", &a, &b, &c); if(b < a) swap(a, b); add(b, a, -c); } if(!spfa(n)) puts("-1"); //前n个点的图有负环 else{ spfa(1); //将第一个点放进去求 if(dist[n] == INF) puts("-2"); else printf("%d\n", dist[n]); } return 0; }
26.394231
112
0.488889
tempure
5dade33a7eb95eb746d98e0eecfccaeba73f0c6f
3,870
cpp
C++
MMC/MMCKeys/keysmanager.cpp
Myweik/MMC_qgroundcontrol
3aa97928d30fc9de56fde2a0d37a49245de83da4
[ "Apache-2.0" ]
2
2020-04-14T12:50:53.000Z
2021-07-19T02:09:04.000Z
MMC/MMCKeys/keysmanager.cpp
Myweik/MMC_qgroundcontrol
3aa97928d30fc9de56fde2a0d37a49245de83da4
[ "Apache-2.0" ]
5
2020-07-01T21:31:53.000Z
2021-02-01T10:53:39.000Z
MMC/MMCKeys/keysmanager.cpp
Myweik/MMC_qgroundcontrol
3aa97928d30fc9de56fde2a0d37a49245de83da4
[ "Apache-2.0" ]
2
2020-05-11T03:11:11.000Z
2021-02-03T10:53:03.000Z
#include "keysmanager.h" #include "QGCApplication.h" #include "MMC/MMCMount/mmcmount.h" MMCKey::MMCKey(int id, QObject *parent) : QObject(parent), _id(id) { _timer = new QTimer(this); _timer->setInterval(100); connect(_timer, SIGNAL(timeout()), this, SLOT(onTimerOut())); } void MMCKey::setKey(bool key) { if(key == _key) return; _key = key; emit keyChanged(_key); if(_key){ emit press(this); _accumulatedTime = 1; _timer->start(); }else{ emit upspring(this); _timer->stop(); if(_accumulatedTime < 5) emit click(this); } } void MMCKey::onTimerOut() { _accumulatedTime++; emit longPress(this); } //------------------------------------------------------------------------------ KeysManager::KeysManager(QObject *parent) : QObject(parent) { for(int i = 0; i < 5; i++){ _key[i] = new MMCKey(i, this); connect(_key[i], SIGNAL(press(MMCKey*)), this, SLOT(onPress(MMCKey*))); connect(_key[i], SIGNAL(upspring(MMCKey*)), this, SLOT(onUpspring(MMCKey*))); connect(_key[i], SIGNAL(longPress(MMCKey*)), this, SLOT(onLongPress(MMCKey*))); connect(_key[i], SIGNAL(click(MMCKey*)), this, SLOT(onClick(MMCKey*))); } /* an jian yu gong neng bang ding */ /* 0-A 1-B 2-C 3-D 4-E */ _keyId[4] = KEY_REC_OR_PHOTO; } void KeysManager::setKey(int id, bool key) { if(id < 0 || id > 4) return; _key[id]->setKey(key); } /* ----------------------------------------- */ void KeysManager::onPress(MMCKey *key) { switch (_keyId[key->id()]) { case KEY_REC_OR_PHOTO: break; case KEY_ZOOM_DOWN: break; case KEY_ZOOM_UP: break; default: break; } } void KeysManager::onUpspring(MMCKey *key) { switch (_keyId[key->id()]) { case KEY_REC_OR_PHOTO: if(key->accumulatedTime() > 1) REC(); break; case KEY_ZOOM_DOWN: break; case KEY_ZOOM_UP: break; default: break; } } void KeysManager::onLongPress(MMCKey *key) { switch (_keyId[key->id()]) { case KEY_REC_OR_PHOTO: break; case KEY_ZOOM_DOWN: break; case KEY_ZOOM_UP: break; default: break; } } void KeysManager::onClick(MMCKey *key) { switch (_keyId[key->id()]) { case KEY_REC_OR_PHOTO: photo(); break; case KEY_ZOOM_DOWN: break; case KEY_ZOOM_UP: break; default: break; } } /* ----------------------------------------- */ void KeysManager::photo() { // if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){ // Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle(); // if(activeVehicle && !activeVehicle->mountLost() && activeVehicle->currentMount() && activeVehicle->currentMount()->mountType() ==MountInfo::MOUNT_CUSTOM){ // CustomMount* camMount = dynamic_cast<CustomMount*>(activeVehicle->currentMount()); // camMount->doCameraTrigger(); // } // } if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){ Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle(); if(activeVehicle){ activeVehicle->doCameraTrigger(); } } } void KeysManager::REC() { if(qgcApp()->toolbox()->multiVehicleManager()->activeVehicleAvailable()){ Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle(); if(activeVehicle && !activeVehicle->mountLost() && activeVehicle->currentMount() && activeVehicle->currentMount()->mountType() ==MountInfo::MOUNT_CUSTOM){ CustomMount* camMount = dynamic_cast<CustomMount*>(activeVehicle->currentMount()); camMount->videoTape(); } } }
26.326531
164
0.576486
Myweik
5dae0f10370c9c8626c1d63c15a43820ef313c15
403
cpp
C++
hackerrank/algorithms/2-implementation/020.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
null
null
null
hackerrank/algorithms/2-implementation/020.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
null
null
null
hackerrank/algorithms/2-implementation/020.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
2
2018-10-04T19:01:52.000Z
2018-10-05T08:49:57.000Z
#include <bits/stdc++.h> using namespace std; int main() { vector<int> a(26); for(int i = 0; i < 26; i++) { cin >> a[i]; } string word; cin >> word; int k = word.length (); vector<int> b(k); int max =0; for (int i = 0; i < k; ++i) { if (a[(int)word[i]-97]>max) { max= a[(int)word[i]-97]; } } cout<<(max*k); return 0; }
15.5
32
0.431762
him1411
5dae827d0c916f3116817b0609f462cbb578064b
41,315
cpp
C++
c/common/tests/crtabstractions_unittests/crtabstractions_unittests.cpp
josesimoes/azure-iot-sdks
75107fa7b0e614a83dfcd81aff4727541d81fa28
[ "MIT" ]
4
2017-08-15T10:02:59.000Z
2021-12-20T10:48:25.000Z
c/common/tests/crtabstractions_unittests/crtabstractions_unittests.cpp
josesimoes/azure-iot-sdks
75107fa7b0e614a83dfcd81aff4727541d81fa28
[ "MIT" ]
null
null
null
c/common/tests/crtabstractions_unittests/crtabstractions_unittests.cpp
josesimoes/azure-iot-sdks
75107fa7b0e614a83dfcd81aff4727541d81fa28
[ "MIT" ]
9
2016-10-08T12:33:33.000Z
2021-12-23T09:46:31.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <cstdlib> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "testrunnerswitcher.h" #include "crt_abstractions.h" #include "errno.h" #include <climits> #include "micromock.h" #ifdef _MSC_VER #pragma warning(disable:4505) #endif #if defined _MSC_VER #include "crtdbg.h" static _invalid_parameter_handler oldInvalidParameterHandler; static int oldReportType; static void my_invalid_parameter_handler( const wchar_t * expression, const wchar_t * function, const wchar_t * file, unsigned int line, uintptr_t pReserved ) { (void)expression; (void)function; (void)file; (void)line; (void)pReserved; /*do nothing*/ } /* The below defines are because on Windows platform, the secure version of the CRT functions will invoke WATSON if no invalid parameter handler provided by the user */ #define HOOK_INVALID_PARAMETER_HANDLER() {oldInvalidParameterHandler = _set_invalid_parameter_handler(my_invalid_parameter_handler);oldReportType=_CrtSetReportMode(_CRT_ASSERT, 0);} #define UNHOOK_INVALID_PARAMETER_HANDLER() {(void)_CrtSetReportMode(_CRT_ASSERT, oldReportType); (void)_set_invalid_parameter_handler(oldInvalidParameterHandler);} #else /* _MSC_VER */ #define HOOK_INVALID_PARAMETER_HANDLER() do{}while(0) #define UNHOOK_INVALID_PARAMETER_HANDLER() do{}while(0) #endif /* _MSC_VER */ static const unsigned int interestingUnsignedIntNumbersToBeConverted[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 32, 43, 54, 65, 76, 87, 98, 123, 1234, 12341, UINT_MAX / 2, UINT_MAX -1, UINT_MAX, 42, 0x42 }; #ifndef SIZE_MAX #define SIZE_MAX ((size_t)~(size_t)0) #endif static const size_t interestingSize_tNumbersToBeConverted[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 32, 43, 54, 65, 76, 87, 98, 123, 1234, 12341, SIZE_MAX / 2, SIZE_MAX -1, SIZE_MAX, 42, 0x42 }; static MICROMOCK_GLOBAL_SEMAPHORE_HANDLE g_dllByDll; BEGIN_TEST_SUITE(CRTAbstractions_UnitTests) TEST_SUITE_INITIALIZE(a) { INITIALIZE_MEMORY_DEBUG(g_dllByDll); } TEST_SUITE_CLEANUP(b) { DEINITIALIZE_MEMORY_DEBUG(g_dllByDll); } /* strcat_s */ // Tests_SRS_CRT_ABSTRACTIONS_99_008: [strcat_s shall append the src to dst and terminates the resulting string with a null character.] // Tests_SRS_CRT_ABSTRACTIONS_99_009: [The initial character of src shall overwrite the terminating null character of dst.] // Tests_SRS_CRT_ABSTRACTIONS_99_003: [strcat_s shall return Zero upon success.] TEST_FUNCTION(strcat_s_Appends_Source_To_Destination) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act result = strcat_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "DestinationSource", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcat_s_Appends_Empty_Source_To_Destination) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = ""; int result; // act result = strcat_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "Destination", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcat_s_Appends_Source_To_Empty_Destination) { // arrange char dstString[128] = ""; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act result = strcat_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcat_s_Appends_Empty_Source_To_Empty_Destination) { // arrange char dstString[128] = ""; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = ""; int result; // act result = strcat_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "", dstString); ASSERT_ARE_EQUAL(int, 0, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_004: [If dst is NULL or unterminated, the error code returned shall be EINVAL & dst shall not be modified.] TEST_FUNCTION(strcat_s_With_NULL_Destination_Fails) { // arrange char* dstString = NULL; size_t sizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strcat_s(dstString, sizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_IS_NULL(dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); } TEST_FUNCTION(strcat_s_With_Unterminated_Destination_Fails) { // arrange char dstString[128]; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; for (size_t i = 0; i < dstSizeInBytes; i++) { dstString[i] = 'z'; } // act HOOK_INVALID_PARAMETER_HANDLER(); result = strcat_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert #ifndef _MSC_VER /* MSDN claims that content of destination buffer is not modified, but that is not true. Filing bug. */ for (size_t i = 0; i < dstSizeInBytes; i++) { ASSERT_ARE_EQUAL(char, 'z', dstString[i]); } #endif ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_005: [If src is NULL, the error code returned shall be EINVAL and dst[0] shall be set to 0.] TEST_FUNCTION(strcat_s_With_NULL_Source_Fails) { // arrange char dstString[128] = "Source"; size_t dstSizeInBytes = sizeof(dstString); char* srcString = NULL; int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strcat_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_006: [If the dstSizeInBytes is 0 or smaller than the required size for dst & src, the error code returned shall be ERANGE & dst[0] set to 0.] TEST_FUNCTION(strcat_s_With_dstSizeInBytes_Equals_Zero_Fails) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act dstSizeInBytes = 0; HOOK_INVALID_PARAMETER_HANDLER(); result = strcat_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert #ifdef _MSC_VER /*MSDN Claims that destination buffer would be set to empty & ERANGE is the error, but not the case. Filing bug.*/ ASSERT_ARE_EQUAL(char_ptr, "Destination", dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); #else ASSERT_ARE_EQUAL(char, '\0', dstString[0]); ASSERT_ARE_EQUAL(int, ERANGE, result); #endif } TEST_FUNCTION(strcat_s_With_dstSizeInBytes_Smaller_Than_dst_and_src_Fails) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act HOOK_INVALID_PARAMETER_HANDLER(); dstSizeInBytes = strlen(dstString) + (strlen(srcString) - 3); result = strcat_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, ERANGE, result); } /* strcpy_s */ // Tests_SRS_CRT_ABSTRACTIONS_99_016: [strcpy_s shall copy the contents in the address of src, including the terminating null character, to the location that's specified by dst.] // Tests_SRS_CRT_ABSTRACTIONS_99_011 : [strcpy_s shall return Zero upon success] TEST_FUNCTION(strcpy_s_copies_Source_into_Destination) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result = 0; // act result = strcpy_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcpy_s_copies_Empty_Source_into_Destination) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = ""; int result = 0; // act result = strcpy_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcpy_s_copies_Source_into_Empty_Destination) { // arrange char dstString[128] = ""; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result = 0; // act result = strcpy_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strcpy_s_copies_Empty_Source_into_Empty_Destination) { // arrange char dstString[128] = ""; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = ""; int result = 0; // act result = strcpy_s(dstString, dstSizeInBytes, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "", dstString); ASSERT_ARE_EQUAL(int, 0, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_012 : [If dst is NULL, the error code returned shall be EINVAL & dst shall not be modified.] TEST_FUNCTION(strcpy_s_With_NULL_Destination_Fails) { // arrange char* dstString = NULL; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result = 0; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strcpy_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char_ptr, NULL, dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_013 : [If src is NULL, the error code returned shall be EINVAL and dst[0] shall be set to 0.] TEST_FUNCTION(strcpy_s_With_NULL_Source_Fails) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char* srcString = NULL; int result = 0; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strcpy_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_014 : [If the dstSizeInBytes is 0 or smaller than the required size for the src string, the error code returned shall be ERANGE & dst[0] set to 0.] TEST_FUNCTION(strcpy_s_With_dstSizeInBytes_Equals_Zero_Fails) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act dstSizeInBytes = 0; HOOK_INVALID_PARAMETER_HANDLER(); result = strcpy_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert #ifdef _MSC_VER /*MSDN Claims that destination buffer would be set to empty & ERANGE is the error, but not the case. Filing bug.*/ ASSERT_ARE_EQUAL(char_ptr, "Destination", dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); #else ASSERT_ARE_EQUAL(char, '\0', dstString[0]); ASSERT_ARE_EQUAL(int, ERANGE, result); #endif } TEST_FUNCTION(strcpy_s_With_dstSizeInBytes_Smaller_Than_source_Fails) { // arrange char dstString[128] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; int result; // act HOOK_INVALID_PARAMETER_HANDLER(); dstSizeInBytes = sizeof(srcString) - 2; result = strcpy_s(dstString, dstSizeInBytes, srcString); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, ERANGE, result); } /* strncpy_s */ // Tests_SRS_CRT_ABSTRACTIONS_99_025 : [strncpy_s shall copy the first N characters of src to dst, where N is the lesser of MaxCount and the length of src.] // Tests_SRS_CRT_ABSTRACTIONS_99_041 : [If those N characters will fit within dst(whose size is given as dstSizeInBytes) and still leave room for a null terminator, then those characters shall be copied and a terminating null is appended; otherwise, strDest[0] is set to the null character and ERANGE error code returned per requirement below.] // Tests_SRS_CRT_ABSTRACTIONS_99_018: [strncpy_s shall return Zero upon success] TEST_FUNCTION(strncpy_s_copies_N_chars_of_source_to_destination_where_maxCount_equals_source_Length) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strncpy_s_copies_N_chars_of_source_to_destination_where_maxCount_is_larger_than_Source_Length) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount+5); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } TEST_FUNCTION(strncpy_s_copies_N_chars_of_source_to_destination_where_maxCount_is_less_than_source_length) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount - 3); // assert ASSERT_ARE_EQUAL(char_ptr, "Sour", dstString); ASSERT_ARE_EQUAL(int, 0, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_026 : [If MaxCount is _TRUNCATE(defined as - 1), then as much of src as will fit into dst shall be copied while still leaving room for the terminating null to be appended.] TEST_FUNCTION(strncpy_s_with_maxCount_set_to_TRUNCATE_and_destination_fits_source) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act maxCount = _TRUNCATE; result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); // assert ASSERT_ARE_EQUAL(char_ptr, "Source", dstString); ASSERT_ARE_EQUAL(int, 0, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_026 : [If MaxCount is _TRUNCATE(defined as - 1), then as much of src as will fit into dst shall be copied while still leaving room for the terminating null to be appended.] // Tests_SRS_CRT_ABSTRACTIONS_99_019: [If truncation occurred as a result of the copy, the error code returned shall be STRUNCATE .] TEST_FUNCTION(strncpy_s_with_maxCount_set_to_TRUNCATE_and_destination_is_smaller_than_source) { // arrange char dstString[] = "Dest"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act maxCount = _TRUNCATE; result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); // assert ASSERT_ARE_EQUAL(char_ptr, "Sour", dstString); ASSERT_ARE_EQUAL(int, STRUNCATE, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_020 : [If dst is NULL, the error code returned shall be EINVAL and dst shall not be modified.] TEST_FUNCTION(strncpy_s_fails_with_destination_set_to_NULL) { // arrange char* dstString = NULL; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_IS_NULL(dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_021: [If src is NULL, the error code returned shall be EINVAL and dst[0] shall be set to 0.] TEST_FUNCTION(strncpy_s_fails_with_source_set_to_NULL) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char* srcString = NULL; size_t maxCount = sizeof(srcString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_022: [If the dstSizeInBytes is 0, the error code returned shall be EINVAL and dst shall not be modified.] TEST_FUNCTION(strncpy_s_fails_with_dstSizeInBytes_set_to_Zero) { // arrange char dstString[] = "Destination"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); dstSizeInBytes = 0; result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char_ptr, "Destination", dstString); ASSERT_ARE_EQUAL(int, EINVAL, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_023 : [If dst is not NULL & dstSizeInBytes is smaller than the required size for the src string, the error code returned shall be ERANGE and dst[0] shall be set to 0.] TEST_FUNCTION(strncpy_s_dstSizeInBytes_is_smaller_than_the_required_size_for_source) { // arrange char dstString[] = "Dest"; size_t dstSizeInBytes = sizeof(dstString); char srcString[] = "Source"; size_t maxCount = sizeof(srcString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); result = strncpy_s(dstString, dstSizeInBytes, srcString, maxCount); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char,'\0', dstString[0]); ASSERT_ARE_EQUAL(int, ERANGE, result); } /* sprintf_s */ // Tests_SRS_CRT_ABSTRACTIONS_99_029: [The sprintf_s function shall format and store series of characters and values in dst.Each argument(if any) is converted and output according to the corresponding Format Specification in the format variable.] // Tests_SRS_CRT_ABSTRACTIONS_99_031: [A null character is appended after the last character written.] // Tests_SRS_CRT_ABSTRACTIONS_99_027: [sprintf_s shall return the number of characters stored in dst upon success. This number shall not include the terminating null character.] TEST_FUNCTION(sprintf_s_formats_and_stores_chars_and_values_in_destination) { // arrange char dstString[1024]; size_t dstSizeInBytes = sizeof(dstString); char expectedString[] = "sprintf_s: 123, hello, Z, 1.5"; int expectedStringSize = (int)(sizeof(expectedString)); int result; // act result = sprintf_s(dstString, dstSizeInBytes, "sprintf_s: %d, %s, %c, %3.1f", 123, "hello", 'Z', 1.5f); // assert ASSERT_ARE_EQUAL(char_ptr, expectedString, dstString); ASSERT_ARE_EQUAL(int, expectedStringSize-1, result); } // Tests_SRS_CRT_ABSTRACTIONS_99_028: [If dst or format is a null pointer, sprintf_s shall return -1.] TEST_FUNCTION(sprintf_s_fails_with_dst_set_to_null) { // arrange char* dstString = NULL; size_t dstSizeInBytes = sizeof(dstString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = sprintf_s(dstString, dstSizeInBytes, "sprintf_s: %d, %s, %c, %3.1f", 123, "hello", 'Z', 1.5f); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(int, -1, result); ASSERT_ARE_EQUAL(int, EINVAL, errno); } TEST_FUNCTION(sprintf_s_fails_with_format_set_to_null) { // arrange char dstString[1024]; size_t dstSizeInBytes = sizeof(dstString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); #ifdef _MSC_VER #pragma warning(suppress: 6387) /* This is test code, explictly calling with NULL argument */ #endif result = sprintf_s(dstString, dstSizeInBytes, NULL); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(int, -1, result); ASSERT_ARE_EQUAL(int, EINVAL, errno); } // Tests_SRS_CRT_ABSTRACTIONS_99_034 : [If the dst buffer is too small for the text being printed, then dst is set to an empty string and the function shall return -1.] TEST_FUNCTION(sprintf_s_fails_with_dst_too_small) { // arrange char dstString[5]; size_t dstSizeInBytes = sizeof(dstString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); result = sprintf_s(dstString, dstSizeInBytes, "sprintf_s: %d, %s, %c, %3.1f", 123, "hello", 'Z', 1.5f); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char_ptr, "", dstString); ASSERT_ARE_EQUAL(int, -1, result); } TEST_FUNCTION(sprintf_s_fails_with_dst_buffer_size_not_fitting_null_char) { // arrange char dstString[5]; size_t dstSizeInBytes = sizeof(dstString); int result; // act HOOK_INVALID_PARAMETER_HANDLER(); result = sprintf_s(dstString, dstSizeInBytes, "12345"); UNHOOK_INVALID_PARAMETER_HANDLER(); // assert ASSERT_ARE_EQUAL(char_ptr, "", dstString); ASSERT_ARE_EQUAL(int, -1, result); } /* mallocAndStrcpy_s */ // Tests_SRS_CRT_ABSTRACTIONS_99_038 : [mallocAndstrcpy_s shall allocate memory for destination buffer to fit the string in the source parameter.] // Tests_SRS_CRT_ABSTRACTIONS_99_039 : [mallocAndstrcpy_s shall copy the contents in the address source, including the terminating null character into location specified by the destination pointer after the memory allocation.] // Tests_SRS_CRT_ABSTRACTIONS_99_035: [mallocAndstrcpy_s shall return Zero upon success] TEST_FUNCTION(mallocAndStrcpy_s_copies_source_string_into_allocated_memory) { // arrange char* destString = NULL; char srcString[] = "Source"; int result; // act result = mallocAndStrcpy_s(&destString, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, destString, srcString); ASSERT_ARE_EQUAL(int, 0, result); ///cleanup free(destString); } // Tests_SRS_CRT_ABSTRACTIONS_99_036: [destination parameter or source parameter is NULL, the error code returned shall be EINVAL and destination shall not be modified.] TEST_FUNCTION(mallocAndStrcpy_s_fails_with_destination_pointer_set_to_null) { // arrange char** destPointer = NULL; char srcString[] = "Source"; int result; // act result = mallocAndStrcpy_s(destPointer, srcString); // assert ASSERT_ARE_EQUAL(int, EINVAL, result); } TEST_FUNCTION(mallocAndStrcpy_s_fails_with_source_set_to_null) { // arrange char* destString = (char*)("Destination"); char* srcString = NULL; int result; // act result = mallocAndStrcpy_s(&destString, srcString); // assert ASSERT_ARE_EQUAL(char_ptr, "Destination", destString); ASSERT_ARE_EQUAL(int, EINVAL, result); } /*http://vstfrd:8080/Azure/RD/_workitems/edit/3216760*/ #if 0 // Tests_SRS_CRT_ABSTRACTIONS_99_037: [Upon failure to allocate memory for the destination, the function will return ENOMEM.] TEST_FUNCTION(mallocAndStrcpy_s_fails_upon_failure_to_allocate_memory) { // arrange char* destString = NULL; char* srcString = "Source"; int result; mallocSize = 0; // act #ifdef _CRTDBG_MAP_ALLOC HOOK_FUNCTION(_malloc_dbg, malloc_null); result = mallocAndStrcpy_s(&destString, srcString); UNHOOK_FUNCTION(_malloc_dbg, malloc_null); #else HOOK_FUNCTION(malloc, malloc_null); result = mallocAndStrcpy_s(&destString, srcString); UNHOOK_FUNCTION(malloc, malloc_null); #endif // assert ASSERT_ARE_EQUAL(int, ENOMEM, result); ASSERT_ARE_EQUAL(size_t,strlen(srcString)+1, mallocSize); } #endif /*Tests_SRS_CRT_ABSTRACTIONS_02_003: [If destination is NULL then unsignedIntToString shall fail.] */ TEST_FUNCTION(unsignedIntToString_fails_when_destination_is_NULL) { // arrange // act auto result = unsignedIntToString(NULL, 100, 43); // assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } /*Tests_SRS_CRT_ABSTRACTIONS_02_002: [If the conversion fails for any reason (for example, insufficient buffer space), a non-zero return value shall be supplied and unsignedIntToString shall fail.] */ TEST_FUNCTION(unsignedIntToString_fails_when_destination_is_not_sufficient_for_1_digit) { // arrange char destination[1000]; unsigned int toBeConverted = 1; size_t destinationSize = 1; ///act int result = unsignedIntToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } /*Tests_SRS_CRT_ABSTRACTIONS_02_002: [If the conversion fails for any reason (for example, insufficient buffer space), a non-zero return value shall be supplied and unsignedIntToString shall fail.] */ TEST_FUNCTION(unsignedIntToString_fails_when_destination_is_not_sufficient_for_more_than_1_digit) { // arrange char destination[1000]; unsigned int toBeConverted = 1; /*7 would not be a right starting digit*/ size_t destinationSize = 1; while (toBeConverted <= (UINT_MAX / 10)) { ///arrange destinationSize++; toBeConverted *= 10; ///act int result = unsignedIntToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [unsignedIntToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ TEST_FUNCTION(unsignedIntToString_succeeds_1_digit) { // arrange char destination[1000]; unsigned int toBeConverted = 2; size_t destinationSize = 2; ///act int result = unsignedIntToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_EQUAL(int, 0, result); ASSERT_ARE_EQUAL(char_ptr, "2", destination); } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [unsignedIntToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ /*Tests_SRS_CRT_ABSTRACTIONS_02_004: [If the conversion has been successfull then unsignedIntToString shall return 0.] */ TEST_FUNCTION(unsignedIntToString_succeeds_for_interesting_numbers) { // arrange char destination[1000]; size_t i; for (i = 0; i<sizeof(interestingUnsignedIntNumbersToBeConverted) / sizeof(interestingUnsignedIntNumbersToBeConverted[0]); i++) { ///act int result = unsignedIntToString(destination, 1000, interestingUnsignedIntNumbersToBeConverted[i]); ///assert ASSERT_ARE_EQUAL(int, 0, result); unsigned int valueFromString = 0; size_t pos = 0; while (destination[pos] != '\0') { if (valueFromString > (UINT_MAX / 10)) { ASSERT_FAIL("string produced was too big... "); } else { valueFromString *= 10; valueFromString += (destination[pos] - '0'); } pos++; } if (interestingUnsignedIntNumbersToBeConverted[i] != valueFromString) { ASSERT_FAIL("unexpected value"); } } } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [unsignedIntToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ /*Tests_SRS_CRT_ABSTRACTIONS_02_004: [If the conversion has been successfull then unsignedIntToString shall return 0.] */ TEST_FUNCTION(unsignedIntToString_succeeds_for_space_just_about_right) { // arrange char destination[1000]; unsigned int toBeConverted = 1; /*7 would not be a right starting digit*/ size_t destinationSize = 2; while (toBeConverted <= (UINT_MAX / 10)) { ///arrange destinationSize++; toBeConverted *= 10; ///act int result = unsignedIntToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_EQUAL(int, 0, result); unsigned int valueFromString = 0; size_t pos = 0; while (destination[pos] != '\0') { if (valueFromString > (UINT_MAX / 10)) { ASSERT_FAIL("string produced was too big... "); } else { valueFromString *= 10; valueFromString += (destination[pos] - '0'); } pos++; } if (toBeConverted != valueFromString) { ASSERT_FAIL("unexpected value"); } } } /*Tests_SRS_CRT_ABSTRACTIONS_02_007: [If destination is NULL then size_tToString shall fail.] */ TEST_FUNCTION(size_tToString_fails_when_destination_is_NULL) { // arrange // act auto result = size_tToString(NULL, 100, 43); // assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } /*Tests_SRS_CRT_ABSTRACTIONS_02_006: [If the conversion fails for any reason (for example, insufficient buffer space), a non-zero return value shall be supplied and size_tToString shall fail.] */ TEST_FUNCTION(size_tToString_fails_when_destination_is_not_sufficient_for_1_digit) { // arrange char destination[1000]; size_t toBeConverted = 1; size_t destinationSize = 1; ///act int result = size_tToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } /*Tests_SRS_CRT_ABSTRACTIONS_02_006: [If the conversion fails for any reason (for example, insufficient buffer space), a non-zero return value shall be supplied and size_tToString shall fail.] */ TEST_FUNCTION(size_tToString_fails_when_destination_is_not_sufficient_for_more_than_1_digit) { // arrange char destination[1000]; size_t toBeConverted = 1; /*7 would not be a right starting digit*/ size_t destinationSize = 1; while (toBeConverted <= (UINT_MAX / 10)) { ///arrange destinationSize++; toBeConverted *= 10; ///act int result = size_tToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_NOT_EQUAL(int, 0, result); } } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [size_tToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ TEST_FUNCTION(size_tToString_succeeds_1_digit) { // arrange char destination[1000]; size_t toBeConverted = 2; size_t destinationSize = 2; ///act int result = size_tToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_EQUAL(int, 0, result); ASSERT_ARE_EQUAL(char_ptr, "2", destination); } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [size_tToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ /*Tests_SRS_CRT_ABSTRACTIONS_02_004: [If the conversion has been successfull then size_tToString shall return 0.] */ TEST_FUNCTION(size_tToString_succeeds_for_interesting_numbers) { // arrange char destination[1000]; size_t i; for (i = 0; i<sizeof(interestingSize_tNumbersToBeConverted) / sizeof(interestingSize_tNumbersToBeConverted[0]); i++) { ///act int result = size_tToString(destination, 1000, interestingSize_tNumbersToBeConverted[i]); ///assert ASSERT_ARE_EQUAL(int, 0, result); size_t valueFromString = 0; size_t pos = 0; while (destination[pos] != '\0') { if (valueFromString > (SIZE_MAX / 10)) { ASSERT_FAIL("string produced was too big... "); } else { valueFromString *= 10; valueFromString += (destination[pos] - '0'); } pos++; } if (interestingSize_tNumbersToBeConverted[i] != valueFromString) { ASSERT_FAIL("unexpected value"); } } } /*Tests_SRS_CRT_ABSTRACTIONS_02_001: [size_tToString shall convert the parameter value to its decimal representation as a string in the buffer indicated by parameter destination having the size indicated by parameter destinationSize.] */ /*Tests_SRS_CRT_ABSTRACTIONS_02_004: [If the conversion has been successfull then size_tToString shall return 0.] */ TEST_FUNCTION(size_tToString_succeeds_for_space_just_about_right) { // arrange char destination[1000]; size_t toBeConverted = 1; /*7 would not be a right starting digit*/ size_t destinationSize = 2; while (toBeConverted <= (SIZE_MAX / 10)) { ///arrange destinationSize++; toBeConverted *= 10; ///act int result = size_tToString(destination, destinationSize, toBeConverted); ///assert ASSERT_ARE_EQUAL(int, 0, result); size_t valueFromString = 0; size_t pos = 0; while (destination[pos] != '\0') { if (valueFromString > (SIZE_MAX / 10)) { ASSERT_FAIL("string produced was too big... "); } else { valueFromString *= 10; valueFromString += (destination[pos] - '0'); } pos++; } if (toBeConverted != valueFromString) { ASSERT_FAIL("unexpected value"); } } } END_TEST_SUITE(CRTAbstractions_UnitTests)
36.789849
352
0.600557
josesimoes
5db03cd420da69738fbe3acbf8468ad87ef583ce
17,405
cpp
C++
xcore/crowd_app/leon/params/params.cpp
baidu-research/hydra-xeye
67d4464cff8f44f3a396a2c9aed46d0ce02f8de2
[ "Apache-2.0" ]
1
2021-09-01T00:50:34.000Z
2021-09-01T00:50:34.000Z
xcore/crowd_app/leon/params/params.cpp
baidu-research/hydra-xeye
67d4464cff8f44f3a396a2c9aed46d0ce02f8de2
[ "Apache-2.0" ]
null
null
null
xcore/crowd_app/leon/params/params.cpp
baidu-research/hydra-xeye
67d4464cff8f44f3a396a2c9aed46d0ce02f8de2
[ "Apache-2.0" ]
null
null
null
#include "params.hpp" #include <Log.h> #ifndef MVLOG_UNIT_NAME #define MVLOG_UNIT_NAME params #endif #include <mvLog.h> #include "utils/utils.hpp" char* Params::merge_conf_json(const char* conf_json) { cJSON* root = cJSON_Parse(conf_json); if (root == NULL) { LOGE << "invalid json string"; return NULL; } // merge xeye_id cJSON_ReplaceItemInObject(root, "xeye_id", cJSON_CreateString(m_xeye_id.c_str())); // merge confidence cJSON_ReplaceItemInObject(root, "confidence", cJSON_CreateNumber(m_confidence)); // merge sensor ccm index cJSON_ReplaceItemInObject(root, "sensor_ccm_index", cJSON_CreateNumber(m_sensor_ccm_index)); // merge data server url cJSON* data_server = cJSON_GetObjectItem(root, "data_server"); if (data_server != NULL) { cJSON_ReplaceItemInObject(data_server, "url", \ cJSON_CreateString(data_server_url().c_str())); } else { LOGE << "Can not merge data server url"; } // merge heartbeat server url cJSON* heartbeat_server = cJSON_GetObjectItem(root, "heartbeat_server"); if (heartbeat_server != NULL) { cJSON_ReplaceItemInObject(heartbeat_server, "url", \ cJSON_CreateString(heartbeat_server_url().c_str())); } else { LOGE << "Can not merge heartbeat server url"; } // merge local network info cJSON* local_network_info = cJSON_GetObjectItem(root, "local_network_info"); if (local_network_info != NULL) { cJSON_ReplaceItemInObject(local_network_info, "ip_address", \ cJSON_CreateString(local_ipaddr().c_str())); cJSON_ReplaceItemInObject(local_network_info, "net_mask", \ cJSON_CreateString(local_netmask().c_str())); cJSON_ReplaceItemInObject(local_network_info, "gate_way", \ cJSON_CreateString(local_gateway().c_str())); } else { LOGE << "Can not merge local network info"; } char* new_json = cJSON_Print(root); cJSON_Delete(root); return new_json; } bool Params::load_from_file(const std::string& filename) { // [NOTE]: before calling load_from_file function, // this callback function should be initialized first // or the xeye_id could not pass to LRT properly. assert(m_params_callback != nullptr); // try to figure out why the c++ way do not work. FILE *f = NULL; long len = 0; /* open in read binary mode */ f = fopen(filename.c_str(), "rb"); if (NULL == f) { LOGE << "Can not open file: " << filename; return false; } /* get the length */ fseek(f, 0, SEEK_END); len = ftell(f); fseek(f, 0, SEEK_SET); std::shared_ptr<char> data(new char[len + 1]); fread(data.get(), 1, len, f); data.get()[len] = '\0'; if (0 != fclose(f)) { // non fatal error, only apply logging LOGE << "close json file: " << filename << " FAILED"; } cJSON* root = cJSON_Parse(data.get()); if (nullptr == root) { LOGE << "Invalid cjson format maybe"; return false; } bool succeed = true; cJSON* psub_node = NULL; psub_node = cJSON_GetObjectItem(root, "xeye_id"); if (psub_node != NULL) { m_xeye_id = std::string(psub_node->valuestring); } else { succeed = false; LOGE << "no xeye_id nodes in config file"; } mvLog(MVLOG_INFO, "xeye_id: %s", m_xeye_id.c_str()); psub_node = cJSON_GetObjectItem(root, "confidence"); if (psub_node != NULL) { m_confidence = psub_node->valueint; } else { succeed = false; LOGE << "no confidence sub node in config file"; } mvLog(MVLOG_INFO, "Confidence: %d", m_confidence); psub_node = cJSON_GetObjectItem(root, "sensor_ccm_index"); if (psub_node != NULL) { m_sensor_ccm_index = psub_node->valueint; } else { succeed = false; LOGE << "No sensor_ccm_index nodes in config file"; } cJSON* running_mode = cJSON_GetObjectItem(root, "running_mode"); if (running_mode != NULL) { psub_node = cJSON_GetObjectItem(running_mode, "mode"); if (psub_node != NULL) { set_mode(std::string(psub_node->valuestring)); } else { succeed = false; LOGE << "No mode nodes in running_mode"; } mvLog(MVLOG_INFO, "Running mode: %s", get_mode_str().c_str()); } else { succeed = false; LOGE << "No running_mode nodes in config file"; } cJSON* online_grab = cJSON_GetObjectItem(root, "online_grab"); if (online_grab != NULL) { psub_node = cJSON_GetObjectItem(online_grab, "enable"); if (psub_node != NULL) { std::get<0>(m_online_img_grab) = (psub_node->valueint != 0); } else { succeed = false; LOGE << "No enable node in online_grab"; } psub_node = cJSON_GetObjectItem(online_grab, "strategy"); if (psub_node != NULL) { std::get<1>(m_online_img_grab) = std::string(psub_node->valuestring); if (online_image_grab_strategy() != "interval" && \ online_image_grab_strategy() != "ondemand") { std::get<0>(m_online_img_grab) = false; LOGE << "Invalid image grabbing strategy, this feature is forced to be disabled."; } else { psub_node = cJSON_GetObjectItem(online_grab, "value"); if (psub_node != NULL && psub_node->valueint > 0) { std::get<2>(m_online_img_grab) = psub_node->valueint; } else { // if value is not valie, still forced this feature to be disabled; std::get<0>(m_online_img_grab) = false; LOGE << "Invalid image grab value setting. value should be > 0"; } } } else { succeed = false; LOGE << "No strategy node in online_grab"; } mvLog(MVLOG_INFO, "online grab enable : %d", is_online_image_grab_enable()); mvLog(MVLOG_INFO, "online grab strategy: %s", online_image_grab_strategy().c_str()); mvLog(MVLOG_INFO, "online grab value : %d", online_image_flow_control_value()); } else { succeed = false; mvLog(MVLOG_ERROR, "No online_grab node in config file"); } cJSON* online_update = cJSON_GetObjectItem(root, "online_update"); if (online_update) { psub_node = cJSON_GetObjectItem(online_update, "host"); if (psub_node != NULL) { std::get<0>(m_online_update) = std::string(psub_node->valuestring); } psub_node = cJSON_GetObjectItem(online_update, "url_prefix"); if (psub_node != NULL) { std::get<1>(m_online_update) = std::string(psub_node->valuestring); } } if (!load_servers_config_from_json(root)) { succeed = false; } if (!load_models_config_from_json(root)) { succeed = false; } cJSON_Delete(root); // save the path of the conf file m_conf_filename = filename; // call the callback function if (m_params_callback) { m_params_callback(this); } return succeed; } bool Params::save_to_file(const std::string& filename) const { cJSON* root = NULL; root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "xeye_id", \ cJSON_CreateString(m_xeye_id.c_str())); cJSON_AddItemToObject(root, "confidence", \ cJSON_CreateNumber(get_confidence())); cJSON_AddItemToObject(root, "sensor_ccm_index", \ cJSON_CreateNumber(m_sensor_ccm_index)); cJSON* mode = cJSON_CreateObject(); cJSON_AddItemToObject(mode, "comment", \ cJSON_CreateString("running mode, can only be configured as record, normal, live mode")); cJSON_AddItemToObject(mode, "mode", cJSON_CreateString(get_mode_str().c_str())); cJSON_AddItemToObject(root, "running_mode", mode); // online grab image configuration cJSON* online_grab = cJSON_CreateObject(); cJSON_AddItemToObject(online_grab, "enable", cJSON_CreateBool(is_online_image_grab_enable())); cJSON_AddItemToObject(online_grab, "strategy", cJSON_CreateString(online_image_grab_strategy().c_str())); cJSON_AddItemToObject(online_grab, "value", cJSON_CreateNumber(online_image_flow_control_value())); cJSON_AddItemToObject(root, "online_grab", online_grab); // online update configuration cJSON* online_update = cJSON_CreateObject(); cJSON_AddItemToObject(online_update, "host", cJSON_CreateString(online_update_host().c_str())); cJSON_AddItemToObject(online_update, "url_prefix", cJSON_CreateString(online_update_url_prefix().c_str())); cJSON_AddItemToObject(root, "online_update", online_update); save_servers_config_to_json(root); // models configuration save_models_config_to_json(root); // must free out_str here, or will cause a memory leak char* out_str = cJSON_Print(root); std::ofstream of(filename, std::ofstream::binary); of.write(out_str, strlen(out_str)); of.close(); cJSON_Delete(root); free(out_str); return true; } bool Params::save_servers_config_to_json(cJSON* root) const { cJSON* data_server = NULL; cJSON* ntp_server = NULL; cJSON* heartbeat_server = NULL; cJSON* playback_server = NULL; cJSON* local_network_info = NULL; // data server cJSON_AddItemToObject(root, "data_server", \ data_server = cJSON_CreateObject()); cJSON_AddItemToObject(data_server, "comment", cJSON_CreateString( \ "the IP address and port of server which xeye send data to")); cJSON_AddItemToObject(data_server, "addr", \ cJSON_CreateString(data_server_addr().c_str())); cJSON_AddItemToObject(data_server, "port", \ cJSON_CreateNumber(data_server_port())); cJSON_AddItemToObject(data_server, "url", \ cJSON_CreateString(data_server_url().c_str())); // ntp server cJSON_AddItemToObject(root, "ntp_server", \ ntp_server = cJSON_CreateObject()); cJSON_AddItemToObject(ntp_server, "comment", cJSON_CreateString( \ "the IP address and port of NTP time syncronization server")); cJSON_AddItemToObject(ntp_server, "addr", \ cJSON_CreateString(ntp_server_addr().c_str())); cJSON_AddItemToObject(ntp_server, "port", \ cJSON_CreateNumber(ntp_server_port())); // heartbeat server cJSON_AddItemToObject(root, "heartbeat_server", \ heartbeat_server = cJSON_CreateObject()); cJSON_AddItemToObject(heartbeat_server, "comment", cJSON_CreateString( \ "the IP address and port of heartbeat server")); cJSON_AddItemToObject(heartbeat_server, "addr", \ cJSON_CreateString(heartbeat_server_addr().c_str())); cJSON_AddItemToObject(heartbeat_server, "port", \ cJSON_CreateNumber(heartbeat_server_port())); cJSON_AddItemToObject(heartbeat_server, "url", \ cJSON_CreateString(heartbeat_server_url().c_str())); // playback server cJSON_AddItemToObject(root, "playback_server", \ playback_server = cJSON_CreateObject()); cJSON_AddItemToObject(playback_server, "comment", cJSON_CreateString( \ "the IP address and port of playback server, \ if addr section is empty, then playback mode is disabled")); cJSON_AddItemToObject(playback_server, "addr", \ cJSON_CreateString(playback_server_addr().c_str())); cJSON_AddItemToObject(playback_server, "port", \ cJSON_CreateNumber(playback_server_port())); // local network info cJSON_AddItemToObject(root, "local_network_info", \ local_network_info = cJSON_CreateObject()); cJSON_AddItemToObject(local_network_info, "comment", cJSON_CreateString( \ "static ip address, netmask and gateway configuration")); cJSON_AddItemToObject(local_network_info, "ip_address", \ cJSON_CreateString(local_ipaddr().c_str())); cJSON_AddItemToObject(local_network_info, "net_mask", \ cJSON_CreateString(local_netmask().c_str())); cJSON_AddItemToObject(local_network_info, "gate_way", \ cJSON_CreateString(local_gateway().c_str())); return true; } bool Params::load_servers_config_from_json(const cJSON* root) { bool succeed = true; cJSON* data_server = cJSON_GetObjectItem(root, "data_server"); if (nullptr == data_server) { LOGE << "NO object named data_server in json file"; succeed = false; } else { m_data_server = std::make_tuple( \ std::string(cJSON_GetObjectItem(data_server, "addr")->valuestring), \ cJSON_GetObjectItem(data_server, "port")->valueint, \ cJSON_GetObjectItem(data_server, "url")->valuestring); } cJSON* ntp_server = cJSON_GetObjectItem(root, "ntp_server"); if (nullptr == ntp_server) { LOGE << "NO object named ntp_server in json file"; succeed = false; } else { m_ntp_server = std::make_pair( \ std::string(cJSON_GetObjectItem(ntp_server, "addr")->valuestring), \ cJSON_GetObjectItem(ntp_server, "port")->valueint); } cJSON* hb_server = cJSON_GetObjectItem(root, "heartbeat_server"); if (nullptr == hb_server) { LOGE << "NO object named heartbeat_server in json file"; succeed = false; } else { m_hb_server = std::make_tuple( \ std::string(cJSON_GetObjectItem(hb_server, "addr")->valuestring), \ cJSON_GetObjectItem(hb_server, "port")->valueint, \ std::string(cJSON_GetObjectItem(hb_server, "url")->valuestring)); } cJSON* local_network_info = cJSON_GetObjectItem(root, "local_network_info"); if (nullptr == local_network_info) { LOGE << "NO object named local_network_info in json file"; succeed = false; } else { m_local_address = std::make_tuple( \ std::string(cJSON_GetObjectItem(local_network_info, "ip_address")->valuestring), \ std::string(cJSON_GetObjectItem(local_network_info, "net_mask")->valuestring), \ std::string(cJSON_GetObjectItem(local_network_info, "gate_way")->valuestring)); } cJSON* playback_server = cJSON_GetObjectItem(root, "playback_server"); if (nullptr == playback_server) { LOGE << "NO object named playback_server in json file"; succeed = false; } else { m_playback_server = std::make_pair( \ std::string(cJSON_GetObjectItem(playback_server, "addr")->valuestring), \ cJSON_GetObjectItem(playback_server, "port")->valueint); } mvLog(MVLOG_INFO, "data_server:(%s, %d, %s)", data_server_addr().c_str(), \ data_server_port(), data_server_url().c_str()); mvLog(MVLOG_INFO, "playback_server:(%s, %d)", playback_server_addr().c_str(), \ playback_server_port()); mvLog(MVLOG_INFO, "ntp_server:(%s, %d)", ntp_server_addr().c_str(), \ ntp_server_port()); mvLog(MVLOG_INFO, "heartbeat_server:(%s, %d, %s)", heartbeat_server_addr().c_str(), \ heartbeat_server_port(), heartbeat_server_url().c_str()); if (std::get<0>(m_local_address) == "") { mvLog(MVLOG_INFO, "Use DHCP server"); } else { mvLog(MVLOG_INFO, "Static ip address: %s, netmask: %s, gateway: %s", \ std::get<0>(m_local_address).c_str(), \ std::get<1>(m_local_address).c_str(), \ std::get<2>(m_local_address).c_str()); } return succeed; } bool Params::save_models_config_to_json(cJSON* root) const { assert(root != NULL); cJSON* models = NULL; // support unlimited models cJSON_AddItemToObject(root, "models", models = cJSON_CreateArray()); for (size_t i = 0; i < m_models.size(); ++i) { cJSON* item = cJSON_CreateObject(); cJSON_AddItemToObject(item, "comment", \ cJSON_CreateString("model_name: the name of the model, \ model_path: the abs path of the model file")); cJSON_AddItemToObject(item, "model_name", \ cJSON_CreateString(m_models[i].first.c_str())); cJSON_AddItemToObject(item, "model_path", \ cJSON_CreateString(m_models[i].second.c_str())); cJSON_AddItemToArray(models, item); } return true; } bool Params::load_models_config_from_json(cJSON* root) { assert(root != NULL); cJSON* models = cJSON_GetObjectItem(root, "models"); if (models == nullptr) { return false; } int models_number = cJSON_GetArraySize(models); if (models_number <= 0) { mvLog(MVLOG_ERROR, "No models defined in conf.json"); return false; } for (int i = 0; i < models_number; ++i) { cJSON* model = cJSON_GetArrayItem(models, i); if (model == nullptr) { LOGE << "No model nodes in models"; return false; } m_models.push_back(std::make_pair( \ cJSON_GetObjectItem(model, "model_name")->valuestring, cJSON_GetObjectItem(model, "model_path")->valuestring)); mvLog(MVLOG_INFO, "model_name: %s, model_path: %s", \ m_models[i].first.c_str(), m_models[i].second.c_str()); } return (m_models.size() > 0); }
40.382831
111
0.637863
baidu-research
5db18a3a6b19a7799cfc90c49021f84d6f461dad
255
cpp
C++
problem/01000~09999/01110/1110.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
1
2019-04-19T16:37:44.000Z
2019-04-19T16:37:44.000Z
problem/01000~09999/01110/1110.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
1
2019-04-20T11:42:44.000Z
2019-04-20T11:42:44.000Z
problem/01000~09999/01110/1110.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
3
2019-04-19T16:37:47.000Z
2021-10-25T00:45:00.000Z
#include <iostream> using namespace std; int main(){ int N, val1, val2, count=0; cin >> N; int val3 = N; do{ val1 = val3%10; val2 = (val3/10+val1)%10; val3 = val1*10+val2; count++; }while(val3!=N); cout << count; return 0; }
15.9375
29
0.556863
njw1204
5db210271b7fdf2ef1417d204ad6eba497f79670
1,076
cpp
C++
codeforces/1254a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1254a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1254a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; char c[62]; int cnt[62]; // zig-zag void solve() { int n,m,k; cin >> n >> m >> k; int rice = 0; vector<string> s(n); for (int i = 0; i < n; i++) { cin >> s[i]; if (i&1) reverse(s[i].begin(), s[i].end()); for (char x: s[i]) if (x == 'R') rice++; } int avg = rice/k, rem = rice%k; for (int i = 0; i < k; i++) { cnt[i] = avg + (i<rem); } int x = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == 'R') { cnt[x]--; } s[i][j] = c[x]; if (cnt[x] == 0 && x+1 < k) x++; } if (i&1) reverse(s[i].begin(), s[i].end()); cout << s[i] << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); for (int i = 0; i < 26; i++) { c[i] = 'a'+i; c[i+26] = 'A'+i; } for (int i = 0; i < 10; i++) { c[i+52] = '0'+i; } int t; cin >> t; while(t--)solve(); cout << endl; }
20.692308
51
0.362454
sogapalag
5db2b7388dc246fb34f34b19ffc9d5ba3637ac36
2,756
cpp
C++
ModelViewer/ScalePage.cpp
scharlton2/modelviewer-mf6
87f3e5daad747e5d81d48b19a8cdc4377df4effb
[ "CC0-1.0" ]
1
2022-03-29T15:10:14.000Z
2022-03-29T15:10:14.000Z
ModelViewer/ScalePage.cpp
scharlton2/modelviewer-mf6
87f3e5daad747e5d81d48b19a8cdc4377df4effb
[ "CC0-1.0" ]
17
2022-01-12T19:58:41.000Z
2022-03-28T22:45:56.000Z
ModelViewer/ScalePage.cpp
scharlton2/modelviewer-mf6
87f3e5daad747e5d81d48b19a8cdc4377df4effb
[ "CC0-1.0" ]
3
2022-01-09T06:17:53.000Z
2022-03-31T21:50:06.000Z
// ScalePage.cpp : implementation file // #include "ModelViewer.h" #include "ScalePage.h" #include "MvDoc.h" #include "GeometryDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CScalePage property page IMPLEMENT_DYNCREATE(CScalePage, CPropertyPage) CScalePage::CScalePage() : CPropertyPage(CScalePage::IDD) { //{{AFX_DATA_INIT(CScalePage) m_XScale = 0.0; m_YScale = 0.0; m_ZScale = 0.0; //}}AFX_DATA_INIT } CScalePage::~CScalePage() { } void CScalePage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CScalePage) DDX_Text(pDX, IDC_XSCALE, m_XScale); DDX_Text(pDX, IDC_YSCALE, m_YScale); DDX_Text(pDX, IDC_ZSCALE, m_ZScale); //}}AFX_DATA_MAP pDX->PrepareEditCtrl(IDC_XSCALE); if (pDX->m_bSaveAndValidate) { if (m_XScale <= 0) { AfxMessageBox("Please enter a positive number.", MB_ICONEXCLAMATION); pDX->Fail(); } } pDX->PrepareEditCtrl(IDC_YSCALE); if (pDX->m_bSaveAndValidate) { if (m_YScale <= 0) { AfxMessageBox("Please enter a positive number.", MB_ICONEXCLAMATION); pDX->Fail(); } } pDX->PrepareEditCtrl(IDC_ZSCALE); if (pDX->m_bSaveAndValidate) { if (m_ZScale <= 0) { AfxMessageBox("Please enter a positive number.", MB_ICONEXCLAMATION); pDX->Fail(); } } } BEGIN_MESSAGE_MAP(CScalePage, CPropertyPage) //{{AFX_MSG_MAP(CScalePage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CScalePage message handlers BOOL CScalePage::OnInitDialog() { CPropertyPage::OnInitDialog(); Reinitialize(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CScalePage::Reinitialize() { m_XScale = 1.0; m_YScale = 1.0; m_ZScale = 1.0; UpdateData(FALSE); Activate(FALSE); } void CScalePage::Activate(BOOL b) { GetDlgItem(IDC_XSCALE)->EnableWindow(b); GetDlgItem(IDC_YSCALE)->EnableWindow(b); GetDlgItem(IDC_ZSCALE)->EnableWindow(b); m_IsActive = b; if (m_Parent->m_PropertySheet->GetActiveIndex() == 0) { m_Parent->m_ApplyButton.EnableWindow(b); } } void CScalePage::Apply() { if (UpdateData(TRUE)) { m_pDoc->SetScale(m_XScale, m_YScale, m_ZScale); } } BOOL CScalePage::OnSetActive() { m_Parent->m_ApplyButton.EnableWindow(m_IsActive); return CPropertyPage::OnSetActive(); }
22.225806
81
0.607765
scharlton2
5db2c6544db63edb6f90ac06ac4cdcc4bd2e6add
2,796
cpp
C++
src/vm/systemCalls.optionals.cpp
DosWorld/tmbasic
99bd593bb074df6af83d952259b5eb81588f1e3f
[ "MIT" ]
1
2022-01-29T05:45:46.000Z
2022-01-29T05:45:46.000Z
src/vm/systemCalls.optionals.cpp
DosWorld/tmbasic
99bd593bb074df6af83d952259b5eb81588f1e3f
[ "MIT" ]
null
null
null
src/vm/systemCalls.optionals.cpp
DosWorld/tmbasic
99bd593bb074df6af83d952259b5eb81588f1e3f
[ "MIT" ]
null
null
null
#include "systemCall.h" #include "Error.h" #include "Optional.h" namespace vm { static std::pair<const ValueOptional*, const ObjectOptional*> valueOrObjectOptional(const Object& object) { const auto* valueOptional = dynamic_cast<const ValueOptional*>(&object); if (valueOptional != nullptr) { return { valueOptional, nullptr }; } const auto* objectOptional = dynamic_cast<const ObjectOptional*>(&object); if (objectOptional != nullptr) { return { nullptr, objectOptional }; } throw Error( ErrorCode::kInternalTypeConfusion, fmt::format( "Internal type confusion error. Target is neither {} nor {}.", NAMEOF_TYPE(ValueOptional), NAMEOF_TYPE(ObjectOptional))); } void initSystemCallsOptionals() { initSystemCall(SystemCall::kHasValue, [](const auto& input, auto* result) { const auto valueOrObject = valueOrObjectOptional(input.getObject(-1)); const auto* valueOptional = valueOrObject.first; const auto* objectOptional = valueOrObject.second; result->returnedValue.setBoolean( valueOptional != nullptr ? valueOptional->item.has_value() : objectOptional->item.has_value()); }); initSystemCall(SystemCall::kObjectOptionalNewMissing, [](const auto& /*input*/, auto* result) { result->returnedObject = boost::make_local_shared<ObjectOptional>(); }); initSystemCall(SystemCall::kObjectOptionalNewPresent, [](const auto& input, auto* result) { result->returnedObject = boost::make_local_shared<ObjectOptional>(input.getObjectPtr(-1)); }); initSystemCall(SystemCall::kValueOptionalNewMissing, [](const auto& /*input*/, auto* result) { result->returnedObject = boost::make_local_shared<ValueOptional>(); }); initSystemCall(SystemCall::kValueOptionalNewPresent, [](const auto& input, auto* result) { result->returnedObject = boost::make_local_shared<ValueOptional>(input.getValue(-1)); }); initSystemCall(SystemCall::kValue, [](const auto& input, auto* result) { const auto valueOrObject = valueOrObjectOptional(input.getObject(-1)); const auto* valueOptional = valueOrObject.first; const auto* objectOptional = valueOrObject.second; if (valueOptional != nullptr) { if (!valueOptional->item.has_value()) { throw Error(ErrorCode::kValueNotPresent, "Optional value is not present."); } result->returnedValue = *valueOptional->item; } else { if (!objectOptional->item.has_value()) { throw Error(ErrorCode::kValueNotPresent, "Optional value is not present."); } result->returnedObject = *objectOptional->item; } }); } } // namespace vm
39.380282
107
0.664521
DosWorld
5db4dcaa97c8e90d29947b66e5a3ddc51388d606
7,673
hpp
C++
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
1
2020-12-27T04:08:49.000Z
2020-12-27T04:08:49.000Z
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
null
null
null
contrib/native/client/src/clientlib/streamSocket.hpp
akumarb2010/incubator-drill
a690b97074376a65ac0c1d86ee2a9fa32e997003
[ "Apache-2.0" ]
2
2019-11-12T09:21:02.000Z
2019-12-16T09:51:25.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STREAMSOCKET_HPP #define STREAMSOCKET_HPP #include "logger.hpp" #include "wincert.ipp" #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> namespace Drill { typedef boost::asio::ip::tcp::socket::lowest_layer_type streamSocket_t; typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslTCPSocket_t; typedef boost::asio::ip::tcp::socket basicTCPSocket_t; // Some helper typedefs to define the highly templatized boost::asio methods typedef boost::asio::const_buffers_1 ConstBufferSequence; typedef boost::asio::mutable_buffers_1 MutableBufferSequence; // ReadHandlers have different possible signatures. // // As a standard C-type callback // typedef void (*ReadHandler)(const boost::system::error_code& ec, std::size_t bytes_transferred); // // Or as a C++ functor // struct ReadHandler { // virtual void operator()( // const boost::system::error_code& ec, // std::size_t bytes_transferred) = 0; //}; // // We need a different signature though, since we need to pass in a member function of a drill client // class (which is C++), as a functor generated by boost::bind as a ReadHandler // typedef boost::function<void (const boost::system::error_code& ec, std::size_t bytes_transferred) > ReadHandler; class AsioStreamSocket{ public: virtual ~AsioStreamSocket(){}; virtual streamSocket_t& getInnerSocket() = 0; virtual std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec) = 0; virtual std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec) = 0; // // boost::asio::async_read has the signature // template< // typename AsyncReadStream, // typename MutableBufferSequence, // typename ReadHandler> // void-or-deduced async_read( // AsyncReadStream & s, // const MutableBufferSequence & buffers, // ReadHandler handler); // // For our use case, the derived class will have an instance of a concrete type for AsyncReadStream which // will implement the requirements for the AsyncReadStream type. We need not pass that in as a parameter // since the class already has the value // The method is templatized since the ReadHandler type is dependent on the class implementing the read // handler (basically the class using the asio stream) // virtual void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler) = 0; // call the underlying protocol's handshake method. // if the useSystemConfig flag is true, then use properties read // from the underlying operating system virtual void protocolHandshake(bool useSystemConfig) = 0; virtual void protocolClose() = 0; }; class Socket: public AsioStreamSocket, public basicTCPSocket_t{ public: Socket(boost::asio::io_service& ioService) : basicTCPSocket_t(ioService) { } ~Socket(){ boost::system::error_code ignorederr; this->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr); this->close(); }; basicTCPSocket_t& getSocketStream(){ return *this;} streamSocket_t& getInnerSocket(){ return this->lowest_layer();} std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec){ return this->write_some(buffers, ec); } std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec){ return this->read_some(buffers, ec); } void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){ return async_read(*this, buffers, handler); } void protocolHandshake(bool useSystemConfig){}; //nothing to do void protocolClose(){ // shuts down the socket! boost::system::error_code ignorederr; ((basicTCPSocket_t*)this)->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr ); } }; #if defined(IS_SSL_ENABLED) class SslSocket: public AsioStreamSocket, public sslTCPSocket_t{ public: SslSocket(boost::asio::io_service& ioService, boost::asio::ssl::context &sslContext) : sslTCPSocket_t(ioService, sslContext) { } ~SslSocket(){ this->lowest_layer().close(); }; sslTCPSocket_t& getSocketStream(){ return *this;} streamSocket_t& getInnerSocket(){ return this->lowest_layer();} std::size_t writeSome( const ConstBufferSequence& buffers, boost::system::error_code & ec){ return this->write_some(buffers, ec); } std::size_t readSome( const MutableBufferSequence& buffers, boost::system::error_code & ec){ return this->read_some(buffers, ec); } void asyncRead( const MutableBufferSequence & buffers, ReadHandler handler){ return async_read(*this, buffers, handler); } // // public method that can be invoked by callers to invoke the ssl handshake // throws: boost::system::system_error void protocolHandshake(bool useSystemConfig){ if(useSystemConfig){ std::string msg = ""; int ret = loadSystemTrustStore(this->native_handle(), msg); if(!msg.empty()){ DRILL_LOG(LOG_WARNING) << msg.c_str() << std::endl; } if(ret){ boost::system::error_code ec(EPROTO, boost::system::system_category()); boost::asio::detail::throw_error(ec, msg.c_str()); } } this->handshake(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::client); return; }; // // public method that can be invoked by callers to invoke a clean ssl shutdown // throws: boost::system::system_error void protocolClose(){ try{ this->shutdown(); }catch(boost::system::system_error e){ //swallow the exception. The channel is unusable anyway } // shuts down the socket! boost::system::error_code ignorederr; this->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignorederr ); return; }; }; #endif } // namespace Drill #endif //STREAMSOCKET_HPP
35.03653
114
0.619314
akumarb2010
5db85986044fcfd4415bf089cdc1a101c59bbf90
12,638
hpp
C++
src/bpsw.hpp
NewYaroslav/xalgorithms
ffb9abc6107bed496382b053f333c40fab61a700
[ "MIT" ]
null
null
null
src/bpsw.hpp
NewYaroslav/xalgorithms
ffb9abc6107bed496382b053f333c40fab61a700
[ "MIT" ]
null
null
null
src/bpsw.hpp
NewYaroslav/xalgorithms
ffb9abc6107bed496382b053f333c40fab61a700
[ "MIT" ]
null
null
null
/* Тест BPSW на простоту чисел Источник: http://e-maxx.ru/algo/bpsw */ #ifndef XA_BPSW_HPP_INCLUDED #define XA_BPSW_HPP_INCLUDED #include <algorithm> #include <cmath> #include <map> #include <vector> namespace xaBPSW { //! Модуль 64-битного числа long long abs (long long n) { return n < 0 ? -n : n; } unsigned long long abs (unsigned long long n) { return n; } //! Возвращает true, если n четное template <class T> bool even (const T & n) { // return n % 2 == 0; return (n & 1) == 0; } //! Делит число на 2 template <class T> void bisect (T & n) { // n /= 2; n >>= 1; } //! Умножает число на 2 template <class T> void redouble (T & n) { // n *= 2; n <<= 1; } //! Возвращает true, если n - точный квадрат простого числа template <class T> bool perfect_square (const T & n) { T sq = (T) ceil (sqrt ((double)n)); return sq*sq == n; } //! Вычисляет корень из числа, округляя его вниз template <class T> T sq_root (const T & n) { return (T) floor (sqrt ((double) n)); } //! Возвращает количество бит в числе (т.е. минимальное количество бит, которыми можно представить данное число) template <class T> unsigned bits_in_number (T n) { if (n == 0) return 1; unsigned result = 0; while (n) { bisect (n); ++result; } return result; } //! Возвращает значение k-го бита числа (биты нумеруются с нуля) template <class T> bool test_bit (const T & n, unsigned k) { return (n & (T(1) << k)) != 0; } //! Умножает a *= b (mod n) template <class T> void mulmod (T & a, T b, const T & n) { // наивная версия, годится только для длинной арифметики a *= b; a %= n; } template <> void mulmod (int & a, int b, const int & n) { a = int( (((long long)a) * b) % n ); } template <> void mulmod (unsigned & a, unsigned b, const unsigned & n) { a = unsigned( (((unsigned long long)a) * b) % n ); } template <> void mulmod (unsigned long long & a, unsigned long long b, const unsigned long long & n) { // сложная версия, основанная на бинарном разложении произведения в сумму if (a >= n) a %= n; if (b >= n) b %= n; unsigned long long res = 0; while (b) if (!even (b)) { res += a; while (res >= n) res -= n; --b; } else { redouble (a); while (a >= n) a -= n; bisect (b); } a = res; } template <> void mulmod (long long & a, long long b, const long long & n) { bool neg = false; if (a < 0) { neg = !neg; a = -a; } if (b < 0) { neg = !neg; b = -b; } unsigned long long aa = a; mulmod<unsigned long long> (aa, (unsigned long long)b, (unsigned long long)n); a = (long long)aa * (neg ? -1 : 1); } //! Вычисляет a^k (mod n). Использует бинарное возведение в степень template <class T, class T2> T powmod (T a, T2 k, const T & n) { T res = 1; while (k) if (!even (k)) { mulmod (res, a, n); --k; } else { mulmod (a, a, n); bisect (k); } return res; } //! Переводит число n в форму q*2^p template <class T> void transform_num (T n, T & p, T & q) { T p_res = 0; while (even (n)) { ++p_res; bisect (n); } p = p_res; q = n; } //! Алгоритм Евклида template <class T, class T2> T gcd (const T & a, const T2 & b) { return (a == 0) ? b : gcd (b % a, a); } //! Вычисляет jacobi(a,b) template <class T> T jacobi (T a, T b) { //#pragma warning (push) //#pragma warning (disable: 4146) if (a == 0) return 0; if (a == 1) return 1; if (a < 0) if ((b & 2) == 0) return jacobi (-a, b); else return - jacobi (-a, b); T e, a1; transform_num (a, e, a1); T s; if (even (e) || (b & 7) == 1 || (b & 7) == 7) s = 1; else s = -1; if ((b & 3) == 3 && (a1 & 3) == 3) s = -s; if (a1 == 1) return s; return s * jacobi (b % a1, a1); //#pragma warning (pop) } //! Вычисляет pi(b) первых простых чисел. Возвращает ссылку на вектор с простыми (в векторе может оказаться больше простых, чем надо) и в pi - pi(b) template <class T, class T2> const std::vector<T> & get_primes (const T & b, T2 & pi) { static std::vector<T> primes; static T counted_b; // если результат уже был вычислен ранее, возвращаем его, иначе довычисляем простые if (counted_b >= b) pi = T2 (std::upper_bound (primes.begin(), primes.end(), b) - primes.begin()); else { // число 2 обрабатываем отдельно if (counted_b == 0) { primes.push_back (2); counted_b = 2; } // теперь обрабатываем все нечётные, пока не наберём нужное количество простых T first = counted_b == 2 ? 3 : primes.back()+2; for (T cur=first; cur<=b; ++++cur) { bool cur_is_prime = true; for (typename std::vector<T>::const_iterator iter = primes.begin(), end = primes.end(); iter != end; ++iter) { const T & div = *iter; if (div * div > cur) break; if (cur % div == 0) { cur_is_prime = false; break; } } if (cur_is_prime) primes.push_back (cur); } counted_b = b; pi = (T2) primes.size(); } return primes; } //! Тривиальная проверка n на простоту, перебираются все делители до m. Результат: 1 - если n точно простое, p - его найденный делитель, 0 - если неизвестно, является ли n простым или нет template <class T, class T2> T2 prime_div_trivial (const T & n, T2 m) { // сначала проверяем тривиальные случаи if (n == 2 || n == 3) return 1; if (n < 2) return 0; if (even (n)) return 2; // генерируем простые от 3 до m T2 pi; const std::vector<T2> & primes = get_primes (m, pi); // делим на все простые for (typename std::vector<T2>::const_iterator iter=primes.begin(), end=primes.end(); iter!=end && *iter <= m; ++iter) { const T2 & div = *iter; if (div * div > n) break; else if (n % div == 0) return div; } if (n < m*m) return 1; return 0; } //! Усиленный алгоритм Миллера-Рабина проверки n на простоту по основанию b template <class T, class T2> bool miller_rabin (T n, T2 b) { // сначала проверяем тривиальные случаи if (n == 2) return true; if (n < 2 || even (n)) return false; // проверяем, что n и b взаимно просты (иначе это приведет к ошибке) // если они не взаимно просты, то либо n не просто, либо нужно увеличить b if (b < 2) b = 2; for (T g; (g = gcd (n, b)) != 1; ++b) if (n > g) return false; // разлагаем n-1 = q*2^p T n_1 = n; --n_1; T p, q; transform_num (n_1, p, q); // вычисляем b^q mod n, если оно равно 1 или n-1, то n, вероятно, простое T rem = powmod (T(b), q, n); if (rem == 1 || rem == n_1) return true; // теперь вычисляем b^2q, b^4q, ... , b^((n-1)/2) // если какое-либо из них равно n-1, то n, вероятно, простое for (T i=1; i<p; i++) { mulmod (rem, rem, n); if (rem == n_1) return true; } return false; } //! Усиленный алгоритм Лукаса-Селфриджа проверки n на простоту. Используется усиленный алгоритм Лукаса с параметрами Селфриджа. Работает только с знаковыми типами!!! Второй параметр unused не используется, он только дает тип template <class T, class T2> bool lucas_selfridge (const T & n, T2 unused) { // сначала проверяем тривиальные случаи if (n == 2) return true; if (n < 2 || even (n)) return false; // проверяем, что n не является точным квадратом, иначе алгоритм даст ошибку if (perfect_square (n)) return false; // алгоритм Селфриджа: находим первое число d такое, что: // jacobi(d,n)=-1 и оно принадлежит ряду { 5,-7,9,-11,13,... } T2 dd; for (T2 d_abs = 5, d_sign = 1; ; d_sign = -d_sign, ++++d_abs) { dd = d_abs * d_sign; T g = gcd (n, d_abs); if (1 < g && g < n) // нашли делитель - d_abs return false; if (jacobi (T(dd), n) == -1) break; } // параметры Селфриджа T2 p = 1, q = (p*p - dd) / 4; // разлагаем n+1 = d*2^s T n_1 = n; ++n_1; T s, d; transform_num (n_1, s, d); // алгоритм Лукаса T u = 1, v = p, u2m = 1, v2m = p, qm = q, qm2 = q*2, qkd = q; for (unsigned bit = 1, bits = bits_in_number(d); bit < bits; bit++) { mulmod (u2m, v2m, n); mulmod (v2m, v2m, n); while (v2m < qm2) v2m += n; v2m -= qm2; mulmod (qm, qm, n); qm2 = qm; redouble (qm2); if (test_bit (d, bit)) { T t1, t2; t1 = u2m; mulmod (t1, v, n); t2 = v2m; mulmod (t2, u, n); T t3, t4; t3 = v2m; mulmod (t3, v, n); t4 = u2m; mulmod (t4, u, n); mulmod (t4, (T)dd, n); u = t1 + t2; if (!even (u)) u += n; bisect (u); u %= n; v = t3 + t4; if (!even (v)) v += n; bisect (v); v %= n; mulmod (qkd, qm, n); } } // точно простое (или псевдо-простое) if (u == 0 || v == 0) return true; // вычисляем оставшиеся члены T qkd2 = qkd; redouble (qkd2); for (T2 r = 1; r < s; ++r) { mulmod (v, v, n); v -= qkd2; if (v < 0) v += n; if (v < 0) v += n; if (v >= n) v -= n; if (v >= n) v -= n; if (v == 0) return true; if (r < s-1) { mulmod (qkd, qkd, n); qkd2 = qkd; redouble (qkd2); } } return false; } //! Алгоритм Бэйли-Померанс-Селфридж-Вагстафф (BPSW) проверки n на простоту template <class T> bool baillie_pomerance_selfridge_wagstaff (T n) { // перебираем тривиальные делители до 1000 int div = prime_div_trivial (n, 1000); if (div == 1) return true; if (div > 1) return false; // тест Миллера-Рабина по основанию 2 if (!miller_rabin (n, 2)) return false; // усиленный тест Лукаса-Селфриджа return lucas_selfridge (n, 0); } //! Алгоритм Бэйли-Померанс-Селфридж-Вагстафф (BPSW) проверки n на простоту template <class T> bool isprime (T n) { return baillie_pomerance_selfridge_wagstaff (n); } } #endif // BPSW_HPP_INCLUDED
26.219917
228
0.438835
NewYaroslav
5db9340d42d094ca8265a0f50a983b31c8c05d7a
3,392
cpp
C++
patrace/src/common/memory.cpp
ricardoquesada/patrace
c55c2817433ab2301733101d64206abb8687d371
[ "MIT" ]
1
2019-10-13T16:57:52.000Z
2019-10-13T16:57:52.000Z
patrace/src/common/memory.cpp
xiangruipuzhao/patrace
db444184177277b23e1de93fd320493628aae850
[ "MIT" ]
null
null
null
patrace/src/common/memory.cpp
xiangruipuzhao/patrace
db444184177277b23e1de93fd320493628aae850
[ "MIT" ]
1
2021-04-15T17:34:35.000Z
2021-04-15T17:34:35.000Z
#include "memory.hpp" #include "os.hpp" #include <cstdio> #include <cassert> namespace common { void PrintMemory(const void *mem, size_t len) { printf("\nMEMORY PRINT BEGIN : %d >>>>>>>>>>>> {\n", (int)len); const unsigned char *begin = (const unsigned char*)mem; for (size_t i = 0; i < len; ++i) { printf("0x%X ", *(begin++)); if ((i+1) % 8 == 0) printf("\n"); } printf("\nMEMORY PRINT END : %d <<<<<<<<<<<<< }\n", (int)len); } bool ClientSideBufferObject::overlap(const void *p, ptrdiff_t s) const { return (PTR_DIFF(p, base_address) < size) && (PTR_DIFF(base_address, p) < s); } const MD5Digest ClientSideBufferObject::md5_digest() const { if (_dirty_md5_digest) { calculate_md5_digest(); } return _md5_digest; } void ClientSideBufferObject::calculate_md5_digest() const { _md5_digest = MD5Digest(base_address, size); _dirty_md5_digest = false; } void * ClientSideBufferObject::extend(const void *p, ptrdiff_t s) { const void *new_base_address = PTR_DIFF(base_address, p) > (ptrdiff_t)(0) ? p : base_address; const ptrdiff_t size1 = PTR_DIFF(PTR_MOVE(p, s), new_base_address); const ptrdiff_t size2 = PTR_DIFF(PTR_MOVE(base_address, size), new_base_address); base_address = const_cast<void*>(new_base_address); size = size1 > size2 ? size1 : size2; return base_address; } VertexAttributeMemoryMerger::VertexAttributeMemoryMerger() { } VertexAttributeMemoryMerger::~VertexAttributeMemoryMerger() { for (unsigned int i = 0; i < _memory_ranges.size(); ++i) { delete _memory_ranges[i]; } _memory_ranges.clear(); for (unsigned int i = 0; i < _attributes.size(); ++i) { delete _attributes[i]; } _attributes.clear(); } void VertexAttributeMemoryMerger::add_attribute( unsigned int index, const void * ptr, ptrdiff_t data_size, int size, unsigned int type, bool normalized, size_t stride) { #if 0 DBG_LOG("VertexAttributeMemoryMerger::add_attribute()\n"); DBG_LOG(" index=%d\n", index); DBG_LOG(" ptr=%p\n", ptr); DBG_LOG(" data_size=%d\n", data_size); DBG_LOG(" size=%d\n", size); DBG_LOG(" type=%d\n", type); DBG_LOG(" normalized=%s\n", normalized?"true":"false"); DBG_LOG(" stride=%d\n", stride); #endif // Loop over available memory blocks, checking for interleaved attributes for (unsigned int i = 0; i < _memory_ranges.size(); ++i) { if (_memory_ranges[i]->overlap(ptr, data_size)) { const void * orig_base_address = _memory_ranges[i]->base_address; const void * new_base_address = _memory_ranges[i]->extend(ptr, data_size); for (unsigned int j = 0; j < _attributes.size(); ++j) { if (_attributes[j]->base_address == orig_base_address) _attributes[j]->update(new_base_address); } _attributes.push_back(new AttributeInfo(index, new_base_address, PTR_DIFF(ptr, new_base_address), size, type, normalized, stride)); return; } } _memory_ranges.push_back(new ClientSideBufferObject(ptr, data_size)); _attributes.push_back(new AttributeInfo(index, ptr, 0, size, type, normalized, stride)); } } // namespace common
28.745763
143
0.623231
ricardoquesada
5dbad53a80bd6f0cecb0edce527bdf09c0216a96
29,959
cxx
C++
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
Hekateros/sw/apps/hek_stalemate/SMCalib.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Package: Hekateros // // Program: StaleMate // // File: SMCalib.cxx // /*! \file * * $LastChangedDate: 2012-06-05 15:17:26 -0600 (Tue, 05 Jun 2012) $ * $Rev: 2028 $ * * \brief StaleMate calibration. * * \author Robin Knight (robin.knight@roadnarrows.com) * \author Daniel Packard (daniel@roadnarrows.com) * * \copyright * \h_copy 2011-2017. RoadNarrows LLC.\n * http://www.roadnarrows.com\n * All Rights Reserved */ // Unless otherwise noted, all materials contained are copyrighted and may not // be used except as provided in these terms and conditions or in the copyright // notice (documents and software ) or other proprietary notice provided with // the relevant materials. // // // IN NO EVENT SHALL THE AUTHOR, ROADNARROWS, OR ANY MEMBERS/EMPLOYEES/ // CONTRACTORS OF ROADNARROWS OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY // PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, // EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE AUTHORS AND ROADNARROWS SPECIFICALLY DISCLAIM ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN // "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO // PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. // //////////////////////////////////////////////////////////////////////////////// #include <sys/types.h> #include <stdarg.h> #include <libgen.h> #include <cstring> #include <iostream> #include <fstream> #include <cmath> #include "rnr/rnrconfig.h" #include "rnr/log.h" #include "rnr/rnrWin.h" #include "StaleMate.h" #include "StaleMateTune.h" using namespace std; using namespace cv; using namespace rnrWin; // --------------------------------------------------------------------------- // Public Interface // --------------------------------------------------------------------------- static bool SMCalibBoardSquares(StaleMateSession &session, int nChessBoardDim) { IplImage *pImg; IplImage *pImgGray = NULL; int nVertDim = nChessBoardDim - 1; int nVertTot = nVertDim * nVertDim; CvSize sizeChessBoard = cvSize(nVertDim, nVertDim); CvPoint2D32f ptCorners[nVertTot]; int nCornerCnt; CvPoint ptImg[nVertDim][nVertDim]; Rot eRot; int i, j, k, m, n; int w1, w2, w3, h1, h2, h3; double dx1, dy1, dx2, dy2; int delta, ddelta; double x, y; double x11, y11, x12, y12, x21, y21, x22, y22; CvScalar colorPoly = CV_RGB(192, 0, 255); CvScalar colorText = CV_RGB(0, 192, 64); CvFont font; char bufText[32]; CvPoint *pPolyLines[nChessBoardDim]; int nPolyPts[nChessBoardDim]; int rc = 0; // - - - - // Run chess calibration // - - - - while( (rc == 0) && (session.m_gui.pMenu->GetCurrentAction() == StaleMateActionCalib) ) { pImg = StaleMateVideoCreateSnapShot(session); if( pImg == NULL ) { break; } if( pImgGray != NULL ) { cvReleaseImage(&pImgGray); } pImgGray = StaleMateCreateRgbChannel(pImg, CHANNEL_GRAY); rc = cvFindChessboardCorners(pImgGray, sizeChessBoard, ptCorners, &nCornerCnt, CV_CALIB_CB_ADAPTIVE_THRESH); cvCvtColor(pImgGray, pImg, CV_GRAY2RGB); //cvDrawChessboardCorners(pImg, sizeChessBoard, ptCorners, // nCornerCnt, rc); StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1); cvReleaseImage(&pImg); session.m_gui.pWin->WaitKey(5); } // - - - - // Calibration aborted or failed. // - - - - if( rc == 0 ) { if( pImgGray != NULL ) { cvReleaseImage(&pImgGray); } LOGERROR("Failed to calibrate board squares."); return false; } cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.50, 0.50, 0, 1); // - - - - // Determine how the corners are rotated clockwise relative to the chess board // 1h position ([0][0] square). // - - - - m = nVertDim + 1; // catty-corner index if( (ptCorners[0].x < ptCorners[m].x) && (ptCorners[0].y < ptCorners[m].y) ) { eRot = Rot0; cerr << "DBG: corners are not rotated." << endl; } else if( (ptCorners[0].x > ptCorners[m].x) && (ptCorners[0].y < ptCorners[m].y)) { eRot = Rot90; cerr << "DBG: corners are 90 degrees cw rotated." << endl; } else if( (ptCorners[0].x > ptCorners[m].x) && (ptCorners[0].y > ptCorners[m].y)) { eRot = Rot180; cerr << "DBG: corners are 180 degrees cw rotated." << endl; } else if( (ptCorners[0].x < ptCorners[m].x) && (ptCorners[0].y > ptCorners[m].y)) { eRot = Rot270; cerr << "DBG: corners are 270 degrees cw rotated." << endl; } else { eRot = Rot0; cerr << "DBG: cannot determine corners rotation - assuming 0 degrees." << endl; } // - - - - // Convert corners to image points normalizing to 0 degree rotation. // - - - - for(i=0; i<nVertTot; ++i) { switch( eRot ) { default: case Rot0: m = i / nVertDim; n = i % nVertDim; break; case Rot90: m = i % nVertDim; n = (nVertTot - i - 1) / nVertDim; break; case Rot180: m = (nVertTot - i - 1) / nVertDim; n = (nVertTot - i - 1) % nVertDim; break; case Rot270: m = (nVertTot - i - 1) % nVertDim; n = i / nVertDim; break; } ptImg[m][n].x = cvRound(ptCorners[i].x); ptImg[m][n].y = cvRound(ptCorners[i].y); sprintf(bufText, "%d", m*nVertDim+n); cvPutText(pImg, bufText, ptImg[m][n], &font, colorText); } cerr << "DBG: corners[]={"; for(m=0; m<nVertDim; ++m) { cerr << endl; for(n=0; n<nVertDim; ++n) { cerr << "(" << ptImg[m][n].x << "," << ptImg[m][n].y << ") "; } } cerr << "}" << endl; memset(session.m_calib.ptBoard, 0, sizeof(session.m_calib.ptBoard)); // - - - - // Central Board Area // - - - - for(i=1, m=0; i<nVertDim; ++i, ++m) { for(j=1, n=0; j<nVertDim; ++j, ++n) { session.m_calib.ptBoard[i][j][0].x = ptImg[m][n].x; session.m_calib.ptBoard[i][j][0].y = ptImg[m][n].y; session.m_calib.ptBoard[i][j][1].x = ptImg[m][n+1].x; session.m_calib.ptBoard[i][j][1].y = ptImg[m][n+1].y; session.m_calib.ptBoard[i][j][2].x = ptImg[m+1][n+1].x; session.m_calib.ptBoard[i][j][2].y = ptImg[m+1][n+1].y; session.m_calib.ptBoard[i][j][3].x = ptImg[m+1][n].x; session.m_calib.ptBoard[i][j][3].y = ptImg[m+1][n].y; } } // - - - - // Outer Left Column // - - - - for(i=1, j=0, k=1, m=2, n=3; i<nChessBoardDim-1; ++i) { // shared points session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[i][k][0].x; session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[i][k][0].y; session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][k][3].x; session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][k][3].y; // find the top widths of the 3 right neighbors w1 = iabs(session.m_calib.ptBoard[i][k][1].x - session.m_calib.ptBoard[i][k][0].x); w2 = iabs(session.m_calib.ptBoard[i][m][1].x - session.m_calib.ptBoard[i][m][0].x); w3 = iabs(session.m_calib.ptBoard[i][n][1].x - session.m_calib.ptBoard[i][n][0].x); // calculate the delta widths and the delta deltas delta = w1 - w2; ddelta = 0; //delta - (w2 - w3); // estimate top left x position x = (double)(session.m_calib.ptBoard[i][j][1].x - (w1 + delta + ddelta)); // // y = (y2 - y1)/(x2 - x1) * (x - x1) + y1 // // delta x and y of the top points of the right neighbor dx1 = (double)(session.m_calib.ptBoard[i][k][1].x - session.m_calib.ptBoard[i][k][0].x); dy1 = (double)(session.m_calib.ptBoard[i][k][1].y - session.m_calib.ptBoard[i][k][0].y); // calculate top left y, given the x, by the two-point line formula: y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][0].x) + (double)(session.m_calib.ptBoard[i][k][0].y); // set top-left point session.m_calib.ptBoard[i][j][0].x = cvRound(x); session.m_calib.ptBoard[i][j][0].y = cvRound(y); // find the bottom widths of the 3 right neighbors w1 = iabs(session.m_calib.ptBoard[i][k][3].x - session.m_calib.ptBoard[i][k][2].x); w2 = iabs(session.m_calib.ptBoard[i][m][3].x - session.m_calib.ptBoard[i][m][2].x); w3 = iabs(session.m_calib.ptBoard[i][n][3].x - session.m_calib.ptBoard[i][n][2].x); // calculate the delta widths and the delta deltas delta = w1 - w2; ddelta = 0; //delta - (w2 - w3); // estimate bottom left x position x = (double)(session.m_calib.ptBoard[i][j][2].x - (w1 + delta + ddelta)); // // y = (y2 - y1)/(x2 - x1) * (x - x1) + y1 // // delta x and y of the bottom points of the right neighbor dx1 = (double)(session.m_calib.ptBoard[i][k][3].x - session.m_calib.ptBoard[i][k][2].x); dy1 = (double)(session.m_calib.ptBoard[i][k][3].y - session.m_calib.ptBoard[i][k][2].y); // calculate bottom left y, given the x, by the two-point line formula: y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][2].x) + (double)(session.m_calib.ptBoard[i][k][2].y); // set bottom-left point session.m_calib.ptBoard[i][j][3].x = cvRound(x); session.m_calib.ptBoard[i][j][3].y = cvRound(y); } // - - - - // Outer Right Column // - - - - for(i=1, j=nChessBoardDim-1, k=j-1, m=j-2, n=j-3; i<nChessBoardDim-1; ++i) { // shared points session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][k][1].x; session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][k][1].y; session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[i][k][2].x; session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[i][k][2].y; // find the top widths of the 3 left neighbors w1 = iabs(session.m_calib.ptBoard[i][k][1].x - session.m_calib.ptBoard[i][k][0].x); w2 = iabs(session.m_calib.ptBoard[i][m][1].x - session.m_calib.ptBoard[i][m][0].x); w3 = iabs(session.m_calib.ptBoard[i][n][1].x - session.m_calib.ptBoard[i][n][0].x); // calculate the delta widths and the delta deltas delta = w1 - w2; ddelta = 0; //delta - (w2 - w3); // estimate top right x position x = (double)(session.m_calib.ptBoard[i][j][0].x + (w1 + delta + ddelta)); // // y = (y2 - y1)/(x2 - x1) * (x - x1) + y1 // // delta x and y of the top points of the left neighbor dx1 = (double)(session.m_calib.ptBoard[i][k][0].x - session.m_calib.ptBoard[i][k][1].x); dy1 = (double)(session.m_calib.ptBoard[i][k][0].y - session.m_calib.ptBoard[i][k][1].y); // calculate top left y, given the x, by the two-point line formula: y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][1].x) + (double)(session.m_calib.ptBoard[i][k][1].y); // set top-right point session.m_calib.ptBoard[i][j][1].x = cvRound(x); session.m_calib.ptBoard[i][j][1].y = cvRound(y); // find the bottom widths of the 3 left neighbors w1 = iabs(session.m_calib.ptBoard[i][k][3].x - session.m_calib.ptBoard[i][k][2].x); w2 = iabs(session.m_calib.ptBoard[i][m][3].x - session.m_calib.ptBoard[i][m][2].x); w3 = iabs(session.m_calib.ptBoard[i][n][3].x - session.m_calib.ptBoard[i][n][2].x); // calculate the delta widths and the delta deltas delta = w1 - w2; ddelta = 0; //delta - (w2 - w3); // estimate bottom right x position x = (double)(session.m_calib.ptBoard[i][j][3].x + (w1 + delta + ddelta)); // // y = (y2 - y1)/(x2 - x1) * (x - x1) + y1 // // delta x and y of the bottom points of the left neighbor dx1 = (double)(session.m_calib.ptBoard[i][k][3].x - session.m_calib.ptBoard[i][k][2].x); dy1 = (double)(session.m_calib.ptBoard[i][k][3].y - session.m_calib.ptBoard[i][k][2].y); // calculate bottom left y, given the x, by the two-point line formula: y = dy1/dx1 * (double)(x - session.m_calib.ptBoard[i][k][2].x) + (double)(session.m_calib.ptBoard[i][k][2].y); // set bottom-right point session.m_calib.ptBoard[i][j][2].x = cvRound(x); session.m_calib.ptBoard[i][j][2].y = cvRound(y); } // - - - - // Outer Top Row // - - - - for(j=1, i=0, k=1, m=2, n=3; j<nChessBoardDim-1; ++j) { // shared points session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[k][j][1].x; session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[k][j][1].y; session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[k][j][0].x; session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[k][j][0].y; // find the left heights of the 3 bottom neighbors h1 = iabs(session.m_calib.ptBoard[k][j][3].y - session.m_calib.ptBoard[k][j][0].y); h2 = iabs(session.m_calib.ptBoard[m][j][3].y - session.m_calib.ptBoard[m][j][0].y); h3 = iabs(session.m_calib.ptBoard[n][j][3].y - session.m_calib.ptBoard[n][j][0].y); // calculate the delta heights and the delta deltas delta = h1 - h2; ddelta = 0; //delta - (h2 - h3); // estimate top left y position y = (double)(session.m_calib.ptBoard[i][j][3].y - (h1 + delta + ddelta)); // // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 // // delta x and y of the left points of bottom neighbor dx1 = (double)(session.m_calib.ptBoard[k][j][3].x - session.m_calib.ptBoard[k][j][0].x); dy1 = (double)(session.m_calib.ptBoard[k][j][3].y - session.m_calib.ptBoard[k][j][0].y); // calculate top left x, given the y, by the two-point line formula: x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][0].y) + (double)(session.m_calib.ptBoard[k][j][0].x); // set top-left point session.m_calib.ptBoard[i][j][0].x = cvRound(x); session.m_calib.ptBoard[i][j][0].y = cvRound(y); // find the right heights of the 3 bottom neighbors h1 = iabs(session.m_calib.ptBoard[k][j][2].y - session.m_calib.ptBoard[k][j][1].y); h2 = iabs(session.m_calib.ptBoard[m][j][2].y - session.m_calib.ptBoard[m][j][1].y); h3 = iabs(session.m_calib.ptBoard[n][j][2].y - session.m_calib.ptBoard[n][j][1].y); // calculate the delta heights and the delta deltas delta = h1 - h2; ddelta = 0; //delta - (h2 - h3); // estimate top right y position y = (double)(session.m_calib.ptBoard[i][j][2].y - (h1 + delta + ddelta)); // // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 // // delta x and y of the right points of bottom neighbor dx1 = (double)(session.m_calib.ptBoard[k][j][2].x - session.m_calib.ptBoard[k][j][1].x); dy1 = (double)(session.m_calib.ptBoard[k][j][2].y - session.m_calib.ptBoard[k][j][1].y); // calculate top right x, given the y, by the two-point line formula: // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][1].y) + (double)(session.m_calib.ptBoard[k][j][1].x); // set top-right point session.m_calib.ptBoard[i][j][1].x = cvRound(x); session.m_calib.ptBoard[i][j][1].y = cvRound(y); } // - - - - // Outer Bottom Row // - - - - for(j=1, i=nChessBoardDim-1, k=i-1, m=i-2, n=i-3; j<nChessBoardDim-1; ++j) { // shared points session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[k][j][3].x; session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[k][j][3].y; session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[k][j][2].x; session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[k][j][2].y; // find the left heights of the 3 top neighbors h1 = iabs(session.m_calib.ptBoard[k][j][3].y - session.m_calib.ptBoard[k][j][0].y); h2 = iabs(session.m_calib.ptBoard[m][j][3].y - session.m_calib.ptBoard[m][j][0].y); h3 = iabs(session.m_calib.ptBoard[n][j][3].y - session.m_calib.ptBoard[n][j][0].y); // calculate the delta heights and the delta deltas delta = h1 - h2; ddelta = 0; //delta - (h2 - h3); // estimate bottom left y position y = (double)(session.m_calib.ptBoard[i][j][0].y + (h1 + delta + ddelta)); // // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 // // delta x and y of the left points of top neighbor dx1 = (double)(session.m_calib.ptBoard[k][j][3].x - session.m_calib.ptBoard[k][j][0].x); dy1 = (double)(session.m_calib.ptBoard[k][j][3].y - session.m_calib.ptBoard[k][j][0].y); // calculate bottom left x, given the y, by the two-point line formula: x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][0].y) + (double)(session.m_calib.ptBoard[k][j][0].x); // set top-left point session.m_calib.ptBoard[i][j][3].x = cvRound(x); session.m_calib.ptBoard[i][j][3].y = cvRound(y); // find the right heights of the 3 top neighbors h1 = iabs(session.m_calib.ptBoard[k][j][2].y - session.m_calib.ptBoard[k][j][1].y); h2 = iabs(session.m_calib.ptBoard[m][j][2].y - session.m_calib.ptBoard[m][j][1].y); h3 = iabs(session.m_calib.ptBoard[n][j][2].y - session.m_calib.ptBoard[n][j][1].y); // calculate the delta heights and the delta deltas delta = h1 - h2; ddelta = 0; //delta - (h2 - h3); // estimate bottom right y position y = (double)(session.m_calib.ptBoard[i][j][1].y + (h1 + delta + ddelta)); // // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 // // delta x and y of the right points of top neighbor dx1 = (double)(session.m_calib.ptBoard[k][j][2].x - session.m_calib.ptBoard[k][j][1].x); dy1 = (double)(session.m_calib.ptBoard[k][j][2].y - session.m_calib.ptBoard[k][j][1].y); // calculate bottom right x, given the y, by the two-point line formula: // x = (x2 - x1)/(y2 - y1) * (y - y1) + x1 x = dx1/dy1 * (double)(y - session.m_calib.ptBoard[k][j][1].y) + (double)(session.m_calib.ptBoard[k][j][1].x); // set top-right point session.m_calib.ptBoard[i][j][2].x = cvRound(x); session.m_calib.ptBoard[i][j][2].y = cvRound(y); } // - - - - // Top Left Corner // - - - - i = 0; j = 0; m = 1; n = 1; // shared points session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[i][n][0].x; session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[i][n][0].y; session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][n][3].x; session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][n][3].y; session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[m][j][0].x; session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[m][j][0].y; // line 1 x11 = (double)session.m_calib.ptBoard[i][n][0].x; y11 = (double)session.m_calib.ptBoard[i][n][0].y; x12 = (double)session.m_calib.ptBoard[i][n][1].x; y12 = (double)session.m_calib.ptBoard[i][n][1].y; dx1 = x12 - x11; dy1 = y12 - y11; // line 2 x21 = (double)session.m_calib.ptBoard[m][j][0].x; y21 = (double)session.m_calib.ptBoard[m][j][0].y; x22 = (double)session.m_calib.ptBoard[m][j][3].x; y22 = (double)session.m_calib.ptBoard[m][j][3].y; dx2 = x22 - x21; dy2 = y22 - y21; // calculate intersection x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2); y = dy1/dx1 * (x - x11) + y11; // set top-left point session.m_calib.ptBoard[i][j][0].x = cvRound(x); session.m_calib.ptBoard[i][j][0].y = cvRound(y); // - - - - // Top Right Corner // - - - - i = 0; j = nChessBoardDim-1; m = 1; n = j - 1; // shared points session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][n][1].x; session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][n][1].y; session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[m][j][1].x; session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[m][j][1].y; session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[m][j][0].x; session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[m][j][0].y; // line 1 x11 = (double)session.m_calib.ptBoard[i][n][0].x; y11 = (double)session.m_calib.ptBoard[i][n][0].y; x12 = (double)session.m_calib.ptBoard[i][n][1].x; y12 = (double)session.m_calib.ptBoard[i][n][1].y; dx1 = x12 - x11; dy1 = y12 - y11; // line 2 x21 = (double)session.m_calib.ptBoard[m][j][1].x; y21 = (double)session.m_calib.ptBoard[m][j][1].y; x22 = (double)session.m_calib.ptBoard[m][j][2].x; y22 = (double)session.m_calib.ptBoard[m][j][2].y; dx2 = x22 - x21; dy2 = y22 - y21; // calculate intersection x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2); y = dy1/dx1 * (x - x11) + y11; // set top-left point session.m_calib.ptBoard[i][j][1].x = cvRound(x); session.m_calib.ptBoard[i][j][1].y = cvRound(y); // - - - - // Bottom Right Corner // - - - - i = nChessBoardDim-1; j = nChessBoardDim-1; m = i - 1; n = j - 1; // shared points session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[i][n][1].x; session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[i][n][1].y; session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[m][j][2].x; session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[m][j][2].y; session.m_calib.ptBoard[i][j][3].x = session.m_calib.ptBoard[i][n][2].x; session.m_calib.ptBoard[i][j][3].y = session.m_calib.ptBoard[i][n][2].y; // line 1 x11 = (double)session.m_calib.ptBoard[i][n][2].x; y11 = (double)session.m_calib.ptBoard[i][n][2].y; x12 = (double)session.m_calib.ptBoard[i][n][3].x; y12 = (double)session.m_calib.ptBoard[i][n][3].y; dx1 = x12 - x11; dy1 = y12 - y11; // line 2 x21 = (double)session.m_calib.ptBoard[m][j][1].x; y21 = (double)session.m_calib.ptBoard[m][j][1].y; x22 = (double)session.m_calib.ptBoard[m][j][2].x; y22 = (double)session.m_calib.ptBoard[m][j][2].y; dx2 = x22 - x21; dy2 = y22 - y21; // calculate intersection x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2); y = dy1/dx1 * (x - x11) + y11; // set top-left point session.m_calib.ptBoard[i][j][2].x = cvRound(x); session.m_calib.ptBoard[i][j][2].y = cvRound(y); // - - - - // Bottom Left Corner // - - - - i = nChessBoardDim-1; j = 0; m = i - 1; n = 1; // shared points session.m_calib.ptBoard[i][j][0].x = session.m_calib.ptBoard[m][j][3].x; session.m_calib.ptBoard[i][j][0].y = session.m_calib.ptBoard[m][j][3].y; session.m_calib.ptBoard[i][j][1].x = session.m_calib.ptBoard[m][j][2].x; session.m_calib.ptBoard[i][j][1].y = session.m_calib.ptBoard[m][j][2].y; session.m_calib.ptBoard[i][j][2].x = session.m_calib.ptBoard[i][n][3].x; session.m_calib.ptBoard[i][j][2].y = session.m_calib.ptBoard[i][n][3].y; // line 1 x11 = (double)session.m_calib.ptBoard[i][n][2].x; y11 = (double)session.m_calib.ptBoard[i][n][2].y; x12 = (double)session.m_calib.ptBoard[i][n][3].x; y12 = (double)session.m_calib.ptBoard[i][n][3].y; dx1 = x12 - x11; dy1 = y12 - y11; // line 2 x21 = (double)session.m_calib.ptBoard[m][j][0].x; y21 = (double)session.m_calib.ptBoard[m][j][0].y; x22 = (double)session.m_calib.ptBoard[m][j][3].x; y22 = (double)session.m_calib.ptBoard[m][j][3].y; dx2 = x22 - x21; dy2 = y22 - y21; // calculate intersection x = (y21 - y11 + dy1/dx1 * x11 - dy2/dx2 * x21) / (dy1/dx1 - dy2/dx2); y = dy1/dx1 * (x - x11) + y11; // set top-left point session.m_calib.ptBoard[i][j][3].x = cvRound(x); session.m_calib.ptBoard[i][j][3].y = cvRound(y); // - - - - // Draw calibration // - - - - cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.75, 0.75, 0, 1); for(i=0; i<nChessBoardDim; ++i) { for(j=0, n=0; j<nChessBoardDim; ++j) { if( (session.m_calib.ptBoard[i][j][0].x == 0) && (session.m_calib.ptBoard[i][j][1].y == 0) ) { continue; } cvPutText(pImg, StaleMateChessBoardCoordStr(i, j), session.m_calib.ptBoard[i][j][3], &font, colorText); pPolyLines[n] = session.m_calib.ptBoard[i][j]; nPolyPts[n] = 4; n++; } if( n > 0 ) { cvPolyLine(pImg, pPolyLines, nPolyPts, n, 2, colorPoly, 1, 8); } } StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1); cvReleaseImage(&pImgGray); return true; } static bool SMCalibVideo(StaleMateSession &session) { IplImage *pImg; if( (pImg = StaleMateVideoCreateSnapShot(session)) == NULL ) { return false; } if( session.m_calib.pImgEmptyRed != NULL ) { cvReleaseImage(&session.m_calib.pImgEmptyRed); } session.m_calib.pImgEmptyRed = StaleMateCreateRgbChannel(pImg, CHANNEL_RED); if( session.m_calib.pImgEmptyBlue != NULL ) { cvReleaseImage(&session.m_calib.pImgEmptyBlue); } session.m_calib.pImgEmptyBlue = StaleMateCreateRgbChannel(pImg, CHANNEL_BLUE); cvReleaseImage(&pImg); return true; } static bool SMCalibRoi(StaleMateSession &session, int nChessBoardDim) { int k; int w1, w2; int h1, h2; k = nChessBoardDim - 1; if( session.m_calib.ptBoard[0][0][0].x < session.m_calib.ptBoard[k][0][3].x ) { session.m_calib.rectRoiBoard.x = session.m_calib.ptBoard[0][0][0].x; } else { session.m_calib.rectRoiBoard.x = session.m_calib.ptBoard[k][0][3].x; } if( session.m_calib.ptBoard[0][0][0].y < session.m_calib.ptBoard[0][k][1].y ) { session.m_calib.rectRoiBoard.y = session.m_calib.ptBoard[0][0][0].y; } else { session.m_calib.rectRoiBoard.y = session.m_calib.ptBoard[0][k][1].y; } w1 = session.m_calib.ptBoard[0][k][1].x - session.m_calib.ptBoard[0][0][0].x; w2 = session.m_calib.ptBoard[k][k][2].x - session.m_calib.ptBoard[k][0][3].x; session.m_calib.rectRoiBoard.width = w1 >= w2? w1: w2; h1 = session.m_calib.ptBoard[k][0][3].y - session.m_calib.ptBoard[0][0][0].y; h2 = session.m_calib.ptBoard[k][k][2].y - session.m_calib.ptBoard[0][k][1].y; session.m_calib.rectRoiBoard.height = h1 >= h2? h1: h2; return true; } // positive x is forward, positive y is left static bool SMCalibDist(StaleMateSession &session, int nChessBoardDim, CvPoint2D32f &ptDEBottom) { CvPoint2D32f ptOrig; double x, y; int i, j; // origin is the center of upper left corner chess square ptOrig.x = ptDEBottom.x + (double)nChessBoardDim * TuneChessSquareDim - TuneChessSquareDim / 2.0; ptOrig.y = ptDEBottom.y + (double)(nChessBoardDim)/2.0 * TuneChessSquareDim - TuneChessSquareDim / 2.0; for(i=0, x = ptOrig.x; i<nChessBoardDim; ++i, x -= TuneChessSquareDim) { for(j=0, y = ptOrig.y; j<nChessBoardDim; ++j, y -= TuneChessSquareDim) { session.m_calib.ptHekDist[i][j].x = x; session.m_calib.ptHekDist[i][j].y = y; } } session.m_calib.ptDEBottom = ptDEBottom; return true; } static void SMCalibShowAnnotated(StaleMateSession &session) { int nDim = session.m_game.nChessBoardDim; IplImage *pImg; CvScalar colorText = CV_RGB(0, 64, 64); CvScalar colorPoly = CV_RGB(64, 32, 255); CvScalar colorRoi = CV_RGB(0, 32, 64); CvFont font; char bufText[32]; CvPoint *pPolyLines[nDim]; int nPolyPts[nDim]; CvPoint pt1, pt2; int i, j, k; if( (pImg = StaleMateVideoCreateSnapShot(session)) == NULL ) { return; } cvInitFont(&font, CV_FONT_HERSHEY_DUPLEX, 0.75, 0.75, 0, 1); pt1.x = 5; pt1.y = 25; cvPutText(pImg, "Calibration", pt1, &font, colorText); for(i=0; i<nDim; ++i) { for(j=0, k=0; j<nDim; ++j) { pt1 = session.m_calib.ptBoard[i][j][3]; pt1.x += 3; pt1.y -= 3; cvPutText(pImg, StaleMateChessBoardCoordStr(i, j), pt1, &font, colorText); pPolyLines[k] = session.m_calib.ptBoard[i][j]; nPolyPts[k] = 4; k++; } cvPolyLine(pImg, pPolyLines, nPolyPts, nDim, 2, colorPoly, 2, 8); } pt1.x = session.m_calib.rectRoiBoard.x; pt1.y = session.m_calib.rectRoiBoard.y; pt2.x = pt1.x + session.m_calib.rectRoiBoard.width - 1; pt2.y = pt1.y + session.m_calib.rectRoiBoard.height - 1; cvRectangle(pImg, pt1, pt2, colorRoi, 1); StaleMateIoIShow(session, pImg, session.m_vid.uImgIndex1); cvReleaseImage(&pImg); } // --------------------------------------------------------------------------- // Public Interface // --------------------------------------------------------------------------- void StaleMateCalib(StaleMateSession &session) { session.m_calib.bCalibrated = false; if( !SMCalibBoardSquares(session, session.m_game.nChessBoardDim) ) { return; } if( !SMCalibVideo(session) ) { return; } if( !SMCalibRoi(session, session.m_game.nChessBoardDim) ) { return; } if( !SMCalibDist(session, session.m_game.nChessBoardDim, session.m_calib.ptDEBottom) ) { return; } SMCalibShowAnnotated(session); LOGDIAG1("Calibration complete."); session.m_calib.bCalibrated = true; }
32.248654
80
0.580326
roadnarrows-robotics
5dbcd6f5f5fb732707e72a761ff1cc70ea0b752d
1,202
hpp
C++
src/custom_topic/include/topic_pubsub/pub.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/custom_topic/include/topic_pubsub/pub.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/custom_topic/include/topic_pubsub/pub.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
/** * Publisher definition. * * Roberto Masocco <robmasocco@gmail.com> * * November 22, 2021 */ #ifndef PUB_HPP #define PUB_HPP #include <rclcpp/rclcpp.hpp> //! rclcpp base library #include <ros2_examples_interfaces/msg/string.hpp> //! This time we use our own #define PUB_PERIOD 300 // Publisher transmission time period [ms] /** * Simple publisher node: transmits strings on a topic. */ //! Every node must extend publicly the Node base class class Pub : public rclcpp::Node { public: //! There must always be a constructor, with arbitrary input arguments Pub(); //! ROS-specific members better be private private: //! DDS endpoint, acting as a publisher //! Syntax is: rclcpp::Publisher<INTERFACE_TYPE>::SharedPtr OBJ; rclcpp::Publisher<ros2_examples_interfaces::msg::String>::SharedPtr publisher_; //! ROS-2 managed timer: enables one to set up a periodic job //! The job is coded in a callback, which better be a private method //! Syntax is: rclcpp::TimerBase::SharedPtr OBJ; //! Callback signature must be: void FUNC_NAME(void); rclcpp::TimerBase::SharedPtr pub_timer_; void pub_timer_callback(void); unsigned long pub_cnt_; // Marks messages }; #endif
26.130435
81
0.72629
IntelligentSystemsLabUTV
5dbfe826e98c69989b1f53d2c6478b563182aedc
1,664
cpp
C++
B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp
podhrmic/Effective-Robotics-Programming-with-ROS
9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00
[ "MIT" ]
46
2017-02-11T18:28:57.000Z
2021-12-12T07:55:22.000Z
B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp
podhrmic/Effective-Robotics-Programming-with-ROS
9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00
[ "MIT" ]
1
2017-03-22T13:07:55.000Z
2020-11-02T09:12:52.000Z
B05576_07_Code/rosbook_arm_snippets/src/move_group_plan_single_target.cpp
podhrmic/Effective-Robotics-Programming-with-ROS
9c5f3188bfdb47d6d0ee5c36da803e2381fb1a00
[ "MIT" ]
23
2016-12-30T05:11:37.000Z
2021-05-04T15:08:34.000Z
#include <moveit/move_group_interface/move_group.h> #include <moveit_msgs/DisplayTrajectory.h> int main(int argc, char **argv) { // Initialize ROS, create the node handle and an async spinner ros::init(argc, argv, "move_group_plan_single_target"); ros::NodeHandle nh; ros::AsyncSpinner spin(1); spin.start(); // Get the arm planning group moveit::planning_interface::MoveGroup plan_group("arm"); // Create a published for the arm plan visualization ros::Publisher display_pub = nh.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true); // Set a goal message as a pose of the end effector geometry_msgs::Pose goal; goal.orientation.x = -0.000764819; goal.orientation.y = 0.0366097; goal.orientation.z = 0.00918912; goal.orientation.w = 0.999287; goal.position.x = 0.775884; goal.position.y = 0.43172; goal.position.z = 2.71809; // Set the tolerance to consider the goal achieved plan_group.setGoalTolerance(0.2); // Set the target pose, which is the goal we already defined plan_group.setPoseTarget(goal); // Perform the planning step, and if it succeeds display the current // arm trajectory and move the arm moveit::planning_interface::MoveGroup::Plan goal_plan; if (plan_group.plan(goal_plan)) { moveit_msgs::DisplayTrajectory display_msg; display_msg.trajectory_start = goal_plan.start_state_; display_msg.trajectory.push_back(goal_plan.trajectory_); display_pub.publish(display_msg); sleep(5.0); plan_group.move(); } ros::shutdown(); return 0; }
30.254545
123
0.695913
podhrmic
5dc04855bd8ddedfd58cc73ff07656b9fcc9f8ac
882
cpp
C++
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
#include<iostream> #include<unordered_map> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; unordered_map<string,vector<string>> map; for(string s : strs){ string key = s; sort(key.begin(),key.end()); map[key].push_back(s); } // 想要拷贝元素:for(auto x : range) // 想要修改元素 : for(auto&& x : range) // 想要只读元素:for(const auto& x : range) for(const auto& p : map){ res.push_back(p.second); } return res; } }; void print_vec(vector<vector<string>>& s){ for(vector<string> vec : s){ for(string c : vec){ cout<<c<<' '; } cout<<endl; } } int main(){ }
23.837838
65
0.510204
codehuanglei
5dc219f3aef70a802c53b00cc97d44a6bf81a1ae
7,173
cpp
C++
src/services/gridftpd/dataread.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/services/gridftpd/dataread.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/services/gridftpd/dataread.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <globus_common.h> #include <globus_io.h> #include <globus_ftp_control.h> #include <arc/globusutils/GlobusErrorUtils.h> #include <arc/Logger.h> #include "fileroot.h" #include "names.h" #include "commands.h" static Arc::Logger logger(Arc::Logger::getRootLogger(),"GridFTP_Commands"); /* file retrieve callbacks */ void GridFTP_Commands::data_connect_retrieve_callback(void* arg,globus_ftp_control_handle_t*,unsigned int /* stripendx */,globus_bool_t /* reused */,globus_object_t *error) { GridFTP_Commands *it = (GridFTP_Commands*)arg; logger.msg(Arc::VERBOSE, "data_connect_retrieve_callback"); globus_thread_blocking_will_block(); globus_mutex_lock(&(it->data_lock)); it->time_spent_disc=0; it->time_spent_network=0; it->last_action_time=time(NULL); logger.msg(Arc::VERBOSE, "Data channel connected (retrieve)"); if(it->check_abort(error)) { it->froot.close(false); globus_mutex_unlock(&(it->data_lock)); return; }; it->data_eof = false; /* make buffers */ logger.msg(Arc::VERBOSE, "data_connect_retrieve_callback: allocate_data_buffer"); it->compute_data_buffer(); if(!(it->allocate_data_buffer())) { logger.msg(Arc::ERROR, "data_connect_retrieve_callback: allocate_data_buffer failed"); it->froot.close(false); it->force_abort(); globus_mutex_unlock(&(it->data_lock)); return; }; /* fill and register all available buffers */ it->data_callbacks=0; it->data_offset=0; for(unsigned int i = 0;i<it->data_buffer_num;i++) { logger.msg(Arc::VERBOSE, "data_connect_retrieve_callback: check for buffer %u", i); if(!((it->data_buffer)[i].data)) continue; /* read data from file */ unsigned long long size = it->data_buffer_size; if(it->virt_restrict) { if((it->data_offset + size) > it->virt_size) size=it->virt_size-it->data_offset; }; struct timezone tz; gettimeofday(&(it->data_buffer[i].time_last),&tz); int fres=it->froot.read(it->data_buffer[i].data, (it->virt_offset)+(it->data_offset),&size); if(fres != 0) { logger.msg(Arc::ERROR, "Closing channel (retrieve) due to local read error :%s", it->froot.error); it->force_abort(); it->free_data_buffer();it->froot.close(false); globus_mutex_unlock(&(it->data_lock)); return; }; if(size == 0) it->data_eof=GLOBUS_TRUE; /* register buffer */ globus_result_t res; res=globus_ftp_control_data_write(&(it->handle), (globus_byte_t*)(it->data_buffer[i].data), size,it->data_offset,it->data_eof, &data_retrieve_callback,it); it->data_offset+=size; if(res != GLOBUS_SUCCESS) { logger.msg(Arc::ERROR, "Buffer registration failed"); logger.msg(Arc::ERROR, "Globus error: %s", Arc::GlobusResult(res).str()); it->force_abort(); if(it->data_callbacks==0){it->free_data_buffer();it->froot.close(false);}; globus_mutex_unlock(&(it->data_lock)); return; }; it->data_callbacks++; if(it->data_eof == GLOBUS_TRUE) break; }; globus_mutex_unlock(&(it->data_lock)); return; } void GridFTP_Commands::data_retrieve_callback(void* arg,globus_ftp_control_handle_t*,globus_object_t *error,globus_byte_t *buffer,globus_size_t length,globus_off_t offset,globus_bool_t eof) { logger.msg(Arc::VERBOSE, "data_retrieve_callback"); globus_thread_blocking_will_block(); GridFTP_Commands *it = (GridFTP_Commands*)arg; struct timezone tz; struct timeval tv; gettimeofday(&tv,&tz); globus_mutex_lock(&(it->data_lock)); it->last_action_time=time(NULL); logger.msg(Arc::VERBOSE, "Data channel (retrieve) %i %i %i", (int)offset, (int)length, (int)eof); it->data_callbacks--; if(it->check_abort(error)) { if(it->data_callbacks==0){it->free_data_buffer();it->froot.close(false);}; globus_mutex_unlock(&(it->data_lock)); return; }; if(it->data_eof) { if(it->data_callbacks==0) { logger.msg(Arc::VERBOSE, "Closing channel (retrieve)"); it->free_data_buffer(); it->virt_offset=0; it->virt_restrict=false; it->transfer_mode=false; it->froot.close(); logger.msg(Arc::VERBOSE, "Time spent waiting for network: %.3f ms", (float)(it->time_spent_network/1000.0)); logger.msg(Arc::VERBOSE, "Time spent waiting for disc: %.3f ms", (float)(it->time_spent_disc/1000.0)); it->send_response("226 Requested file transfer completed\r\n"); }; globus_mutex_unlock(&(it->data_lock)); return; }; /* find this buffer */ unsigned int i; for(i = 0;i<it->data_buffer_num;i++) { if((it->data_buffer)[i].data == (unsigned char*)buffer) break; }; if(i >= it->data_buffer_num) { /* lost buffer - probably memory corruption */ logger.msg(Arc::ERROR, "data_retrieve_callback: lost buffer"); it->force_abort(); if(it->data_callbacks==0){it->free_data_buffer();it->froot.close(false);}; globus_mutex_unlock(&(it->data_lock)); return; }; unsigned long long int time_diff = (tv.tv_sec-(it->data_buffer[i].time_last.tv_sec))*1000000+ (tv.tv_usec-(it->data_buffer[i].time_last.tv_usec)); it->time_spent_network+=time_diff; /* read data from file */ unsigned long long size = it->data_buffer_size; if(it->virt_restrict) { if((it->data_offset + size) > it->virt_size) size=it->virt_size-it->data_offset; }; #ifdef __USE_PARALLEL_FILE_ACCESS__ it->data_callbacks++; /* Unlock while reading file, so to allow others to read in parallel. This can speed up read if on striped device/filesystem. */ globus_mutex_unlock(&(it->data_lock)); #endif /* NOTE: it->data_lock is not unlocked here because it->froot.write is not thread safe */ struct timeval tv_last; gettimeofday(&tv_last,&tz); int fres=it->froot.read(it->data_buffer[i].data, (it->virt_offset)+(it->data_offset),&size); #ifdef __USE_PARALLEL_FILE_ACCESS__ globus_mutex_lock(&(it->data_lock)); it->data_callbacks--; #endif gettimeofday(&tv,&tz); time_diff=(tv.tv_sec-tv_last.tv_sec)*1000000+(tv.tv_usec-tv_last.tv_usec); it->time_spent_disc+=time_diff; if((fres != 0) || (!it->transfer_mode) || (it->transfer_abort)) { logger.msg(Arc::ERROR, "Closing channel (retrieve) due to local read error: %s", it->froot.error); it->force_abort(); if(it->data_callbacks==0){it->free_data_buffer();it->froot.close(false);}; globus_mutex_unlock(&(it->data_lock)); return; }; if(size == 0) it->data_eof=true; /* register buffer */ globus_result_t res; res=globus_ftp_control_data_write(&(it->handle), (globus_byte_t*)(it->data_buffer[i].data), size,it->data_offset,it->data_eof, &data_retrieve_callback,it); it->data_offset+=size; if(res != GLOBUS_SUCCESS) { logger.msg(Arc::ERROR, "Buffer registration failed"); logger.msg(Arc::ERROR, "Globus error: %s", Arc::GlobusResult(res).str()); it->force_abort(); if(it->data_callbacks==0){it->free_data_buffer();it->froot.close(false);}; globus_mutex_unlock(&(it->data_lock)); return; }; it->data_callbacks++; globus_mutex_unlock(&(it->data_lock)); return; }
39.412088
191
0.679074
davidgcameron
5dc231a42ee8385223e30f930b0c31d7f47869a4
5,048
cpp
C++
LocalizationUtils/src/Commands/GenerateCommand.cpp
LazyPanda07/LocalizationUtils
294bd5df5efe33f238c54b40543d0455f61c60a0
[ "MIT" ]
null
null
null
LocalizationUtils/src/Commands/GenerateCommand.cpp
LazyPanda07/LocalizationUtils
294bd5df5efe33f238c54b40543d0455f61c60a0
[ "MIT" ]
null
null
null
LocalizationUtils/src/Commands/GenerateCommand.cpp
LazyPanda07/LocalizationUtils
294bd5df5efe33f238c54b40543d0455f61c60a0
[ "MIT" ]
null
null
null
#include "GenerateCommand.h" using namespace std; namespace commands { void GenerateCommand::start(const filesystem::path& localizationFolder, const string& originalLanguage, const vector<string>& otherLanguages) const { json::JSONBuilder metaBuilder(CP_UTF8); filesystem::create_directory(localizationFolder); metaBuilder[originalLanguage] = encoding::SHA256::getHash((ostringstream() << ifstream(utility::makeLocalizationFile(originalLanguage, localizationFolder)).rdbuf()).str()); for (const auto& i : otherLanguages) { metaBuilder[i] = encoding::SHA256::getHash((ostringstream() << ifstream(utility::makeLocalizationFile(i, localizationFolder)).rdbuf()).str()); } ofstream(localizationFolder / files::metaFile) << metaBuilder; } void GenerateCommand::repeat(const filesystem::path& localizationFolder, const string& originalLanguage, const vector<string>& otherLanguages) const { filesystem::directory_iterator it(localizationFolder); unordered_map<string, string> localizationFiles; json::JSONParser localizationKeys; json::JSONParser metaParser = ifstream(localizationFolder / files::metaFile); for (const auto& i : it) { string fileName = i.path().string(); if (fileName.find(files::metaFile) != string::npos) { continue; } string language = string(fileName.begin() + fileName.rfind('_') + 1, fileName.begin() + fileName.rfind('.')); localizationFiles[move(language)] = move(fileName); } if (localizationFiles.find(originalLanguage) == localizationFiles.end()) { localizationKeys.setJSONData((ostringstream() << ifstream(utility::makeLocalizationFile(originalLanguage, localizationFolder)).rdbuf()).str()); } else { string pathToOriginalLanguageLocalizationFile = (localizationFolder / global::localizationFile).string(); localizationKeys.setJSONData((ostringstream() << ifstream(format(pathToOriginalLanguageLocalizationFile, originalLanguage)).rdbuf()).str()); } localizationFiles.erase(originalLanguage); if (otherLanguages.size() != localizationFiles.size()) { for (const auto& i : otherLanguages) { if (localizationFiles.find(i) == localizationFiles.end()) { utility::makeLocalizationFile(i, localizationFolder, utility::copyOriginalLanguage(localizationKeys)); } } } const string& previousHash = metaParser.getString(originalLanguage); encoding::SHA256 currentHash; unordered_map<string, string> updatedHashes; json::JSONBuilder updateMetaBuilder(metaParser.getParsedData(), CP_UTF8); for (const auto& i : localizationKeys) { currentHash.update(i->first); } if (currentHash.getHash() != previousHash) { updateMetaBuilder[originalLanguage] = currentHash.getHash(); for (const auto& i : otherLanguages) { const string& pathToCurrentFile = localizationFiles[i]; json::JSONParser languageParser = ifstream(pathToCurrentFile); unordered_set<string> existingKeys; unordered_map<const string*, const string*> values; existingKeys.reserve(languageParser.getParsedData().data.size()); values.reserve(languageParser.getParsedData().data.size()); for (const auto& j : languageParser) { const string& key = *existingKeys.insert(j->first).first; values[&key] = &get<string>(j->second); } json::JSONBuilder updateBuilder = utility::copyOriginalLanguage(localizationKeys, existingKeys); for (const auto& [key, value] : values) { updateBuilder[*key] = *value; } ofstream(pathToCurrentFile) << updateBuilder; updatedHashes[i] = encoding::SHA256::getHash((ostringstream() << ifstream(pathToCurrentFile).rdbuf()).str()); } } else { for (const auto& i : otherLanguages) { string checkHash = encoding::SHA256::getHash((ostringstream() << ifstream(localizationFiles[i]).rdbuf()).str()); if (metaParser.contains(i, json::utility::variantTypeEnum::jString) && checkHash == metaParser.getString(i)) { continue; } updatedHashes[i] = move(checkHash); } } for (auto& [language, hash] : updatedHashes) { updateMetaBuilder[language] = move(hash); } ofstream(localizationFolder / files::metaFile) << updateMetaBuilder; } GenerateCommand::GenerateCommand(const json::JSONParser& settings) : ICommand(settings) { } void GenerateCommand::run() const { const string& originalLanguage = settings.getString(settings::originalLanguageSetting); vector<string> otherLanguages = json::utility::JSONArrayWrapper(settings.getArray(settings::otherLanguagesSetting)).getAsStringArray(); filesystem::path localizationFolder = utility::makePath(global::startFolder, folders::localizationFolder); if (!filesystem::exists(localizationFolder)) { this->start(localizationFolder, originalLanguage, otherLanguages); } else { if (!filesystem::exists(localizationFolder / files::metaFile)) { this->start(localizationFolder, originalLanguage, otherLanguages); } this->repeat(localizationFolder, originalLanguage, otherLanguages); } } }
31.354037
174
0.726624
LazyPanda07
5dc2feb812db79fb1073f297761d6c13fb2b266b
1,321
cpp
C++
UVa 11844 - The Melding Plague/sample/11844 - The Melding Plague.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 11844 - The Melding Plague/sample/11844 - The Melding Plague.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 11844 - The Melding Plague/sample/11844 - The Melding Plague.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <string.h> #include <iostream> #include <map> using namespace std; map<string, int> R; int getLabel(string s) { int &x = R[s]; return x == 0 ? x = R.size() : x; } #define MAXN 4096 int main() { int Nm, Ni, Nc, n, x, y; char s[MAXN]; while(scanf("%d %d %d %d", &Nm, &Ni, &Nc, &n) == 4) { if(Nm + Ni + Nc + n == 0) break; R.clear(); int Icnt[MAXN] = {}, Ccnt[MAXN] = {}, g[MAXN] = {}; int eflag = 0; for(int i = 1; i < MAXN; i++) g[i] = i; for(int i = 0; i < Nm; i++) { scanf("%s", s); x = getLabel(s); scanf("%s", s); y = getLabel(s); if(g[x] != x && g[x] != y) eflag = 1; g[x] = y; } for(int i = 0; i < Ni; i++) { scanf("%s %d", s, &y); x = getLabel(s); Icnt[x] = y; } for(int i = 0; i < Nc; i++) { scanf("%s %d", s, &y); x = getLabel(s); Ccnt[x] = y; } if(eflag) { puts("Protein mutations are not deterministic"); continue; } eflag = 1; for(int i = 0; i <= n; i++) { if(memcmp(Icnt, Ccnt, sizeof(Icnt)) == 0) { printf("Cure found in %d mutation(s)\n", i); eflag = 0; break; } int next[MAXN] = {}; for(int j = 1; j <= R.size(); j++) { next[g[j]] += Icnt[j]; } memcpy(Icnt, next, sizeof(next)); } if(eflag) puts("Nostalgia for Infinity is doomed"); } return 0; }
20.640625
54
0.482967
tadvi
5dc40e9c639f7b42e1895144a209170499da2c2e
561
hpp
C++
include/ccbase/utility/bytes.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
8
2015-01-08T05:44:43.000Z
2021-05-11T15:54:17.000Z
include/ccbase/utility/bytes.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
1
2016-01-31T08:48:53.000Z
2016-01-31T08:54:28.000Z
include/ccbase/utility/bytes.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
2
2015-03-26T11:08:18.000Z
2016-01-30T03:28:06.000Z
/* ** File Name: bytes.hpp ** Author: Aditya Ramesh ** Date: 07/09/2014 ** Contact: _@adityaramesh.com */ #ifndef Z66BE627C_AD04_47FD_9360_9A51E7280DC8 #define Z66BE627C_AD04_47FD_9360_9A51E7280DC8 #include <cstdint> constexpr uint64_t operator ""_KB(unsigned long long int x) { return x << 10; } constexpr uint64_t operator ""_MB(unsigned long long int x) { return x << 20; } constexpr uint64_t operator ""_GB(unsigned long long int x) { return x << 30; } constexpr uint64_t operator ""_TB(unsigned long long int x) { return x << 40; } #endif
18.7
45
0.716578
adityaramesh
5dc5ddbdb072da284c0a9d7aafb8e7ebed1790e8
2,377
cpp
C++
mp/src/game/server/Mod/ClassicPhases.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
7
2019-02-04T01:17:26.000Z
2022-02-26T21:36:34.000Z
mp/src/game/server/Mod/ClassicPhases.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
11
2016-05-06T22:44:46.000Z
2016-05-06T22:45:03.000Z
mp/src/game/server/Mod/ClassicPhases.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
2
2016-06-28T11:34:53.000Z
2017-04-01T18:08:46.000Z
/* ***** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/LGPL 2.1/GPL 2.0 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with ... for the specific language governing rights and limitations under the License. The Original Code is for LuminousForts. The Initial Developer of the Original Code is Hekar Khani. Portions created by the Hekar Khani are Copyright (C) 2010 Hekar Khani. All Rights Reserved. Contributor(s): Hekar Khani <hekark@gmail.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), ... the terms of any one of the MPL, the GPL or the LGPL. ***** END LICENSE BLOCK ***** */ /*=============================================================== Server This is a pretty old file from probably around March 2009. Only the phase manager really applies. If you want you can use the other stuff though. Last Updated Sept 13 2009 ===============================================================*/ #include "cbase.h" #include "PhaseControl.h" #include "ClassicPhases.h" #define LUMINOUSFORTS_SOUND_BUILD "Luminousforts.Build" #define LUMINOUSFORTS_SOUND_COMBAT "Luminousforts.Combat" class CPrecachePhaseSounds : public CBaseEntity { public: void Precache() { PrecacheScriptSound( LUMINOUSFORTS_SOUND_BUILD ); PrecacheScriptSound( LUMINOUSFORTS_SOUND_COMBAT ); //HODO: Move hacky precaches PrecacheScriptSound( "CTF.Draw" ); PrecacheScriptSound( "CTF.BlueWins" ); PrecacheScriptSound( "CTF.RedWins" ); } }; LINK_ENTITY_TO_CLASS( precache_sourceforts_sounds, CPrecachePhaseSounds ); // // Name: CBuildPhase // Author: Hekar Khani // Description: On the switch to build phase // Notes: // CBuildPhase::CBuildPhase() : CPhaseBase( PHASE_BUILD, "BuildPhase" ) { } CBuildPhase::~CBuildPhase() { } void CBuildPhase::SwitchTo() { Msg( "[LF] Build Phase Has Begun\n" ); PlaySound( LUMINOUSFORTS_SOUND_BUILD ); } // // Name: CCombatPhase // Author: Hekar Khani // Description: On the switch to combat phase // Notes: // CCombatPhase::CCombatPhase() : CPhaseBase( PHASE_COMBAT, "CombatPhase" ) { } CCombatPhase::~CCombatPhase() { } void CCombatPhase::SwitchTo() { Msg( "[LF] Combat Phase Has Begun\n" ); PlaySound( LUMINOUSFORTS_SOUND_COMBAT ); }
22.855769
76
0.700042
hekar
5dcaaef856d43a2166ded3825b63f727ed989dbf
770
hpp
C++
src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp
takuya-takeuchi/OpenJijDotNet
e1cd30efbf0c561e89bc10bd90cd36a3176ad09a
[ "MIT" ]
null
null
null
src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp
takuya-takeuchi/OpenJijDotNet
e1cd30efbf0c561e89bc10bd90cd36a3176ad09a
[ "MIT" ]
null
null
null
src/OpenJijDotNet.Native/openjij/utility/Xorshift.hpp
takuya-takeuchi/OpenJijDotNet
e1cd30efbf0c561e89bc10bd90cd36a3176ad09a
[ "MIT" ]
null
null
null
#ifndef _CPP_UTILITY_XORSHIFT_H_ #define _CPP_UTILITY_XORSHIFT_H_ #include "../export.hpp" #include "../shared.hpp" #include <random> #include <utility/random.hpp> using namespace openjij; using namespace openjij::utility; DLLEXPORT Xorshift* utility_Xorshift_new() { return new Xorshift(); } DLLEXPORT Xorshift* utility_Xorshift_new2(const uint32_t s) { return new Xorshift(s); } DLLEXPORT void utility_Xorshift_delete(Xorshift* xorshift) { delete xorshift; } DLLEXPORT uint32_t utility_Xorshift_operator(Xorshift* xorshift) { return xorshift->operator()(); } DLLEXPORT uint32_t utility_Xorshift_min() { return Xorshift::min(); } DLLEXPORT uint32_t utility_Xorshift_max() { return Xorshift::max(); } #endif // _CPP_UTILITY_XORSHIFT_H_
17.5
64
0.758442
takuya-takeuchi
5dce0207b6d99ec0a88c88a57160b5a0ecc20997
4,507
cpp
C++
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2020-03-04T10:41:26.000Z
2021-04-15T06:29:41.000Z
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
2
2019-01-14T15:58:47.000Z
2021-04-18T09:09:51.000Z
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2018-07-20T14:36:42.000Z
2021-06-28T13:03:57.000Z
/*BSD 2-Clause License * Copyright(c) 2019, Pekka Astola * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met : * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "predictdepth.hh" #include "warping.hh" #include "medianfilter.hh" #include "ppm.hh" #include "inpainting.hh" #include "merging.hh" #include <ctime> #include <vector> #include <cstdint> using std::int32_t; using std::uint32_t; using std::int16_t; using std::uint16_t; using std::int8_t; using std::uint8_t; void WaSP_predict_depth(view* SAI, view *LF) { /* forward warp depth */ if (SAI->n_depth_references > 0) { printf("Predicting normalized disparity for view %03d_%03d\n", SAI->c, SAI->r); uint16_t **warped_texture_views_0_N = new uint16_t*[SAI->n_depth_references](); uint16_t **warped_depth_views_0_N = new uint16_t*[SAI->n_depth_references](); float **DispTargs_0_N = new float*[SAI->n_depth_references](); init_warping_arrays( SAI->n_depth_references, warped_texture_views_0_N, warped_depth_views_0_N, DispTargs_0_N, SAI->nr, SAI->nc, SAI->ncomp); for (int32_t ij = 0; ij < SAI->n_depth_references; ij++) { view *ref_view = LF + SAI->depth_references[ij]; int32_t tmp_w, tmp_r, tmp_ncomp; aux_read16PGMPPM( ref_view->path_out_pgm, tmp_w, tmp_r, tmp_ncomp, ref_view->depth); ref_view->color = new uint16_t[ref_view->nr*ref_view->nc * 3](); //aux_read16PGMPPM(ref_view->path_out_ppm, tmp_w, tmp_r, tmp_ncomp, // ref_view->color); warpView0_to_View1( ref_view, SAI, warped_texture_views_0_N[ij], warped_depth_views_0_N[ij], DispTargs_0_N[ij]); delete[](ref_view->depth); delete[](ref_view->color); ref_view->depth = nullptr; ref_view->color = nullptr; } /* merge depth using median*/ //int32_t startt = clock(); double *hole_mask = new double[SAI->nr*SAI->nc](); for (int32_t ij = 0; ij < SAI->nr * SAI->nc; ij++) { hole_mask[ij] = INIT_DISPARITY_VALUE; std::vector<uint16_t> depth_values; for (int32_t uu = 0; uu < SAI->n_depth_references; uu++) { uint16_t *pp = warped_depth_views_0_N[uu]; float *pf = DispTargs_0_N[uu]; if (*(pf + ij) > INIT_DISPARITY_VALUE) { depth_values.push_back(*(pp + ij)); } } if (depth_values.size() > 0) { SAI->depth[ij] = getMedian(depth_values); hole_mask[ij] = 1.0f; } } uint32_t nholes = holefilling( SAI->depth, SAI->nr, SAI->nc, INIT_DISPARITY_VALUE, hole_mask); delete[](hole_mask); clean_warping_arrays( SAI->n_depth_references, warped_texture_views_0_N, warped_depth_views_0_N, DispTargs_0_N); } }
31.739437
87
0.607278
astolap
5dce530424b87c168b126ff86d52f7deab82eb32
375
hpp
C++
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
#pragma once #include "texture_types.hpp" namespace raycaster { texture load_texture(const char *filepath); const uint8_t *texture_get_image(texture t); uint32_t texture_get_width(texture t); uint32_t texture_get_height(texture t); uint32_t texture_get_channels(texture t); uint32_t texture_get_size(texture t); void destroy_texture(texture t); } // namespace raycaster
22.058824
44
0.810667
Honeybunch
5dd64d69ad3c1f2f10e2bf5a0ac37c5b54f116ce
11,478
cpp
C++
quic/congestion_control/test/PacerTest.cpp
Shikugawa/mvfst-quicbench
5c6bb05cb5b9810bf1afddc5fe168d6b220bcd1d
[ "MIT" ]
null
null
null
quic/congestion_control/test/PacerTest.cpp
Shikugawa/mvfst-quicbench
5c6bb05cb5b9810bf1afddc5fe168d6b220bcd1d
[ "MIT" ]
1
2022-03-08T19:07:06.000Z
2022-03-08T19:07:06.000Z
quic/congestion_control/test/PacerTest.cpp
Shikugawa/mvfst-quicbench
5c6bb05cb5b9810bf1afddc5fe168d6b220bcd1d
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/congestion_control/Pacer.h> #include <folly/portability/GTest.h> #include <quic/congestion_control/TokenlessPacer.h> #include <quic/state/test/MockQuicStats.h> #include <quic/state/test/Mocks.h> using namespace testing; namespace quic { namespace test { class TokenlessPacerTest : public Test { public: void SetUp() override { conn.transportSettings.pacingTimerTickInterval = 1us; } protected: QuicConnectionStateBase conn{QuicNodeType::Client}; TokenlessPacer pacer{conn, conn.transportSettings.minCwndInMss}; }; TEST_F(TokenlessPacerTest, RateCalculator) { pacer.setPacingRateCalculator([](const QuicConnectionStateBase&, uint64_t, uint64_t, std::chrono::microseconds) { return PacingRate::Builder().setInterval(1234us).setBurstSize(4321).build(); }); pacer.refreshPacingRate(200000, 200us); EXPECT_EQ(0us, pacer.getTimeUntilNextWrite()); EXPECT_EQ(4321, pacer.updateAndGetWriteBatchSize(Clock::now())); EXPECT_NEAR(1234, pacer.getTimeUntilNextWrite().count(), 100); } TEST_F(TokenlessPacerTest, NoCompensateTimerDrift) { pacer.setPacingRateCalculator([](const QuicConnectionStateBase&, uint64_t, uint64_t, std::chrono::microseconds) { return PacingRate::Builder().setInterval(1000us).setBurstSize(10).build(); }); auto currentTime = Clock::now(); pacer.refreshPacingRate(20, 100us); // These two values do not matter here EXPECT_EQ(10, pacer.updateAndGetWriteBatchSize(currentTime + 1000us)); EXPECT_EQ(10, pacer.updateAndGetWriteBatchSize(currentTime + 2000us)); } TEST_F(TokenlessPacerTest, CompensateTimerDriftForExperimental) { auto mockCongestionController = std::make_unique<MockCongestionController>(); auto rawCongestionController = mockCongestionController.get(); conn.congestionController = std::move(mockCongestionController); EXPECT_CALL(*rawCongestionController, isAppLimited()) .WillRepeatedly(Return(false)); auto mockStats = std::make_shared<MockQuicStats>(); conn.statsCallback = mockStats.get(); // This should be called for two of the three updateAndGetWriteBatchSize calls // below. EXPECT_CALL(*mockStats, onPacerTimerLagged()).Times(2); pacer.setPacingRateCalculator([](const QuicConnectionStateBase&, uint64_t, uint64_t, std::chrono::microseconds) { return PacingRate::Builder().setInterval(1000us).setBurstSize(10).build(); }); pacer.setExperimental(true); auto currentTime = Clock::now(); pacer.refreshPacingRate(20, 100us); // These two values do not matter here EXPECT_EQ(10, pacer.updateAndGetWriteBatchSize(currentTime + 1000us)); // 2 intervals later should return twice the burst size EXPECT_EQ(20, pacer.updateAndGetWriteBatchSize(currentTime + 3000us)); // 6 intervals later should only return 50 (maxBurstInterval * 10) EXPECT_EQ(50, pacer.updateAndGetWriteBatchSize(currentTime + 9000us)); } TEST_F(TokenlessPacerTest, NextWriteTime) { EXPECT_EQ(0us, pacer.getTimeUntilNextWrite()); pacer.setPacingRateCalculator([](const QuicConnectionStateBase&, uint64_t, uint64_t, std::chrono::microseconds rtt) { return PacingRate::Builder().setInterval(rtt).setBurstSize(10).build(); }); pacer.refreshPacingRate(20, 1000us); // Right after refresh, it's always 0us. You can always send right after an // ack. EXPECT_EQ(0us, pacer.getTimeUntilNextWrite()); EXPECT_EQ(10, pacer.updateAndGetWriteBatchSize(Clock::now())); // Then we use real delay: EXPECT_NEAR(1000, pacer.getTimeUntilNextWrite().count(), 100); } TEST_F(TokenlessPacerTest, RttFactor) { auto realRtt = 100ms; bool calculatorCalled = false; pacer.setRttFactor(1, 2); pacer.setPacingRateCalculator([&](const QuicConnectionStateBase&, uint64_t, uint64_t, std::chrono::microseconds rtt) { EXPECT_EQ(rtt, realRtt / 2); calculatorCalled = true; return PacingRate::Builder().setInterval(rtt).setBurstSize(10).build(); }); pacer.refreshPacingRate(20, realRtt); EXPECT_TRUE(calculatorCalled); } TEST_F(TokenlessPacerTest, ImpossibleToPace) { conn.transportSettings.pacingTimerTickInterval = 1ms; pacer.setPacingRateCalculator([](const QuicConnectionStateBase& conn, uint64_t cwndBytes, uint64_t, std::chrono::microseconds rtt) { return PacingRate::Builder() .setInterval(rtt) .setBurstSize(cwndBytes / conn.udpSendPacketLen) .build(); }); pacer.refreshPacingRate(200 * conn.udpSendPacketLen, 100us); EXPECT_EQ(0us, pacer.getTimeUntilNextWrite()); EXPECT_EQ( conn.transportSettings.writeConnectionDataPacketsLimit, pacer.updateAndGetWriteBatchSize(Clock::now())); } TEST_F(TokenlessPacerTest, ChangeMaxPacingRate) { int calculatorCallCount = 0; pacer.setPacingRateCalculator([&calculatorCallCount]( const QuicConnectionStateBase& conn, uint64_t cwndBytes, uint64_t, std::chrono::microseconds rtt) { calculatorCallCount++; return PacingRate::Builder() .setInterval(rtt) .setBurstSize(cwndBytes / conn.udpSendPacketLen) .build(); }); auto rtt = 500 * 1000us; auto timestamp = Clock::now(); // Request pacing at 50 Mbps pacer.refreshPacingRate(3125000, rtt); EXPECT_EQ(1, calculatorCallCount); EXPECT_EQ( 3125000 / kDefaultUDPSendPacketLen, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(rtt.count(), pacer.getTimeUntilNextWrite(timestamp).count()); // Set max pacing rate to 40 Mbps pacer.setMaxPacingRate(5 * 1000 * 1000u); // Bytes per second // This should bring down the pacer rate to 40 Mbps EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); auto burst = pacer.updateAndGetWriteBatchSize(timestamp); auto interval = pacer.getTimeUntilNextWrite(timestamp); uint64_t pacerRate = burst * kDefaultUDPSendPacketLen * std::chrono::seconds{1} / interval; EXPECT_EQ(5 * 1000 * 1000u, pacerRate); pacer.reset(); // Requesting a rate of 50 Mbps should not change interval or burst pacer.refreshPacingRate(3125000, rtt); EXPECT_EQ(1, calculatorCallCount); // Calculator not called again. EXPECT_EQ(burst, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(interval.count(), pacer.getTimeUntilNextWrite(timestamp).count()); pacer.reset(); // The setPacingRate API shouldn't make changes either pacer.setPacingRate(6250 * 1000u); // 50 Mbps EXPECT_EQ(burst, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(interval.count(), pacer.getTimeUntilNextWrite(timestamp).count()); pacer.reset(); // Increasing max pacing rate to 75 Mbps shouldn't make changes pacer.setMaxPacingRate(9375 * 1000u); EXPECT_EQ(burst, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(interval.count(), pacer.getTimeUntilNextWrite(timestamp).count()); pacer.reset(); // Increase pacing to 50 Mbps and ensure it takes effect pacer.refreshPacingRate(3125000, rtt); EXPECT_EQ(2, calculatorCallCount); // Calculator called EXPECT_EQ( 3125000 / kDefaultUDPSendPacketLen, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(rtt.count(), pacer.getTimeUntilNextWrite(timestamp).count()); pacer.reset(); // Increase pacing to 80 Mbps using alternative API and ensure rate is limited // to 75 Mbps pacer.setPacingRate(10 * 1000 * 1000u); burst = pacer.updateAndGetWriteBatchSize(timestamp); interval = pacer.getTimeUntilNextWrite(timestamp); pacerRate = burst * kDefaultUDPSendPacketLen * std::chrono::seconds{1} / interval; EXPECT_NEAR(9375 * 1000u, pacerRate, 1000); // To accommodate rounding } TEST_F(TokenlessPacerTest, SetMaxPacingRateOnUnlimitedPacer) { auto timestamp = Clock::now(); // Pacing is currently not pacing EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); EXPECT_NE(0, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); // Set max pacing rate 40 Mbps and ensure it took effect pacer.setMaxPacingRate(5 * 1000 * 1000u); // Bytes per second EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); auto burst = pacer.updateAndGetWriteBatchSize(timestamp); auto interval = pacer.getTimeUntilNextWrite(timestamp); uint64_t pacerRate = burst * kDefaultUDPSendPacketLen * std::chrono::seconds{1} / interval; EXPECT_NEAR(5 * 1000 * 1000u, pacerRate, 1000); // To accommodate rounding } TEST_F(TokenlessPacerTest, SetZeroPacingRate) { auto timestamp = Clock::now(); // A Zero pacing rate should not result in a divide-by-zero conn.transportSettings.pacingTimerTickInterval = 1000us; pacer.setPacingRate(0); EXPECT_EQ(0, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(1000, pacer.getTimeUntilNextWrite(timestamp).count()); } TEST_F(TokenlessPacerTest, RefreshPacingRateWhenRTTIsZero) { auto timestamp = Clock::now(); // rtt=0 should not result in a divide-by-zero conn.transportSettings.pacingTimerTickInterval = 1000us; pacer.refreshPacingRate(100, 0us); // Verify burst is writeConnectionDataPacketsLimit and interval is // 0us right after writing EXPECT_EQ( conn.transportSettings.writeConnectionDataPacketsLimit, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); } TEST_F(TokenlessPacerTest, RefreshPacingRateWhenRTTIsDefault) { auto timestamp = Clock::now(); auto tick = 1000us; pacer.setPacingRateCalculator([](const QuicConnectionStateBase&, uint64_t cwnd, uint64_t, std::chrono::microseconds rtt) { return PacingRate::Builder().setInterval(rtt).setBurstSize(cwnd).build(); }); conn.transportSettings.pacingTimerTickInterval = tick; // rtt=kDefaultMinRTT should result in this update being skipped // There should be no pacing. Interval and Burst should use the defaults pacer.refreshPacingRate(100, kDefaultMinRtt); EXPECT_EQ( conn.transportSettings.writeConnectionDataPacketsLimit, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(0us, pacer.getTimeUntilNextWrite(timestamp)); // This won't be skipped pacer.refreshPacingRate( 20, tick); // writes these values to the burst and interval directly EXPECT_EQ(20, pacer.updateAndGetWriteBatchSize(timestamp)); EXPECT_EQ(tick, pacer.getTimeUntilNextWrite(timestamp)); // rtt=kDefaultMinRTT should result in this update being skipped // Interval should not change. pacer.refreshPacingRate(100, kDefaultMinRtt); EXPECT_EQ(tick, pacer.getTimeUntilNextWrite(timestamp)); } } // namespace test } // namespace quic
40.273684
80
0.701429
Shikugawa
5dd72157657a7f90b29c9333a51eb5164b604f4c
2,612
cpp
C++
modules/core/src/named_output_pipe.cpp
tizenorg/platform.framework.web.wrt-commons
5835a89c8b013c00b828fecf04f423adc9e5d561
[ "Apache-2.0" ]
null
null
null
modules/core/src/named_output_pipe.cpp
tizenorg/platform.framework.web.wrt-commons
5835a89c8b013c00b828fecf04f423adc9e5d561
[ "Apache-2.0" ]
null
null
null
modules/core/src/named_output_pipe.cpp
tizenorg/platform.framework.web.wrt-commons
5835a89c8b013c00b828fecf04f423adc9e5d561
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @file named_output_pipe.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 * @brief This file is the implementation file of named output pipe */ #include <dpl/named_output_pipe.h> #include <dpl/binary_queue.h> #include <dpl/scoped_free.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> namespace DPL { NamedOutputPipe::NamedOutputPipe() : m_fifo(-1) { } NamedOutputPipe::~NamedOutputPipe() { Close(); } void NamedOutputPipe::Open(const std::string& pipeName) { // Then open it for reading or writing int fifo = TEMP_FAILURE_RETRY(open(pipeName.c_str(), O_WRONLY | O_NONBLOCK)); if (fifo == -1) ThrowMsg(Exception::OpenFailed, pipeName); m_fifo = fifo; } void NamedOutputPipe::Close() { if (m_fifo == -1) return; if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1) Throw(Exception::CloseFailed); m_fifo = -1; } size_t NamedOutputPipe::Write(const BinaryQueue &buffer, size_t bufferSize) { // Adjust write size if (bufferSize > buffer.Size()) bufferSize = buffer.Size(); // FIXME: User write visitor to write ! // WriteVisitor visitor ScopedFree<void> flattened(malloc(bufferSize)); buffer.Flatten(flattened.Get(), bufferSize); ssize_t result = TEMP_FAILURE_RETRY(write(m_fifo, flattened.Get(), bufferSize)); if (result > 0) { // Successfuly written some bytes return static_cast<size_t>(result); } else if (result == 0) { // This is abnormal result ThrowMsg(CommonException::InternalError, "Invalid socket write result, 0 bytes written"); } else { // Interpret error result // FIXME: Handle errno Throw(AbstractOutput::Exception::WriteFailed); } } int NamedOutputPipe::WaitableWriteHandle() const { return m_fifo; } } // namespace DPL
25.607843
97
0.667305
tizenorg
5dd761884638a68e07ba43e0773063c7e933c7ec
1,969
cc
C++
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
23
2017-03-11T16:44:14.000Z
2022-02-10T13:31:03.000Z
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
32
2018-01-31T11:11:16.000Z
2022-03-03T14:37:58.000Z
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
17
2017-08-02T15:59:25.000Z
2022-02-10T13:31:06.000Z
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ #include <string> #include <stdio.h> #include "../simworld.h" #include "load_relief_frame.h" #include "welt.h" #include "simwin.h" #include "../dataobj/translator.h" #include "../dataobj/settings.h" #include "../dataobj/environment.h" #include "../dataobj/height_map_loader.h" /** * Action, started on button pressing */ bool load_relief_frame_t::item_action(const char *fullpath) { sets->heightfield = fullpath; if (gui_frame_t *new_world_gui = win_get_magic( magic_welt_gui_t )) { static_cast<welt_gui_t*>(new_world_gui)->update_preview(true); } return false; } load_relief_frame_t::load_relief_frame_t(settings_t* const sets) : savegame_frame_t( NULL, false, "maps/", env_t::show_delete_buttons ) { new_format.init( button_t::square_automatic, "Maximize height levels"); new_format.pressed = env_t::new_height_map_conversion; bottom_left_frame.add_component( &new_format ); const std::string extra_path = env_t::program_dir + env_t::objfilename + "maps/"; this->add_path(extra_path.c_str()); set_name(translator::translate("Lade Relief")); this->sets = sets; sets->heightfield = ""; } const char *load_relief_frame_t::get_info(const char *fullpath) { static char size[64]; sint16 w, h; sint8 *h_field ; height_map_loader_t hml(new_format.pressed); if(hml.get_height_data_from_file(fullpath, (sint8)sets->get_groundwater(), h_field, w, h, true )) { sprintf( size, "%i x %i", w, h ); env_t::new_height_map_conversion = new_format.pressed; return size; } return ""; } bool load_relief_frame_t::check_file( const char *fullpath, const char * ) { sint16 w, h; sint8 *h_field; height_map_loader_t hml(new_format.pressed); if(hml.get_height_data_from_file(fullpath, (sint8)sets->get_groundwater(), h_field, w, h, true )) { return w>0 && h>0; env_t::new_height_map_conversion = new_format.pressed; } return false; }
25.907895
135
0.731336
soukouki
5de06650f8ac14307b254df239aeb0ef406a1352
378
cpp
C++
codeforces/Div2/CS204/Lab1/q2.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
codeforces/Div2/CS204/Lab1/q2.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
codeforces/Div2/CS204/Lab1/q2.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct city { /* data */ string city; int x,y; }; int noOfCities=0; city DbUsingarray[5000]; void insertRecordInDb1(string s,int x,int y){ DbUsingarray[++noOfCities].city=s; DbUsingarray[noOfCities].x=x; DbUsingarray[noOfCities].y=y; } void deleteCityString(string s){ } int main(){ }
13.034483
45
0.637566
jeevanpuchakay
5de0866d172736958bd7f785d6d2b2f265c6201b
495
hpp
C++
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
7
2019-06-09T03:52:14.000Z
2020-03-01T13:27:24.000Z
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
27
2019-12-28T12:29:12.000Z
2022-03-02T04:08:55.000Z
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
2
2019-11-29T22:32:47.000Z
2021-02-18T23:47:47.000Z
#define HANDLER void #define EOSIO_DISPATCH_VAPAEE( TYPE, MEMBERS, HANDLERS ) \ extern "C" { \ void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \ if( code == receiver ) { \ switch( action ) { \ EOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \ } \ } \ name handler = eosio::name(string("h") + eosio::name(action).to_string()); \ switch( handler.value ) { \ EOSIO_DISPATCH_HELPER( TYPE, HANDLERS ) \ } \ } \ } \
30.9375
82
0.567677
vapaee
5de18f2b8e19e5f3e560b6afae3f6c584c0624e2
1,697
cpp
C++
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarth/TextureCompositor> #include <osgEarth/Registry> #include <osgEarth/Capabilities> using namespace osgEarth; #define LC "[TextureCompositor] " TextureCompositor::TextureCompositor() { //nop } bool TextureCompositor::reserveTextureImageUnit(int& out_unit) { out_unit = -1; unsigned maxUnits = osgEarth::Registry::instance()->getCapabilities().getMaxGPUTextureUnits(); Threading::ScopedMutexLock exclusiveLock( _reservedUnitsMutex ); for( unsigned i=0; i<maxUnits; ++i ) { if (_reservedUnits.find(i) == _reservedUnits.end()) { _reservedUnits.insert( i ); out_unit = i; return true; } } return false; } void TextureCompositor::releaseTextureImageUnit(int unit) { Threading::ScopedMutexLock exclusiveLock( _reservedUnitsMutex ); _reservedUnits.erase( unit ); }
28.762712
98
0.709487
energonQuest
5de59b6b8ea6c93ea369034f0d20254884e58cc9
931
hpp
C++
Includes/Components/Renderer/Utils.hpp
Snowapril/YachtSimulator
534cce6401f64b29fd4e6ded6c04836bae0f15fb
[ "MIT" ]
4
2021-06-03T11:00:47.000Z
2021-07-15T11:01:07.000Z
Includes/Components/Renderer/Utils.hpp
Snowapril/YachtSimulator
534cce6401f64b29fd4e6ded6c04836bae0f15fb
[ "MIT" ]
null
null
null
Includes/Components/Renderer/Utils.hpp
Snowapril/YachtSimulator
534cce6401f64b29fd4e6ded6c04836bae0f15fb
[ "MIT" ]
2
2021-10-12T07:16:24.000Z
2022-01-29T08:06:08.000Z
#ifndef UTILS_HPP #define UTILS_HPP #include <vulkan/vulkan.h> #include <Components/Common/Logger.hpp> #include <cassert> #include <string> namespace Renderer { //! Returns VkResult error code as a string std::string ErrorToString(VkResult result); //! Check given VkResult is success or not //! If failed, print error code and abort program #define VK_CHECK_ERROR(result, message) \ { \ if (result) \ { \ LOG_ERROR << '(' << ErrorToString(result) << ") " << message; \ std::abort(); \ } \ } }; // namespace Renderer #endif //! UTILS_HPP
35.807692
75
0.407089
Snowapril
5de81372c4ff0fa17b5851ca48828317269fde1f
2,496
cc
C++
cpp/art/scoped_thread_state_change.cc
fettdrac/ArtHook
76205461bbc620e9d516cbfa317c459e9e4620e6
[ "Apache-2.0" ]
23
2019-08-13T04:55:20.000Z
2021-12-21T13:28:49.000Z
cpp/art/scoped_thread_state_change.cc
fettdrac/ArtHook
76205461bbc620e9d516cbfa317c459e9e4620e6
[ "Apache-2.0" ]
1
2021-07-04T16:08:49.000Z
2021-07-04T16:08:49.000Z
cpp/art/scoped_thread_state_change.cc
fettdrac/ArtHook
76205461bbc620e9d516cbfa317c459e9e4620e6
[ "Apache-2.0" ]
4
2019-08-22T01:49:11.000Z
2021-09-15T14:30:54.000Z
#include "scoped_thread_state_change.h" #include "../base/log.h" #include "../base/jni_helper.h" #include "ARTSymbol.h" namespace whale { namespace art { static volatile long kNoGCDaemonsGuard = 0; jclass ScopedNoGCDaemons::java_lang_Daemons; jmethodID ScopedNoGCDaemons::java_lang_Daemons_start; jmethodID ScopedNoGCDaemons::java_lang_Daemons_stop; void ScopedNoGCDaemons::Load(JNIEnv *env) { java_lang_Daemons = reinterpret_cast<jclass>(env->NewGlobalRef( env->FindClass("java/lang/Daemons"))); if (java_lang_Daemons == nullptr) { JNIExceptionClear(env); LOGE("java/lang/Daemons API is unavailable."); return; } java_lang_Daemons_start = env->GetStaticMethodID(java_lang_Daemons, "start", "()V"); if (java_lang_Daemons_start == nullptr) { JNIExceptionClear(env); java_lang_Daemons_start = env->GetStaticMethodID(java_lang_Daemons, "startPostZygoteFork", "()V"); } if (java_lang_Daemons_start == nullptr) { LOGE("java/lang/Daemons API is available but no start/startPostZygoteFork method."); JNIExceptionClear(env); } java_lang_Daemons_stop = env->GetStaticMethodID(java_lang_Daemons, "stop", "()V"); JNIExceptionClear(env); } ScopedNoGCDaemons::ScopedNoGCDaemons(JNIEnv *env) : env_(env) { if (java_lang_Daemons_start != nullptr) { if (__sync_sub_and_fetch(&kNoGCDaemonsGuard, 1) <= 0) { env_->CallStaticVoidMethod(java_lang_Daemons, java_lang_Daemons_stop); JNIExceptionClear(env_); } } } ScopedNoGCDaemons::~ScopedNoGCDaemons() { if (java_lang_Daemons_stop != nullptr) { if (__sync_add_and_fetch(&kNoGCDaemonsGuard, 1) == 1) { env_->CallStaticVoidMethod(java_lang_Daemons, java_lang_Daemons_start); JNIExceptionClear(env_); } } } ScopedSuspendAll::ScopedSuspendAll() { ManualControl(true); } ScopedSuspendAll::~ScopedSuspendAll() { ManualControl(false); } void ScopedSuspendAll::ManualControl(bool suspend) { ArtSymbolList *symbols = ARTSymbol::GetSymbol(); bool supported=(symbols->suspend_vm && symbols->resume_vm); if (!supported) { LOGE("Suspend VM API is unavailable."); return; } if(suspend) { symbols->suspend_vm(); }else{ symbols->resume_vm(); } } } // namespace art } // namespace whale
30.439024
98
0.654647
fettdrac
5de81bd593ea23d921b914f76e6e658d904aa090
475
cpp
C++
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <QByteArray> #include <zlib.h> #include "alerts/zlipWrapper/CCRC.hpp" template <class T> unsigned long CCRC::calc(const T& data, int offset, int endOffset) { unsigned long crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, reinterpret_cast<const unsigned char *>( data.data() + offset), data.size()- offset - endOffset); return crc; } template unsigned long CCRC::calc( const QByteArray&, int, int);
23.75
79
0.644211
ymuv
5de87638ebd72dc517076c2a159d070c8504250a
2,972
cpp
C++
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
2
2018-02-28T06:57:08.000Z
2018-02-28T06:57:37.000Z
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
2
2018-10-06T18:29:44.000Z
2018-10-07T16:46:04.000Z
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
1
2019-10-14T05:28:17.000Z
2019-10-14T05:28:17.000Z
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/packet/ICMPHdr.h" /* * References: * https://code.google.com/p/googletest/wiki/Primer * https://code.google.com/p/googletest/wiki/AdvancedGuide */ #include <gtest/gtest.h> #include <folly/IPAddress.h> #include <folly/IPAddressV6.h> #include <folly/io/Cursor.h> #include "fboss/agent/hw/mock/MockRxPacket.h" using namespace facebook::fboss; using folly::IPAddress; using folly::IPAddressV6; using folly::io::Cursor; using std::string; TEST(ICMPHdrTest, default_constructor) { ICMPHdr icmpv6Hdr; EXPECT_EQ(0, icmpv6Hdr.type); EXPECT_EQ(0, icmpv6Hdr.code); EXPECT_EQ(0, icmpv6Hdr.csum); } TEST(ICMPHdrTest, copy_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs(lhs); EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, parameterized_data_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); EXPECT_EQ(type, lhs.type); EXPECT_EQ(code, lhs.code); EXPECT_EQ(csum, lhs.csum); } TEST(ICMPHdrTest, cursor_data_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong auto pkt = MockRxPacket::fromHex( // ICMPv6 Header "80" // Type: Echo Request "00" // Code: 0 "00 00" // Checksum ); Cursor cursor(pkt->buf()); ICMPHdr icmpv6Hdr(cursor); EXPECT_EQ(type, icmpv6Hdr.type); EXPECT_EQ(code, icmpv6Hdr.code); EXPECT_EQ(csum, icmpv6Hdr.csum); } TEST(ICMPHdrTest, cursor_data_constructor_too_small) { auto pkt = MockRxPacket::fromHex( // ICMPv6 Header "80" // Type: Echo Request "00" // Code: 0 "00 " // OOPS! One octet too small! ); Cursor cursor(pkt->buf()); EXPECT_THROW({ICMPHdr icmpv6Hdr(cursor);}, HdrParseError); } TEST(ICMPHdrTest, assignment_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs = lhs; EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, equality_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 02; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs(type, code, csum); EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, inequality_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum1 = 0; // Obviously wrong uint16_t csum2 = 1; // Obviously wrong ICMPHdr lhs(type, code, csum1); ICMPHdr rhs(type, code, csum2); EXPECT_NE(lhs, rhs); }
26.535714
79
0.702557
vitaliy-senchyshyn
5de996fa4d288cf20fa94093dc1352dea15f8d33
7,167
cpp
C++
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
25
2015-04-07T23:13:49.000Z
2021-09-27T08:03:53.000Z
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
42
2015-04-27T03:12:48.000Z
2018-05-08T13:53:39.000Z
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
8
2015-04-26T06:29:01.000Z
2021-05-27T09:50:03.000Z
#include <assert.h> #include <common-ee.h> #include <string.h> #include <timer.h> #include "test_runner.h" static const bool DEBUG_TEST_RUNNER = false; static u32 vu_reg_pos = 0x100; // 16 integer regs, 32 float regs, 3 status regs. static u32 vu_reg_size = 16 * (16 + 32 + 3); static u8 *const vu0_reg_mem = vu0_mem + vu_reg_pos; static u8 *const vu1_reg_mem = vu1_mem + vu_reg_pos; // Helper to "sleep" the ee for a few ticks (less than a second.) // This is used to wait for the vu test to finish. // We don't use interlock in case it stalls. static void delay_ticks(int t) { u32 goal = cpu_ticks() + t; while (cpu_ticks() < goal) { continue; } } // Determine whether the specified vu is running or not. static bool vu_running(int vu) { // Must be 0 or 1. Change to 0 or (1 << 8). u32 mask = vu == 0 ? 1 : (1 << 8); u32 stat; asm volatile ( "cfc2 %0, $29" : "=r"(stat) ); return (stat & mask) != 0; } void TestRunner::Execute() { // Just to be sure. RunnerExit(); InitRegisters(); InitFlags(); if (vu_ == 1) { if (DEBUG_TEST_RUNNER) { printf("Calling vu0 code.\n"); } asm volatile ( // This writes to cmsar1 ($31). The program is simply at 0. "ctc2 $0, $31\n" ); } else { if (DEBUG_TEST_RUNNER) { printf("Calling vu0 code.\n"); } asm volatile ( // Actually call the microcode. "vcallms 0\n" ); } if (DEBUG_TEST_RUNNER) { printf("Waiting for vu to finish.\n"); } // Spin while waiting for the vu unit to finish. u32 max_ticks = cpu_ticks() + 100000; while (vu_running(vu_)) { if (cpu_ticks() > max_ticks) { printf("ERROR: Timed out waiting for vu code to finish.\n"); // TODO: Force stop? break; } delay_ticks(200); } if (DEBUG_TEST_RUNNER && !vu_running(vu_)) { printf("Finished with vu code.\n"); } } void TestRunner::RunnerExit() { using namespace VU; // The goal here is to store all the registers from the VU side. // This way we're not testing register transfer, we're testing VU interaction. // Issues with spilling may be more obvious this way. // First, integers. u32 pos = vu_reg_pos / 16; for (int i = 0; i < 16; ++i) { Wr(ISW(DEST_XYZW, Reg(VI00 + i), VI00, pos++)); } // Then floats. Wr(IADDIU(VI02, VI00, pos)); for (int i = 0; i < 32; ++i) { Wr(SQ(DEST_XYZW, Reg(VF00 + i), VI00, pos++)); } // Lastly, flags (now that we've saved integers.) Wr(FCGET(VI01)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); Wr(FMOR(VI01, VI00)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); Wr(FSOR(VI01, 0)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); // And actually write an exit (just two NOPs, the first with an E bit.) SafeExit(); if (DEBUG_TEST_RUNNER) { printf("Emitted exit code.\n"); } } void TestRunner::InitRegisters() { // Clear the register state (which will be set by the code run in RunnerExit.) if (vu_ == 1) { memset(vu1_reg_mem, 0xCC, vu_reg_size); } else { memset(vu0_reg_mem, 0xCC, vu_reg_size); } } void TestRunner::InitFlags() { // Grab the previous values. asm volatile ( // Try to clear them first, if possible. "vnop\n" "ctc2 $0, $16\n" "ctc2 $0, $17\n" "ctc2 $0, $18\n" // Then read. "vnop\n" "cfc2 %0, $16\n" "cfc2 %1, $17\n" "cfc2 %2, $18\n" : "=&r"(status_), "=&r"(mac_), "=&r"(clipping_) ); if (clipping_ != 0) { printf("WARNING: Clipping flag was not cleared.\n"); } } u16 TestRunner::GetValueAddress(const u32 *val) { u16 ptr = 0; if (vu_ == 0) { assert(val >= (u32 *)vu0_mem && val < (u32 *)(vu0_mem + vu0_mem_size)); ptr = ((u8 *)val - vu0_mem) / 16; } else { assert(val >= (u32 *)vu1_mem && val < (u32 *)(vu1_mem + vu1_mem_size)); ptr = ((u8 *)val - vu1_mem) / 16; } return ptr; } void TestRunner::WrLoadFloatRegister(VU::Dest dest, VU::Reg r, const u32 *val) { using namespace VU; assert(r >= VF00 && r <= VF31); u16 ptr = GetValueAddress(val); if ((ptr & 0x3FF) == ptr) { Wr(LQ(dest, r, VI00, ptr)); } else { // This shouldn't happen? Even with 16kb, all reads should be < 0x400. printf("Unhandled pointer load."); assert(false); } } void TestRunner::WrSetIntegerRegister(VU::Reg r, u32 v) { using namespace VU; assert(r >= VI00 && r <= VI15); assert((v & 0xFFFF) == v); // Except for 0x8000, we can get to everything with one op. if (v == 0x8000) { Wr(IADDI(r, VI00, -1)); Wr(ISUBIU(r, r, 0x7FFF)); } else if (v & 0x8000) { Wr(ISUBIU(r, VI00, v & ~0x8000)); } else { Wr(IADDIU(r, VI00, v)); } } void TestRunner::WrLoadIntegerRegister(VU::Dest dest, VU::Reg r, const u32 *val) { using namespace VU; assert(r >= VI00 && r <= VI15); u16 ptr = GetValueAddress(val); if ((ptr & 0x3FF) == ptr) { Wr(ILW(dest, r, VI00, ptr)); } else { // This shouldn't happen? Even with 16kb, all reads should be < 0x400. printf("Unhandled pointer load."); assert(false); } } void TestRunner::PrintRegister(VU::Reg r, bool newline) { using namespace VU; if (r >= VI00 && r <= VI15) { PrintIntegerRegister(r - VI00); } else { PrintVectorRegister(r); } if (newline) { printf("\n"); } } void TestRunner::PrintIntegerRegister(int i) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // The integer registers are first, so it's just at the specified position. const u32 *p = (const u32 *)(regs + 16 * i); printf("%04x", *p); } union FloatBits { float f; u32 u; }; static inline void printFloatString(const FloatBits &bits) { // We want -0.0 and -NAN to show as negative. // So, let's just print the sign manually with an absolute value. FloatBits positive = bits; positive.u &= ~0x80000000; char sign = '+'; if (bits.u & 0x80000000) { sign = '-'; } printf("%c%0.2f", sign, positive.f); } static inline void printFloatBits(const FloatBits &bits) { printf("%08x/", bits.u); printFloatString(bits); } void TestRunner::PrintRegisterField(VU::Reg r, VU::Field field, bool newline) { using namespace VU; assert(r >= VF00 && r <= VF31); const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + r)); printFloatBits(p[field]); if (newline) { printf("\n"); } } void TestRunner::PrintVectorRegister(int i) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // Skip the 16 integer registers, and jump to the vector. const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + i)); // Let's just print each lane separated by a space. printFloatBits(p[0]); printf(" "); printFloatBits(p[1]); printf(" "); printFloatBits(p[2]); printf(" "); printFloatBits(p[3]); } void TestRunner::PrintStatus(bool newline) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // Skip 16 integer regs and 32 vector regs, to get a base for the status regs. const u32 *flags = (const u32 *)(regs + 16 * (16 + 32)); // Note that they are spaced out by 16 bytes (4 words.) u32 clipping = flags[0]; u32 mac = flags[4]; u32 status = flags[8]; if (status == status_ && mac == mac_ && clipping == clipping_) { printf(" (no flag changes)"); } else { printf(" st=+%04x,-%04x, mac=+%04x,-%04x, clip=%08x", status & ~status_, ~status & status_, mac & ~mac_, ~mac & mac_, clipping); } if (newline) { printf("\n"); } }
23.89
130
0.629273
unknownbrackets
5de9ebb1b258d1e6ae6c5592bbc939400e6b58e2
9,930
hpp
C++
include/lvr2/attrmaps/StableVector.hpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
1
2019-08-07T03:55:27.000Z
2019-08-07T03:55:27.000Z
include/lvr2/attrmaps/StableVector.hpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
null
null
null
include/lvr2/attrmaps/StableVector.hpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL University Osnabrück 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. */ /* * StableVector.hpp * * @date 08.06.2017 * @author Johan M. von Behren <johan@vonbehren.eu> */ #ifndef LVR2_ATTRMAPS_STABLEVECTOR_H_ #define LVR2_ATTRMAPS_STABLEVECTOR_H_ #include <vector> #include <utility> #include <boost/optional.hpp> #include <boost/shared_array.hpp> using std::move; using std::vector; using boost::optional; #include <lvr2/util/BaseHandle.hpp> #include <lvr2/geometry/Handles.hpp> namespace lvr2 { /** * @brief Iterator over handles in this vector, which skips deleted elements * * Important: This is NOT a fail fast iterator. If the vector is changed while * using an instance of this iterator the behavior is undefined! */ template<typename HandleT, typename ElemT> class StableVectorIterator { private: /// Reference to the deleted marker array this iterator belongs to const vector<optional<ElemT>>* m_elements; /// Current position in the vector size_t m_pos; public: StableVectorIterator(const vector<optional<ElemT>>* deleted, bool startAtEnd = false); StableVectorIterator& operator=(const StableVectorIterator& other); bool operator==(const StableVectorIterator& other) const; bool operator!=(const StableVectorIterator& other) const; StableVectorIterator& operator++(); bool isAtEnd() const; HandleT operator*() const; }; /** * @brief A vector which guarantees stable indices and features O(1) deletion. * * This is basically a wrapper for the std::vector, which marks an element as * deleted but does not actually delete it. This means that indices are never * invalidated. When inserting an element, you get its index (its so called * "handle") back. This handle can later be used to access the element. This * remains true regardless of other insertions and deletions happening in * between. * * USE WITH CAUTION: This NEVER frees memory of deleted values (except on its * own destruction and can get very large if used incorrectly! If deletions in * your use-case are far more numerous than insertions, this data structure is * probably not fitting your needs. The memory requirement of this class is * O(n_p) where n_p is the number of `push()` calls. * * @tparam HandleT This handle type contains the actual index. It has to be * derived from `BaseHandle`! * @tparam ElemT Type of elements in the vector. */ template<typename HandleT, typename ElemT> class StableVector { static_assert( std::is_base_of<BaseHandle<Index>, HandleT>::value, "HandleT must inherit from BaseHandle!" ); public: using ElementType = ElemT; using HandleType = HandleT; /** * @brief Creates an empty StableVector. */ StableVector() : m_usedCount(0) {}; /** * @brief Creates a StableVector with `countElements` many copies of * `defaultValue`. * * The elements are stored contiguously in the vectors, thus the valid * indices of these elements are 0 to `countElements` - 1. */ StableVector(size_t countElements, const ElementType& defaultValue); StableVector(size_t countElements, const boost::shared_array<ElementType>& sharedArray); /** * @brief Adds the given element to the vector. * * @return The handle referring to the inserted element. */ HandleType push(const ElementType& elem); /** * @brief Adds the given element by moving from it. * * @return The handle referring to the inserted element. */ HandleType push(ElementType&& elem); /** * @brief Increases the size of the vector to the length of `upTo`. * * This means that the next call to `push()` after calling `resize(upTo)` * will return exactly the `upTo` handle. All elements that are inserted * by this method are marked as deleted and thus aren't initialized. They * can be set later with `set()`. * * If `upTo` is already a valid handle, this method will panic! */ void increaseSize(HandleType upTo); /** * @brief Increases the size of the vector to the length of `upTo` by * inserting copies of `elem`. * * This means that the next call to `push()` after calling `resize(upTo)` * will return exactly the `upTo` handle. * * If `upTo` is already a valid handle, this method will panic! */ void increaseSize(HandleType upTo, const ElementType& elem); /** * @brief The handle which would be returned by calling `push` now. */ HandleType nextHandle() const; /** * @brief Mark the element behind the given handle as deleted. * * While the element is deleted, the handle stays valid. This means that * trying to obtain the element with this handle later, will always result * in `none` (if `get()` was used). Additionally, the handle can also be * used with the `set()` method. */ void erase(HandleType handle); /** * @brief Removes all elements from the vector. */ void clear(); /** * @brief Returns the element referred to by `handle`. * * Returns `none` if the element was deleted or if the handle is out of * bounds. */ boost::optional<ElementType&> get(HandleType handle); /** * @brief Returns the element referred to by `handle`. * * Returns `none` if the element was deleted or if the handle is out of * bounds. */ boost::optional<const ElementType&> get(HandleType handle) const; /** * @brief Set a value for the existing `handle`. * * In this method, the `handle` has to be valid: it has to be obtained by * a prior `push()` call. If you want to insert a new element, use `push()` * instead of this `set()` method! */ void set(HandleType handle, const ElementType& elem); /** * @brief Set a value for the existing `handle` by moving from `elem`. * * In this method, the `handle` has to be valid: it has to be obtained by * a prior `push()` call. If you want to insert a new element, use `push()` * instead of this `set()` method! */ void set(HandleType handle, ElementType&& elem); /** * @brief Returns the element referred to by `handle`. * * If `handle` is out of bounds or the element was deleted, this method * will throw an exception in debug mode and has UB in release mode. Use * `get()` instead to gracefully handle the absence of an element. */ ElementType& operator[](HandleType handle); /** * @brief Returns the element referred to by `handle`. * * If `handle` is out of bounds or the element was deleted, this method * will throw an exception in debug mode and has UB in release mode. Use * `get()` instead to gracefully handle the absence of an element. */ const ElementType& operator[](HandleType handle) const; /** * @brief Absolute size of the vector (including deleted elements). */ size_t size() const; /** * @brief Number of non-deleted elements. */ size_t numUsed() const; /** * @brief Returns an iterator to the first element of this vector. * * This iterator auto skips deleted elements and returns handles to the * valid elements. */ StableVectorIterator<HandleType, ElementType> begin() const; /** * @brief Returns an iterator to the element after the last element of * this vector. */ StableVectorIterator<HandleType, ElementType> end() const; /** * @brief Increase the capacity of the vector to a value that's greater or * equal to newCap. * * If newCap is greater than the current capacity, new storage is * allocated, otherwise the method does nothing. * * @param newCap new capacity of the vector */ void reserve(size_t newCap); private: /// Count of used elements in elements vector size_t m_usedCount; /// Vector for stored elements vector<optional<ElementType>> m_elements; /** * @brief Assert that the requested handle is not deleted or throw an * exception otherwise. */ void checkAccess(HandleType handle) const; }; } // namespace lvr2 #include <lvr2/attrmaps/StableVector.tcc> #endif /* LVR2_ATTRMAPS_STABLEVECTOR_H_ */
33.661017
92
0.679557
jtpils
5decf23567abe79738db2ccd0ab8f389a42e1458
1,600
hpp
C++
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
null
null
null
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
1
2021-03-16T20:13:58.000Z
2021-03-17T01:04:08.000Z
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <algorithm> #include "../includes/node.hpp" #include "../includes/edge.hpp" #include "../includes/globals.hpp" // int raiz(const int &u, const std::vector<int> &padres){ // if (padres[u] != -1) // return raiz(padres[u], padres); // return u; // } /** * @brief check the root of two nodes and meke them the sema as they are in the same conex component (disjoint sets) * * @param u * @param padres * @return int */ int raiz(const int &u, std::vector<int> & padres){ int p = padres[u]; if (p == -1) return u; else{ int r = raiz(p,padres); padres[u] = r; return r; } } /** * @brief join the roots of two given nodes * * @param u * @param v * @param padres */ void juntar(const int &u, const int &v, std::vector<int> &padres){ padres[raiz(u, padres)] = raiz(v, padres); } /** * @brief executes de mst kruskal * * @return std::vector<edge> */ std::vector<edge> kusrkal(){ std::vector<edge> arbol; std::vector<edge> kruskal_aristas = aristas; std::sort(kruskal_aristas.begin(), kruskal_aristas.end(), compare()); //las ordenamos por peso std::vector<int> padres (vertices.size()); for (auto &elem : padres) elem = -1; int u,v; for (int i = 0; i < kruskal_aristas.size(); ++i){ u = kruskal_aristas[i].nodes[0]; v = kruskal_aristas[i].nodes[1]; if (raiz(u,padres) != raiz(v, padres)){ arbol.push_back(kruskal_aristas[i]); juntar(u,v,padres); } } return arbol; }
24.242424
116
0.575
EMACC99
5df28db94f03945126a46fe651a3622346012c95
2,145
hpp
C++
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
23
2015-03-02T10:56:40.000Z
2021-01-27T03:32:49.000Z
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
73
2015-04-14T09:39:05.000Z
2020-11-11T21:49:10.000Z
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
3
2016-02-22T01:29:32.000Z
2018-01-02T06:07:12.000Z
#pragma once #include <array> #include "vec4.hpp" namespace noob { /* stored like this: 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15 */ template <typename T> struct mat4_type { mat4_type() noexcept(true) = default; mat4_type(T a, T b, T c, T d, T e, T f, T g, T h, T i, T j, T k, T l, T mm, T n, T o, T p) noexcept(true) { m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f; m[6] = g; m[7] = h; m[8] = i; m[9] = j; m[10] = k; m[11] = l; m[12] = mm; m[13] = n; m[14] = o; m[15] = p; } mat4_type(const std::array<T,16>& mm) noexcept(true) { for (uint32_t i = 0; i < 16; i++) { m[i] = mm[i]; } } T& operator[](uint32_t x) noexcept(true) { return m[x]; } const T& operator[](uint32_t x) const noexcept(true) { return m[x]; } vec4_type<T> operator*(const vec4_type<T>& rhs) const noexcept(true) { // 0x + 4y + 8z + 12w T x = m[0] * rhs.v[0] + m[4] * rhs.v[1] + m[8] * rhs.v[2] + m[12] * rhs.v[3]; // 1x + 5y + 9z + 13w T y = m[1] * rhs.v[0] + m[5] * rhs.v[1] + m[9] * rhs.v[2] + m[13] * rhs.v[3]; // 2x + 6y + 10z + 14w T z = m[2] * rhs.v[0] + m[6] * rhs.v[1] + m[10] * rhs.v[2] + m[14] * rhs.v[3]; // 3x + 7y + 11z + 15w T w = m[3] * rhs.v[0] + m[7] * rhs.v[1] + m[11] * rhs.v[2] + m[15] * rhs.v[3]; return vec4_type<T>(x, y, z, w); } mat4_type operator*(const mat4_type& rhs) const noexcept(true) { mat4_type r; std::fill_n(&r.m[0], 16, 0.0); uint32_t r_index = 0; for (uint32_t col = 0; col < 4; col++) { for (uint32_t row = 0; row < 4; row++) { T sum = 0.0f; for (uint32_t i = 0; i < 4; i++) { sum += rhs.m[i + col * 4] * m[row + i * 4]; } r.m[r_index] = sum; r_index++; } } return r; } mat4_type& operator=(const mat4_type& rhs) noexcept(true) { for (uint32_t i = 0; i < 16; i++) { m[i] = rhs.m[i]; } return *this; } std::array<T, 16> m; }; }
18.491379
108
0.435431
ColinGilbert
5df2ee14779ce0efadeb1dbf521fa0015da97b3e
867
cpp
C++
src/tests/ie_test_utils/functional_test_utils/src/skip_tests_config.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/tests/ie_test_utils/functional_test_utils/src/skip_tests_config.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/tests/ie_test_utils/functional_test_utils/src/skip_tests_config.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <iostream> #include <fstream> #include "common_test_utils/file_utils.hpp" #include "functional_test_utils/skip_tests_config.hpp" namespace FuncTestUtils { namespace SkipTestsConfig { bool disable_tests_skipping = false; bool currentTestIsDisabled() { if (disable_tests_skipping) return false; const auto fullName = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name() + std::string(".") + ::testing::UnitTest::GetInstance()->current_test_info()->name(); for (const auto &pattern : disabledTestPatterns()) { std::regex re(pattern); if (std::regex_match(fullName, re)) return true; } return false; } } // namespace SkipTestsConfig } // namespace FuncTestUtils
26.272727
111
0.683968
kurylo
5df2eff03c132fbed6173c40e486cf9e62cca2cd
30
hpp
C++
oxygine/src/ox/json.hpp
savegame/oxygine-framework
bf49a097a86a2b99690a4fdc97efa73f2dfb70e4
[ "MIT" ]
803
2015-01-03T13:11:43.000Z
2022-03-15T17:38:58.000Z
oxygine/src/ox/json.hpp
savegame/oxygine-framework
bf49a097a86a2b99690a4fdc97efa73f2dfb70e4
[ "MIT" ]
100
2015-01-07T17:07:56.000Z
2021-12-21T20:09:20.000Z
oxygine/src/ox/json.hpp
savegame/oxygine-framework
bf49a097a86a2b99690a4fdc97efa73f2dfb70e4
[ "MIT" ]
265
2015-01-03T13:11:43.000Z
2022-03-01T04:37:15.000Z
#include "oxygine/json/json.h"
30
30
0.766667
savegame
5df3bde3711d7e111f675f2b04d73527f8b74c8a
2,012
cpp
C++
Prim/PrimComToken_Enum.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
Prim/PrimComToken_Enum.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
2
2021-07-07T17:31:49.000Z
2021-07-16T11:40:38.000Z
Prim/PrimComToken_Enum.cpp
OuluLinux/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
#include <Prim/PrimIncludeAll.h> #ifndef NO_DATA TYPEINFO_SINGLE(PrimComToken_Enum, PrimComToken_String); #endif #ifndef NO_CODE // // Construct an aName token for a string value in theValue as part of aParser, using // someOptions for parsing, and aUsage as a description of the token. // PrimComToken_Enum::PrimComToken_Enum(PrimComParse& aParser, const PrimEnum& anEnum, int& theValue, const char* aName, const char* aUsage, const TokenOptions& someOptions) : Super(aParser, _buffer, aName, aUsage, someOptions), _enum(anEnum), _value(theValue), _default_value(0) {} // // Construct an aName token for a string value defaulting to defaultValue in theValue // as part of aParser, using someOptions for parsing, and aUsage as a description of the token. // PrimComToken_Enum::PrimComToken_Enum(PrimComParse& aParser, const PrimEnum& anEnum, int& theValue, const char* aName, const char* aUsage, int defaultValue, const TokenOptions& someOptions) : Super(aParser, _buffer, aName, aUsage, *PrimStringHandle(anEnum[defaultValue]), someOptions), _enum(anEnum), _value(theValue), _default_value(defaultValue) {} // // The default destructor does nothing. // PrimComToken_Enum::~PrimComToken_Enum() {} // // Initialise for a new parsing pass. // void PrimComToken_Enum::initialise_parse(PrimComParse& aParser) { _value = _default_value; Super::initialise_parse(aParser); } // // Attempt to parse someText, returning true if accepted. // const char* PrimComToken_Enum::parse_text(PrimComParse& aParser, const char* someText) { const char* p = Super::parse_text(aParser, someText); if (p == 0) // If bad text return 0; // parsing fails std::istrstream s((char*)_buffer.str()); size_t aValue = _enum[s]; if (!s && aParser.diagnose_warnings()) { PRIMWRN(BAD_PARSE, *this << " failed to resolve \"" << _buffer << "\""); return 0; } _value = aValue; return p; } #endif
28.338028
126
0.698807
UltimateScript
5df405db206b2d794e9c8436841795245c65cd1a
247
cpp
C++
ProfessionalC++/hellovariables/hellovariables.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
ProfessionalC++/hellovariables/hellovariables.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
ProfessionalC++/hellovariables/hellovariables.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int uninitializedInt; int initializedInt = 7; cout << uninitializedInt << " is a random value" << endl; cout << initializedInt << " was assigned an initial value" << endl; return 0; }
16.466667
68
0.680162
zzragida
5df5298d3186ec5d2e696adea58960b14325d6cb
19,504
cpp
C++
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
#include <mirrage/graphic/device_memory.hpp> #include <mirrage/utils/container_utils.hpp> #include <mirrage/utils/ranges.hpp> #include <gsl/gsl> #include <bitset> #include <cmath> #include <mutex> namespace mirrage::graphic { namespace { template <typename T> constexpr T log2(T n) { return (n < 2) ? 0 : 1 + log2(n / 2); } template <std::uint32_t MinSize, std::uint32_t MaxSize> class Buddy_block_alloc { public: Buddy_block_alloc(const vk::Device&, std::uint32_t type, bool mapable, std::mutex& free_mutex); Buddy_block_alloc(const Buddy_block_alloc&) = delete; Buddy_block_alloc(Buddy_block_alloc&&) = delete; Buddy_block_alloc& operator=(const Buddy_block_alloc&) = delete; Buddy_block_alloc& operator=(Buddy_block_alloc&&) = delete; ~Buddy_block_alloc() { if(_allocation_count > 0) { LOG(plog::error) << "Still " << _allocation_count << " unfreed GPU memory allocations left."; } } auto alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory>; void free(std::uint32_t index, std::uint32_t layer); auto free_memory() const -> std::uint32_t { auto free_memory = std::size_t(0); for(auto i = std::size_t(0); i < layers; i++) { auto free = _free_blocks[i].size(); free_memory = total_size / (1L << (i + 1)) * free; } return gsl::narrow<std::uint32_t>(free_memory); } auto empty() const noexcept { return !_free_blocks[0].empty(); } private: using Free_list = std::vector<std::uint32_t>; static constexpr auto layers = log2(MaxSize) - log2(MinSize) + 1; static constexpr auto total_size = (1 << layers) * MinSize; static constexpr auto blocks = (1 << layers) - 1; vk::UniqueDeviceMemory _memory; char* _mapped_addr; std::array<Free_list, layers> _free_blocks; std::bitset<blocks / 2> _free_buddies; std::int64_t _allocation_count = 0; std::mutex& _free_mutex; auto _index_to_offset(std::uint32_t layer, std::uint32_t idx) -> vk::DeviceSize; /// split given block, return index of one of the new blocks auto _split(std::uint32_t layer, std::uint32_t idx) -> std::uint32_t; /// tries to merge the given block with its buddy auto _merge(std::uint32_t layer, std::uint32_t idx) -> bool; auto _buddies_different(std::uint32_t layer, std::uint32_t idx) { auto abs_idx = (1L << layer) - 1 + idx; MIRRAGE_INVARIANT(abs_idx > 0, "_buddies_different() called for layer 0!"); return _free_buddies[gsl::narrow<std::size_t>((abs_idx - 1) / 2)]; } }; } // namespace template <std::uint32_t MinSize, std::uint32_t MaxSize> class Device_memory_pool { public: Device_memory_pool(const vk::Device&, std::uint32_t type, bool mapable); ~Device_memory_pool() = default; auto alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory>; auto shrink_to_fit() -> std::size_t { auto lock = std::scoped_lock{_mutex}; auto new_end = std::remove_if( _blocks.begin(), _blocks.end(), [](auto& block) { return block->empty(); }); auto deleted = std::distance(new_end, _blocks.end()); if(deleted > 0) { LOG(plog::debug) << "Freed " << deleted << "/" << _blocks.size() << " blocks in allocator for type " << _type; } _blocks.erase(new_end, _blocks.end()); return gsl::narrow<std::size_t>(deleted); } auto usage_statistic() const -> Device_memory_pool_usage { auto lock = std::scoped_lock{_mutex}; auto usage = Device_memory_pool_usage{0, 0, _blocks.size()}; for(auto& block : _blocks) { usage.reserved += MaxSize; usage.used += MaxSize - block->free_memory(); } return usage; } private: const vk::Device& _device; std::uint32_t _type; bool _mapable; mutable std::mutex _mutex; std::vector<std::unique_ptr<Buddy_block_alloc<MinSize, MaxSize>>> _blocks; }; class Device_heap { public: Device_heap(const vk::Device& device, std::uint32_t type, bool mapable) : _device(device) , _type(type) , _mapable(mapable) , _temporary_pool(device, type, mapable) , _normal_pool(device, type, mapable) , _persistent_pool(device, type, mapable) { } Device_heap(const Device_heap&) = delete; Device_heap(Device_heap&&) = delete; Device_heap& operator=(const Device_heap&) = delete; Device_heap& operator=(Device_heap&&) = delete; auto alloc(std::uint32_t size, std::uint32_t alignment, Memory_lifetime lifetime) -> util::maybe<Device_memory> { auto memory = [&] { switch(lifetime) { case Memory_lifetime::temporary: return _temporary_pool.alloc(size, alignment); case Memory_lifetime::normal: return _normal_pool.alloc(size, alignment); case Memory_lifetime::persistent: return _persistent_pool.alloc(size, alignment); } MIRRAGE_FAIL("Unreachable"); }(); if(memory.is_some()) return memory; // single allocation auto alloc_info = vk::MemoryAllocateInfo{size, _type}; auto m = _device.allocateMemoryUnique(alloc_info); auto mem_addr = _mapable ? static_cast<char*>(_device.mapMemory(*m, 0, VK_WHOLE_SIZE)) : nullptr; return Device_memory{this, +[](void* self, std::uint32_t, std::uint32_t, vk::DeviceMemory memory) { static_cast<Device_heap*>(self)->_device.freeMemory(memory); }, 0, size, m.release(), 0, mem_addr}; } auto shrink_to_fit() -> std::size_t { return _temporary_pool.shrink_to_fit() + _normal_pool.shrink_to_fit() + _persistent_pool.shrink_to_fit(); } auto usage_statistic() const -> Device_memory_type_usage { auto temporary_usage = _temporary_pool.usage_statistic(); auto normal_usage = _normal_pool.usage_statistic(); auto persistent_usage = _persistent_pool.usage_statistic(); return {temporary_usage.reserved + normal_usage.reserved + persistent_usage.reserved, temporary_usage.used + normal_usage.used + persistent_usage.used, temporary_usage, normal_usage, persistent_usage}; } private: friend class Device_memory_allocator; friend class Device_memory; const vk::Device& _device; std::uint32_t _type; bool _mapable; Device_memory_pool<1024L * 1024 * 4, 256L * 1024 * 1024> _temporary_pool; Device_memory_pool<1024L * 1024 * 1, 256L * 1024 * 1024> _normal_pool; Device_memory_pool<1024L * 1024 * 1, 256L * 1024 * 1024> _persistent_pool; }; Device_memory::Device_memory(Device_memory&& rhs) noexcept : _owner(rhs._owner) , _deleter(rhs._deleter) , _index(rhs._index) , _layer(rhs._layer) , _memory(std::move(rhs._memory)) , _offset(rhs._offset) , _mapped_addr(rhs._mapped_addr) { rhs._owner = nullptr; } Device_memory& Device_memory::operator=(Device_memory&& rhs) noexcept { if(&rhs == this) return *this; if(_owner) { _deleter(_owner, _index, _layer, _memory); } _owner = rhs._owner; _deleter = rhs._deleter; _index = rhs._index; _layer = rhs._layer; _memory = rhs._memory; _offset = rhs._offset; _mapped_addr = rhs._mapped_addr; rhs._owner = nullptr; return *this; } Device_memory::~Device_memory() { if(_owner) { _deleter(_owner, _index, _layer, _memory); } } Device_memory::Device_memory(void* owner, Deleter* deleter, std::uint32_t index, std::uint32_t layer, vk::DeviceMemory m, vk::DeviceSize o, char* mapped_addr) : _owner(owner) , _deleter(deleter) , _index(index) , _layer(layer) , _memory(m) , _offset(o) , _mapped_addr(mapped_addr) { } Device_memory_allocator::Device_memory_allocator(const vk::Device& device, vk::PhysicalDevice gpu, bool dedicated_alloc_supported) : _device(device) , _is_unified_memory_architecture(true) , _is_dedicated_allocations_supported(dedicated_alloc_supported) { auto memory_properties = gpu.getMemoryProperties(); const auto host_visible_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent; const auto device_local_flags = vk::MemoryPropertyFlagBits::eDeviceLocal; _pools.reserve(memory_properties.memoryTypeCount); for(auto id : util::range(memory_properties.memoryTypeCount)) { auto host_visible = (memory_properties.memoryTypes[id].propertyFlags & host_visible_flags) == host_visible_flags; _pools.emplace_back(std::make_unique<Device_heap>(_device, id, host_visible)); } for(auto i : util::range(memory_properties.memoryTypeCount)) { auto host_visible = (memory_properties.memoryTypes[i].propertyFlags & host_visible_flags) == host_visible_flags; auto device_local = (memory_properties.memoryTypes[i].propertyFlags & device_local_flags) == device_local_flags; if(host_visible) { _host_visible_pools.emplace_back(i); } if(device_local) { _device_local_pools.emplace_back(i); } if(host_visible || device_local) { _is_unified_memory_architecture &= host_visible && device_local; } } if(_is_unified_memory_architecture) { LOG(plog::info) << "Detected a unified memory architecture."; } if(_is_dedicated_allocations_supported) { LOG(plog::info) << "VK_NV_dedicated_allocation enabled"; } } Device_memory_allocator::~Device_memory_allocator() = default; auto Device_memory_allocator::alloc(std::uint32_t size, std::uint32_t alignment, std::uint32_t type_mask, bool host_visible, Memory_lifetime lifetime) -> util::maybe<Device_memory> { const auto& pool_ids = host_visible ? _host_visible_pools : _device_local_pools; for(auto id : pool_ids) { if(type_mask & (1u << id)) { auto& pool = _pools[id]; try { return pool->alloc(size, alignment, lifetime); } catch(std::system_error& e) { auto usage = usage_statistic(); LOG(plog::error) << "Couldn't allocate block of size " << size << "\n Usage: " << usage.used << "/" << usage.reserved; // free memory and retry if(e.code() == vk::Result::eErrorOutOfDeviceMemory && shrink_to_fit() > 0) { return pool->alloc(size, alignment, lifetime); } } } } MIRRAGE_FAIL("No pool on the device matches the requirements. Type mask=" << type_mask << ", host visible=" << host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Image image, bool host_visible) -> util::maybe<Device_memory> { return alloc_dedicated({}, image, host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Buffer buffer, bool host_visible) -> util::maybe<Device_memory> { return alloc_dedicated(buffer, {}, host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Buffer buffer, vk::Image image, bool host_visible) -> util::maybe<Device_memory> { const auto& pool_ids = host_visible ? _host_visible_pools : _device_local_pools; auto requirements = buffer ? _device.getBufferMemoryRequirements(buffer) : _device.getImageMemoryRequirements(image); for(auto id : pool_ids) { if(requirements.memoryTypeBits & (1u << id)) { auto alloc_info = vk::MemoryAllocateInfo{requirements.size, id}; #ifdef VK_NV_dedicated_allocation auto dedicated_info = vk::DedicatedAllocationMemoryAllocateInfoNV{}; if(_is_dedicated_allocations_supported) { dedicated_info.buffer = buffer; dedicated_info.image = image; alloc_info.pNext = &dedicated_info; } #endif LOG(plog::debug) << "Alloc: " << (float(requirements.size) / 1024.f / 1024.f) << " MB"; auto mem = _device.allocateMemoryUnique(alloc_info); auto mem_addr = host_visible ? static_cast<char*>(_device.mapMemory(*mem, 0, VK_WHOLE_SIZE)) : nullptr; return Device_memory{ this, +[](void* self, std::uint32_t, std::uint32_t, vk::DeviceMemory memory) { static_cast<Device_memory_allocator*>(self)->_device.freeMemory(memory); }, 0, 0, mem.release(), 0, mem_addr}; } } MIRRAGE_FAIL("No pool on the device matches the requirements. Type mask=" << requirements.memoryTypeBits << ", host visible=" << host_visible); } auto Device_memory_allocator::shrink_to_fit() -> std::size_t { auto sum = std::size_t(0); for(auto& heap : _pools) { if(heap) { sum += heap->shrink_to_fit(); } } return sum; } auto Device_memory_allocator::usage_statistic() const -> Device_memory_usage { auto types = std::unordered_map<std::uint32_t, Device_memory_type_usage>(); auto reserved = std::size_t(0); auto used = std::size_t(0); auto type = std::uint32_t(0); for(auto& heap : _pools) { if(heap) { auto& t_usage = types[0]; t_usage = heap->usage_statistic(); reserved += t_usage.reserved; used += t_usage.used; } type++; } return {reserved, used, types}; } // POOL template <std::uint32_t MinSize, std::uint32_t MaxSize> Device_memory_pool<MinSize, MaxSize>::Device_memory_pool(const vk::Device& device, std::uint32_t type, bool mapable) : _device(device), _type(type), _mapable(mapable) { } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Device_memory_pool<MinSize, MaxSize>::alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory> { if(size > MaxSize) return util::nothing; auto lock = std::scoped_lock{_mutex}; for(auto& block : _blocks) { auto m = block->alloc(size, alignment); if(m.is_some()) return m; } _blocks.emplace_back( std::make_unique<Buddy_block_alloc<MinSize, MaxSize>>(_device, _type, _mapable, _mutex)); auto m = _blocks.back()->alloc(size, alignment); MIRRAGE_INVARIANT(m.is_some(), "Couldn't allocate " << size << " byte with allignment" << alignment << " from newly created block of size " << MaxSize); return m; } namespace { template <std::uint32_t MinSize, std::uint32_t MaxSize> Buddy_block_alloc<MinSize, MaxSize>::Buddy_block_alloc(const vk::Device& device, std::uint32_t type, bool mapable, std::mutex& free_mutex) : _memory(device.allocateMemoryUnique({MaxSize, type})) , _mapped_addr(mapable ? static_cast<char*>(device.mapMemory(*_memory, 0, VK_WHOLE_SIZE)) : nullptr) , _free_mutex(free_mutex) { LOG(plog::debug) << "Alloc: " << (MaxSize / 1024.f / 1024.f) << " MB"; _free_blocks[0].emplace_back(0); } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory> { // protected by the mutex locked in Device_memory_pool::alloc, that is the same as _free_mutex if(size < alignment) { size = alignment; } else if(size % alignment != 0) { size += alignment - size % alignment; } if(size < MinSize) { size = MinSize; } auto layer = gsl::narrow<std::uint32_t>(std::ceil(std::log2(static_cast<float>(size))) - log2(MinSize)); layer = layer < layers ? layers - layer - 1 : 0; // find first layer with free block >= size auto current_layer = layer; while(_free_blocks[current_layer].empty()) { if(current_layer == 0) { return util::nothing; //< not enough free space } current_layer--; } // reserve found block auto index = _free_blocks[current_layer].back(); _free_blocks[current_layer].pop_back(); if(current_layer > 0) { _buddies_different(current_layer, index).flip(); } // unwinde and split all blocks an the way down for(; current_layer <= layer; current_layer++) { if(current_layer != layer) index = _split(current_layer, index); } auto offset = _index_to_offset(layer, index); MIRRAGE_INVARIANT(offset % alignment == 0, "Resulting offset is not aligned correctly. Expected:" << alignment << " Offset: " << offset); _allocation_count++; return Device_memory{this, +[](void* self, std::uint32_t i, std::uint32_t l, vk::DeviceMemory) { static_cast<Buddy_block_alloc*>(self)->free(l, i); }, index, layer, *_memory, offset, _mapped_addr ? _mapped_addr + offset : nullptr}; } template <std::uint32_t MinSize, std::uint32_t MaxSize> void Buddy_block_alloc<MinSize, MaxSize>::free(std::uint32_t layer, std::uint32_t index) { auto lock = std::scoped_lock{_free_mutex}; _allocation_count--; _free_blocks[layer].emplace_back(index); if(layer == 0) { MIRRAGE_INVARIANT(index == 0, "index overflow in layer 0, index=" << index); } else { _buddies_different(layer, index).flip(); _merge(layer, index); } } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_index_to_offset(std::uint32_t layer, std::uint32_t idx) -> vk::DeviceSize { return total_size / (1L << (layer + 1)) * idx; } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_split(std::uint32_t layer, std::uint32_t idx) -> std::uint32_t { _buddies_different(layer + 1, idx * 2 + 1) = true; _free_blocks[layer + 1].emplace_back(idx * 2 + 1); return idx * 2; } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_merge(std::uint32_t layer, std::uint32_t index) -> bool { if(layer == 0) return false; auto diff = _buddies_different(layer, index); if(diff == false) { // both free // remove nodes from freelist and add parent auto parent_index = index / 2; util::erase_fast(_free_blocks[layer], parent_index * 2); util::erase_fast(_free_blocks[layer], parent_index * 2 + 1); _free_blocks[layer - 1].emplace_back(parent_index); if(layer > 1) { _buddies_different(layer - 1, parent_index).flip(); _merge(layer - 1, parent_index); } return true; } return false; } } // namespace } // namespace mirrage::graphic
31.559871
104
0.622488
lowkey42
5df53d6d97c8bc4307d93f202acfe67b94973e08
238
cpp
C++
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018 Daniel dos Santos Marques <danielsmarques7@gmail.com> // License: BSD 3 clause #include <iostream> #include "Trainer.h" int main(int argc, char** argv) { Trainer trainer; trainer.train(argv[1]); return 0; }
18.307692
75
0.697479
ddsmarques
5df6477f2ff543a723c0d79fdccef83c74875181
6,176
cc
C++
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
#include "riscvIla.hpp" #include <ilang/vtarget-out/vtarget_gen.h> using namespace ilang; /// the function to parse commandline arguments VerilogVerificationTargetGenerator::vtg_config_t SetConfiguration(); VerilogVerificationTargetGenerator::vtg_config_t HandleArguments(int argc, char **argv); void verifyNibblerInstCosa( Ila& model, VerilogVerificationTargetGenerator::vtg_config_t vtg_cfg, const std::vector<std::string> & design_files, const std::string & varmap, const std::string & instcont ) { VerilogGeneratorBase::VlgGenConfig vlg_cfg; vlg_cfg.pass_node_name = true; vtg_cfg.CosaAddKeep = false; vtg_cfg.MemAbsReadAbstraction = true; vtg_cfg.target_select = vtg_cfg.INST; //vtg_cfg.ForceInstCheckReset = true; std::string RootPath = ".."; std::string VerilogPath = RootPath + "/verilog/"; std::string IncludePath = VerilogPath + "include/"; std::string RefrelPath = RootPath + "/refinement/"; std::string OutputPath = RootPath + "/verification/"; std::vector<std::string> path_to_design_files; // update path for(auto && f : design_files) path_to_design_files.push_back( VerilogPath + f ); VerilogVerificationTargetGenerator vg( {IncludePath}, // no include path_to_design_files, // designs "param_riscv_Core", // top_module_name RefrelPath + varmap, // variable mapping RefrelPath + instcont, // conditions of start/ready OutputPath, // output path model.get(), // model VerilogVerificationTargetGenerator::backend_selector::COSA, // backend: COSA vtg_cfg, // target generator configuration vlg_cfg); // verilog generator configuration vg.GenerateTargets(); } void verifyNibblerInvPdr( Ila& model, VerilogVerificationTargetGenerator::vtg_config_t vtg_cfg, const std::vector<std::string> & design_files, const std::string & varmap, const std::string & instcont ) { VerilogGeneratorBase::VlgGenConfig vlg_cfg; vlg_cfg.pass_node_name = true; vtg_cfg.CosaAddKeep = false; vtg_cfg.MemAbsReadAbstraction = true; vtg_cfg.target_select = vtg_cfg.INV; vtg_cfg.InvariantSynthesisKeepMemory = false; vtg_cfg.InvariantCheckKeepMemory = false; vtg_cfg.YosysSmtFlattenHierarchy = true; vtg_cfg.AbcPath = "~/abc/"; vtg_cfg.YosysPropertyCheckShowProof = true; // vtg_cfg.YosysSmtStateSort = vtg_cfg.BitVec; // vtg_cfg.ForceInstCheckReset = true; std::string RootPath = ".."; std::string VerilogPath = RootPath + "/verilog/"; std::string IncludePath = VerilogPath + "include/"; std::string RefrelPath = RootPath + "/refinement/"; std::string OutputPath = RootPath + "/verification/"; std::vector<std::string> path_to_design_files; // update path for(auto && f : design_files) path_to_design_files.push_back( VerilogPath + f ); VerilogVerificationTargetGenerator vg( {IncludePath}, // no include path_to_design_files, // designs "param_riscv_Core", // top_module_name RefrelPath + varmap, // variable mapping RefrelPath + instcont, // conditions of start/ready OutputPath, // output path model.get(), // model VerilogVerificationTargetGenerator::backend_selector::ABCPDR, // backend: Z3PDR, COSA vtg_cfg, // target generator configuration vlg_cfg); // verilog generator configuration vg.GenerateTargets(); } int main(int argc, char **argv) { // TODO std::vector<std::string> design_files = { "param-Ctrl.v", "param-ShiftDemux.v", "param-CoreDpathRegfile.v", "param-CoreDpathAlu.v", "param-SIMDLaneDpath.v", "param-ClkEnBuf.v", "param-DeserializedReg.v", "param-PCComputation.v", "param-Dpath.v", "param-Core.v" }; auto vtg_cfg = SetConfiguration(); //auto vtg_cfg = HandleArguments(argc, argv); // build the model riscvILA_user nibbler; nibbler.addInstructions(); // 37 base integer instructions verifyNibblerInstCosa(nibbler.model, vtg_cfg, design_files, "varmap-nibbler.json", "instcond-nibbler.json"); verifyNibblerInvPdr(nibbler.model, vtg_cfg, design_files, "varmap-nibbler.json", "instcond-nibbler.json"); // riscvILA_user riscvILA(0); return 0; } VerilogVerificationTargetGenerator::vtg_config_t HandleArguments(int argc, char **argv) { // the solver, the cosa environment // you can use a commandline parser if desired, but since it is not the main focus of // this demo, we skip it // set ilang option, operators like '<' will refer to unsigned arithmetics SetUnsignedComparison(true); VerilogVerificationTargetGenerator::vtg_config_t ret; for(unsigned p = 1; p<argc; p++) { std::string arg = argv[p]; auto split = arg.find("="); auto argName = arg.substr(0,split); auto param = arg.substr(split+1); if(argName == "Solver") ret.CosaSolver = param; else if(argName == "Env") ret.CosaPyEnvironment = param; else if(argName == "Cosa") ret.CosaPath = param; // else unknown else { std::cerr<<"Unknown argument:" << argName << std::endl; std::cerr<<"Expecting Solver/Env/Cosa=???" << std::endl; } } ret.CosaGenTraceVcd = true; /// other configurations ret.PortDeclStyle = VlgVerifTgtGenBase::vtg_config_t::NEW; ret.CosaGenJgTesterScript = true; //ret.CosaOtherSolverOptions = "--blackbox-array"; //ret.ForceInstCheckReset = true; return ret; } VerilogVerificationTargetGenerator::vtg_config_t SetConfiguration() { // set ilang option, operators like '<' will refer to unsigned arithmetics SetUnsignedComparison(true); VerilogVerificationTargetGenerator::vtg_config_t ret; ret.CosaSolver = "btor"; ret.CosaPyEnvironment = "/ibuild/ilang-env/bin/activate"; ret.CosaGenTraceVcd = true; /// other configurations ret.PortDeclStyle = VlgVerifTgtGenBase::vtg_config_t::NEW; ret.CosaGenJgTesterScript = true; //ret.CosaOtherSolverOptions = "--blackbox-array"; //ret.ForceInstCheckReset = true; return ret; }
32.505263
110
0.686528
yuzeng2333
5df816bda08fdd326c7d6d96d7fd2311f56dc455
8,856
cpp
C++
UrabeVocalSynthA/GUIMan.cpp
DanNixon/UrabeVocalSynth
c062069a140ddb8bfd0280cd8daf5102ec54c58a
[ "Apache-2.0" ]
1
2018-12-26T13:03:29.000Z
2018-12-26T13:03:29.000Z
UrabeVocalSynthA/GUIMan.cpp
DanNixon/UrabeVocalSynth
c062069a140ddb8bfd0280cd8daf5102ec54c58a
[ "Apache-2.0" ]
null
null
null
UrabeVocalSynthA/GUIMan.cpp
DanNixon/UrabeVocalSynth
c062069a140ddb8bfd0280cd8daf5102ec54c58a
[ "Apache-2.0" ]
null
null
null
#include "GUIMan.h" extern char *VERSION_STRING; using namespace GUIMan; GUIManager::GUIManager(GLCDManager *glcd_manager, JpSynthManager *jp_synth_manager, SynthManager *synth_manager) { this->current_window = MAIN; this->mode = MENU; this->glcd_man = glcd_manager; this->jps_man = jp_synth_manager; this->synth_man = synth_manager; } SystemMode GUIManager::get_system_mode() { return this->mode; } void GUIManager::draw() { this->glcd_man->u8g.firstPage(); do { do_draw(); } while(this->glcd_man->u8g.nextPage()); } void GUIManager::do_draw() { this->mode = MENU; this->glcd_man->draw_base(); switch(this->current_window) { case MAIN: this->current_option = 0; this->glcd_man->draw_title_large("UrabeVocalSynth"); this->glcd_man->draw_buttons_lower("Synth", "Vocal"); this->glcd_man->u8g.setFont(u8g_font_helvR08); this->glcd_man->u8g.drawStr(0, 24, VERSION_STRING); this->glcd_man->u8g.drawStr(0, 34, "dan-nixon.com"); break; case SYNTH_MENU: this->glcd_man->draw_title("Synth"); this->glcd_man->draw_buttons_upper("Back", "Run"); this->glcd_man->draw_buttons_lower("Settings", ""); break; case JP_MENU: this->glcd_man->draw_title("Vocal"); this->glcd_man->draw_buttons_upper("Back", "Run"); this->glcd_man->draw_buttons_lower("Settings", ""); break; case SYNTH_SETTINGS: this->glcd_man->draw_title("Synth S"); this->glcd_man->draw_buttons_upper("Back", ""); glcd_man->draw_option(this->synth_man->options[this->current_option]); break; case JP_SETTINGS: this->glcd_man->draw_title("Vocal S"); this->glcd_man->draw_buttons_upper("Back", ""); glcd_man->draw_option(this->jps_man->options[this->current_option]); break; case SYNTH_RUN: this->mode = WAVEFORM; this->glcd_man->draw_title("Synth"); this->glcd_man->draw_buttons_upper("Back", ""); this->glcd_man->draw_buttons_lower("Panic", ""); this->glcd_man->u8g.setFont(u8g_font_5x7); //Print some general info this->glcd_man->u8g.drawStr(0, 22, this->synth_man->get_waveform_name()); char dist_buf[10]; sprintf(dist_buf, "Dist: %d", this->synth_man->get_freq_distortion()); this->glcd_man->u8g.drawStr(0, 30, dist_buf); char poly_buf[10]; sprintf(poly_buf, "Poly: %d", this->synth_man->get_notes_on()); this->glcd_man->u8g.drawStr(0, 38, poly_buf); //Print the envelope stage labels this->glcd_man->u8g.drawStr(55, 30, "A"); this->glcd_man->u8g.drawStr(55, 38, "D"); this->glcd_man->u8g.drawStr(55, 46, "R"); //Print envelope durations this->glcd_man->u8g.drawStr(65, 22, "Dur."); this->glcd_man->u8g.drawStr(65, 30, this->synth_man->get_attack_duration()); this->glcd_man->u8g.drawStr(65, 38, this->synth_man->get_decay_duration()); this->glcd_man->u8g.drawStr(65, 46, this->synth_man->get_release_duration()); //print envelope amplitudes this->glcd_man->u8g.drawStr(95, 22, "Amp."); char atk_buf[10]; sprintf(atk_buf, "%d", this->synth_man->get_attack_amp()); this->glcd_man->u8g.drawStr(95, 30, atk_buf); char dec_buf[10]; sprintf(dec_buf, "%d", this->synth_man->get_decay_amp()); this->glcd_man->u8g.drawStr(95, 38, dec_buf); char rel_buf[10]; sprintf(rel_buf, "%d", this->synth_man->get_release_amp()); this->glcd_man->u8g.drawStr(95, 46, rel_buf); break; case JP_RUN: this->mode = VOCAL; this->glcd_man->draw_title("Vocal"); this->glcd_man->draw_buttons_upper("Back", ""); this->glcd_man->draw_buttons_lower("Panic", "Clr Buf"); this->glcd_man->u8g.setFont(u8g_font_5x7); //Print kana buffer pointer values char read_counter_buf[10]; char write_counter_buf[10]; sprintf(read_counter_buf, "R:%d", this->jps_man->get_buffer_position()); sprintf(write_counter_buf, "W:%d", this->jps_man->get_buffer_add_position()); this->glcd_man->u8g.drawStr(88, 22, read_counter_buf); this->glcd_man->u8g.drawStr(88, 30, write_counter_buf); //Print kana buffer KanaTable::Kana disp_kana[9]; int offset = 0; if(this->jps_man->get_notes_on()) offset = -1; for(int i=0; i<9; i++) { int position = i + this->jps_man->get_buffer_position() + offset; if(position >= KANA_BUFFER_SIZE) position = position % KANA_BUFFER_SIZE; disp_kana[i] = this->jps_man->kana_buffer[position]; } this->glcd_man->draw_kana_buffer(disp_kana, this->jps_man->get_notes_on()); break; } } void GUIManager::handle_menu_input(ButtonValue b_val) { switch(this->current_window) { case MAIN: switch(b_val) { case _F3: //Synth this->current_window = SYNTH_MENU; break; case _F4: //Vocal this->current_window = JP_MENU; break; } break; case SYNTH_MENU: switch(b_val) { case _F1: //Back this->current_window = MAIN; break; case _F2: //Run this->current_window = SYNTH_RUN; this->synth_man->panic(); break; case _F3: //Settings this->current_option = 0; this->current_window = SYNTH_SETTINGS; break; } break; case JP_MENU: switch(b_val) { case _F1: //Back this->current_window = MAIN; break; case _F2: //Run this->current_window = JP_RUN; this->jps_man->panic(); break; case _F3: //Settings this->current_option = 0; this->current_window = JP_SETTINGS; break; } break; case SYNTH_SETTINGS: switch(b_val) { case _F1: //Back this->current_window = SYNTH_MENU; this->synth_man->update_config(); break; case _UP: this->change_option(&this->synth_man->options[this->current_option], 1); break; case _DOWN: this->change_option(&this->synth_man->options[this->current_option], -1); break; case _LEFT: this->current_option--; if(this->current_option < 0) this->current_option = this->synth_man->get_option_count() - 1; break; case _RIGHT: this->current_option++; if(this->current_option >= this->synth_man->get_option_count()) this->current_option = 0; break; } break; case JP_SETTINGS: switch(b_val) { case _F1: //Back this->current_window = JP_MENU; this->jps_man->update_config(); break; case _UP: this->change_option(&this->jps_man->options[this->current_option], 1); break; case _DOWN: this->change_option(&this->jps_man->options[this->current_option], -1); break; case _LEFT: this->current_option--; if(this->current_option < 0) this->current_option = this->jps_man->get_option_count() - 1; break; case _RIGHT: this->current_option++; if(this->current_option >= this->jps_man->get_option_count()) this->current_option = 0; break; } break; case SYNTH_RUN: switch(b_val) { case _F1: //Exit this->current_window = SYNTH_MENU; break; case _F3: //Panic this->synth_man->panic(); break; } break; case JP_RUN: switch(b_val) { case _F1: //Exit this->current_window = JP_MENU; break; case _F3: //Panic this->jps_man->panic(); break; case _F4: //Clear Buffer this->jps_man->kana_buffer_clear(); break; } break; } this->draw(); } void GUIManager::change_option(ConfigData::ConfigOption *option, int direction) { int precision = 1; if(direction < 0) precision = -1; switch(option->type) { case ConfigData::INT: if(option->value_count != -1) precision *= option->value_count; if(abs(precision) == 1) precision *= 5; //Default Precision option->value += precision; int min; int max; sscanf(option->values[0], "%d", &min); sscanf(option->values[1], "%d", &max); if(option->value < min) option->value = min; if(option->value > max) option->value = max; break; case ConfigData::ENUM: option->value += precision; if(option->value < 0) option->value = option->value_count - 1; if(option->value >= option->value_count) option->value = 0; break; } }
31.516014
112
0.590899
DanNixon
5df8c24ffd67744dd690811b123ba5f5648fd10a
3,148
cpp
C++
src/Buffers/test_CPUBuffer.cpp
abcucberkeley/cudaDecon
d21ae81f47701bdd68ba155ccf2be97cf6bc3feb
[ "BSL-1.0" ]
13
2020-03-11T18:41:04.000Z
2022-03-10T09:46:47.000Z
src/Buffers/test_CPUBuffer.cpp
tlambert03/CUDA_SIMrecon
84f6828d2db850660088ec4d625735f98ab722d5
[ "MIT" ]
8
2019-12-16T15:38:14.000Z
2021-11-25T20:38:44.000Z
src/Buffers/test_CPUBuffer.cpp
tlambert03/CUDA_SIMrecon
84f6828d2db850660088ec4d625735f98ab722d5
[ "MIT" ]
11
2019-02-28T22:37:16.000Z
2021-07-12T15:05:54.000Z
#include "Buffer.h" #include "CPUBuffer.h" #include "GPUBuffer.h" #include "gtest/gtest.h" #include <cstdlib> int compareArrays(char* arr1, char* arr2, int size); TEST(CPUBuffer, IncludeTest) { ASSERT_EQ(0, 0); } TEST(CPUBuffer, ConstructorTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); CPUBuffer b(4 * sizeof(float)); ASSERT_EQ(4 * sizeof(float), b.getSize()); EXPECT_TRUE(0 != b.getPtr()); } TEST(CPUBuffer, ResizeTest) { CPUBuffer a; a.resize(10); ASSERT_EQ(10, a.getSize()); EXPECT_TRUE(0 != a.getPtr()); } TEST(CPUBuffer, SetFromPlainArrayTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } TEST(CPUBuffer, SetTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); CPUBuffer b; b.resize(a.getSize()); a.set(&b, 0, 4 * sizeof(float), 0); b.setPlainArray(out, 0, b.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } TEST(CPUBuffer, TakeOwnershipTest) { CPUBuffer a; float* src = new float[4]; src[0] = 11.0; src[1] = 22.0; src[2] = 33.0; src[3] = 44.0; float result[4] = {11.0, 22.0, 33.0, 44.0}; a.takeOwnership(src, 4 * sizeof(float)); ASSERT_EQ(0, compareArrays((char*)a.getPtr(), (char*)result, sizeof(result))); } TEST(CPUBuffer, Dump) { CPUBuffer a; float* src = new float[4]; src[0] = 11.0; src[1] = 22.0; src[2] = 33.0; src[3] = 44.0; a.takeOwnership(src, 4 * sizeof(float)); a.dump(std::cout, 2); ASSERT_EQ(0, 0); } TEST(CPUBuffer, GPUSetTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); GPUBuffer b; b.resize(a.getSize()); a.set(&b, 0, 4 * sizeof(float), 0); CPUBuffer c; c.resize(b.getSize()); ASSERT_EQ(4 * sizeof(float), c.getSize()); b.set(&c, 0, 4 * sizeof(float), 0); c.setPlainArray(out, 0, c.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } int compareArrays(char* arr1, char* arr2, int size) { int difference = 0; for (int i = 0; i < size; ++i) { difference += abs(arr1[i] - arr2[i]); } return difference; }
27.137931
72
0.589263
abcucberkeley
5df969fae251834aab030e73baa81d57084db5d7
6,981
cpp
C++
coresim/simulator.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
null
null
null
coresim/simulator.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
1
2021-06-18T19:12:19.000Z
2021-06-18T19:12:19.000Z
coresim/simulator.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
1
2021-06-18T07:01:16.000Z
2021-06-18T07:01:16.000Z
#include <iostream> #include <algorithm> #include <fstream> #include <stdlib.h> #include <deque> #include <stdint.h> #include <time.h> #include <assert.h> #include <map> #include <string> #include <unordered_set> #include <vector> #include "agg_channel.h" #include "event.h" #include "flow.h" #include "node.h" #include "packet.h" #include "queue.h" #include "random_variable.h" #include "topology.h" #include "../run/params.h" Topology* topology; double current_time = 0; //std::vector<std::priority_queue<Event*, std::vector<Event*>, EventComparator>> event_queues; std::priority_queue<Event*, std::vector<Event*>, EventComparator> event_queue; std::deque<Flow*> flows_to_schedule; //std::vector<std::deque<Event*>> flow_arrivals; std::deque<Event*> flow_arrivals; std::vector<std::map<std::pair<uint32_t, uint32_t>, AggChannel *>> channels; // for every qos level, a map of channels indexed by src-dst pair std::vector<std::vector<double>> per_pkt_lat; std::vector<std::vector<double>> per_pkt_rtt; std::vector<std::vector<uint32_t>> cwnds; std::vector<std::vector<uint32_t>> dwnds; std::vector<double> D3_allocation_counter_per_queue; std::vector<uint32_t> D3_num_allocations_per_queue; double total_time_period = 0; uint32_t total_num_periods = 0; //std::vector<double> time_spent_send_data; //std::vector<double> burst_start_time; //std::vector<uint32_t> curr_burst_size; std::map<std::pair<uint32_t, uint32_t>, double> time_spent_send_data; std::map<std::pair<uint32_t, uint32_t>, double> burst_start_time; std::map<std::pair<uint32_t, uint32_t>, uint32_t> curr_burst_size; std::map<std::pair<uint32_t, uint32_t>, uint32_t> curr_burst_size_in_flow; uint32_t num_outstanding_packets = 0; uint32_t max_outstanding_packets = 0; uint32_t num_outstanding_packets_at_50 = 0; uint32_t num_outstanding_packets_at_100 = 0; uint32_t arrival_packets_at_50 = 0; uint32_t arrival_packets_at_100 = 0; uint32_t arrival_packets_count = 0; uint32_t total_finished_flows = 0; uint32_t duplicated_packets_received = 0; uint32_t num_early_termination = 0; uint32_t injected_packets = 0; uint32_t duplicated_packets = 0; uint32_t dead_packets = 0; uint32_t completed_packets = 0; uint32_t backlog3 = 0; uint32_t backlog4 = 0; uint32_t total_completed_packets = 0; uint32_t sent_packets = 0; std::vector<uint32_t> num_timeouts; uint32_t num_pkt_drops = 0; uint32_t pkt_drops_agg_switches = 0; uint32_t pkt_drops_core_switches = 0; uint32_t pkt_drops_host_queues = 0; std::vector<uint32_t> pkt_drops_per_agg_sw; std::vector<uint32_t> pkt_drops_per_host_queues; std::vector<uint32_t> pkt_drops_per_prio; uint32_t num_downgrades = 0; std::vector<uint32_t> num_downgrades_per_host; std::vector<uint32_t> num_check_passed; std::vector<uint32_t> num_check_failed_and_downgrade; std::vector<uint32_t> num_check_failed_but_stay; std::vector<uint32_t> num_qos_h_downgrades; uint32_t num_qos_m_downgrades; double last_passed_time = 0; std::vector<std::vector<double>> per_prio_qd; std::vector<uint32_t> per_pctl_downgrades; uint32_t num_bad_QoS_H_RPCs = 0; time_t clock_start_time; uint32_t event_total_count = 0; uint32_t pkt_total_count = 0; std::vector<uint32_t> per_host_QoS_H_downgrades; std::vector<uint32_t> per_host_QoS_H_rpcs; std::vector<uint32_t> dwnds_qosh; uint32_t num_measurements_cleared = 0; uint32_t total_measurements = 0; std::vector<uint32_t> lat_cleared; std::map<std::pair<uint32_t, uint32_t>, uint32_t> flip_coin; std::vector<double> qos_h_admit_prob; std::vector<double> total_qos_h_admit_prob; std::vector<std::vector<double>> qos_h_admit_prob_per_host; std::vector<uint32_t> qos_h_issued_rpcs_per_host; //std::vector<uint32_t> qos_h_total_misses_per_host; int init_count = 0; std::vector<uint32_t> qos_h_memory_misses; std::vector<uint32_t> per_host_qos_h_rpc_issued; std::vector<uint32_t> per_host_qos_h_rpc_finished; std::vector<std::vector<double>> fairness_qos_h_admit_prob_per_host; std::vector<std::vector<double>> fairness_qos_h_ts_per_host; std::vector<std::vector<double>> fairness_qos_h_rates_per_host; std::vector<uint32_t> fairness_qos_h_bytes_per_host; std::vector<double> fairness_last_check_time; uint32_t num_outstanding_rpcs = 0; std::vector<uint32_t> num_outstanding_rpcs_total; std::vector<std::vector<uint32_t>> num_outstanding_rpcs_one_sw; //double switch_max_inst_load = 0; std::vector<double> switch_max_inst_load; extern DCExpParams params; //double start_time = -1; double simulaiton_event_duration = 0; const std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } void add_to_event_queue(Event* ev) { event_queue.push(ev); } double get_current_time() { return current_time; // in seconds } void handle_events() { int last_evt_type = -1; int same_evt_count = 0; while (event_queue.size() > 0) { Event *ev = event_queue.top(); event_queue.pop(); current_time = ev->time; //if (start_time < 0) { // start_time = current_time; //} if (ev->cancelled) { delete ev; //TODO: Smarter ////ev = NULL; continue; } ev->process_event(); if(last_evt_type == ev->type && last_evt_type != 9) same_evt_count++; else same_evt_count = 0; last_evt_type = ev->type; if(same_evt_count > 1000000){ // make sure this value is large enough for large-scale exp std::cout << "Ended event dead loop. Type:" << last_evt_type << "\n"; break; } delete ev; event_total_count++; } } /* Runs an initialized scenario (in fact this includes everything) */ void run_scenario() { // Flow Arrivals create new flow arrivals // Add the first flow arrival if (flow_arrivals.size() > 0) { add_to_event_queue(flow_arrivals.front()); flow_arrivals.pop_front(); } handle_events(); } extern void run_experiment(int argc, char** argv, uint32_t exp_type); int main (int argc, char ** argv) { ////time_t clock_start_time; time(&clock_start_time); //srand(time(NULL)); srand(0); std::cout.precision(15); uint32_t exp_type = atoi(argv[1]); switch (exp_type) { case GEN_ONLY: case DEFAULT_EXP: run_experiment(argc, argv, exp_type); break; default: assert(false); } time_t clock_end_time; time(&clock_end_time); double duration = difftime(clock_end_time, clock_start_time); std::cout.precision(4); std::cout << currentDateTime() << " Simulator ended. Program execution time: " << duration << " seconds\n"; //std::cout << "Simulation event duration: " << simulaiton_event_duration << " seconds" << std::endl; }
32.319444
142
0.723249
SymbioticLab
5dfce1c18a3a44da16a8b3fb291b51abb45bce46
21,261
cpp
C++
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** File Class Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brfile.h" #include "brfilemanager.h" #include "brendian.h" #include "brmemoryfunctions.h" #include <stdio.h> /*! ************************************ \class Burger::File \brief System file reference class A functional equivalent to FILE *, except files are all considered binary and pathnames are only Burgerlib format ***************************************/ /*! ************************************ \brief Create a Burger::File class Initialize variables, however no file is opened so all file access functions will fail until Open() is called and it succeeds \sa Open(const char *,eFileAccess), Open(Filename *,eFileAccess), Close(), ~File() ***************************************/ Burger::File::File() : m_pFile(NULL), m_uPosition(0), m_Filename(), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif } /*! ************************************ \brief Create a Burger::File class with a file Open a file and initialize the variables. If the file open operation fails, all file access functions will fail until a new file is opened. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \sa Open(const char *,eFileAccess), File(Filename *,eFileAccess), Close() ***************************************/ Burger::File::File(const char *pFileName,eFileAccess eAccess) : m_pFile(NULL), m_uPosition(0), m_Filename(pFileName), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif Open(pFileName,eAccess); } /*! ************************************ \brief Create a Burger::File class with a Burger::Filename Open a file and initialize the variables. If the file open operation fails, all file access functions will fail until a new file is opened. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \sa File(const char *,eFileAccess), Open(Filename *,eFileAccess), Close() ***************************************/ Burger::File::File(Filename *pFileName,eFileAccess eAccess) : m_pFile(NULL), m_uPosition(0), m_Filename(pFileName[0]), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif Open(pFileName,eAccess); } /*! ************************************ \brief Close any open file Shut down the \ref File and close any open file. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ Burger::File::~File() { Close(); } /*! ************************************ \brief Create a new File instance Allocate memory using Burger::Alloc() and initialize a File with it. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \return \ref NULL if out of memory or the file didn't successfully open \sa Burger::Delete(const File *) ***************************************/ Burger::File * BURGER_API Burger::File::New(const char *pFileName,eFileAccess eAccess) { // Manually allocate the memory File *pThis = new (Alloc(sizeof(File))) File(); if (pThis) { // Load up the data if (pThis->Open(pFileName,eAccess)==kErrorNone) { // We're good! return pThis; } // Kill the malformed class Delete(pThis); } // Sorry Charlie! return nullptr; } /*! ************************************ \brief Create a new File instance Allocate memory using Burger::Alloc() and initialize a File with it. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \return \ref NULL if out of memory or the file didn't successfully open \sa Burger::Delete(const File *) ***************************************/ Burger::File * BURGER_API Burger::File::New(Filename *pFileName,eFileAccess eAccess) { // Manually allocate the memory File *pThis = new (Alloc(sizeof(File))) File(); if (pThis) { // Load up the data if (pThis->Open(pFileName,eAccess)==kErrorNone) { // We're good! return pThis; } // Kill the malformed class Delete(pThis); } // Sorry Charlie! return nullptr; } /*! ************************************ \fn uint_t Burger::File::IsOpened(void) const \brief Return \ref TRUE if a file is open Test if a file is currently open. If there's an active file, return \ref TRUE, otherwise return \ref FALSE \return \ref TRUE if there's an open file \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ /*! ************************************ \brief Open a file using a Burgerlib pathname Close any previously opened file and open a new file. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \return kErrorNone if no error, error code if not. \sa Open(Filename *, eFileAccess) and File(const char *,eFileAccess) ***************************************/ Burger::eError BURGER_API Burger::File::Open(const char *pFileName,eFileAccess eAccess) BURGER_NOEXCEPT { Filename MyFilename(pFileName); return Open(&MyFilename,eAccess); } /*! ************************************ \brief Open a file using a Burger::Filename Close any previously opened file and open a new file. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \return kErrorNone if no error, error code if not. \sa Open(const char *, eFileAccess) and File(const char *,eFileAccess) ***************************************/ #if !(defined(BURGER_WINDOWS) || defined(BURGER_MSDOS) || defined(BURGER_MACOS) || defined(BURGER_IOS) || defined(BURGER_XBOX360) || defined(BURGER_VITA)) || defined(DOXYGEN) Burger::eError BURGER_API Burger::File::Open(Filename *pFileName,eFileAccess eAccess) BURGER_NOEXCEPT { static const char *g_OpenFlags[4] = { "rb","wb","ab","r+b" }; Close(); FILE *fp = fopen(pFileName->GetNative(),g_OpenFlags[eAccess&3]); uint_t uResult = kErrorFileNotFound; if (fp) { m_pFile = fp; uResult = kErrorNone; } return static_cast<Burger::eError>(uResult); } /*! ************************************ \brief Close any open file Close any previously opened file \return kErrorNone if no error, error code if not. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ Burger::eError BURGER_API Burger::File::Close(void) BURGER_NOEXCEPT { eError uResult = kErrorNone; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { if (fclose(static_cast<FILE *>(fp))) { uResult = kErrorIO; } m_pFile = NULL; } return uResult; } /*! ************************************ \brief Return the size of a file in bytes If a file is open, query the operating system for the size of the file in bytes. \note The return value is 32 bits wide on a 32 bit operating system, 64 bits wide on 64 bit operating systems \return 0 if error or an empty file. Non-zero is the size of the file in bytes. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ uintptr_t BURGER_API Burger::File::GetSize(void) { uintptr_t uSize = 0; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Save the current file mark long Temp = ftell(fp); // Seek to the end of file if (!fseek(fp,0,SEEK_END)) { // Get the file size uSize = static_cast<uintptr_t>(ftell(fp)); } // If no error, restore the old file mark if (Temp!=-1) { fseek(fp,Temp,SEEK_SET); } } return uSize; } /*! ************************************ \brief Read data from an open file If a file is open, perform a read operation. This function will fail if the file was not opened for read access. \param pOutput Pointer to a buffer of data to read from a file \param uSize Number of bytes to read \return Number of bytes read (Can be less than what was requested due to EOF or read errors) \sa Write(const void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::Read(void *pOutput,uintptr_t uSize) { uintptr_t uResult = 0; if (uSize && pOutput) { FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { uResult = fread(pOutput,1,uSize,fp); } } return uResult; } /*! ************************************ \brief Write data into an open file If a file is open, perform a write operation. This function will fail if the file was not opened for write access. \param pInput Pointer to a buffer of data to write to a file \param uSize Number of bytes to write \return Number of bytes written (Can be less than what was requested due to EOF or write errors) \sa Read(void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::Write(const void *pInput,uintptr_t uSize) BURGER_NOEXCEPT { uintptr_t uResult = 0; if (uSize && pInput) { FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { uResult = fwrite(pInput,1,uSize,fp); } } return uResult; } /*! ************************************ \brief Get the current file mark If a file is open, query the operating system for the location of the file mark for future reads or writes. \return Current file mark or zero if an error occurred \sa Write(const void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::GetMark(void) { uintptr_t uMark = 0; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Save the current file mark long Temp = ftell(fp); // If no error, restore the old file mark if (Temp!=-1) { uMark = static_cast<uintptr_t>(Temp); } } return uMark; } /*! ************************************ \brief Set the current file mark If a file is open, set the read/write mark at the location passed. \param uMark Value to set the new file mark to. \return kErrorNone if successful, kErrorOutOfBounds if not. \sa GetMark() or SetMarkAtEOF() ***************************************/ Burger::eError BURGER_API Burger::File::SetMark(uintptr_t uMark) { eError uResult = kErrorNotInitialized; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Seek to the end of file if (!fseek(fp,static_cast<long>(uMark),SEEK_SET)) { uResult = kErrorNone; } else { uResult = kErrorOutOfBounds; } } return uResult; } /*! ************************************ \brief Set the current file mark at the end of the file If a file is open, set the read/write mark to the end of the file. \return kErrorNone if successful, kErrorOutOfBounds if not. \sa GetMark() or SetMark() ***************************************/ uint_t BURGER_API Burger::File::SetMarkAtEOF(void) { uint_t uResult = kErrorOutOfBounds; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { if (!fseek(fp,0,SEEK_END)) { uResult = kErrorNone; } } return uResult; } /*! ************************************ \brief Get the time the file was last modified If a file is open, query the operating system for the last time the file was modified. \param pOutput Pointer to a Burger::TimeDate_t to receive the file modification time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa GetCreationTime() or SetModificationTime() ***************************************/ Burger::eError BURGER_API Burger::File::GetModificationTime(TimeDate_t *pOutput) { pOutput->Clear(); return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Get the time the file was created If a file is open, query the operating system for the time the file was created. \param pOutput Pointer to a Burger::TimeDate_t to receive the file creation time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa GetModificationTime() or SetCreationTime() ***************************************/ Burger::eError BURGER_API Burger::File::GetCreationTime(TimeDate_t *pOutput) { pOutput->Clear(); return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Set the time the file was last modified If a file is open, call the operating system to set the file modification time to the passed value. \param pInput Pointer to a Burger::TimeDate_t to use for the new file modification time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetCreationTime() or GetModificationTime() ***************************************/ uint_t BURGER_API Burger::File::SetModificationTime(const TimeDate_t * /* pInput */) { return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Set the time the file was created If a file is open, call the operating system to set the file creation time to the passed value. \param pInput Pointer to a Burger::TimeDate_t to use for the new file creation time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetModificationTime() or GetCreationTime() ***************************************/ uint_t BURGER_API Burger::File::SetCreationTime(const TimeDate_t * /* pInput */) { return kErrorNotSupportedOnThisPlatform; } #endif uint_t BURGER_API Burger::File::OpenAsync(const char *pFileName,eFileAccess eAccess) { m_Filename.Set(pFileName); FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandOpen,nullptr,eAccess); return 0; } uint_t BURGER_API Burger::File::OpenAsync(Filename *pFileName,eFileAccess eAccess) { m_Filename = pFileName[0]; FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandOpen,nullptr,eAccess); return 0; } uint_t BURGER_API Burger::File::CloseAsync(void) { FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandClose,nullptr,0); return 0; } uint_t BURGER_API Burger::File::ReadAsync(void *pOutput,uintptr_t uSize) { FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandRead,pOutput,uSize); return 0; } /*! ************************************ \fn Burger::File::SetAuxType(uint32_t uAuxType) \brief Set the file's auxiliary type If a file is open, call the MacOS operating system to set the file's auxiliary type to the passed value. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uAuxType Value to set the file's auxiliary type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetAuxAndFileType(), SetFileType() or GetAuxType() ***************************************/ /*! ************************************ \fn Burger::File::SetFileType(uint32_t uFileType) \brief Set the file's type code If a file is open, call the MacOS operating system to set the file's type to the passed value. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uFileType Value to set the file's type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetAuxAndFileType(), SetAuxType() or GetFileType() ***************************************/ /*! ************************************ \fn Burger::File::GetAuxType(void) \brief Get the file's auxiliary type If a file is open, call the MacOS operating system to get the file's auxiliary type. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail by returning zero. \return The four byte code or zero on failure \sa SetAuxType() or GetFileType() ***************************************/ /*! ************************************ \fn Burger::File::GetFileType(void) \brief Get the file's type code If a file is open, call the MacOS operating system to get the file's type code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail by returning zero. \return The four byte code or zero on failure \sa SetFileType() or GetAuxType() ***************************************/ /*! ************************************ \fn Burger::File::SetAuxAndFileType(uint32_t uAuxType,uint32_t uFileType) \brief Set the file's auxiliary and file type If a file is open, call the MacOS operating system to set the file's auxiliary and file types to the passed values. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uAuxType Value to set the file's auxiliary type \param uFileType Value to set the file's type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetFileType() or SetAuxType() ***************************************/ /*! ************************************ \brief Read a "C" string with the terminating zero to a file stream Read a "C" string with a terminating zero from the file stream. If the string read is larger than the buffer, it is truncated. The buffer will have an ending zero on valid read or a trucated read. If uLength was zero, then pInput can be \ref NULL \param pOutput Pointer to a "C" string to write. \param uLength Size of the buffer (To prevent overruns) \return \ref TRUE if the string was read, \ref FALSE, hit EOF \sa Burger::WriteCString(FILE *,const char *) ***************************************/ uint_t BURGER_API Burger::File::ReadCString(char *pOutput,uintptr_t uLength) { // Set the maximum buffer size // and remove 1 to make space or the ending zero char *pEnd = (pOutput+uLength)-1; uint_t uTemp; for (;;) { // Stay until either zero or EOF uint8_t Buffer; if (Read(&Buffer,1)!=1) { uTemp = 666; // EOF reached break; } uTemp = Buffer; if (!uTemp) { // Exit due to end of string? break; } // Can I store it? if (pOutput<pEnd) { pOutput[0] = static_cast<char>(uTemp); ++pOutput; // Inc the input pointer } } if (uLength) { // Any space in buffer? pOutput[0] = 0; // Add ending zero } if (uTemp) { // EOF? return FALSE; // Hit the EOF. } return TRUE; // Hit the end of string (More data may be present) } /*! ************************************ \brief Read a big endian 32-bit value from a file. Given a file opened for reading, read a 32-bit value in big endian format from the file stream. \sa Burger::File::ReadBigWord16() and Burger::File::ReadLittleWord32() \return A 32 bit big endian int converted to native endian ***************************************/ uint32_t BURGER_API Burger::File::ReadBigWord32(void) { uint32_t mValue; Read(&mValue,4); // Save the long word return BigEndian::Load(&mValue); } /*! ************************************ \brief Read a big endian 16-bit value from a file. Given a file opened for reading, read a 16-bit value in big endian format from the file stream. \sa Burger::File::ReadBigWord32() and Burger::File::ReadLittleWord16() \return A 16 bit big endian short converted to native endian ***************************************/ uint16_t BURGER_API Burger::File::ReadBigWord16(void) { uint16_t mValue; Read(&mValue,2); // Save the short word return BigEndian::Load(&mValue); } /*! ************************************ \brief Read a little endian 32-bit value from a file. Given a file opened for reading, read a 32-bit value in little endian format from the file stream. \sa Burger::File::ReadLittleWord16() and Burger::File::ReadBigWord32() \return A 32 bit little endian int converted to native endian ***************************************/ uint32_t BURGER_API Burger::File::ReadLittleWord32(void) { uint32_t mValue; Read(&mValue,4); // Save the long word return LittleEndian::Load(&mValue); } /*! ************************************ \brief Read a little endian 16-bit value from a file. Given a file opened for reading, read a 16-bit value in little endian format from the file stream. \sa Burger::File::ReadLittleWord32() and Burger::File::ReadBigWord16() \return A 16 bit little endian short converted to native endian ***************************************/ uint16_t BURGER_API Burger::File::ReadLittleWord16(void) { uint16_t mValue; Read(&mValue,2); // Save the long word return LittleEndian::Load(&mValue); }
28.423797
174
0.648041
Olde-Skuul
b909222bddaf0414336790ed23872ec1ea1532c0
168
cc
C++
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
16
2016-01-12T21:36:32.000Z
2022-01-13T13:28:43.000Z
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
2
2016-01-11T22:20:01.000Z
2018-10-09T20:11:07.000Z
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
3
2016-01-11T16:12:50.000Z
2020-12-02T21:44:31.000Z
#include "allocators.h" #include "erl_nif.h" void* mem_allocate(size_t size) { return enif_alloc(size); } void mem_deallocate(void* ptr) { enif_free(ptr); }
12
31
0.690476
silviucpp
b90b91620a969c95e23a40f6f2a7381727c4d1c6
6,942
cpp
C++
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
16
2015-04-29T11:18:01.000Z
2020-09-21T20:32:08.000Z
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
null
null
null
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
2
2015-12-06T20:49:38.000Z
2021-08-14T10:33:01.000Z
/* Copyright (c) 2015, 2016, 2017 Genome Research Ltd. Copyright (c) 2014 Jouni Siren and Simon Gog Author: Jouni Siren <jouni.siren@iki.fi> Author: Simon Gog 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 <cstdlib> #include <unistd.h> #include <sdsl/construct.hpp> #include <sdsl/lcp.hpp> #include "support.h" using namespace relative; const size_type DEFAULT_SA_SAMPLE_RATE = 17; const size_type DEFAULT_ISA_SAMPLE_RATE = 64; int main(int argc, char** argv) { if(argc < 2) { std::cerr << "Usage: build_bwt [options] input1 [input2 ...]" << std::endl; std::cerr << " -i N Sample one out of N ISA values (default " << DEFAULT_ISA_SAMPLE_RATE << ")." << std::endl; std::cerr << " -l Also build the LCP array." << std::endl; std::cerr << " -s N Sample one out of N SA values (default " << DEFAULT_SA_SAMPLE_RATE << ")." << std::endl; std::cerr << std::endl; return 1; } bool build_lcp = false; size_type sa_sample_rate = DEFAULT_SA_SAMPLE_RATE, isa_sample_rate = DEFAULT_ISA_SAMPLE_RATE; int c = 0; while((c = getopt(argc, argv, "i:ls:")) != -1) { switch(c) { case 'i': isa_sample_rate = atol(optarg); break; case 'l': build_lcp = true; break; case 's': sa_sample_rate = atol(optarg); break; case '?': return 2; default: return 3; } } std::cout << "BWT construction" << std::endl; std::cout << "Options:"; if(isa_sample_rate > 0) { std::cout << " isa_sample_rate=" << isa_sample_rate; } if(build_lcp) { std::cout << " lcp"; } if(sa_sample_rate > 0) { std::cout << " sa_sample_rate=" << sa_sample_rate; } std::cout << std::endl; std::cout << std::endl; for(int i = optind; i < argc; i++) { std::string base_name = argv[i]; std::cout << "File: " << base_name << std::endl; sdsl::int_vector<8> text; sdsl::cache_config config; size_type size = 0; // Read text. { std::ifstream in(base_name.c_str(), std::ios_base::binary); if(!in) { std::cerr << "build_bwt: Cannot open input file " << base_name << std::endl; std::cout << std::endl; continue; } size = sdsl::util::file_size(base_name); text.resize(size + 1); std::cout << "Text size: " << size << std::endl; in.read((char*)(text.data()), size); text[size] = 0; in.close(); } // Build BWT and sample SA. sdsl::int_vector<0> sa_samples, isa_samples; { double start = readTimer(); sdsl::int_vector<64> sa(size + 1); divsufsort64((const unsigned char*)(text.data()), (int64_t*)(sa.data()), size + 1); if(sa_sample_rate > 0) { sa_samples = sdsl::int_vector<0>(size / sa_sample_rate + 1, 0, bit_length(size)); for(size_type i = 0; i <= size; i += sa_sample_rate) { sa_samples[i / sa_sample_rate] = sa[i]; } } if(isa_sample_rate > 0) { isa_samples = sdsl::int_vector<0>(size / isa_sample_rate + 1, 0, bit_length(size)); for(size_type i = 0; i <= size; i++) { if(sa[i] % isa_sample_rate == 0) { isa_samples[sa[i] / isa_sample_rate] = i; } } } char_type* bwt = (char_type*)(sa.data()); // Overwrite SA with BWT. size_type to_add[2] = { (size_type)-1, size }; for(size_type i = 0; i <= size; i++) { bwt[i] = text[sa[i] + to_add[sa[i] == 0]]; } for(size_type i = 0; i <= size; i++) { text[i] = bwt[i]; } sdsl::util::clear(sa); double seconds = readTimer() - start; std::cout << "BWT built in " << seconds << " seconds (" << (inMegabytes(size) / seconds) << " MB/s)" << std::endl; } // Compact the alphabet and write it. { Alphabet alpha(text); for(size_type i = 0; i <= size; i++) { text[i] = alpha.char2comp[text[i]]; } std::string filename = base_name + ALPHA_EXTENSION; if(!(sdsl::store_to_file(alpha, filename))) { std::cerr << "build_bwt: Cannot write to alphabet file " << filename << std::endl; } else { std::cout << "Alphabet written to " << filename << std::endl; } } // Write BWT. { std::string filename = base_name + BWT_EXTENSION; if(!(sdsl::store_to_file(text, filename))) { std::cerr << "build_bwt: Cannot open BWT file " << filename << std::endl; } else { std::cout << "BWT written to " << filename << std::endl; if(build_lcp) { config.file_map[sdsl::conf::KEY_BWT] = filename; } } sdsl::util::clear(text); } // Write SA/ISA samples. if(sa_sample_rate > 0 || isa_sample_rate > 0) { std::string filename = base_name + SAMPLE_EXTENSION; std::ofstream out(filename.c_str(), std::ios_base::binary); if(!out) { std::cerr << "build_bwt: Cannot open sample file " << filename << std::endl; } else { sdsl::write_member(sa_sample_rate, out); sa_samples.serialize(out); sdsl::write_member(isa_sample_rate, out); isa_samples.serialize(out); out.close(); std::cout << "Samples written to " << filename << std::endl; } sdsl::util::clear(sa_samples); sdsl::util::clear(isa_samples); } // Build and write LCP. if(build_lcp) { double start = readTimer(); construct_lcp_bwt_based(config); sdsl::int_vector_buffer<0> lcp_buffer(sdsl::cache_file_name(sdsl::conf::KEY_LCP, config)); SLArray lcp(lcp_buffer); double seconds = readTimer() - start; std::cout << "LCP array built in " << seconds << " seconds (" << (inMegabytes(size) / seconds) << " MB/s)" << std::endl; std::string filename = base_name + LCP_EXTENSION; sdsl::store_to_file(lcp, filename); lcp_buffer.close(); std::remove(sdsl::cache_file_name(sdsl::conf::KEY_LCP, config).c_str()); } std::cout << std::endl; } return 0; }
34.029412
126
0.60703
jltsiren
b914a12c1e3034e755dcdaa51963388fe0b62598
120
cpp
C++
src/common/BatchDeleteSql.cpp
luhouxiang/batch-database-demo
9669a7cb831d13c845c762333e65f1538c0d4bd2
[ "Apache-2.0" ]
1
2021-06-21T07:44:09.000Z
2021-06-21T07:44:09.000Z
src/common/BatchDeleteSql.cpp
luhouxiang/batch-database-demo
9669a7cb831d13c845c762333e65f1538c0d4bd2
[ "Apache-2.0" ]
null
null
null
src/common/BatchDeleteSql.cpp
luhouxiang/batch-database-demo
9669a7cb831d13c845c762333e65f1538c0d4bd2
[ "Apache-2.0" ]
null
null
null
#include "BatchDeleteSql.h" BatchDeleteSql::BatchDeleteSql(void) { } BatchDeleteSql::~BatchDeleteSql(void) { }
13.333333
38
0.716667
luhouxiang
2c6a0eb0b59d5e98b4af8ec5887d38bd1b3e4526
939
cpp
C++
Material/RobertLafore_Book/Solution_Book_SourceCode/Chapter-5/10.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
4
2020-12-26T03:17:45.000Z
2022-01-11T05:54:40.000Z
Material/RobertLafore_Book/Solution_Book_SourceCode/Chapter-5/10.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
null
null
null
Material/RobertLafore_Book/Solution_Book_SourceCode/Chapter-5/10.cpp
hpaucar/OOP-C-plus-plus-repo
e1fedd376029996a53d70d452b7738d9c43173c0
[ "MIT" ]
null
null
null
/* Write a function that, when you call it, displays a message telling how many times it has been called: “I have been called 3 times”, for instance. Write a main() program that calls this function at least 10 times. Try implementing this function in two different ways. First, use a global variable to store the count. Second, use a local static variable. Which is more appropriate? Why can’t you use a local variable? */ //author @Nishant #include <iostream> using namespace std; int count=0; void globalVar(); int localVar(); int main(){ for(int i=0; i<10; i++){ globalVar(); } for(int j=0; j<5; j++){ localVar(); } int lCount = localVar(); cout << "Using global variable count = " << count << endl; cout << "Using local variable count = " << lCount << endl; return 0; } void globalVar(){ count++; } int localVar(){ static int lCount = 0; lCount++; return lCount; }
23.475
91
0.651757
hpaucar
2c6a213bbd02ab9b17999421b6ffe44ea26929af
6,626
cpp
C++
Engine/Source/Editor/DetailCustomizations/Private/CameraFocusSettingsCustomization.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/DetailCustomizations/Private/CameraFocusSettingsCustomization.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/DetailCustomizations/Private/CameraFocusSettingsCustomization.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CameraFocusSettingsCustomization.h" #include "Misc/Attribute.h" #include "Templates/Casts.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Engine/GameViewportClient.h" #include "Widgets/SBoxPanel.h" #include "DetailWidgetRow.h" #include "PropertyHandle.h" #include "IDetailPropertyRow.h" #include "IDetailChildrenBuilder.h" #include "PropertyCustomizationHelpers.h" #include "CineCameraComponent.h" #include "ScopedTransaction.h" #define LOCTEXT_NAMESPACE "CameraFocusSettingsCustomization" static FName NAME_Category(TEXT("Category")); static FString ManualFocusSettingsString(TEXT("Manual Focus Settings")); static FString TrackingFocusSettingsString(TEXT("Tracking Focus Settings")); static FString GeneralFocusSettingsString(TEXT("Focus Settings")); TSharedRef<IPropertyTypeCustomization> FCameraFocusSettingsCustomization::MakeInstance() { return MakeShareable(new FCameraFocusSettingsCustomization); } void FCameraFocusSettingsCustomization::CustomizeHeader(TSharedRef<IPropertyHandle> StructPropertyHandle, FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& CustomizationUtils) { HeaderRow. NameContent() [ StructPropertyHandle->CreatePropertyNameWidget() ] .ValueContent() [ StructPropertyHandle->CreatePropertyValueWidget() ]; } void FCameraFocusSettingsCustomization::CustomizeChildren(TSharedRef<IPropertyHandle> StructPropertyHandle, class IDetailChildrenBuilder& ChildBuilder, IPropertyTypeCustomizationUtils& StructCustomizationUtils) { // Retrieve structure's child properties uint32 NumChildren; StructPropertyHandle->GetNumChildren(NumChildren); TMap<FName, TSharedPtr< IPropertyHandle > > PropertyHandles; for (uint32 ChildIndex = 0; ChildIndex < NumChildren; ++ChildIndex) { TSharedRef<IPropertyHandle> ChildHandle = StructPropertyHandle->GetChildHandle(ChildIndex).ToSharedRef(); const FName PropertyName = ChildHandle->GetProperty()->GetFName(); PropertyHandles.Add(PropertyName, ChildHandle); } // Retrieve special case properties FocusMethodHandle = PropertyHandles.FindChecked(GET_MEMBER_NAME_CHECKED(FCameraFocusSettings, FocusMethod)); ManualFocusDistanceHandle = PropertyHandles.FindChecked(GET_MEMBER_NAME_CHECKED(FCameraFocusSettings, ManualFocusDistance)); for (auto Iter(PropertyHandles.CreateConstIterator()); Iter; ++Iter) { // make the widget IDetailPropertyRow& PropertyRow = ChildBuilder.AddProperty(Iter.Value().ToSharedRef()); // set up delegate to know if we need to hide it FString const& Category = Iter.Value()->GetMetaData(NAME_Category); if (Category == ManualFocusSettingsString) { PropertyRow.Visibility(TAttribute<EVisibility>(this, &FCameraFocusSettingsCustomization::IsManualSettingGroupVisible)); } else if (Category == TrackingFocusSettingsString) { PropertyRow.Visibility(TAttribute<EVisibility>(this, &FCameraFocusSettingsCustomization::IsTrackingSettingGroupVisible)); } else if (Category == GeneralFocusSettingsString) { PropertyRow.Visibility(TAttribute<EVisibility>(this, &FCameraFocusSettingsCustomization::IsGeneralSettingGroupVisible)); } // special customization to show scene depth picker widget if (Iter.Value() == ManualFocusDistanceHandle) { TSharedPtr<SWidget> NameWidget; TSharedPtr<SWidget> ValueWidget; FDetailWidgetRow Row; PropertyRow.GetDefaultWidgets(NameWidget, ValueWidget, Row); PropertyRow.CustomWidget(/*bShowChildren*/ true) .NameContent() [ NameWidget.ToSharedRef() ] .ValueContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .VAlign(VAlign_Center) [ ValueWidget.ToSharedRef() ] + SHorizontalBox::Slot() .Padding(2.0f, 0.0f) .AutoWidth() .VAlign(VAlign_Center) [ PropertyCustomizationHelpers::MakeSceneDepthPicker(FOnSceneDepthLocationSelected::CreateSP(this, &FCameraFocusSettingsCustomization::OnSceneDepthLocationSelected)) ] ]; } } } void FCameraFocusSettingsCustomization::OnSceneDepthLocationSelected(FVector PickedSceneLoc) { if (PickedSceneLoc != FVector::ZeroVector) { // find the camera component and set it relative to that UCameraComponent* OuterCameraComponent = nullptr; { TArray<UObject*> OuterObjects; ManualFocusDistanceHandle->GetOuterObjects(OuterObjects); for (UObject* Obj : OuterObjects) { UCameraComponent* const CamComp = dynamic_cast<UCameraComponent*>(Obj); if (CamComp) { OuterCameraComponent = CamComp; break; } } } if (OuterCameraComponent) { FVector const CamToPickedLoc = PickedSceneLoc - OuterCameraComponent->GetComponentLocation(); FVector const CamForward = OuterCameraComponent->GetComponentRotation().Vector(); // if picked behind camera, don't set it if ((CamToPickedLoc | CamForward) > 0.f) { float const FinalSceneDepth = CamToPickedLoc.ProjectOnToNormal(CamForward).Size(); const FScopedTransaction Transaction(LOCTEXT("PickedSceneDepth", "Pick Scene Depth")); ensure(ManualFocusDistanceHandle->SetValue(FinalSceneDepth, EPropertyValueSetFlags::NotTransactable) == FPropertyAccess::Result::Success); } } } } EVisibility FCameraFocusSettingsCustomization::IsManualSettingGroupVisible() const { uint8 FocusMethodNumber; FocusMethodHandle->GetValue(FocusMethodNumber); ECameraFocusMethod const FocusMethod = static_cast<ECameraFocusMethod>(FocusMethodNumber); if (FocusMethod == ECameraFocusMethod::Manual) { // if focus method is set to none, all non-none setting groups are collapsed return EVisibility::Visible; } return EVisibility::Collapsed; } EVisibility FCameraFocusSettingsCustomization::IsTrackingSettingGroupVisible() const { uint8 FocusMethodNumber; FocusMethodHandle->GetValue(FocusMethodNumber); ECameraFocusMethod const FocusMethod = static_cast<ECameraFocusMethod>(FocusMethodNumber); if (FocusMethod == ECameraFocusMethod::Tracking) { // if focus method is set to none, all non-none setting groups are collapsed return EVisibility::Visible; } return EVisibility::Collapsed; } EVisibility FCameraFocusSettingsCustomization::IsGeneralSettingGroupVisible() const { uint8 FocusMethodNumber; FocusMethodHandle->GetValue(FocusMethodNumber); ECameraFocusMethod const FocusMethod = static_cast<ECameraFocusMethod>(FocusMethodNumber); if (FocusMethod != ECameraFocusMethod::None) { // if focus method is set to none, all non-none setting groups are collapsed return EVisibility::Visible; } return EVisibility::Collapsed; } #undef LOCTEXT_NAMESPACE // CameraFocusSettingsCustomization
34.154639
210
0.787504
windystrife
2c6cc68367f41d0284cd7f981f6da2ea7a251162
942
cpp
C++
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
9
2020-10-01T09:29:10.000Z
2022-02-12T04:58:41.000Z
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
6
2020-10-03T16:08:58.000Z
2020-10-14T12:06:25.000Z
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
17
2020-10-01T09:17:27.000Z
2021-06-18T09:36:31.000Z
class Solution{ public: int median(vector<vector<int>> &matrix, int r, int c){ // code here int min = INT_MAX, max = INT_MIN; // Maximum and minimum element from the array for(int i = 0;i<r;++i) { if(matrix[i][0] < min) { min = matrix[i][0]; } if(matrix[i][c-1] > max) { max = matrix[i][c-1]; } } int desired = (r*c +1)/2; while(min<max) { int mid = min + (max - min) /2; int place = 0; for(int i = 0 ;i<r;i++) { place += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); } if(place<desired) { min = mid +1; } else{ max = mid; } } return min; } };
25.459459
98
0.359873
vermagaurav8
2c6d492cbe59ce88947591fe7dbfe67dfb0cf0b7
4,038
hpp
C++
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
10
2018-09-13T17:37:22.000Z
2020-05-08T16:20:42.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
1
2018-12-02T14:17:39.000Z
2018-12-02T20:59:26.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
2
2019-03-03T12:06:10.000Z
2020-04-12T13:23:02.000Z
// // Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu> // ---------------------------------------------------------- // // 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/>. // #ifndef ZI_HEAP_BINARY_HEAP_HPP #define ZI_HEAP_BINARY_HEAP_HPP #include <zi/bits/cstdint.hpp> #include <zi/bits/hash.hpp> #include <zi/bits/unordered_map.hpp> #include <zi/utility/exception.hpp> #include <functional> #include <cstring> #include <cstdlib> #include <cstddef> #include <map> #include <zi/detail/identity.hpp> #include <zi/detail/member_function.hpp> #include <zi/detail/member_variable.hpp> #include <zi/detail/global_function.hpp> #include <zi/heap/detail/binary_heap_impl.hpp> namespace zi { namespace heap { using ::zi::detail::identity; using ::zi::detail::member_function; using ::zi::detail::const_member_function; using ::zi::detail::member_variable; using ::zi::detail::global_function; template< class KeyExtractor, class Hash = ::zi::hash< typename KeyExtractor::result_type >, class Pred = std::equal_to< typename KeyExtractor::result_type > > struct hashed_index { typedef typename KeyExtractor::result_type key_type; typedef KeyExtractor key_extractor; typedef unordered_map< const key_type, uint32_t, Hash, Pred > container_type; }; template< class KeyExtractor, class Compare = std::less< typename KeyExtractor::result_type > > struct ordered_index { typedef typename KeyExtractor::result_type key_type; typedef KeyExtractor key_extractor; typedef std::map< const key_type, uint32_t, Compare > container_type; }; template< class ValueExtractor, class ValueCompare = std::less< typename ValueExtractor::result_type > > struct value { typedef typename ValueExtractor::result_type value_type; typedef ValueExtractor value_extractor; typedef ValueCompare compare_type; }; } // namespace heap template< class Type, class IndexTraits = heap::hashed_index< heap::identity< Type > >, class ValueTraits = heap::value< heap::identity< Type > >, class Allocator = std::allocator< Type > > struct binary_heap: ::zi::heap::detail::binary_heap_impl< Type, typename IndexTraits::key_type, typename ValueTraits::value_type, typename IndexTraits::key_extractor, typename ValueTraits::value_extractor, typename ValueTraits::compare_type, typename IndexTraits::container_type, Allocator > { private: typedef typename ValueTraits::compare_type compare_type; typedef Allocator alloc_type ; typedef ::zi::heap::detail::binary_heap_impl< Type, typename IndexTraits::key_type, typename ValueTraits::value_type, typename IndexTraits::key_extractor, typename ValueTraits::value_extractor, typename ValueTraits::compare_type, typename IndexTraits::container_type, Allocator > base_type; public: binary_heap( const alloc_type& alloc ) : base_type( compare_type(), alloc ) { } binary_heap( const compare_type& compare = compare_type(), const alloc_type& alloc = alloc_type()) : base_type( compare, alloc ) { } }; } // namespace zi #endif
30.590909
82
0.668895
VCG
2c7155ffd3fe940dc76676ef5cc2c14c387fae9b
140
hxx
C++
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_BGPATTRIBUTESFORROUTE_PRIVATE_H #define __UNIX_BGPATTRIBUTESFORROUTE_PRIVATE_H #endif #endif
11.666667
46
0.864286
brunolauze
2c726e26dbc634fe32ce8ee51e3229c60d158366
1,630
cpp
C++
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
72
2021-09-13T20:29:29.000Z
2022-03-30T01:42:09.000Z
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
33
2019-01-09T11:02:15.000Z
2022-03-31T11:47:54.000Z
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
35
2019-03-06T01:54:00.000Z
2022-02-03T07:06:37.000Z
// Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 "FullBuffer.hpp" TEST_F(FullBuffer, Block_8) { fill_buffer_except(7); try_block_8(); } TEST_F(FullBuffer, Block_4) { fill_buffer_except(3); try_block_4(); } TEST_F(FullBuffer, Block_2) { fill_buffer_except(1); try_block_2(); } TEST_F(FullBuffer, Block_1) { fill_buffer_except(0); try_block_1(); } # define SUCCESSFUL_SERIALIZATION 3 # define ARRAY_SERIALIZATION (SUCCESSFUL_SERIALIZATION + 1) TEST_F(FullBuffer, ArrayBlock_8) { fill_buffer_except(8 * SUCCESSFUL_SERIALIZATION + 7); try_array_block_8(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_4) { fill_buffer_except(4 * SUCCESSFUL_SERIALIZATION + 3); try_array_block_4(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_2) { fill_buffer_except(2 * SUCCESSFUL_SERIALIZATION + 1); try_array_block_2(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_1) { fill_buffer_except(SUCCESSFUL_SERIALIZATION); try_array_block_1(ARRAY_SERIALIZATION); }
24.328358
75
0.745399
shaopengyuan
2c730117ecdbb590132104350c5016e542399781
1,456
cpp
C++
912-sort-an-array-mergesort.cpp
Iciclelz/leetcode
e4b698e0161033922851641885fdc6e47f9ce270
[ "Apache-2.0" ]
null
null
null
912-sort-an-array-mergesort.cpp
Iciclelz/leetcode
e4b698e0161033922851641885fdc6e47f9ce270
[ "Apache-2.0" ]
null
null
null
912-sort-an-array-mergesort.cpp
Iciclelz/leetcode
e4b698e0161033922851641885fdc6e47f9ce270
[ "Apache-2.0" ]
null
null
null
class Solution { public: std::vector<int32_t> sortArray(std::vector<int32_t>& v) { mergesort<int32_t>(v, [](int32_t a, int32_t b) -> bool { return a < b; }); return v; } private: template <typename T> std::vector<T> merge(std::vector<T> &a, std::vector<T> &b, std::function<bool(T, T)> &cmp) { if (a.empty()) { return b; } else if (b.empty()) { return a; } else { std::vector<T> v; v.reserve(a.size() + b.size()); size_t n = 0; size_t m = 0; while (n < a.size() && m < b.size()) { v.push_back(cmp(a[n], b[m]) ? a[n++] : b[m++]); } while (n < a.size()) { v.push_back(a[n++]); } while (m < b.size()) { v.push_back(b[m++]); } return v; } } template <typename T> void mergesort(std::vector<T> &v, std::function<bool(T, T)> cmp) { if (v.size() <= 1) { return; } std::vector<T> a(v.begin(), v.begin() + v.size() / 2); std::vector<T> b(v.begin() + v.size() / 2, v.end()); mergesort<T>(a, cmp); mergesort<T>(b, cmp); v = merge<T>(a, b, cmp); } };
24.677966
117
0.370192
Iciclelz
2c737130a6b4a3b19d530105baa65e078c00faa1
7,675
cc
C++
components/viz/common/gl_nv12_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/viz/common/gl_nv12_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/viz/common/gl_nv12_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/common/gl_nv12_converter.h" #include "base/memory/ptr_util.h" #include "components/viz/common/gl_i420_converter.h" #include "components/viz/common/gpu/context_provider.h" namespace viz { // static std::unique_ptr<GLNV12Converter> GLNV12Converter::CreateConverterForTest( ContextProvider* context_provider, bool allow_mrt_path) { return base::WrapUnique( new GLNV12Converter(context_provider, allow_mrt_path)); } GLNV12Converter::GLNV12Converter(ContextProvider* context_provider) : GLNV12Converter(context_provider, true) {} GLNV12Converter::GLNV12Converter(ContextProvider* context_provider, bool allow_mrt_path) : context_provider_(context_provider), step1_(context_provider_), step2_(context_provider_) { DCHECK(context_provider_); context_provider_->AddObserver(this); if (!allow_mrt_path || step1_.GetMaxDrawBuffersSupported() < 2) { step3_ = std::make_unique<GLScaler>(context_provider_); } } GLNV12Converter::~GLNV12Converter() { OnContextLost(); // Free context-related resources. } // static gfx::Rect GLNV12Converter::ToAlignedRect(const gfx::Rect& rect) { // Origin coordinates: FLOOR(...) const int aligned_x = ((rect.x() < 0) ? ((rect.x() - 3) / 4) : (rect.x() / 4)) * 4; const int aligned_y = ((rect.y() < 0) ? ((rect.y() - 1) / 2) : (rect.y() / 2)) * 2; // Span coordinates: CEIL(...) const int aligned_right = ((rect.right() < 0) ? (rect.right() / 4) : ((rect.right() + 3) / 4)) * 4; const int aligned_bottom = ((rect.bottom() < 0) ? (rect.bottom() / 2) : ((rect.bottom() + 1) / 2)) * 2; return gfx::Rect(aligned_x, aligned_y, aligned_right - aligned_x, aligned_bottom - aligned_y); } // static bool GLNV12Converter::ParametersAreEquivalent(const Parameters& a, const Parameters& b) { // Implemented in terms of GLI420Converter: return GLI420Converter::ParametersAreEquivalent(a, b); } void GLNV12Converter::EnsureIntermediateTextureDefined( const gfx::Size& required) { if (intermediate_texture_size_ == required) { return; } auto* const gl = context_provider_->ContextGL(); if (intermediate_texture_ == 0) { gl->GenTextures(1, &intermediate_texture_); } gl->BindTexture(GL_TEXTURE_2D, intermediate_texture_); gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, required.width(), required.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); intermediate_texture_size_ = required; } bool GLNV12Converter::Configure(const Parameters& params) { Parameters step1_params = params; if (!step1_params.output_color_space.IsValid()) { step1_params.output_color_space = gfx::ColorSpace::CreateREC709(); } // Configure the "step 1" scaler. if (is_using_mrt_path()) { step1_params.export_format = Parameters::ExportFormat::NV61; DCHECK_EQ(step1_params.swizzle[0], params.swizzle[0]); step1_params.swizzle[1] = GL_RGBA; // Don't swizzle 2nd rendering target. } else { step1_params.export_format = Parameters::ExportFormat::INTERLEAVED_QUADS; step1_params.swizzle[0] = GL_RGBA; // Will swizzle in steps 2-3. } if (!step1_.Configure(step1_params)) { return false; } // Configure the "step 2" scaler (and step 3 for the non-MRT path) that // further transform the output from the "step 1" scaler to produce the final // outputs. Parameters step2_params; step2_params.scale_to = gfx::Vector2d(1, 1); step2_params.source_color_space = step1_params.output_color_space; step2_params.output_color_space = step1_params.output_color_space; // Use FAST quality, a single bilinear pass, because there will either be no // scaling or exactly 50% scaling. step2_params.quality = Parameters::Quality::FAST; step2_params.swizzle[0] = params.swizzle[0]; if (is_using_mrt_path()) { // NV61 provides half-width and full-height U/V. NV12 UV planes are // half-width and half-height. So, scale just the Y by 50%. step2_params.scale_from = gfx::Vector2d(1, 2); step2_params.export_format = Parameters::ExportFormat::INTERLEAVED_QUADS; step2_params.swizzle[1] = step2_params.swizzle[0]; if (!step2_.Configure(step2_params)) { return false; } } else { // Extract a full-size Y plane from the interleaved YUVA from step 1. step2_params.scale_from = gfx::Vector2d(1, 1); step2_params.export_format = Parameters::ExportFormat::CHANNEL_0; if (!step2_.Configure(step2_params)) { return false; } // Extract a half-size UV plane from the interleaved YUVA from step 1. // UV_CHANNELS provides half-width and full-height UV plane. NV12 UV planes // are half-wifth and half-height. So, scale just the Y by 50%. step2_params.scale_from = gfx::Vector2d(1, 2); step2_params.export_format = Parameters::ExportFormat::UV_CHANNELS; if (!step3_->Configure(step2_params)) { return false; } } params_ = params; return true; } bool GLNV12Converter::Convert(GLuint src_texture, const gfx::Size& src_texture_size, const gfx::Vector2d& src_offset, const gfx::Rect& aligned_output_rect, const GLuint yuv_textures[2]) { DCHECK_EQ(aligned_output_rect.x() % 4, 0); DCHECK_EQ(aligned_output_rect.width() % 4, 0); DCHECK_EQ(aligned_output_rect.y() % 2, 0); DCHECK_EQ(aligned_output_rect.height() % 2, 0); if (!context_provider_) { return false; } if (is_using_mrt_path()) { const gfx::Rect luma_output_rect( aligned_output_rect.x() / 4, aligned_output_rect.y(), aligned_output_rect.width() / 4, aligned_output_rect.height()); EnsureIntermediateTextureDefined(luma_output_rect.size()); const gfx::Rect chroma_output_rect( gfx::Size(luma_output_rect.width(), luma_output_rect.height() / 2)); return (step1_.ScaleToMultipleOutputs( src_texture, src_texture_size, src_offset, yuv_textures[0], intermediate_texture_, luma_output_rect) && step2_.Scale(intermediate_texture_, intermediate_texture_size_, gfx::Vector2d(), yuv_textures[1], chroma_output_rect)); } // Non-MRT path: EnsureIntermediateTextureDefined(aligned_output_rect.size()); const gfx::Rect luma_output_rect(0, 0, aligned_output_rect.width() / 4, aligned_output_rect.height()); const gfx::Rect chroma_output_rect(0, 0, luma_output_rect.width(), luma_output_rect.height() / 2); return (step1_.Scale(src_texture, src_texture_size, src_offset, intermediate_texture_, aligned_output_rect) && step2_.Scale(intermediate_texture_, intermediate_texture_size_, gfx::Vector2d(), yuv_textures[0], luma_output_rect) && step3_->Scale(intermediate_texture_, intermediate_texture_size_, gfx::Vector2d(), yuv_textures[1], chroma_output_rect)); } void GLNV12Converter::OnContextLost() { if (intermediate_texture_ != 0) { if (auto* gl = context_provider_->ContextGL()) { gl->DeleteTextures(1, &intermediate_texture_); } intermediate_texture_ = 0; intermediate_texture_size_ = gfx::Size(); } if (context_provider_) { context_provider_->RemoveObserver(this); context_provider_ = nullptr; } } } // namespace viz
39.158163
80
0.679088
zealoussnow
2c76092f73c7aa8f3ba9540812917f283984af57
106
cpp
C++
src/add_test/library/src/echo.cpp
mariokonrad/cmake-cheatsheet
268d68327e0d6af997684ec9e0fc96b5e7276a22
[ "CC-BY-4.0" ]
36
2019-03-28T09:05:10.000Z
2022-01-13T14:33:17.000Z
src/add_test/library/src/echo.cpp
bernedom/cmake-cheatsheet
280378bafe187a525b8376ba17b73781bba08861
[ "CC-BY-4.0" ]
null
null
null
src/add_test/library/src/echo.cpp
bernedom/cmake-cheatsheet
280378bafe187a525b8376ba17b73781bba08861
[ "CC-BY-4.0" ]
5
2019-04-05T20:55:37.000Z
2021-11-01T08:40:42.000Z
#include <library/echo.hpp> namespace library { std::string echo(const std::string & s) { return s; } }
11.777778
39
0.679245
mariokonrad
2c76ac4fc6dcbeb3a656e9839bd6eaea94463abc
3,674
cpp
C++
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
7
2021-10-29T20:29:48.000Z
2022-03-03T01:38:45.000Z
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
linux/SensorsLinuxInterface.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * Copyright (C) 2019-2020 STMicroelectronics * * 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 <cstdlib> #include <cerrno> #include <iostream> #include <cstring> #include "SensorsLinuxInterface.h" #include "LinuxPropertiesLoader.h" #include <IConsole.h> static const std::string configFilename = "/etc/stm-sensors-hal/config"; SensorsLinuxInterface::SensorsLinuxInterface(void) : sensorsCore(ISTMSensorsHAL::getInstance()), console(IConsole::getInstance()), propertiesManager(PropertiesManager::getInstance()) { } /** * initialize: initialize the interface * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::initialize(void) { LinuxPropertiesLoader linuxPropertiesLoader; if (!linuxPropertiesLoader.loadFromConfigFile(configFilename)) { propertiesManager.load(linuxPropertiesLoader); } sensorsCore.initialize(*dynamic_cast<ISTMSensorsCallback *>(this)); return 0; } /** * getSensorsList: retrieve sensors list * * Return value: const reference of sensors list. */ const std::vector<STMSensor>& SensorsLinuxInterface::getSensorsList(void) const { return sensorsCore.getSensorsList().getList(); } /** * enable: enable or disable specified sensor * @handle: sensor handle ID (retrieved from sensors list). * @enable: enable or disable flag. * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::enable(uint32_t handle, bool enable) { return sensorsCore.activate(handle, enable); } /** * setRate: set sensor sampling period and batch time * @handle: sensor handle ID (retrieved from sensors list). * @samplingPeriodNanoSec: sensor sampling period in nsec. * @maxReportLatencyNanoSec: sensor batch time in nsec. * * Return value: 0 on success, else a negative error code. */ int SensorsLinuxInterface::setRate(uint32_t handle, int64_t samplingPeriodNanoSec, int64_t maxReportLatencyNanoSec) { return sensorsCore.setRate(handle, samplingPeriodNanoSec, maxReportLatencyNanoSec); } /** * onNewSensorsData: receive data from STMSensorsHAL, * reference: ISTMSensorsCallbackData class */ void SensorsLinuxInterface::onNewSensorsData(const std::vector<ISTMSensorsCallbackData> &sensorsData) { (void) sensorsData; } /** * onSaveDataRequest: receive data to store, * reference: ISTMSensorsCallbackData class */ int SensorsLinuxInterface::onSaveDataRequest(const std::string& resourceID, const void *data, ssize_t len) { (void) resourceID; (void) data; (void) len; return 0; } /** * onLoadDataRequest: load data from disk, * reference: ISTMSensorsCallbackData class */ int SensorsLinuxInterface::onLoadDataRequest(const std::string& resourceID, void *data, ssize_t len) { (void) resourceID; (void) data; (void) len; return 0; }
28.703125
96
0.688351
STMicroelectronics
2c7a7c042aec611c7029b8ec65a0be05c512621c
9,713
cc
C++
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
166
2020-11-02T05:30:35.000Z
2022-03-26T07:39:16.000Z
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
2
2020-06-02T00:12:58.000Z
2020-06-13T23:22:25.000Z
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
19
2020-11-08T02:44:09.000Z
2022-02-26T19:49:33.000Z
/* * A YCSB implementation based off of Silo's and equivalent to FOEDUS's. */ #include "bench.h" #include "ycsb.h" #ifndef ADV_COROUTINE extern uint g_reps_per_tx; extern uint g_rmw_additional_reads; extern ReadTransactionType g_read_txn_type; extern YcsbWorkload ycsb_workload; class ycsb_cs_worker : public ycsb_base_worker { public: ycsb_cs_worker( unsigned int worker_id, unsigned long seed, ermia::Engine *db, const std::map<std::string, ermia::OrderedIndex *> &open_tables, spin_barrier *barrier_a, spin_barrier *barrier_b) : ycsb_base_worker(worker_id, seed, db, open_tables, barrier_a, barrier_b) { } // Essentially a coroutine scheduler that switches between active transactions virtual void MyWork(char *) override { // No replication support ALWAYS_ASSERT(is_worker); workload = get_workload(); txn_counts.resize(workload.size()); if (ermia::config::coro_batch_schedule) { //PipelineScheduler(); BatchScheduler(); } else { Scheduler(); } } virtual workload_desc_vec get_workload() const override { workload_desc_vec w; if (ycsb_workload.insert_percent() || ycsb_workload.update_percent()) { LOG(FATAL) << "Not implemented"; } LOG_IF(FATAL, g_read_txn_type != ReadTransactionType::SimpleCoro) << "Read txn type must be simple-coro"; if (ycsb_workload.read_percent()) { w.push_back(workload_desc("Read", double(ycsb_workload.read_percent()) / 100.0, nullptr, TxnRead)); } if (ycsb_workload.rmw_percent()) { LOG_IF(FATAL, ermia::config::index_probe_only) << "Not supported"; w.push_back(workload_desc("RMW", double(ycsb_workload.rmw_percent()) / 100.0, nullptr, TxnRMW)); } if (ycsb_workload.scan_percent()) { if (ermia::config::scan_with_it) { w.push_back(workload_desc("ScanWithIterator", double(ycsb_workload.scan_percent()) / 100.0, nullptr, TxnScanWithIterator)); } else { LOG_IF(FATAL, ermia::config::index_probe_only) << "Not supported"; w.push_back(workload_desc("Scan", double(ycsb_workload.scan_percent()) / 100.0, nullptr, TxnScan)); } } return w; } static ermia::coro::generator<rc_t> TxnRead(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_read(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnRMW(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_rmw(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnScan(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_scan(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnScanWithIterator(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_scan_with_iterator(idx, begin_epoch); } // Read transaction with context-switch using simple coroutine ermia::coro::generator<rc_t> txn_read(uint32_t idx, ermia::epoch_num begin_epoch) { ermia::transaction *txn = nullptr; if (ermia::config::index_probe_only) { arenas[idx].reset(); } else { txn = db->NewTransaction( ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; } for (int i = 0; i < g_reps_per_tx; ++i) { ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; if (ermia::config::index_probe_only) { ermia::varstr &k = str(arenas[idx], sizeof(ycsb_kv::key)); new (&k) ermia::varstr((char *)&k + sizeof(ermia::varstr), sizeof(ycsb_kv::key)); BuildKey(rng_gen_key(), k); ermia::ConcurrentMasstree::threadinfo ti(begin_epoch); ermia::ConcurrentMasstree::versioned_node_t sinfo; ermia::OID oid = ermia::INVALID_OID; rc._val = (co_await table_index->GetMasstree().search_coro(k, oid, ti, &sinfo)) ? RC_TRUE : RC_FALSE; } else { ermia::varstr &k = GenerateKey(txn); rc = co_await table_index->coro_GetRecord(txn, k, v); } #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(ermia::config::index_probe_only || *(char*)v.data() == 'a'); #endif if (!ermia::config::index_probe_only) memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), sizeof(ycsb_kv::value)); } #ifndef CORO_BATCH_COMMIT if (!ermia::config::index_probe_only) { TryCatchCoro(db->Commit(txn)); } #endif co_return {RC_TRUE}; } // Read-modify-write transaction with context-switch using simple coroutine ermia::coro::generator<rc_t> txn_rmw(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { ermia::varstr &k = GenerateKey(txn); ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; rc = co_await table_index->coro_GetRecord(txn, k, v); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed LOG_IF(FATAL, rc._val != RC_TRUE); ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(*(char*)v.data() == 'a'); #endif ASSERT(v.size() == sizeof(ycsb_kv::value)); memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), v.size()); // Re-initialize the value structure to use my own allocated memory - // DoTupleRead will change v.p to the object's data area to avoid memory // copy (in the read op we just did). new (&v) ermia::varstr((char *)&v + sizeof(ermia::varstr), sizeof(ycsb_kv::value)); new (v.data()) ycsb_kv::value("a"); rc = co_await table_index->coro_UpdateRecord(txn, k, v); // Modify-write TryCatchCoro(rc); } for (int i = 0; i < g_rmw_additional_reads; ++i) { ermia::varstr &k = GenerateKey(txn); ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; rc = co_await table_index->coro_GetRecord(txn, k, v); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(*(char*)v.data() == 'a'); #endif ASSERT(v.size() == sizeof(ycsb_kv::value)); memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), v.size()); } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } ermia::coro::generator<rc_t> txn_scan(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { rc_t rc = rc_t{RC_INVALID}; ScanRange range = GenerateScanRange(txn); ycsb_scan_callback callback; rc = co_await table_index->coro_Scan(txn, range.start_key, &range.end_key, callback); ALWAYS_ASSERT(callback.size() <= g_scan_max_length); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else ALWAYS_ASSERT(rc._val == RC_TRUE); #endif } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } ermia::coro::generator<rc_t> txn_scan_with_iterator(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { rc_t rc = rc_t{RC_INVALID}; ScanRange range = GenerateScanRange(txn); ycsb_scan_callback callback; ermia::ConcurrentMasstree::coro_ScanIterator</*IsRerverse=*/false> iter(txn->GetXIDContext(), &table_index->GetMasstree(), range.start_key, &range.end_key); bool more = co_await iter.init(); ermia::varstr valptr; ermia::dbtuple* tuple = nullptr; while (more) { if (!ermia::config::index_probe_only) { tuple = ermia::oidmgr->oid_get_version( iter.tuple_array(), iter.value(), txn->GetXIDContext()); if (tuple) { rc = txn->DoTupleRead(tuple, &valptr); if (rc._val == RC_TRUE) { callback.Invoke(iter.key().data(), iter.key().length(), valptr); } } #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else ALWAYS_ASSERT(rc._val == RC_TRUE); #endif } more = iter.next(); } ALWAYS_ASSERT(ermia::config::index_probe_only || callback.size() <= g_scan_max_length); } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } }; void ycsb_cs_do_test(ermia::Engine *db, int argc, char **argv) { ycsb_parse_options(argc, argv); ycsb_bench_runner<ycsb_cs_worker> r(db); r.run(); } #endif // ADV_COROUTINE
36.107807
120
0.650777
sfu-dis
2c7e801237ea626ae741f5008f2cad677b7389ef
6,536
cpp
C++
Homeworks/miscellaneous/LW15/grade_calculator.cpp
sameer-h/CSCE121
b6a302bfc248bfaedd03ab38060e12163458c7f8
[ "MIT" ]
1
2020-11-01T21:02:03.000Z
2020-11-01T21:02:03.000Z
Homeworks/miscellaneous/LW15/grade_calculator.cpp
sameer-h/CSCE121
b6a302bfc248bfaedd03ab38060e12163458c7f8
[ "MIT" ]
null
null
null
Homeworks/miscellaneous/LW15/grade_calculator.cpp
sameer-h/CSCE121
b6a302bfc248bfaedd03ab38060e12163458c7f8
[ "MIT" ]
null
null
null
#include <vector> #include <string> #include <fstream> #include <stdexcept> #include "grade_calculator.h" //////////////////////////////////////////////////////////////////////////////// // TODO(student): implement these methods double GradeCalculator::exam_average() const { // TODO(student) double grade = 0; int countGrades = 0; double average; for (size_t i = 0; i < exam_grades.size(); ++i) { grade += exam_grades.at(i); countGrades++; } grade += final_exam; countGrades++; double examAvg = grade / countGrades; if (final_exam > examAvg) { return final_exam; } average = grade / countGrades; return average; } double GradeCalculator::zybook_average() const { // TODO(student) double grade = 0; int countGrades = 0; double average; for (size_t i = 0; i < zybook_participation_grades.size(); ++i) { grade += zybook_participation_grades.at(i); countGrades++; } for (size_t i = 0; i < zybook_challenge_grades.size(); ++i) { grade += zybook_challenge_grades.at(i); countGrades++; } double zybookAvg = grade / countGrades; if (zybookAvg >= 85) { return 100; } average = zybookAvg + 15; return average; } double GradeCalculator::hw_average() const { // TODO(student) double grade = 0; int countGrades = 0; double average; for (size_t i = 0; i < hw_grades.size(); ++i) { if (hw_redemption_grades.size() > i) { if (hw_redemption_grades.at(i) > hw_grades.at(i)) { grade += (hw_redemption_grades.at(i) - hw_grades.at(i)) / 2; } } grade += hw_grades.at(i); countGrades++; } average = grade / countGrades; return average; } double GradeCalculator::lw_average() const { // TODO(student) double grade = 0; int countGrades = 0; double average; for (size_t i = 0; i < lw_grades.size(); ++i) { grade += lw_grades.at(i); countGrades++; } average = 100 * (grade / countGrades); return average; } double GradeCalculator::final_grade_numeric() const { // TODO(student) double grade = exam_average() * (0.5) + zybook_average() * (0.07) + hw_average() * (0.35) + lw_average() * (0.08); return grade; } char GradeCalculator::final_grade_letter() const { // TODO(student) double course_avg = final_grade_numeric(); if (!has_syllabus_ack || course_avg < 60) { // no syllabus acknowledgement return 'F'; } else if (exam_average() < 60 || course_avg < 70) { return 'D'; } else if (course_avg < 80) { return 'C'; } else if (course_avg < 90) { return 'B'; } else { return 'A'; } } //////////////////////////////////////////////////////////////////////////////// void GradeCalculator::read_final_exam(std::ifstream& fin) { has_final_exam = true; fin >> final_exam; if (fin.fail()) { throw std::runtime_error("failed to read final exam grade"); } } void GradeCalculator::read_exam_hw_redemption_zybook(std::ifstream& fin, const std::string& category) { unsigned number; fin >> number; if (fin.fail()) { throw std::runtime_error("failed to read " + category + " number"); } std::vector<double>* vec; if (category == "exam") { vec = &exam_grades; } else if (category == "hw") { vec = &hw_grades; } else if (category == "hw-redemption") { vec = &hw_redemption_grades; } else if (category == "zybook") { char type; fin >> type; if (fin.fail()) { // HOW TO REACH THIS? throw std::runtime_error("failed to read " + category + " type"); } switch (type) { case 'p': vec = &zybook_participation_grades; break; case 'c': vec = &zybook_challenge_grades; break; default: throw std::runtime_error("unrecognized zybook assignment type: " + type); } } else { throw std::runtime_error("unrecognized category: " + category); } double grade; fin >> grade; if (fin.fail()) { throw std::runtime_error("failed to read "+category+" grade"); } while (number > vec->size()) { vec->push_back(0); } vec->at(number-1) = grade; } void GradeCalculator::read_lw(std::ifstream& fin) { unsigned number; fin >> number; if (fin.fail()) { throw std::runtime_error("failed to read lw number"); } std::string str; fin >> str; if (fin.fail()) { // HOW TO REACH THIS? throw std::runtime_error("failed to read lw grade"); } while (number > lw_grades.size()) { lw_grades.push_back(false); } if (str == "0" || str == "false") { lw_grades.at(number-1) = false; } else if (str == "1" || str == "true") { lw_grades.at(number-1) = true; } else { throw std::runtime_error("invalid lw grade value: " + str); } } void GradeCalculator::read_syllabus_ack(std::ifstream& fin) { std::string str; fin >> str; if (fin.fail()) { // HOW TO REACH THIS? throw std::runtime_error("failed to read syllabus-ack type"); } if (str == "0" || str == "false") { has_syllabus_ack = false; } else if (str == "1" || str == "true") { has_syllabus_ack = true; } else { throw std::runtime_error("invalid syllabus-ack grade value: " + str); } } void GradeCalculator::load_grades(const std::string& filename) { std::ifstream fin(filename); if (!fin.is_open()) { throw std::runtime_error("could not open file"); } while (!fin.eof()) { std::string category; fin >> category; if (fin.fail()) { if (fin.eof()) { continue; } // HOW TO REACH THIS? throw std::runtime_error("failed to read category"); } if (category == "final-exam") { read_final_exam(fin); } else if (category == "exam" || category == "hw" || category == "hw-redemption" || category == "zybook") { read_exam_hw_redemption_zybook(fin, category); } else if (category == "lw") { read_lw(fin); } else if (category == "syllabus-ack") { read_syllabus_ack(fin); } else { throw std::runtime_error("invalid category: " + category); } } }
25.333333
116
0.544829
sameer-h
2c7fdde362e53ae77e884f8df0b864268c483ff4
5,130
cpp
C++
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
#include "api_plugin_number.h" #include "rodsDef.h" #include "rcConnect.h" #include "rodsPackInstruct.h" #include "rcMisc.h" #include "client_api_whitelist.hpp" #include "apiHandler.hpp" #include <functional> #ifdef RODS_SERVER // // Server-side Implementation // #include "objDesc.hpp" #include "irods_stacktrace.hpp" #include "irods_server_api_call.hpp" #include "irods_re_serialization.hpp" #include "rsModDataObjMeta.hpp" #include "scoped_privileged_client.hpp" #include "key_value_proxy.hpp" #include <string> #include <tuple> namespace { // // Function Prototypes // auto call_data_object_modify_info(irods::api_entry*, rsComm_t*, modDataObjMeta_t*) -> int; auto is_input_valid(const bytesBuf_t*) -> std::tuple<bool, std::string>; auto rs_data_object_modify_info(rsComm_t*, modDataObjMeta_t*) -> int; // // Function Implementations // auto call_data_object_modify_info(irods::api_entry* api, rsComm_t* comm, modDataObjMeta_t* input) -> int { return api->call_handler<modDataObjMeta_t*>(comm, input); } auto is_input_valid(const modDataObjMeta_t* input) -> std::tuple<bool, std::string> { if (!input) { return {false, "Input is null"}; } irods::experimental::key_value_proxy proxy{*input->regParam}; const auto is_invalid_keyword = [](const auto& handle) { // To allow modification of a column, comment out the condition // referencing that column. return handle.key() == CHKSUM_KW || handle.key() == COLL_ID_KW || //handle.key() == DATA_COMMENTS_KW || handle.key() == DATA_CREATE_KW || //handle.key() == DATA_EXPIRY_KW || handle.key() == DATA_ID_KW || handle.key() == DATA_MAP_ID_KW || handle.key() == DATA_MODE_KW || //handle.key() == DATA_MODIFY_KW || handle.key() == DATA_NAME_KW || handle.key() == DATA_OWNER_KW || handle.key() == DATA_OWNER_ZONE_KW || //handle.key() == DATA_RESC_GROUP_NAME_KW || // Not defined. handle.key() == DATA_SIZE_KW || //handle.key() == DATA_TYPE_KW || handle.key() == FILE_PATH_KW || handle.key() == REPL_NUM_KW || handle.key() == REPL_STATUS_KW || handle.key() == RESC_HIER_STR_KW || handle.key() == RESC_ID_KW || handle.key() == RESC_NAME_KW || handle.key() == STATUS_STRING_KW || handle.key() == VERSION_KW; }; if (std::any_of(std::begin(proxy), std::end(proxy), is_invalid_keyword)) { return {false, "Invalid keyword found"}; } return {true, ""}; } auto rs_data_object_modify_info(rsComm_t* comm, modDataObjMeta_t* input) -> int { if (auto [valid, msg] = is_input_valid(input); !valid) { rodsLog(LOG_ERROR, msg.data()); return USER_BAD_KEYWORD_ERR; } irods::experimental::scoped_privileged_client spc{*comm}; return rsModDataObjMeta(comm, input); } using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op = rs_data_object_modify_info; #define CALL_DATA_OBJECT_MODIFY_INFO call_data_object_modify_info } // anonymous namespace #else // RODS_SERVER // // Client-side Implementation // #include "modDataObjMeta.h" namespace { using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op{}; #define CALL_DATA_OBJECT_MODIFY_INFO nullptr } // anonymous namespace #endif // RODS_SERVER // The plugin factory function must always be defined. extern "C" auto plugin_factory(const std::string& _instance_name, const std::string& _context) -> irods::api_entry* { #ifdef RODS_SERVER irods::client_api_whitelist::instance().add(DATA_OBJECT_MODIFY_INFO_APN); #endif // RODS_SERVER // clang-format off irods::apidef_t def{DATA_OBJECT_MODIFY_INFO_APN, // API number RODS_API_VERSION, // API version NO_USER_AUTH, // Client auth NO_USER_AUTH, // Proxy auth "ModDataObjMeta_PI", 0, // In PI / bs flag nullptr, 0, // Out PI / bs flag op, // Operation "data_object_modify_info", // Operation name clearModDataObjMetaInp, // Null clear function (funcPtr) CALL_DATA_OBJECT_MODIFY_INFO}; // clang-format on auto* api = new irods::api_entry{def}; api->in_pack_key = "ModDataObjMeta_PI"; api->in_pack_value = ModDataObjMeta_PI; return api; }
32.675159
94
0.569591
mcv21
2c84e904cc3b848675e7fbffbcd7bf280569228a
6,818
cpp
C++
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/AttachDetach/tls_app_ia32.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/AttachDetach/tls_app_ia32.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/AttachDetach/tls_app_ia32.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
/* * Copyright (C) 2009-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ /*! @file * We test two aspects: - tls value before and after PIN_Detach() - creation new threads while PIN is detached from application */ #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <sys/syscall.h> #include <linux/unistd.h> #include <asm/ldt.h> #include <errno.h> #include <string.h> #include <sys/utsname.h> #ifndef __NR_set_thread_area #define __NR_set_thread_area 243 #endif #ifndef __NR_get_thread_area #define __NR_get_thread_area 244 #endif #ifndef SYS_set_thread_area #define SYS_set_thread_area __NR_set_thread_area #endif #ifndef SYS_get_thread_area #define SYS_get_thread_area __NR_get_thread_area #endif #define NTHREADS 4 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; unsigned int numOfThreadsReadyForDetach = 0; unsigned long pinDetached = 0; /* This function is replaced by Pin tool */ extern "C" void TellPinToDetach(unsigned long* updateWhenReady) { return; } struct UserDesc { UserDesc() : _entry_number(0), _base_addr(0), _val1(0), _val2(0) {} unsigned int _entry_number; unsigned int _base_addr; unsigned int _val1; unsigned int _val2; }; #define TLS_GET_GS_REG() \ ( \ { \ int __seg; \ __asm("movw %%gs, %w0" : "=q"(__seg)); \ __seg & 0xffff; \ }) #define TLS_SET_GS_REG(val) __asm("movw %w0, %%gs" ::"q"(val)) #define TLS_GET_FS_REG() \ ( \ { \ int __seg; \ __asm("movw %%fs, %w0" : "=q"(__seg)); \ __seg & 0xffff; \ }) #define TLS_SET_FS_REG(val) __asm("movw %w0, %%fs" ::"q"(val)) char buf[NTHREADS][3000]; unsigned int mainThreadAddress[8192]; #define GDT_NUM_OF_ENTRIES 3 #define GDT_ENTRIES 16 unsigned int GdtFirstEntry() { static int first = 0; if (first) return first; UserDesc thrDescr; for (int i = 0; i < GDT_ENTRIES; i++) { thrDescr._entry_number = i; int res = syscall(SYS_get_thread_area, &thrDescr); if ((res == 0) || (errno != EINVAL)) { first = i; return first; } } fprintf(stderr, "First GDT entry is not found\n"); exit(-1); } /* Check that TLS remains the same after Pin is detached * */ void* thread_func(void* arg) { unsigned long thread_no = (unsigned long)arg + 1; unsigned int gs_value = TLS_GET_GS_REG(); unsigned int gdtEntryMin = GdtFirstEntry(); unsigned int gdtEntryMax = gdtEntryMin + GDT_NUM_OF_ENTRIES - 1; UserDesc thrDescr[GDT_NUM_OF_ENTRIES]; for (unsigned int i = gdtEntryMin; i <= gdtEntryMax; i++) { unsigned int ind = i - gdtEntryMin; thrDescr[ind]._entry_number = i; int res = syscall(SYS_get_thread_area, &(thrDescr[ind])); if (res != 0) { fprintf(stderr, "SYS_get_thread_area failed for entry %d with error: %s\n", thrDescr[ind]._entry_number, strerror(errno)); return (void*)1; } } while (!pinDetached) { sched_yield(); } fprintf(stderr, "thread %d runs native\n", thread_no); UserDesc thrDescrAfter[GDT_NUM_OF_ENTRIES]; for (unsigned int i = gdtEntryMin; i <= gdtEntryMax; i++) { unsigned int ind = i - gdtEntryMin; thrDescrAfter[ind]._entry_number = i; int res = syscall(SYS_get_thread_area, &(thrDescrAfter[ind])); if (res != 0) { fprintf(stderr, "SYS_get_thread_area failed for entry %d with error: %s\n", thrDescrAfter[ind]._entry_number, strerror(errno)); return (void*)1; } if (thrDescrAfter[ind]._base_addr != thrDescr[ind]._base_addr) { fprintf(stderr, "ERROR in thread %d: base addr of entry %d before detach 0x%lx; after detach 0x%lx\n", thread_no, i, thrDescrAfter[ind]._base_addr, thrDescr[ind]._base_addr); return (void*)1; } } return 0; } int main(int argc, char* argv[]) { pthread_t h[NTHREADS]; unsigned int gdtEntryMin = GdtFirstEntry(); unsigned int gdtEntryMax = gdtEntryMin + GDT_NUM_OF_ENTRIES - 1; UserDesc thrDescr[GDT_NUM_OF_ENTRIES]; for (unsigned int i = gdtEntryMin; i <= gdtEntryMax; i++) { unsigned int ind = i - gdtEntryMin; thrDescr[ind]._entry_number = i; int res = syscall(SYS_get_thread_area, &thrDescr[ind]); if (res != 0) { fprintf(stderr, "SYS_get_thread_area failed for entry %d with error: %s\n", thrDescr[ind]._entry_number, strerror(errno)); return -1; } } for (unsigned long i = 0; i < NTHREADS; i++) { pthread_create(&h[i], 0, thread_func, (void*)i); } /* * If the number of threads is big, some threads leave system call "clone" * while PIN is detached. This functionality is also tested here. */ TellPinToDetach(&pinDetached); void* result[NTHREADS]; for (unsigned long i = 0; i < NTHREADS; i++) { pthread_join(h[i], &(result[i])); } fprintf(stderr, "main thread runs native\n"); for (unsigned long i = 0; i < NTHREADS; i++) { if (result[i] != 0) { fprintf(stderr, "TEST FAILED\n"); return -1; } } UserDesc thrDescrAfter[GDT_NUM_OF_ENTRIES]; for (unsigned int i = gdtEntryMin; i <= gdtEntryMax; i++) { unsigned int ind = i - gdtEntryMin; thrDescrAfter[ind]._entry_number = i; int res = syscall(SYS_get_thread_area, &thrDescrAfter[ind]); if (res != 0) { fprintf(stderr, "SYS_get_thread_area failed for entry %d with error: %s\n", thrDescrAfter[ind]._entry_number, strerror(errno)); return -1; } if (thrDescrAfter[ind]._base_addr != thrDescr[ind]._base_addr) { fprintf(stderr, "ERROR in the main thread: base addr of entry %d before detach 0x%lx; after detach 0x%lx\n", i, thrDescr[ind]._base_addr, thrDescrAfter[ind]._base_addr); fprintf(stderr, "TEST FAILED\n"); return -1; } } fprintf(stderr, "TEST PASSED\n"); return 0; }
29.772926
128
0.560135
ArthasZhang007
2c8c834831719e425d519b2c0b9966f3d5ef31b0
1,035
cpp
C++
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
//============================================================================ // Name : 291 - The House Of Santa Claus.cpp // Author : ztrixack // Copyright : MIT License // Description : 278 The House Of Santa Claus in C++, Ansi-style // Run Time : 0.008 seconds //============================================================================ #include <iostream> #include <string> #include <algorithm> using namespace std; #define FRI(i, a, b) for (i = a; i < b; ++i) int mem[] = { 1, 2, 3, 1, 5, 3, 4, 5, 2 }; int main() { int i, x, y; bool ma; do { bool direct[5][5] = { {0, 1, 1, 0, 1}, {0, 0, 1, 0, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 0} }; ma = true; FRI (i, 0, 8) { x = min(mem[i] - 1, mem[i + 1] - 1); y = max(mem[i] - 1, mem[i + 1] - 1); if (!(direct[x][y]) || direct[y][x]) { ma = false; break; } direct[y][x] = true; } if (ma) { FRI(i, 0, 9) cout << mem[i]; cout << endl; } next_permutation(mem, mem + 9); } while (mem[0] == 1); return 0; }
25.875
110
0.416425
ztrixack
2c8fb070e02e6041d8afc175ca40059d7286a195
18,046
cpp
C++
camera/hal/intel/ipu3/common/gcss/gcss_utils.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/intel/ipu3/common/gcss/gcss_utils.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/intel/ipu3/common/gcss/gcss_utils.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright (C) 2015-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "GCSS" #include "LogHelper.h" #include "cipf_css/ia_cipf_css.h" #include "gcss.h" #include "gcss_item.h" #include "gcss_utils.h" using namespace GCSS; using namespace std; using namespace cros::intel; IGraphConfig* GraphCameraUtil::nodeGetPortById(const IGraphConfig *node, uint32_t id) { const GraphConfigNode *gcNode; GraphConfigNode *portNode; int portId; css_err_t ret; if (!node) return nullptr; gcNode = static_cast<const GraphConfigNode*>(node); GraphConfigItem::const_iterator it = gcNode->begin(); while (it != gcNode->end()) { ret = gcNode->getDescendant(GCSS_KEY_TYPE, "port", it, &portNode); if (ret != css_err_none) continue; ret = portNode->getValue(GCSS_KEY_ID, portId); if (ret == css_err_none && (uint32_t)portId == id) return portNode; } return nullptr; } css_err_t GraphCameraUtil::portGetPeer(const IGraphConfig *port, IGraphConfig **peer) { css_err_t ret = css_err_none; IGraphConfig *root; int enabled = 1; string peerName; if (port == nullptr || peer == nullptr) { LOGE("Invalid Node, cannot get the peer port"); return css_err_argument; } ret = port->getValue(GCSS_KEY_ENABLED, enabled); if (ret == css_err_none && !enabled) return css_err_noentry; root = port->getRoot(); if (root == nullptr) { LOGE("Failed to get root"); return css_err_internal; } ret = port->getValue(GCSS_KEY_PEER, peerName); if (ret != css_err_none) { LOGE("Couldn't find peer value"); return css_err_argument; } *peer = root->getDescendantByString(peerName); if (*peer == nullptr) { LOGE("Failed to find peer by name %s", peerName.c_str()); return css_err_argument; } return css_err_none; } css_err_t GraphCameraUtil::portGetFourCCInfo(const IGraphConfig *portNode, ia_uid &stageId, uint32_t &terminalId) { IGraphConfig *pgNode; // The Program group node css_err_t ret = css_err_none; int32_t pgId, portId; string type; if (portNode == nullptr) return css_err_argument; ret = portNode->getValue(GCSS_KEY_ID, portId); if (ret != css_err_none) { LOGE("Failed to get port's id"); return css_err_argument; } pgNode = portNode->getAncestor(); if (ret != css_err_none || pgNode == nullptr) { LOGE("Failed to get port ancestor"); return css_err_argument; } ret = pgNode->getValue(GCSS_KEY_TYPE, type); if (ret != css_err_none) { LOGE("Failed to get port's ancestor type "); return css_err_argument; } ret = pgNode->getValue(GCSS_KEY_PG_ID, pgId); if (ret == css_err_none) { stageId = psys_2600_pg_uid(pgId); terminalId = stageId + (uint32_t)portId; } else { stageId = 0; terminalId = (uint32_t)portId; } return css_err_none; } int32_t GraphCameraUtil::portGetDirection(const IGraphConfig *port) { int32_t direction = 0; css_err_t ret = css_err_none; ret = port->getValue(GCSS_KEY_DIRECTION, direction); if (ret != css_err_none) { LOGE("Failed to retrieve port direction, default to input"); } return direction; } bool GraphCameraUtil::portIsVirtual(const IGraphConfig *port) { string type; css_err_t ret = css_err_none; if (!port) return false; ret = port->getValue(GCSS_KEY_TYPE, type); if (ret != css_err_none) { LOGE("Failed to retrieve port type, default to input"); } return (type == string("sink")); } bool GraphCameraUtil::isEdgePort(const IGraphConfig *port) { css_err_t ret = css_err_none; IGraphConfig *peer = nullptr; IGraphConfig *peerAncestor = nullptr; int32_t portDirection; int32_t execCtxId = -1; int32_t peerExecCtxId = -1; string peerType; portDirection = GraphCameraUtil::portGetDirection(port); ret = portGetPeer(port, &peer); if (ret != css_err_none) { if (ret != css_err_noentry) { LOGE("Failed to create fourcc info for source port"); } return false; } execCtxId = GraphCameraUtil::portGetExecCtxId(port); if (execCtxId < 0) { // Fall back to stream id execCtxId = GraphCameraUtil::portGetStreamId(port); if (execCtxId < 0) return false; } /* * get the execCtx id of the peer port * we also check the ancestor for that. If the peer is a virtual sink then * it does not have ancestor. */ if (!GraphCameraUtil::portIsVirtual(peer)) { peerAncestor = peer->getAncestor(); if (peerAncestor == nullptr) { LOGE("Failed to get peer's ancestor"); return false; } ret = peerAncestor->getValue(GCSS_KEY_EXEC_CTX_ID, peerExecCtxId); if (ret != css_err_none) { LOGV("Failed to get exec ctx ID of peer PG. Trying to use stream id"); // Fall back to stream id ret = peerAncestor->getValue(GCSS_KEY_STREAM_ID, peerExecCtxId); if (ret != css_err_none) { LOGE("Failed to get stream ID of peer PG %s", print(peerAncestor).c_str()); return false; } } /* * Retrieve the type of the peer ancestor. It could be it is not a * program group node but a sink or hw block */ peerAncestor->getValue(GCSS_KEY_TYPE, peerType); } if (portDirection == PORT_DIRECTION_INPUT) { /* * input port, * The port is on the edge, if the peer is a hw block, or has a * different execCtx id */ if ((execCtxId != peerExecCtxId) || (peerType == string("hw"))) { return true; } } else { /* * output port, * The port is on the edge if the peer is a virtual port, or has a * different execCtx id */ if (portIsVirtual(peer) || (execCtxId != peerExecCtxId)) { return true; } } return false; } int GraphCameraUtil::portGetStreamId(const IGraphConfig *port) { int i = portGetKey(port, GCSS_KEY_STREAM_ID); if (i < 0) LOGE("Failed to get %s", ItemUID::key2str(GCSS_KEY_STREAM_ID)); return i; } /** * Retrieve the existing ctx id's of the program group nodes * in the graph settings passed as parameter. * * \param[in] settings Head node of the graph config settings * \param[out] execCtxIds Set with the found executions context ids * * \return css_err_none * \return other if a node of type program group did not have an execution * context associated with it */ css_err_t GraphCameraUtil::getExecCtxIds(const IGraphConfig &settings, std::set<int32_t> &execCtxIds) { css_err_t ret(css_err_none); uint32_t descendentCount = settings.getDescendantCount(); IGraphConfig* nodePtr(nullptr); for (uint32_t i = 0; i < descendentCount; i++) { nodePtr = settings.iterateDescendantByIndex(GCSS_KEY_TYPE, GCSS_KEY_PROGRAM_GROUP, i); if (nodePtr != nullptr) { int32_t execCtxId(-1); ret = nodePtr->getValue(GCSS_KEY_EXEC_CTX_ID, execCtxId); if (ret == css_err_none) execCtxIds.insert(execCtxId); } } return ret; } int GraphCameraUtil::portGetExecCtxId(const IGraphConfig *port) { return portGetKey(port, GCSS_KEY_EXEC_CTX_ID); } int GraphCameraUtil::portGetKey(const IGraphConfig *port, ia_uid uid) { css_err_t ret = css_err_none; const IGraphConfig *ancestor; int32_t keyValue = -1; string type; if (port == nullptr) { LOGE("Invalid Node, cannot get the port execCtx id"); return -1; } ret = port->getValue(GCSS_KEY_TYPE, type); if (ret != css_err_none) { LOGE("Failed to get Node Type"); return -1; } /* Virtual sinks do not have nested ports, but instead the * peer attributes point to sink node itself. Therefore, * with sinks we do not need to traverse to anchestor.*/ if (type == "sink") { ancestor = port; } else { ancestor = port->getAncestor(); if (ancestor == nullptr) { LOGE("Failed to get port's ancestor"); return -1; } } ret = ancestor->getValue(uid, keyValue); if (ret != css_err_none) { return -1; } return keyValue; } css_err_t GraphCameraUtil::getDimensions(const IGraphConfig *node, int32_t *w, int32_t *h, int32_t *bpl, int32_t *l, int32_t *t, int32_t *r, int32_t *b) { css_err_t ret; if (!node) return css_err_argument; if (w) { ret = node->getValue(GCSS_KEY_WIDTH, *w); if (ret != css_err_none) { LOGE("Error: Couldn't get width"); return css_err_noentry; } } if (h) { ret = node->getValue(GCSS_KEY_HEIGHT, *h); if (ret != css_err_none) { LOGE("Error: Couldn't get height"); return css_err_noentry; } } if (bpl) { ret = node->getValue(GCSS_KEY_BYTES_PER_LINE, *bpl); if (ret != css_err_none) { LOGE("Error: Couldn't get bpl"); return css_err_noentry; } } if (l) { ret = node->getValue(GCSS_KEY_LEFT, *l); if (ret != css_err_none) { LOGE("Error: Couldn't get left crop"); return css_err_noentry; } } if (t) { ret = node->getValue(GCSS_KEY_TOP, *t); if (ret != css_err_none) { LOGE("Error: Couldn't get top crop"); return css_err_noentry; } } if (r) { ret = node->getValue(GCSS_KEY_RIGHT, *r); if (ret != css_err_none) { LOGE("Error: Couldn't get right crop"); return css_err_noentry; } } if (b) { ret = node->getValue(GCSS_KEY_BOTTOM, *b); if (ret != css_err_none) { LOGE("Error: Couldn't get bottom crop"); return css_err_noentry; } } return css_err_none; } css_err_t GraphCameraUtil::sensorGetBinningFactor(const IGraphConfig *node, int &hBin, int &vBin) { css_err_t ret = css_err_none; if (!node) return css_err_argument; ret = node->getValue(GCSS_KEY_BINNING_H_FACTOR, hBin); if (ret != css_err_none) { LOGE("Error: Couldn't get horizontal binning factor"); return ret; } ret = node->getValue(GCSS_KEY_BINNING_V_FACTOR, vBin); if (ret != css_err_none) { LOGE("Error: Couldn't get vertical binning factor"); return ret; } return css_err_none; } css_err_t GraphCameraUtil::sensorGetScalingFactor(const IGraphConfig *node, int &scalingNum, int &scalingDenom) { css_err_t ret = css_err_none; if (!node) return css_err_argument; ret = node->getValue(GCSS_KEY_SCALING_FACTOR_NUM, scalingNum); if (ret != css_err_none) { LOGE("Error: Couldn't get width scaling num ratio"); return ret; } ret = node->getValue(GCSS_KEY_SCALING_FACTOR_DENOM, scalingDenom); if (ret != css_err_none) { LOGE("Error: Couldn't get width scaling num ratio"); return ret; } return css_err_none; } /** * DEPRECATED TO BE REMOVED. * Kept here to allow a backward compatible change. * XOS tests would need to move to getInputPort * Then it can be deleted. */ css_err_t GraphCameraUtil::streamGetInputPort(int32_t execCtxId, const IGraphConfig *graphHandle, IGraphConfig **port) { return getInputPort(GCSS_KEY_STREAM_ID, execCtxId, graphHandle, port); } css_err_t GraphCameraUtil::getInputPort(ia_uid uid, int32_t execCtxId, const IGraphConfig *graphHandle, IGraphConfig **port) { css_err_t ret = css_err_none; GraphConfigNode *tmp = nullptr; GraphConfigNode *pgNode = nullptr; IGraphConfig *result = nullptr; int32_t execCtxIdFound = -1; if (graphHandle == nullptr || port == nullptr) { LOGE("nullptr pointer given"); return css_err_argument; } *port = nullptr; // Use the handle to get pointer to the root of the graph GraphConfigNode *root = static_cast<GraphConfigNode*>(graphHandle->getRoot()); GraphConfigItem::const_iterator it = root->begin(); while (it != root->end()) { ret = root->getDescendant(GCSS_KEY_TYPE, "program_group", it, &pgNode); if (ret != css_err_none) continue; ret = pgNode->getValue(uid, execCtxIdFound); if ((ret == css_err_none) && (execCtxIdFound == execCtxId)) { GraphConfigItem::const_iterator it = pgNode->begin(); while (it != pgNode->end()) { ret = pgNode->getDescendant(GCSS_KEY_TYPE, "port", it, &tmp); if (ret != css_err_none) continue; result = tmp; int32_t direction = portGetDirection(result); if (direction == PORT_DIRECTION_INPUT) { GCSS::IGraphConfig *peer; ret = portGetPeer(result, &peer); if (ret != css_err_none) { LOGV("%s: no peer", __FUNCTION__); continue; } peer = peer->getAncestor(); if (ret != css_err_none) continue; int32_t peerExecCtxId; ret = peer->getValue(uid, peerExecCtxId); if (ret != css_err_none) { LOGV("%s: no %s for peer %s", __FUNCTION__, ItemUID::key2str(uid), print(peer).c_str()); continue; } std::string str; ret = peer->getValue(GCSS_KEY_TYPE, str); if (ret != css_err_none) { continue; } /* If the ancestor is not a PG, we've reached the end */ if (str != "program_group") { *port = result; return css_err_none; } if (peerExecCtxId == execCtxId) continue; /* assuming only one input per execCtx */ *port = result; return css_err_none; } } } } return (*port == nullptr) ? css_err_argument : css_err_none; } css_err_t GraphCameraUtil::getProgramGroups(ia_uid uid, int32_t value, const GCSS::IGraphConfig *GCHandle, std::vector<IGraphConfig*> &pgs) { css_err_t ret = css_err_none; GraphConfigNode *result; std::vector<GraphConfigNode*> allProgramGroups; int32_t idFound = -1; const GraphConfigNode *temp = static_cast<const GraphConfigNode*>(GCHandle); GraphConfigNode::const_iterator it = temp->begin(); while (it != temp->end()) { ret = temp->getDescendant(GCSS_KEY_TYPE, "program_group", it, &result); if (ret == css_err_none) allProgramGroups.push_back(result); } if (allProgramGroups.empty()) { LOGE("Failed to find any PG's for value id %d" " BUG(check graph config file)", value); return css_err_general; } for (size_t i = 0; i < allProgramGroups.size(); i++) { ret = allProgramGroups[i]->getValue(uid, idFound); if ((ret == css_err_none) && (idFound == value)) { pgs.push_back(static_cast<IGraphConfig*>(allProgramGroups[i])); } } return css_err_none; } std::string GraphCameraUtil::print(const IGraphConfig *node) { string retstr = ""; string value; css_err_t ret; ret = node->getValue(GCSS_KEY_TYPE, value); if (ret != css_err_none) { value = "NODE"; } retstr += value + "["; ret = node->getValue(GCSS_KEY_NAME, value); if (ret != css_err_none) { value = "NA"; /** \todo fetch node key and key2str */ } retstr += value + "]"; /** \todo based on type port, kernel, also fetch ancestor info */ return retstr; }
30.076667
82
0.556245
strassek
2c950ea8bc485bc27cc267776101ac911fe8a0d2
1,630
cc
C++
maze/MZCharacter.cc
nandor/MAZE
fd19cff7d82dd9db44925661455dacb3e0a0b38e
[ "BSD-3-Clause" ]
1
2018-03-17T14:23:54.000Z
2018-03-17T14:23:54.000Z
maze/MZCharacter.cc
nandor/MAZE
fd19cff7d82dd9db44925661455dacb3e0a0b38e
[ "BSD-3-Clause" ]
null
null
null
maze/MZCharacter.cc
nandor/MAZE
fd19cff7d82dd9db44925661455dacb3e0a0b38e
[ "BSD-3-Clause" ]
null
null
null
// This file is part of the MAZE project // Licensing information can be found in the LICENSE file // (C) 2012 The MAZE project. All rights reserved. #include "MZPlatform.h" using namespace MAZE; // ------------------------------------------------------------------------------------------------ Character::Character(Engine *engine) : Entity(engine, CHARACTER) { } // ------------------------------------------------------------------------------------------------ Character::~Character() { } // ------------------------------------------------------------------------------------------------ void Character::Update(float time, float dt) { Entity::Update(time, dt); } // ------------------------------------------------------------------------------------------------ void Character::UpdateInternals() { mBoxWorld = mBoxModel.Move(mPosition); } // ------------------------------------------------------------------------------------------------ void Character::Render(RenderBuffer* buffer, RenderMode mode) { ObjectRenderData* data; switch (mode) { case Entity::RENDER_GBUFFER: { buffer->Objects.resize(buffer->Objects.size() + 1); data = &(*buffer->Objects.rbegin()); break; } case Entity::RENDER_SHADOW: { buffer->ShadowCasters.resize(buffer->ShadowCasters.size() + 1); data = &(*buffer->ShadowCasters.rbegin()); break; } } for (size_t i = 0; i < MAX_BONES; ++i) { data->Skin[i] = glm::mat4(1.0f); } data->TextureMatrix = glm::mat2(1.0f); data->ModelMatrix = mModelMat; data->Position = mPosition; data->model = mModel; data->Handle = fHandle; data->Skinned = true; }
25.873016
99
0.469325
nandor
2c9a4be39b6f62045c34b2d32e6883bbca91d8c0
453
cc
C++
sandbox/policy/linux/bpf_print_backend_policy_linux.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
sandbox/policy/linux/bpf_print_backend_policy_linux.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
sandbox/policy/linux/bpf_print_backend_policy_linux.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/policy/linux/bpf_print_backend_policy_linux.h" namespace sandbox { namespace policy { PrintBackendProcessPolicy::PrintBackendProcessPolicy() = default; PrintBackendProcessPolicy::~PrintBackendProcessPolicy() = default; } // namespace policy } // namespace sandbox
30.2
73
0.788079
zealoussnow
2c9ba5f1643b1cd82cb93145c7fca4d5cf0795fc
2,673
cpp
C++
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <iomanip> #include "Connect4State.h" #include "humanplayer.h" #include "autoc4player.h" #include "l181139AIplayer.h" using namespace std; void BlankLines(int n) { for (int i = 0; i < n; i++) cout << "\n"; } void ShowConnect4(GameState *C) { Connect4State *C4 = static_cast<Connect4State *>(C); string P1 = C4->GetPlayerName(0); string P2 = C4->GetPlayerName(1); cout << "\t\t" << P1 << "\t\t vs \t\t" << P2; BlankLines(3); for (int i = 1; i < 8; i++) { if (i == 1) cout << setw(8) << i; else cout << setw(11) << i; } BlankLines(3); for (int r = 0; r < 6; r++) { for (int c = 0; c < 7; c++) { if (c == 0) cout << setw(2) << "|"; char PlayerCode = C4->getState(r, c); cout << setw(6) << PlayerCode << setw(5) << "|"; } cout << endl; for (int b = 0; r < 5 && b < 2; b++) { for (int c = 0; r < 5 && c < 7; c++) { if (c == 0) cout << setw(2) << "|"; cout << setw(6) << ' ' << setw(5) << "|"; } cout << endl; } } for (int i = 0; i < 80; i++) cout << char(220); if (C4->GetTurningPlayer() == 1) cout << endl << "Turn of " << P2; else cout << endl << "Turn of " << P1; cout << endl << endl; } int main() { Player *Players[3]; int InvalidMoveCount[3]; Players[1] = new l181139AIplayer("Malik", 'L'); //Players[1] = new l181139AIplayer("Malik", 'P'); Players[0] = new HumanPlayer("Human1", 'H'); //Players[1] = new HumanPlayer("Human2", 'K'); //Players[1] = new AutoC4Player('L'); Players[2] = new AutoC4Player('B'); int TotalPlayers = 2; for (int i = 0; i < TotalPlayers - 1; i++) { for (int j = i + 1; j < TotalPlayers; j++) { GameState *C4 = new Connect4State(); C4->AddPlayer(Players[i]); C4->AddPlayer(Players[j]); int TurningPlayer; int Toggle = 1; while (!C4->GameOver()) { if (Toggle) { ShowConnect4(C4); } Toggle = (Toggle + 1) % 2; TurningPlayer = C4->GetTurningPlayer(); cout << "Player Turning: " << C4->GetPlayerName(TurningPlayer) << "-" << C4->GetPlayerColor(TurningPlayer) << endl; if (!C4->MakeMove()) { TurningPlayer = C4->GetTurningPlayer(); InvalidMoveCount[TurningPlayer]++; cout << "made invalid Move\n"; ShowConnect4(C4); system("pause"); } } ShowConnect4(C4); cout << "\nWho Won?\n" << C4->WhoWon() << " Color:" << C4->GetPlayerColor(C4->WhoWon()); } } return 0; }
22.090909
123
0.495698
ghostdart
2c9c77633a0c1777af09aa7d61a0ee6dbf81c06d
2,058
cpp
C++
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
2
2019-07-15T05:01:57.000Z
2019-09-25T20:23:04.000Z
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
#include "hcExam01.h" #include "GenHeader.h" #include "GenItem.h" #include "GenOption.h" #include "GenText.h" #include "Log.h" #include <vector> void hcExam01(std::ofstream &LaTeXfile) { LOGD("Generating LaTeX started", 3); const bool IS_CORRECT{true}; // std::vector<message_t> messages; // std::shared_ptr<GenExams> pMCtst(new GenExams(messages)); // pMCtst->setID("Hard coded test1"); // std::shared_ptr<GenItem> pI; // std::shared_ptr<GenText> pT1; // std::shared_ptr<GenText> pT2; // std::shared_ptr<GenText> pT3; // std::shared_ptr<GenJava> pJ1; // std::shared_ptr<GenJava> pJ2; // std::shared_ptr<GenOption> pO1; // std::shared_ptr<GenOption> pO2; // std::shared_ptr<GenOption> pO3; // std::shared_ptr<GenOption> pO4; // std::shared_ptr<GenImage> pImg; auto pHeader = std::make_shared<GenHeader>(); pHeader->setID("h1"); pHeader->School = "HAN Engineering"; pHeader->Course = "Introduction C programming"; pHeader->Lecturer = "Jos Onokiewicz"; pHeader->Other = "22th September 2018"; pHeader->BoxedText = "Success!"; // pMCtst->add(pHeader); // Item #1 ------------------------------------------------------------------ auto pItem = std::make_unique<GenItem>(); pItem->setID("I1"); auto pText1 = std::make_unique<GenText>(pItem->getID() + ".txt", "Welk van de volgende typen gebruik je om aan te geven dat het een " "variabele tekst bevat?"); auto pO1 = std::make_unique<GenOption>("O1", "Character"); auto pO2 = std::make_unique<GenOption>("O2", "char"); auto pO3 = std::make_unique<GenOption>("O3", "String"); auto pO4 = std::make_unique<GenOption>("O4", "String[ ]"); // pItem->addToStem(pText1); // pItem->addToOptions(pO1); // pItem->addToOptions(pO2); // pItem->addToOptions(pO3, IS_CORRECT); // pItem->addToOptions(pO4); // pItem->shuffleON(); // pMCtst->add(pI); // pMCtst->generate(TexFile); LOGD("Generating LaTeX ready", 3); }
31.181818
80
0.6069
josokw
2ca4465ca23c9ca59239947c9babf8dd0212fafd
1,486
hpp
C++
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-06T03:04:40.000Z
2019-07-20T15:35:00.000Z
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
6
2018-11-30T08:04:45.000Z
2019-05-15T03:04:28.000Z
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-11T11:51:22.000Z
2020-05-11T07:27:31.000Z
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_SOCKET_HPP__ #define __STOUT_OS_SOCKET_HPP__ #include <stout/error.hpp> #include <stout/try.hpp> #include <stout/os/int_fd.hpp> #ifdef __WINDOWS__ #include <stout/os/windows/socket.hpp> #else #include <stout/os/posix/socket.hpp> #endif // __WINDOWS__ namespace net { // Returns a socket file descriptor for the specified options. // NOTE: on OS X, the returned socket will have the SO_NOSIGPIPE option set. inline Try<int_fd> socket(int family, int type, int protocol) { int_fd s; if ((s = ::socket(family, type, protocol)) < 0) { return ErrnoError(); } #ifdef __APPLE__ // Disable SIGPIPE via setsockopt because OS X does not support // the MSG_NOSIGNAL flag on send(2). const int enable = 1; if (setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &enable, sizeof(int)) == -1) { return ErrnoError(); } #endif // __APPLE__ return s; } } // namespace net { #endif // __STOUT_OS_SOCKET_HPP__
28.037736
76
0.728129
sagar8192
2ca604241ad4a9089d3cdf3375eaef03d46f60d3
1,505
cpp
C++
cpp/test/longest_common_subsequence_test.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
3
2017-07-08T05:18:33.000Z
2021-06-11T13:49:37.000Z
cpp/test/longest_common_subsequence_test.cpp
kondratyev-nv/training
ed28507694bc2026867b67c26dc9c4a955b24fb4
[ "Unlicense" ]
44
2017-10-05T20:23:03.000Z
2022-02-10T19:50:21.000Z
cpp/test/longest_common_subsequence_test.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
4
2017-10-06T19:29:55.000Z
2022-01-04T23:25:18.000Z
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "longest_common_subsequence.hpp" TEST(longest_common_subsequence, returns_zero_for_empty_vector) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {}), testing::ElementsAre()); ASSERT_THAT(longest_common_subsequence({}, {1, 2, 3}), testing::ElementsAre()); } TEST(longest_common_subsequence, returns_zero_for_no_common_symbols) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {4, 5, 6}), testing::ElementsAre()); } TEST(longest_common_subsequence, returns_one_for_single_common_symbol) { ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {4, 5, 6, 2}), testing::ElementsAre(2)); } TEST(longest_common_subsequence, returns_for_multiple_common_symbols) { ASSERT_THAT(longest_common_subsequence({2, 7, 5}, {2, 5}), testing::ElementsAre(2, 5)); ASSERT_THAT(longest_common_subsequence({2, 7, 8, 3}, {5, 2, 8, 7}), testing::AnyOf(testing::ElementsAre(2, 7), testing::ElementsAre(2, 8))); ASSERT_THAT(longest_common_subsequence({1, 2, 2, 3, 1, 4}, {2, 5, 3, 5, 1, 6, 4}), testing::ElementsAre(2, 3, 1, 4)); } TEST(longest_common_subsequence, returns_for_three_sequences) { ASSERT_THAT(longest_common_subsequence({8, 3, 2, 1, 7}, {8, 2, 1, 3, 8, 10, 7}, {6, 8, 3, 1, 4, 7}), testing::AnyOf(testing::ElementsAre(8, 3, 7), testing::ElementsAre(8, 1, 7))); ASSERT_THAT(longest_common_subsequence({1, 2, 3}, {2, 1, 3}, {1, 3, 5}), testing::ElementsAre(1, 3)); }
47.03125
105
0.684385
CarnaViire
2ca7539b80257bbd05ffd4326b8e38518434b4d4
2,733
cpp
C++
RayTracer/src/AABox.cpp
MadEqua/Ray-Tracer
b49c9e1da8d1e4edffdc4152c27a46fd6ead871b
[ "MIT" ]
1
2021-11-02T10:47:00.000Z
2021-11-02T10:47:00.000Z
RayTracer/src/AABox.cpp
MadEqua/Ray-Tracer
b49c9e1da8d1e4edffdc4152c27a46fd6ead871b
[ "MIT" ]
null
null
null
RayTracer/src/AABox.cpp
MadEqua/Ray-Tracer
b49c9e1da8d1e4edffdc4152c27a46fd6ead871b
[ "MIT" ]
1
2021-04-15T18:40:36.000Z
2021-04-15T18:40:36.000Z
#include "AABox.h" #include "Utils.h" AABox::AABox(const vec3 &center, const vec3 &dimensions, const Material &material) : min(vec3(center.x - dimensions.x / 2.0f, center.y - dimensions.y / 2.0f, center.z - dimensions.z / 2.0f)), max(vec3(center.x + dimensions.x / 2.0f, center.y + dimensions.y / 2.0f, center.z + dimensions.z / 2.0f)), Object(center, material) { } AABox::AABox(const vec3 &center, const vec3 &min, const vec3 max, const Material &material) : min(min), max(max), Object(center, material) { } AABox::~AABox() { } const Intersection AABox::intersect(const Ray &ray) const { Intersection intersection(&ray, this, -1); float tmin = (min.x - ray.orig.x) / ray.dir.x; float tmax = (max.x - ray.orig.x) / ray.dir.x; if (tmin > tmax) swap(tmin, tmax); float tymin = (min.y - ray.orig.y) / ray.dir.y; float tymax = (max.y - ray.orig.y) / ray.dir.y; if (tymin > tymax) swap(tymin, tymax); if ((tmin > tymax) || (tymin > tmax)) return intersection; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (min.z - ray.orig.z) / ray.dir.z; float tzmax = (max.z - ray.orig.z) / ray.dir.z; if (tzmin > tzmax) swap(tzmin, tzmax); if ((tmin > tzmax) || (tzmin > tmax)) return intersection; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; intersection.rayT = tmin > 0 ? tmin : tmax; return intersection; } const SurfacePointData AABox::getSurfacePointData(const Intersection &intersection) const { SurfacePointData data; const vec3 &surfacePoint = intersection.getIntersectionPosition(); const float epsilon = 0.001f; if (Utils::floatEquals(surfacePoint.x, min.x, epsilon)) { data.normal = { -1, 0, 0 }; data.tangent = {0, 0 , 1}; data.bitangent = { 0, 1, 0 }; } else if (Utils::floatEquals(surfacePoint.x, max.x, epsilon)) { data.normal = { 1, 0, 0 }; data.tangent = { 0, 0, 1 }; data.bitangent = { 0, 1, 0 }; } else if (Utils::floatEquals(surfacePoint.y, min.y, epsilon)) { data.normal = { 0, -1, 0 }; data.tangent = { 1, 0, 0 }; data.bitangent = { 0, 0, 1 }; } else if (Utils::floatEquals(surfacePoint.y, max.y, epsilon)){ data.normal = { 0, 1, 0 }; data.tangent = { 1, 0, 1 }; data.bitangent = { 0, 0, 1 }; } else if (Utils::floatEquals(surfacePoint.z, min.z, epsilon)) { data.normal = { 0, 0, -1 }; data.tangent = { 1, 0, 0 }; data.bitangent = { 0, 1, 0 }; } else if (Utils::floatEquals(surfacePoint.z, max.z, epsilon)) { data.normal = { 0, 0, 1 }; data.tangent = { 1, 0, 0 }; data.bitangent = { 0, 1, 0 }; } data.position = surfacePoint; //texcoords? return data; }
25.783019
107
0.600439
MadEqua
2ca7d5a766386b8acd33397e6800e2896350a71f
1,900
cpp
C++
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
#include "pch.h" #define _WIN32_WINNT 0x0501 #include "Server.h" int main() { cout << "Server is Running..." << endl << endl; for (;;) { Server newServer; boost::asio::io_service NewService; tcp::acceptor NewAcceptor(NewService, tcp::endpoint(tcp::v4(), 4523)); //listen to new Connection tcp::socket ServerSocket(NewService); //ServerSide Socket creation NewAcceptor.accept(ServerSocket); //waiting for connection //After Connection enstablished string ClientGetName = newServer.Read(ServerSocket); //Catch client MsgName string ClientGetSurname = newServer.Read(ServerSocket); //Catch client MsgSurname string ClientGetAM = newServer.Read(ServerSocket); //Catch client MsgAm int ResponseResult = 0; cout << "Client Name: " << ClientGetName.c_str(); cout << "Client Surname: " << ClientGetSurname.c_str(); cout << "Client Am: " << ClientGetAM.c_str(); if (stoi(ClientGetAM) < 0) { cout << "Negative AM Error" << endl; newServer.Send(ServerSocket, "Negative AM Error"); //Response }//if else { if (((ClientGetName.length() + ClientGetSurname.length()) % 2) == 0) //name + surname letters are even { for (int i = 0; i <= stoi(ClientGetAM); ++i) { if (i % 2 == 0) ++ResponseResult; //number of even numbers from 0-ClientAm } //for } //if else { for (int i = 1; i <= stoi(ClientGetAM); ++i) //name + surname letters are odd { if (i % 2 != 0) ++ResponseResult; //number of odd numbers from 1-ClientAm } //for } //else cout << "Result sent Back:" << to_string(ResponseResult).c_str() << endl; string Return = "The Result is:" + to_string(ResponseResult) + "\n"; newServer.Send(ServerSocket, Return); //Response } //else cout << endl; ResponseResult = 0; //reset } //for infinite loop return 0; } //main
30.15873
106
0.625263
AlexanderArgyriou
2ca7f75cb63717982860d4014419e8413417a5cf
220
cpp
C++
Test/Expect/test109.cpp
dMajoIT/spin2cpp
f2ee655d150c9d69042b2dfaf8cae57123b7702c
[ "MIT" ]
39
2015-02-10T13:43:24.000Z
2022-03-08T14:56:41.000Z
Test/Expect/test109.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
230
2015-04-12T22:04:54.000Z
2022-03-30T05:22:11.000Z
Test/Expect/test109.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
21
2016-03-05T05:15:06.000Z
2022-03-24T11:58:15.000Z
#define __SPIN2CPP__ #include <propeller.h> #include "test109.h" int32_t test109::Readdelta(int32_t Encid) { int32_t Deltapos = 0; Deltapos = 0 + (Encid < Totdelta); Totdelta = -(!Totdelta); return Deltapos; }
16.923077
41
0.695455
dMajoIT
2ca87bae7f11b13142de7d3ee4935ff338a1a172
10,072
cpp
C++
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
6
2019-11-18T16:05:12.000Z
2021-06-16T16:11:41.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
26
2019-10-17T14:59:31.000Z
2022-02-07T17:06:30.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
7
2020-03-13T07:17:07.000Z
2022-03-29T07:58:37.000Z
#include <iostream> #include <random> #include <lsAdvect.hpp> #include <lsBooleanOperation.hpp> #include <lsConvexHull.hpp> #include <lsDomain.hpp> #include <lsExpand.hpp> #include <lsMakeGeometry.hpp> #include <lsPrune.hpp> #include <lsSmartPointer.hpp> #include <lsToDiskMesh.hpp> #include <lsToMesh.hpp> #include <lsToSurfaceMesh.hpp> #include <lsToVoxelMesh.hpp> #include <lsVTKWriter.hpp> /** 3D Example showing how to use the library for topography simulation. A hexagonal pattern of rounded cones is formed. These cones are then used as masks for etching. A uniform layer is then deposited on top creating voids in the structure. \example PatternedSubstrate.cpp */ // implement velocity field describing a directional etch class directionalEtch : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int material, const std::array<double, 3> &normalVector, unsigned long /*pointId*/) { // etch directionally if (material > 0) { return (normalVector[2] > 0.) ? -normalVector[2] : 0; } else { return 0; } } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // implement velocity field describing an isotropic deposition class isotropicDepo : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { // deposit isotropically everywhere return 1; } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // create a rounded cone as the primitive pattern. // Define a pointcloud and create a hull mesh using lsConvexHull. void makeRoundCone(lsSmartPointer<lsMesh<>> mesh, hrleVectorType<double, 3> center, double radius, double height) { // cone is just a circle with a point above the center auto cloud = lsSmartPointer<lsPointCloud<double, 3>>::New(); // frist inside top point { hrleVectorType<double, 3> topPoint = center; topPoint[2] += height; cloud->insertNextPoint(topPoint); } // now create all points of the base unsigned numberOfBasePoints = 40; unsigned numberOfEdgePoints = 7; for (unsigned i = 0; i < numberOfBasePoints; ++i) { double angle = double(i) / double(numberOfBasePoints) * 2. * 3.141592; for (unsigned j = 1; j <= numberOfEdgePoints; ++j) { double distance = double(j) / double(numberOfEdgePoints) * radius; double pointHeight = std::sqrt(double(numberOfEdgePoints - j) / double(numberOfEdgePoints)) * height; double x = center[0] + distance * cos(angle); double y = center[1] + distance * sin(angle); cloud->insertNextPoint( hrleVectorType<double, 3>(x, y, center[2] + pointHeight)); } } lsConvexHull<double, 3>(mesh, cloud).apply(); } int main() { constexpr int D = 3; omp_set_num_threads(6); // scale in micrometers double coneDistance = 3.5; double xExtent = 21; double yConeDelta = std::sqrt(3) * coneDistance / 2; double yExtent = 6 * yConeDelta; double gridDelta = 0.15; double bounds[2 * D] = {-xExtent / 2., xExtent / 2., -yExtent / 2., yExtent / 2., -5, 5}; lsDomain<double, D>::BoundaryType boundaryCons[D]; boundaryCons[0] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[1] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[2] = lsDomain<double, D>::BoundaryType::INFINITE_BOUNDARY; auto substrate = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); { double origin[3] = {0., 0., 0.001}; double planeNormal[3] = {0., 0., 1.}; auto plane = lsSmartPointer<lsPlane<double, D>>::New(origin, planeNormal); lsMakeGeometry<double, D>(substrate, plane).apply(); } // copy the structure to add the pattern on top auto pattern = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); pattern->setLevelSetWidth(2); // Create varying cones and put them in hexagonal pattern --------- { std::cout << "Creating pattern..." << std::endl; // need to place cone one grid delta below surface to avoid rounding hrleVectorType<double, D> coneCenter(-xExtent / 2.0 + coneDistance / 2.0, -3 * yConeDelta, -gridDelta); double coneRadius = 1.4; double coneHeight = 1.5; // adjust since cone is slightly below the surface { double gradient = coneHeight / coneRadius; coneRadius += gridDelta / gradient; coneHeight += gridDelta * gradient; } // random radius cones double variation = 0.1; std::mt19937 gen(532132432); std::uniform_real_distribution<> dis(1 - variation, 1 + variation); // for each row for (unsigned j = 0; j < 6; ++j) { // for each cone in a row for (unsigned i = 0; i < 6; ++i) { // make ls from cone mesh and add to substrate auto cone = lsSmartPointer<lsDomain<double, D>>::New( bounds, boundaryCons, gridDelta); // create cone auto coneMesh = lsSmartPointer<lsMesh<>>::New(); makeRoundCone(coneMesh, coneCenter, coneRadius * dis(gen), coneHeight * dis(gen)); lsFromSurfaceMesh<double, D>(cone, coneMesh, false).apply(); lsBooleanOperation<double, D> boolOp(pattern, cone, lsBooleanOperationEnum::UNION); boolOp.apply(); // now shift mesh for next bool coneCenter[0] += coneDistance; } coneCenter[0] = -xExtent / 2. + ((j % 2) ? coneDistance / 2.0 : 0); coneCenter[1] += yConeDelta; } } lsBooleanOperation<double, D>(substrate, pattern, lsBooleanOperationEnum::UNION) .apply(); // Etch the substrate under the pattern --------------------------- unsigned numberOfEtchSteps = 30; std::cout << "Advecting" << std::endl; lsAdvect<double, D> advectionKernel; advectionKernel.insertNextLevelSet(pattern); advectionKernel.insertNextLevelSet(substrate); { auto velocities = lsSmartPointer<directionalEtch>::New(); advectionKernel.setVelocityField(velocities); // Now advect the level set, outputting every // advection step. Save the physical time that // passed during the advection. double passedTime = 0.; for (unsigned i = 0; i < numberOfEtchSteps; ++i) { std::cout << "\rEtch step " + std::to_string(i) + " / " << numberOfEtchSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(numberOfEtchSteps) + ".vtp") .apply(); } std::cout << "Time passed during directional etch: " << passedTime << std::endl; } // make disk mesh and output { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToDiskMesh<double, 3>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, lsFileFormatEnum::VTP, "diskMesh.vtp").apply(); } // Deposit new layer ---------------------------------------------- // new level set for new layer auto fillLayer = lsSmartPointer<lsDomain<double, D>>::New(substrate); { auto velocities = lsSmartPointer<isotropicDepo>::New(); advectionKernel.setVelocityField(velocities); advectionKernel.insertNextLevelSet(fillLayer); // stop advection in voids, which will form advectionKernel.setIgnoreVoids(true); double passedTime = 0.; unsigned numberOfDepoSteps = 30; for (unsigned i = 0; i < numberOfDepoSteps; ++i) { std::cout << "\rDepo step " + std::to_string(i) + " / " << numberOfDepoSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + 1 + i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>( mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + numberOfDepoSteps) + ".vtp") .apply(); } std::cout << "Time passed during isotropic deposition: " << passedTime << std::endl; } // now output the final level sets { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "final-substrate.vtp").apply(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "final-fillLayer.vtp").apply(); } return 0; }
34.611684
80
0.606732
YourKarma42
2ca90626c2839ad729800f30daddb71e9c9d17de
699
cpp
C++
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define pb push_back using namespace std; // Pillai's Arithmetical Function search result to for(i = 1 until n) sum += gcd(i, n) vector<int> Divisors(int n){ vector<int>v; for(int i=1; i*i <= n; i++){ if(n%i == 0){ v.pb(i); if(i != (n/i))v.pb(n/i); } } return v; } double phi(int n){ double totient = n; for(int i=2; i*i<=n; i++){ if(n%i == 0){ while(n%i == 0) n/=i; totient *= (1.0 -(1.0/(double)i)); } } if(n>1) totient *= (1.0 -(1.0/(double)n)); return totient; } int main(){ int n, ans = 0; cin >> n; vector<int> d = Divisors(n); for(auto a : d){ ans += a*phi(n/a); } cout << ans << endl; return 0; }
14.265306
87
0.515021
igortakeo
2caf4f07438e65cc804bea91704c942233c37e81
4,344
cpp
C++
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
/** * File "Client.cpp" * Created by Sina on Sun May 31 13:39:03 2015. */ #include "Client.h" Client::Client(string name, address IP, address serverIp, int routerPort) : SuperClient(IP, serverIp, routerPort) { this->name = name; } void Client::run(){ fd_set router_fds, read_fds; FD_ZERO(&router_fds); FD_ZERO(&read_fds); FD_SET(0, &router_fds); FD_SET(routerFd, &router_fds); sh(routerFd); int max_fd = routerFd; while(true){ read_fds = router_fds; if(select(max_fd+1, &read_fds, NULL, NULL, NULL) < 0) throw Exeption("problem in sockets select!"); for(int client_fd=0; client_fd<=max_fd ; client_fd++) { try { if(FD_ISSET(client_fd , &read_fds)) { if(client_fd==0) { //cerr<<"in recive\n"; string cmd; getline(cin, cmd); parseCmd(cmd); } else if(client_fd==routerFd) { //cerr<<"sock recive\n"; Packet p; p.recive(routerFd); parsePacket(p); } } } catch(Exeption ex) { cout<<ex.get_error()<<endl; } } } } void Client::updateGroups(string data){ istringstream iss(data); string name, addr; while(iss>>name>>addr){ groups[name] = stringToAddr(addr); } } void Client::parsePacket(Packet p){ if(p.getType() == GET_GROUPS_LIST){ cout<<"Groups are:\n"; cout<<p.getDataStr(); updateGroups(p.getDataStr()); } else if(p.getType() == DATA){ //SuperClient::reciveUnicast(p); cout<<"Data: "<<p.getDataStr()<<endl; } else if(p.getType() == SHOW_MY_GROUPS){ cout<<"i'm in groups:\n"<<p.getDataStr()<<endl; } } void Client::parseCmd(string line){ string cmd0, cmd1, cmd2; istringstream iss(line); iss>>cmd0; if(cmd0=="Get"){ if(iss>>cmd1>>cmd2 && cmd1=="group" && cmd2=="list"){ getGroupList(); cout<<"group list request sent.\n"; } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Select"){ if(iss>>cmd1){ selectGroup(cmd1); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Join"){ if(iss>>cmd1){ joinGroup(cmd1); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Send"){ if(iss>>cmd1 && cmd1=="message"){ string message; getline(iss, message); sendMessage(message); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Show"){ if(iss>>cmd1 && cmd1=="group"){ showGroup(); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="SendUniCast"){ if(iss>>cmd1>>cmd2){ SuperClient::sendUnicast(stringToAddr(cmd1), cmd2); } else { throw Exeption("invalid cmd"); } } } void Client::sendMessage(string message){ if(selGroup == "") throw Exeption("no Group selected!\n"); Packet p; p.setType(SEND_MESSAGE); p.setSource(IP); p.setDest(groups[selGroup]); p.setData(message); p.send(routerFd); } void Client::getGroupList(){ Packet p; p.setType(GET_GROUPS_LIST); p.setSource(IP); p.setDest(serverIP); p.send(routerFd); } void Client::showGroup(){ Packet p; p.setType(SHOW_MY_GROUPS); p.setSource(IP); p.setDest(serverIP); p.send(routerFd); } void Client::selectGroup(string g){ if(groups.count(g)<=0) throw Exeption("Group does not exist"); selGroup = g; cout<<"group "<< g << " with ip " << addrToString( groups[g] ) <<" selected!\n"; } void Client::joinGroup(string g){ if(groups.count(g)<=0) throw Exeption("Group does not exist"); Packet p; p.setType(REQ_JOIN); p.setSource(IP); p.setDest(serverIP); p.setData(g); p.send(routerFd); cout<<"group "<< g << " with ip " << addrToString( groups[g] ) <<" joined!\n"; }
24.542373
84
0.508748
laboox
2cafb68262c344939433dd3300226cc9f8519380
7,369
cpp
C++
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
3
2018-11-14T07:20:39.000Z
2021-12-20T20:32:48.000Z
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
null
null
null
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
3
2020-04-28T13:10:05.000Z
2021-12-20T13:32:12.000Z
/********************************************************************************* Copyright (c) 2010, Vernier Software & Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Vernier Software & Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VERNIER SOFTWARE & TECHNOLOGY 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. **********************************************************************************/ // GPortRef.cpp #include "stdafx.h" #include "GPortRef.h" #include "GUtils.h" #include "GTextUtils.h" #ifdef _DEBUG #include "GPlatformDebug.h" // for DEBUG_NEW definition #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef LIB_NAMESPACE namespace LIB_NAMESPACE { #endif namespace { const cppstring k_sPortRefCode = "PortRef"; const cppstring k_sPortTypeCode = "PortType"; const cppstring k_sLocationCode = "Location"; const cppstring k_sDisplayNameCode = "DisplayName"; } // local namespace GPortRef &GPortRef::operator=(const GPortRef &source) { m_ePortType = source.GetPortType(); m_sLocation = source.GetLocation(); m_sDisplayName = source.GetDisplayName(); m_USBVendorID = source.GetUSBVendorID(); m_USBProductID = source.GetUSBProductID(); return *this; } GPortRef::GPortRef(const GPortRef & source) { m_ePortType = source.GetPortType(); m_sLocation = source.GetLocation(); m_sDisplayName = source.GetDisplayName(); m_USBVendorID = source.GetUSBVendorID(); m_USBProductID = source.GetUSBProductID(); } GPortRef & GPortRef::Assign(const GPortRef & src) { SetPortType(src.GetPortType()); SetLocation(src.GetLocation()); SetDisplayName(src.GetDisplayName()); SetUSBVendorID(src.GetUSBVendorID()); SetUSBProductID(src.GetUSBProductID()); return (*this); } void GPortRef::EncodeToString(cppstring * pOutString) { if (pOutString != NULL) { cppsstream ss; EncodeToStream(&ss); *pOutString = ss.str(); } } void GPortRef::EncodeToStream(cppostream * pOutStream) { // We use a single XML tag to encode the port ref to the stream. // The tag is self-terminating; all fields are attributes. // Note that the DECODE method does not require all fields to be // present and does not care about their order. // REVISIT - use GXMLUtils to just build an element an write it. if (pOutStream != NULL) { *pOutStream << GSTD_S("<") << k_sPortRefCode << GSTD_S(" "); *pOutStream << k_sPortTypeCode << GSTD_S("=\"") << GetPortType() << GSTD_S("\" "); *pOutStream << k_sLocationCode << GSTD_S("=\"") << GetLocation() << GSTD_S("\" "); *pOutStream << k_sDisplayNameCode << GSTD_S("=\"") << GetDisplayName() << GSTD_S("\" "); *pOutStream << "/>"; } } int GPortRef::DecodeFromString(const cppstring & sInString) { int nResult = kResponse_Error; cppstring::size_type nSearchStartPos = 0; cppstring::size_type nCurrentPos = 0; cppstring::size_type nNextPos = 0; cppstring::size_type nTestPos = 0; // ensure that we have a GPortRef tag... nSearchStartPos = sInString.find(k_sPortRefCode, 0); if (nSearchStartPos != cppstring::npos) nSearchStartPos += k_sPortRefCode.length(); if (nSearchStartPos >= sInString.length()) nSearchStartPos = cppstring::npos; if (nSearchStartPos != cppstring::npos) nTestPos = sInString.find_last_of('>'); if (nTestPos != cppstring::npos) { cppstring sSubStr; // decode port-type nCurrentPos = sInString.find(k_sPortTypeCode, nSearchStartPos); nCurrentPos += k_sPortTypeCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if ( nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_ePortType = (EPortType) GTextUtils::CPPStringToLong(sSubStr.c_str()); sSubStr = GSTD_S(""); // decode location nCurrentPos = sInString.find(k_sLocationCode, nSearchStartPos); nCurrentPos += k_sLocationCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if ( nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_sLocation = sSubStr; sSubStr = GSTD_S(""); // decode display-name nCurrentPos = sInString.find(k_sDisplayNameCode, nSearchStartPos); nCurrentPos += k_sDisplayNameCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if (nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_sDisplayName = sSubStr; sSubStr = GSTD_S(""); } return nResult; } int GPortRef::DecodeFromStream(cppistream * pInStream) { // REVISIT - use GXMLUtils to extract the element int nResult = kResponse_Error; if (pInStream != NULL) { // Get the text from the in-stream up until the next ">"... cppstring sText; std::getline(*pInStream, sText, GSTD_S('>')); if (sText.length() > 0) { sText += GSTD_S('>'); nResult = DecodeFromString(sText); } } return nResult; } #ifdef LIB_NAMESPACE } #endif
33.495455
91
0.680825
lionel-rigoux
2cb44c32b00921be289eb1bda4abe8b1df738f99
12,598
cc
C++
third_party/blink/renderer/core/html/link_web_bundle.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
third_party/blink/renderer/core/html/link_web_bundle.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
third_party/blink/renderer/core/html/link_web_bundle.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/html/link_web_bundle.h" #include "base/unguessable_token.h" #include "services/network/public/mojom/web_bundle_handle.mojom-blink.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/html/cross_origin_attribute.h" #include "third_party/blink/renderer/core/html/html_link_element.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/loader/threadable_loader.h" #include "third_party/blink/renderer/core/loader/threadable_loader_client.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/loader/cors/cors.h" #include "third_party/blink/renderer/platform/loader/fetch/bytes_consumer.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/loader/fetch/subresource_web_bundle_list.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver_set.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" namespace blink { class WebBundleLoader : public GarbageCollected<WebBundleLoader>, public ThreadableLoaderClient, public network::mojom::WebBundleHandle { public: WebBundleLoader(LinkWebBundle& link_web_bundle, Document& document, const KURL& url, CrossOriginAttributeValue cross_origin_attribute_value) : link_web_bundle_(&link_web_bundle), url_(url), security_origin_(SecurityOrigin::Create(url)), web_bundle_token_(base::UnguessableToken::Create()), task_runner_( document.GetFrame()->GetTaskRunner(TaskType::kInternalLoading)), receivers_(this, document.GetExecutionContext()) { ResourceRequest request(url); request.SetUseStreamOnResponse(true); // TODO(crbug.com/1082020): Revisit these once the fetch and process the // linked resource algorithm [1] for <link rel=webbundle> is defined. // [1] // https://html.spec.whatwg.org/multipage/semantics.html#fetch-and-process-the-linked-resource request.SetRequestContext( mojom::blink::RequestContextType::SUBRESOURCE_WEBBUNDLE); // https://github.com/WICG/webpackage/blob/main/explainers/subresource-loading.md#requests-mode-and-credentials-mode request.SetMode(network::mojom::blink::RequestMode::kCors); switch (cross_origin_attribute_value) { case kCrossOriginAttributeNotSet: case kCrossOriginAttributeAnonymous: request.SetCredentialsMode( network::mojom::CredentialsMode::kSameOrigin); break; case kCrossOriginAttributeUseCredentials: request.SetCredentialsMode(network::mojom::CredentialsMode::kInclude); break; } request.SetRequestDestination( network::mojom::RequestDestination::kWebBundle); request.SetPriority(ResourceLoadPriority::kHigh); mojo::PendingRemote<network::mojom::WebBundleHandle> web_bundle_handle; receivers_.Add(web_bundle_handle.InitWithNewPipeAndPassReceiver(), task_runner_); request.SetWebBundleTokenParams(ResourceRequestHead::WebBundleTokenParams( url_, web_bundle_token_, std::move(web_bundle_handle))); ExecutionContext* execution_context = document.GetExecutionContext(); ResourceLoaderOptions resource_loader_options( execution_context->GetCurrentWorld()); resource_loader_options.data_buffering_policy = kDoNotBufferData; loader_ = MakeGarbageCollected<ThreadableLoader>(*execution_context, this, resource_loader_options); loader_->Start(std::move(request)); } void Trace(Visitor* visitor) const override { visitor->Trace(link_web_bundle_); visitor->Trace(loader_); visitor->Trace(receivers_); } bool HasLoaded() const { return !failed_; } // ThreadableLoaderClient void DidStartLoadingResponseBody(BytesConsumer& consumer) override { // Drain |consumer| so that DidFinishLoading is surely called later. consumer.DrainAsDataPipe(); } void DidFail(uint64_t, const ResourceError&) override { DidFailInternal(); } void DidFailRedirectCheck(uint64_t) override { DidFailInternal(); } // network::mojom::WebBundleHandle void Clone(mojo::PendingReceiver<network::mojom::WebBundleHandle> receiver) override { receivers_.Add(std::move(receiver), task_runner_); } void OnWebBundleError(network::mojom::WebBundleErrorType type, const std::string& message) override { link_web_bundle_->OnWebBundleError(url_.ElidedString() + ": " + message.c_str()); } void OnWebBundleLoadFinished(bool success) override { if (failed_) return; failed_ = !success; link_web_bundle_->NotifyLoaded(); } const KURL& url() const { return url_; } scoped_refptr<SecurityOrigin> GetSecurityOrigin() const { return security_origin_; } const base::UnguessableToken& WebBundleToken() const { return web_bundle_token_; } void ClearReceivers() { // Clear receivers_ explicitly so that resources in the netwok process are // released. receivers_.Clear(); } private: void DidFailInternal() { if (failed_) return; failed_ = true; link_web_bundle_->NotifyLoaded(); } Member<LinkWebBundle> link_web_bundle_; Member<ThreadableLoader> loader_; bool failed_ = false; KURL url_; scoped_refptr<SecurityOrigin> security_origin_; base::UnguessableToken web_bundle_token_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // we need ReceiverSet here because WebBundleHandle is cloned when // ResourceRequest is copied. HeapMojoReceiverSet<network::mojom::WebBundleHandle, WebBundleLoader> receivers_; }; // static bool LinkWebBundle::IsFeatureEnabled(const ExecutionContext* context) { return context && context->IsSecureContext() && RuntimeEnabledFeatures::SubresourceWebBundlesEnabled(context); } LinkWebBundle::LinkWebBundle(HTMLLinkElement* owner) : LinkResource(owner) { UseCounter::Count(owner_->GetDocument().GetExecutionContext(), WebFeature::kSubresourceWebBundles); } LinkWebBundle::~LinkWebBundle() = default; void LinkWebBundle::Trace(Visitor* visitor) const { visitor->Trace(bundle_loader_); LinkResource::Trace(visitor); SubresourceWebBundle::Trace(visitor); } void LinkWebBundle::NotifyLoaded() { if (owner_) owner_->ScheduleEvent(); } void LinkWebBundle::OnWebBundleError(const String& message) const { if (!owner_) return; ExecutionContext* context = owner_->GetDocument().GetExecutionContext(); if (!context) return; context->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kWarning, message)); } void LinkWebBundle::Process() { if (!owner_ || !owner_->GetDocument().GetFrame()) return; if (!owner_->ShouldLoadLink()) return; ResourceFetcher* resource_fetcher = owner_->GetDocument().Fetcher(); if (!resource_fetcher) return; SubresourceWebBundleList* active_bundles = resource_fetcher->GetOrCreateSubresourceWebBundleList(); // We don't support crossorigin= attribute's dynamic change. It seems // other types of link elements doesn't support that too. See // HTMLlinkElement::ParseAttribute, which doesn't call Process() for // crossorigin= attribute change. if (!bundle_loader_ || bundle_loader_->url() != owner_->Href()) { if (active_bundles->GetMatchingBundle(owner_->Href())) { // This can happen when a requested bundle is a nested bundle. // // clang-format off // Example: // <link rel="webbundle" href=".../nested-main.wbn" resources=".../nested-sub.wbn"> // <link rel="webbundle" href=".../nested-sub.wbn" resources="..."> // clang-format on if (bundle_loader_) { active_bundles->Remove(*this); ReleaseBundleLoader(); } NotifyLoaded(); OnWebBundleError("A nested bundle is not supported: " + owner_->Href().ElidedString()); return; } bundle_loader_ = MakeGarbageCollected<WebBundleLoader>( *this, owner_->GetDocument(), owner_->Href(), GetCrossOriginAttributeValue( owner_->FastGetAttribute(html_names::kCrossoriginAttr))); } active_bundles->Add(*this); } LinkResource::LinkResourceType LinkWebBundle::GetType() const { return kOther; } bool LinkWebBundle::HasLoaded() const { return bundle_loader_ && bundle_loader_->HasLoaded(); } void LinkWebBundle::OwnerRemoved() { if (!owner_) return; ResourceFetcher* resource_fetcher = owner_->GetDocument().Fetcher(); if (!resource_fetcher) return; SubresourceWebBundleList* active_bundles = resource_fetcher->GetOrCreateSubresourceWebBundleList(); active_bundles->Remove(*this); if (bundle_loader_) ReleaseBundleLoader(); } bool LinkWebBundle::CanHandleRequest(const KURL& url) const { if (!url.IsValid()) return false; if (!ResourcesOrScopesMatch(url)) return false; if (url.Protocol() == "urn") return true; DCHECK(bundle_loader_); if (!bundle_loader_->GetSecurityOrigin()->IsSameOriginWith( SecurityOrigin::Create(url).get())) { OnWebBundleError(url.ElidedString() + " cannot be loaded from WebBundle " + bundle_loader_->url().ElidedString() + ": bundled resource must be same origin with the bundle."); return false; } if (!url.GetString().StartsWith(bundle_loader_->url().BaseAsString())) { OnWebBundleError( url.ElidedString() + " cannot be loaded from WebBundle " + bundle_loader_->url().ElidedString() + ": bundled resource path must contain the bundle's path as a prefix."); return false; } return true; } bool LinkWebBundle::ResourcesOrScopesMatch(const KURL& url) const { if (!owner_) return false; if (owner_->ValidResourceUrls().Contains(url)) return true; for (const auto& scope : owner_->ValidScopeUrls()) { if (url.GetString().StartsWith(scope.GetString())) return true; } return false; } String LinkWebBundle::GetCacheIdentifier() const { DCHECK(bundle_loader_); return bundle_loader_->url().GetString(); } const KURL& LinkWebBundle::GetBundleUrl() const { DCHECK(bundle_loader_); return bundle_loader_->url(); } const base::UnguessableToken& LinkWebBundle::WebBundleToken() const { DCHECK(bundle_loader_); return bundle_loader_->WebBundleToken(); } void LinkWebBundle::ReleaseBundleLoader() { DCHECK(bundle_loader_); // Clear receivers explicitly here, instead of waiting for Blink GC. bundle_loader_->ClearReceivers(); bundle_loader_ = nullptr; } // static KURL LinkWebBundle::ParseResourceUrl(const AtomicString& str) { // The implementation is almost copy and paste from ParseExchangeURL() defined // in services/data_decoder/web_bundle_parser.cc, replacing GURL with KURL. // TODO(hayato): Consider to support a relative URL. KURL url(str); if (!url.IsValid()) return KURL(); // Exchange URL must not have a fragment or credentials. if (url.HasFragmentIdentifier() || !url.User().IsEmpty() || !url.Pass().IsEmpty()) return KURL(); // For now, we allow only http:, https: and urn: schemes in Web Bundle URLs. // TODO(crbug.com/966753): Revisit this once // https://github.com/WICG/webpackage/issues/468 is resolved. if (!url.ProtocolIsInHTTPFamily() && !url.ProtocolIs("urn")) return KURL(); return url; } } // namespace blink
36.944282
120
0.720829
DamieFC
2cb6c94b694687676e30311e354d1d830ba7d363
421
hpp
C++
src/pattern-aggregator.hpp
Rutvik28/dfc
86ce00057c358f91d38826d3c36c95ad0d7b4b74
[ "MIT" ]
null
null
null
src/pattern-aggregator.hpp
Rutvik28/dfc
86ce00057c358f91d38826d3c36c95ad0d7b4b74
[ "MIT" ]
1
2019-09-19T21:31:36.000Z
2019-09-23T04:43:25.000Z
src/pattern-aggregator.hpp
skindstrom/dfc
4d7b9c29bc791c0a18a325478eafbeb459b48758
[ "MIT" ]
null
null
null
#ifndef DFC_PATTERN_AGGREGATOR_HPP #define DFC_PATTERN_AGGREGATOR_HPP #include <vector> #include "immutable-pattern.hpp" namespace dfc { class PatternAggregator { private: std::vector<RawPattern> patterns_; public: void add(RawPattern pat); std::vector<ImmutablePattern> aggregate(); private: void removeDuplicates(); std::vector<ImmutablePattern> createPatterns() const; }; } // namespace dfc #endif
17.541667
55
0.760095
Rutvik28
2cb925922e5aab8253a8ee29367255f1a2b29f6b
8,461
cpp
C++
CocosWidget/Slider.cpp
LingJiJian/Tui-x
e00e79109db466143ed2b399a8991be4e5fea28f
[ "MIT" ]
67
2015-02-09T03:20:59.000Z
2022-01-17T05:53:07.000Z
CocosWidget/Slider.cpp
fuhongxue/Tui-x
9b288540a36942dd7f3518dc3e12eb2112bd93b0
[ "MIT" ]
3
2015-04-14T01:47:27.000Z
2016-03-15T06:56:04.000Z
CocosWidget/Slider.cpp
fuhongxue/Tui-x
9b288540a36942dd7f3518dc3e12eb2112bd93b0
[ "MIT" ]
34
2015-02-18T04:42:07.000Z
2019-08-15T05:34:46.000Z
/**************************************************************************** Copyright (c) 2014 Lijunlin - Jason lee Created by Lijunlin - Jason lee on 2014 jason.lee.c@foxmail.com http://www.cocos2d-x.org 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 "Slider.h" NS_CC_WIDGET_BEGIN CSlider::CSlider() : m_pSlider(NULL) , m_bDrag(false) { setThisObject(this); } CSlider::~CSlider() { } CSlider* CSlider::create() { CSlider* pRet = new CSlider(); if( pRet && pRet->init() ) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } CSlider* CSlider::create(const char* pSlider, const char* pProgress) { CSlider* pRet = new CSlider(); if( pRet && pRet->initWithSlider(pSlider, pProgress) ) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } bool CSlider::initWithSlider(const char* pSlider, const char* pProgress) { setSliderImage(pSlider); if( initWithFile(pProgress) ) { return true; } return false; } CSlider* CSlider::createSpriteFrame(const char* pSlider, const char* pProgress) { CSlider* pRet = new CSlider(); if (pRet && pRet->initWithSliderSpriteFrame(pSlider, pProgress)) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } bool CSlider::initWithSliderSpriteFrame(const char* pSlider, const char* pProgress) { setSliderSpriteFrameName(pSlider); if (initWithFileSpriteFrame(pProgress)) { return true; } return false; } void CSlider::setContentSize(const Size& tSize) { if( m_pSlider && m_pProgressSprite ) { const Size& tSliderSize = m_pSlider->getContentSize(); Size tTargetSize; tTargetSize.width = m_tProgressSize.width + tSliderSize.width; tTargetSize.height = m_tProgressSize.height + tSliderSize.height; CProgressBar::setContentSize(tTargetSize); return; } CProgressBar::setContentSize(tSize); } int CSlider::valueFromPercent(float fPercentage) { return (int)(fPercentage * m_nMaxValue); } int CSlider::valueFromPoint(const Vec2& tPoint) { int nRet = 0; switch( m_eDirection ) { case eProgressBarDirectionLeftToRight: { float fHalfWidth = m_tProgressSize.width / 2; if( tPoint.x < m_tCenterPoint.x - fHalfWidth ) { nRet = m_nMinValue; break; } if( tPoint.x > m_tCenterPoint.x + fHalfWidth ) { nRet = m_nMaxValue; break; } float fStartPoint = tPoint.x - (m_tCenterPoint.x - fHalfWidth); float fPercentage = fStartPoint / m_tProgressSize.width; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionRightToLeft: { float fHalfWidth = m_tProgressSize.width / 2; if( tPoint.x < m_tCenterPoint.x - fHalfWidth ) { nRet = m_nMaxValue; break; } if( tPoint.x > m_tCenterPoint.x + fHalfWidth ) { nRet = m_nMinValue; break; } float fStartPoint = tPoint.x - (m_tCenterPoint.x - fHalfWidth); float fPercentage = (m_tProgressSize.width - fStartPoint) / m_tProgressSize.width; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionBottomToTop: { float fHalfHeight = m_tProgressSize.height / 2; if( tPoint.y < m_tCenterPoint.y - fHalfHeight ) { nRet = m_nMinValue; break; } if( tPoint.y > m_tCenterPoint.y + fHalfHeight ) { nRet = m_nMaxValue; break; } float fStartPoint = tPoint.y - (m_tCenterPoint.y - fHalfHeight); float fPercentage = fStartPoint / m_tProgressSize.height; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionTopToBottom: { float fHalfHeight = m_tProgressSize.height / 2; if( tPoint.y < m_tCenterPoint.y - fHalfHeight ) { nRet = m_nMaxValue; break; } if( tPoint.y > m_tCenterPoint.y + fHalfHeight ) { nRet = m_nMinValue; break; } float fStartPoint = tPoint.y - (m_tCenterPoint.y - fHalfHeight); float fPercentage = (m_tProgressSize.height - fStartPoint) / m_tProgressSize.height; nRet = valueFromPercent(fPercentage); } break; default: break; } return nRet; } CWidgetTouchModel CSlider::onTouchBegan(Touch *pTouch) { m_bDrag = m_pSlider->getBoundingBox().containsPoint( convertToNodeSpace(pTouch->getLocation()) ); if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); return eWidgetTouchSustained; } return eWidgetTouchNone; } void CSlider::onTouchMoved(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::onTouchEnded(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::onTouchCancelled(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::pointFromValue(int nValue, Vec2& tOutPoint) { float fPercentage = getPercentage(); switch( m_eDirection ) { case eProgressBarDirectionLeftToRight: { tOutPoint.x = m_tProgressSize.width * fPercentage + (m_tCenterPoint.x - m_tProgressSize.width / 2); tOutPoint.y = m_tCenterPoint.y; } break; case eProgressBarDirectionRightToLeft: { tOutPoint.x = m_tProgressSize.width - (m_tProgressSize.width * fPercentage) + (m_tCenterPoint.x - m_tProgressSize.width / 2); tOutPoint.y = m_tCenterPoint.y; } break; case eProgressBarDirectionBottomToTop: { tOutPoint.x = m_tCenterPoint.x; tOutPoint.y = m_tProgressSize.height * fPercentage + (m_tCenterPoint.y - m_tProgressSize.height / 2); } break; case eProgressBarDirectionTopToBottom: { tOutPoint.x = m_tCenterPoint.x; tOutPoint.y = m_tProgressSize.height - (m_tProgressSize.height * fPercentage) + (m_tCenterPoint.y - m_tProgressSize.height / 2); } break; default: break; } } void CSlider::changeValueAndExecuteEvent(int nValue, bool bExeEvent) { CProgressBar::changeValueAndExecuteEvent(nValue, bExeEvent); if( m_pSlider ) { Vec2 tOutPoint; pointFromValue(m_nValue, tOutPoint); m_pSlider->setPosition(tOutPoint); } } void CSlider::setSliderImage(const char* pFile) { if( pFile && strlen(pFile) ) { Texture2D* pTexture = Director::getInstance()->getTextureCache()->addImage(pFile); setSliderTexture(pTexture); } } void CSlider::setSliderTexture(Texture2D* pTexture) { if( m_pSlider ) { m_pSlider->setTexture(pTexture); Rect tRect = Rect::ZERO; tRect.size = pTexture->getContentSize(); m_pSlider->setTextureRect(tRect); } else { m_pSlider = Sprite::createWithTexture(pTexture); addChild(m_pSlider, 2); } setContentSize(_contentSize); } void CSlider::setSliderSpriteFrame(SpriteFrame* pFrame) { if( pFrame ) { if( m_pSlider ) { m_pSlider->setSpriteFrame(pFrame); } else { m_pSlider = Sprite::createWithSpriteFrame(pFrame); addChild(m_pSlider,2); } } setContentSize(_contentSize); } void CSlider::setValue( int nValue ) { changeValueAndExecuteEvent(nValue, true); } void CSlider::setSliderSpriteFrameName(const char* pSpriteName) { SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pSpriteName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; sprintf(msg, "Invalid spriteFrameName: %s", pSpriteName); CCAssert(pFrame != NULL, msg); #endif return setSliderSpriteFrame(pFrame); } NS_CC_WIDGET_END
23.372928
131
0.714336
LingJiJian
2cbcbf06bc2d170744d660890740960491444f2d
871
c++
C++
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r",stdin); freopen("output.txt","w", stdout); #endif int n,m; cin>>n>>m; int arr[n][m]; for( int i=0; i<n;i++){ for(int j=0;j<m;j++){ cin>>arr[i][j]; } } cout<<"Matrix is:\n"; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<arr[i][j]<<" "; } cout<<"\n"; } int x; cin>>x; bool flag=false; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(arr[i][j]==x){ cout<<i<<" "<<j<<"\n"; flag=true; } } } if(flag){ cout<<"Element is found\n"; }else{ cout<<"Element is not found\n"; } return 0; }
15.836364
38
0.375431
Sambitcr-7
2cbcc094d6d3489ff9636dc69edb9fcf8f692dd4
9,380
cpp
C++
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
1
2020-02-19T13:13:10.000Z
2020-02-19T13:13:10.000Z
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
//======================================================================= // Copyright (c) 2014-2018 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" /// sequence_generator TEMPLATE_TEST_CASE_2("sequence/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_2", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(99); REQUIRE_EQUALS(b[0], 99.0); REQUIRE_EQUALS(b[1], 100.0); REQUIRE_EQUALS(b[2], 101.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_3", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(99); REQUIRE_EQUALS(b[0], 99.0); REQUIRE_EQUALS(b[1], 100.0); REQUIRE_EQUALS(b[2], 101.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_4", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = 0.5 * etl::sequence_generator<Z>(99.0); REQUIRE_EQUALS(b[0], 49.5); REQUIRE_EQUALS(b[1], 50.0); REQUIRE_EQUALS(b[2], 50.5); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b(0, 0), 0.0); REQUIRE_EQUALS(b(0, 1), 1.0); REQUIRE_EQUALS(b(1, 0), 2.0); REQUIRE_EQUALS(b(1, 1), 3.0); REQUIRE_EQUALS(b(2, 0), 4.0); REQUIRE_EQUALS(b(2, 1), 5.0); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_2", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = 0.1 * etl::sequence_generator<Z>(); REQUIRE_DIRECT(etl::decay_traits<decltype(0.1 * etl::sequence_generator())>::is_generator); REQUIRE_EQUALS_APPROX(b(0, 0), 0.0); REQUIRE_EQUALS_APPROX(b(0, 1), 0.1); REQUIRE_EQUALS_APPROX(b(1, 0), 0.2); REQUIRE_EQUALS_APPROX(b(1, 1), 0.3); REQUIRE_EQUALS_APPROX(b(2, 0), 0.4); REQUIRE_EQUALS_APPROX(b(2, 1), 0.5); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_3", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b(1.0); b = 0.1 * etl::sequence_generator<Z>() + b; REQUIRE_EQUALS_APPROX(b(0, 0), 1.0); REQUIRE_EQUALS_APPROX(b(0, 1), 1.1); REQUIRE_EQUALS_APPROX(b(1, 0), 1.2); REQUIRE_EQUALS_APPROX(b(1, 1), 1.3); REQUIRE_EQUALS_APPROX(b(2, 0), 1.4); REQUIRE_EQUALS_APPROX(b(2, 1), 1.5); } TEMPLATE_TEST_CASE_2("sequence/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/dyn_vector_2", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::sequence_generator<Z>() >> 2.0; REQUIRE_EQUALS(b(0, 0), 0.0); REQUIRE_EQUALS(b(0, 1), 2.0); REQUIRE_EQUALS(b(1, 0), 4.0); REQUIRE_EQUALS(b(1, 1), 6.0); REQUIRE_EQUALS(b(2, 0), 8.0); REQUIRE_EQUALS(b(2, 1), 10.0); } /// normal_generator //Simply ensures that it compiles TEMPLATE_TEST_CASE_2("normal/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::normal_generator<Z>() >> etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 5); b = etl::normal_generator<Z>(); } /// truncated_normal_generator //Simply ensures that it compiles TEMPLATE_TEST_CASE_2("truncated_normal/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::truncated_normal_generator<Z>(); } /// uniform_generator TEMPLATE_TEST_CASE_2("generators/uniform/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(-2.0, +2.0); for (auto value : b) { REQUIRE_DIRECT(value >= -2.0); REQUIRE_DIRECT(value <= +2.0); } } TEMPLATE_TEST_CASE_2("generators/uniform/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(5.5, 8.0); for (auto value : b) { REQUIRE_DIRECT(value >= 5.5); REQUIRE_DIRECT(value <= 8.0); } } TEMPLATE_TEST_CASE_2("generators/uniform/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(1.0, 2.0) >> 4.0; for (auto value : b) { REQUIRE_DIRECT(value >= 4.0); REQUIRE_DIRECT(value <= 8.0); } } /// dropout_mask TEMPLATE_TEST_CASE_2("generators/dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } /// state_dropout_mask TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_dropout_mask<Z>(0.5); b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/4", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_dropout_mask<Z>(0.5); b = (dropout * 0.5f) + 1.0f; for (auto value : b) { REQUIRE_DIRECT(value == Z(1.0) || value == Z(1.5)); } } /// inverted_dropout_mask TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0 / 0.8)); } } TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0 / 0.5)); } } TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.5) >> 2.0; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0 / 0.5)); } } /// state_inverted_dropout_mask TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_inverted_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.25)); } } TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_inverted_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } } TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_inverted_dropout_mask<Z>(0.5); b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } }
25.911602
95
0.6129
BeatWolf
2cc029785f36a64242e7cb5f91e128444d80da67
1,469
cpp
C++
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
36
2021-07-13T19:28:50.000Z
2022-01-09T14:52:15.000Z
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
null
null
null
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
6
2021-07-15T02:06:29.000Z
2021-11-23T03:06:14.000Z
#include "Actuator/ActuatorMotor.h" #include "Joint/Joint.h" namespace redmax { ActuatorMotor::ActuatorMotor(Joint* joint, VectorX ctrl_min, VectorX ctrl_max, std::string name) : Actuator(joint->_ndof, ctrl_min, ctrl_max, name) { _joint = joint; } ActuatorMotor::ActuatorMotor(Joint* joint, dtype ctrl_min, dtype ctrl_max, std::string name) : Actuator(joint->_ndof, ctrl_min, ctrl_max, name) { _joint = joint; } void ActuatorMotor::computeForce(VectorX& fm, VectorX& fr) { VectorX u = _u.cwiseMin(VectorX::Ones(_joint->_ndof)).cwiseMax(VectorX::Ones(_joint->_ndof) * -1.); fr.segment(_joint->_index[0], _joint->_ndof) += ((u + VectorX::Ones(_joint->_ndof)) / 2.).cwiseProduct(_ctrl_max - _ctrl_min) + _ctrl_min; } void ActuatorMotor::computeForceWithDerivative(VectorX& fm, VectorX& fr, MatrixX& Km, MatrixX& Dm, MatrixX& Kr, MatrixX& Dr) { VectorX u = _u.cwiseMin(VectorX::Ones(_joint->_ndof)).cwiseMax(VectorX::Ones(_joint->_ndof) * -1.); fr.segment(_joint->_index[0], _joint->_ndof) += ((u + VectorX::Ones(_joint->_ndof)) / 2.).cwiseProduct(_ctrl_max - _ctrl_min) + _ctrl_min; } void ActuatorMotor::compute_dfdu(MatrixX& dfm_du, MatrixX& dfr_du) { for (int i = 0;i < _joint->_ndof;i++) if (_u[i] < -1. || _u[i] > 1.) { dfr_du(_joint->_index[i], _index[i]) += 0.; } else { dfr_du(_joint->_index[i], _index[i]) += (_ctrl_max[i] - _ctrl_min[i]) / 2.; } } }
38.657895
142
0.650783
eanswer
2cc1a61317e22d15fc9f4f103cf81cd7de2522bf
1,063
cpp
C++
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
4
2015-08-13T08:25:36.000Z
2017-04-07T21:33:10.000Z
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
// // CIndexBufferOGL2_0.h // OpenJam // // Created by Yevgeniy Logachev // Copyright (c) 2014 yev. All rights reserved. // #if defined(RENDER_OGL2_0) #include "CIndexBufferOGL2_0.h" using namespace jam; // ***************************************************************************** // Constants // ***************************************************************************** // ***************************************************************************** // Public Methods // ***************************************************************************** CIndexBufferOGL2_0::CIndexBufferOGL2_0() { } CIndexBufferOGL2_0::~CIndexBufferOGL2_0() { } // ***************************************************************************** // Protected Methods // ***************************************************************************** // ***************************************************************************** // Private Methods // ***************************************************************************** #endif /* defined(RENDER_OGL2_0) */
27.25641
80
0.281279
opengamejam
2cc2880daa8fb8d10a2c84b8b5d42d91dba386af
9,740
cpp
C++
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
8
2018-06-27T13:10:45.000Z
2022-01-25T02:57:54.000Z
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
null
null
null
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
3
2020-08-20T03:00:13.000Z
2022-01-04T10:11:16.000Z
/* * test_unscented_transform.cpp * * Created on: 12 Jun 2018 * Author: Fabian Meyer */ #include "bayes_filter/unscented_transform.h" #include "eigen_assert.h" #include <catch.hpp> using namespace bf; using namespace std::placeholders; static Eigen::VectorXd linearTransform( const Eigen::VectorXd &state, const Eigen::VectorXd &facs) { assert(state.rows() == facs.rows()); Eigen::VectorXd result(state.size()); for(unsigned int i = 0; i < state.rows(); ++i) result(i) = state(i) * facs(i); return result; } static Eigen::MatrixXd linearTransformCov( const Eigen::MatrixXd &cov, const Eigen::VectorXd &facs) { assert(cov.rows() == facs.rows()); Eigen::MatrixXd result; result.setZero(cov.rows(), cov.cols()); for(unsigned int i = 0; i < cov.rows(); ++i) result(i, i) = cov(i, i) * facs(i) * facs(i); return result; } static SigmaPoints linearTransformSig( SigmaPoints &sigma, const Eigen::VectorXd &facs) { assert(facs.rows() == sigma.points.rows()); SigmaPoints result; result = sigma; for(unsigned int i = 0; i < sigma.points.cols(); ++i) { result.points.col(i) = linearTransform(result.points.col(i), facs); } return result; } TEST_CASE("Unscented Transform") { /* ===================================================================== * Sigma Points * ===================================================================== */ SECTION("calculate sigma points") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with simple params") { trans.setAlpha(1.0); trans.setBeta(1.0); trans.setKappa(1.0); Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::MatrixXd wexp(2, 7); wexp << 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 1.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(3, 7); sexp << 1, 3, 1, 1, -1, 1, 1, 1, 1, 3, 1, 1, -1, 1, 1, 1, 1, 3, 1, 1, -1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(1.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } SECTION("with different params") { trans.setAlpha(1.0); trans.setBeta(2.0); trans.setKappa(2.0); Eigen::VectorXd state(2); state << 1, 1; Eigen::MatrixXd cov(2, 2); cov << 1, 0, 0, 1; Eigen::MatrixXd wexp(2, 5); wexp << 0.5, 0.125, 0.125, 0.125, 0.125, 2.5, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(2, 5); sexp << 1, 3, 1, -1, 1, 1, 1, 3, 1, -1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(2.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } SECTION("with zero uncertainty") { trans.setAlpha(1.0); trans.setBeta(1.0); trans.setKappa(1.0); Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 0, 0, 0, 0, 0; Eigen::MatrixXd wexp(2, 7); wexp << 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 1.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(3, 7); sexp << 1, 3, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(1.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } } /* ===================================================================== * Recover Distribution * ===================================================================== */ SECTION("recover distribution") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with identity transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with identity transform and near zero uncertainty") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with linear transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::VectorXd facs(3); facs << 1, 2, 3; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); sigma = linearTransformSig(sigma, facs); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); state = linearTransform(state, facs); cov = linearTransformCov(cov, facs); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with linear transform and near zero uncertainty") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; Eigen::VectorXd facs(3); facs << 1, 2, 3; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); sigma = linearTransformSig(sigma, facs); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); state = linearTransform(state, facs); cov = linearTransformCov(cov, facs); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } } /* ===================================================================== * Cross Covariance * ===================================================================== */ SECTION("caclulate cross covariance") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with identity transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; SigmaPoints sigma; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverCrossCorrelation(sigma, state, sigma, state, actCrossCov); REQUIRE_MAT(cov, actCrossCov, eps); } SECTION("with linear transform") { Eigen::VectorXd state1(3); state1 << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::VectorXd facs(3); facs << 1, 2, 3; Eigen::VectorXd state2 = linearTransform(state1, facs); Eigen::MatrixXd crossCov(3, 3); crossCov << 1, 0, 0, 0, 2, 0, 0, 0, 3; SigmaPoints sigma1; SigmaPoints sigma2; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state1, cov, sigma1); sigma2 = linearTransformSig(sigma1, facs); trans.recoverCrossCorrelation(sigma1, state1, sigma2, state2, actCrossCov); REQUIRE_MAT(crossCov, actCrossCov, eps); } SECTION("with linear transform and near zero uncertainty") { Eigen::VectorXd state1(3); state1 << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; Eigen::VectorXd facs(3); facs << 1, 2, 3; Eigen::VectorXd state2 = linearTransform(state1, facs); Eigen::MatrixXd crossCov(3, 3); crossCov << 0, 0, 0, 0, 2, 0, 0, 0, 0; SigmaPoints sigma1; SigmaPoints sigma2; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state1, cov, sigma1); sigma2 = linearTransformSig(sigma1, facs); trans.recoverCrossCorrelation(sigma1, state1, sigma2, state2, actCrossCov); REQUIRE_MAT(crossCov, actCrossCov, eps); } } }
30.342679
80
0.489322
MartinEekGerhardsen