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
109
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
48.5k
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
27965ac4051d43b2d857b12477817ab90f28b336
3,459
cc
C++
programs/playlist.cc
paulfd/fmidi
f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20
[ "BSL-1.0" ]
17
2018-04-18T08:57:12.000Z
2022-01-25T08:24:14.000Z
programs/playlist.cc
paulfd/fmidi
f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20
[ "BSL-1.0" ]
3
2018-11-02T13:20:51.000Z
2021-08-03T13:42:06.000Z
programs/playlist.cc
paulfd/fmidi
f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20
[ "BSL-1.0" ]
3
2020-04-22T17:55:31.000Z
2021-08-02T21:10:01.000Z
// Copyright Jean Pierre Cimalando 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "playlist.h" #if defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM) #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace sys = boost::system; #else #include <fts.h> #endif #include <memory> #include <ctime> #if !defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM) struct FTS_Deleter { void operator()(FTS *x) const { fts_close(x); } }; typedef std::unique_ptr<FTS, FTS_Deleter> FTS_u; #endif // void Linear_Play_List::add_file(const std::string &path) { files_.emplace_back(path); } void Linear_Play_List::start() { index_ = 0; } bool Linear_Play_List::at_end() const { return index_ == files_.size(); } const std::string &Linear_Play_List::current() const { return files_[index_]; } bool Linear_Play_List::go_next() { if (index_ == files_.size()) return false; ++index_; return true; } bool Linear_Play_List::go_previous() { if (index_ == 0) return false; --index_; return true; } // Random_Play_List::Random_Play_List() : prng_(std::time(nullptr)) { } void Random_Play_List::add_file(const std::string &path) { scan_files(path); } void Random_Play_List::start() { index_ = 0; history_.clear(); if (!files_.empty()) history_.push_back(&files_[random_file()]); } bool Random_Play_List::at_end() const { return history_.empty(); } const std::string &Random_Play_List::current() const { return *history_[index_]; } bool Random_Play_List::go_next() { if (index_ < history_.size() - 1) ++index_; else { if (history_.size() == history_max) history_.pop_front(); history_.push_back(&files_[random_file()]); index_ = history_.size() - 1; } return true; } bool Random_Play_List::go_previous() { if (index_ == 0) return false; --index_; return true; } size_t Random_Play_List::random_file() const { std::uniform_int_distribution<size_t> dist(0, files_.size() - 1); return dist(prng_); } #if !defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM) void Random_Play_List::scan_files(const std::string &path) { char *path_argv[] = { (char *)path.c_str(), nullptr }; FTS_u fts(fts_open(path_argv, FTS_NOCHDIR|FTS_LOGICAL, nullptr)); if (!fts) return; while (FTSENT *ent = fts_read(fts.get())) { if (ent->fts_info == FTS_F) files_.emplace_back(ent->fts_path); } } #else void Random_Play_List::scan_files(const std::string &path) { sys::error_code ec; ec.clear(); fs::file_status st = fs::status(path, ec); if (ec) return; switch (st.type()) { default: break; case fs::regular_file: files_.emplace_back(path); break; case fs::directory_file: ec.clear(); fs::recursive_directory_iterator it(path, ec); if (ec) return; while (it != fs::recursive_directory_iterator()) { ec.clear(); st = it->status(ec); if (ec || st.type() != fs::regular_file) continue; files_.emplace_back(it->path().string()); ec.clear(); it.increment(ec); if (ec) break; } break; } } #endif
20.589286
69
0.614629
paulfd
279d9d7f6e6fb3e43173bfb31229a534e324ab41
919
cpp
C++
imGUIWin.Demo/mainapp.cpp
Bit00009/imGUIWin
98c3f2d114a9ebd5351a6a863317a3a474e0c994
[ "MIT" ]
null
null
null
imGUIWin.Demo/mainapp.cpp
Bit00009/imGUIWin
98c3f2d114a9ebd5351a6a863317a3a474e0c994
[ "MIT" ]
null
null
null
imGUIWin.Demo/mainapp.cpp
Bit00009/imGUIWin
98c3f2d114a9ebd5351a6a863317a3a474e0c994
[ "MIT" ]
null
null
null
#include <Windows.h> #include <iostream> #include "imGUIWinLib.h" #pragma comment(lib, "..\\build\\imGUIWinLib.lib") using namespace std; int main() { cout << "imGUIWin.Demo" << endl; InitializeGUIEngine(); cout << "GUI Engine has been initialized." << endl; ViewHandle view01 = CreateNewViewWindow(L"imGUI View 01"); cout << "view01 has been created, Handle : " << hex << view01 << endl; ViewHandle view02 = CreateNewViewWindow(L"imGUI View 02"); cout << "view02 has been created, Handle : " << hex << view02 << endl; MSG msg; ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); continue; } RenderViewWindow(view01); RenderViewWindow(view02); } }
24.837838
75
0.581066
Bit00009
27a1666fb2f9df9fbeadd5efa5ddf5724aa308d4
5,673
cpp
C++
src/backend/dnnl/patterns/reorder_fusion.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/dnnl/patterns/reorder_fusion.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/dnnl/patterns/reorder_fusion.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2021-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "backend/dnnl/internal_ops.hpp" #include "backend/dnnl/patterns/fusions.hpp" namespace dnnl { namespace graph { namespace impl { namespace dnnl_impl { namespace pass { namespace pm = impl::utils::pm; using in_edges_t = pm::in_edges_t; using pb_graph = pm::pb_graph_t; using FCreateV2FusedOp = impl::pass::FCreateV2FusedOp; using FCreateV2Pattern = impl::pass::FCreateV2Pattern; /*! * \brief This provides reorder-related fusion * The process includes follow steps: * 1. look for fusion pattern on the graph * 2. If found, verify if this transformation is safe / correct * 3. replace the pattern with a fused op, update the graph */ DNNL_BACKEND_REGISTER_PASSES_DEF_BEGIN(reorder_fusion) DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, reorder_sum_fusion) .set_priority(10.1f) .set_attr<FCreateV2Pattern>("FCreateV2Pattern", [](const std::shared_ptr<pb_graph> &pgraph) -> void { pm::pb_op_t *reorder = pgraph->append_op( impl::op_kind::Reorder, "preorder"); pm::pb_op_t *add = pgraph->append_op(impl::op_kind::Add, {in_edge(0, reorder, 0)}, "padd"); add->append_decision_function([](op_t *graph_op) -> bool { return !graph_op->has_attr("auto_broadcast") || graph_op->get_attr<std::string>( "auto_broadcast") == "none"; }); }) .set_attr<FCreateV2FusedOp>( "FCreateV2FusedOp", []() -> std::shared_ptr<op_t> { std::shared_ptr<op_t> fused_op = std::make_shared<op_t>(op_kind::reorder_sum); fused_op->set_attr<std::string>("backend", "dnnl"); return fused_op; }); DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, int8_reorder_fusion) .set_priority(10.1f) .set_attr<FCreateV2Pattern>("FCreateV2Pattern", [](const std::shared_ptr<pb_graph> &pgraph) -> void { pm::pb_op_t *dequant = pgraph->append_op( impl::op_kind::Dequantize, "pdequant"); pm::pb_op_t *reorder = pgraph->append_op(impl::op_kind::Reorder, {in_edge(0, dequant, 0)}, "preorder"); pgraph->append_op(impl::op_kind::Quantize, {in_edge(0, reorder, 0)}, "pquant"); }) .set_attr<FCreateV2FusedOp>( "FCreateV2FusedOp", []() -> std::shared_ptr<op_t> { std::shared_ptr<op_t> fused_op = std::make_shared<op_t>(op_kind::int8_reorder); fused_op->set_attr<std::string>("backend", "dnnl"); return fused_op; }); DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, int8_reorder_sum_fusion) .set_priority(10.2f) .set_attr<FCreateV2Pattern>("FCreateV2Pattern", [](const std::shared_ptr<pb_graph> &pgraph) -> void { pm::pb_op_t *dequant = pgraph->append_op( impl::op_kind::Dequantize, "pdequant"); pm::pb_op_t *dequant_other = pgraph->append_op( impl::op_kind::Dequantize, "pdequant_other"); pm::pb_op_t *reorder = pgraph->append_op(impl::op_kind::Reorder, {in_edge(0, dequant, 0)}, "preorder"); pm::pb_op_t *add = pgraph->append_op(impl::op_kind::Add, {in_edge(0, reorder, 0), in_edge(1, dequant_other, 0)}, "padd"); add->append_decision_function([](op_t *graph_op) -> bool { return !graph_op->has_attr("auto_broadcast") || graph_op->get_attr<std::string>( "auto_broadcast") == "none"; }); pgraph->append_op(impl::op_kind::Quantize, {in_edge(0, add, 0)}, "pquant"); }) .set_attr<FCreateV2FusedOp>( "FCreateV2FusedOp", []() -> std::shared_ptr<op_t> { std::shared_ptr<op_t> fused_op = std::make_shared<op_t>(op_kind::int8_reorder); fused_op->set_attr<std::string>("backend", "dnnl"); return fused_op; }); DNNL_BACKEND_REGISTER_PASSES_DEF_END } // namespace pass } // namespace dnnl_impl } // namespace impl } // namespace graph } // namespace dnnl
45.75
80
0.52318
wuxun-zhang
27ab6eb974d421324d24ad2527fcb0c1b80f652c
1,711
cpp
C++
main.cpp
thirdkindgames/thread_context
715ba7a7a8be11f3806b85828096107cd9eb1619
[ "Unlicense" ]
null
null
null
main.cpp
thirdkindgames/thread_context
715ba7a7a8be11f3806b85828096107cd9eb1619
[ "Unlicense" ]
null
null
null
main.cpp
thirdkindgames/thread_context
715ba7a7a8be11f3806b85828096107cd9eb1619
[ "Unlicense" ]
null
null
null
#include <assert.h> #include <stack> #include <windows.h> #include "fiber_job_system.h" #include "memory_pool.h" #include "page_allocator.h" #include "system_memory_pool.h" #include "thread_context.h" // Program void main() { // Mem Test char* x = new char[ 512 ]; // Allocates using the default allocator (the system allocator) auto pageAllocator = new PageAllocator( 2048 ); // Allocator that doesn't free, just delete the whole allocator when done ThreadPushMemoryPool( pageAllocator ); char * y = new char[ 256 ]; // This is allocated from the pagePool as can be seen by identitying the allocated value int * z = new( &g_systemMemoryPool )int; // Ignores the 'current' pool and uses the supplied system allocator instead ThreadPopMemoryPool( pageAllocator ); delete x; // Deletes from the default allocator (the system allocator) // Thread Function Table - Uncommenting the next line will use the job thread function table instead so Sleep will call the fiberSleep function instead //g_threadContext.threadFunctions = g_fiberJobThreadFunctionTable; // This line should be called on the job thread immediately after creation ThreadSleep( 1000 ); // This call will end up in either StandardThread_Sleep or FiberJobThread_Sleep depending on which function table this thread is using delete pageAllocator; } // Externals and other CUs to make building simpler SystemMemoryPool g_systemMemoryPool; #include "fiber_job_system.cpp" #include "thread_context.cpp"
45.026316
191
0.670368
thirdkindgames
27aded1679161f1d0eefd20d95a03c012fb6fb36
1,013
cpp
C++
leetcode-solutions/medium/61 Rotate-List.cpp
jaikarans/coding-solutions
b3cb8251c902d6a8b626fff1a86500249ff7c9e4
[ "MIT" ]
null
null
null
leetcode-solutions/medium/61 Rotate-List.cpp
jaikarans/coding-solutions
b3cb8251c902d6a8b626fff1a86500249ff7c9e4
[ "MIT" ]
null
null
null
leetcode-solutions/medium/61 Rotate-List.cpp
jaikarans/coding-solutions
b3cb8251c902d6a8b626fff1a86500249ff7c9e4
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { vector <ListNode*> v; ListNode* tmp = head; ListNode* headNext; while (tmp) { v.push_back(tmp); tmp = tmp->next; } if (v.size() == 0 || k%v.size() == 0) return head; else { // making tmp as new head which is Kth node of linked list tmp = v[v.size()-k%v.size()]; // making left node's([K-1]th) next pointer NULL because it will be last node. v[v.size()-k%v.size()-1]->next = NULL; // pointing last Node to head; v[v.size()-1]->next = head; return tmp; } } };
28.942857
90
0.483712
jaikarans
27aef24a7ac056d1fd0950cd6b1e13db814f5b83
2,428
hh
C++
include/G4NRFNuclearLevelStore.hh
jvavrek/NIMB2018
0aaf4143db2194b9f95002c681e4f860c8c76f7a
[ "MIT" ]
4
2020-06-28T02:18:53.000Z
2022-01-17T07:54:31.000Z
include/G4NRFNuclearLevelStore.hh
jvavrek/NIMB2018
0aaf4143db2194b9f95002c681e4f860c8c76f7a
[ "MIT" ]
3
2018-08-16T18:49:53.000Z
2020-10-19T18:04:25.000Z
include/G4NRFNuclearLevelStore.hh
jvavrek/NIMB2018
0aaf4143db2194b9f95002c681e4f860c8c76f7a
[ "MIT" ]
null
null
null
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // #ifndef G4NRFNuclearLevelStore_hh #define G4NRFNuclearLevelStore_hh 1 #include <map> #include <vector> #include "G4NRFNuclearLevelManager.hh" class G4NRFNuclearLevel; class G4NRFNuclearLevelStore { private: G4NRFNuclearLevelStore(); public: static G4NRFNuclearLevelStore* GetInstance(); G4NRFNuclearLevelManager * GetManager(const G4int Z, const G4int A, G4bool standalone = false); ~G4NRFNuclearLevelStore(); private: G4String GenerateKey(const G4int Z, const G4int A); G4int GetKeyIndex(const G4int Z, const G4int A); static std::vector<G4String> theKeys_fast; static std::vector<G4NRFNuclearLevelManager*> theManagers_fast; static std::map<G4String, G4NRFNuclearLevelManager*> theManagers; static G4String dirName; }; #endif
39.803279
97
0.59514
jvavrek
27aefb76dc69488e0458ffb30b71fcdf94edd217
864
hpp
C++
src/metal-pipeline/include/metal-pipeline/operator_specification.hpp
metalfs/metal_fs
f244d4125622849f36bd7846881a5f3a7efca188
[ "MIT" ]
12
2020-04-21T05:21:32.000Z
2022-02-19T11:27:18.000Z
src/metal-pipeline/include/metal-pipeline/operator_specification.hpp
metalfs/metal_fs
f244d4125622849f36bd7846881a5f3a7efca188
[ "MIT" ]
10
2019-02-10T17:10:16.000Z
2020-02-01T20:05:42.000Z
src/metal-pipeline/include/metal-pipeline/operator_specification.hpp
metalfs/metal_fs
f244d4125622849f36bd7846881a5f3a7efca188
[ "MIT" ]
4
2020-07-15T04:42:20.000Z
2022-02-19T11:27:19.000Z
#pragma once #include <metal-pipeline/metal-pipeline_api.h> #include <string> #include <unordered_map> #include <metal-pipeline/operator_argument.hpp> namespace metal { class METAL_PIPELINE_API OperatorSpecification { public: explicit OperatorSpecification(std::string id, const std::string& manifest); std::string id() const { return _id; } std::string description() const { return _description; } uint8_t streamID() const { return _streamID; } bool prepareRequired() const { return _prepareRequired; } const std::unordered_map<std::string, OperatorOptionDefinition> optionDefinitions() const { return _optionDefinitions; } protected: std::string _id; std::string _description; uint8_t _streamID; bool _prepareRequired; std::unordered_map<std::string, OperatorOptionDefinition> _optionDefinitions; }; } // namespace metal
25.411765
79
0.758102
metalfs
27b0e47d6ba351a80f5da82c3c167c3f05893d6e
1,978
cpp
C++
Source/NightLight/Core/BaseImpactEffect.cpp
sena0711/NightLight
d7de62c0e731fa42973ac27ab20be7bc99e05688
[ "Apache-2.0" ]
null
null
null
Source/NightLight/Core/BaseImpactEffect.cpp
sena0711/NightLight
d7de62c0e731fa42973ac27ab20be7bc99e05688
[ "Apache-2.0" ]
null
null
null
Source/NightLight/Core/BaseImpactEffect.cpp
sena0711/NightLight
d7de62c0e731fa42973ac27ab20be7bc99e05688
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "BaseImpactEffect.h" #include "PhysicalMaterials/PhysicalMaterial.h" #include "Kismet/GameplayStatics.h" #include "Materials/Material.h" //#include "Components/SceneComponent.h" //#include "Sound/SoundBase.h" #include "Components/PrimitiveComponent.h" #include "Sound/SoundCue.h" // Sets default values ABaseImpactEffect::ABaseImpactEffect() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; bAutoDestroyWhenFinished = true; DecalLifeSpan = 10.0f; DecalSize = 16.0f; } void ABaseImpactEffect::PostInitializeComponents() { Super::PostInitializeComponents(); /* Figure out what we hit (SurfaceHit is setting during actor instantiation in weapon class) */ UPhysicalMaterial* HitPhysMat = SurfaceHit.PhysMaterial.Get(); EPhysicalSurface HitSurfaceType = UPhysicalMaterial::DetermineSurfaceType(HitPhysMat); UParticleSystem* ImpactFX = GetImpactFX(HitSurfaceType); if (ImpactFX) { UGameplayStatics::SpawnEmitterAtLocation(this, ImpactFX, GetActorLocation(), GetActorRotation()); } USoundCue* ImpactSound = GetImpactSound(HitSurfaceType); if (ImpactSound) { UGameplayStatics::PlaySoundAtLocation(this, ImpactSound, GetActorLocation()); } if (DecalMaterial) { FRotator RandomDecalRotation = SurfaceHit.ImpactNormal.Rotation(); RandomDecalRotation.Roll = FMath::FRandRange(-180.0f, 180.0f); UGameplayStatics::SpawnDecalAttached(DecalMaterial, FVector(DecalSize, DecalSize, 1.0f), SurfaceHit.Component.Get(), SurfaceHit.BoneName, SurfaceHit.ImpactPoint, RandomDecalRotation, EAttachLocation::KeepWorldPosition, DecalLifeSpan); } } UParticleSystem* ABaseImpactEffect::GetImpactFX(EPhysicalSurface SurfaceType) const { return DefaultFX; } USoundCue* ABaseImpactEffect::GetImpactSound(EPhysicalSurface SurfaceType) const { return nullptr; }
29.522388
115
0.787159
sena0711
27b2961fb467b28a14de8321f475dc26165779db
723
cpp
C++
swig/cpp/tests/transport/inproc.cpp
mwpowellhtx/cppnngswig
44e4c050b77b83608b440801dd253995c14bd1fc
[ "MIT" ]
null
null
null
swig/cpp/tests/transport/inproc.cpp
mwpowellhtx/cppnngswig
44e4c050b77b83608b440801dd253995c14bd1fc
[ "MIT" ]
null
null
null
swig/cpp/tests/transport/inproc.cpp
mwpowellhtx/cppnngswig
44e4c050b77b83608b440801dd253995c14bd1fc
[ "MIT" ]
null
null
null
// // Copyright (c) 2017 Michael W Powell <[email protected]> // Copyright 2017 Garrett D'Amore <[email protected]> // Copyright 2017 Capitar IT Group BV <[email protected]> // // This software is supplied under the terms of the MIT License, a // copy of which should be located in the distribution where this // file was obtained (LICENSE.txt). A copy of the license may also be // found online at https://opensource.org/licenses/MIT. // #include "transport.h" #include "../catch/catch_tags.h" namespace constants { const std::vector<std::string> prefix_tags = { "inproc" }; const std::string test_addr_base = "inproc://test_"; const char port_delim = '\0'; } void init(const std::string& addr) {}
27.807692
70
0.706777
mwpowellhtx
27b5a4972bbff713175558c3a0de9c12ee830474
1,487
cpp
C++
test/engine/world/scene.t.cpp
numinousgames/tron
86cd3e5a1f020f0b7f938e1abede8bb29a432dbb
[ "Apache-2.0" ]
null
null
null
test/engine/world/scene.t.cpp
numinousgames/tron
86cd3e5a1f020f0b7f938e1abede8bb29a432dbb
[ "Apache-2.0" ]
null
null
null
test/engine/world/scene.t.cpp
numinousgames/tron
86cd3e5a1f020f0b7f938e1abede8bb29a432dbb
[ "Apache-2.0" ]
null
null
null
// scene.t.cpp #include <engine/world/scene.h> #include <gtest/gtest.h> #include "engine/world/mock_tickable.h" TEST( Scene, Construction ) { using namespace nge::wrld; Scene scene; Scene copy( scene ); Scene moved( std::move( scene ) ); copy = moved; copy = std::move( moved ); } TEST( Scene, TickableManagementAndUpdate ) { using namespace nge::wrld; using namespace nge::test; Scene scene; MockTickable mock; scene.addTickable( &mock ); scene.update( 10.0f ); ASSERT_EQ( 1, mock.preticks() ); ASSERT_EQ( 1, mock.ticks() ); ASSERT_EQ( 1, mock.posticks() ); ASSERT_EQ( 10.0f, mock.elapsed() ); scene.update( 0.0f ); ASSERT_EQ( 2, mock.preticks() ); ASSERT_EQ( 2, mock.ticks() ); ASSERT_EQ( 2, mock.posticks() ); ASSERT_EQ( 10.0f, mock.elapsed() ); scene.removeTickable( &mock ); mock.reset(); scene.update( 10.0f ); ASSERT_EQ( 0, mock.preticks() ); ASSERT_EQ( 0, mock.ticks() ); ASSERT_EQ( 0, mock.posticks() ); ASSERT_EQ( 0.0f, mock.elapsed() ); scene.addTickable( &mock ); scene.update( 10.0f ); ASSERT_EQ( 1, mock.preticks() ); ASSERT_EQ( 1, mock.ticks() ); ASSERT_EQ( 1, mock.posticks() ); ASSERT_EQ( 10.0f, mock.elapsed() ); scene.removeAll(); scene.update( 10.0f ); ASSERT_EQ( 1, mock.preticks() ); ASSERT_EQ( 1, mock.ticks() ); ASSERT_EQ( 1, mock.posticks() ); ASSERT_EQ( 10.0f, mock.elapsed() ); }
20.943662
42
0.60121
numinousgames
27b990e961898e03202bbd0ecb432f3e2a2d7c73
59
cpp
C++
Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp
dymons/Sumo2Unreal
c0dc6a9552572035535c9081df0006889213179a
[ "MIT" ]
33
2018-10-03T17:05:14.000Z
2022-03-09T08:10:40.000Z
Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp
dymons/Sumo2Unreal
c0dc6a9552572035535c9081df0006889213179a
[ "MIT" ]
7
2018-12-06T15:49:18.000Z
2021-07-27T03:33:11.000Z
Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp
dymons/Sumo2Unreal
c0dc6a9552572035535c9081df0006889213179a
[ "MIT" ]
19
2019-04-17T05:22:27.000Z
2021-07-27T03:08:43.000Z
#include "SimpleSpline.h" SimpleSpline::SimpleSpline() {};
19.666667
32
0.745763
dymons
27b99f627bae9a54b10e0fa3479cbde992218694
664
hpp
C++
include/lol/def/LcdsPayloadDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LcdsPayloadDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LcdsPayloadDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LcdsPayloadDto { std::string method; std::map<std::string, std::string> headers; std::string path; std::string body; }; inline void to_json(json& j, const LcdsPayloadDto& v) { j["method"] = v.method; j["headers"] = v.headers; j["path"] = v.path; j["body"] = v.body; } inline void from_json(const json& j, LcdsPayloadDto& v) { v.method = j.at("method").get<std::string>(); v.headers = j.at("headers").get<std::map<std::string, std::string>>(); v.path = j.at("path").get<std::string>(); v.body = j.at("body").get<std::string>(); } }
30.181818
75
0.585843
Maufeat
27bd55db8a9046a9a14a30bbe9c7dd6b56b54d99
462
hpp
C++
source/mat2.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
source/mat2.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
source/mat2.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
#ifndef MAT2_HPP #define MAT2_HPP #include<array> #include <cmath> #include"vec2.hpp" struct Mat2 { float e_00 = 1.0f; float e_01 = 0.0f; float e_10 = 0.0f; float e_11 = 1.0f; Mat2& operator*=(Mat2 const& m); float deter() const; }; Mat2 operator*(Mat2 const& m1, Mat2 const& m2); Vec2 operator*(Mat2 const& m, Vec2 const& v); Mat2 inverses(Mat2 const& m); Mat2 transponierte(Mat2 const& m); Mat2 rotations_matrix(float phi); #endif
18.48
47
0.668831
Lucius-sama
27c0dac61f1aeb9f4c4cb987c46aa74053235b57
2,652
cpp
C++
day08/08_04_videoDrift/src/ofApp.cpp
ajbajb/ARTTECH3135-spring2019
ecce35823dbdb37ad6d1071a6e0c290d5d795b2e
[ "MIT" ]
1
2019-01-24T05:03:27.000Z
2019-01-24T05:03:27.000Z
day08/08_04_videoDrift/src/ofApp.cpp
ajbajb/ARTTECH3135-spring2019
ecce35823dbdb37ad6d1071a6e0c290d5d795b2e
[ "MIT" ]
null
null
null
day08/08_04_videoDrift/src/ofApp.cpp
ajbajb/ARTTECH3135-spring2019
ecce35823dbdb37ad6d1071a6e0c290d5d795b2e
[ "MIT" ]
1
2019-04-11T18:26:18.000Z
2019-04-11T18:26:18.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { grabber.setup(640, 480); gw = grabber.getWidth(); gh = grabber.getHeight(); bufferPix.allocate(gw, gh, OF_PIXELS_RGB); tex.allocate(gw, gh, GL_RGB); bufferPix.set(255); } //-------------------------------------------------------------- void ofApp::update() { grabber.update(); if (grabber.isFrameNew()) { grabberPix = grabber.getPixels(); for (int x = 0; x < gw; x++) { for (int y = 0; y < gh; y++) { if (x < gw-1) { // get the previous color to the RIGHT of the one you currently on ofColor prevLeft = bufferPix.getColor(x+1, y); ofColor current = grabberPix.getColor(x, y); ofColor lerpedColor = prevLeft.getLerped(current, 0.01); bufferPix.setColor(x, y, lerpedColor); } else { ofColor grabberColor = grabberPix.getColor(x,y); bufferPix.setColor(x, y, grabberColor); } } } } tex.loadData(bufferPix); } //-------------------------------------------------------------- void ofApp::draw() { tex.draw(0, 0); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
23.678571
86
0.343514
ajbajb
27c7e278a0ba05774413146ed4b9f8f68c15ebc3
1,761
cpp
C++
src/Sphere.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-03-29T09:39:33.000Z
2021-03-29T09:39:33.000Z
src/Sphere.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-05-19T05:55:23.000Z
2021-09-07T14:00:01.000Z
src/Sphere.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include "Sphere.hpp" #include "Vector3D.hpp" #include "Ray3D.hpp" #include "IntersectionRecord.hpp" Sphere::Sphere() { } Sphere::Sphere(Vector3D position, float radius) { this->setPosition(position); this->setRadius(radius); } Vector3D Sphere::getPosition() const { return this->position; } float Sphere::getRadius() const { return this->radius; } void Sphere::setPosition(Vector3D position) { this->position = position; } void Sphere::setRadius(float radius) { this->radius = radius; } bool Sphere::intersect(IntersectionRecord& result, Ray3D ray) { // a, b, c are the A, B, C in the quadtratic equation // a = (d . d) float a = ray.getDirection().dot(ray.getDirection()); // b = (d . (e - c)) float b = (ray.getDirection() * 2).dot( ray.getOrigin() - this->getPosition()); // c = (rayPos - center) . (rayPos - center) - R^2 float c = ((ray.getOrigin() - this->getPosition()).dot( (ray.getOrigin() - this->getPosition()))) - (this->getRadius() * this->getRadius()); // D = B^2-4AC float discriminant = (b * b) - (4 * a * c); if (discriminant < 0) { return false; } float tPlus = (-b + sqrt(discriminant)) / (2 * a); float tMinus = (-b - sqrt(discriminant)) / (2 * a); float t = fmin(tPlus, tMinus); // point on ray is P(t) = e + td result.pointOfIntersection = ray.getOrigin() + (ray.getDirection() * t); result.normalAtIntersection = (result.pointOfIntersection - this->getPosition()) * (1 / this->getRadius()); result.t = t; result.surfaceIntersected = this; return true; }
24.123288
112
0.578648
nsilvestri
27c8e7abdea4e48fff14c39789b4633ec14f7e0d
18,739
cpp
C++
TextFile/TextFile.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
null
null
null
TextFile/TextFile.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
33
2018-09-14T21:58:20.000Z
2022-01-12T21:39:22.000Z
TextFile/TextFile.cpp
pmachapman/Tulip
54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a
[ "Unlicense" ]
null
null
null
/* ========================================================================== Class : CTextFile Author : Johan Rosengren, Abstrakt Mekanik AB Date : 2004-03-22 Purpose : The class is a helper-package for text files and windows. It allows loading and saving text files in a single operation, as well as getting text to and from edit- and listboxes. If an empty filename is given as a parameter to a call, the standard file dialog will be displayed, to let the user select a file. Error handling is managed internally, and the different API-functions return a "BOOL" to signal success or failure. In case of failure, "FALSE" returned, the member function "GetErrorMessage" can be called to retrieve a "CString" with the error message. If this string is empty, the file selection was aborted in the case of an empty input name. ========================================================================*/ #include "stdafx.h" #include "TextFile.h" //////////////////////////////////////// // CTextFile construction/destruction CTextFile::CTextFile(const CString& ext, const CString& eol) /* ============================================================ Function : CTextFile::CTextFile Description : Constructor Access : Public Return : void Parameters : const CString& ext - Standard extension to use in case no file name is given. const CString& eol - The end-of-line to use. Defaults to '\n'. Usage : Should normally be created on the stack. ============================================================*/ { m_extension = ext; m_eol = eol; } CTextFile::~CTextFile() /* ============================================================ Function : CTextFile::~CTextFile Description : Destructor Access : Public Return : void Parameters : none Usage : Should normally be created on the stack. ============================================================*/ { } //////////////////////////////////////// // CTextFile operations // BOOL CTextFile::ReadTextFile(CString& filename, CStringArray& contents) /* ============================================================ Function : CTextFile::ReadTextFile Description : Will read the contents of the file "filename" into the "CStringArray" "contents", one line from the file at a time. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage" will contain errors. Parameters : CString& filename - file to read from CStringArray& contents - will be filled with the contents of the file Usage : Call to read the contents of a text file into a "CStringArray". ============================================================*/ { ClearError(); BOOL result = TRUE; if (filename.IsEmpty()) result = GetFilename(FALSE, filename); if (result) { CStdioFile file; CFileException feError; if (file.Open(filename, CFile::modeRead, &feError)) { contents.RemoveAll(); CString line; while (file.ReadString(line)) contents.Add(line); file.Close(); } else { TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } BOOL CTextFile::ReadTextFile(CString& filename, CString& contents) /* ============================================================ Function : CTextFile::ReadTextFile Description : Will read the contents of the file "filename" into "contents". If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage" will contain errors. Parameters : CString& filename - file to read from CString& contents - will be filled with the contents of the file Usage : Call to read the contents of a text file into a "CString". ============================================================*/ { contents = _T(""); // Error handling ClearError(); CStdioFile file; CFileException feError; BOOL result = TRUE; if (filename.IsEmpty()) { result = GetFilename(FALSE, filename); } if (result) { // Reading the file if (file.Open(filename, CFile::modeRead, &feError)) { CString line; while (file.ReadString(line)) { contents += line + m_eol; } file.Close(); } else { // Setting error message TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } BOOL CTextFile::WriteTextFile(CString& filename, const CStringArray& contents) /* ============================================================ Function : CTextFile::WriteTextFile Description : Writes "contents" to "filename". Will create the file if it doesn't already exist, overwrite it otherwise. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage" will return errors Parameters : CString& filename - file to write to conste CStringArray& contents - contents to write Usage : Call to write the contents of a "CStringArray" to a text file. ============================================================*/ { // Error handling ClearError(); CStdioFile file; CFileException feError; BOOL result = TRUE; if (filename.IsEmpty()) result = GetFilename(TRUE, filename); if (result) { // Write file if (file.Open(filename, CFile::modeWrite | CFile::modeCreate, &feError)) { INT_PTR max = contents.GetSize(); for (INT_PTR t = 0; t < max; t++) file.WriteString(contents[t] + m_eol); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } BOOL CTextFile::WriteTextFile(CString& filename, const CString& contents) /* ============================================================ Function : CTextFile::WriteTextFile Description : Writes "contents" to "filename". Will create the file if it doesn't already exist, overwrite it otherwise. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage" will return errors Parameters : CString& filename - file to write to const CString& contents - contents to write Usage : Call to write the contents of a string to a text file. ============================================================*/ { // Error checking ClearError(); CFile file; CFileException feError; BOOL result = TRUE; if (filename.IsEmpty()) result = GetFilename(TRUE, filename); if (result) { // Write the file if (file.Open(filename, CFile::modeWrite | CFile::modeCreate, &feError)) { file.Write(CStringA(contents), contents.GetLength()); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } BOOL CTextFile::AppendFile(CString& filename, const CString& contents) /* ============================================================ Function : CTextFile::AppendFile Description : Appends "contents" to "filename". Will create the file if it doesn't already exist. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. AppendFile will not add eols. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage" will return errors Parameters : CString& filename - file to write to const CString& contents - contents to write Usage : Call to append the contents of a string to a text file. ============================================================*/ { CFile file; CFileException feError; BOOL result = TRUE; if (filename.IsEmpty()) result = GetFilename(TRUE, filename); if (result) { // Write the file if (file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError)) { file.SeekToEnd(); file.Write(CStringA(contents), contents.GetLength()); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } BOOL CTextFile::AppendFile(CString& filename, const CStringArray& contents) /* ============================================================ Function : CTextFile::AppendFile Description : Appends "contents" to "filename". Will create the file if it doesn't already exist. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "TRUE" if OK. "GetErrorMessage " will return errors Parameters : CString& filename - file to write to CStringArray contents - contents to write Usage : Call to append the contents of a CStringArray to a textfile. ============================================================*/ { CStdioFile file; CFileException feError; BOOL result = TRUE; if (filename.IsEmpty()) result = GetFilename(TRUE, filename); if (result) { // Write the file if (file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError)) { file.SeekToEnd(); INT_PTR max = contents.GetSize(); for (INT_PTR t = 0; t < max; t++) file.WriteString(contents[t] + m_eol); file.Close(); } else { // Set error message TCHAR errBuff[256]; feError.GetErrorMessage(errBuff, 256); m_error = errBuff; result = FALSE; } } return result; } //////////////////////////////////////// // Window operations // BOOL CTextFile::Load(CString& filename, CEdit* edit) /* ============================================================ Function : CTextFile::Load Description : Loads a text file from "filename" to the "CEdit" "edit". If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. No translation of eols will be made. Access : Public Return : BOOL - "FALSE" if failure. "GetErrorMessage" will return the error. Parameters : CString& filename - name of file to load CEdit* edit - pointer to "CEdit" to set text to Usage : Call to load the contents of a text file to an editbox. ============================================================*/ { BOOL result = FALSE; // Error checking if (ValidParam(edit)) { CString contents; if (ReadTextFile(filename, contents)) { edit->SetWindowText(contents); result = TRUE; } } return result; } BOOL CTextFile::Load(CString& filename, CListBox* list) /* ============================================================ Function : CTextFile::Load Description : Loads a text file from "filename" to the "CListBox" "list". If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "FALSE" if failure. "GetErrorMessage" will return the error. Parameters : CString& filename - name of file to load CListBox* list - pointer to "CListBox" to set text to Usage : Call to load the contents of a texfile to a listbox. ============================================================*/ { BOOL result = FALSE; // Error checking if (ValidParam(list)) { // Read the file CStringArray contents; if (ReadTextFile(filename, contents)) { // Set to listbox INT_PTR max = contents.GetSize(); for (INT_PTR t = 0; t < max; t++) if (contents[t].GetLength()) list->AddString(contents[t]); result = TRUE; } } return result; } BOOL CTextFile::Save(CString& filename, CEdit* edit) /* ============================================================ Function : CTextFile::Save Description : Saves the contents of the "CEdit" "edit" to the file "filename". The file will be created or overwritten. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Note that the eol-markers from the editbox will be used. Access : Public Return : BOOL - "FALSE" if failure. "GetErrorMessage" will return the error. Parameters : CString& filename - name of file to save to. Will be overwritten CEdit* edit - pointer to "CEdit" to get text from Usage : Call to save the contents of an editbox to a text file. ============================================================*/ { BOOL result = FALSE; // Error checking if (ValidParam(edit)) { // Get text CString contents; edit->GetWindowText(contents); // Write file if (WriteTextFile(filename, contents)) result = TRUE; } return result; } BOOL CTextFile::Save(CString& filename, CListBox* list) /* ============================================================ Function : CTextFile::Save Description : Saves the contents of the "CListBox" "list" to the file "filename". The file will be created or overwritten. If "filename" is empty, the standard file dialog will be displayed, and - if OK is selected - "filename" will contain the selected filename on return. Access : Public Return : BOOL - "FALSE" if failure. "GetErrorMessage" will return the error. Parameters : CString& filename - name of file to save to. Will be overwritten CListBox* list - pointer to "CListBox" to get text from Usage : Call to save the contents of a listbox to a file. ============================================================*/ { BOOL result = FALSE; // Error checking if (ValidParam(list)) { // Get listbox contents CStringArray contents; int max = list->GetCount(); for (int t = 0; t < max; t++) { CString line; list->GetText(t, line); contents.Add(line); } // Write file if (WriteTextFile(filename, contents)) result = TRUE; } return result; } //////////////////////////////////////// // Error handling // CString CTextFile::GetErrorMessage() /* ============================================================ Function : CTextFile::GetErrorMessage Description : Gets the error message. Should be called if any of the file operations return "FALSE" and the file name is not empty. Access : Public Return : CString - The current error string Parameters : none Usage : Call to get the current error message. ============================================================*/ { return m_error; } //////////////////////////////////////// // Private functions // void CTextFile::ClearError() /* ============================================================ Function : CTextFile::ClearError Description : Clears the internal error string. Should be called first by all functions setting the error message string. Access : Private Return : void Parameters : none Usage : Call to clear the internal error string. ============================================================*/ { m_error = _T(""); } BOOL CTextFile::ValidParam(CWnd* wnd) /* ============================================================ Function : CTextFile::ValidParam Description : Used to check parameters of the Save/Load functions. The pointer to the window must be valid and the window itself must exist. Access : Private Return : BOOL - "FALSE" if any parameter was invalid Parameters : CWnd* wnd - a window pointer, that must be valid, to a window Usage : Call to check the validity of the feedback window. ============================================================*/ { ClearError(); BOOL result = TRUE; if (wnd == NULL) { ASSERT(FALSE); result = FALSE; } if (!IsWindow(wnd->m_hWnd)) { ASSERT(FALSE); result = FALSE; } if (!result) m_error = "Bad Window handle as parameter"; return result; } BOOL CTextFile::GetFilename(BOOL save, CString& filename) /* ============================================================ Function : CTextFile::GetFilename Description : The function will display a standard file dialog. If the instance is created with an extension, the extension will be used to filter files. Access : Protected Return : BOOL - "TRUE" if a file was selected Parameters : BOOL save - "TRUE" if the file should be saved. CString& filename - Placeholder for the selected filename Usage : Call to display the standard file dialog. ============================================================*/ { CString filter; CString extension = GetExtension(); if (extension.GetLength()) filter = extension + _T("-files (*." + extension + ")|*.") + extension + _T("|All Files (*.*)|*.*||"); BOOL result = FALSE; CFileDialog dlg(!save, extension, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter); if (dlg.DoModal() == IDOK) { filename = dlg.GetPathName(); result = TRUE; } return result; } CString CTextFile::GetExtension() /* ============================================================ Function : CTextFile::GetExtension Description : An accessor for the "m_extension" field. Access : Protected Return : CString - the extension. Parameters : none Usage : Call to get the default extension of the files. ============================================================*/ { return m_extension; }
23.780457
104
0.566946
pmachapman
27cac3ab4618836b2c4357611d31a49178579e95
1,376
cpp
C++
Week4/Ex_Curs/main.cpp
cristearadu02/CommandDefense
e8878359b18cedf4c2d3975198fcd661bdff1d8b
[ "MIT" ]
null
null
null
Week4/Ex_Curs/main.cpp
cristearadu02/CommandDefense
e8878359b18cedf4c2d3975198fcd661bdff1d8b
[ "MIT" ]
null
null
null
Week4/Ex_Curs/main.cpp
cristearadu02/CommandDefense
e8878359b18cedf4c2d3975198fcd661bdff1d8b
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string.h> #include "Sort.h" using namespace std; int main() { char c1[] = "209,73,900,85,6"; Sort a(c1); // din sir de caractere a.Print(); a.BubbleSort(); a.Print(); a.QuickSort(); a.Print(); a.InsertSort(); a.Print(); printf("\n%d\n%d", a.GetElementsCount(), a.GetElementFromIndex(2)); printf("\n"); int v[] = { 101, 202,76, 21,9001, 10,-2, 13 }; int nr = sizeof(v) / sizeof(v[1]); Sort b(v,nr); // din alt vector b.Print(); b.BubbleSort(); b.Print(); b.QuickSort(); b.Print(); b.InsertSort(); b.Print(); printf("\n%d\n%d", b.GetElementsCount(), b.GetElementFromIndex(2)); printf("\n"); Sort c(10, -200, 7000); // din interval random c.Print(); c.BubbleSort(); c.Print(); c.QuickSort(); c.Print(); c.InsertSort(); c.Print(); printf("\n%d\n%d", c.GetElementsCount(), c.GetElementFromIndex(2)); printf("\n"); Sort d(7, -23, 1, -45, 203, 67, 16); // din variadic parameters d.Print(); d.BubbleSort(); d.Print(); d.QuickSort(); d.Print(); d.InsertSort(); d.Print(); printf("\n%d\n%d", d.GetElementsCount(), d.GetElementFromIndex(2)); printf("\n"); Sort e; // din lista de initializare e.Print(); e.BubbleSort(); e.Print(); e.QuickSort(); e.Print(); e.InsertSort(); e.Print(); printf("\n%d\n%d", e.GetElementsCount(), e.GetElementFromIndex(2)); return 0; }
20.537313
68
0.617733
cristearadu02
27cc57bc206f0f416f6da50d0b0047a514f44313
3,331
cpp
C++
test/testGeneric.cpp
borisVanhoof/peafowl
56f7feb6480fc20052d3077a1b5032f48266dca9
[ "MIT" ]
null
null
null
test/testGeneric.cpp
borisVanhoof/peafowl
56f7feb6480fc20052d3077a1b5032f48266dca9
[ "MIT" ]
null
null
null
test/testGeneric.cpp
borisVanhoof/peafowl
56f7feb6480fc20052d3077a1b5032f48266dca9
[ "MIT" ]
null
null
null
/** * Generic tests. **/ #include "common.h" #include <time.h> TEST(GenericTest, MaxFlows) { pfwl_state_t* state = pfwl_init(); std::vector<uint> protocols; pfwl_set_expected_flows(state, 1, PFWL_FLOWS_STRATEGY_SKIP); uint errors = 0; getProtocols("./pcaps/whatsapp.pcap", protocols, state, [&](pfwl_status_t status, pfwl_dissection_info_t r){ if(status == PFWL_ERROR_MAX_FLOWS){ ++errors; } }); EXPECT_GT(errors, 0); pfwl_terminate(state); } TEST(GenericTest, MaxTrials) { pfwl_state_t* state = pfwl_init(); std::vector<uint> protocols; pfwl_set_max_trials(state, 1); getProtocols("./pcaps/imap.cap", protocols, state); EXPECT_EQ(protocols[PFWL_PROTO_L7_IMAP], 5); pfwl_terminate(state); } TEST(GenericTest, NullState) { EXPECT_EQ(pfwl_set_expected_flows(NULL, 0, PFWL_FLOWS_STRATEGY_NONE), 1); EXPECT_EQ(pfwl_set_max_trials(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_enable_ipv4(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_enable_ipv6(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_per_host_memory_limit_ipv4(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_per_host_memory_limit_ipv6(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_total_memory_limit_ipv4(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_total_memory_limit_ipv6(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_reassembly_timeout_ipv4(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_set_reassembly_timeout_ipv6(NULL, 0), 1); EXPECT_EQ(pfwl_defragmentation_disable_ipv4(NULL), 1); EXPECT_EQ(pfwl_defragmentation_disable_ipv6(NULL), 1); EXPECT_EQ(pfwl_tcp_reordering_enable(NULL), 1); EXPECT_EQ(pfwl_tcp_reordering_disable(NULL), 1); EXPECT_EQ(pfwl_protocol_l7_enable(NULL, PFWL_PROTO_L7_BGP), 1); EXPECT_EQ(pfwl_protocol_l7_disable(NULL, PFWL_PROTO_L7_BGP), 1); EXPECT_EQ(pfwl_protocol_l7_enable_all(NULL), 1); EXPECT_EQ(pfwl_protocol_l7_disable_all(NULL), 1); EXPECT_EQ(pfwl_set_flow_cleaner_callback(NULL, NULL), 1); EXPECT_EQ(pfwl_field_add_L7(NULL, PFWL_FIELDS_L7_DNS_AUTH_SRV), 1); EXPECT_EQ(pfwl_field_remove_L7(NULL, PFWL_FIELDS_L7_DNS_AUTH_SRV), 1); EXPECT_EQ(pfwl_set_protocol_accuracy_L7(NULL, PFWL_PROTO_L7_BGP, PFWL_DISSECTOR_ACCURACY_HIGH), 1); } TEST(GenericTest, FieldNamesConversion) { EXPECT_STREQ(pfwl_get_L7_field_name(PFWL_FIELDS_L7_NUM), "NUM"); EXPECT_STREQ(pfwl_get_L7_field_name(PFWL_FIELDS_L7_HTTP_BODY), "BODY"); EXPECT_EQ(pfwl_get_L7_field_id(PFWL_PROTO_L7_SSL, "CERTIFICATE"), PFWL_FIELDS_L7_SSL_CERTIFICATE); EXPECT_EQ(pfwl_get_L7_field_id(PFWL_PROTO_L7_HTTP, "URL"), PFWL_FIELDS_L7_HTTP_URL); } TEST(GenericTest, ProtoL2NamesConversion) { EXPECT_STREQ(pfwl_get_L2_protocol_name(PFWL_PROTO_L2_FDDI), "FDDI"); EXPECT_EQ(pfwl_get_L2_protocol_id("EN10MB"), PFWL_PROTO_L2_EN10MB); } TEST(GenericTest, ProtoL3NamesConversion) { EXPECT_STREQ(pfwl_get_L3_protocol_name(PFWL_PROTO_L3_IPV4), "IPv4"); EXPECT_EQ(pfwl_get_L3_protocol_id("IPv6"), PFWL_PROTO_L3_IPV6); } TEST(GenericTest, ProtoL4NamesConversion) { EXPECT_STREQ(pfwl_get_L4_protocol_name(IPPROTO_TCP), "TCP"); EXPECT_EQ(pfwl_get_L4_protocol_id("UDP"), IPPROTO_UDP); } TEST(GenericTest, ProtoL7NamesConversion) { EXPECT_STREQ(pfwl_get_L7_protocol_name(PFWL_PROTO_L7_JSON_RPC), "JSON-RPC"); EXPECT_EQ(pfwl_get_L7_protocol_id("QUIC"), PFWL_PROTO_L7_QUIC); }
40.621951
110
0.794056
borisVanhoof
27d04c21ae8ad74b0fd41881785163136d4bbf7e
3,535
hpp
C++
src/test/test_component_oom.hpp
jmbannon/KerasSynthesized
50e0275dadd45c5418384186e2541f4db7f5f9ed
[ "MIT" ]
3
2018-10-30T04:10:34.000Z
2021-09-07T15:19:55.000Z
src/test/test_component_oom.hpp
jmbannon/KerasSynthesized
50e0275dadd45c5418384186e2541f4db7f5f9ed
[ "MIT" ]
null
null
null
src/test/test_component_oom.hpp
jmbannon/KerasSynthesized
50e0275dadd45c5418384186e2541f4db7f5f9ed
[ "MIT" ]
null
null
null
#ifndef TEST_CONVOLUTION_OOM_HPP #define TEST_CONVOLUTION_OOM_HPP #include "HLS/hls.h" #include <stdio.h> #include <math.h> #include "../tensor3.hpp" #include "../tensor4.hpp" #include "../common.hpp" #include "../component_convolver.hpp" int test_component_oom_args(uint input_rows, uint input_cols, uint input_depth, uint input_tile_rows, uint input_tile_cols, uint input_tile_depth, uint input_padding_rows, uint input_padding_cols, uint output_padding_rows, uint output_padding_cols) { Numeric weights[3][3] = { { 0.0f, 1.0f, 2.0f }, { 0.0f, 1.0f, 2.0f }, { 0.0f, 1.0f, 2.0f } }; uint kernel_len = 3; uint input_rows_p = input_rows + (2 * input_padding_cols); uint input_cols_p = input_cols + (2 * input_padding_cols); uint output_rows = input_rows_p - kernel_len + 1; uint output_cols = input_cols_p - kernel_len + 1; tiled_tensor3 input; tiled_tensor3_init_padding(&input, input_rows, input_cols, input_depth, input_tile_rows, input_tile_cols, input_tile_depth, ROW_MAJ, ROW_MAJ, input_padding_rows, input_padding_cols); tiled_tensor3_set_data_sequential_row_padding(&input, input_padding_rows, input_padding_cols); tiled_tensor3 output; tiled_tensor3_init_padding(&output, output_rows, output_cols, 1, input_tile_rows, input_tile_cols, input_tile_depth, ROW_MAJ, ROW_MAJ, output_padding_rows, output_padding_cols); tiled_tensor3_fill_zero(&output); mm_src mm_src_weights(weights, POW2(kernel_len) * sizeof(Numeric)); mm_src mm_src_input(input.data, input.rows * input.cols * sizeof(Numeric)); mm_src mm_src_output(output.data, output.rows * output.cols * sizeof(Numeric)); return 0; } int test_component_oom_tiles_3_2__5_5() { int rows_t = 3; int cols_t = 2; int tile_rows = 5; int tile_cols = 5; int rows = tile_rows * rows_t; int cols = tile_cols * cols_t; int depth = 1; return test_component_oom_args(rows, cols, depth, tile_rows, tile_cols, depth, 0, 0, 0, 0); } int test_component_oom_5_5() { Numeric arr_weights[3][3] = { { 1.0f, 1.0f, 1.0f }, { 2.0f, 2.0f, 2.0f }, { 3.0f, 3.0f, 3.0f } }; Numeric arr_input[5][5] = { { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f } }; Numeric arr_output[3][3] = { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } }; Numeric exp_output[3][3] = { { 0.0f, 6.0f, 12.0f }, { 0.0f, 6.0f, 12.0f }, { 0.0f, 6.0f, 12.0f } }; mm_src mm_src_weights(arr_weights, 9 * sizeof(Numeric)); mm_src mm_src_input(arr_input, 25 * sizeof(Numeric)); mm_src mm_src_output(arr_output, 9 * sizeof(Numeric)); tiled_tensor3 in, out; tiled_tensor3_init_dims( &in, 5, 5, 1, 5, 5, 1, ROW_MAJ, ROW_MAJ); tiled_tensor3_init_dims( &out, 3, 3, 1, 3, 3, 1, ROW_MAJ, ROW_MAJ); convolution9(mm_src_input, mm_src_output, mm_src_weights, in, out, 0, 0, 0, 0, 0); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { // printf("%f %f\n", NUMERIC_VAL(exp_output[i][j]), NUMERIC_VAL(arr_output[i][j])); if (!fcompare(exp_output[i][j], arr_output[i][j])) { return 1; } } } return 0; } #endif
29.214876
184
0.610184
jmbannon
27d051e118c6aaca9f3210335c3162ce99c38c6b
46,532
cpp
C++
src/Parser.cpp
Ibarria/rapid
866e32bc9b902f5f5814063f1556cfc6b1c697bf
[ "MIT" ]
8
2019-10-25T19:49:27.000Z
2022-01-25T00:20:29.000Z
src/Parser.cpp
Ibarria/c2
866e32bc9b902f5f5814063f1556cfc6b1c697bf
[ "MIT" ]
null
null
null
src/Parser.cpp
Ibarria/c2
866e32bc9b902f5f5814063f1556cfc6b1c697bf
[ "MIT" ]
null
null
null
#include "Parser.h" #include "Lexer.h" #include "Interpreter.h" #include <assert.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef WIN32 # define sprintf_s sprintf # define vsprintf_s vsnprintf # define strncpy_s strncpy #endif extern bool option_printTokens; #define NEW_AST(ast_type) (ast_type *) setASTinfo(this, (BaseAST *) new(this->pool) ast_type ) u64 sequence_id = 100; void copyASTinfo(BaseAST *src, BaseAST *dst) { dst->filename = src->filename; dst->line_num = src->line_num; dst->char_num = src->char_num; dst->s = sequence_id++; dst->scope = src->scope; } static BaseAST * setASTloc(Parser *p, BaseAST *ast) { SrcLocation loc; p->lex->getLocation(loc); ast->line_num = loc.line; ast->char_num = loc.col; ast->filename = p->lex->getFilename(); // @TODO: make this an atomic operation ast->s = sequence_id++; return ast; } static BaseAST * setASTinfo(Parser *p, BaseAST *ast) { setASTloc(p, ast); ast->scope = p->current_scope; return ast; } void Parser::ErrorWithLoc(SrcLocation &loc, const char *msg, ...) { va_list args; s32 off = sprintf(errorString, "%s:%d:%d: error : ", lex->getFilename(), loc.line, loc.col); va_start(args, msg); off += vsprintf(errorString + off, msg, args); va_end(args); success = false; errorString += off; errorString = lex->getFileData()->printLocation(loc, errorString); } void Parser::Error(const char *msg, ...) { va_list args; SrcLocation loc; lex->getLocation(loc); s32 off = sprintf(errorString, "%s:%d:%d: error : ", lex->getFilename(), loc.line, loc.col); va_start(args, msg); off += vsprintf(errorString + off, msg, args); va_end(args); success = false; errorString += off; errorString = lex->getFileData()->printLocation(loc, errorString); } bool Parser::MustMatchToken(TOKEN_TYPE type, const char *msg) { if (!lex->checkToken(type)) { if (type == TK_SEMICOLON) { Token tok; lex->lookbehindToken(tok); ErrorWithLoc(tok.loc, "%s - Expected a semicolon after this token\n", msg); return false; } Error("%s - Token %s was expected, but we found: %s\n", msg, TokenTypeToStr(type), TokenTypeToStr(lex->getTokenType()) ); return false; } lex->consumeToken(); return true; } bool Parser::AddDeclarationToScope(VariableDeclarationAST * decl) { for (auto d : current_scope->decls) { if (d->varname == decl->varname) { Error("Variable [%s] is already defined in the scope", decl->varname); return false; } } current_scope->decls.push_back(decl); if (!(decl->flags & DECL_FLAG_IS_FUNCTION_ARGUMENT)) { // argument declarations have their flag set already if (current_scope->parent == nullptr) { decl->flags |= DECL_FLAG_IS_GLOBAL_VARIABLE; } else { decl->flags |= DECL_FLAG_IS_LOCAL_VARIABLE; } } return true; } bool Parser::AddDeclarationToStruct(StructDefinitionAST * struct_def, VariableDeclarationAST * decl) { for (auto d : struct_def->struct_type->struct_scope.decls) { if (d->varname == decl->varname) { Error("Variable %s is already defined within this struct", decl->varname); return false; } } struct_def->struct_type->struct_scope.decls.push_back(decl); decl->scope = &struct_def->struct_type->struct_scope; decl->flags |= DECL_FLAG_IS_STRUCT_MEMBER; return true; } static bool isIntegerType(BasicType t) { return (t == BASIC_TYPE_INTEGER); } static bool isFloatType(BasicType t) { return (t == BASIC_TYPE_FLOATING); } static bool isUnaryPrefixOperator(TOKEN_TYPE type) { return (type == TK_PLUS) || (type == TK_MINUS) || (type == TK_BANG) || (type == TK_STAR) || (type == TK_LSHIFT); } static bool isAssignmentOperator(TOKEN_TYPE type) { return (type == TK_ASSIGN) || (type == TK_MUL_ASSIGN) || (type == TK_DIV_ASSIGN) || (type == TK_MOD_ASSIGN) || (type == TK_ADD_ASSIGN) || (type == TK_SUB_ASSIGN) || (type == TK_AND_ASSIGN) || (type == TK_XOR_ASSIGN) || (type == TK_OR_ASSIGN); } static bool isBinOperator(TOKEN_TYPE type) { return (type == TK_EQ) || (type == TK_LEQ) || (type == TK_GEQ) || (type == TK_NEQ) || (type == TK_LT) || (type == TK_GT) || (type == TK_STAR) || (type == TK_DIV) || (type == TK_MOD) || (type == TK_PIPE) || (type == TK_DOUBLE_PIPE) || (type == TK_HAT) || (type == TK_AMP) || (type == TK_DOUBLE_AMP) || (type == TK_PLUS) || (type == TK_MINUS); } bool isBoolOperator(TOKEN_TYPE type) { return (type == TK_EQ) || (type == TK_LEQ) || (type == TK_GEQ) || (type == TK_NEQ) || (type == TK_LT) || (type == TK_GT); } static u32 getPrecedence(TOKEN_TYPE t) { switch (t) { case TK_STAR: case TK_DIV: case TK_MOD: return 1; case TK_MINUS: case TK_PLUS: return 2; case TK_LT: case TK_GT: case TK_LEQ: case TK_GEQ: return 4; case TK_EQ: case TK_NEQ: return 5; case TK_AMP: return 6; case TK_HAT: return 7; case TK_PIPE: return 8; case TK_DOUBLE_AMP: return 9; case TK_DOUBLE_PIPE: return 10; } return 0; } static bool isBuiltInType(TOKEN_TYPE t) { return (t == TK_BOOL) || (t == TK_INT) || (t == TK_U8) || (t == TK_U16) || (t == TK_U32) || (t == TK_U64) || (t == TK_S8) || (t == TK_S16) || (t == TK_S32) || (t == TK_S64) || (t == TK_FLOAT) || (t == TK_F32) || (t == TK_F64) || (t == TK_STRING_KEYWORD) || (t == TK_VOID); } static bool isHexNumber(Token &t) { if (t.type == TK_NUMBER) { return strcmp("0x", t.string) == 0; } return false; } static f64 computeDecimal(Token &t) { assert(t.type == TK_NUMBER); assert(!isHexNumber(t)); double total = 0; double divisor = 10; char *s = t.string; while (*s != 0) { float num = (float)(*s - '0'); total += num / divisor; divisor *= 10; s++; } return total; } static struct TypeHelperRec { TOKEN_TYPE tk; const char *name; u64 bytes; BasicType bt; bool sign; DirectTypeAST *ast; } TypeHelper[] = { { TK_VOID, "void", 0, BASIC_TYPE_VOID, false, nullptr }, { TK_BOOL, "bool", 1, BASIC_TYPE_BOOL, false, nullptr }, { TK_STRING_KEYWORD, "string", 16, BASIC_TYPE_STRING, false, nullptr }, { TK_U8, "u8", 1, BASIC_TYPE_INTEGER, false, nullptr }, { TK_U16, "u16", 2, BASIC_TYPE_INTEGER, false, nullptr }, { TK_U32, "u32", 4, BASIC_TYPE_INTEGER, false, nullptr }, { TK_U64, "u64", 8, BASIC_TYPE_INTEGER, false, nullptr }, { TK_S8, "s8", 1, BASIC_TYPE_INTEGER, true, nullptr }, { TK_S16, "s16", 2, BASIC_TYPE_INTEGER, true, nullptr }, { TK_S32, "s32", 4, BASIC_TYPE_INTEGER, true, nullptr }, { TK_S64, "s64", 8, BASIC_TYPE_INTEGER, true, nullptr }, { TK_INT, "int", 8, BASIC_TYPE_INTEGER, true, nullptr }, { TK_F32, "f32", 4, BASIC_TYPE_FLOATING, true, nullptr }, { TK_F64, "f64", 8, BASIC_TYPE_FLOATING, true, nullptr }, { TK_FLOAT, "float", 8, BASIC_TYPE_FLOATING, true, nullptr }, { TK_INVALID, nullptr, 0, BASIC_TYPE_VOID, false, nullptr } }; DirectTypeAST *getTypeEx(DirectTypeAST *oldtype, u32 newbytes) { TypeHelperRec *th; for (th = TypeHelper; th->name != nullptr; th++) { if ((th->bt == oldtype->basic_type) && (th->sign == oldtype->isSigned) && (th->bytes == newbytes)) { return th->ast; } } assert(false); return nullptr; } DirectTypeAST *getBuiltInType(TOKEN_TYPE tktype) { if ((tktype >= TK_VOID) && (tktype <= TK_FLOAT)) { return TypeHelper[tktype - TK_VOID].ast; } assert(false); return nullptr; } void Parser::defineBuiltInTypes() { if (TypeHelper[0].ast != nullptr) return; TypeHelperRec *th; for (th = TypeHelper; th->name != nullptr; th++) { DirectTypeAST *tp; tp = createType(th->tk, CreateTextType(pool, th->name)); th->ast = tp; } assert(TypeHelper[TK_FLOAT - TK_VOID].tk == TK_FLOAT); } DirectTypeAST *Parser::createType(TOKEN_TYPE tktype, TextType name) { DirectTypeAST *type = (DirectTypeAST *) new(this->pool) DirectTypeAST; type->s = sequence_id++; type->name = name; switch (tktype) { case TK_VOID: type->basic_type = BASIC_TYPE_VOID; type->size_in_bytes = 0; // Basically this can never be a direct type break; case TK_BOOL: type->basic_type = BASIC_TYPE_BOOL; type->size_in_bytes = 1; // This could change, but enough for now break; case TK_STRING_KEYWORD: type->basic_type = BASIC_TYPE_STRING; type->size_in_bytes = 8 + 8; // for the pointer to data and the size of the string break; case TK_U8: type->basic_type = BASIC_TYPE_INTEGER; type->size_in_bytes = 1; break; case TK_U16: type->basic_type = BASIC_TYPE_INTEGER; type->size_in_bytes = 2; break; case TK_U32: type->basic_type = BASIC_TYPE_INTEGER; type->size_in_bytes = 4; break; case TK_U64: type->basic_type = BASIC_TYPE_INTEGER; type->size_in_bytes = 8; break; case TK_S8: type->basic_type = BASIC_TYPE_INTEGER; type->isSigned = true; type->size_in_bytes = 1; break; case TK_S16: type->basic_type = BASIC_TYPE_INTEGER; type->isSigned = true; type->size_in_bytes = 2; break; case TK_S32: type->basic_type = BASIC_TYPE_INTEGER; type->isSigned = true; type->size_in_bytes = 4; break; case TK_INT: case TK_S64: type->basic_type = BASIC_TYPE_INTEGER; type->isSigned = true; type->size_in_bytes = 8; break; case TK_F32: type->basic_type = BASIC_TYPE_FLOATING; type->size_in_bytes = 4; type->isSigned = true; break; case TK_FLOAT: case TK_F64: type->basic_type = BASIC_TYPE_FLOATING; type->size_in_bytes = 8; type->isSigned = true; break; case TK_IDENTIFIER: type->basic_type = BASIC_TYPE_CUSTOM; break; default: assert(!"Identifier types, custom types are not implemented"); } return type; } DirectTypeAST *Parser::getType(TOKEN_TYPE tktype, TextType name) { if ((tktype >= TK_VOID) && (tktype <= TK_FLOAT)) { return TypeHelper[tktype - TK_VOID].ast; } DirectTypeAST *type = NEW_AST(DirectTypeAST); type->name = name; switch (tktype) { case TK_IDENTIFIER: type->basic_type = BASIC_TYPE_CUSTOM; break; default: assert(!"Identifier types, custom types are not implemented"); } return type; } TypeAST *Parser::parseDirectType() { // @TODO: support pointer, arrays, etc Token t; lex->getNextToken(t); if ((t.type == TK_IDENTIFIER) || isBuiltInType(t.type)) { return getType(t.type, t.string); } else if (t.type == TK_STAR) { // This is a pointer to something PointerTypeAST *pt = NEW_AST(PointerTypeAST); pt->points_to_type = parseDirectType(); pt->size_in_bytes = 8; return pt; } else if (t.type == TK_OPEN_SQBRACKET) { // this is an array declaration // The only supported options are: [] , [..] , [constant number expression] // option 3 is evaluated at Interpreter time ArrayTypeAST *at = NEW_AST(ArrayTypeAST); VariableDeclarationAST *data_decl = NEW_AST(VariableDeclarationAST); PointerTypeAST *pt = NEW_AST(PointerTypeAST); pt->points_to_type = nullptr; // will be filled later pt->size_in_bytes = 8; data_decl->specified_type = pt; data_decl->varname = CreateTextType(pool, "data"); at->decls.push_back(data_decl); VariableDeclarationAST *count_decl = NEW_AST(VariableDeclarationAST); count_decl->specified_type = getType(TK_U64, nullptr); count_decl->varname = CreateTextType(pool, "count"); at->decls.push_back(count_decl); if (lex->checkToken(TK_CLOSE_SQBRACKET)) { lex->consumeToken(); at->array_type = ArrayTypeAST::SIZED_ARRAY; } else if (lex->checkToken(TK_DOUBLE_PERIOD)) { lex->consumeToken(); MustMatchToken(TK_CLOSE_SQBRACKET, "Declaration of array type needs a closed square bracket"); if (!success) { return nullptr; } at->array_type = ArrayTypeAST::DYNAMIC_ARRAY; VariableDeclarationAST *rsize_decl = NEW_AST(VariableDeclarationAST); rsize_decl->specified_type = getType(TK_U64, nullptr); rsize_decl->varname = CreateTextType(pool, "reserved_size"); at->decls.push_back(rsize_decl); } else { at->num_expr = parseExpression(); if (!success) { return nullptr; } MustMatchToken(TK_CLOSE_SQBRACKET, "Declaration of array type needs a closed square bracket"); if (!success) { return nullptr; } at->array_type = ArrayTypeAST::STATIC_ARRAY; } at->array_of_type = parseType(); if (!success) { return nullptr; } pt->points_to_type = at->array_of_type; return at; } else { if (t.type == TK_STRUCT) { Error("To declare a struct you need to use the form of <var> := struct { ... }"); } else { Error("Variable type token could not be found, but we found: %s\n", TokenTypeToStr(t.type)); } return nullptr; } } TypeAST * Parser::parseType() { if (lex->checkToken(TK_OPEN_PAREN)) { return parseFunctionDeclaration(); } return parseDirectType(); } VariableDeclarationAST *Parser::parseArgumentDeclaration() { Token t; lex->lookaheadToken(t); VariableDeclarationAST *arg = NEW_AST(VariableDeclarationAST); MustMatchToken(TK_IDENTIFIER, "Argument declaration needs to start with an identifier"); if (!success) { return nullptr; } arg->varname = t.string; MustMatchToken(TK_COLON, "Argument declaration needs a colon between identifier and type"); if (!success) { return nullptr; } arg->specified_type = parseType(); if (!success) { return nullptr; } arg->flags |= DECL_FLAG_IS_FUNCTION_ARGUMENT; return arg; } FunctionTypeAST *Parser::parseFunctionDeclaration() { MustMatchToken(TK_OPEN_PAREN, "Function declarations need to start with an open parenthesis"); if (!success) { return nullptr; } FunctionTypeAST *fundec = NEW_AST(FunctionTypeAST); while (!lex->checkToken(TK_CLOSE_PAREN)) { if (lex->checkToken(TK_DOUBLE_PERIOD)) { // this is a special argument case, the variable lenght argument lex->consumeToken(); fundec->hasVariableArguments = true; if (!lex->checkToken(TK_CLOSE_PAREN)) { Error("Variable lenght arguments must be the last parameter in a function\n"); return nullptr; } continue; } VariableDeclarationAST *arg = Parser::parseArgumentDeclaration(); if (!success) { return nullptr; } fundec->arguments.push_back(arg); if (lex->checkToken(TK_COMMA)) { lex->consumeToken(); } else if (!lex->checkToken(TK_CLOSE_PAREN)) { Error("Comma must be used in between parameters in a function\n"); return nullptr; } } lex->consumeToken(); // Now do the return value, which can be empty if (lex->checkToken(TK_RETURN_ARROW)) { lex->consumeToken(); fundec->return_type = parseType(); } else { fundec->return_type = getType(TK_VOID, (char *)"void"); } if (!success) { return nullptr; } return fundec; } ReturnStatementAST *Parser::parseReturnStatement() { ReturnStatementAST *ret = NEW_AST(ReturnStatementAST); MustMatchToken(TK_RETURN); if (!success) { return nullptr; } ret->ret = parseExpression(); if (!success) { return nullptr; } MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon"); if (!success) { return nullptr; } return ret; } IfStatementAST * Parser::parseIfStatement() { IfStatementAST *ifst = NEW_AST(IfStatementAST); MustMatchToken(TK_IF); if (!success) { return nullptr; } ifst->condition = parseExpression(); if (!success) { return nullptr; } ifst->then_branch = parseStatement(); if (!success) { return nullptr; } TOKEN_TYPE cur_type; cur_type = lex->getTokenType(); if (cur_type == TK_ELSE) { lex->consumeToken(); ifst->else_branch = parseStatement(); if (!success) { return nullptr; } } return ifst; } static IdentifierAST *checkArrayIterator(ExpressionAST *expr, bool &isPtr) { isPtr = false; if (expr->ast_type == AST_IDENTIFIER) return (IdentifierAST *)expr; if (expr->ast_type == AST_UNARY_OPERATION) { auto unop = (UnaryOperationAST *)expr; if (unop->op != TK_STAR) return nullptr; if (unop->expr->ast_type == AST_IDENTIFIER) { isPtr = true; return (IdentifierAST *)unop->expr; } } return nullptr; } ForStatementAST * Parser::parseForStatement() { ForStatementAST *forst = NEW_AST(ForStatementAST); MustMatchToken(TK_FOR); if (!success) { return nullptr; } forst->is_array = true; ExpressionAST *expr = parseExpression(); if (!success) { return nullptr; } TOKEN_TYPE cur_type; cur_type = lex->getTokenType(); switch (cur_type) { case TK_DOUBLE_PERIOD: { lex->consumeToken(); // this is the case where we iterate in a range forst->is_array = false; forst->start = expr; forst->end = parseExpression(); if (!success) { return nullptr; } break; } case TK_COLON: case TK_COMMA: { lex->consumeToken(); // When we see a comma, means we are going to have named iterator and index forst->it = checkArrayIterator(expr, forst->is_it_ptr); if (forst->it == nullptr) { Error("Iterator on the for loop has to be an identifier"); return nullptr; } if (forst->it->next) { Error("Iterator on the for loop has to be a simple identifier"); return nullptr; } if (cur_type == TK_COMMA) { expr = parseExpression(); if (!success) { return nullptr; } if (expr->ast_type != AST_IDENTIFIER) { Error("Iterator index on the for loop has to be an identifier"); return nullptr; } forst->it_index = (IdentifierAST *)expr; if (forst->it_index->next) { Error("Iterator index on the for loop has to be a simple identifier"); return nullptr; } if (!lex->checkToken(TK_COLON)) { Error("For loop with iterator and index needs to be followed by \": <array> "); return nullptr; } lex->consumeToken(); } // Here we parse the range, which can be an array or start .. end expr = parseExpression(); if (!success) { return nullptr; } if (lex->checkToken(TK_DOUBLE_PERIOD)) { // we are in a range case forst->is_array = false; // first, store the previous expression in start forst->start = expr; lex->consumeToken(); forst->end = parseExpression(); if (!success) { return nullptr; } } else { // the current expression has to refer to an array if (expr->ast_type != AST_IDENTIFIER) { Error("For array variable has to be an identifier"); return nullptr; } forst->arr = (IdentifierAST *)expr; } break; } default: { // We must have seen something that is the for block, so assume expr is the array if (expr->ast_type != AST_IDENTIFIER) { Error("For array variable has to be an identifier"); return nullptr; } forst->arr = (IdentifierAST *)expr; if (!success) { return nullptr; } } } forst->for_scope.parent = current_scope; current_scope = &forst->for_scope; // Assume single array, time to parse a statement forst->loop_block = parseStatement(); current_scope = current_scope->parent; if (!success) { return nullptr; } return forst; } StatementAST *Parser::parseStatement() { TOKEN_TYPE cur_type; StatementAST *statement = nullptr; cur_type = lex->getTokenType(); if (cur_type == TK_IDENTIFIER) { // could be a variable definition or a statement if (lex->checkAheadToken(TK_COLON,1) || lex->checkAheadToken(TK_DOUBLE_COLON, 1) || lex->checkAheadToken(TK_IMPLICIT_ASSIGN, 1)) { statement = parseDeclaration(); } else if (lex->checkAheadToken(TK_OPEN_PAREN, 1)) { // this is a function call, parse it as such statement = parseFunctionCall(); if (!success) { return nullptr; } MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon"); if (!success) { return nullptr; } } else { statement = parseAssignmentOrExpression(); if (!success) { return nullptr; } MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon"); if (!success) { return nullptr; } } return statement; } else if (cur_type == TK_OPEN_BRACKET) { return parseStatementBlock(); } else if (cur_type == TK_RETURN) { return parseReturnStatement(); } else if (cur_type == TK_IF) { return parseIfStatement(); } else if (cur_type == TK_FOR) { return parseForStatement(); } else if (cur_type == TK_WHILE) { Error("The `while` statement is not yet supported.\n"); return nullptr; } else if (cur_type == TK_ELSE) { Error("Found a mismatched `else`.\n"); return nullptr; } else { statement = parseAssignmentOrExpression(); MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon"); if (!success) { return nullptr; } return statement; } } StatementBlockAST *Parser::parseStatementBlock(FunctionDefinitionAST *fundef) { if (!lex->checkToken(TK_OPEN_BRACKET)) { Error("We are trying to parse a statement block and it needs to start with an open bracket\n"); return nullptr; } lex->consumeToken(); // consume the { StatementBlockAST *block = NEW_AST(StatementBlockAST); // push scope block->block_scope.parent = current_scope; current_scope = &block->block_scope; if (fundef) { current_scope->current_function = fundef; // if this is the body of a function, register the arguments as variables for(auto arg:fundef->declaration->arguments) { AddDeclarationToScope(arg); arg->scope = current_scope; } } while (!lex->checkToken(TK_CLOSE_BRACKET)) { StatementAST *statement = nullptr; statement = parseStatement(); if (!success) { return nullptr; } block->statements.push_back(statement); if (lex->checkToken(TK_LAST_TOKEN)) { Error("Failed to find a matching close bracket, open bracket at line %d\n", block->line_num); if (!success) { return nullptr; } } } lex->consumeToken(); // match } // pop scope current_scope = current_scope->parent; return block; } FunctionDefinitionAST *Parser::parseFunctionDefinition() { FunctionDefinitionAST *fundef = NEW_AST(FunctionDefinitionAST); fundef->declaration = parseFunctionDeclaration(); if (!success) { return nullptr; } if (isImport && lex->checkToken(TK_FOREIGN)) { // foreign functions are special, there is no body for them fundef->declaration->isForeign = true; lex->consumeToken(); MustMatchToken(TK_SEMICOLON, "Function definitions need to end in semicolon\n"); return fundef; } if (!lex->checkToken(TK_OPEN_BRACKET)) { Error("Function declaration needs to be followed by an implementation {}, found token: %s \n", TokenTypeToStr(lex->getTokenType())); return nullptr; } // We need to add the declarated variables into the statementBlock // for the function fundef->function_body = parseStatementBlock(fundef); if (!success) { return nullptr; } return fundef; } // This is really the declaration... StructDefinitionAST * Parser::parseStructDefinition() { StructDefinitionAST *struct_def = NEW_AST(StructDefinitionAST); struct_def->struct_type = NEW_AST(StructTypeAST); Token t; lex->getNextToken(t); assert(t.type == TK_STRUCT); // Add here possible support for SOA or other qualifiers lex->getNextToken(t); if (t.type == TK_OPEN_BRACKET) { while (t.type != TK_CLOSE_BRACKET) { // now we process the different elements inside the struct, recursively VariableDeclarationAST *decl = parseDeclaration(true); if (!success) { return nullptr; } AddDeclarationToStruct(struct_def, decl); if (!success) { return nullptr; } lex->lookaheadToken(t); } // consume the close bracket lex->consumeToken(); } return struct_def; } FunctionCallAST * Parser::parseFunctionCall() { FunctionCallAST *funcall = NEW_AST(FunctionCallAST); Token t; lex->getNextToken(t); assert(t.type == TK_IDENTIFIER); funcall->function_name = t.string; MustMatchToken(TK_OPEN_PAREN); if (!success) { return nullptr; } while (!lex->checkToken(TK_CLOSE_PAREN)) { ExpressionAST * expr = parseExpression(); if (!success) { return nullptr; } funcall->args.push_back(expr); if (!lex->checkToken(TK_CLOSE_PAREN)) { if (lex->checkToken(TK_COMMA)) { lex->consumeToken(); } else { Error("Comma must be used to separate function arguments\n"); return nullptr; } } } MustMatchToken(TK_CLOSE_PAREN); if (!success) { return nullptr; } return funcall; } VarReferenceAST * Parser::parseVarReference() { Token t; lex->getCurrentToken(t); if (t.type == TK_OPEN_SQBRACKET) { lex->consumeToken(); // This is an array access ArrayAccessAST *acc = NEW_AST(ArrayAccessAST); acc->array_exp = parseExpression(); if (!success) { return nullptr; } MustMatchToken(TK_CLOSE_SQBRACKET, "Cound not find matching close square bracket"); if (!success) { return nullptr; } acc->next = parseVarReference(); if (acc->next) { acc->next->prev = acc; } return acc; } if (t.type == TK_PERIOD) { lex->consumeToken(); // compound statement StructAccessAST *sac = NEW_AST(StructAccessAST); lex->getNextToken(t); if (t.type != TK_IDENTIFIER) { Error("An identifier must follow after a period access expression"); return nullptr; } sac->name = t.string; sac->next = parseVarReference(); if (sac->next) { sac->next->prev = sac; // the scope for a variable reference is that of the enclosing struct // since we do not yet know it, just null it to be safe sac->next->scope = nullptr; } return sac; } // This is not an error, just that the VarReference has ended return nullptr; } ExpressionAST * Parser::parseLiteral() { Token t; lex->getNextToken(t); if (t.type == TK_IDENTIFIER) { IdentifierAST *ex = NEW_AST(IdentifierAST); ex->name = t.string; ex->next = parseVarReference(); if (ex->next) { ex->next->prev = ex; } return ex; } else if (t.type == TK_NULL) { auto nptr = NEW_AST(NullPtrAST); nptr->expr_type = NEW_AST(NullPtrTypeAST); nptr->expr_type->size_in_bytes = 8; return nptr; } else if ((t.type == TK_NUMBER) || (t.type == TK_TRUE) || (t.type == TK_FNUMBER) || (t.type == TK_STRING) || (t.type == TK_FALSE)) { auto ex = NEW_AST(LiteralAST); // setASTinfo(this, ex->typeAST); if (t.type == TK_NUMBER) { ex->typeAST = getType(TK_U64, nullptr); //ex->typeAST.basic_type = BASIC_TYPE_INTEGER; //ex->typeAST.size_in_bytes = 8; ex->_u64 = t._u64; } else if (t.type == TK_FNUMBER) { ex->typeAST = getType(TK_FLOAT, nullptr); //ex->typeAST.basic_type = BASIC_TYPE_FLOATING; //ex->typeAST.size_in_bytes = 8; ex->_f64 = t._f64; } else if (t.type == TK_STRING) { ex->typeAST = getType(TK_STRING_KEYWORD, nullptr); //ex->typeAST.basic_type = BASIC_TYPE_STRING; //ex->typeAST.size_in_bytes = 8+8; ex->str = t.string; } else if (t.type == TK_TRUE) { ex->typeAST = getType(TK_BOOL, nullptr); //ex->typeAST.basic_type = BASIC_TYPE_BOOL; //ex->typeAST.size_in_bytes = 1; ex->_bool = true; } else if (t.type == TK_FALSE) { ex->typeAST = getType(TK_BOOL, nullptr); //ex->typeAST.basic_type = BASIC_TYPE_BOOL; //ex->typeAST.size_in_bytes = 1; ex->_bool = false; } return ex; } else if (t.type == TK_OPEN_PAREN) { SrcLocation loc; loc = t.loc; ExpressionAST *expr = parseExpression(); if (!success) return nullptr; lex->getNextToken(t); if (t.type != TK_CLOSE_PAREN) { Error("Cound not find a matching close parentesis, open parenthesis was at %d:%d\n", loc.line, loc.col); if (!success) { return nullptr; } } return expr; } else if (t.type == TK_PERIOD) { // We support period for expressions like `.5` if (lex->checkAheadToken(TK_NUMBER, 1)) { lex->getNextToken(t); if (isHexNumber(t)) { Error("After a period we need to see normal numbers, not hex numbers"); return nullptr; } auto ex = NEW_AST(LiteralAST); ex->typeAST = getType(TK_FLOAT, nullptr); ex->_f64 = computeDecimal(t); return ex; } else { Error("Could not parse a literal expression! Unknown token type: %s", TokenTypeToStr(t.type)); return nullptr; } } Error("Could not parse a literal expression! Unknown token type: %s", TokenTypeToStr(t.type)); return nullptr; } ExpressionAST * Parser::parseUnaryExpression() { Token t; lex->lookaheadToken(t); if (t.type == TK_IDENTIFIER) { if (lex->checkAheadToken(TK_OPEN_PAREN, 1)) { return parseFunctionCall(); } } else if (t.type == TK_NEW) { lex->consumeToken(); NewAllocAST *nast = NEW_AST(NewAllocAST); nast->type = parseType(); if (!success) return nullptr; return nast; } else if (isUnaryPrefixOperator(t.type)) { lex->consumeToken(); ExpressionAST *expr = parseUnaryExpression(); if (!success) return nullptr; // optimization, if expr is a real literal, merge the actual value if (expr->ast_type == AST_LITERAL) { auto lit = (LiteralAST *)expr; switch (lit->typeAST->basic_type) { case BASIC_TYPE_FLOATING: if (t.type == TK_BANG) { Error("The bang operator cannot be used with floating point numbers"); return nullptr; } else if (t.type == TK_MINUS) { lit->_f64 = -lit->_f64; return expr; } else { assert(t.type == TK_PLUS); // a plus unary sign can be ignored return expr; } break; case BASIC_TYPE_BOOL: if (t.type == TK_BANG) { lit->_bool = !lit->_bool; return expr; } else { Error("Operator %s cannot be used with boolean types", TokenTypeToStr(t.type)); return nullptr; } break; case BASIC_TYPE_STRING: Error("The type string does not support unary operators"); return nullptr; break; case BASIC_TYPE_INTEGER: if (t.type == TK_BANG) { Error("Operator ! cannot be used for integer types"); return nullptr; //UnaryOperationAST *un = new UnaryOperationAST(); //setASTinfo(this, un); //un->op = t.type; //un->expr = expr; //return un; } else if (t.type == TK_MINUS) { if (lit->typeAST->isSigned) { lit->_s64 = -lit->_s64; } else { lit->_s64 = -(s64)lit->_u64; lit->typeAST = getType(TK_S64, nullptr); } return expr; } else { assert(t.type == TK_PLUS); // a plus unary sign can be ignored return expr; } break; } } UnaryOperationAST *un = NEW_AST(UnaryOperationAST); un->op = t.type; un->expr = expr; return un; } else if (t.type == TK_RUN) { return parseRunDirective(); } // @TODO: Handle postfix operators after the parseLiteral return parseLiteral(); } ExpressionAST *Parser::parseBinOpExpressionRecursive(u32 oldprec, ExpressionAST *lhs) { TOKEN_TYPE cur_type; while (1) { cur_type = lex->getTokenType(); if (isBinOperator(cur_type)) { u32 cur_prec = getPrecedence(cur_type); if (cur_prec < oldprec) { return lhs; } else { lex->consumeToken(); ExpressionAST *rhs = parseUnaryExpression(); if (isBinOperator(lex->getTokenType())) { u32 newprec = getPrecedence(lex->getTokenType()); if (cur_prec < newprec) { rhs = parseBinOpExpressionRecursive(cur_prec + 1, rhs); } } BinaryOperationAST *bin = NEW_AST(BinaryOperationAST); bin->lhs = lhs; bin->rhs = rhs; bin->op = cur_type; lhs = bin; } } else { break; } } return lhs; } ExpressionAST *Parser::parseBinOpExpression() { ExpressionAST *lhs = parseUnaryExpression(); return parseBinOpExpressionRecursive( 0, lhs); } ExpressionAST * Parser::parseAssignmentOrExpression() { ExpressionAST *lhs = parseBinOpExpression(); TOKEN_TYPE type; type = lex->getTokenType(); if (isAssignmentOperator(type)) { lex->consumeToken(); AssignmentAST *assign = NEW_AST(AssignmentAST); assign->lhs = lhs; assign->op = type; assign->rhs = parseAssignmentOrExpression(); return assign; } return lhs; } ExpressionAST * Parser::parseExpression() { return parseBinOpExpression(); } void Parser::parseImportDirective() { Token t; // @TODO: make import be module based with module folders // and appending extension, as well as figuring out libs to link against MustMatchToken(TK_IMPORT); if (!success) return; lex->getNextToken(t); if (t.type != TK_STRING) { Error("When parsing an #import directive, a string needs to follow\n"); return; } // import directives can define new functions // as well as new types, all in global scope / Or the current scope? // things not allowed on an import /* - full function definition? (to be discussed) - #run directives ? - #load directive */ // things ONLY allowed on an import /* - #foreign - */ // this could be done in parallel if needed be Parser import_parser; import_parser.isImport = true; import_parser.interp = interp; import_parser.current_scope = current_scope; // All modules are in the modules folder, with the extension // One day this will be a search path char fname[64]; sprintf_s(fname, "modules/%s.rad", t.string); bool val; // This does the equivalent of pragma once, and also // records the libraries we opened (#import) if (!top_level_ast->imports.get(t.string, val)) { top_level_ast->imports.put(t.string, true); import_parser.Parse(fname, pool, top_level_ast); if (!import_parser.success) { errorString = strcpy(errorString, import_parser.errorStringBuffer); success = false; } } } void Parser::parseLoadDirective() { Token t; lex->getNextToken(t); MustMatchToken(TK_LOAD); if (!success) return; lex->getNextToken(t); if (t.type != TK_STRING) { Error("When parsing an #load directive, a string needs to follow\n"); return; } // load directives can define new functions // as well as new types, all in global scope / Or the current scope? // this could be done in parallel if needed be Parser import_parser; import_parser.interp = interp; import_parser.current_scope = current_scope; import_parser.Parse(t.string, pool, top_level_ast); if (!import_parser.success) { errorString = strcpy(errorString, import_parser.errorStringBuffer); success = false; } } RunDirectiveAST* Parser::parseRunDirective() { MustMatchToken(TK_RUN); // After run, it is an expression in general. Run can appear anywhere, and affect (or not) // the code and what is parsed. // if run produces output, it should be inserted (on a separate compilation phase) ExpressionAST *expr; expr = parseUnaryExpression(); if (!success) { return nullptr; } RunDirectiveAST *run = NEW_AST(RunDirectiveAST); run->expr = expr; // have a list of all run directives to process them later on // top_level_ast->run_items.push_back(run); return run; } DefinitionAST *Parser::parseDefinition() { Token t; lex->lookaheadToken(t); if (t.type == TK_OPEN_PAREN) { bool oneArgument = (lex->checkAheadToken(TK_IDENTIFIER, 1) && lex->checkAheadToken(TK_COLON, 2)); bool noArguments = lex->checkAheadToken(TK_CLOSE_PAREN, 1); if (oneArgument || noArguments) { // if we encounter a [ ( IDENTIFER : ] sequence, this is // a function and not an expression, as we do not use the COLON // for anything else. When functions get more complex, this // check will be too. return parseFunctionDefinition(); } } else if (t.type == TK_STRUCT) { return parseStructDefinition(); } return parseExpression(); } VariableDeclarationAST * Parser::parseDeclaration(bool isStruct) { Token t; lex->getNextToken(t); VariableDeclarationAST *decl = NEW_AST(VariableDeclarationAST); if (t.type != TK_IDENTIFIER) { Error("Identifier expected but not found\n"); return nullptr; } decl->varname = t.string; lex->lookaheadToken(t); if ((t.type != TK_COLON) && (t.type != TK_DOUBLE_COLON) && (t.type != TK_IMPLICIT_ASSIGN)) { Error("Declaration needs a colon, but found token: %s\n", TokenTypeToStr(t.type)); return nullptr; } if (t.type == TK_COLON) { lex->consumeToken(); // we are doing a variable declaration decl->specified_type = parseType(); if (!success) { return nullptr; } lex->lookaheadToken(t); } if (t.type == TK_DOUBLE_COLON) { decl->flags |= DECL_FLAG_IS_CONSTANT; } if ((t.type == TK_ASSIGN) || (t.type == TK_DOUBLE_COLON) || (t.type == TK_IMPLICIT_ASSIGN)) { lex->consumeToken(); // we are doing an assignment or initial value decl->definition = parseDefinition(); if (!success) { return nullptr; } if (decl->definition->ast_type == AST_FUNCTION_DEFINITION) { // we want to be able to find the name of the function auto fundef = (FunctionDefinitionAST *)decl->definition; fundef->var_decl = decl; } else if (decl->definition->ast_type == AST_STRUCT_DEFINITION) { // we need this pointer for C generation ordering auto sdef = (StructDefinitionAST *)decl->definition; sdef->struct_type->decl = decl; } lex->lookaheadToken(t); } else if (t.type != TK_SEMICOLON) { Error("Declaration is malformed, a semicolon was expected"); if (!success) { return nullptr; } } if (!decl->definition || decl->definition->needsSemiColon) { // @TODO: support compiler flags and others here if (t.type != TK_SEMICOLON) { Error("Declaration needs to end with a semicolon\n"); if (!success) { return nullptr; } } lex->getNextToken(t); } if (!isStruct) { // struct members do not follow the AddDeclaration to scope AddDeclarationToScope(decl); } return decl; } // first version, just return a list of AST FileAST *Parser::Parse(const char *filename, PoolAllocator *pool, FileAST *fast) { Lexer lex; this->lex = &lex; this->pool = pool; CPU_SAMPLE("Parser Main"); lex.setPoolAllocator(pool); if (errorString == nullptr) { errorString = errorStringBuffer; errorString[0] = 0; } if (!lex.openFile(filename)) { errorString += sprintf(errorString, "Error: File [%s] could not be opened to be processed\n", filename); return nullptr; } return ParseInternal(fast); } FileAST * Parser::ParseFromString(const char *str, u64 str_size, PoolAllocator *pool, FileAST *fast) { Lexer lex; this->lex = &lex; this->pool = pool; CPU_SAMPLE("Parser From String"); lex.setPoolAllocator(pool); if (errorString == nullptr) { errorString = errorStringBuffer; errorString[0] = 0; } if (!lex.loadString(str, str_size)) { errorString += sprintf(errorString, "Error: String could not be loaded to be processed\n"); return nullptr; } return ParseInternal(fast); } FileAST * Parser::ParseInternal(FileAST *fast) { FileAST *file_inst = nullptr; if (fast != nullptr) { file_inst = fast; } else { file_inst = new (pool) FileAST; file_inst->global_scope.parent = nullptr; file_inst->scope = &file_inst->global_scope; file_inst->filename = CreateTextType(pool, lex->getFileData()->getFilename()); } top_level_ast = file_inst; success = true; if (errorString == nullptr) { errorString = errorStringBuffer; } defineBuiltInTypes(); lex->parseFile(); interp->files.push_back(lex->getFileData()); if (option_printTokens) { while (!lex->checkToken(TK_LAST_TOKEN)) { Token t; lex->getNextToken(t); t.print(); } lex->setTokenStreamPosition(0); } if (current_scope == nullptr) { current_scope = &file_inst->global_scope; } while (!lex->checkToken(TK_LAST_TOKEN)) { Token t; lex->lookaheadToken(t); if (t.type == TK_IMPORT) { parseImportDirective(); } else if (t.type == TK_LOAD) { parseLoadDirective(); } else if (t.type == TK_RUN) { RunDirectiveAST *r = parseRunDirective(); if (!success) { return nullptr; } // Allow semicolons after a #run directive lex->lookaheadToken(t); if (t.type == TK_SEMICOLON) lex->consumeToken(); file_inst->items.push_back(r); } else { VariableDeclarationAST *d = parseDeclaration(); if (!success) { return nullptr; } file_inst->items.push_back(d); } } this->lex = nullptr; return file_inst; }
29.469284
112
0.572058
Ibarria
27d267ead683bc769840aec6e7f7a5acd2b22680
1,425
hpp
C++
schema_parser/Schema.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
5
2021-01-15T16:59:59.000Z
2022-02-28T15:41:00.000Z
schema_parser/Schema.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
null
null
null
schema_parser/Schema.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
1
2021-06-22T04:53:38.000Z
2021-06-22T04:53:38.000Z
#ifndef H_Schema_hpp #define H_Schema_hpp #include <vector> #include <string> #include <unordered_map> #include "Types.hpp" #include <memory> namespace SchemaParser { struct Schema { struct SecondaryIndex { std::string name; std::string table; std::vector<unsigned> attributes; SecondaryIndex(const std::string & name) : name(name) { } }; struct Relation { struct Attribute { std::string name; Types::Tag type; unsigned len; unsigned len2; bool notNull; Attribute() : len(~0), notNull(false) {} }; std::string name; std::vector<std::unique_ptr<Schema::Relation::Attribute>> attributes; std::vector<unsigned> primaryKey; std::vector<Schema::SecondaryIndex *> secondaryIndices; Relation(const std::string& name) : name(name) {} }; std::vector<Schema::Relation> relations; std::vector<Schema::SecondaryIndex> indices; std::unordered_multimap<std::string, Relation::Attribute *> attributes; std::string toString() const; }; const SchemaParser::Schema & getSchema(); const Schema::Relation & getRelation(const std::string & name); const Schema::Relation::Attribute * getAttribute(const std::string & name); const Schema::Relation::Attribute * getAttribute( const Schema::Relation & rel, const std::string & name); bool isAttributeName(const std::string & name); } #endif
25.446429
75
0.667368
josefschmeisser
27d39bfa2b856a1d6bc6d630c33bf409fb69264d
1,385
cpp
C++
DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "Engine/stdafx.h" #include "Engine/Physics/PhysicsComponent.h" #include "Engine/Physics/ColliderShape.h" #include "Engine/Physics/Physics.h" PhysicsComponent::PhysicsComponent(GameObject& object) : Component(object) , m_collisionLayer(EPhysicsCollisionLayer::Default) { Modules::Physics->OnPhysicsComponentCreated(this); } PhysicsComponent::~PhysicsComponent() { Modules::Physics->OnPhysicsComponentDestroyed(this); } Component& PhysicsComponent::CloneTo(GameObject& otherObject) const { PhysicsComponent& newComponent = Modules::Physics->CreatePhysicsComponentOnObject(otherObject); newComponent.SetCollisionLayer(GetCollisionLayer()); newComponent.SetCollisionDetectionMode(GetCollisionDetectionMode()); newComponent.m_physicsMaterial = GetPhysicsMaterial(); newComponent.SetBodyType(GetBodyType()); newComponent.SetTrigger(IsTrigger()); newComponent.SetMass(GetMass()); newComponent.SetLinearDamping(GetLinearDamping()); newComponent.SetAngularDamping(GetAngularDamping()); newComponent.SetEnabled(IsEnabled()); return newComponent; } void PhysicsComponent::SetCollisionLayer(EPhysicsCollisionLayer collisionLayer) { m_collisionLayer = collisionLayer; } EPhysicsCollisionLayer PhysicsComponent::GetCollisionLayer() const { return m_collisionLayer; } const PhysicsMaterial& PhysicsComponent::GetPhysicsMaterial() const { return m_physicsMaterial; }
28.854167
96
0.823105
nyaki-HUN
27d5c06f468040ac9f7a3fb1a5d1da135cf3b071
3,368
cpp
C++
Sources/Files/LoadedValue.cpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
1
2019-03-13T08:26:38.000Z
2019-03-13T08:26:38.000Z
Sources/Files/LoadedValue.cpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
Sources/Files/LoadedValue.cpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
#include "LoadedValue.hpp" #include <ostream> namespace acid { LoadedValue::LoadedValue(LoadedValue *parent, const std::string &name, const std::string &value, const std::map<std::string, std::string> &attributes) : m_parent(parent), m_children(std::vector<LoadedValue *>()), m_name(FormatString::RemoveAll(name, '\"')), m_value(value), m_attributes(attributes) { } LoadedValue::~LoadedValue() { for (auto &child : m_children) { delete child; } } std::vector<LoadedValue *> LoadedValue::GetChildren(const std::string &name) { auto result = std::vector<LoadedValue *>(); for (auto &child : m_children) { if (child->m_name == name) { result.push_back(child); } } return result; } LoadedValue *LoadedValue::GetChild(const std::string &name, const bool &addIfNull, const bool &reportError) { std::string nameNoSpaces = FormatString::Replace(name, " ", "_"); for (auto &child : m_children) { if (child->m_name == name || child->m_name == nameNoSpaces) { return child; } } if (!addIfNull) { if (reportError) { fprintf(stderr, "Could not find child in loaded value '%s' of name '%s'\n", m_name.c_str(), name.c_str()); } return nullptr; } auto child = new LoadedValue(this, name, ""); m_children.emplace_back(child); return child; } LoadedValue *LoadedValue::GetChild(const uint32_t &index, const bool &addIfNull, const bool &reportError) { if (m_children.size() >= index) { return m_children.at(index); } // TODO //if (!addIfNull) //{ if (reportError) { fprintf(stderr, "Could not find child in loaded value '%s' at '%i'\n", m_name.c_str(), index); } return nullptr; //} } LoadedValue *LoadedValue::GetChildWithAttribute(const std::string &childName, const std::string &attribute, const std::string &value, const bool &reportError) { auto children = GetChildren(childName); if (children.empty()) { return nullptr; } for (auto &child : children) { std::string attrib = child->GetAttribute(attribute); if (attrib == value) { return child; } } if (reportError) { fprintf(stderr, "Could not find child in loaded value '%s' with '%s'\n", m_name.c_str(), attribute.c_str()); } return nullptr; } void LoadedValue::AddChild(LoadedValue *value) { auto child = GetChild(value->m_name); if (child != nullptr) { child->m_value = value->m_value; return; } child = value; m_children.emplace_back(child); } std::string LoadedValue::GetAttribute(const std::string &attribute) const { auto it = m_attributes.find(attribute); if (it == m_attributes.end()) { return nullptr; } return (*it).second; } void LoadedValue::AddAttribute(const std::string &attribute, const std::string &value) { auto it = m_attributes.find(attribute); if (it == m_attributes.end()) { m_attributes.emplace(attribute, value); } (*it).second = value; } bool LoadedValue::RemoveAttribute(const std::string &attribute) { auto it = m_attributes.find(attribute); if (it != m_attributes.end()) { m_attributes.erase(it); return true; } return false; } std::string LoadedValue::GetString() { return FormatString::RemoveAll(m_value, '\"'); } void LoadedValue::SetString(const std::string &data) { m_value = "\"" + data + "\""; } }
19.468208
159
0.649644
hhYanGG
27d6344871393ba0ea54801376ae49b4ef1f9650
5,223
cc
C++
daemon/network_interface_description.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
104
2017-05-22T20:41:57.000Z
2022-03-24T00:18:34.000Z
daemon/network_interface_description.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
3
2017-11-14T08:12:46.000Z
2022-03-03T11:14:17.000Z
daemon/network_interface_description.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
71
2017-05-22T20:41:59.000Z
2022-03-29T10:34:32.000Z
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "network_interface_description.h" #include <nlohmann/json.hpp> /// Validate the interface description static nlohmann::json validateInterfaceDescription(const nlohmann::json& json) { if (!json.is_object()) { throw std::invalid_argument("value must be JSON of type object"); } bool host = false; bool port = false; bool family = false; bool type = false; for (const auto& kv : json.items()) { if (kv.key() == "host") { if (!kv.value().is_string()) { throw std::invalid_argument("host must be JSON of type string"); } host = true; } else if (kv.key() == "port") { // Yack. One thought one could use is_number_unsigned and it would // return true for all positive integer values, but it actually // looks at the _datatype_ so it may return false for lets say // 0 and 11210. Perform the checks myself if (!kv.value().is_number_integer()) { throw std::invalid_argument("port must be JSON of type number"); } if (kv.value().get<int>() < 0) { throw std::invalid_argument("port must be a positive number"); } if (kv.value().get<int>() > std::numeric_limits<in_port_t>::max()) { throw std::invalid_argument( "port must be [0," + std::to_string(std::numeric_limits<in_port_t>::max()) + "]"); } port = true; } else if (kv.key() == "family") { if (!kv.value().is_string()) { throw std::invalid_argument( "family must be JSON of type string"); } const auto value = kv.value().get<std::string>(); if (value != "inet" && value != "inet6") { throw std::invalid_argument(R"(family must "inet" or "inet6")"); } family = true; } else if (kv.key() == "tls") { if (!kv.value().is_boolean()) { throw std::invalid_argument("tls must be JSON of type boolean"); } } else if (kv.key() == "system") { if (!kv.value().is_boolean()) { throw std::invalid_argument( "system must be JSON of type boolean"); } } else if (kv.key() == "type") { if (!kv.value().is_string()) { throw std::invalid_argument("type must be JSON of type string"); } const auto value = kv.value().get<std::string>(); if (value != "mcbp" && value != "prometheus") { throw std::invalid_argument( R"(type must "mcbp" or "prometheus")"); } type = true; } else if (kv.key() == "tag") { if (!kv.value().is_string()) { throw std::invalid_argument("tag must be JSON of type string"); } } else if (kv.key() == "uuid") { if (!kv.value().is_string()) { throw std::invalid_argument("uuid must be JSON of type string"); } } else { throw std::invalid_argument("Unsupported JSON property " + kv.key()); } } if (!host || !port || !family || !type) { throw std::invalid_argument( R"("host", "port", "family" and "type" must all be set)"); } return json; } NetworkInterfaceDescription::NetworkInterfaceDescription( const nlohmann::json& json) : NetworkInterfaceDescription(validateInterfaceDescription(json), true) { } static sa_family_t toFamily(const std::string& family) { if (family == "inet") { return AF_INET; } if (family == "inet6") { return AF_INET6; } throw std::invalid_argument( "toFamily(): family must be 'inet' or 'inet6': " + family); } NetworkInterfaceDescription::NetworkInterfaceDescription( const nlohmann::json& json, bool) : host(json["host"].get<std::string>()), port(json["port"].get<in_port_t>()), family(toFamily(json["family"].get<std::string>())), system(!(json.find("system") == json.cend()) && json["system"].get<bool>()), type(json["type"].get<std::string>() == "mcbp" ? Type::Mcbp : Type::Prometheus), tag(json.find("tag") == json.cend() ? "" : json["tag"].get<std::string>()), tls(!(json.find("tls") == json.cend()) && json["tls"].get<bool>()), uuid(json.find("uuid") == json.cend() ? "" : json["uuid"].get<std::string>()) { }
39.870229
80
0.515987
nawazish-couchbase
27dac96816d29817f5b26faa1fc7d35519651029
422
hpp
C++
exceptions/InvalidDataException.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
exceptions/InvalidDataException.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
exceptions/InvalidDataException.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
// // Created by adrijarch on 5/26/19. // #ifndef OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP #define OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP #include <stdexcept> /** * Marks any case where data has not been as expected. */ class InvalidDataException : public std::runtime_error { public: explicit InvalidDataException(const std::string &arg) : runtime_error(arg) { } }; #endif //OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP
21.1
80
0.774882
Adrijaned
27dbe03cdcc424e19cf179c200f36afdfb516e5e
854
hpp
C++
Helena/Traits/Constness.hpp
NIKEA-SOFT/HelenaFramework
4f443710e6a67242ddd4361f9c1a89e9d757c820
[ "MIT" ]
24
2020-08-17T21:49:38.000Z
2022-03-31T13:31:46.000Z
Helena/Traits/Constness.hpp
NIKEA-SOFT/HelenaFramework
4f443710e6a67242ddd4361f9c1a89e9d757c820
[ "MIT" ]
null
null
null
Helena/Traits/Constness.hpp
NIKEA-SOFT/HelenaFramework
4f443710e6a67242ddd4361f9c1a89e9d757c820
[ "MIT" ]
2
2021-04-21T09:27:03.000Z
2021-08-20T09:44:53.000Z
#ifndef HELENA_TRAITS_CONSTNESS_HPP #define HELENA_TRAITS_CONSTNESS_HPP #include <type_traits> namespace Helena::Traits { /** * @brief Transcribes the constness of a type to another type. * @tparam To The type to which to transcribe the constness. * @tparam From The type from which to transcribe the constness. */ template<typename To, typename From> struct Constness { /*! @brief The type resulting from the transcription of the constness. */ using type = std::remove_const_t<To>; }; /*! @copydoc constness_as */ template<typename To, typename From> struct Constness<To, const From> { /*! @brief The type resulting from the transcription of the constness. */ using type = std::add_const_t<To>; }; } #endif // HELENA_TRAITS_CONSTNESS_HPP
30.5
82
0.660422
NIKEA-SOFT
27e7f84dd56ff1377295227a2b0ede4ee928a7fd
1,178
hpp
C++
src/gui/hud/hud.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
7
2015-01-28T09:17:08.000Z
2020-04-21T13:51:16.000Z
src/gui/hud/hud.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
null
null
null
src/gui/hud/hud.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
1
2020-07-11T09:20:25.000Z
2020-07-11T09:20:25.000Z
/** @addtogroup Ui * @{ */ /** * Uniq object owned by the Screen. It is in charge of displaying all * static information about the game, like the time, the minimap, entities * attributes, interface buttons, etc. * @class Hud */ #include <SFML/System.hpp> #ifndef __HUP_HPP__ # define __HUP_HPP__ #define HUD_HEIGHT 323 #include <gui/screen/screen_element.hpp> #include <gui/hud/info_hud.hpp> #include <gui/hud/abilities_panel.hpp> class Screen; class GameClient; class Hud: public ScreenElement { public: Hud(GameClient* game, Screen* screen); ~Hud(); void draw() override final; bool handle_event(const sf::Event&) override final; void update(const utils::Duration& dt) override final; bool is_entity_hovered(const Entity*) const; void add_info_message(std::string&& text); void activate_ability(const std::size_t nb); bool handle_keypress(const sf::Event& event); bool handle_keyrelease(const sf::Event& event); private: Hud(const Hud&); Hud& operator=(const Hud&); GameClient* game; sf::Texture hud_texture; sf::Sprite hud_sprite; sf::Font font; AbilitiesPanel abilities_panel; InfoHud info_hud; }; #endif // __HUP_HPP__
22.226415
74
0.726655
louiz
27e9f2aa136291997b4f98ad4946faa09e82375f
1,944
hpp
C++
pellets/z_http/mem_write.hpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
pellets/z_http/mem_write.hpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
pellets/z_http/mem_write.hpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ #pragma once #include "stream_writter.hpp" #include "z_http_interface.h" namespace zl { namespace http { class ZLMemWrite : public ICurlWrite { public: ZLMemWrite() { } virtual ~ZLMemWrite() { } virtual int Write(BYTE *pData, int nLength) { m_stream.WriteBinary(pData, nLength); return nLength; } virtual const BYTE* GetData() { return (const BYTE*)m_stream.GetStream(); } virtual int GetLength() { return m_stream.GetSize(); } ZLStreamWriter& GetStreamWriter() { return m_stream; } private: ZLStreamWriter m_stream; }; } }
30.857143
74
0.296811
wohaaitinciu
27eee5181ee98dc3d63b1216c64d059f9b5afdba
5,995
hpp
C++
src/math/CartesianToGeodeticFukushima.hpp
JordanMcManus/MBES-lib
618d64f4e042bf5660015819f89537cdd70e696d
[ "MIT" ]
13
2019-10-29T14:16:13.000Z
2022-02-24T06:44:37.000Z
src/math/CartesianToGeodeticFukushima.hpp
JordanMcManus/MBES-lib
618d64f4e042bf5660015819f89537cdd70e696d
[ "MIT" ]
62
2019-04-16T13:53:50.000Z
2022-03-07T19:44:23.000Z
src/math/CartesianToGeodeticFukushima.hpp
JordanMcManus/MBES-lib
618d64f4e042bf5660015819f89537cdd70e696d
[ "MIT" ]
18
2019-04-10T19:51:21.000Z
2022-01-31T21:42:22.000Z
/* * Copyright 2020 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés */ /* * File: CartesianToGeodeticFukushima.hpp * Author: jordan */ #ifndef CARTESIANTOGEODETICFUKUSHIMA_HPP #define CARTESIANTOGEODETICFUKUSHIMA_HPP #ifdef _WIN32 #define _USE_MATH_DEFINES #include <math.h> #else #include <cmath> #endif #include <vector> #include <Eigen/Dense> #include "../Position.hpp" #include "../utils/Constants.hpp" class CartesianToGeodeticFukushima { /* * This class implements the method given in Fukushima (2006): * * Transformation from Cartesian to geodetic coordinates * accelerated by Halley's method * DOI: 10.1007/s00190-006-0023-2 */ private: unsigned int numberOfIterations; // Ellipsoid parameters double a; // semi-major axis double e2; // first eccentricity squared // Derived parameters double b; // semi-minor axis double a_inverse; // 1/a double ec; // sqrt(1 - e*e) public: CartesianToGeodeticFukushima(unsigned int numberOfIterations, double a=a_wgs84, double e2=e2_wgs84) : numberOfIterations(numberOfIterations), a(a), e2(e2) { ec = std::sqrt(1 - e2); b = a*ec; a_inverse = 1 / a; } ~CartesianToGeodeticFukushima() {}; void ecefToLongitudeLatitudeElevation(Eigen::Vector3d & ecefPosition, Position & positionGeographic) { double x = ecefPosition(0); double y = ecefPosition(1); double z = ecefPosition(2); // Center of the Earth if (x == 0.0 && y == 0.0 && z == 0.0) { positionGeographic.setLatitude(0.0); positionGeographic.setLongitude(0.0); positionGeographic.setEllipsoidalHeight(0.0); return; } // Position at Poles if (x == 0.0 && y == 0.0 && z != 0.0) { if (z > 0) { positionGeographic.setLatitude(M_PI_2*R2D); } else { positionGeographic.setLatitude(-M_PI_2*R2D); } positionGeographic.setLongitude(0.0); positionGeographic.setEllipsoidalHeight(std::abs(z) - b); return; } double pp = x * x + y * y; double p = std::sqrt(pp); // Position at Equator if (z == 0.0) { positionGeographic.setLatitude(0.0); positionGeographic.setLongitude(estimateLongitude(x, y, p)*R2D); positionGeographic.setEllipsoidalHeight(std::sqrt(x * x + y * y) - a); return; } double P = p*a_inverse; double Z = a_inverse * ec * std::abs(z); //double R = std::sqrt(pp + z * z); std::vector<double> S(numberOfIterations + 1, 0); std::vector<double> C(numberOfIterations + 1, 0); std::vector<double> D(numberOfIterations + 1, 0); std::vector<double> F(numberOfIterations + 1, 0); std::vector<double> A(numberOfIterations + 1, 0); std::vector<double> B(numberOfIterations + 1, 0); S[0] = Z; //starter variables. See (Fukushima, 2006) p.691 equation (17) C[0] = ec*P; //starter variables. See (Fukushima, 2006) p.691 equation (17) A[0] = std::sqrt(S[0] * S[0] + C[0] * C[0]); B[0] = 1.5 * e2 * e2 * P * S[0] * S[0] * C[0] * C[0] * (A[0] - ec); //starter variables. See (Fukushima, 2006) p.691 equation (18) unsigned int iterationNumber = 1; while (iterationNumber <= numberOfIterations) { D[iterationNumber - 1] = Z * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] + e2 * S[iterationNumber - 1] * S[iterationNumber - 1] * S[iterationNumber - 1]; F[iterationNumber - 1] = P * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] - e2 * C[iterationNumber - 1] * C[iterationNumber - 1] * C[iterationNumber - 1]; S[iterationNumber] = D[iterationNumber - 1] * F[iterationNumber - 1] - B[iterationNumber - 1] * S[iterationNumber - 1]; C[iterationNumber] = F[iterationNumber - 1] * F[iterationNumber - 1] - B[iterationNumber - 1] * C[iterationNumber - 1]; A[iterationNumber] = std::sqrt( S[iterationNumber] * S[iterationNumber] + C[iterationNumber] * C[iterationNumber]); B[iterationNumber] = 1.5 * e2 * S[iterationNumber] * C[iterationNumber] * C[iterationNumber] * ((P * S[iterationNumber] - Z * C[iterationNumber]) * A[iterationNumber] - e2 * S[iterationNumber] * C[iterationNumber]); ++iterationNumber; } double lon = estimateLongitude(x, y, p); double Cc = ec*C[numberOfIterations]; double lat = estimateLatitude(z, S[numberOfIterations], Cc); double h = estimateHeight(z, p, A[numberOfIterations], S[numberOfIterations], Cc); positionGeographic.setLatitude(lat*R2D); positionGeographic.setLongitude(lon*R2D); positionGeographic.setEllipsoidalHeight(h); } double estimateLongitude(double x, double y, double p) { // Vermeille (2004), stable longitude calculation // atan(y/x) suffers when x = 0 if (y < 0) { return -M_PI_2 + 2*std::atan(x/(p - y)); } return M_PI_2 - 2*std::atan(x/(p + y)); } double estimateLatitude(double z, double S, double Cc) { double lat = std::abs(std::atan(S / Cc)); if (z < 0) { return -lat; } return lat; } double estimateHeight(double z, double p, double A, double S, double Cc) { return (p * Cc + std::abs(z) * S - b * A) / std::sqrt(Cc * Cc + S * S); } }; #endif /* CARTESIANTOGEODETICFUKUSHIMA_HPP */
32.93956
139
0.568474
JordanMcManus
27f50ee1c6d1bb148b49053e73d852f5ee973bd8
2,350
cpp
C++
src/framework/GSD3D11Mesh.cpp
3dhater/miGUI
a086201ce18393d7d00f4018a201635ed5aa63c0
[ "MIT" ]
1
2021-11-16T23:11:26.000Z
2021-11-16T23:11:26.000Z
src/framework/GSD3D11Mesh.cpp
3dhater/miGUI
a086201ce18393d7d00f4018a201635ed5aa63c0
[ "MIT" ]
null
null
null
src/framework/GSD3D11Mesh.cpp
3dhater/miGUI
a086201ce18393d7d00f4018a201635ed5aa63c0
[ "MIT" ]
null
null
null
#include "mgf.h" #ifdef MGF_GS_D3D11 #include "Log.h" #include "GSD3D11.h" #include "GSD3D11Mesh.h" using namespace mgf; GSD3D11Mesh::GSD3D11Mesh(GSMeshInfo* mi, ID3D11Device* d, ID3D11DeviceContext* dc) { m_d3d11DevCon = dc; m_meshInfo = *mi; Mesh* mesh = (Mesh*)m_meshInfo.m_meshPtr; m_vertexType = mesh->m_vertexType; D3D11_BUFFER_DESC vbd, ibd; ZeroMemory(&vbd, sizeof(D3D11_BUFFER_DESC)); ZeroMemory(&ibd, sizeof(D3D11_BUFFER_DESC)); vbd.Usage = D3D11_USAGE_DEFAULT; //vbd.Usage = D3D11_USAGE_DYNAMIC; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_STREAM_OUTPUT; ibd.Usage = D3D11_USAGE_DEFAULT; //ibd.Usage = D3D11_USAGE_DYNAMIC; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; //vbd.CPUAccessFlags = 0; //ibd.CPUAccessFlags = 0; //D3D11_CPU_ACCESS_WRITE D3D11_SUBRESOURCE_DATA vData, iData; ZeroMemory(&vData, sizeof(D3D11_SUBRESOURCE_DATA)); ZeroMemory(&iData, sizeof(D3D11_SUBRESOURCE_DATA)); HRESULT hr = 0; vbd.ByteWidth = mesh->m_stride * mesh->m_vCount; vData.pSysMem = &mesh->m_vertices[0]; hr = d->CreateBuffer(&vbd, &vData, &m_vBuffer); if (FAILED(hr)) LogWriteError("Can't create Direct3D 11 vertex buffer\n"); m_stride = mesh->m_stride; m_iCount = mesh->m_iCount; if (mesh->m_indices) { uint32_t index_sizeof = sizeof(uint16_t); m_indexType = DXGI_FORMAT_R16_UINT; if (mesh->m_indexType == Mesh::MeshIndexType_u32) { m_indexType = DXGI_FORMAT_R32_UINT; index_sizeof = sizeof(uint32_t); } ibd.ByteWidth = index_sizeof * mesh->m_iCount; iData.pSysMem = &mesh->m_indices[0]; hr = d->CreateBuffer(&ibd, &iData, &m_iBuffer); if (FAILED(hr)) LogWriteError("Can't create Direct3D 11 index buffer\n"); } } GSD3D11Mesh::~GSD3D11Mesh() { if (m_vBuffer) { m_vBuffer->Release(); m_vBuffer = 0; } if (m_iBuffer) { m_iBuffer->Release(); m_iBuffer = 0; } } void GSD3D11Mesh::MapModelForWriteVerts(uint8_t** v_ptr) { static D3D11_MAPPED_SUBRESOURCE mapData; auto hr = m_d3d11DevCon->Map( m_vBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapData ); if (FAILED(hr)) { printf("Can not lock D3D11 render model buffer. Code : %u\n", hr); return; } *v_ptr = (uint8_t*)mapData.pData; m_lockedResource = m_vBuffer; } void GSD3D11Mesh::UnmapModelForWriteVerts() { m_d3d11DevCon->Unmap(m_lockedResource, 0); m_lockedResource = nullptr; } #endif
21.363636
82
0.722979
3dhater
27f56b53bc11e807e51a4ede90f64c85420a85ec
758
cpp
C++
src/scenes/stage.cpp
AgoutiGames/Piper
160f0c7e8afb8d3ea91dd69ee10c63da60f66a21
[ "MIT" ]
null
null
null
src/scenes/stage.cpp
AgoutiGames/Piper
160f0c7e8afb8d3ea91dd69ee10c63da60f66a21
[ "MIT" ]
2
2020-06-13T11:48:59.000Z
2020-06-13T11:56:24.000Z
src/scenes/stage.cpp
AgoutiGames/Piper
160f0c7e8afb8d3ea91dd69ee10c63da60f66a21
[ "MIT" ]
null
null
null
#include "scenes/stage.hpp" #include "core/scene_manager.hpp" const char* Stage::type = "Stage"; const bool Stage::good = GameScene::register_class<Stage>(Stage::type); Stage::Stage(salmon::MapRef map, SceneManager* scene_manager) : GameScene(map,scene_manager) {} void Stage::init() { m_scene_manager->set_game_resolution(320,320); m_scene_manager->set_fullscreen(false); m_scene_manager->set_window_size(640,640); // Initializes all characters in scene GameScene::init(); // Setup member vars here | example: put(m_speed, "m_speed"); // Clear data accessed via put get_data().clear(); } void Stage::update() { // Add scene logic here // Calls update on all characters in scene GameScene::update(); }
25.266667
71
0.695251
AgoutiGames
27f7d4bfcbb0624d36a6f492fcc93315fc86bbb9
1,141
cxx
C++
Applications/WorkBench/main.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
4
2017-04-13T06:01:49.000Z
2019-12-04T07:23:53.000Z
Applications/WorkBench/main.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
1
2017-10-27T02:00:44.000Z
2017-10-27T02:00:44.000Z
Applications/WorkBench/main.cxx
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
2
2017-09-06T01:59:07.000Z
2019-12-04T07:23:54.000Z
#include <QApplication> //qfmain #include "iqf_main.h" //qtxml #include "Utils/PluginFactory.h" #include "UIs/QF_Plugin.h" #ifdef Q_WS_X11 #include <X11/Xlib.h> #endif #include "qf_log.h" int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); std::cout << "*********************************************Initialize Main Control**************************************************" << std::endl; //Create IQF_Main object, meanwhile assign application entry and library path QF::IQF_Main* pMain = QF::QF_CreateMainObject(qApp->applicationFilePath().toLocal8Bit().constData(), qApp->applicationDirPath().toLocal8Bit().constData(), false); //Load the launcher plugin pMain->Init("","init-plugins.cfg"); std::cout << "***************************************************Initialized*********************************************************\n" << std::endl; //Setup launcher QF::QF_Plugin* launcher = dynamic_cast<QF::QF_Plugin*>(QF::PluginFactory::Instance()->Create("Launcher")); launcher->SetMainPtr(pMain); launcher->SetupResource(); return qtapplication.exec(); }
33.558824
154
0.568799
linson7017
27f9371977b9d599d725a7c73671a4ead38ad6b0
3,819
cpp
C++
src/tracer/src/core/medium/heterogeneous.cpp
AirGuanZ/Atrc
a0c4bc1b7bb96ddffff8bb1350f88b651b94d993
[ "MIT" ]
358
2018-11-29T08:15:05.000Z
2022-03-31T07:48:37.000Z
src/tracer/src/core/medium/heterogeneous.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
23
2019-04-06T17:23:58.000Z
2022-02-08T14:22:46.000Z
src/tracer/src/core/medium/heterogeneous.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
22
2019-03-04T01:47:56.000Z
2022-01-13T06:06:49.000Z
#include <agz/tracer/core/medium.h> #include <agz/tracer/core/texture3d.h> #include <agz/tracer/utility/phase_function.h> #include <agz-utils/misc.h> #include <agz-utils/texture.h> AGZ_TRACER_BEGIN class HeterogeneousMedium : public Medium { FTransform3 local_to_world_; RC<const Texture3D> density_; RC<const Texture3D> albedo_; RC<const Texture3D> g_; real max_density_; real inv_max_density_; int max_scattering_count_; public: HeterogeneousMedium( const FTransform3 &local_to_world, RC<const Texture3D> density, RC<const Texture3D> albedo, RC<const Texture3D> g, int max_scattering_count) { local_to_world_ = local_to_world; density_ = std::move(density); albedo_ = std::move(albedo); g_ = std::move(g); max_density_ = density_->max_real(); max_density_ = (std::max)(max_density_, EPS()); inv_max_density_ = 1 / max_density_; max_scattering_count_ = max_scattering_count; } int get_max_scattering_count() const noexcept override { return max_scattering_count_; } FSpectrum tr( const FVec3 &a, const FVec3 &b, Sampler &sampler) const noexcept override { real result = 1; real t = 0; const real t_max = distance(a, b); for(;;) { const real delta_t = -std::log(1 - sampler.sample1().u) * inv_max_density_; t += delta_t; if(t >= t_max) break; const FVec3 pos = lerp(a, b, t / t_max); const FVec3 unit_pos = local_to_world_.apply_inverse_to_point(pos); const real density = density_->sample_real(unit_pos); result *= 1 - density / max_density_; } return FSpectrum(result); } FSpectrum ab( const FVec3 &a, const FVec3 &b, Sampler &sampler) const noexcept override { // FIXME return tr(a, b, sampler); } SampleOutScatteringResult sample_scattering( const FVec3 &a, const FVec3 &b, Sampler &sampler, Arena &arena) const noexcept override { const real t_max = distance(a, b); real t = 0; for(;;) { const real delta_t = -std::log(1 - sampler.sample1().u) * inv_max_density_; t += delta_t; if(t >= t_max) break; const FVec3 pos = lerp(a, b, t / t_max); const FVec3 unit_pos = local_to_world_.apply_inverse_to_point(pos); const real density = density_->sample_real(unit_pos); if(sampler.sample1().u < density / max_density_) { const FSpectrum albedo = albedo_->sample_spectrum(unit_pos); const real g = g_->sample_real(unit_pos); MediumScattering scattering; scattering.pos = pos; scattering.medium = this; scattering.wr = (a - b) / t_max; auto phase_function = arena.create<HenyeyGreensteinPhaseFunction>( g, FSpectrum(albedo)); return SampleOutScatteringResult( scattering, FSpectrum(albedo), phase_function); } } return SampleOutScatteringResult({}, FSpectrum(1), nullptr); } }; RC<Medium> create_heterogeneous_medium( const FTransform3 &local_to_world, RC<const Texture3D> density, RC<const Texture3D> albedo, RC<const Texture3D> g, int max_scattering_count) { return newRC<HeterogeneousMedium>( local_to_world, std::move(density), std::move(albedo), std::move(g), max_scattering_count); } AGZ_TRACER_END
28.5
81
0.579733
AirGuanZ
7e061b21f22d9c5e4f585bf7e991810c4974be77
554
cpp
C++
src/ShowAlwaysOn.cpp
joergkeller/arduino-musicbox
2fbbfabd77a9daf6fdc73b6212416be7ec7bca22
[ "MIT" ]
null
null
null
src/ShowAlwaysOn.cpp
joergkeller/arduino-musicbox
2fbbfabd77a9daf6fdc73b6212416be7ec7bca22
[ "MIT" ]
7
2019-05-12T22:08:55.000Z
2021-04-29T12:26:25.000Z
src/ShowAlwaysOn.cpp
joergkeller/arduino-musicbox
2fbbfabd77a9daf6fdc73b6212416be7ec7bca22
[ "MIT" ]
null
null
null
/* * Constantly switch on all lights of the trellis display. * * Written by Jörg Keller, Winterthur, Switzerland * https://github.com/joergkeller/arduino-musicbox * MIT license, all text above must be included in any redistribution */ #include "ShowAlwaysOn.h" ShowAlwaysOn::ShowAlwaysOn(const Adafruit_Trellis& t) : trellis(t) {} void ShowAlwaysOn::initialize() { trellis.setBrightness(BRIGHTNESS_IDLE); trellis.blinkRate(HT16K33_BLINK_OFF); for (byte i = 0; i < NUMKEYS; i++) { trellis.setLED(i); } trellis.writeDisplay(); }
25.181818
69
0.722022
joergkeller
7e0d343109dfea3b9c1cc5bb77248222b6979b1d
1,114
cpp
C++
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
#include <iostream>; #include <string>; #include <unordered_set> #include <unordered_map> #include <map>; using std::cin; using std::cout; using std::endl; using std::string; using std::map; using std::unordered_map; using std::unordered_set; int main() { std::cin.sync_with_stdio(false); std::cout.sync_with_stdio(false); map<string, int> playersDict; unordered_map<string, unordered_set<string>> teamsDict; int t = 0; cin >> t; for (int i = 0; i < t; i++) { string team = ""; cin >> team; int teamSize = 0; cin >> teamSize; for (int j = 0; j < teamSize; j++) { string teamMember = ""; cin >> teamMember; teamsDict[team].insert(teamMember); playersDict[teamMember] = 0; } } int g = 0; cin >> g; for (int i = 0; i < g; i++) { string team = ""; cin >> team; std::unordered_map<string, unordered_set<string>>::iterator foundTeam = teamsDict.find(team); if (foundTeam != teamsDict.end()) { for (auto const& player : foundTeam->second) { playersDict[player]++; } } } // output for (auto const& player : playersDict) { cout << player.second << " "; } }
20.62963
95
0.631957
Knightwalker
7e0ed2ed9273a7f594c83ab02d157548ca530ace
1,483
cpp
C++
solved/c-e/dynamic-frog/frog.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/c-e/dynamic-frog/frog.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/c-e/dynamic-frog/frog.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cstdio> #include <cstring> using namespace std; #define MAXN 100 #define Zero(v) memset((v), 0, sizeof(v)) int N, D; int rocks[MAXN + 2]; int n; bool vis[MAXN + 2]; bool check(int d) { Zero(vis); int from = 0, to = 0; for (int i = 1; i < n; ++i) { if (rocks[i] - rocks[from] <= d) { to = i; continue; } vis[to] = true; from = to, to = i; if (rocks[to] - rocks[from] > d) return false; } vis[n-1] = false; from = 0; for (int i = 1; i < n; ++i) { if (vis[i]) continue; if (rocks[i] - rocks[from] > d) return false; from = i; } return true; } int shortest() { int lo = 0, hi = rocks[n - 1] - rocks[0]; while (lo <= hi) { int mid = (hi + lo) / 2; if (check(mid)) hi = mid - 1; else lo = mid + 1; } return lo; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%d%d", &N, &D); int ans = 0; n = 1; rocks[0] = 0; for (int i = 0; i < N; ++i) { char S; int M; scanf(" %c-%d", &S, &M); rocks[n++] = M; if (S == 'B') { ans = max(ans, shortest()); n = 1; rocks[0] = M; } } rocks[n++] = D; ans = max(ans, shortest()); printf("Case %d: %d\n", ++ncase, ans); } return 0; }
16.662921
62
0.403237
abuasifkhan
7e12279f45de48bf733b2984cf350751b11a54a0
838
cpp
C++
src/util/util.cpp
TijnBertens/light-show
a95c63b96643b9ec5dead495ffc6f45048bfee5f
[ "MIT" ]
1
2020-11-10T22:05:19.000Z
2020-11-10T22:05:19.000Z
src/util/util.cpp
TijnBertens/light-show
a95c63b96643b9ec5dead495ffc6f45048bfee5f
[ "MIT" ]
null
null
null
src/util/util.cpp
TijnBertens/light-show
a95c63b96643b9ec5dead495ffc6f45048bfee5f
[ "MIT" ]
null
null
null
#include "util.hpp" int Util::read_file(char **buffer, size_t *size, const char *file_name) { FILE *file = fopen(file_name, "rb"); if (!file) { ls_log::log(LOG_ERROR, "failed to open file \"%s\"\n", file_name); return EXIT_FAILURE; } fseek(file, 0, SEEK_END); *size = ftell(file); rewind(file); *buffer = new char[*size + 1]; // +1 for null terminator if (!(*buffer)) { ls_log::log(LOG_ERROR, "failed to allocate %d bytes\n", *size); fclose(file); return EXIT_FAILURE; } size_t read_size = fread(*buffer, sizeof(char), *size, file); fclose(file); if (read_size != *size) { ls_log::log(LOG_ERROR, "failed to read all bytes in file\n", *size); return EXIT_FAILURE; } (*buffer)[*size] = '\0'; return EXIT_SUCCESS; }
23.277778
76
0.577566
TijnBertens
7e14065129dfc400b0987c24236954090dbe741d
4,811
cpp
C++
test_deprecated/testUtil/example_tc_socket.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
1
2019-09-05T07:25:51.000Z
2019-09-05T07:25:51.000Z
test_deprecated/testUtil/example_tc_socket.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
null
null
null
test_deprecated/testUtil/example_tc_socket.cpp
SuckShit/TarsCpp
3f42f4e7a7bf43026a782c5d4b033155c27ed0c4
[ "BSD-3-Clause" ]
1
2021-05-21T09:59:06.000Z
2021-05-21T09:59:06.000Z
/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "util/tc_socket.h" #include "util/tc_clientsocket.h" #include "util/tc_http.h" #include "util/tc_epoller.h" #include "util/tc_common.h" #include <iostream> #include <arpa/inet.h> #include <fcntl.h> #include <netdb.h> using namespace tars; string now2str(const string &sFormat = "%Y%m%d%H%M%S") { time_t t = time(NULL); struct tm *pTm = localtime(&t); if(pTm == NULL) { return ""; } char sTimeString[255] = "\0"; strftime(sTimeString, sizeof(sTimeString), sFormat.c_str(), pTm); return string(sTimeString); } void testTC_Socket() { TC_Socket tcSocket; tcSocket.createSocket(); tcSocket.bind("192.168.128.66", 8765); tcSocket.listen(5); } void testTC_TCPClient() { TC_TCPClient tc; tc.init("172.16.28.79", 8382, 3); cout << now2str() << endl; int i = 10000; while(i>0) { string s = "test"; char c[1024] = "\0"; size_t length = 4; int iRet = tc.sendRecv(s.c_str(), s.length(), c, length); if(iRet < 0) { cout << "send recv error:" << iRet << ":" << c << endl; } i--; // cout << c << endl; assert(c == s); } cout << now2str() << endl; } void testShortSock() { int i = 1000; while(i>0) { TC_TCPClient tc; tc.init("127.0.0.1", 8382, 10); string s = "test"; char c[1024] = "\0"; size_t length = 4; int iRet = tc.sendRecv(s.c_str(), s.length(), c, length); if(iRet < 0) { cout << "send recv error" << endl; } if(i % 1000 == 0) { cout << i << endl; } usleep(10); i--; assert(c == s); } } void testUdp() { fork();fork();fork();fork();fork(); int i = 1000; string s; for(int j = 0; j < 7192; j++) { s += "0"; } s += "\n"; while(i>0) { TC_UDPClient tc; tc.init("127.0.0.1", 8082, 3000); char c[10240] = "\0"; size_t length = sizeof(c); int iRet = tc.sendRecv(s.c_str(), s.length(), c, length); if(iRet < 0) { cout << "send recv error:" << iRet << endl; } if(i % 1000 == 0) { cout << i << endl; } i--; if(c != s) { cout << c << endl; // break; } } } void testTimeoutSock() { int i = 10; while(i>0) { TC_TCPClient tc; tc.init("127.0.0.1", 8382, 3); string s = "test"; char c[1024] = "\0"; size_t length = 4; int iRet = tc.sendRecv(s.c_str(), s.length(), c, length); if(iRet < 0) { cout << "send recv error" << endl; } if(i % 1000 == 0) { cout << i << endl; } i--; sleep(3); assert(c == s); } } void testLocalHost() { vector<string> v = TC_Socket::getLocalHosts(); cout << TC_Common::tostr(v.begin(), v.end()) << endl; } int main(int argc, char *argv[]) { try { testUdp(); return 0; TC_Socket t; t.createSocket(); t.bind("127.0.0.1", 0); string d; uint16_t p; t.getSockName(d, p); t.close(); cout << d << ":" << p << endl; return 0; testLocalHost(); string st; TC_Socket s; s.createSocket(SOCK_STREAM, AF_LOCAL); if(argc > 1) { s.bind("/tmp/tmp.udp.sock"); s.listen(5); s.getSockName(st); cout << st << endl; struct sockaddr_un stSockAddr; socklen_t iSockAddrSize = sizeof(sockaddr_un); TC_Socket c; s.accept(c, (struct sockaddr *) &stSockAddr, iSockAddrSize); } else { s.connect("/tmp/tmp.udp.sock"); s.getPeerName(st); cout << st << endl; } } catch(exception &ex) { cout << ex.what() << endl; } return 0; }
21.193833
92
0.49761
SuckShit
7e1e127e19c3473f9d35587aee2a2f2ef038b05e
610
cpp
C++
Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
31
2018-10-30T09:54:23.000Z
2022-03-02T21:45:51.000Z
Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
2
2016-12-24T23:39:20.000Z
2017-07-02T22:51:28.000Z
Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
30
2018-10-25T12:28:36.000Z
2022-01-31T14:31:02.000Z
#include <bits/stdc++.h> #define N 20 using namespace std; int tab[N]; string ans[N]; string v[N]; int n; int main() { ios_base::sync_with_stdio(0); ans[1]="1"; ans[2]="2\n1"; v[1]="1"; v[2]="1\n2\n1"; cin>>n; for(int i=3;i<=n;++i) { ans[i]=""; ans[i]=ans[i]+ans[i-2]+"\n"; if(i/10!=0) ans[i]+=('0'+i/10); ans[i]+=('0'+i%10); ans[i]+="\n"; ans[i]=ans[i]+v[i-1]; v[i]=v[i-1]+"\n"; if(i/10!=0) v[i]+=('0'+i/10); v[i]+=('0'+i%10); v[i]+="\n"; v[i]=v[i]+v[i-1]; } cout<<ans[n]<<endl; return 0; }
16.944444
34
0.406557
Wurlosh
7e219e1b2c300ef8b466403ebd01c7ddd29d7c70
2,897
cpp
C++
CaptureManagerSource/CaptureManager/Main.cpp
luoyingwen/CaptureManagerSDK
e96395a120175a45c56ff4e2b3283b807a42fd75
[ "MIT" ]
64
2020-07-20T09:35:16.000Z
2022-03-27T19:13:08.000Z
CaptureManagerSource/CaptureManager/Main.cpp
luoyingwen/CaptureManagerSDK
e96395a120175a45c56ff4e2b3283b807a42fd75
[ "MIT" ]
8
2020-07-30T09:20:28.000Z
2022-03-03T22:37:10.000Z
CaptureManagerSource/CaptureManager/Main.cpp
luoyingwen/CaptureManagerSDK
e96395a120175a45c56ff4e2b3283b807a42fd75
[ "MIT" ]
28
2020-07-20T13:02:42.000Z
2022-03-18T07:36:05.000Z
/* MIT License Copyright(c) 2020 Evgeny Pereguda 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. */ #define WIN32_LEAN_AND_MEAN #include "../Common/Singleton.h" #include "CommercialConfig.h" #include "Libraries.h" #include "../COMServer/RegisterManager.h" #include "../COMServer/ClassFactory.h" #include "../LogPrintOut/LogPrintOut.h" #include "../Common/Macros.h" using namespace CaptureManager; using namespace CaptureManager::COMServer; HINSTANCE gModuleInstance = NULL; BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: gModuleInstance = hInstance; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } STDAPI DllCanUnloadNow() { return Singleton<ClassFactory>::getInstance().checkLock(); } STDAPI DllGetClassObject( REFCLSID aRefCLSID, REFIID aRefIID, void** aPtrPtrVoidObject) { return Singleton<ClassFactory>::getInstance().getClassObject( aRefCLSID, aRefIID, aPtrPtrVoidObject); } STDAPI DllRegisterServer() { return Singleton<RegisterManager>::getInstance().registerServer(gModuleInstance); } STDAPI DllUnregisterServer() { return Singleton<RegisterManager>::getInstance().unregisterServer(gModuleInstance); } void InitLogOut() { LogPrintOut::getInstance().printOutln( LogPrintOut::INFO_LEVEL, L"***** CAPTUREMANAGER SDK ", (int)VERSION_MAJOR, L".", (int)VERSION_MINOR, L".", (int)VERSION_PATCH, L" ", WSTRINGIZE(ADDITIONAL_LABEL), L" - ", __DATE__, L" (Author: Evgeny Pereguda) *****\n"); } void UnInitLogOut() { LogPrintOut::getInstance().printOutlnUnlock( LogPrintOut::INFO_LEVEL, L"***** CAPTUREMANAGER SDK ", (int)VERSION_MAJOR, L".", (int)VERSION_MINOR, L".", (int)VERSION_PATCH, L" ", WSTRINGIZE(ADDITIONAL_LABEL), L" - ", __DATE__, L" (Author: Evgeny Pereguda) - is closed *****\n"); }
24.974138
85
0.754574
luoyingwen
7e28d48a883b09ea6b4fbe126622a7206d5a7d32
1,872
cc
C++
transformations/legacy/LinearInterpolator.cc
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
5
2019-10-14T01:06:57.000Z
2021-02-02T16:33:06.000Z
transformations/legacy/LinearInterpolator.cc
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
transformations/legacy/LinearInterpolator.cc
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
#include "LinearInterpolator.hh" void LinearInterpolator::indexBins() { if (m_xs.size() < 2) { return; } double minbinsize = std::numeric_limits<double>::infinity(); for (size_t i = 0; i < m_xs.size()-1; ++i) { minbinsize = std::min(minbinsize, m_xs[i+1] - m_xs[i]); } m_index.clear(); m_index.reserve((m_xs.back() - m_xs.front())/minbinsize); double x = m_xs.front(); size_t i = 0; for (size_t k = 0; ; ++k) { x = m_xs.front() + k*minbinsize; if (x > m_xs[i]) { if (i+1 == m_xs.size()) { m_index.push_back(i); break; } else { i += 1; } } m_index.push_back(i); } m_minbinsize = minbinsize; } void LinearInterpolator::interpolate(FunctionArgs& fargs) { const auto &xs = fargs.args[0].x; auto &ys = fargs.rets[0].x; Eigen::ArrayXi idxes = ((xs - m_xs[0]) / m_minbinsize).cast<int>(); for (int i = 0; i < idxes.size(); ++i) { if (idxes(i) < 0 || static_cast<size_t>(idxes(i)) >= m_index.size()) { if (m_status_on_fail == ReturnOnFail::UseZero) { ys(i) = 0.; } else { ys(i) = std::numeric_limits<double>::quiet_NaN(); } continue; } size_t j; for (j = m_index[idxes(i)]; j < m_xs.size(); ++j) { if (m_xs[j] <= xs(i) && xs(i) <= m_xs[j+1]) { break; } } if (j < m_xs.size()) { size_t j2; double off = xs(i) - m_xs[j]; if (off == 0) { ys(i) = m_ys[j]; continue; } else if ((off > 0 && j+1 < m_xs.size()) || j == 0) { j2 = j+1; } else { j2 = j-1; } ys(i) = m_ys[j] + (m_ys[j2]-m_ys[j])/(m_xs[j2]-m_xs[j])*off; } else if (m_status_on_fail == ReturnOnFail::UseNaN) { ys(i) = std::numeric_limits<double>::quiet_NaN(); } else if (m_status_on_fail == ReturnOnFail::UseZero) { ys(i) = 0.; } } }
27.130435
74
0.514423
gnafit
7e2aadb0e396b36365109f16ac9086a5307fcc81
990
cpp
C++
learn_joy/src/jaws_joy_pub_joint.cpp
iConor/learn-ros
91343f06c9d0df1c69ff01203a959366b0905953
[ "BSD-3-Clause" ]
2
2015-10-21T16:37:07.000Z
2017-09-03T13:54:36.000Z
learn_joy/src/jaws_joy_pub_joint.cpp
iConor/learn-ros
91343f06c9d0df1c69ff01203a959366b0905953
[ "BSD-3-Clause" ]
null
null
null
learn_joy/src/jaws_joy_pub_joint.cpp
iConor/learn-ros
91343f06c9d0df1c69ff01203a959366b0905953
[ "BSD-3-Clause" ]
null
null
null
#include <ros/ros.h> #include <sensor_msgs/JointState.h> #include <sensor_msgs/Joy.h> class Servos { private: ros::NodeHandle nh; ros::Subscriber sub; ros::Publisher pub; sensor_msgs::JointState js; public: Servos(); void callback(const sensor_msgs::Joy::ConstPtr& joy); void loop(); }; int main(int argc, char **argv) { ros::init(argc, argv, "state_publisher"); Servos servos; servos.loop(); } Servos::Servos() : nh() { sub = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Servos::callback, this); pub = nh.advertise<sensor_msgs::JointState>("joint_states", 1); } void Servos::callback(const sensor_msgs::Joy::ConstPtr& joy) { js.header.stamp = ros::Time::now(); js.name.resize(2); js.position.resize(2); js.name[0] ="port-base"; js.position[0] = joy->axes[2] * -0.7853975; js.name[1] ="stbd-base"; js.position[1] = joy->axes[2] * -0.7853975; pub.publish(js); } void Servos::loop() { while(ros::ok()) { ros::spin(); } }
19.411765
74
0.634343
iConor
7e2e35a3010afffb4f4882e87cd594fc5d4b5db6
1,813
hpp
C++
src/FrameWork/Math/Vectors.hpp
kevin20x2/PersistEngine
eeb4e14840d53274aa51fca6ad69f6f44a4e61ab
[ "MIT" ]
null
null
null
src/FrameWork/Math/Vectors.hpp
kevin20x2/PersistEngine
eeb4e14840d53274aa51fca6ad69f6f44a4e61ab
[ "MIT" ]
null
null
null
src/FrameWork/Math/Vectors.hpp
kevin20x2/PersistEngine
eeb4e14840d53274aa51fca6ad69f6f44a4e61ab
[ "MIT" ]
null
null
null
#pragma once #include <math.h> namespace Persist { #pragma pack(push) #pragma pack(4) template <typename T> struct Vector2 { Vector2(T _x, T _y) : x(_x) { } T x,y; }; using Vector2f = Vector2<float>; template <typename T> struct Vector3 { Vector3(T _x,T _y , T _z) : x(_x),y(_y),z(_z) { } Vector3(const Vector3 & rhs) : x(rhs.x) , y(rhs.y),z(rhs.z) { } T dot(const Vector3 & rhs) { return x*rhs.x + y * rhs.y + z * rhs.z; } T dot(const Vector3 & rhs) const { return x* rhs.x + y*rhs.y + z* rhs.z; } Vector3 operator *(const Vector3 & rhs) { return Vector3(x * rhs.x , y * rhs.y , z * rhs.z); } Vector3 operator*(T mul) const { return Vector3(x *mul , y * mul , z * mul); } // no pram Vector3 operator-() const { return Vector3(-x,-y,-z); } T length() { return sqrt(x*x + y*y + z*z); } Vector3 & normalize() { T len = length(); if(len > 1e-6) { x/= len; y/= len; z/= len; return *this; } else { throw Status::Error("normalize vector of length 0"); return *this; } } //T x,y,z; union { T x , r ;}; union { T y , g ;}; union { T z , b ;}; }; using Vector3f = Vector3<float> ; template <typename T> struct Vector4 { Vector4( T _x , T _y , T _z , T _w) : x(_x),y(_y),z(_z),w(_w) { } Vector4(const Vector4 & rhs) : x(rhs.x) , y (rhs.y) , z(rhs.z) ,w(rhs.z) { } union { T x,r; }; union { T y,g; }; union { T z,b; }; union { T w,a; }; }; using Vector4f = Vector4<float>; #pragma pack(pop) }
15.62931
64
0.453392
kevin20x2
7e2fe949026cf8235f24d233935c8342af9c649a
2,955
cpp
C++
benchmarks/statistical/spawn_threads_analysis.cpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
benchmarks/statistical/spawn_threads_analysis.cpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
benchmarks/statistical/spawn_threads_analysis.cpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2012 Daniel Kogler // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /*This benchmark measures how long it takes to spawn new threads directly*/ #include "statstd.hpp" #include <hpx/include/threadmanager.hpp> #include <hpx/util/lightweight_test.hpp> #include <boost/assign/std/vector.hpp> #include <boost/lexical_cast.hpp> //just an empty function to assign to the thread void void_thread(){ } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //this runs a series of tests for a packaged_action.apply() void run_tests(uint64_t); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //still required to run hpx int hpx_main(variables_map& vm){ uint64_t num = vm["number-spawned"].as<uint64_t>(); csv = (vm.count("csv") ? true : false); run_tests(num); return hpx::finalize(); } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]){ // Configure application-specific options. options_description desc_commandline("usage: " HPX_APPLICATION_STRING " [options]"); desc_commandline.add_options() ("number-spawned,N", boost::program_options::value<uint64_t>() ->default_value(50000), "number of created and joined") ("csv", "output results as csv " "(format:count,mean,accurate mean,variance,min,max)"); // Initialize and run HPX outname = argv[0]; return hpx::init(desc_commandline, argc, argv); } /////////////////////////////////////////////////////////////////////////////// //measure how long it takes to spawn threads with a simple argumentless function void run_tests(uint64_t num){ uint64_t i = 0; double ot = timer_overhead(num); double mean1; string message = "Measuring time required to spawn threads:"; vector<double> time; vector<hpx::thread> threads; threads.reserve(2*num); //first measure the average time it takes to spawn threads high_resolution_timer t; for(; i < num; ++i) threads.push_back(hpx::thread(&void_thread)); mean1 = t.elapsed()/num; //now retrieve the statistical sampling of this time time.reserve(num); for(i = 0; i < num; i++){ high_resolution_timer t1; threads.push_back(hpx::thread(&void_thread)); time.push_back(t1.elapsed()); } printout(time, ot, mean1, message); //ensure all created threads have joined or else we will not be able to safely //exit the program for(i = 0; i < num; ++i) threads[i].join(); for(i = num; i < num+num; ++i) threads[i].join(); }
33.579545
82
0.554315
vamatya
7e314be72e15b42eb5bf81a4f947791aeed1a9ab
2,040
cpp
C++
src/net/LwipOutputQueue.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
null
null
null
src/net/LwipOutputQueue.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
null
null
null
src/net/LwipOutputQueue.cpp
jnmeurisse/FortiRDP
53f48413c8a292304de27468b271847534353c61
[ "Apache-2.0" ]
1
2022-02-19T19:47:43.000Z
2022-02-19T19:47:43.000Z
/*! * This file is part of FortiRDP * * Copyright (C) 2022 Jean-Noel Meurisse * SPDX-License-Identifier: Apache-2.0 * */ #include <algorithm> #include "net/LwipOutputQueue.h" namespace net { using namespace tools; LwipOutputQueue::LwipOutputQueue(int capacity): OutputQueue(capacity), _logger(Logger::get_logger()) { DEBUG_CTOR(_logger, "LwipOutputQueue"); } LwipOutputQueue::~LwipOutputQueue() { DEBUG_DTOR(_logger, "LwipOutputQueue"); } lwip_err LwipOutputQueue::write(::tcp_pcb* socket, size_t& written) { if (_logger->is_trace_enabled()) _logger->trace( ".... %x enter LwipOutputQueue::write tcp=%x", this, socket); int rc = 0; written = 0; while (!empty()) { PBufChain* const pbuf = front(); // Compute the length of the next chunk of data. The length of // a chunk is always less than 64 Kb, we can cast to an unsigned 16 Bits // integer. uint16_t available = static_cast<u16_t>(pbuf->cend() - pbuf->cbegin()); // Determine how many bytes we can effectively send uint16_t len = min(tcp_sndbuf(socket), available); // stop writing if no more space available if (len == 0) break; // is this pbuf exhausted ? u8_t flags = TCP_WRITE_FLAG_COPY | ((available > len) ? TCP_WRITE_FLAG_MORE : 0); // send rc = tcp_write(socket, pbuf->cbegin(), len, flags); if (rc) goto write_error; // report the number of sent bytes. written += len; // move our pointer into the payload if bytes have been sent pbuf->move(len); // unlink the first chain if no more data if (pbuf->empty()) { pop_front(); delete pbuf; } } if (written > 0) { rc = tcp_output(socket); if (rc) goto write_error; } write_error: if (_logger->is_trace_enabled()) _logger->trace( ".... %x leave LwipOutputQueue::write tcp=%x rc=%d written=%d", this, socket, rc, written); if (rc == ERR_IF) // The output buffer was full, we will try to send the pbuf chain later rc = ERR_OK; return rc; } }
21.030928
84
0.647059
jnmeurisse
cce3401856453e5ad64f0c61acf95e1c3f2e7067
1,339
hpp
C++
challenges/c0005/challenge.hpp
cdalvaro/project-euler
7a09b06a0034ab555706214017ac2e6e3f019806
[ "MIT" ]
null
null
null
challenges/c0005/challenge.hpp
cdalvaro/project-euler
7a09b06a0034ab555706214017ac2e6e3f019806
[ "MIT" ]
18
2021-02-27T16:42:33.000Z
2022-02-12T11:40:40.000Z
challenges/c0005/challenge.hpp
cdalvaro/project-euler
7a09b06a0034ab555706214017ac2e6e3f019806
[ "MIT" ]
1
2021-02-22T13:08:13.000Z
2021-02-22T13:08:13.000Z
// // challenge.hpp // Challenges // // Created by Carlos David on 11/06/2020. // Copyright © 2020 cdalvaro. All rights reserved. // #ifndef challenges_c0005_challenge_hpp #define challenges_c0005_challenge_hpp #include "challenges/ichallenge.hpp" namespace challenges { /** @class Challenge5 @brief This class is intended to solve Challenge 5 @link https://projecteuler.net/problem=5 @endlink */ class Challenge5 : virtual public IChallenge { public: //! @copydoc IChallenge::Type_t using Type_t = size_t; /** @brief Class constructor This is the main constructor of Challenge5 class @param last_number The las number starting from 1 to be divisible without remainder */ Challenge5(const Type_t &last_number); /** @brief Default constructor */ virtual ~Challenge5() = default; /** This method contains the algorithm that solves challenge 5 @return The solution for challenge 5 */ std::any solve() override final; private: Type_t last_number; /**< The las number starting from 1 to be divisible without remainder */ }; } // namespace challenges #endif /* challenges_c0005_challenge_hpp */
23.910714
79
0.625093
cdalvaro
cce4ba72a191d9307a795629a1381f53b5e47067
3,611
cpp
C++
SynchronisationServer/src/mainapp.cpp
FilmakademieRnd/v-p-e-t
d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b
[ "MIT" ]
62
2016-10-12T17:29:37.000Z
2022-02-27T01:24:48.000Z
SynchronisationServer/src/mainapp.cpp
FilmakademieRnd/v-p-e-t
d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b
[ "MIT" ]
75
2017-01-05T12:02:43.000Z
2021-04-06T19:07:50.000Z
SynchronisationServer/src/mainapp.cpp
FilmakademieRnd/v-p-e-t
d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b
[ "MIT" ]
16
2016-10-12T17:29:42.000Z
2021-12-01T17:27:33.000Z
/* ----------------------------------------------------------------------------- This source file is part of VPET - Virtual Production Editing Tool http://vpet.research.animationsinstitut.de/ http://github.com/FilmakademieRnd/VPET Copyright (c) 2018 Filmakademie Baden-Wuerttemberg, Animationsinstitut R&D Lab This project has been initiated in the scope of the EU funded project Dreamspace under grant agreement no 610005 in the years 2014, 2015 and 2016. http://dreamspaceproject.eu/ Post Dreamspace the project has been further developed on behalf of the research and development activities of Animationsinstitut. The VPET components Scene Distribution and Synchronization Server are intended for research and development purposes only. Commercial use of any kind is not permitted. There is no support by Filmakademie. Since the Scene Distribution and Synchronization Server are available for free, Filmakademie shall only be liable for intent and gross negligence; warranty is limited to malice. Scene Distribution and Synchronization Server may under no circumstances be used for racist, sexual or any illegal purposes. In all non-commercial productions, scientific publications, prototypical non-commercial software tools, etc. using the Scene Distribution and/or Synchronization Server Filmakademie has to be named as follows: “VPET-Virtual Production Editing Tool by Filmakademie Baden-Württemberg, Animationsinstitut (http://research.animationsinstitut.de)“. In case a company or individual would like to use the Scene Distribution and/or Synchronization Server in a commercial surrounding or for commercial purposes, software based on these components or any part thereof, the company/individual will have to contact Filmakademie (research<at>filmakademie.de). ----------------------------------------------------------------------------- */ #include "mainapp.h" MainApp::MainApp(QString ownIP, QString ncamIP, QString ncamPort, bool debug) { context_ = new zmq::context_t(1); ownIP_ = ownIP; ncamIP_ = ncamIP; ncamPort_ = ncamPort; debug_ = debug; isRecording = false; } void MainApp::run() { //create Thread to receive zeroMQ messages from tablets QThread* zeroMQHandlerThread = new QThread(); ZeroMQHandler* zeroMQHandler = new ZeroMQHandler(ownIP_, debug_ , context_); zeroMQHandler->moveToThread(zeroMQHandlerThread); QObject::connect( zeroMQHandlerThread, SIGNAL(started()), zeroMQHandler, SLOT(run())); zeroMQHandlerThread->start(); zeroMQHandler->requestStart(); #ifdef Q_OS_WIN NcamAdapter* ncamAdapter = new NcamAdapter(ncamIP_, ncamPort_, ownIP_, context_); if(ncamIP_ != "" && ncamPort_ != "") { QThread* ncamThread = new QThread(); ncamAdapter->moveToThread(ncamThread); QObject::connect( ncamThread, SIGNAL(started()), ncamAdapter, SLOT(run())); ncamThread->start(); } #endif /* RecordWriter* recordWriter = new RecordWriter( &messagesStorage, &m_mutex ); QThread* writeThread = new QThread(); recordWriter->moveToThread( writeThread ); QObject::connect( writeThread, SIGNAL( started() ), recordWriter, SLOT( run() ) ); writeThread->start(); QThread* recorderThread = new QThread(); TransformationRecorder* transformationRecorder = new TransformationRecorder(ownIP_, context_, &messagesStorage, &m_mutex, ncamAdapter );//, recordWriter); transformationRecorder->moveToThread(recorderThread); QObject::connect( recorderThread, SIGNAL(started()), transformationRecorder, SLOT(run())); recorderThread->start(); */ }
43.506024
158
0.725561
FilmakademieRnd
ccea58bdb68c43bd9734b4a77a0afa626e250990
614
hpp
C++
lab1/1_triangle/triangle/triangle.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
2
2015-10-08T15:07:07.000Z
2017-09-17T10:08:36.000Z
lab1/1_triangle/triangle/triangle.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
lab1/1_triangle/triangle/triangle.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
// (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine #ifndef _TRIANGLE_HPP_ #define _TRIANGLE_HPP_ /*****************************************************************************/ #include "point.hpp" /*****************************************************************************/ class Triangle { /*-----------------------------------------------------------------*/ // ... TODO ... /*------------------------------------------------------------------*/ }; /*****************************************************************************/ #endif // _TRIANGLE_HPP_
21.928571
80
0.218241
zaychenko-sergei
ccef907f0b16ea546b61a842b2c637ee439a8238
330
hpp
C++
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
include/Order.hpp
Xhiel23/Practica_Tienda_cpp
412003c72498f28e67d4b9f41852e3545f82e7ed
[ "MIT" ]
null
null
null
#include "utilities.hpp" #include "Food.hpp" class Order { public: std::vector<Product> products; int orderDay; int orderMonth; int orderYear; int totalProducts; double totalPrice; Order(int orderDay, int orderMonth, int orderYear); Order(); void computeBill(); void printOrders(); };
18.333333
55
0.657576
Xhiel23
ccf1217613402246c262ac1036dbac0d9c1bb5d9
4,019
cpp
C++
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
20
2016-03-28T08:00:28.000Z
2019-07-01T04:23:48.000Z
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
null
null
null
PokerGame/Classes/Hands.cpp
mettoboshi/poker-game
eae81438d55b2f66b768a6519350c4da0935e7c7
[ "MIT" ]
4
2017-03-28T16:11:06.000Z
2019-02-20T17:27:59.000Z
// // Hands.cpp // PokerGame // #include "Hands.hpp" USING_NS_CC; Hands::Hands() {} Hands::~Hands() { for(auto card : this->cards) { CC_SAFE_RELEASE_NULL(card.second->card); CC_SAFE_RELEASE_NULL(card.second); } } bool Hands::init() { return true; } // 手札のn番目にカードをセット void Hands::setCard(int n, Card* card) { CardState* cardState { CardState::create(card, false) }; this->cards.insert(n, cardState); } // 手札のn番目のカードを取得 Card* Hands::getCard(int n) const { return this->cards.at(n)->card; } // HOLD状態を切り替える bool Hands::toggleHold(int n) { bool hold { false }; this->cards.at(n)->hold?hold = false:hold = true; return this->cards.at(n)->hold = hold; } // HOLD状態を取得 bool Hands::isHold(int n) const { return this->cards.at(n)->hold; } // 役の判定 void Hands::dicisionHand() { // フラッシュ bool isFlush = false; Suit firstSuit { this->getCard(0)->getSuit() }; if (firstSuit == this->getCard(1)->getSuit() && firstSuit == this->getCard(2)->getSuit() && firstSuit == this->getCard(3)->getSuit() && firstSuit == this->getCard(4)->getSuit()) { isFlush = true; } // カードの数字を変数にいれる std::vector<int> numbers {}; for (int i { 0 }; i < HANDS_MAX; i++) { numbers.push_back(this->getCard(i)->getNumber()); } // ソート std::sort(numbers.begin(), numbers.end()); // ロイヤル・ストレート bool isRoyal = false; if (numbers.at(0) == 1 && numbers.at(1) == 10 && numbers.at(2) == 11 && numbers.at(3) == 12 && numbers.at(4) == 13) { isRoyal = true; } // ストレート bool isStraight = false; int firstNumber { numbers.at(0) }; if (numbers.at(1) == (firstNumber + 1) && numbers.at(2) == (firstNumber + 2) && numbers.at(3) == (firstNumber + 3) && numbers.at(4) == (firstNumber + 4)) { isStraight = true; } // ペア系の判定 // ペアの数のカウント用 int pearCount = 0; // ジャックス・オア・ベター bool isJacks = false; // スリーカード bool is3card = false; // フォーカード bool is4card = false; // トランプの数字についてそれぞれ調査する for(int no { 1 }; no <= 13; no++){ // 手札に数字が何枚含まれているかを数える int count = 0; for(int i { 0 }; i < HANDS_MAX; i++){ // 調査対象の数字ならカウント if(numbers.at(i) == no){ count++; } } // 枚数に応じて、ペアのカウントを計算 switch(count) { case 2: { // ペアの場合はカウント pearCount++; if(no > 10 || no == 1){ // J Q K A の場合は、ジャックス・オア・ベター isJacks = true; } break; } case 3: { // スリーカード is3card = true; break; } case 4: { // フォーカード is4card = true; break; } } } // ツーペア bool is2pear = false; if(pearCount == 2){ is2pear = true; } // 判定 this->hand = Hand::NOTHING; if(isRoyal && isFlush) { this->hand = Hand::ROYAL_STRAIGHT_FLUSH; } else if(isStraight && isFlush) { this->hand = Hand::STRAIGHT_FLUSH; } else if(is4card) { this->hand = Hand::FOUR_OF_A_KIND; } else if(is3card && pearCount > 0) { this->hand = Hand::FULL_HOUSE; } else if(isFlush) { this->hand = Hand::FLUSH; } else if(isRoyal || isStraight) { this->hand = Hand::STRAIGHT; } else if(is3card) { this->hand = Hand::THREE_OF_A_KIND; } else if(pearCount == 2) { this->hand = Hand::TWOPAIR; } else if(isJacks) { this->hand = Hand::JACKS_OR_BETTER; } } // 役の取得 Hand Hands::getHand() const { return this->hand; } // 配当の取得 int Hands::getRate() const { return Rate.at(this->hand); }
19.509709
60
0.485195
mettoboshi
ccf40d824395a01575342a23d6a985a49c672275
24,565
cpp
C++
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
1
2016-07-20T18:43:34.000Z
2016-07-20T18:43:34.000Z
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
4
2016-08-30T05:29:18.000Z
2016-11-07T04:02:15.000Z
libs/win/winexec.cpp
gknowles/dimapp
daadd9afe5fb1a6f716c431411e20c48ca180f9f
[ "BSL-1.0" ]
1
2017-10-20T22:31:17.000Z
2017-10-20T22:31:17.000Z
// Copyright Glen Knowles 2019 - 2021. // Distributed under the Boost Software License, Version 1.0. // // winres.cpp - dim windows platform #include "pch.h" #pragma hdrstop using namespace std; using namespace Dim; /**************************************************************************** * * Declarations * ***/ namespace Dim { class ExecProgram : public ListLink<> , public ITimerNotify { public: class ExecPipe : public IPipeNotify { public: // Inherited via IPipeNotify bool onPipeAccept() override; bool onPipeRead(size_t * bytesUsed, string_view data) override; void onPipeDisconnect() override; void onPipeBufferChanged(const PipeBufferInfo & info) override; ExecProgram * m_notify = {}; StdStream m_strm = {}; RunMode m_mode = kRunStopped; HANDLE m_child = {}; }; public: static void write(IExecNotify * notify, std::string_view data); static void dequeue(); public: ExecProgram( IExecNotify * notify, string_view cmdline, const ExecOptions & opts ); ~ExecProgram(); void exec(); TaskQueueHandle queue() const { return m_hq; } void terminate(); void postJobExit(); bool onAccept(StdStream strm); bool onRead(size_t * bytesUsed, StdStream strm, string_view data); void onDisconnect(StdStream strm); void onBufferChanged(StdStream strm, const PipeBufferInfo & info); void onJobExit(); // Inherited via ITimerNotify Duration onTimer(TimePoint now) override; private: bool createPipe( HANDLE * hchild, StdStream strm, string_view name, Pipe::OpenMode oflags ); bool completeIfDone_LK(); TaskQueueHandle m_hq; HANDLE m_job = NULL; HANDLE m_process = NULL; HANDLE m_thread = NULL; string m_cmdline; ExecOptions m_opts; //----------------------------------------------------------------------- mutex m_mut; IExecNotify * m_notify{}; ExecPipe m_pipes[3]; unsigned m_connected{}; RunMode m_mode{kRunStopped}; bool m_canceled = true; int m_exitCode = -1; }; } // namespace /**************************************************************************** * * Variables * ***/ static auto & s_perfTotal = uperf("exec.programs"); static auto & s_perfIncomplete = uperf("exec.programs (incomplete)"); static auto & s_perfWaiting = uperf("exec.programs (waiting)"); static mutex s_mut; static HANDLE s_iocp; static List<ExecProgram> s_programs; /**************************************************************************** * * IOCP completion thread * ***/ //=========================================================================== static void jobObjectIocpThread() { const int kMaxEntries = 8; OVERLAPPED_ENTRY entries[kMaxEntries]; ULONG found; for (;;) { if (!GetQueuedCompletionStatusEx( s_iocp, entries, (ULONG) size(entries), &found, INFINITE, // timeout false // alertable )) { WinError err; if (err == ERROR_ABANDONED_WAIT_0) { // Completion port closed while inside get status. break; } else if (err == ERROR_INVALID_HANDLE) { // Completion port closed before call to get status. break; } else { logMsgFatal() << "GetQueuedCompletionStatusEx(JobPort): " << err; } } for (unsigned i = 0; i < found; ++i) { auto exe = reinterpret_cast<ExecProgram *>( entries[i].lpCompletionKey ); DWORD msg = entries[i].dwNumberOfBytesTransferred; [[maybe_unused]] DWORD procId = (DWORD) (uintptr_t) entries[i].lpOverlapped; if (msg == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO) { // The process, and any child processes it may have launched, // have exited. taskPush(exe->queue(), [=](){ exe->onJobExit(); }); } } } scoped_lock lk{s_mut}; s_iocp = 0; } //=========================================================================== static HANDLE iocpHandle() { scoped_lock lk(s_mut); if (s_iocp) return s_iocp; s_iocp = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, // existing port NULL, // completion key 0 // concurrent threads, 0 for default ); if (!s_iocp) logMsgFatal() << "CreateIoCompletionPort(null): " << WinError{}; // Start IOCP dispatch task taskPushOnce("JobObject Dispatch", jobObjectIocpThread); return s_iocp; } /**************************************************************************** * * ExecProgram::ExecPipe * ***/ //=========================================================================== bool ExecProgram::ExecPipe::onPipeAccept() { return m_notify->onAccept(m_strm); } //=========================================================================== bool ExecProgram::ExecPipe::onPipeRead( size_t * bytesUsed, std::string_view data ) { return m_notify->onRead(bytesUsed, m_strm, data); } //=========================================================================== void ExecProgram::ExecPipe::onPipeDisconnect() { m_notify->onDisconnect(m_strm); } //=========================================================================== void ExecProgram::ExecPipe::onPipeBufferChanged(const PipeBufferInfo & info) { m_notify->onBufferChanged(m_strm, info); } /**************************************************************************** * * ExecProgram * ***/ //=========================================================================== // static void ExecProgram::write(IExecNotify * notify, string_view data) { if (notify->m_exec) pipeWrite(&notify->m_exec->m_pipes[kStdIn], data); } //=========================================================================== // static void ExecProgram::dequeue() { List<ExecProgram> progs; { scoped_lock lk{s_mut}; while (auto prog = s_programs.front()) { if (prog->m_opts.concurrency <= s_perfIncomplete) break; s_perfWaiting -= 1; s_perfIncomplete += 1; progs.link(prog); } } while (auto prog = progs.front()) { prog->unlink(); prog->exec(); } } //=========================================================================== ExecProgram::ExecProgram( IExecNotify * notify, string_view cmdline, const ExecOptions & opts ) : m_notify(notify) , m_cmdline(cmdline) , m_opts(opts) { s_perfTotal += 1; s_perfWaiting += 1; m_notify->m_exec = this; if (m_opts.concurrency == 0) m_opts.concurrency = envProcessors(); for (auto && e : { kStdIn, kStdOut, kStdErr }) { m_pipes[e].m_strm = e; m_pipes[e].m_notify = this; } scoped_lock lk{s_mut}; s_programs.link(this); } //=========================================================================== ExecProgram::~ExecProgram() { assert(!m_notify); for ([[maybe_unused]] auto && pi : m_pipes) assert(pi.m_mode == kRunStopped); if (linked()) { s_perfWaiting -= 1; } else { s_perfIncomplete -= 1; } } //=========================================================================== void ExecProgram::terminate() { unique_lock lk(m_mut); if (m_mode == kRunStopped || !m_process) return; if (!TerminateProcess(m_process, (UINT) -1)) { logMsgError() << "TerminateProcess(" << m_cmdline << "): " << WinError{}; } CloseHandle(m_process); // Set to null handle so the process will be recognized as canceled. m_process = {}; } //=========================================================================== void ExecProgram::postJobExit() { // Exit events are posted to the job queue so the onExecComplete event gets // routed to the task queue selected by the application. if (!PostQueuedCompletionStatus( s_iocp, JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO, (uintptr_t) this, (OVERLAPPED *) (uintptr_t) GetProcessId(m_process) )) { logMsgFatal() << "PostQueuedCompletionStatus: " << WinError{}; } } //=========================================================================== void ExecProgram::exec() { // Now that we're committed to getting an onJobExit() call, change mode // so that we'll wait for it. m_mode = kRunStarting; m_hq = m_opts.hq; // Create pipes char rawname[100]; snprintf( rawname, sizeof rawname, "//./pipe/local/%u_%p", envProcessId(), this ); string name = rawname; struct { StdStream strm; string name; Pipe::OpenMode oflags; } pipes[] = { { kStdIn, name + ".in", Pipe::fReadWrite }, { kStdOut, name + ".out", Pipe::fReadOnly }, { kStdErr, name + ".err", Pipe::fReadOnly }, }; // First set all pipes to kRunStarting (not kRunStopped), so that the // following transition to stopped can be unambiguously detected. for (auto&& p : pipes) m_pipes[p.strm].m_mode = kRunStarting; for (auto && p : pipes) { auto & child = m_pipes[p.strm].m_child; if (!createPipe(&child, p.strm, p.name, p.oflags)) { postJobExit(); return; } } } //=========================================================================== bool ExecProgram::onAccept(StdStream strm) { unique_lock lk(m_mut); assert(m_mode == kRunStarting); assert(m_pipes[strm].m_mode == kRunStarting); m_pipes[strm].m_mode = kRunRunning; if (m_pipes[kStdIn].m_mode == kRunStarting || m_pipes[kStdOut].m_mode == kRunStarting || m_pipes[kStdErr].m_mode == kRunStarting ) { // If it wasn't the last pipe to finish starting, continue waiting for // the last one. return true; } // Now that all pipes have started, check to make sure all are running, and // stop the whole exec if they aren't. if (m_pipes[kStdIn].m_mode != kRunRunning || m_pipes[kStdOut].m_mode != kRunRunning || m_pipes[kStdErr].m_mode != kRunRunning ) { lk.unlock(); postJobExit(); return true; } bool success = false; for (;;) { m_job = CreateJobObject(NULL, NULL); if (!m_job) { logMsgError() << "CreateJobObjectW()" << WinError{}; break; } JOBOBJECT_EXTENDED_LIMIT_INFORMATION ei = {}; auto & bi = ei.BasicLimitInformation; bi.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject( m_job, JobObjectExtendedLimitInformation, &ei, sizeof ei )) { logMsgError() << "SetInformationJobObject(KILL_ON_JOB_CLOSE): " << WinError{}; break; } JOBOBJECT_ASSOCIATE_COMPLETION_PORT ap = {}; ap.CompletionKey = this; ap.CompletionPort = iocpHandle(); if (!SetInformationJobObject( m_job, JobObjectAssociateCompletionPortInformation, &ap, sizeof ap )) { logMsgError() << "SetInformationJobObject(ASSOC_IOCP): " << WinError{}; break; } success = true; break; } if (!success) { lk.unlock(); postJobExit(); return true; } char * envBlk = nullptr; string envBuf; if (!m_opts.envVars.empty()) { auto env = envGetVars(); for (auto&& [name, value] : m_opts.envVars) { if (value.empty()) { env.erase(name); } else { env[name] = value; } } for (auto&& [name, value] : env) { envBuf += name; envBuf += '='; envBuf += value; envBuf += '\0'; } envBuf += '\0'; envBlk = envBuf.data(); } auto wcmdline = toWstring(m_cmdline); auto wworkDir = toWstring(m_opts.workingDir); STARTUPINFOW si = { sizeof si }; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = m_pipes[kStdIn].m_child; si.hStdOutput = m_pipes[kStdOut].m_child; si.hStdError = m_pipes[kStdErr].m_child; PROCESS_INFORMATION pi = {}; bool running = CreateProcessW( NULL, // explicit application name (no search path) wcmdline.data(), NULL, // process attrs NULL, // thread attrs true, // inherit handles, true to inherit the pipe handles CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDED, envBlk, wworkDir.empty() ? NULL : wworkDir.c_str(), // current dir &si, &pi ); WinError err; // Close parents reference to child side of pipes. for (auto && pipe : m_pipes) { CloseHandle(pipe.m_child); pipe.m_child = {}; } if (!running) { logMsgError() << "CreateProcessW(" << m_cmdline << "): " << err; lk.unlock(); postJobExit(); return true; } m_process = pi.hProcess; m_thread = pi.hThread; if (!AssignProcessToJobObject(m_job, m_process)) { logMsgError() << "AssignProcessToJobObject(" << m_cmdline << "): " << WinError{}; lk.unlock(); terminate(); postJobExit(); return true; } // Now that the process has been assigned to the job it can be resumed. // If it had launched a process before joining the job that child would // be untracked. m_mode = kRunRunning; ResumeThread(m_thread); CloseHandle(m_thread); // Start the allowed execution time countdown. timerUpdate(this, m_opts.timeout); auto pipe = &m_pipes[kStdIn]; if (!m_opts.stdinData.empty()) { // if !enableExecWrite the pipe will be closed when this write // completes. pipeWrite(pipe, m_opts.stdinData); } else if (!m_opts.enableExecWrite) { pipeClose(pipe); } return true; } //=========================================================================== bool ExecProgram::onRead( size_t * bytesUsed, StdStream strm, string_view data ) { return m_notify->onExecRead(bytesUsed, strm, data); } //=========================================================================== void ExecProgram::onDisconnect(StdStream strm) { unique_lock lk(m_mut); auto & pi = m_pipes[strm]; pi.m_mode = kRunStopped; if (completeIfDone_LK()) lk.release(); } //=========================================================================== void ExecProgram::onBufferChanged( StdStream strm, const PipeBufferInfo & info ) { if (strm == kStdIn && !m_opts.enableExecWrite && !info.incomplete) pipeClose(&m_pipes[strm]); } //=========================================================================== Duration ExecProgram::onTimer(TimePoint now) { terminate(); return kTimerInfinite; } //=========================================================================== void ExecProgram::onJobExit() { assert(m_mode != kRunStopped); unique_lock lk(m_mut); for (auto && pi : m_pipes) { pipeClose(&pi); if (pi.m_child) { CloseHandle(pi.m_child); pi.m_child = {}; } } m_mode = kRunStopped; DWORD rc; if (GetExitCodeProcess(m_process, &rc)) { m_canceled = false; m_exitCode = rc; } else { WinError err; m_canceled = true; m_exitCode = -1; } CloseHandle(m_process); CloseHandle(m_job); if (completeIfDone_LK()) lk.release(); } //=========================================================================== bool ExecProgram::completeIfDone_LK() { if (m_pipes[kStdIn].m_mode != kRunStopped || m_pipes[kStdOut].m_mode != kRunStopped || m_pipes[kStdErr].m_mode != kRunStopped || m_mode != kRunStopped ) { return false; } if (m_notify) { m_notify->m_exec = nullptr; m_notify->onExecComplete(m_canceled, m_exitCode); m_notify = nullptr; } m_mut.unlock(); delete this; dequeue(); return true; } //=========================================================================== bool ExecProgram::createPipe( HANDLE * child, StdStream strm, string_view name, Pipe::OpenMode oflags ) { assert(m_pipes[strm].m_mode == kRunStarting); pipeListen(&m_pipes[strm], name, oflags, queue()); if (child) { unsigned flags = SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION; // Child side has read & write reversed from listening parent if (oflags & Pipe::fReadOnly) flags |= GENERIC_WRITE; if (oflags & Pipe::fWriteOnly) flags |= GENERIC_READ; if (oflags & Pipe::fReadWrite) flags |= GENERIC_READ | GENERIC_WRITE; auto wname = toWstring(name); SECURITY_ATTRIBUTES sa = {}; sa.bInheritHandle = true; auto cp = CreateFileW( wname.c_str(), flags, 0, // share &sa, OPEN_EXISTING, 0, // attributes and flags NULL // template file ); if (cp == INVALID_HANDLE_VALUE) { logMsgError() << "CreateFile(pipe): " << WinError{}; return false; } *child = cp; } return true; } /**************************************************************************** * * IExecNotify * ***/ //=========================================================================== bool IExecNotify::onExecRead( size_t * bytesUsed, StdStream strm, string_view data ) { switch (strm) { case kStdIn: break; case kStdOut: m_out.append(data); break; case kStdErr: m_err.append(data); break; } *bytesUsed = data.size(); return true; } /**************************************************************************** * * Execute child program * ***/ //=========================================================================== void Dim::execProgram( IExecNotify * notify, const std::string & cmdline, const ExecOptions & rawOpts ) { assert(notify); auto opts = rawOpts; if (!opts.hq) opts.hq = taskEventQueue(); new ExecProgram(notify, cmdline, opts); ExecProgram::dequeue(); } //=========================================================================== void Dim::execProgram( IExecNotify * notify, const std::vector<std::string> & args, const ExecOptions & opts ) { execProgram(notify, Cli::toCmdline(args), opts); } //=========================================================================== void Dim::execWrite(IExecNotify * notify, std::string_view data) { ExecProgram::write(notify, data); } /**************************************************************************** * * Simple execute child program * ***/ namespace { struct SimpleExecNotify : public IExecNotify { function<void(ExecResult && res)> m_fn; ExecResult m_res; void onExecComplete(bool canceled, int exitCode) override; }; } // namespace //=========================================================================== void SimpleExecNotify::onExecComplete(bool canceled, int exitCode) { m_res.exitCode = exitCode; m_res.out = move(m_out); m_res.err = move(m_err); m_fn(move(m_res)); delete this; } //=========================================================================== void Dim::execProgram( function<void(ExecResult && res)> fn, const string & cmdline, const ExecOptions & opts ) { auto notify = new SimpleExecNotify; notify->m_fn = fn; notify->m_res.cmdline = cmdline; execProgram(notify, cmdline, opts); } //=========================================================================== void Dim::execProgram( function<void(ExecResult && res)> fn, const vector<string> & args, const ExecOptions & opts ) { execProgram(fn, Cli::toCmdline(args), opts); } /**************************************************************************** * * Execute child program and wait * ***/ //=========================================================================== bool Dim::execProgramWait( ExecResult * out, const string & cmdline, const ExecOptions & rawOpts ) { auto opts = rawOpts; if (!opts.hq) opts.hq = taskInEventThread() ? taskComputeQueue() : taskEventQueue(); mutex mut; condition_variable cv; out->cmdline = cmdline; bool complete = false; execProgram( [&](ExecResult && res) { { scoped_lock lk{mut}; *out = move(res); complete = true; } cv.notify_one(); }, cmdline, opts ); unique_lock lk{mut}; while (!complete) cv.wait(lk); return out->exitCode != -1; } //=========================================================================== bool Dim::execProgramWait( ExecResult * res, const vector<string> & args, const ExecOptions & opts ) { return execProgramWait(res, Cli::toCmdline(args), opts); } /**************************************************************************** * * Elevated * ***/ //=========================================================================== bool Dim::execElevatedWait( int * exitCode, const string & cmdline, const string & workingDir ) { SHELLEXECUTEINFOW ei = { sizeof ei }; ei.lpVerb = L"RunAs"; auto args = Cli::toArgv(string(cmdline)); auto wexe = toWstring(args.empty() ? "" : args[0]); ei.lpFile = wexe.c_str(); auto wargs = toWstring(cmdline); ei.lpParameters = wargs.c_str(); auto wdir = toWstring(workingDir); if (wdir.size()) ei.lpDirectory = wdir.c_str(); ei.fMask = SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI ; ei.nShow = SW_HIDE; if (!ShellExecuteExW(&ei)) { WinError err; if (err == ERROR_CANCELLED) { logMsgError() << "Operation canceled."; } else { logMsgError() << "ShellExecuteExW: " << WinError(); } *exitCode = -1; return false; } if (!ei.hProcess) { *exitCode = EX_OK; } else { DWORD rc = EX_OSERR; if (WAIT_OBJECT_0 == WaitForSingleObject(ei.hProcess, INFINITE)) GetExitCodeProcess(ei.hProcess, &rc); *exitCode = rc; CloseHandle(ei.hProcess); } return true; } /**************************************************************************** * * External * ***/ //=========================================================================== void Dim::execCancelWaiting() { List<ExecProgram> progs; { scoped_lock lk{s_mut}; progs.link(move(s_programs)); } while (auto prog = progs.front()) { s_programs.unlink(prog); prog->onJobExit(); } } /**************************************************************************** * * Shutdown monitor * ***/ namespace { class ShutdownNotify : public IShutdownNotify { void onShutdownServer(bool firstTry) override; void onShutdownConsole(bool firstTry) override; }; } // namespace static ShutdownNotify s_cleanup; //=========================================================================== void ShutdownNotify::onShutdownServer(bool firstTry) { if (s_perfIncomplete || s_perfWaiting) return shutdownIncomplete(); } //=========================================================================== void ShutdownNotify::onShutdownConsole(bool firstTry) { scoped_lock lk(s_mut); if (firstTry && s_iocp) { auto h = s_iocp; s_iocp = INVALID_HANDLE_VALUE; if (!CloseHandle(h)) logMsgError() << "CloseHandle(IOCP): " << WinError{}; Sleep(0); } if (s_iocp) shutdownIncomplete(); } /**************************************************************************** * * Internal API * ***/ //=========================================================================== void Dim::winExecInitialize() { shutdownMonitor(&s_cleanup); }
26.876368
79
0.495095
gknowles
6901773a79e7819829a285391bbdc7d7c0feaf79
2,546
cc
C++
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
backends/npu/kernels/cast_kernel.cc
Aganlengzi/PaddleCustomDevice
0aa0d2e1b2e5db556777604e6fe851a7d0697456
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "kernels/funcs/npu_funcs.h" #include "kernels/funcs/npu_op_runner.h" #include "paddle/phi/core/tensor_meta.h" namespace custom_kernel { template <typename T, typename Context> void CastKernel(const Context& dev_ctx, const phi::DenseTensor& x, phi::DenseTensorMeta::DataType dtype, phi::DenseTensor* out) { if (x.dtype() == dtype) { dev_ctx.template Alloc<T>(out); TensorCopy(dev_ctx, x, false, out); return; } int aclDtype = ConvertToNpuDtype(dtype); if (dtype == phi::DenseTensorMeta::DataType::FLOAT32) { dev_ctx.template Alloc<float>(out); } else if (dtype == phi::DenseTensorMeta::DataType::FLOAT64) { dev_ctx.template Alloc<double>(out); } else if (dtype == phi::DenseTensorMeta::DataType::FLOAT16) { dev_ctx.template Alloc<phi::dtype::float16>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT16) { dev_ctx.template Alloc<int16_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT32) { dev_ctx.template Alloc<int32_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::INT64) { dev_ctx.template Alloc<int64_t>(out); } else if (dtype == phi::DenseTensorMeta::DataType::BOOL) { dev_ctx.template Alloc<bool>(out); } aclrtStream stream = static_cast<aclrtStream>(dev_ctx.stream()); const auto& runner = NpuOpRunner( "Cast", {x}, {*out}, {{"dst_type", static_cast<int32_t>(aclDtype)}}); runner.Run(stream); } } // namespace custom_kernel PD_REGISTER_PLUGIN_KERNEL(cast, ascend, ALL_LAYOUT, custom_kernel::CastKernel, phi::dtype::float16, float, double, int16_t, int32_t, int64_t, bool) {}
35.859155
75
0.628437
Aganlengzi
6902fa66817a82195c3b78aac8867e849e1a6533
227
cpp
C++
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
verify/verify-yosupo-string/yosupo-z-algorithm.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#define PROBLEM "https://judge.yosupo.jp/problem/zalgorithm" // #include "../../template/template.hpp" // #include "../../string/z-algorithm.hpp" using namespace Nyaan; void Nyaan::solve() { ins(s); out(z_algorithm(s)); }
18.916667
60
0.669604
NachiaVivias
690ab434cbe96c481358662fbc419dc351a1d613
36,549
cpp
C++
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
6
2015-06-29T16:59:17.000Z
2017-12-14T13:50:36.000Z
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
null
null
null
hgpucl/hgpucl_devices.cpp
vadimdi/PRNGCL
e935c9139066a5384ef150de4a54716fc1c24b7b
[ "BSD-2-Clause" ]
3
2015-03-26T15:08:52.000Z
2020-01-07T06:11:29.000Z
/****************************************************************************** * @file hgpucl_devices.cpp * @author Vadim Demchik <[email protected]> * @version 1.0.2 * * @brief [HGPU library] * Interface for OpenCL AMD APP & nVidia SDK environment * devices submodule * * * @section LICENSE * * Copyright (c) 2013-2015 Vadim Demchik * 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. * * 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 "hgpucl_devices.h" // new OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_new(unsigned int number_of_devices){ if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); if (number_of_devices>HGPU_GPU_MAX_DEVICES) HGPU_GPU_error_message(HGPU_ERROR_NO_MEMORY,"exceed maximal number of descriptions for devices"); HGPU_GPU_devices* result = (HGPU_GPU_devices*) calloc(1,sizeof(HGPU_GPU_devices)); result->devices = (cl_device_id*) calloc(number_of_devices,sizeof(cl_device_id)); result->number_of_devices = number_of_devices; return result; } // new OpenCL devices empty devices HGPU_GPU_devices* HGPU_GPU_devices_new_empty(void){ HGPU_GPU_devices* result = (HGPU_GPU_devices*) calloc(1,sizeof(HGPU_GPU_devices)); result->devices = NULL; result->number_of_devices = 0; return result; } // delete OpenCL devices void HGPU_GPU_devices_delete(HGPU_GPU_devices** devices){ if (!(*devices)) return; free((*devices)->devices); free(*devices); (*devices) = NULL; } // clone OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_clone(HGPU_GPU_devices* devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); size_t bytes = number_of_devices * sizeof(cl_device_id); memcpy_s(result->devices,bytes,devices->devices,bytes); return result; } // copy OpenCL devices void HGPU_GPU_devices_copy(HGPU_GPU_devices** devices_destination,HGPU_GPU_devices* devices_source){ HGPU_GPU_devices_delete(devices_destination); (*devices_destination) = HGPU_GPU_devices_clone(devices_source); } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get(void){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_platforms_delete(&platforms); return result; } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get_on_platforms(HGPU_GPU_platforms* platforms){ unsigned int number_of_devices = HGPU_GPU_devices_get_number_on_platforms(platforms); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); unsigned int device_index = 0; for (unsigned int i=0; i<HGPU_GPU_platforms_get_number(platforms); i++){ unsigned int number_of_devices_on_platform = HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); if (number_of_devices_on_platform){ HGPU_GPU_devices* devices_on_platform = HGPU_GPU_devices_get_on_platform(platforms->platforms[device_index]); for (unsigned int j=0; j<number_of_devices_on_platform; j++) result->devices[device_index++] = devices_on_platform->devices[j]; HGPU_GPU_devices_delete(&devices_on_platform); } } return result; } // get all OpenCL devices HGPU_GPU_devices* HGPU_GPU_devices_get_on_platform(cl_platform_id platform){ cl_uint number_of_devices = HGPU_GPU_devices_get_number_on_platform(platform); HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices); HGPU_GPU_error_message(clGetDeviceIDs(platform,CL_DEVICE_TYPE_ALL,number_of_devices, result->devices, &result->number_of_devices),"clGetDeviceIDs failed"); if(!result->number_of_devices) HGPU_GPU_error_message(HGPU_ERROR_NO_PLATFORM,"there are no any available OpenCL devices"); return result; } // get OpenCL devices by vendor HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor(HGPU_GPU_vendor vendor){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } // get OpenCL devices by vendor on platform HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor_on_platform(cl_platform_id platform,HGPU_GPU_vendor vendor){ HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platform(platform); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } // get OpenCL devices by vendor on platforms HGPU_GPU_devices* HGPU_GPU_devices_get_by_vendor_on_platforms(HGPU_GPU_platforms* platforms,HGPU_GPU_vendor vendor){ HGPU_GPU_devices* result = HGPU_GPU_devices_get_on_platforms(platforms); HGPU_GPU_devices_select_by_vendor(&result,vendor); return result; } //get max OpenCL version of devices on platforms HGPU_GPU_version HGPU_GPU_devices_get_version_max(HGPU_GPU_devices* devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); HGPU_GPU_version version = HGPU_GPU_device_get_version(devices->devices[0]); for (unsigned int i=1; i<number_of_devices; i++) version = HGPU_GPU_version_max(version,HGPU_GPU_device_get_version(devices->devices[i])); return version; } // get number of OpenCL devices unsigned int HGPU_GPU_devices_get_number(HGPU_GPU_devices* devices){ if (!devices) return 0; return devices->number_of_devices; } // get total number of OpenCL devices unsigned int HGPU_GPU_devices_get_total_number(void){ HGPU_GPU_platforms* platforms = HGPU_GPU_platforms_get(); unsigned int result = 0; for (unsigned int i=0;i<HGPU_GPU_platforms_get_number(platforms);i++) result += HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); HGPU_GPU_platforms_delete(&platforms); return result; } // get number of OpenCL devices unsigned int HGPU_GPU_devices_get_number_on_platform(cl_platform_id platform){ cl_uint number_of_devices = 0; cl_int get_number_of_devices_result = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 0, NULL, &number_of_devices); if (get_number_of_devices_result!=CL_DEVICE_NOT_FOUND) HGPU_GPU_error_message(get_number_of_devices_result, "clGetDeviceIDs failed"); return number_of_devices; } // get number of OpenCL devices on platforms unsigned int HGPU_GPU_devices_get_number_on_platforms(HGPU_GPU_platforms* platforms){ unsigned int result = 0; for (unsigned int i=0;i<HGPU_GPU_platforms_get_number(platforms);i++) result += HGPU_GPU_devices_get_number_on_platform(platforms->platforms[i]); return result; } // select section_________________________________________________________________________________________________ // select OpenCL devices by vendor void HGPU_GPU_devices_select_by_vendor(HGPU_GPU_devices** devices,HGPU_GPU_vendor vendor){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); char infobuf[HGPU_MAX_STR_INFO_LENGHT]; cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id GPU_device = (*devices)->devices[i]; HGPU_GPU_error_message(clGetDeviceInfo(GPU_device,CL_DEVICE_VENDOR,sizeof(infobuf),infobuf,NULL),"clGetDeviceInfo failed"); if ((HGPU_convert_vendor_from_str(infobuf)==vendor) || (vendor==HGPU_GPU_vendor_any)) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int j=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id GPU_device = (*devices)->devices[i]; HGPU_GPU_error_message(clGetDeviceInfo(GPU_device,CL_DEVICE_VENDOR,sizeof(infobuf),infobuf,NULL),"clGetDeviceInfo failed"); if ((HGPU_convert_vendor_from_str(infobuf)==vendor) || (vendor==HGPU_GPU_vendor_any)) result->devices[j++] = GPU_device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by OpenCL version void HGPU_GPU_devices_select_by_version(HGPU_GPU_devices** devices,HGPU_GPU_version version){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; HGPU_GPU_version version_gpu = HGPU_GPU_device_get_version(device); if (HGPU_GPU_version_check(version_gpu,version)) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; HGPU_GPU_version version_gpu = HGPU_GPU_device_get_version(device); if (HGPU_GPU_version_check(version_gpu,version)) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by type void HGPU_GPU_devices_select_by_type(HGPU_GPU_devices** devices,cl_device_type device_type){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_device_type dev_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(dev_type),&dev_type,NULL),"clGetDeviceInfo failed"); if (dev_type & device_type) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_device_type dev_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(dev_type),&dev_type,NULL),"clGetDeviceInfo failed"); if (dev_type & device_type) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by device available void HGPU_GPU_devices_select_by_device_and_compiler_available(HGPU_GPU_devices** devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_bool device_available; cl_bool compiler_available; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_AVAILABLE,sizeof(device_available),&device_available,NULL),"clGetDeviceInfo failed"); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_COMPILER_AVAILABLE,sizeof(device_available),&compiler_available,NULL),"clGetDeviceInfo failed"); if (device_available & compiler_available) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_bool device_available; cl_bool compiler_available; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_AVAILABLE,sizeof(device_available),&device_available,NULL),"clGetDeviceInfo failed"); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_COMPILER_AVAILABLE,sizeof(device_available),&compiler_available,NULL),"clGetDeviceInfo failed"); if (device_available & compiler_available) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices by global memory size void HGPU_GPU_devices_select_by_global_mem_size(HGPU_GPU_devices** devices,unsigned long int memory_size_in_bytes){ HGPU_GPU_devices* result = (*devices); HGPU_GPU_devices_select_by_parameter_uint(&result,CL_DEVICE_GLOBAL_MEM_SIZE,memory_size_in_bytes); (*devices) = result; } // select OpenCL devices by max allocable memory size void HGPU_GPU_devices_select_by_max_alloc_mem(HGPU_GPU_devices** devices,unsigned long int memory_size_in_bytes){ HGPU_GPU_devices* result = (*devices); HGPU_GPU_devices_select_by_parameter_uint(&result,CL_DEVICE_MAX_MEM_ALLOC_SIZE,memory_size_in_bytes); (*devices) = result; } // select OpenCL devices by uint parameter void HGPU_GPU_devices_select_by_parameter_uint(HGPU_GPU_devices** devices,cl_device_info parameter,unsigned long int min_value){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_ulong device_output; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(device_output),&device_output,NULL),"clGetDeviceInfo failed"); if (device_output>=min_value) desired_devices++; } HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++){ cl_device_id device = (*devices)->devices[i]; cl_ulong device_output; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(device_output),&device_output,NULL),"clGetDeviceInfo failed"); if (device_output>=min_value) result->devices[device_index++] = device; } } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } // select OpenCL devices, supporting double precision void HGPU_GPU_devices_select_by_double_precision(HGPU_GPU_devices** devices){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices) HGPU_GPU_error(HGPU_ERROR_NO_DEVICE); cl_uint desired_devices = 0; for(unsigned int i=0; i<number_of_devices; i++) if (HGPU_GPU_device_check_double_precision((*devices)->devices[i])) desired_devices++; HGPU_GPU_devices* result; if(desired_devices){ result = HGPU_GPU_devices_new(desired_devices); int device_index=0; for(unsigned int i=0; i<number_of_devices; i++) if (HGPU_GPU_device_check_double_precision((*devices)->devices[i])) result->devices[device_index++] = (*devices)->devices[i]; } else result = HGPU_GPU_devices_new_empty(); HGPU_GPU_devices_delete(devices); (*devices) = result; } void HGPU_GPU_devices_select_by_highest_version(HGPU_GPU_devices** devices){ HGPU_GPU_version version = HGPU_GPU_devices_get_version_max(*devices); HGPU_GPU_devices_select_by_version(devices,version); } void HGPU_GPU_devices_exclude_device(HGPU_GPU_devices** devices,cl_device_id device){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (!number_of_devices){ HGPU_GPU_devices_delete(devices); return; } unsigned int number_of_devices_result = 0; for (unsigned int i=0; i<number_of_devices; i++) if ((*devices)->devices[i]!=device) number_of_devices_result++; if (!number_of_devices_result){ HGPU_GPU_devices_delete(devices); return; } HGPU_GPU_devices* result = HGPU_GPU_devices_new(number_of_devices_result); unsigned int j = 0; for (unsigned int i=0; i<number_of_devices; i++) if (((*devices)->devices[i]) && ((*devices)->devices[i]!=device)) result->devices[j++]=(*devices)->devices[i]; HGPU_GPU_devices_delete(devices); (*devices) = result; } // print names of OpenCL devices void HGPU_GPU_devices_print(HGPU_GPU_devices* devices){ if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); for (unsigned int i=0; i<number_of_devices; i++){ char* device_name = HGPU_GPU_device_get_name(devices->devices[i]); printf("Device [%u]: %s\n",i,device_name); free(device_name); } } // print names of platforms of OpenCL devices void HGPU_GPU_devices_print_platforms(HGPU_GPU_devices* devices){ if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); for (unsigned int i=0; i<number_of_devices; i++){ char* platform_name = HGPU_GPU_platform_get_name(HGPU_GPU_device_get_platform(devices->devices[i])); printf("Platform [%u]: %s\n",i,platform_name); free(platform_name); } } // single device___________________________________________________________________________________________________ // get index of OpenCL device by device unsigned int HGPU_GPU_device_get_index_of(cl_device_id device){ unsigned int result = 0; HGPU_GPU_devices* devices = HGPU_GPU_devices_get(); bool flag = true; while ((result<HGPU_GPU_devices_get_number(devices))&&(flag)){ if (devices->devices[result]==device) flag = false; else result++; } HGPU_GPU_devices_delete(&devices); if (flag) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return result; } // get index of OpenCL device by device on platform unsigned int HGPU_GPU_device_get_index_of_on_platform(cl_device_id device){ unsigned int result = 0; cl_platform_id platform = HGPU_GPU_device_get_platform(device); HGPU_GPU_devices* devices = HGPU_GPU_devices_get_on_platform(platform); bool flag = true; while ((result<HGPU_GPU_devices_get_number(devices))&&(flag)){ if (devices->devices[result]==device) flag = false; else result++; } HGPU_GPU_devices_delete(&devices); if (flag) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return result; } // get platform of OpenCL device cl_platform_id HGPU_GPU_device_get_platform(cl_device_id device){ cl_platform_id platform; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_PLATFORM,sizeof(platform),&platform,NULL),"clGetDeviceInfo (get platform) failed"); return platform; } // get index of platform for OpenCL device unsigned int HGPU_GPU_device_get_platform_index_of(cl_device_id device){ unsigned int platform_index = HGPU_GPU_platform_get_index_of(HGPU_GPU_device_get_platform(device)); return platform_index; } // get OpenCL device by index cl_device_id HGPU_GPU_device_get_by_index(unsigned int device_index){ cl_device_id result; HGPU_GPU_devices* devices = HGPU_GPU_devices_get(); if (HGPU_GPU_devices_get_number(devices)<=device_index) { HGPU_GPU_devices_delete(&devices); HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); } result = devices->devices[device_index]; HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device by index cl_device_id HGPU_GPU_device_get_by_index_on_platform(cl_platform_id platform,unsigned int device_index){ cl_device_id result; HGPU_GPU_devices* devices = HGPU_GPU_devices_get_on_platform(platform); if (HGPU_GPU_devices_get_number(devices)<=device_index) { HGPU_GPU_devices_delete(&devices); HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); } result = devices->devices[device_index]; HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device info char* HGPU_GPU_device_get_info_str(cl_device_id device,cl_device_info parameter){ size_t parameter_length; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,0,NULL,&parameter_length),"clGetDeviceInfo failed"); char* result_str = (char*) calloc(parameter_length,sizeof(char)); HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,(parameter_length),result_str,NULL),"clGetDeviceInfo failed"); return result_str; } // get OpenCL device info (unsigned long int) unsigned long int HGPU_GPU_device_get_info_uint(cl_device_id device,cl_device_info parameter){ cl_ulong result = 0; HGPU_GPU_error_message(clGetDeviceInfo(device,parameter,sizeof(result),&result,NULL),"clGetDeviceInfo failed"); return (unsigned long int) result; } char* HGPU_GPU_device_get_name(cl_device_id device){ char* device_name = HGPU_GPU_device_get_info_str(device,CL_DEVICE_NAME); HGPU_string_trim(device_name); return device_name; } // get short info on OpenCL device char* HGPU_GPU_device_get_info_short(cl_device_id device){ char* result = (char*) calloc(HGPU_MAX_STR_INFO_LENGHT,sizeof(char)); char* name = HGPU_GPU_device_get_name(device); char* vendor = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VENDOR); char* profile = HGPU_GPU_device_get_info_str(device,CL_DEVICE_PROFILE); char* version = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VERSION); char* extensions = HGPU_GPU_device_get_info_str(device,CL_DEVICE_EXTENSIONS); unsigned int j = 0; j = sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," Device: %s\n",name); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j,"device's vendor: %s\n",vendor); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," profile: %s\n",profile); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," version: %s\n",version); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," extensions: %s\n",extensions); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j,"max alloc. size: %lu\n",HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_MEM_ALLOC_SIZE)); j += sprintf_s(result+j,HGPU_MAX_STR_INFO_LENGHT-j," index: [%u] [%u]\n",HGPU_GPU_device_get_index_of(device),HGPU_GPU_device_get_index_of_on_platform(device)); free(extensions); free(version); free(profile); free(vendor); free(name); return result; } // get device's OpenCL version (min of DEVICE and DRIVER version) HGPU_GPU_version HGPU_GPU_device_get_version(cl_device_id device){ HGPU_GPU_version version, version2; char* version_str = HGPU_GPU_device_get_info_str(device,CL_DEVICE_VERSION); version = HGPU_GPU_version_get(version_str); if (version.minor>=1) { char* version_str2 = HGPU_GPU_device_get_info_str(device,CL_DEVICE_OPENCL_C_VERSION); // CL_DEVICE_OPENCL_C_VERSION option only in OpenCL 1.1 version2 = HGPU_GPU_version_get(version_str2); version = HGPU_GPU_version_min(version,version2); free(version_str2); } free(version_str); return version; } // get vendor of OpenCL device HGPU_GPU_vendor HGPU_GPU_device_get_vendor(cl_device_id device){ size_t parameter_length; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_VENDOR,0,NULL,&parameter_length),"clGetDeviceInfo failed"); char* result_str = (char*) calloc(parameter_length+1,sizeof(char)); HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_VENDOR,(parameter_length+1),result_str,NULL),"clGetDeviceInfo failed"); HGPU_GPU_vendor vendor = HGPU_convert_vendor_from_str(result_str); free(result_str); return vendor; } // get first available device cl_device_id HGPU_GPU_device_get_first(HGPU_GPU_devices* devices){ if ((!devices) || (!HGPU_GPU_devices_get_number(devices))) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return devices->devices[0]; } // get best available device cl_device_id HGPU_GPU_device_get_best(HGPU_GPU_devices* devices){ if ((!devices) || (!HGPU_GPU_devices_get_number(devices))) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); HGPU_GPU_devices* devs = HGPU_GPU_devices_clone(devices); HGPU_GPU_devices_sort(&devs); cl_device_id result = devs->devices[0]; return result; } // get next available device cl_device_id HGPU_GPU_device_get_next(HGPU_GPU_devices* devices,cl_device_id device){ unsigned int number_of_devices = HGPU_GPU_devices_get_number(devices); if (!number_of_devices) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); unsigned int device_last_index = number_of_devices; for (unsigned int i=0;i<number_of_devices;i++){ if (devices->devices[i]==device){ device_last_index = i; i = number_of_devices; } } if (device_last_index>=(number_of_devices-1)) HGPU_GPU_error_message(HGPU_ERROR_NO_DEVICE,"there is no any desired OpenCL device"); return devices->devices[device_last_index+1]; } // check if OpenCL supports double precision bool HGPU_GPU_device_check_double_precision(cl_device_id device){ bool result = false; char device_output[HGPU_MAX_STR_INFO_LENGHT]; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_EXTENSIONS,HGPU_MAX_STR_INFO_LENGHT,&device_output,NULL),"clGetDeviceInfo failed"); HGPU_string_to_lowercase(device_output); if (strstr(device_output,"cl_khr_fp64")) result = true; return result; } // automatically select OpenCL devices according to (HGPU_parameter) parameters HGPU_GPU_devices* HGPU_GPU_devices_select_auto(HGPU_parameter** parameters){ HGPU_GPU_platforms* platforms = NULL; HGPU_GPU_devices* devices = NULL; HGPU_parameter* parameter_device = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_DEVICE); HGPU_parameter* parameter_device_type = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_DEVICE_TYPE); HGPU_parameter* parameter_platform = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_PLATFORM); if (parameter_platform) { unsigned int platform_id = parameter_platform->value_integer; if ((!platform_id) && (strlen(parameter_platform->value_text)>1)){ // get platforms by vendor platforms = HGPU_GPU_platforms_get(); HGPU_GPU_vendor platform_vendor = HGPU_convert_vendor_from_str(parameter_platform->value_text); HGPU_GPU_platforms_select_by_vendor(&platforms,platform_vendor); } else { platforms = HGPU_GPU_platforms_new(1); platforms[0].platforms[0] = HGPU_GPU_platform_get_by_index(platform_id); } devices = HGPU_GPU_devices_get_on_platforms(platforms); } if (parameter_device) { unsigned int device_id = parameter_device->value_integer; if ((!device_id) && (strlen(parameter_device->value_text)>1)){ HGPU_GPU_vendor device_vendor = HGPU_convert_vendor_from_str(parameter_device->value_text); // get devices by vendor if (parameter_platform) HGPU_GPU_devices_select_by_vendor(&devices,device_vendor); else devices = HGPU_GPU_devices_get_by_vendor(device_vendor); } else { devices = HGPU_GPU_devices_new(1); if (parameter_platform) devices[0].devices[0] = HGPU_GPU_device_get_by_index_on_platform(platforms[0].platforms[0],device_id); else devices[0].devices[0] = HGPU_GPU_device_get_by_index(device_id); } } if ((!parameter_platform) && (!parameter_device)) devices = HGPU_GPU_devices_get(); if (parameter_device_type) { if (!strcmp(parameter_device_type->value_text,"GPU")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_GPU); if (!strcmp(parameter_device_type->value_text,"CPU")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_CPU); if (!strcmp(parameter_device_type->value_text,"ACCELERATOR")) HGPU_GPU_devices_select_by_type(&devices,CL_DEVICE_TYPE_ACCELERATOR); } HGPU_GPU_devices_sort(&devices); return devices; } // get rating of OpenCL device unsigned int HGPU_GPU_device_get_rating(cl_device_id device){ //+++ GPU - 1000 points //+++ Double precision - 100 points //+++ OpenCL major version - 10 points //+++ OpenCL minor version - 1 point unsigned int result = 0; if (device){ cl_device_type device_type; HGPU_GPU_error_message(clGetDeviceInfo(device,CL_DEVICE_TYPE,sizeof(device_type),&device_type,NULL),"clGetDeviceInfo failed"); if (device_type==CL_DEVICE_TYPE_GPU) result += 1000; if (HGPU_GPU_device_check_double_precision(device)) result += 100; HGPU_GPU_version version = HGPU_GPU_device_get_version(device); result += version.major * 10; result += version.minor; } return result; } // sort OpenCL devices by characteristics void HGPU_GPU_devices_sort(HGPU_GPU_devices** devices){ // 1. GPU which supports double precision with highest version of OpenCL // 2. GPU with highest version of OpenCL // 3. device which supports double precision with highest version of OpenCL // 4. any other OpenCL device if (!devices) return; unsigned int number_of_devices = HGPU_GPU_devices_get_number(*devices); if (number_of_devices>0){ unsigned int* rating = (unsigned int*) calloc(number_of_devices,sizeof(unsigned int)); for (unsigned int i=0;i<number_of_devices;i++) rating[i]=HGPU_GPU_device_get_rating((*devices)->devices[i]); // sort by result for (unsigned int i=0;i<(number_of_devices-1);i++){ unsigned int max_rating = rating[i]; unsigned int max_index = i; for (unsigned int j=(i+1);j<number_of_devices;j++){ if (rating[j]>max_rating) { max_index = j; max_rating = rating[j]; } } if (max_index>i) { unsigned int temp_rating = rating[i]; cl_device_id temp_device = (*devices)->devices[i]; (*devices)->devices[i] = (*devices)->devices[max_index]; rating[i] = rating[max_index]; (*devices)->devices[max_index] = temp_device; rating[max_index] = temp_rating; } } } } // automatically select OpenCL device cl_device_id HGPU_GPU_device_select_auto(void){ return HGPU_GPU_device_select_auto_with_parameters(NULL); } // automatically select OpenCL device from devices cl_device_id HGPU_GPU_device_select_auto_from_devices(HGPU_GPU_devices* devices){ return HGPU_GPU_device_get_best(devices); } // automatically select next OpenCL device from devices cl_device_id HGPU_GPU_device_select_auto_from_devices_next(HGPU_GPU_devices* devices,cl_device_id device){ HGPU_GPU_devices* results = HGPU_GPU_devices_clone(devices); HGPU_GPU_devices_sort(&results); cl_device_id result = NULL; bool device_found = false; cl_device_id temp_device; while ((results) && (HGPU_GPU_devices_get_number(results)) && (!device_found)) { temp_device = HGPU_GPU_device_get_first(results); if (temp_device==device) device_found = true; HGPU_GPU_devices_exclude_device(&results,temp_device); } if ((results) && (HGPU_GPU_devices_get_number(results))) result = HGPU_GPU_device_get_first(results); HGPU_GPU_devices_delete(&results); return result; } // automatically select next OpenCL device cl_device_id HGPU_GPU_device_select_auto_next(cl_device_id device){ return HGPU_GPU_device_select_auto_with_parameters_next(device,NULL); } // automatically select OpenCL device with parameters cl_device_id HGPU_GPU_device_select_auto_with_parameters(HGPU_parameter** parameters){ return HGPU_GPU_device_select_auto_with_parameters_next(NULL,parameters); } // automatically select next OpenCL device with parameters cl_device_id HGPU_GPU_device_select_auto_with_parameters_next(cl_device_id device,HGPU_parameter** parameters){ HGPU_GPU_devices* devices = HGPU_GPU_devices_select_auto(parameters); cl_device_id result; if (!device) result = HGPU_GPU_device_get_best(devices); else result = HGPU_GPU_device_select_auto_from_devices_next(devices,device); HGPU_GPU_devices_delete(&devices); return result; } // get OpenCL device info HGPU_GPU_device_info HGPU_GPU_device_get_info(cl_device_id device){ HGPU_GPU_device_info result; result.platform_vendor = HGPU_GPU_platform_get_vendor(HGPU_GPU_device_get_platform(device)); result.device_vendor = HGPU_GPU_device_get_vendor(device); result.global_memory_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_GLOBAL_MEM_SIZE); result.local_memory_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_LOCAL_MEM_SIZE); result.max_compute_units = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_COMPUTE_UNITS); result.max_constant_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE); result.max_memory_height = (size_t) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_HEIGHT); result.max_memory_width = (size_t) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_WIDTH); result.max_workgroup_size = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_WORK_GROUP_SIZE); result.memory_align_factor= HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_WORK_GROUP_SIZE); if (result.max_memory_width) result.max_memory_width = HGPU_GPU_MAX_MEMORY_WIDTH; if (result.max_memory_height) result.max_memory_height = HGPU_GPU_MAX_MEMORY_HEIGHT; #if defined(HGPU_GPU_MAX_INTEL_WORKGROUP_SIZE) if (result.device_vendor == HGPU_GPU_vendor_intel) result.max_workgroup_size = HGPU_GPU_MAX_INTEL_WORKGROUP_SIZE; #endif return result; } // print short info on OpenCL device void HGPU_GPU_device_print_info(cl_device_id device){ char* device_info = HGPU_GPU_device_get_info_short(device); printf("%s",device_info); free(device_info); } // print OpenCL device's name void HGPU_GPU_device_print_name(cl_device_id device){ char* device_name = HGPU_GPU_device_get_name(device); printf("%s",device_name); free(device_name); } // get max memory width unsigned int HGPU_GPU_device_get_max_memory_width(cl_device_id device){ unsigned int result = (unsigned int) HGPU_GPU_device_get_info_uint(device,CL_DEVICE_IMAGE3D_MAX_WIDTH); if (!result) result = 8192; return result; } // get max allocation memory unsigned long int HGPU_GPU_device_get_max_allocation_memory(cl_device_id device){ unsigned long int result = HGPU_GPU_device_get_info_uint(device,CL_DEVICE_MAX_MEM_ALLOC_SIZE); return result; }
42.847597
173
0.744015
vadimdi
691113bd555bada5d5032b9618441c3c1bc9d8af
4,144
cpp
C++
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
Circuit3C/src/main.cpp
padlewski/DLP_COMP444
7635517b50f2c806856fc748db6f6f6c5bc26d34
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Servo.h> //include the servo library const int trigPin = 11; //connects to the trigger pin on the distance sensor const int echoPin = 12; //connects to the echo pin on the distance sensor const int redPin = 3; //pin to control the red LED inside the RGB LED const int greenPin = 5; //pin to control the green LED inside the RGB LED const int bluePin = 6; //pin to control the blue LED inside the RGB LED const int buzzerPin = 10; //pin that will drive the buzzer float distance = 0; //stores the distance measured by the distance sensor Servo myservo; //create a servo object float getDistance(); void setup() { Serial.begin (9600); //set up a serial connection with the computer pinMode(trigPin, OUTPUT); //the trigger pin will output pulses of electricity pinMode(echoPin, INPUT); //the echo pin will measure the duration of pulses coming back from the distance sensor //set the RGB LED pins to output pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(buzzerPin, OUTPUT); //set the buzzer pin to output myservo.attach(9); //use pin 9 to control the servo } void loop() { distance = getDistance(); //variable to store the distance measured by the sensor Serial.print(distance); //print the distance that was measured Serial.println(" in"); //print units after the distance #ifdef _EXPERIMENT_1_ if (distance < 24) { //if the object is close #else if (distance <= 10) { //if the object is close #endif //make the RGB LED red analogWrite(redPin, 255); analogWrite(greenPin, 0); analogWrite(bluePin, 0); //this code wiggles the servo and beeps the buzzer tone(buzzerPin, 272); //buzz the buzzer pin #ifdef _EXPERIMENT_2_ myservo.write(10); //move the servo to 45 degrees delay(300); //wait 100 milliseconds noTone(buzzerPin); //turn the buzzer off myservo.write(160); //move the servo to 135 degrees delay(300); tone(buzzerPin, 272); //buzz the buzzer pin myservo.write(45); delay(150); noTone(buzzerPin); myservo.write(65); delay(150); #else myservo.write(10); //move the servo to 45 degrees delay(100); //wait 100 milliseconds noTone(buzzerPin); //turn the buzzer off myservo.write(160); //move the servo to 135 degrees delay(100); //wait 100 milliseconds #endif #ifdef _EXPERIMENT_1_ } else if(distance < 40){ #else } else if (10 < distance && distance < 20) { //if the object is a medium distance #endif //make the RGB LED yellow analogWrite(redPin, 255); analogWrite(greenPin, 50); analogWrite(bluePin, 0); } else { //if the object is far away //make the RGB LED green analogWrite(redPin, 0); analogWrite(greenPin, 255); analogWrite(bluePin, 0); } delay(50); //delay 50ms between each reading } //------------------FUNCTIONS------------------------------- //RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR float getDistance() { float echoTime; //variable to store the time it takes for a ping to bounce off an object float calculatedDistance; //variable to store the distance calculated from the echo time //send out an ultrasonic pulse that's 10ms long digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the //pulse to bounce back to the sensor calculatedDistance = echoTime / 148.0; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound) return calculatedDistance; //send back the distance that was calculated }
34.533333
161
0.624759
padlewski
6911c61370affdff725c6a6f147cc296d2b5dfed
3,489
cpp
C++
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
libsrc/jsonserver/JsonServer.cpp
juanesf/hyperion_openwrt_mt7620
a29624e1ca03c37517b043956b55064b6021c7b4
[ "MIT" ]
null
null
null
// system includes #include <stdexcept> // project includes #include <jsonserver/JsonServer.h> #include "JsonClientConnection.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/WebSocket.h" #include "Poco/Net/NetException.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerParams.h" #include "Poco/Delegate.h" class WebSocketRequestHandler: public Poco::Net::HTTPRequestHandler { public: WebSocketRequestHandler(Hyperion *hyperion) : _hyperion(hyperion) { } void handleRequest(Poco::Net::HTTPServerRequest & request, Poco::Net::HTTPServerResponse & response) { try { Poco::Net::WebSocket socket(request, response); std::cout << "New json connection from " << request.clientAddress().toString() << std::endl; JsonClientConnection connection(&socket, _hyperion); // connection.setColorsEvent += Poco::delegate(_hyperion, &Hyperion::setColorsD); // connection.clearEvent += Poco::delegate(_hyperion, &Hyperion::clearD); // connection.clearAllEvent += Poco::delegate(_hyperion, &Hyperion::clearAllD); int result; do { result = connection.processRequest(); } while (result == 0); std::cout << "Connection to " << request.clientAddress().toString() << " closed" << std::endl; // connection.setColorsEvent -= Poco::delegate(_hyperion, &Hyperion::setColorsD); // connection.clearEvent -= Poco::delegate(_hyperion, &Hyperion::clearD); // connection.clearAllEvent -= Poco::delegate(_hyperion, &Hyperion::clearAllD); } catch (Poco::Net::WebSocketException & exc) { std::cout << exc.what() << std::endl; switch (exc.code()) { case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION: response.set("Sec-WebSocket-Version", Poco::Net::WebSocket::WEBSOCKET_VERSION); // fallthrough case Poco::Net::WebSocket::WS_ERR_NO_HANDSHAKE: case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_VERSION: case Poco::Net::WebSocket::WS_ERR_HANDSHAKE_NO_KEY: response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response.setContentLength(0); response.send(); break; } } catch (const std::exception& e) { std::cerr << "[ERROR] handleRequest: " << e.what() << std::endl; } } private: Hyperion * _hyperion; }; class WebSocketRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory { public: WebSocketRequestHandlerFactory(Hyperion *hyperion) : _hyperion(hyperion) { } Poco::Net::HTTPRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) { return new WebSocketRequestHandler(_hyperion); } private: Hyperion * _hyperion; }; JsonServer::JsonServer(Hyperion *hyperion, uint16_t port) : _hyperion(hyperion) { Poco::Net::ServerSocket serverSocket(port); _server = new Poco::Net::HTTPServer(new WebSocketRequestHandlerFactory(_hyperion), serverSocket, new Poco::Net::HTTPServerParams); _server->start(); } JsonServer::~JsonServer() { _server->stop(); delete _server; } uint16_t JsonServer::getPort() const { return _server->port(); }
32.305556
134
0.651476
juanesf
69158c9c357a594c3e78806e318ed2bba85b49da
4,810
cxx
C++
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
4
2020-04-23T12:28:41.000Z
2021-06-07T05:54:16.000Z
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
null
null
null
MSEL_src/MSEL_core/dbdet_curvelet.cxx
yuliangguo/MSEL_contour_extraction_cxx
723893a92370dfe084afd23d9a69d3e2fead2464
[ "MIT" ]
1
2017-06-05T18:00:21.000Z
2017-06-05T18:00:21.000Z
#include "dbdet_curvelet.h" #include <vcl_iostream.h> #include <vcl_fstream.h> #include <vcl_cassert.h> #include <vcl_deque.h> #include <vcl_algorithm.h> //: copy constructor dbdet_curvelet::dbdet_curvelet(const dbdet_curvelet& other) { //the edgels have to copied as links because curvelets are just groupings of the edgels ref_edgel = other.ref_edgel; edgel_chain = other.edgel_chain; //but the curve model has to be deep copied switch(other.curve_model->type) { case dbdet_curve_model::LINEAR: curve_model = new dbdet_linear_curve_model(*(dbdet_linear_curve_model*)other.curve_model); break; case dbdet_curve_model::CC: curve_model = new dbdet_CC_curve_model(*(dbdet_CC_curve_model*)other.curve_model); case dbdet_curve_model::CC2: curve_model = new dbdet_CC_curve_model_new(*(dbdet_CC_curve_model_new*)other.curve_model); case dbdet_curve_model::CC3d: curve_model = new dbdet_CC_curve_model_3d(*(dbdet_CC_curve_model_3d*)other.curve_model); case dbdet_curve_model::ES: curve_model = new dbdet_ES_curve_model(*(dbdet_ES_curve_model*)other.curve_model); default: curve_model=0; //TO DO } forward = other.forward; length = other.length; quality = other.quality; used = other.used; } //: copy constructor with provisions for copying a different curve bundle dbdet_curvelet::dbdet_curvelet(const dbdet_curvelet& other, dbdet_curve_model* cm) { //the edgels have to copied as links because curvelets are just groupings of the edgels ref_edgel = other.ref_edgel; edgel_chain = other.edgel_chain; //do not copy the CB, just assign the ne passed to it curve_model = cm; forward = other.forward; length = other.length; quality = other.quality; used = other.used; } //: destructor dbdet_curvelet::~dbdet_curvelet() { //delete the curve model if (curve_model) delete curve_model; edgel_chain.clear(); } // weighting constants for the heuristic #define alpha3 1.0 #define alpha4 1.0 //: compute properties of this curvelet once formed void dbdet_curvelet::compute_properties(double R, double token_len) { //find out the # of edgels before and after the reference edgel //also find out the length before and after the reference edgel int num_before=0, num_after=0; double Lm=0, Lp=0; bool before_ref = true; for (unsigned i=0; i<edgel_chain.size()-1; i++){ if (before_ref) { Lm += vgl_distance(edgel_chain[i]->pt, edgel_chain[i+1]->pt); num_before++; } else { Lp += vgl_distance(edgel_chain[i]->pt, edgel_chain[i+1]->pt); num_after++; } if (edgel_chain[i+1]==ref_edgel) before_ref = false; } //compute the length of the curvelet (extrinsic length) length = Lm+Lp; //also compute the LG ratio and store as quality //quality = (num_before+num_after)*token_len/length; //new quality measure (1/cost of the compatibility heauristic) quality = 2/(alpha3*R/length + alpha4*length/token_len/edgel_chain.size()); } //: print info to file void dbdet_curvelet::print(vcl_ostream& os) { //first output the edgel chain os << "["; for (unsigned i=0; i< edgel_chain.size(); i++){ os << edgel_chain[i]->id << " "; } os << "] "; //forward/backward tag os << "("; if (forward) os << "F"; else os << "B"; os << ") "; //next output the curve model curve_model->print(os); //then output the other properties os << " " << length << " " << quality << vcl_endl; } //: read info from file void dbdet_curvelet::read(vcl_istream& /*is*/) { //this is not possible without access to the edgemap } vcl_list<dbdet_edgel*> dbdet_curvelet::child_chain() { bool flag=false; vcl_list<dbdet_edgel*> return_chain; for(unsigned i=0;i<edgel_chain.size();i++) { if(flag) return_chain.push_back(edgel_chain[i]); if(edgel_chain[i]->id==ref_edgel->id) flag=true; } return return_chain; } vcl_list<dbdet_edgel*> dbdet_curvelet::parent_chain() { bool flag=true; vcl_list<dbdet_edgel*> return_chain; for(unsigned i=0;i<edgel_chain.size();i++) { if(edgel_chain[i]->id==ref_edgel->id) flag=false; if(flag) return_chain.push_front(edgel_chain[i]); } return return_chain; } ////: does a larger grouping exist already? //dbdet_curvelet* dbdet_curvelet::exists(dbdet_curvelet* cv) //{ // curvelet_list_iter c_it = larger_curvelets.begin(); // for (; c_it != larger_curvelets.end(); c_it++){ // dbdet_curvelet* lcv = (*c_it); // // bool found = true; // for (unsigned j=0; j<lcv->edgel_chain.size(); j++){ // if (cv->edgel_chain[j] != lcv->edgel_chain[j]) // found = false; // } // // if (found) // return lcv; // } // //not found // return 0; //}
26.574586
99
0.673805
yuliangguo
69169830c1ce01e00e1d9551f7e899d2e1cadcd4
346
cc
C++
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
tests/s-approximations-unittest.cc
vined/biosensor-modeling
dda882d70fbf7128bc45cf3aed2b73dbc70f6693
[ "MIT" ]
null
null
null
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "../src/s-approximations.h" using ::testing::ElementsAreArray; namespace { TEST(ApproximationsUtilsTest, GetProgressTest) { std::vector<double> y_new {1, 2, 3, 4, 5}; std::vector<double> y_old {0, 1, 2, 3, 3}; EXPECT_DOUBLE_EQ(2.0, getProgress(y_new, y_old)); } }
18.210526
53
0.66474
vined
69192dd65e8e8a19fafdc420ad72dabcb3b60a6d
11,464
hpp
C++
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
Pods/GeoFeatures/GeoFeatures/Internal/geofeatures/operators/Intersects.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
null
null
null
/** * Intersects.hpp * * Copyright 2015 Tony Stone * * 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. * * Created by Tony Stone on 10/6/15. */ #ifndef __GeoFeature_Intersects_Other_Operation_HPP_ #define __GeoFeature_Intersects_Other_Operation_HPP_ #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/variant_fwd.hpp> #include <boost/geometry/strategies/strategies.hpp> #include <boost/geometry/algorithms/intersects.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include "GeometryVariant.hpp" namespace geofeatures { namespace operators { namespace detail { /** * intersects implementation class. */ struct intersects { /** * Internal class to convert from GeometryCollection variant * to the GeometryPtrVariant type. */ struct VariantToPtrVariant : public boost::static_visitor<GeometryPtrVariant> { template <typename T> GeometryPtrVariant operator()(const T & v) const { return GeometryPtrVariant(&v); } }; /** * Internal visitor class for variant access. */ class IntersectsSelfVisitor : public boost::static_visitor<bool> { public: /** * Constructor to initialize the visitor members */ IntersectsSelfVisitor() : variantToPtrVariantVisitor() {} /** * Generic intersects that are implemented by boost */ template <typename T> bool operator()(const T * t) const { return boost::geometry::intersects(*t); } /* * Intersects operation methods specific to 1 type */ bool operator()(const Point * v) const { return false; // A point can't intersect itself } bool operator()(const MultiPoint * v) const { return false; // A multipoint can't intersect itself } bool operator()(const Box * v) const { return false; // A box can't intersect itself } // GeometryCollection intersects bool operator()(const GeometryCollection<> * collection) const { for (auto it = collection->begin(); it != collection->end(); ++it ) { geofeatures::GeometryPtrVariant ptrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, ptrVariant)) { return true; } } return false; } private: VariantToPtrVariant variantToPtrVariantVisitor; }; /** * Internal visitor class for variant access. */ class IntersectsOtherVisitor : public boost::static_visitor<bool> { public: /** * Constructor to initialize the visitor members */ IntersectsOtherVisitor() : variantToPtrVariantVisitor() {} /** * Generic intersects that are implemented by boost */ template <typename T1, typename T2> bool operator()(const T1 * t1, const T2 * t2) const { return boost::geometry::intersects(*t1,*t2); } /* * Intersects operation methods specific to 2 types */ /** * Generic template for MultiType to single type intersects */ template<typename MultiType, typename SingleType> inline bool multiIntersects(const MultiType * multiType, const SingleType * singleType) const { // // If any point in the item in the multi intersects the other geometry, // we have an intersection. // for (auto it = multiType->begin(); it != multiType->end(); it++) { if (boost::geometry::intersects(*it,*singleType)) { return true; } } return false; } bool operator()(const MultiPoint * multiPoint, const Ring * ring) const { return multiIntersects(multiPoint,ring); } bool operator()(const Ring * ring, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,ring); } bool operator()(const Polygon * polygon, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,polygon); } bool operator()(const MultiPoint * multiPoint, const Polygon * polygon) const { return multiIntersects(multiPoint,polygon); } bool operator()(const MultiPoint * multiPoint, const MultiPolygon * multiPolygon) const { return multiIntersects(multiPoint,multiPolygon); } bool operator()(const MultiPolygon * multiPolygon, const MultiPoint * multiPoint) const { // reverse them and use the multiIntersect return multiIntersects(multiPoint,multiPolygon); } bool operator()(const GeometryCollection<> * lhs, const GeometryCollection<> * rhs) const { for (auto it = lhs->begin(); it != lhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); geofeatures::GeometryPtrVariant rhsPtrVariant(rhs); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } for (auto it = rhs->begin(); it != rhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant(lhs); geofeatures::GeometryPtrVariant rhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } template <typename T> bool operator()(const GeometryCollection<> * lhs, const T * rhs) const { geofeatures::GeometryPtrVariant rhsPtrVariant(rhs); for (auto it = lhs->begin(); it != lhs->end(); ++it ) { geofeatures::GeometryPtrVariant lhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } template <typename T> bool operator()(const T * lhs, const GeometryCollection<> * rhs) const { geofeatures::GeometryPtrVariant lhsPtrVariant(lhs); for (auto it = rhs->begin(); it != rhs->end(); ++it ) { geofeatures::GeometryPtrVariant rhsPtrVariant = boost::apply_visitor(variantToPtrVariantVisitor,*it); if (boost::apply_visitor(*this, lhsPtrVariant, rhsPtrVariant)) { return true; } } return false; } private: VariantToPtrVariant variantToPtrVariantVisitor; }; /** * Apply the detail implementation to the variant passed. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T)> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const & variant) { return boost::apply_visitor(IntersectsSelfVisitor(), variant); } /** * Apply the detail implementation to the variants passed. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2)> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant1,boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const & variant2) { return boost::apply_visitor(IntersectsOtherVisitor(), variant1, variant2); } }; } /** * intersect self method. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T)> inline bool intersects(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const & variant) { return detail::intersects::apply(variant); } /** * intersect other method. */ template <BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2)> inline bool intersects(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const & variant2) { return detail::intersects::apply(variant1, variant2); } } // namespace operators } // namespace geofeatures #endif //__GeoFeature_Intersects_Other_Operation_HPP_
43.097744
167
0.491626
xarvey
691dc3230f62e0fb18cb4241f8918f8e447cb4cf
7,144
hpp
C++
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
6
2021-03-08T15:29:20.000Z
2021-07-04T06:39:23.000Z
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
1
2021-03-25T03:36:57.000Z
2021-03-25T03:36:57.000Z
src/dispatch.hpp
wenjian0202/mod-abm-2.0
0057126f583d76834237daf4dd9f96ffb4715eff
[ "MIT" ]
3
2021-03-18T07:32:00.000Z
2021-08-11T09:53:40.000Z
/// \author Jian Wen /// \date 2021/02/02 #pragma once #include "types.hpp" #include <cstddef> /// \brief Assign the pending trips to the vehicles using Insertion Heuristics. /// \param pending_trip_ids A vector holding indices to the pending trips. /// \param trips A vector of all trips. /// \param vehicles A vector of all vehicles. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void assign_trips_through_insertion_heuristics(const std::vector<size_t> &pending_trip_ids, std::vector<Trip> &trips, std::vector<Vehicle> &vehicles, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Assign one single trip to the vehicles using using Insertion Heuristics. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicles A vector of all vehicles. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void assign_trip_through_insertion_heuristics(Trip &trip, const std::vector<Trip> &trips, std::vector<Vehicle> &vehicles, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Compute the cost (time in millisecond) of serving the current waypoints. /// \details The cost of serving all waypoints is defined as the total time taken to drop off each /// of the trips based on the current ordering. uint64_t get_cost_of_waypoints(const std::vector<Waypoint> &waypoints); /// \brief Validate waypoints by checking all constraints. Returns true if valid. bool validate_waypoints(const std::vector<Waypoint> &waypoints, const std::vector<Trip> &trips, const Vehicle &vehicle, uint64_t system_time_ms); /// \brief Compute the time that the trip is picked up knowing pickup index. /// \param pos The current vehicle pose. /// \param waypoints The waypoints that are orignially planned. /// \param pickup_pos The pose for the pickup. /// \param pickup_index The index in the waypoint list where we pick up. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. /// \return A pair. True if the trip can be inserted, together with the pick up time. False /// otherwise. template <typename RouterFunc> std::pair<bool, uint64_t> get_pickup_time(Pos pos, const std::vector<Waypoint> &waypoints, Pos pickup_pos, size_t pickup_index, uint64_t system_time_ms, RouterFunc &router_func); /// \brief The return type of the following function. /// \details If the trip could not be inserted based on the current vehicle status, result is false. /// Otherwise, result is true. The cost_ms is the additional cost in milliseconds required to serve /// this trip, The following indices point to where to insert the pickup and dropoff. struct InsertionResult { bool success = false; size_t vehicle_id; uint64_t cost_ms = std::numeric_limits<uint64_t>::max(); size_t pickup_index; size_t dropoff_index; }; /// \brief Compute the additional cost (time in millisecond) if a vehicle is to serve a trip. /// \see get_cost_of_waypoints has the detialed definition of cost. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicle The vehicle that serves the trip. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> InsertionResult compute_cost_of_inserting_trip_to_vehicle(const Trip &trip, const std::vector<Trip> &trips, const Vehicle &vehicle, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Compute the additional cost knowing pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param trips A vector of all trips. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \param system_time_ms The current system time. /// \tparam router_func The router func that finds path between two poses. /// \return A pair. True if the trip can be inserted, together with the additional cost in seconds. /// False otherwise. template <typename RouterFunc> std::pair<bool, uint64_t> compute_cost_of_inserting_trip_to_vehicle_given_pickup_and_dropoff_indices( const Trip &trip, const std::vector<Trip> &trips, const Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, uint64_t system_time_ms, RouterFunc &router_func); /// \brief Insert the trip to the vehicle given known pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> void insert_trip_to_vehicle(Trip &trip, Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, RouterFunc &router_func); /// \brief Generate a vector of waypoints given known pickup and dropoff indices. /// \param trip The trip to be inserted. /// \param vehicle The vehicle that serves the trip. /// \param pickup_index The index in the waypoint list where we pick up. /// \param dropoff_index The index in the waypoint list where we drop off. /// \param routing_type The type of the route. /// \tparam router_func The router func that finds path between two poses. template <typename RouterFunc> std::vector<Waypoint> generate_waypoints(const Trip &trip, const Vehicle &vehicle, size_t pickup_index, size_t dropoff_index, RoutingType routing_type, RouterFunc &router_func); // Implementation is put in a separate file for clarity and maintainability. #include "dispatch_impl.hpp"
51.028571
100
0.638438
wenjian0202
691e38ca93768071e24cbf69f255584a2bdbd21d
1,630
cpp
C++
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Render/BufferObject/BBTranslateFeedbackObject.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
#include "BBTranslateFeedbackObject.h" #include "BBVertexBufferObject.h" BBTranslateFeedbackObject::BBTranslateFeedbackObject(int nVertexCount, GLenum hint, GLenum eDrawPrimitiveType) : BBBufferObject() { m_nVertexCount = nVertexCount; m_eDrawPrimitiveType = eDrawPrimitiveType; createTFO(); } void BBTranslateFeedbackObject::bind() { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); // all data of TFO will be written into the buffer glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, m_Name); glBeginTransformFeedback(m_eDrawPrimitiveType); } void BBTranslateFeedbackObject::unbind() { glEndTransformFeedback(); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); } void BBTranslateFeedbackObject::debug() { BBBufferObject::bind(); // extract from gpu BBVertex *pVertexes = new BBVertex[m_nVertexCount]; glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, sizeof(BBVertex) * m_nVertexCount, pVertexes); if (pVertexes) { for (int i = 0; i < m_nVertexCount; i++) { qDebug() << pVertexes[i].m_fPosition[0] << pVertexes[i].m_fPosition[1] << pVertexes[i].m_fPosition[2]; } } else { qDebug() << "error"; } glUnmapBuffer(m_BufferType); BBBufferObject::unbind(); } GLuint BBTranslateFeedbackObject::createTFO() { glGenTransformFeedbacks(1, &m_TFO); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_TFO); m_Name = createBufferObject(m_BufferType, sizeof(BBVertex) * m_nVertexCount, GL_STATIC_DRAW, nullptr); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); return m_TFO; }
29.107143
114
0.725153
xiaoxianrouzhiyou
69244678a6c097ed04b869e4f77fd7482b68c4c2
6,618
cxx
C++
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
core/teca_index_executive.cxx
Data-Scientist-Wannabe/TECA
feb0ae7eb23e031842ca958b85168f7fdcae7f06
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "teca_index_executive.h" #include "teca_config.h" #include "teca_common.h" #include <string> #include <sstream> #include <iostream> #include <utility> using std::cerr; using std::endl; // -------------------------------------------------------------------------- teca_index_executive::teca_index_executive() : start_index(0), end_index(-1), stride(1) { } // -------------------------------------------------------------------------- void teca_index_executive::set_index(long s) { this->start_index = std::max(0l, s); this->end_index = s; } // -------------------------------------------------------------------------- void teca_index_executive::set_start_index(long s) { this->start_index = std::max(0l, s); } // -------------------------------------------------------------------------- void teca_index_executive::set_end_index(long s) { this->end_index = s; } // -------------------------------------------------------------------------- void teca_index_executive::set_stride(long s) { this->stride = std::max(0l, s); } // -------------------------------------------------------------------------- void teca_index_executive::set_extent(unsigned long *ext) { this->set_extent({ext[0], ext[1], ext[2], ext[3], ext[4], ext[4]}); } // -------------------------------------------------------------------------- void teca_index_executive::set_extent(const std::vector<unsigned long> &ext) { this->extent = ext; } // -------------------------------------------------------------------------- void teca_index_executive::set_bounds(double *bds) { this->set_bounds({bds[0], bds[1], bds[2], bds[3], bds[4], bds[5]}); } // -------------------------------------------------------------------------- void teca_index_executive::set_bounds(const std::vector<double> &bds) { this->bounds = bds; } // -------------------------------------------------------------------------- void teca_index_executive::set_arrays(const std::vector<std::string> &v) { this->arrays = v; } // -------------------------------------------------------------------------- int teca_index_executive::initialize(MPI_Comm comm, const teca_metadata &md) { #if !defined(TECA_HAS_MPI) (void)comm; #endif this->requests.clear(); // locate the keys that enable us to know how many // requests we need to make and what key to use if (md.get("index_initializer_key", this->index_initializer_key)) { TECA_ERROR("No index initializer key has been specified") return -1; } if (md.get("index_request_key", this->index_request_key)) { TECA_ERROR("No index request key has been specified") return -1; } // locate available indices long n_indices = 0; if (md.get(this->index_initializer_key, n_indices)) { TECA_ERROR("metadata is missing the initializer key \"" << this->index_initializer_key << "\"") return -1; } // apply restriction long last = this->end_index >= 0 ? this->end_index : n_indices - 1; long first = ((this->start_index >= 0) && (this->start_index <= last)) ? this->start_index : 0; n_indices = last - first + 1; // partition indices across MPI ranks. each rank // will end up with a unique block of indices // to process. size_t rank = 0; size_t n_ranks = 1; #if defined(TECA_HAS_MPI) int is_init = 0; MPI_Initialized(&is_init); if (is_init) { int tmp = 0; MPI_Comm_size(comm, &tmp); n_ranks = tmp; MPI_Comm_rank(comm, &tmp); rank = tmp; } #endif size_t n_big_blocks = n_indices%n_ranks; size_t block_size = 1; size_t block_start = 0; if (rank < n_big_blocks) { block_size = n_indices/n_ranks + 1; block_start = block_size*rank; } else { block_size = n_indices/n_ranks; block_start = block_size*rank + n_big_blocks; } // consrtuct base request teca_metadata base_req; if (this->bounds.empty()) { if (this->extent.empty()) { std::vector<unsigned long> whole_extent(6, 0l); md.get("whole_extent", whole_extent); base_req.set("extent", whole_extent); } else base_req.set("extent", this->extent); } else base_req.set("bounds", this->bounds); base_req.set("arrays", this->arrays); // apply the base request to local indices. for (size_t i = 0; i < block_size; ++i) { size_t index = i + block_start + first; if ((index % this->stride) == 0) { this->requests.push_back(base_req); this->requests.back().set(this->index_request_key, index); } } // print some info about the set of requests if (this->get_verbose()) cerr << teca_parallel_id() << " teca_index_executive::initialize index_initializer_key=" << this->index_initializer_key << " index_request_key=" << this->index_request_key << " first=" << this->start_index << " last=" << this->end_index << " stride=" << this->stride << endl; return 0; } // -------------------------------------------------------------------------- teca_metadata teca_index_executive::get_next_request() { teca_metadata req; if (!this->requests.empty()) { req = this->requests.back(); this->requests.pop_back(); // print the details of the current request. this is a execution // progress indicator of where the run is at if (this->get_verbose()) { std::vector<unsigned long> ext; req.get("extent", ext); std::vector<double> bds; req.get("bounds", bds); unsigned long index; req.get(this->index_request_key, index); std::ostringstream oss; oss << teca_parallel_id() << " teca_index_executive::get_next_request " << this->index_request_key << "=" << index; if (bds.empty()) { if (!ext.empty()) oss << " extent=" << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5]; } else { oss << " bounds=" << bds[0] << ", " << bds[1] << ", " << bds[2] << ", " << bds[3] << ", " << bds[4] << ", " << bds[5]; } cerr << oss.str() << endl; } } return req; }
28.649351
88
0.487307
Data-Scientist-Wannabe
6928e167ced08d070afdc700b552d5dd9c6833de
624
cpp
C++
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Vanya and Lanterns/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n, l; cin >> n >> l; vector<int>lanterns(n); for (int i = 0; i < n; ++i) { cin >> lanterns[i]; } sort(lanterns.begin(), lanterns.end()); int maxx = 2*max(lanterns[0], l-lanterns[n-1]); for (int i = 1; i < n; ++i) { maxx=max(maxx, (lanterns[i]-lanterns[i-1])); } cout << maxx/2.0; }
23.111111
72
0.573718
wdjpng
692bf79c7d220200f498c249b7da064afde48f59
1,906
hpp
C++
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
asps/modbus/pdu/semantic/pdu_client.hpp
activesys/asps
36cc90a192d13df8669f9743f80a0662fe888d16
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The asps Authors. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Modbus PDU Client. #ifndef ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP #define ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP #include <functional> #include <asps/modbus/frame/adu_service.hpp> #include <asps/modbus/pdu/semantic/constant.hpp> #include <asps/modbus/pdu/semantic/data_model.hpp> #include <asps/modbus/pdu/session/client_session.hpp> namespace asps { namespace modbus { namespace pdu { using namespace std::placeholders; // Modbus PDU Client class pdu_client : public client_session_observer { public: pdu_client(frame::adu_service::pointer_type adu = frame::make_tcp_adu()) : adu_(adu) { session_.register_observer(this); adu_->set_handler(std::bind(&pdu_client::read_handler, this, _1)); } virtual ~pdu_client() {} public: void read_coils(uint16_t starting_address, uint16_t quantity_of_coils); void read_discrete_inputs(uint16_t starting_address, uint16_t quantity_of_inputs); public: virtual void on_read_coils(const coils& status) {} virtual void on_read_discrete_inputs(const discrete_inputs& status) {} virtual void on_exception(function_code fc, exception_code ec) {} private: virtual void update_send(const buffer_type& pdu) override; virtual void update_datas(const request::pointer_type& req, const mb_datas& datas) override; virtual void update_exception(const request::pointer_type& req, exception_code ec) override; private: void read_handler(const buffer_type& pdu); protected: frame::adu_service::pointer_type adu_; client_session session_; }; } // pdu } // modbus } // asps #endif // ASPS_MODBUS_PDU_SEMANTIC_CLIENT_HPP
28.878788
77
0.732424
activesys
692edafe41c3a64de468fbbbc2a38ba867907740
2,086
cpp
C++
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
1
2021-01-14T06:01:02.000Z
2021-01-14T06:01:02.000Z
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
8
2018-03-27T11:47:19.000Z
2018-11-12T06:02:12.000Z
solutions/0950.x-of-a-kind-in-a-deck-of-cards/0950.x-of-a-kind-in-a-deck-of-cards.1541745454.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
2
2020-04-30T09:47:01.000Z
2020-12-03T09:34:08.000Z
/* * [950] X of a Kind in a Deck of Cards * * https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/ * * algorithms * Easy (33.02%) * Total Accepted: 7.7K * Total Submissions: 23.2K * Testcase Example: '[1,2,3,4,4,3,2,1]' * * In a deck of cards, each card has an integer written on it. * * Return true if and only if you can choose X >= 2 such that it is possible to * split the entire deck into 1 or more groups of cards, where: * * * Each group has exactly X cards. * All the cards in each group have the same integer. * * * * * Example 1: * * * Input: [1,2,3,4,4,3,2,1] * Output: true * Explanation: Possible partition [1,1],[2,2],[3,3],[4,4] * * * * Example 2: * * * Input: [1,1,1,2,2,2,3,3] * Output: false * Explanation: No possible partition. * * * * Example 3: * * * Input: [1] * Output: false * Explanation: No possible partition. * * * * Example 4: * * * Input: [1,1] * Output: true * Explanation: Possible partition [1,1] * * * * Example 5: * * * Input: [1,1,2,2,2,2] * Output: true * Explanation: Possible partition [1,1],[2,2],[2,2] * * * * * * * * Note: * * * 1 <= deck.length <= 10000 * 0 <= deck[i] < 10000 * * * * * * * * * * * * */ class Solution { public: bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int, int> count; for (int d : deck) { count[d]++; } unordered_set<int> ocs; int mino = 10000; for (auto& e: count) { mino = min(mino, e.second); ocs.insert(e.second); } if (mino == 1) { return false; } for (int i = 2; i <= mino; i++) { if (all_divide(ocs, i)) { return true; } } return false; } private: bool all_divide(unordered_set<int>& ocs, int i) { for (int o : ocs) { if (o % i != 0) { return false; } } return true; } };
16.555556
79
0.490892
nettee
69327c89e8e8109949bbeecf1eff31b65c76f042
2,114
cpp
C++
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
3
2021-10-10T11:12:03.000Z
2021-11-04T16:46:57.000Z
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
patch/game/rapmaker.cpp
Tonyx97/TombMP
7eb2d265df2fe7312b7ed07dd5943736340b921c
[ "MIT" ]
null
null
null
#include <specific/stypes.h> #include "objects.h" #include "lara.h" #include "lot.h" #include "types.h" #define MAX_RAPTORS 5 #define LARA_TOO_CLOSE SQUARE(WALL_L * 4) int16_t RaptorItem[3] = { NO_ITEM, NO_ITEM, NO_ITEM }; void RaptorEmitterControl(int16_t item_num) { auto item = &items[item_num]; if (!(item->active) || item->timer <= 0) return; if (RaptorItem[0] == NO_ITEM) { for (int target_number = 0, i = 0; target_number < level_items; ++target_number) { auto target = &items[target_number]; if (target->object_number == RAPTOR && target->ai_bits == MODIFY) RaptorItem[i++] = target_number; if (i > 2) return; } return; } if (items[RaptorItem[0]].data != nullptr && items[RaptorItem[1]].data != nullptr && items[RaptorItem[2]].data != nullptr) return; int z = lara_item->pos.z_pos - item->pos.z_pos, x = lara_item->pos.x_pos - item->pos.x_pos, distance = (z * z) + (x * x); if (distance < LARA_TOO_CLOSE) return; if (item->item_flags[0] <= 0) { item->item_flags[0] = 255; item->timer -= 30; } else { --item->item_flags[0]; return; } int raptor_num = 0; for (int i = 0; i < 3; ++i, ++raptor_num) if (!items[RaptorItem[i]].data) break; auto raptor = &items[RaptorItem[raptor_num]]; raptor->pos = item->pos; raptor->anim_number = objects[raptor->object_number].anim_index; raptor->frame_number = anims[raptor->anim_number].frame_base; raptor->current_anim_state = raptor->goal_anim_state = anims[raptor->anim_number].current_anim_state; raptor->required_anim_state = 0; raptor->flags &= ~(ONESHOT | KILLED_ITEM | INVISIBLE); raptor->data = 0; raptor->status = ACTIVE; raptor->mesh_bits = 0xffffffff; raptor->hit_points = objects[raptor->object_number].hit_points; raptor->collidable = 1; if (raptor->active) RemoveActiveItem(RaptorItem[raptor_num]); AddActiveItem(RaptorItem[raptor_num]); ItemNewRoom(RaptorItem[raptor_num], item->room_number); EnableBaddieAI(RaptorItem[raptor_num], 1); } void InitialiseRaptorEmitter(int16_t item_number) { items[item_number].item_flags[0] = (item_number & 0x3) * 96; }
24.022727
122
0.685904
Tonyx97
6934c1945f8a1f4015897ef2f9f40e73e5587b80
2,823
cc
C++
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
test/LRUcacheSingletonTest.cc
vsdmars/cpp_libs
d3a67006e9c3bd4806945a42d8e9ae9b16aa5b7d
[ "MIT" ]
null
null
null
#include "lrucache_api.h" // posix header #include <arpa/inet.h> #include <sys/socket.h> #include <thread> #include <gtest/gtest.h> using std::thread; using namespace AtsPluginUtils; namespace AtsPluginUtils { constexpr int TEST_TYPE = 42; template<> struct CacheValue<static_cast<CACHE_VALUE_TYPE>(TEST_TYPE)> { int value; CacheValue() = default; }; using testCache = LRUC::ScalableLRUCache<int, CacheValue<static_cast<CACHE_VALUE_TYPE>(TEST_TYPE)>>; } // namespace AtsPluginUtils /** * create_IpAddress is a callable object taking IPv4 address as const char* and returns IpAddress * */ auto create_IpAddress = [](auto ipv4) -> IpAddress { sockaddr_in socket; socket.sin_family = AF_INET; socket.sin_port = 42; if (inet_pton(AF_INET, ipv4, &socket.sin_addr) == 1) { IpAddress ipa{(sockaddr*)& socket}; return ipa; } return IpAddress{}; }; /** * singletonTest tests the cache instances returned from different DSO * point to the same memory address. * Thus, the inserted key/value from one DSO can be retrieved from another DSO. * */ TEST(LRUcacheSingletonTest, singletonTest) { thread t1([] {init_cache1();}); thread t2([] {init_cache2();}); t1.join(); t2.join(); const char* ip1 = "192.168.1.1"; const char* ip2 = "192.168.1.2"; auto key1 = create_IpAddress(ip1); auto key2 = create_IpAddress(ip2); constexpr auto ts1 = 1'629'834'401; constexpr auto ts2 = 1'629'834'402; AtsPluginUtils::CacheValue<AtsPluginUtils::CACHE_VALUE_TYPE::TIME_ENTITY_LOOKUP_INFO> value1; AtsPluginUtils::CacheValue<AtsPluginUtils::CACHE_VALUE_TYPE::TIME_ENTITY_LOOKUP_INFO> value2; value1.expiryTs = ts1; value2.expiryTs = ts2; cache1_insert(key1, value1); auto retrieved_value1 = cache2_find(key1); EXPECT_EQ(retrieved_value1.expiryTs, ts1); cache2_insert(key2, value2); auto retrieved_value2 = cache1_find(key2); EXPECT_EQ(retrieved_value2.expiryTs, ts2); auto& cache_1 = get_cache1(); // retrieve cache from liblrucache1.so auto& cache_2 = get_cache2(); // retrieve cache from liblrucache2.so EXPECT_EQ(cache_1.capacity(), magic_cache_size); EXPECT_EQ(cache_1.capacity(), cache_2.capacity()); ASSERT_EQ(&cache_1, &cache_2); } /** * differentCacheValueTypeTest tests the cache insert key with different value type. * */ TEST(LRUcacheSingletonTest, differentCacheValueTypeTest) { auto cache = AtsPluginUtils::testCache{42, 4}; constexpr auto val = 1'629'834'401; AtsPluginUtils::CacheValue<static_cast<AtsPluginUtils::CACHE_VALUE_TYPE>(AtsPluginUtils::TEST_TYPE)> value; value.value = val; cache.insert(42, value); AtsPluginUtils::testCache::ConstAccessor ca; EXPECT_EQ(cache.find(ca, 42), true); EXPECT_EQ(ca->value, val); ASSERT_EQ(cache.size(), 1); EXPECT_EQ(cache.erase(42), 1); ASSERT_EQ(cache.size(), 0); }
26.885714
109
0.72972
vsdmars
693764b377374707b669ae6cd44e739a77dc6693
4,454
cpp
C++
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
src/options/didyoumean.cpp
FabianWolff/cvc4-debian
e38afe6cb10bdb79f0bae398b9605e4deae7578f
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file didyoumean.cpp ** \verbatim ** Top contributors (to current version): ** Kshitij Bansal, Tim King, Clark Barrett ** This file is part of the CVC4 project. ** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief did-you-mean style suggestions ** ** ``What do you mean? I don't understand.'' An attempt to be more ** helpful than that. Similar to one in git. ** ** There are no dependencies on CVC4 (except namespace). **/ #include "options/didyoumean.h" #include <iostream> #include <set> #include <sstream> #include <string> #include <vector> namespace CVC4 { std::vector<std::string> DidYouMean::getMatch(std::string input) { /** Magic numbers */ const int similarityThreshold = 7; const unsigned numMatchesThreshold = 10; typedef std::set<std::pair<int, std::string> > ScoreSet; ScoreSet scores; std::vector<std::string> ret; for (Words::const_iterator it = d_words.begin(); it != d_words.end(); ++it) { std::string s = (*it); if (s == input) { // if input matches AS-IS just return that ret.push_back(s); return ret; } int score; if (s.compare(0, input.size(), input) == 0) { score = 0; } else { score = editDistance(input, s) + 1; } scores.insert(make_pair(score, s)); } int min_score = scores.begin()->first; for (ScoreSet::const_iterator i = scores.begin(); i != scores.end(); ++i) { // add if score is overall not too big, and also not much close to // the score of the best suggestion if (i->first < similarityThreshold && i->first <= min_score + 1) { ret.push_back(i->second); #ifdef DIDYOUMEAN_DEBUG cout << i->second << ": " << i->first << std::endl; #endif } } if (ret.size() > numMatchesThreshold) { ret.resize(numMatchesThreshold); } return ret; } int DidYouMean::editDistance(const std::string& a, const std::string& b) { // input string: a // desired string: b const int swapCost = 0; const int substituteCost = 2; const int addCost = 1; const int deleteCost = 3; const int switchCaseCost = 0; int len1 = a.size(); int len2 = b.size(); int* C[3]; int ii; for (ii = 0; ii < 3; ++ii) { C[ii] = new int[len2 + 1]; } // int C[3][len2+1]; // cost for (int j = 0; j <= len2; ++j) { C[0][j] = j * addCost; } for (int i = 1; i <= len1; ++i) { int cur = i % 3; int prv = (i + 2) % 3; int pr2 = (i + 1) % 3; C[cur][0] = i * deleteCost; for (int j = 1; j <= len2; ++j) { C[cur][j] = 100000000; // INF if (a[i - 1] == b[j - 1]) { // match C[cur][j] = std::min(C[cur][j], C[prv][j - 1]); } else if (tolower(a[i - 1]) == tolower(b[j - 1])) { // switch case C[cur][j] = std::min(C[cur][j], C[prv][j - 1] + switchCaseCost); } else { // substitute C[cur][j] = std::min(C[cur][j], C[prv][j - 1] + substituteCost); } // swap if (i >= 2 && j >= 2 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) { C[cur][j] = std::min(C[cur][j], C[pr2][j - 2] + swapCost); } // add C[cur][j] = std::min(C[cur][j], C[cur][j - 1] + addCost); // delete C[cur][j] = std::min(C[cur][j], C[prv][j] + deleteCost); #ifdef DIDYOUMEAN_DEBUG1 std::cout << "C[" << cur << "][" << 0 << "] = " << C[cur][0] << std::endl; #endif } } int result = C[len1 % 3][len2]; for (ii = 0; ii < 3; ++ii) { delete[] C[ii]; } return result; } std::string DidYouMean::getMatchAsString(std::string input, int prefixNewLines, int suffixNewLines) { std::vector<std::string> matches = getMatch(input); std::ostringstream oss; if (matches.size() > 0) { while (prefixNewLines-- > 0) { oss << std::endl; } if (matches.size() == 1) { oss << "Did you mean this?"; } else { oss << "Did you mean any of these?"; } for (unsigned i = 0; i < matches.size(); ++i) { oss << "\n " << matches[i]; } while (suffixNewLines-- > 0) { oss << std::endl; } } return oss.str(); } } /* CVC4 namespace */
27.493827
80
0.540413
FabianWolff
6943a049660ee3277364c015dfb829533683e515
7,691
cc
C++
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
2
2017-02-23T09:55:54.000Z
2017-02-23T10:06:32.000Z
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
null
null
null
src/zjump.cc
vteromero/zjump
c8c0d38065f8779d144d05381f0945b5f0db43e3
[ "MIT" ]
null
null
null
/** Copyright (c) 2017 Vicente Romero. All rights reserved. Licensed under the MIT License. See LICENSE file in the project root for full license information. */ #include <cstdio> #include <cstring> #include <string> #include "compress.h" #include "constants.h" #include "decompress.h" using namespace std; struct ExecConfig { bool help_opt; bool decompress_opt; bool stdout_opt; bool force_opt; bool keep_opt; bool version_opt; bool license_opt; string in_file_name; string out_file_name; FILE *in_file; FILE *out_file; ExecConfig() { help_opt = false; decompress_opt = false; stdout_opt = false; force_opt = false; keep_opt = false; version_opt = false; license_opt = false; in_file = stdin; out_file = stdout; } ~ExecConfig() { if((in_file != nullptr) && (in_file != stdin)) { fclose(in_file); } if((out_file != nullptr) && (out_file != stdout)) { fclose(out_file); } } }; static const char *kZjumpCompressedExt = ".zjump"; static const char *kZjumpDecompressedExt = ".orig"; static void DisplayVersionNumber() { uint32_t major = kZjumpVersion / 10000; uint32_t minor = (kZjumpVersion / 100) % 100; uint32_t patch = kZjumpVersion % 100; fprintf(stderr, "zjump %u.%u.%u\n", major, minor, patch); } static void DisplayLicense() { fprintf(stderr, "Copyright (c) 2017 Vicente Romero. All rights reserved.\n" "Licensed under the MIT License. See LICENSE file, which is included in the\n" "zjump source distribution, for full license information.\n" ); } static void Usage(const char *name) { fprintf(stderr, "zjump, a data compressor/decompressor\n" "\n" "Usage: %s [OPTIONS] [FILE]\n" "\n" " -c, --stdout Write on standard output\n" " -d, --decompress Decompress FILE\n" " -f, --force Force to overwrite the output file\n" " -h, --help Output this help and exit\n" " -k, --keep Keep the input file (do not delete it)\n" " -L, --license Display software license\n" " -V, --version Display version number\n" "\n" "If no FILE is given, zjump compresses or decompresses\n" "from standard input to standard output." "\n", name); } static void SetOutputFileName(ExecConfig* config) { if(config->stdout_opt || (config->in_file_name.empty())) { return; } if(config->decompress_opt) { size_t last_dot = config->in_file_name.find_last_of('.'); if( (last_dot == string::npos) || (config->in_file_name.compare(last_dot, string::npos, kZjumpCompressedExt) != 0)) { config->out_file_name = config->in_file_name + kZjumpDecompressedExt; } else { config->out_file_name = config->in_file_name.substr(0, last_dot); } } else { config->out_file_name = config->in_file_name + kZjumpCompressedExt; } } static int ParseOptions(int argc, char **argv, ExecConfig* config) { for(int i=1; i<argc; ++i) { if((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "--stdout") == 0)) { config->stdout_opt = true; } else if((strcmp(argv[i], "-d") == 0) || (strcmp(argv[i], "--decompress") == 0)) { config->decompress_opt = true; } else if((strcmp(argv[i], "-f") == 0) || (strcmp(argv[i], "--force") == 0)) { config->force_opt = true; } else if((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0)) { config->help_opt = true; } else if((strcmp(argv[i], "-k") == 0) || (strcmp(argv[i], "--keep") == 0)) { config->keep_opt = true; } else if((strcmp(argv[i], "-L") == 0) || (strcmp(argv[i], "--license") == 0)) { config->license_opt = true; } else if((strcmp(argv[i], "-V") == 0) || (strcmp(argv[i], "--version") == 0)) { config->version_opt = true; } else if(argv[i][0] == '-') { fprintf(stderr, "Unrecognized option: '%s'\n", argv[i]); } else { return i; } } return argc; } static ZjumpErrorCode ValidateOptions(int argc, char **argv, int last_opt, ExecConfig* config) { if(config->help_opt) { return ZJUMP_NO_ERROR; } int last_args = argc - last_opt; if(last_args > 1) { fprintf(stderr, "Incorrect arguments. Use -h to display more information\n"); return ZJUMP_ERROR_ARGUMENT; } else if(last_args == 1) { config->in_file_name = argv[last_opt]; SetOutputFileName(config); } return ZJUMP_NO_ERROR; } static bool FileExists(const char* file_name) { FILE *file = fopen(file_name, "rb"); if(file == nullptr) { return false; } else { fclose(file); return true; } } static ZjumpErrorCode ValidateOutput(const ExecConfig& config) { if(config.force_opt) { return ZJUMP_NO_ERROR; } if(config.out_file_name.empty()) { return ZJUMP_NO_ERROR; } const char *out_file_name = config.out_file_name.c_str(); if(FileExists(out_file_name)) { fprintf(stderr, "Output file %s already exists.\n", out_file_name); return ZJUMP_ERROR_FILE; } return ZJUMP_NO_ERROR; } static ZjumpErrorCode OpenFiles(ExecConfig* config) { if(!config->in_file_name.empty()) { const char *in_file_name = config->in_file_name.c_str(); config->in_file = fopen(in_file_name, "rb"); if(config->in_file == nullptr) { perror(in_file_name); return ZJUMP_ERROR_FILE; } } if(!config->out_file_name.empty()) { const char *out_file_name = config->out_file_name.c_str(); config->out_file = fopen(out_file_name, "wb"); if(config->out_file == nullptr) { perror(out_file_name); return ZJUMP_ERROR_FILE; } } return ZJUMP_NO_ERROR; } static ZjumpErrorCode RemoveInput(const ExecConfig& config) { if(config.keep_opt) { return ZJUMP_NO_ERROR; } if(config.in_file == stdin) { return ZJUMP_NO_ERROR; } const char *in_file_name = config.in_file_name.c_str(); if(remove(in_file_name) != 0) { perror(in_file_name); return ZJUMP_ERROR_FILE; } return ZJUMP_NO_ERROR; } int main(int argc, char **argv) { ExecConfig config; int last_opt = ParseOptions(argc, argv, &config); int ret_code = ValidateOptions(argc, argv, last_opt, &config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } if(config.version_opt || config.license_opt) { DisplayVersionNumber(); DisplayLicense(); return ZJUMP_NO_ERROR; } if(config.help_opt) { Usage(argv[0]); return ZJUMP_NO_ERROR; } ret_code = ValidateOutput(config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } ret_code = OpenFiles(&config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } if(config.decompress_opt) { Decompressor decompressor; ret_code = decompressor.Decompress(config.in_file, config.out_file); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } } else { Compressor compressor; ret_code = compressor.Compress(config.in_file, config.out_file); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } } ret_code = RemoveInput(config); if(ret_code != ZJUMP_NO_ERROR) { return ret_code; } return ZJUMP_NO_ERROR; }
27.467857
96
0.593421
vteromero
69449ea720c73b0352bf124099774276b9843361
1,410
cpp
C++
engine/conversion/source/ArtifactDumper.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/conversion/source/ArtifactDumper.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/conversion/source/ArtifactDumper.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include <sstream> #include "ArtifactDumper.hpp" #include "Conversion.hpp" #include "ItemDumper.hpp" #include "TextKeys.hpp" using namespace std; ArtifactDumper::ArtifactDumper(const ItemMap& new_item_map, const GenerationValuesMap& new_igv_map, const uint new_num_cols) : item_map(new_item_map), igv_map(new_igv_map), num_cols(new_num_cols) { } // Loop through all the items in the game, and display info for artifacts. string ArtifactDumper::str() const { ostringstream ss; ss << String::centre(StringTable::get(TextKeys::GENERATED_ARTIFACTS), num_cols) << endl << endl; ss << get_artifacts() << endl; ss << endl; return ss.str(); } string ArtifactDumper::get_artifacts() const { ostringstream ss; for (const auto& item_pair : item_map) { ItemPtr item = item_pair.second; if (item != nullptr && item->get_artifact()) { auto igv_it = igv_map.find(item->get_base_id()); // Ensure we only show artifacts that have already been generated. if (igv_it != igv_map.end() && igv_it->second.is_maximum_reached()) { ItemDumper item_dumper(nullptr, item, false); // Ignore blindness checks because we're checking on globally generated // values, not what's in the creature's equipment or inventory. item_dumper.set_ignore_blindness_checks(true); ss << item_dumper.str(); } } } return ss.str(); }
26.111111
124
0.690071
sidav
6944e8a081f3a002f6638a7265f8665b6a7db528
3,368
cpp
C++
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
stream.cpp
ondra-novak/userver
4ba4797637fedbb49c8f448469d7143746102ee5
[ "MIT" ]
null
null
null
/* * stream.cpp * * Created on: 9. 1. 2021 * Author: ondra */ #include "stream.h" #include "async_provider.h" namespace userver { std::string_view SocketStream::read() { std::string_view out; if (curbuff.empty()) { if (!eof) { if (rdbuff.empty()) rdbuff.resize(1000); int sz = sock->read(rdbuff.data(), rdbuff.size()); if (sz == 0) { eof = true; } else { if (sz == static_cast<int>(rdbuff.size())) rdbuff.resize(sz*3/2); out = rdbuff; out = out.substr(0, sz); } } } else { std::swap(out, curbuff); } return out; } std::size_t SocketStream::maxWrBufferSize = 65536; void SocketStream::putBack(const std::string_view &pb) { curbuff = pb; } void SocketStream::write(const std::string_view &data) { wrbuff.append(data); if (wrbuff.size() >= wrbufflimit) { flush_lk(); } } bool SocketStream::timeouted() const { return sock->timeouted(); } void SocketStream::closeOutput() { flush_lk(); sock->closeOutput(); } void SocketStream::closeInput() { sock->closeInput(); } void SocketStream::flush() { flush_lk(); } ISocket& SocketStream::getSocket() const { return *sock; } bool SocketStream::writeNB(const std::string_view &data) { wrbuff.append(data); return (wrbuff.size() >= wrbufflimit); } void SocketStream::flushAsync(const std::string_view &data, bool firstCall, CallbackT<void(bool)> &&fn) { if (data.empty()) { getCurrentAsyncProvider().runAsync([fn = std::move(fn)] { fn(true); }); } else { sock->write(data.data(), data.size(), [this, data, firstCall, fn = std::move(fn)](int r) mutable { if (r <= 0) { wrbuff.clear(); fn(false); } else if (static_cast<std::size_t>(r) == data.size()) { wrbufflimit = std::min(wrbufflimit * 3 / 2, maxWrBufferSize); wrbuff.clear(); fn(true); } else { if (!firstCall) wrbufflimit = (r * 2 + 2) / 3 ; flushAsync(data.substr(r), false, std::move(fn)); } }); } } void SocketStream::flushAsync(CallbackT<void(bool)> &&fn) { if (wrbuff.empty()) { getCurrentAsyncProvider().runAsync([fn = std::move(fn)] { fn(true); }); } else { std::string_view s(wrbuff); flushAsync(s, true, std::move(fn)); } } void SocketStream::flush_lk() { std::string_view s(wrbuff); if (!s.empty()) { unsigned int wx = sock->write(s.data(),s.length()); bool rep = wx < s.length(); while (rep) { s = s.substr(wx); wx = sock->write(s.data(),s.length()); rep = wx < s.length(); if (rep && wx < wrbufflimit) { wrbufflimit = (wx * 2+2) / 3; } } wrbufflimit = std::min(wrbufflimit *3/2, maxWrBufferSize); wrbuff.clear(); } } void SocketStream::readAsync(CallbackT<void(const std::string_view &data)> &&fn) { std::string_view out; if (curbuff.empty() && !eof) { if (rdbuff.empty()) rdbuff.resize(1000); sock->read(rdbuff.data(), rdbuff.size(), [this, fn = std::move(fn)](int sz){ std::string_view out; if (sz == 0) { eof = true; } else { if (sz == static_cast<int>(rdbuff.size())) rdbuff.resize(sz*3/2); out = rdbuff; out = out.substr(0, sz); } fn(out); }); } else { std::swap(out,curbuff); getCurrentAsyncProvider().runAsync([fn = std::move(fn), out](){ fn(out); }); } } std::size_t SocketStream::getOutputBufferSize() const { return wrbufflimit; } void SocketStream::clearTimeout() { sock->clearTimeout(); eof = false; } }
20.662577
105
0.615202
ondra-novak
694510257d4c266d8c021b6aa035a78dc1ace904
1,395
cpp
C++
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
DP/House_Robber_198.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: House_Robber_198.cpp > Author: zzy > Mail: [email protected] > Created Time: Fri 22 Feb 2019 07:16:58 PM CST ********************************************************************** */ /* 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。 */ /* * dp: 最后一间房,要么偷,要么不偷 * 公式: f(n) = max(f(n-2) + a[n], f(n-1)) */ #include <vector> #include<gtest/gtest.h> #include <stdio.h> using std::vector; class Solution { public: int rob(vector<int>& nums) { if (nums.empty()) { return 0; } const int n = nums.size(); int money[n+1]; money[0] = 0; money[1] = nums[0]; for (int i = 2; i <= n; ++i) { money[i] = std::max(nums[i-1] + money[i-2], money[i-1]); } return money[n]; } }; TEST(test_rob, dp) { Solution s; std::vector<int> nums_1{1,2,3,1}; std::vector<int> nums_2{2,7,9,3,1}; EXPECT_EQ(s.rob(nums_1), 4); EXPECT_EQ(s.rob(nums_2), 12); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
19.647887
92
0.53405
obviouskkk
6947647fc635cb94d51eca5ba5c1346daba305ab
7,662
cpp
C++
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
4
2021-06-22T20:52:30.000Z
2022-02-04T00:19:44.000Z
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
null
null
null
user/drivers/acpi/src/bus/PciBus.cpp
tristanseifert/kush-os
1ffd595aae8f3dc880e798eff72365b8b6c631f0
[ "0BSD" ]
null
null
null
#include "PciBus.h" #include "acpi.h" #include "log.h" #include <driver/DrivermanClient.h> #include <mpack/mpack.h> using namespace acpi; std::string const PciBus::kBusName = "PCI"; std::string const PciBus::kDriverName = "AcpiPciRootBridge"; bool PciBus::gLogInterrupts = false; /** * Extracts the interrupt routing from a given ACPI object. * * @param object Handle to the PCI object (such as "\_SB.PCI0") in the ACPI namespace. */ void PciBus::getIrqRoutes(ACPI_HANDLE object) { ACPI_STATUS status; // set up the buffer ACPI_BUFFER buf; buf.Length = ACPI_ALLOCATE_BUFFER; buf.Pointer = nullptr; // read tables status = AcpiGetIrqRoutingTable(object, &buf); if(status != AE_OK) { Abort("AcpiGetIrqRoutingTable failed: %s", AcpiFormatException(status)); } // iterate over the interrupts std::byte *scan = reinterpret_cast<std::byte *>(buf.Pointer); while(true) { // get table and exit if we've reached the end auto table = reinterpret_cast<const ACPI_PCI_ROUTING_TABLE *>(scan); if(!table->Length) { break; } uint8_t slot = (table->Address >> 16); // static interrupt assignment if(!table->Source[0]) { // TODO: implement static IRQs Trace("gsi %u pin %u (slot %u)", table->SourceIndex, table->Pin, slot); } // the assignment is dynamic else { // get PCI link ACPI_HANDLE linkObject; status = AcpiGetHandle(object, table->Source, &linkObject); if(status != AE_OK) { Abort("failed to get source '%s': %s", table->Source, AcpiFormatException(status)); } // get associated IRQ ACPI_BUFFER resbuf; resbuf.Length = ACPI_ALLOCATE_BUFFER; resbuf.Pointer = NULL; status = AcpiGetCurrentResources(linkObject, &resbuf); if(status != AE_OK) { Abort("AcpiGetCurrentResources failed for '%s': %s", table->Source, AcpiFormatException(status)); } auto rscan = reinterpret_cast<std::byte *>(resbuf.Pointer); resource::Irq devIrq; while(1) { // bail if at end auto res = reinterpret_cast<ACPI_RESOURCE *>(rscan); if(res->Type == ACPI_RESOURCE_TYPE_END_TAG) { break; } // handle interrupt resource types else if(res->Type == ACPI_RESOURCE_TYPE_IRQ) { devIrq = resource::Irq(res->Data.Irq); break; } else if(res->Type == ACPI_RESOURCE_TYPE_EXTENDED_IRQ) { devIrq = resource::Irq(res->Data.ExtendedIrq); break; } // check next resource rscan += res->Length; } // release resource buffer free(resbuf.Pointer); // record the interrupt we got if(devIrq.flags == resource::IrqMode::Invalid) { Abort("failed to derive IRQ for device %d from '%s'", (int)slot, table->Source); } // modify an IRQ map entry given the current state auto yeeter = [&, devIrq](DeviceIrqInfo &map) { switch(table->Pin) { case 0: map.inta = devIrq; break; case 1: map.intb = devIrq; break; case 2: map.intc = devIrq; break; case 3: map.intd = devIrq; break; } }; // have we an existing object? if(this->irqMap.contains(slot)) { auto &map = this->irqMap.at(slot); yeeter(map); } else { DeviceIrqInfo map; yeeter(map); this->irqMap.emplace(slot, std::move(map)); } } // go to next scan += table->Length; } // clean up free(buf.Pointer); // XXX: print for(const auto &[device, map] : this->irqMap) { int a = -1, b = -1, c = -1, d = -1; if(map.inta) { a = (*map.inta).irq; } if(map.intb) { b = (*map.intb).irq; } if(map.intc) { c = (*map.intc).irq; } if(map.intd) { d = (*map.intd).irq; } if(gLogInterrupts) { Trace("Device %2u: INTA %2d INTB %2d INTC %2d INTD %2d", device, a, b, c, d); } } } /** * Loads a driver for this PCI bus. */ void PciBus::loadDriver(const uintptr_t) { std::vector<std::byte> aux; this->serializeAuxData(aux); auto rpc = libdriver::RpcClient::the(); // register driver this->drivermanPath = libdriver::RpcClient::the()->AddDevice(kAcpiBusRoot, kDriverName); Trace("PCI bus registered at %s", this->drivermanPath.c_str()); // set configuration rpc->SetDeviceProperty(this->drivermanPath, kAuxDataKey, aux); rpc->StartDevice(this->drivermanPath); } /** * Serializes the interrupt map to an msgpack object. It's basically identical to the * representation used in memory. Additionally, bus address is added. */ void PciBus::serializeAuxData(std::vector<std::byte> &out) { char *data; size_t size; // set up writer mpack_writer_t writer; mpack_writer_init_growable(&writer, &data, &size); mpack_start_map(&writer, 4); mpack_write_cstr(&writer, "bus"); mpack_write_u8(&writer, this->bus); mpack_write_cstr(&writer, "segment"); mpack_write_u8(&writer, this->segment); mpack_write_cstr(&writer, "address"); mpack_write_u32(&writer, this->address); // serialize mpack_write_cstr(&writer, "irqs"); if(!this->irqMap.empty()) { mpack_start_map(&writer, this->irqMap.size()); for(const auto &[device, info] : this->irqMap) { mpack_write_u8(&writer, device); info.serialize(&writer); } mpack_finish_map(&writer); } else { mpack_write_nil(&writer); } // clean up mpack_finish_map(&writer); auto status = mpack_writer_destroy(&writer); if(status != mpack_ok) { Warn("%s failed: %d", "mpack_writer_destroy", status); return; } // copy to output buffer out.resize(size); out.assign(reinterpret_cast<std::byte *>(data), reinterpret_cast<std::byte *>(data + size)); free(data); } /** * Serializes an interrupt info object. */ void PciBus::DeviceIrqInfo::serialize(mpack_writer_t *writer) const { mpack_start_map(writer, 4); // INTA //mpack_write_cstr(writer, "a"); mpack_write_u8(writer, 0); if(this->inta) { this->inta->serialize(writer); } else { mpack_write_nil(writer); } // INTB //mpack_write_cstr(writer, "b"); mpack_write_u8(writer, 1); if(this->intb) { this->intb->serialize(writer); } else { mpack_write_nil(writer); } // INTC //mpack_write_cstr(writer, "c"); mpack_write_u8(writer, 2); if(this->intc) { this->intc->serialize(writer); } else { mpack_write_nil(writer); } // INTD //mpack_write_cstr(writer, "d"); mpack_write_u8(writer, 3); if(this->intd) { this->intd->serialize(writer); } else { mpack_write_nil(writer); } // clean up mpack_finish_map(writer); }
28.273063
113
0.543461
tristanseifert
6947925b89d6354d11d2ebeb364896efe5c8f025
1,109
cpp
C++
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Graph/DetectCycleUndirected/DetectCycleUsingUnionFind.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not. Constraints: 1 ≤ V, E ≤ 10^5 Approach: This is another method based on Union-Find. This method assumes that the graph doesn’t contain any self-loops. We can keep track of the subsets in a 1D array, let’s call it parent[]. Time Complexity: O(V + E) Space Complexity: O(V) */ int findSet(int currentVertex, int parent[]) { if(parent[currentVertex]==-1) { return currentVertex; } findSet(parent[currentVertex], parent); } bool isCycle(int V,vector<int> g[] ) { int parent[V]; for(int i=0;i<V;i++) { parent[i] = -1; } int s1,s2; for(int i=0;i<V;i++) { vector<int>::iterator it; for(it=g[i].begin(); it!=g[i].end(); it++) { s1 = findSet(i, parent); s2 = findSet(*it, parent); if(s1!=s2) { parent[*it] = i; } else { if(parent[i]!=*it) { return true; } } } } return false; }
23.595745
121
0.540126
PrachieNaik
6948c4b730f092e9aa145ba7b471eb6a9749d816
267
cpp
C++
source/framework/partitioned_array/src/array_partition_uint64.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/partitioned_array/src/array_partition_uint64.cpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/partitioned_array/src/array_partition_uint64.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "lue/framework/partitioned_array/array_partition_impl.hpp" namespace lue { template class ArrayPartition<std::uint64_t, 0>; template class ArrayPartition<std::uint64_t, 1>; template class ArrayPartition<std::uint64_t, 2>; } // namespace lue
24.272727
67
0.749064
computationalgeography
694aadddf1dc57e6a0d2e3eb4ff5ac13043a5624
5,188
cpp
C++
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
lib/heif/Srcs/writer/auxiliaryimagewriter.cpp
anzksdk/tifig-by
17a306b27e6e2dd2992e1c0896312047541f4be0
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015-2017, Nokia Technologies Ltd. * All rights reserved. * * Licensed under the Nokia High-Efficiency Image File Format (HEIF) License (the "License"). * * You may not use the High-Efficiency Image File Format except in compliance with the License. * The License accompanies the software and can be found in the file "LICENSE.TXT". * * You may also obtain the License at: * https://nokiatech.github.io/heif/license.txt */ #include "auxiliaryimagewriter.hpp" #include "auxiliarytypeproperty.hpp" #include "avcconfigurationbox.hpp" #include "datastore.hpp" #include "hevcconfigurationbox.hpp" #include "imagespatialextentsproperty.hpp" #include "itempropertiesbox.hpp" #include "mediatypedefs.hpp" #include "metabox.hpp" #include "services.hpp" #include "writerconstants.hpp" #include <memory> #define ANDROID_STOI_HACK #define ANDROID_TO_STRING_HACK #include "androidhacks.hpp" AuxiliaryImageWriter::AuxiliaryImageWriter(const IsoMediaFile::Auxiliary& config, const std::uint32_t contextId) : RootMetaImageWriter({""}, contextId), mConfig(config) { } void AuxiliaryImageWriter::write(MetaBox* metaBox) { RootMetaImageWriter::initWrite(); storeValue("uniq_bsid", std::to_string(mConfig.uniq_bsid)); storeValue("capsulation", META_ENCAPSULATION); RootMetaImageWriter::parseInputBitStream(mConfig.file_path, mConfig.code_type); ItemSet itemIds = addItemReferences(metaBox); ilocWrite(metaBox, itemIds); iinfWrite(metaBox, itemIds); iprpWrite(metaBox, itemIds); } void AuxiliaryImageWriter::ilocWrite(MetaBox* metaBox, const ItemSet& itemIds) const { for (const auto& item : mMetaItems) { if (itemIds.count(item.mId)) { metaBox->addIloc(item.mId, item.mOffset, item.mLength, getBaseOffset()); } } } void AuxiliaryImageWriter::iinfWrite(MetaBox* metaBox, const ItemSet& itemIds) const { for (const auto& item : mMetaItems) { if (itemIds.count(item.mId)) { metaBox->addItem(item.mId, item.mType, item.mName, mConfig.hidden); } } } void AuxiliaryImageWriter::iprpWrite(MetaBox* metaBox, const ItemSet& itemIds) const { std::vector<std::uint32_t> itemIdVector; for (const auto id : itemIds) { itemIdVector.push_back(id); } RootMetaImageWriter::iprpWrite(metaBox); // Add 'auxC' property auto auxBox = std::make_shared<AuxiliaryTypeProperty>(); auxBox->setAuxType(mConfig.urn); metaBox->addProperty(auxBox, itemIdVector, true); } AuxiliaryImageWriter::ItemSet AuxiliaryImageWriter::addItemReferences(MetaBox* metaBox) const { ItemId fromId = mMetaItems.at(0).mId; ItemSet itemIds; if (mConfig.idxs_list.size() == 0) { // No idxs_list was given, so assume 1:1 mapping for referenced image items and auxiliary image items, or // map an auxiliary image to every master if there is only one. const std::vector<std::string> masterImageIds = getMasterStoreValue("item_indx"); for (size_t i = 0; i < masterImageIds.size(); ++i) { if (mMetaItems.size() > 1) { fromId = mMetaItems.at(i).mId; } metaBox->addItemReference("auxl", fromId, std::stoi(masterImageIds.at(i))); itemIds.insert(fromId); } } else { // idxs_list was given, so set the first auxiliary image for all images listed. const ReferenceToItemIdMap referenceMap = createReferenceToItemIdMap(); for (size_t i = 0; i < mConfig.refs_list.size(); ++i) { const UniqBsid masterUniqBsid = mConfig.refs_list.at(i); const ItemIdVector& indexList = mConfig.idxs_list.at(i); for (const auto index : indexList) { const ItemId masterImageId = referenceMap.at(masterUniqBsid).at(index - 1); metaBox->addItemReference("auxl", fromId, masterImageId); itemIds.insert(fromId); } } } return itemIds; } /// @todo This is common with derived item writer and should be refactored. AuxiliaryImageWriter::ReferenceToItemIdMap AuxiliaryImageWriter::createReferenceToItemIdMap() const { ReferenceToItemIdMap referenceToItemIdMap; // Add meta master contexts to the map const std::vector<std::uint32_t> storeIds = DataServe::getStoreIds(); for (const auto storeId : storeIds) { const std::shared_ptr<DataStore> dataStore = DataServe::getStore(storeId); if (dataStore->isValueSet("uniq_bsid") && dataStore->isValueSet("capsulation") && dataStore->getValue("capsulation").at(0) == META_ENCAPSULATION) { const UniqBsid uniqBsid = std::stoi(dataStore->getValue("uniq_bsid").at(0)); const std::vector<std::string> itemIdStrings = dataStore->getValue("item_indx"); ItemIdVector itemIds; for (const auto& itemId : itemIdStrings) { itemIds.push_back(std::stoi(itemId)); } referenceToItemIdMap.insert( { uniqBsid, itemIds }); } } return referenceToItemIdMap; }
33.25641
114
0.667887
anzksdk
694e41b62fd18581a35e497b57379741b0f936eb
583
cc
C++
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/bind/03.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
/* bind()绑定时参数个数固定,类型需匹配 */ #include <iostream> #include <functional> using namespace std; void func3(int n1, int n2, int n3) { cout << n1 << ' ' << n2 << ' ' << n3 << endl; } void test3_1() { auto f3 = std::bind(func3, placeholders::_1, 101); //f3(11); // 编译错误,因为bind函数中少了一个参数 } void test3_2() { auto f3 = std::bind(func3, placeholders::_1, 101, 102, 103); //f3(11); // 编译错误,因为bind函数中多了一个参数 } void test3_3() { auto f3 = std::bind(func3, placeholders::_1, "test", placeholders::_1); //f3(11); // 编译错误,第二个参数类型不匹配,无法将参数 2 从“const char *”转换为“int” }
23.32
75
0.600343
chanchann
695075a6022cc3460f34c545bcc6ee5984704557
2,104
cpp
C++
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
1
2018-08-13T04:01:11.000Z
2018-08-13T04:01:11.000Z
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
null
null
null
test/spec/ts/psi/pat_spec.cpp
mrk21/ts-processor
965d19939558e4c956bee7d35167f7483411c755
[ "MIT" ]
1
2018-09-23T03:36:20.000Z
2018-09-23T03:36:20.000Z
#include <bandit_with_gmock/bandit_with_gmock.hpp> #include <ts_processor/ts/data.hpp> #include <ts_processor/ts/psi/pat.hpp> #include <bitfield/iostream.hpp> namespace ts_processor { namespace ts { namespace psi { go_bandit([]{ using namespace bandit; describe("ts::psi::pat", [&]{ ts::data data; auto equals_v = [](pat::pid_type v){ return Equals(v); }; before_each([&]{ ts::packet packet{ #include <fixture/ts/psi/pat/single_packet.cpp> }; data.reset(packet.pid); data.push(packet); }); describe("#sections", [&]{ it("should iterate each fieldset in the section list", [&]{ auto & sections = data->psi.get<pat>()->sections; auto it = sections.begin(); auto end = sections.end(); AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::network)); AssertThat(it->pid, Equals(0x0010)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x0101)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x0102)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x1FC8)); ++it; AssertThat(it, not Equals(end)); AssertThat(it->type(), equals_v(pat::pid_type::program_map)); AssertThat(it->pid, Equals(0x1FC9)); ++it; AssertThat(it, Equals(end)); }); }); }); }); }}}
33.935484
77
0.475285
mrk21
6950c2cf28f88da37efe9b1e4c84267ceda1962b
7,988
inl
C++
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
5
2015-09-22T02:33:34.000Z
2018-08-29T07:37:54.000Z
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
1
2018-12-12T12:08:28.000Z
2018-12-13T06:14:54.000Z
ssd/octree/OctreeCache.inl
csiro-workspace/pointcloudplugin
815dd598ccf3780739b1ecae086ee78daa94ed5d
[ "BSD-3-Clause" ]
4
2015-03-04T00:09:18.000Z
2020-09-08T02:58:06.000Z
/* Copyright (c) 2013, Fatih Calakli and Daniel Moreno 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 Brown University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(_MSC_VER) && (_MSC_VER<1600) // VS2008 defines std::unordered_map as std::tr1::unordered_map namespace std {using namespace std::tr1;}; #endif template <typename Octree> void OctreeCache<Octree>::clear(void) { _cells.clear(); _vertices.clear(); _cellmap.clear(); _vertexmap.clear(); } template <typename Octree> void OctreeCache<Octree>::build(Octree & octree) { static const size_t MORTON_TO_TAUBIN_VERTEX_ORDER[8] = { 0, 4, 2, 6, 1, 5, 3, 7 }; // 0 1 2 3 4 5 6 7 _octree = &octree; size_t cell_count = octree.getNumberOfCells(); size_t vertex_count = octree.getNumberOfVertices(); _cells.clear(); _cells.resize(cell_count); _vertices.clear(); _vertices.resize(vertex_count); _cellmap.clear(); _cellmap.rehash(cell_count); _vertexmap.clear(); _vertexmap.rehash(vertex_count); size_t index = 0; size_t v_index = 0; for (typename Octree::cell_iterator iter=octree.cell_begin(); iter!=octree.cell_end(); ++iter) { //original key typename Octree::CellKey cellA = (*iter).first; //mapped key size_t index_a; typename CellMap::const_iterator map_a = _cellmap.find(cellA); if (map_a==_cellmap.end()) { //not found: create _cellmap[cellA] = index; index_a = index; ++index; } else { //found index_a = map_a->second; } //cache CellCache & cache_a = _cells[index_a]; cache_a.key = cellA; //save user data (first point in partition) //cache_a.data = iter->second->data; cache_a.data = (*iter).second; //save cell coords octree.getCellCoords(cellA, cache_a.cell); //make neighbor edges typename Octree::CellKey neighbor_keys[6]; octree.getFaceNeighborKeys(cellA, neighbor_keys); typename Octree::Cell neighbors[6] = { octree.getCellFirstAncestor(neighbor_keys[0]), octree.getCellFirstAncestor(neighbor_keys[1]), octree.getCellFirstAncestor(neighbor_keys[2]), octree.getCellFirstAncestor(neighbor_keys[3]), octree.getCellFirstAncestor(neighbor_keys[4]), octree.getCellFirstAncestor(neighbor_keys[5])}; std::vector<size_t> & edges_a = cache_a.edges; for (size_t i=0; i<6; ++i) { typename Octree::CellKey cellB = neighbors[i].first; if (cellB==octree.INVALID_CELL_KEY) { continue; } //mapped key size_t index_b; typename CellMap::const_iterator map_b = _cellmap.find(cellB); if (map_b==_cellmap.end()) { //not found: create _cellmap[cellB] = index; index_b = index; ++index; } else { //found index_b = map_b->second; } if (cellB<cellA) { if (std::find(edges_a.begin(), edges_a.end(), index_b)==edges_a.end()) { edges_a.push_back(index_b); } } else { std::vector<size_t> & edges_b = _cells[index_b].edges; if (std::find(edges_b.begin(), edges_b.end(), index_a)==edges_b.end()) { edges_b.push_back(index_a); } } } //get current cell vertices typename Octree::Vertex vertices[8]; octree.getVertices(cellA, vertices); size_t * vertices_a = cache_a.vertices; for (size_t i=0; i<8; ++i) { //original key typename Octree::VertexKey v = vertices[i].first; //mapped key size_t j; typename VertexMap::const_iterator map_v = _vertexmap.find(v); if (map_v==_vertexmap.end()) { //not found: add _vertexmap[v] = v_index; _vertices[v_index] = vertices[i].second; j = v_index; ++v_index; } else { //found j = map_v->second; } //save in the current cell vertices_a[MORTON_TO_TAUBIN_VERTEX_ORDER[i]] = j; } }//for each cell } template <typename Octree> void OctreeCache<Octree>::getFaceNeighborKeys(CellKey key, CellKey neighbors[6]) const { std::vector<size_t> const& edges = _cells[key].edges; std::vector<size_t>::const_iterator iter = edges.begin(); for (size_t i=0; i<6; ++i) { neighbors[i] = (iter==edges.end() ? INVALID_CELL_KEY : *iter++); } } template <typename Octree> void OctreeCache<Octree>::getCellNeighborKeys(CellKey key, const size_t * direction, CellKey * neighbors) const { typename Octree::CellKey original_neighbors[27]; _octree->getCellNeighborKeys(_cells[key].key, direction, original_neighbors); for (size_t i=0; original_neighbors[i]!=MAX_VALUE; ++i) { neighbors[i] = _cellmap.find(original_neighbors[i])->second; } } template <typename Octree> typename OctreeCache<Octree>::Cell OctreeCache<Octree>::getCellFirstAncestor(CellKey key) { //this is just exists, we cannot do better //assert(false); //just a warning abut the incomplete implementation here if (key<_cells.size()) { return Cell(key, _cells[key].data); } //not found return Cell(); } template <typename Octree> void OctreeCache<Octree>::getVertices(CellKey key, Vertex vertices[8]) { if (key<_cells.size()) { const size_t * v = _cells[key].vertices; vertices[0] = Vertex(v[0], _vertices[v[0]]); vertices[1] = Vertex(v[1], _vertices[v[1]]); vertices[2] = Vertex(v[2], _vertices[v[2]]); vertices[3] = Vertex(v[3], _vertices[v[3]]); vertices[4] = Vertex(v[4], _vertices[v[4]]); vertices[5] = Vertex(v[5], _vertices[v[5]]); vertices[6] = Vertex(v[6], _vertices[v[6]]); vertices[7] = Vertex(v[7], _vertices[v[7]]); } //not found }
35.660714
138
0.591888
csiro-workspace
6956574a542563798f6067be8bd422597f891254
529
hpp
C++
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
src/application/appWindow.hpp
giffi-dev/GeimBoi
6cf4f8cc3c07569d23bc70e2fa921ac870fd16f1
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <thread> #include <SDL2/SDL.h> #include "../core/gbGameBoy.hpp" namespace Giffi { class appWindow { public: // Retruns true on success static void Init(); static void Run(); static void CleanUp(); private: static bool ShouldWindowClose(); static void DoEvents(); public: static std::shared_ptr<gbGameBoy> mGameBoy; static bool mClosing; private: static SDL_Renderer* mRenderer; static SDL_Window* mWindow; appWindow() = delete; ~appWindow() = delete; }; } // Namespace
14.694444
44
0.718336
giffi-dev
695a43ee250ed0289249ded550bd3162e6a1419a
2,082
hpp
C++
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/lib/cost_model/cost_feature.hpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#pragma once #include <map> #include "all_type_variant.hpp" #include "types.hpp" namespace opossum { /** * List of features usable in AbstractCostModels. * * Using enum to provide the unified "AbstractCostFeatureProxy" to access the same features for LQPs and PQPs. * Also, this makes it easy to specify Cost formulas from data only, as e.g. CostModelRuntime does. */ enum class CostFeature { /** * Numerical features */ LeftInputRowCount, RightInputRowCount, InputRowCountProduct, // LeftInputRowCount * RightInputRowCount LeftInputReferenceRowCount, RightInputReferenceRowCount, // *InputRowCount if the input is References, 0 otherwise LeftInputRowCountLogN, RightInputRowCountLogN, // *InputRowCount * log(*InputRowCount) LargerInputRowCount, SmallerInputRowCount, // Major = Input with more rows, Minor = Input with less rows LargerInputReferenceRowCount, SmallerInputReferenceRowCount, OutputRowCount, OutputReferenceRowCount, // If input is References, then OutputRowCount. 0 otherwise. /** * Categorical features */ LeftDataType, RightDataType, // Only valid for Predicated Joins, TableScans PredicateCondition, // Only valid for Predicated Joins, TableScans /** * Boolean features */ LeftInputIsReferences, RightInputIsReferences, // *Input is References RightOperandIsColumn, // Only valid for TableScans LeftInputIsMajor // LeftInputRowCount > RightInputRowCount }; using CostFeatureWeights = std::map<CostFeature, float>; /** * Wraps a Variant of all data types for CostFeatues and provides getters for the member types of the variants that * perform type checking at runtime. */ struct CostFeatureVariant { public: template <typename T> CostFeatureVariant(const T& value) : value(value) {} // NOLINT - implicit conversion is intended bool boolean() const; float scalar() const; DataType data_type() const; PredicateCondition predicate_condition() const; boost::variant<float, DataType, PredicateCondition, bool> value; }; } // namespace opossum
29.742857
115
0.747839
IanJamesMcKay
695d90ca7d2170399ec7ba8c66ab5355e1365be4
363
cpp
C++
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
null
null
null
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
null
null
null
2022/semana0/hw_0+/i.cpp
imeplusplus/ps
bc5b0539ce26b023962ca0f87e05027edf8d04cb
[ "MIT" ]
1
2022-03-19T16:36:09.000Z
2022-03-19T16:36:09.000Z
#include <bits/stdc++.h> using namespace std; const int N = 100; int f[N]; int main(){ int n, m; scanf("%d%d",&n, &m); for(int i = 0; i < m; i++) scanf("%d", &f[i]); sort(f, f + m); int ans = f[n-1] - f[0]; for(int i = 0; i + n - 1 < m; i++){ ans = min(ans, f[i + n - 1] - f[i]); } printf("%d\n", ans); return 0; }
18.15
50
0.424242
imeplusplus
696037a3bc442b3bb621e969d50de7e921795a43
950
hpp
C++
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
55
2018-06-19T08:22:47.000Z
2022-03-30T01:02:59.000Z
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
null
null
null
32 - Spawning Projectiles/src/C_ProjectileAttack.hpp
ThatGamesGuy/that_platform_game
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
[ "MIT" ]
21
2019-04-19T15:39:08.000Z
2022-02-20T11:21:13.000Z
#ifndef C_ProjectileAttack_hpp #define C_ProjectileAttack_hpp #include "Component.hpp" #include "C_Animation.hpp" #include "Input.hpp" #include "ObjectCollection.hpp" #include "WorkingDirectory.hpp" class C_ProjectileAttack : public Component { public: C_ProjectileAttack(Object* owner); void Awake() override; void Start() override; void Update(float deltaTime) override; void SetInput(Input* input); void SetObjectCollection(ObjectCollection* objects); void SetWorkingDirectory(WorkingDirectory* workingDirectory); void SetTextureAllocator(ResourceAllocator<sf::Texture>* textureAllocator); private: void SpawnProjectile(); std::shared_ptr<C_Animation> animation; Input* input; ObjectCollection* objects; WorkingDirectory* workingDirectory; ResourceAllocator<sf::Texture>* textureAllocator; int projectileTextureID; }; #endif /* C_ProjectileAttack_hpp */
25
79
0.742105
ThatGamesGuy
696126e293cc4b8ef990ec222c6fca82d0914430
1,241
cpp
C++
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/stats/src/Utility_SampleMomentCollection.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_SampleMomentCollection.cpp //! \author Alex Robinson //! \brief The sample moment collection class definition //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "FRENSIE_Archives.hpp" #include "Utility_SampleMomentCollection.hpp" EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,1,2> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,1,2> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,2,1> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,2,1> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,1,2,3,4> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,1,2,3,4> ); EXPLICIT_TEMPLATE_CLASS_INST( Utility::SampleMomentCollection<double,4,3,2,1> ); EXPLICIT_CLASS_SAVE_LOAD_INST( Utility::SampleMomentCollection<double,4,3,2,1> ); //---------------------------------------------------------------------------// // end Utility_SampleMomentCollection.cpp //---------------------------------------------------------------------------//
44.321429
81
0.603546
bam241
6963d1bb9788c97622a89edfdf28a71440a7195b
1,268
cc
C++
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
cpp/sorting/insertion_sort.cc
stn/algorithms
435c6b1bcdc042553c13a711d20f6d871988c251
[ "Apache-2.0" ]
null
null
null
#include "insertion_sort.h" void insertion_sort(int *arr, int n) { for (int i = 1; i < n; ++i) { for (int j = i; j > 0; --j) { if (arr[j] < arr[j - 1]) { int tmp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = tmp; } } } } void insertion_sort2(int *arr, int n) { for (int i = 1; i < n; ++i) { int tmp = arr[i]; // search the position where the value is smaller than or equals to tmp. int j; for (j = i; j > 0; --j) { if (arr[j - 1] <= tmp) { break; } arr[j] = arr[j - 1]; } arr[j] = tmp; } } void insertion_sort3(int *arr, int n) { if (n == 0) return; int min_pos = n - 1; for (int i = n - 1; i > 0; --i) { if (arr[i - 1] < arr[min_pos]) { min_pos = i - 1; } } int tmp = arr[min_pos]; arr[min_pos] = arr[0]; arr[0] = tmp; for (int i = 2; i < n; ++i) { int tmp = arr[i]; // search the position where the value is smaller than or equals to tmp. int j = i; while (tmp < arr[j - 1]) { arr[j] = arr[j - 1]; --j; } arr[j] = tmp; } }
23.481481
80
0.391956
stn
69667186065462c9306a5071a4ddc0aac6fb719b
1,447
cpp
C++
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/Declarations/PackageDeclaration.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
#include "PackageDeclaration.hpp" #include <assert.h> namespace Dwarf { PackageDeclaration::PackageDeclaration (std::string name, std::vector<Declaration *> declarationsInside) : name_ (name), declarationsInside_ (declarationsInside) { } PackageDeclaration::~PackageDeclaration () { if (!declarationsInside_.empty ()) for (int index = 0; index < declarationsInside_.size (); index++) delete declarationsInside_.at (index); declarationsInside_.clear (); } Declaration *PackageDeclaration::GetDeclarationByIndex (int index) { assert (index < declarationsInside_.size ()); return declarationsInside_.at (index); } int PackageDeclaration::GetDeclarationsCount () { return declarationsInside_.size (); } std::string PackageDeclaration::GetName () { return name_; } std::string PackageDeclaration::GetType () { return "Package"; } std::string PackageDeclaration::ToString (int addSpacesIndentation) { std::string result; std::string indent = ""; if (addSpacesIndentation > 0) for (int index = 0; index < addSpacesIndentation; index++) indent += " "; result += indent + "[package " + name_ + "; content:\n"; for (int index = 0; index < declarationsInside_.size (); index++) result += declarationsInside_.at (index)->ToString (addSpacesIndentation + 4) + "\n"; result += indent + "end of package " + name_ + "]"; return result; } }
24.525424
106
0.67519
KonstantinTomashevich
696bc84d688fd35ea25b6456adca2b8d8b5a2073
4,894
hpp
C++
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
1
2022-02-08T14:01:20.000Z
2022-02-08T14:01:20.000Z
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
null
null
null
Native/Blackberry-Cascades/pushCollector/src/app.hpp
robertrumney/pushwoosh-sdk-samples
55ccad683de8cec2f751ff1778045d04b9621c7e
[ "MIT" ]
null
null
null
/*! * Copyright (c) 2012, 2013 BlackBerry Limited. * * 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 APP_HPP #define APP_HPP #include "pushwoosh/PushNotificationService.h" #include "service/PushHandler.hpp" #include <bb/cascades/GroupDataModel> #include <bb/system/InvokeManager> #include <bb/system/SystemCredentialsPrompt> class PushContentController; class App : public QObject { Q_OBJECT // The data model that contains all received pushes Q_PROPERTY(bb::cascades::GroupDataModel* model READ model CONSTANT) Q_PROPERTY(bool modelIsEmpty READ modelIsEmpty NOTIFY modelIsEmptyChanged) // The title and body text for the notification dialog Q_PROPERTY(QString notificationTitle READ notificationTitle NOTIFY notificationChanged) Q_PROPERTY(QString notificationBody READ notificationBody NOTIFY notificationChanged) // The title and body text for the activity dialog Q_PROPERTY(QString activityDialogTitle READ activityDialogTitle NOTIFY activityDialogChanged) Q_PROPERTY(QString activityDialogBody READ activityDialogBody NOTIFY activityDialogChanged) // The controller object for the push content page Q_PROPERTY(PushContentController* currentPushContent READ currentPushContent CONSTANT) public: App(); /** * Calls the push service create channel */ Q_INVOKABLE void createChannel(); /** * Calls the push service destroy channel */ Q_INVOKABLE void destroyChannel(); Q_INVOKABLE void deletePush(const QVariantMap &item); Q_INVOKABLE void deleteAllPushes(); Q_INVOKABLE void markAllPushesAsRead(); /** * Marks the passed push as current one and prepares the controller * object of the PushContentPage. */ Q_INVOKABLE void selectPush(const QVariantList &indexPath); Q_INVOKABLE QString convertToUtf8String(const QVariant &pushContent); public Q_SLOTS: void onInvoked(const bb::system::InvokeRequest &request); void registeredForPushNotifications(const QString & token); void errorRegisteringForPushNotifications(const QString & error); void onNoPushServiceConnection(); void onFullscreen(); void setTagsFinished(PWRequest * request); void getTagsFinished(PWRequest * request); Q_SIGNALS: void modelIsEmptyChanged(); void notificationChanged(); void activityDialogChanged(); void openActivityDialog(); void closeActivityDialog(); private: // A helper function to initialize the push session void initializePushSession(); bool validateUser(const QString &dialogTitle, const QString &username, const QString &password); void setPromptDefaultText(bb::system::SystemCredentialsPrompt* prompt,const QString &username, const QString &password); void pushNotificationHandler(bb::network::PushPayload &pushPayload); void showDialog(const QString &title, const QString &message); void openActivityDialog(const QString &title, const QString &message); // used to open and display a push when a notification is selected in the BlackBerry Hub void openPush(QByteArray pushContent); // a helper function which marks the push as read, and updates the displayed push content void updatePushContent(Push &push, const QVariantList &indexPath); // The accessor methods of the properties bb::cascades::GroupDataModel* model() const; bool modelIsEmpty() const; QString notificationTitle() const; QString notificationBody() const; QString activityDialogTitle() const; QString activityDialogBody() const; PushContentController* currentPushContent() const; // The manager object to react to invocations bb::system::InvokeManager *m_invokeManager; PushNotificationService m_pushNotificationService; PushHandler m_pushHandler; // Whether or not the application has at some point in time been running in the foreground bool m_hasBeenInForeground; // Whether or not the Configuration is in the process of being saved bool m_configSaveAction; // The controller object for the push content page PushContentController* m_pushContentController; // The property values bb::cascades::GroupDataModel *m_model; QString m_notificationTitle; QString m_notificationBody; QString m_activityDialogTitle; QString m_activityDialogBody; bool m_launchApplicationOnPush; }; #endif
33.751724
124
0.759297
robertrumney
69727009d55ca59e3f3d27bf829c440bb003129e
247
cpp
C++
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
VRP.FGA_2022/FirstIteration/Chromosome.cpp
DimaSidorenko/VRP.FGA_2022
3f08d9c976c9f86a25cdf51f287e3fc5b75c7451
[ "MIT" ]
null
null
null
#include "Chromosome.h" Chromosome::Chromosome() : genes() {}; Chromosome::Chromosome(int32_t size) { genes.resize(size); for (size_t i = 0; i < size; i++) { genes[i] = Gene(size); } } size_t Chromosome::Size() { return genes.size(); }
13
36
0.62753
DimaSidorenko
69755c97c66a733c90f12ed00a62408cd847e140
459
cpp
C++
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Codechef/Monthly Long Off/aug/learn.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> using namespace std; #define FOR(i, n) for (int i = 1; i <= n; ++i) int main() { int n, m, a, b, c; int w[320][320]; long long s; scanf("%d", &n); FOR(i, n) FOR(j, n) scanf("%d", &w[i][j]); scanf("%d", &m); FOR(k, m) { scanf("%d%d%d", &a, &b, &c); s = 0; FOR(i, n) FOR(j, n) s += (w[i][j] = min(w[i][j], min(w[i][a] + c + w[b][j], w[i][b] + c + w[a][j]))); printf("%I64d\n", s / 2); } return 0; }
17.653846
103
0.457516
TiwariAnil
6981a6356647992695df325bb03489f783c4828d
37,810
cc
C++
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
src/trace_processor/importers/proto/graphics_event_parser.cc
kuscsik/perfetto
41874a94cbe332d4a253fe870af279cdd32bfab0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/importers/proto/graphics_event_parser.h" #include <inttypes.h> #include "perfetto/ext/base/utils.h" #include "perfetto/protozero/field.h" #include "src/trace_processor/importers/common/args_tracker.h" #include "src/trace_processor/importers/common/event_tracker.h" #include "src/trace_processor/importers/common/process_tracker.h" #include "src/trace_processor/importers/common/slice_tracker.h" #include "src/trace_processor/importers/common/track_tracker.h" #include "src/trace_processor/storage/trace_storage.h" #include "src/trace_processor/types/trace_processor_context.h" #include "protos/perfetto/common/gpu_counter_descriptor.pbzero.h" #include "protos/perfetto/trace/android/graphics_frame_event.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_counter_event.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_log.pbzero.h" #include "protos/perfetto/trace/gpu/gpu_render_stage_event.pbzero.h" #include "protos/perfetto/trace/gpu/vulkan_api_event.pbzero.h" #include "protos/perfetto/trace/gpu/vulkan_memory_event.pbzero.h" #include "protos/perfetto/trace/interned_data/interned_data.pbzero.h" namespace perfetto { namespace trace_processor { namespace { // https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkObjectType.html typedef enum VkObjectType { VK_OBJECT_TYPE_UNKNOWN = 0, VK_OBJECT_TYPE_INSTANCE = 1, VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2, VK_OBJECT_TYPE_DEVICE = 3, VK_OBJECT_TYPE_QUEUE = 4, VK_OBJECT_TYPE_SEMAPHORE = 5, VK_OBJECT_TYPE_COMMAND_BUFFER = 6, VK_OBJECT_TYPE_FENCE = 7, VK_OBJECT_TYPE_DEVICE_MEMORY = 8, VK_OBJECT_TYPE_BUFFER = 9, VK_OBJECT_TYPE_IMAGE = 10, VK_OBJECT_TYPE_EVENT = 11, VK_OBJECT_TYPE_QUERY_POOL = 12, VK_OBJECT_TYPE_BUFFER_VIEW = 13, VK_OBJECT_TYPE_IMAGE_VIEW = 14, VK_OBJECT_TYPE_SHADER_MODULE = 15, VK_OBJECT_TYPE_PIPELINE_CACHE = 16, VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17, VK_OBJECT_TYPE_RENDER_PASS = 18, VK_OBJECT_TYPE_PIPELINE = 19, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20, VK_OBJECT_TYPE_SAMPLER = 21, VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22, VK_OBJECT_TYPE_DESCRIPTOR_SET = 23, VK_OBJECT_TYPE_FRAMEBUFFER = 24, VK_OBJECT_TYPE_COMMAND_POOL = 25, VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION = 1000156000, VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE = 1000085000, VK_OBJECT_TYPE_SURFACE_KHR = 1000000000, VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000, VK_OBJECT_TYPE_DISPLAY_KHR = 1000002000, VK_OBJECT_TYPE_DISPLAY_MODE_KHR = 1000002001, VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT = 1000011000, VK_OBJECT_TYPE_OBJECT_TABLE_NVX = 1000086000, VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX = 1000086001, VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT = 1000128000, VK_OBJECT_TYPE_VALIDATION_CACHE_EXT = 1000160000, VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV = 1000165000, VK_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000, VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR = VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE, VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR = VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION, VK_OBJECT_TYPE_MAX_ENUM = 0x7FFFFFFF } VkObjectType; } // anonymous namespace GraphicsEventParser::GraphicsEventParser(TraceProcessorContext* context) : context_(context), vulkan_memory_tracker_(context), description_id_(context->storage->InternString("description")), gpu_render_stage_scope_id_( context->storage->InternString("gpu_render_stage")), graphics_event_scope_id_( context->storage->InternString("graphics_frame_event")), unknown_event_name_id_(context->storage->InternString("unknown_event")), no_layer_name_name_id_(context->storage->InternString("no_layer_name")), layer_name_key_id_(context->storage->InternString("layer_name")), event_type_name_ids_{ {context->storage->InternString( "unspecified_event") /* UNSPECIFIED */, context->storage->InternString("Dequeue") /* DEQUEUE */, context->storage->InternString("Queue") /* QUEUE */, context->storage->InternString("Post") /* POST */, context->storage->InternString( "AcquireFenceSignaled") /* ACQUIRE_FENCE */, context->storage->InternString("Latch") /* LATCH */, context->storage->InternString( "HWCCompositionQueued") /* HWC_COMPOSITION_QUEUED */, context->storage->InternString( "FallbackComposition") /* FALLBACK_COMPOSITION */, context->storage->InternString( "PresentFenceSignaled") /* PRESENT_FENCE */, context->storage->InternString( "ReleaseFenceSignaled") /* RELEASE_FENCE */, context->storage->InternString("Modify") /* MODIFY */, context->storage->InternString("Detach") /* DETACH */, context->storage->InternString("Attach") /* ATTACH */, context->storage->InternString("Cancel") /* CANCEL */}}, present_frame_name_(present_frame_buffer_, base::ArraySize(present_frame_buffer_)), present_frame_layer_name_(present_frame_layer_buffer_, base::ArraySize(present_frame_layer_buffer_)), present_frame_numbers_(present_frame_numbers_buffer_, base::ArraySize(present_frame_numbers_buffer_)), gpu_log_track_name_id_(context_->storage->InternString("GPU Log")), gpu_log_scope_id_(context_->storage->InternString("gpu_log")), tag_id_(context_->storage->InternString("tag")), log_message_id_(context->storage->InternString("message")), log_severity_ids_{{context_->storage->InternString("UNSPECIFIED"), context_->storage->InternString("VERBOSE"), context_->storage->InternString("DEBUG"), context_->storage->InternString("INFO"), context_->storage->InternString("WARNING"), context_->storage->InternString("ERROR"), context_->storage->InternString( "UNKNOWN_SEVERITY") /* must be last */}}, vk_event_track_id_(context->storage->InternString("Vulkan Events")), vk_event_scope_id_(context->storage->InternString("vulkan_events")), vk_queue_submit_id_(context->storage->InternString("vkQueueSubmit")) {} void GraphicsEventParser::ParseGpuCounterEvent(int64_t ts, ConstBytes blob) { protos::pbzero::GpuCounterEvent::Decoder event(blob.data, blob.size); protos::pbzero::GpuCounterDescriptor::Decoder descriptor( event.counter_descriptor()); // Add counter spec to ID map. for (auto it = descriptor.specs(); it; ++it) { protos::pbzero::GpuCounterDescriptor_GpuCounterSpec::Decoder spec(*it); if (!spec.has_counter_id()) { PERFETTO_ELOG("Counter spec missing counter id"); context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); continue; } if (!spec.has_name()) { context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); continue; } auto counter_id = spec.counter_id(); auto name = spec.name(); if (gpu_counter_track_ids_.find(counter_id) == gpu_counter_track_ids_.end()) { auto desc = spec.description(); StringId unit_id = kNullStringId; if (spec.has_numerator_units() || spec.has_denominator_units()) { char buffer[1024]; base::StringWriter unit(buffer, sizeof(buffer)); for (auto numer = spec.numerator_units(); numer; ++numer) { if (unit.pos()) { unit.AppendChar(':'); } unit.AppendInt(*numer); } char sep = '/'; for (auto denom = spec.denominator_units(); denom; ++denom) { unit.AppendChar(sep); unit.AppendInt(*denom); sep = ':'; } unit_id = context_->storage->InternString(unit.GetStringView()); } auto name_id = context_->storage->InternString(name); auto desc_id = context_->storage->InternString(desc); auto track_id = context_->track_tracker->CreateGpuCounterTrack( name_id, 0 /* gpu_id */, desc_id, unit_id); gpu_counter_track_ids_.emplace(counter_id, track_id); if (spec.has_groups()) { for (auto group = spec.groups(); group; ++group) { tables::GpuCounterGroupTable::Row row; row.group_id = *group; row.track_id = track_id; context_->storage->mutable_gpu_counter_group_table()->Insert(row); } } else { tables::GpuCounterGroupTable::Row row; row.group_id = protos::pbzero::GpuCounterDescriptor::UNCLASSIFIED; row.track_id = track_id; context_->storage->mutable_gpu_counter_group_table()->Insert(row); } } else { // Either counter spec was repeated or it came after counter data. PERFETTO_ELOG("Duplicated counter spec found. (counter_id=%d, name=%s)", counter_id, name.ToStdString().c_str()); context_->storage->IncrementStats(stats::gpu_counters_invalid_spec); } } for (auto it = event.counters(); it; ++it) { protos::pbzero::GpuCounterEvent_GpuCounter::Decoder counter(*it); if (counter.has_counter_id() && (counter.has_int_value() || counter.has_double_value())) { auto counter_id = counter.counter_id(); // Check missing counter_id if (gpu_counter_track_ids_.find(counter_id) == gpu_counter_track_ids_.end()) { char buffer[64]; base::StringWriter writer(buffer, sizeof(buffer)); writer.AppendString("gpu_counter("); writer.AppendUnsignedInt(counter_id); writer.AppendString(")"); auto name_id = context_->storage->InternString(writer.GetStringView()); TrackId track = context_->track_tracker->CreateGpuCounterTrack( name_id, 0 /* gpu_id */); gpu_counter_track_ids_.emplace(counter_id, track); context_->storage->IncrementStats(stats::gpu_counters_missing_spec); } if (counter.has_int_value()) { context_->event_tracker->PushCounter( ts, counter.int_value(), gpu_counter_track_ids_[counter_id]); } else { context_->event_tracker->PushCounter( ts, counter.double_value(), gpu_counter_track_ids_[counter_id]); } } } } const StringId GraphicsEventParser::GetFullStageName( const protos::pbzero::GpuRenderStageEvent_Decoder& event) const { size_t stage_id = static_cast<size_t>(event.stage_id()); StringId stage_name; if (stage_id < gpu_render_stage_ids_.size()) { stage_name = gpu_render_stage_ids_[stage_id].first; } else { char buffer[64]; snprintf(buffer, sizeof(buffer), "render stage(%zu)", stage_id); stage_name = context_->storage->InternString(buffer); } return stage_name; } /** * Create a GPU render stage track based * GpuRenderStageEvent.Specifications.Description. */ void GraphicsEventParser::InsertGpuTrack( const protos::pbzero:: GpuRenderStageEvent_Specifications_Description_Decoder& hw_queue) { StringId track_name = context_->storage->InternString(hw_queue.name()); if (gpu_hw_queue_counter_ >= gpu_hw_queue_ids_.size() || !gpu_hw_queue_ids_[gpu_hw_queue_counter_].has_value()) { tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track.description = context_->storage->InternString(hw_queue.description()); if (gpu_hw_queue_counter_ >= gpu_hw_queue_ids_.size()) { gpu_hw_queue_ids_.emplace_back( context_->track_tracker->InternGpuTrack(track)); } else { // If a gpu_render_stage_event is received before the specification, it is // possible that the slot has already been allocated. gpu_hw_queue_ids_[gpu_hw_queue_counter_] = context_->track_tracker->InternGpuTrack(track); } } else { // If a gpu_render_stage_event is received before the specification, a track // will be automatically generated. In that case, update the name and // description. auto track_id = gpu_hw_queue_ids_[gpu_hw_queue_counter_]; if (track_id.has_value()) { auto row = context_->storage->mutable_gpu_track_table() ->id() .IndexOf(track_id.value()) .value(); context_->storage->mutable_gpu_track_table()->mutable_name()->Set( row, track_name); context_->storage->mutable_gpu_track_table()->mutable_description()->Set( row, context_->storage->InternString(hw_queue.description())); } else { tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track.description = context_->storage->InternString(hw_queue.description()); } } ++gpu_hw_queue_counter_; } base::Optional<std::string> GraphicsEventParser::FindDebugName( int32_t vk_object_type, uint64_t vk_handle) const { auto map = debug_marker_names_.find(vk_object_type); if (map == debug_marker_names_.end()) { return base::nullopt; } auto name = map->second.find(vk_handle); if (name == map->second.end()) { return base::nullopt; } else { return name->second; } } void GraphicsEventParser::ParseGpuRenderStageEvent(int64_t ts, ConstBytes blob) { protos::pbzero::GpuRenderStageEvent::Decoder event(blob.data, blob.size); if (event.has_specifications()) { protos::pbzero::GpuRenderStageEvent_Specifications::Decoder spec( event.specifications().data, event.specifications().size); for (auto it = spec.hw_queue(); it; ++it) { protos::pbzero::GpuRenderStageEvent_Specifications_Description::Decoder hw_queue(*it); if (hw_queue.has_name()) { InsertGpuTrack(hw_queue); } } for (auto it = spec.stage(); it; ++it) { protos::pbzero::GpuRenderStageEvent_Specifications_Description::Decoder stage(*it); if (stage.has_name()) { gpu_render_stage_ids_.emplace_back(std::make_pair( context_->storage->InternString(stage.name()), context_->storage->InternString(stage.description()))); } } } auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { size_t stage_id = static_cast<size_t>(event.stage_id()); if (stage_id < gpu_render_stage_ids_.size()) { auto description = gpu_render_stage_ids_[stage_id].second; if (description != kNullStringId) { inserter->AddArg(description_id_, Variadic::String(description)); } } for (auto it = event.extra_data(); it; ++it) { protos::pbzero::GpuRenderStageEvent_ExtraData_Decoder datum(*it); StringId name_id = context_->storage->InternString(datum.name()); StringId value = context_->storage->InternString( datum.has_value() ? datum.value() : base::StringView()); inserter->AddArg(name_id, Variadic::String(value)); } }; if (event.has_event_id()) { TrackId track_id; uint32_t hw_queue_id = static_cast<uint32_t>(event.hw_queue_id()); if (hw_queue_id < gpu_hw_queue_ids_.size() && gpu_hw_queue_ids_[hw_queue_id].has_value()) { track_id = gpu_hw_queue_ids_[hw_queue_id].value(); } else { // If the event has a hw_queue_id that does not have a Specification, // create a new track for it. char buf[128]; base::StringWriter writer(buf, sizeof(buf)); writer.AppendLiteral("Unknown GPU Queue "); if (hw_queue_id > 1024) { // We don't expect this to happen, but just in case there is a corrupt // packet, make sure we don't allocate a ridiculous amount of memory. hw_queue_id = 1024; context_->storage->IncrementStats( stats::gpu_render_stage_parser_errors); PERFETTO_ELOG("Invalid hw_queue_id."); } else { writer.AppendInt(event.hw_queue_id()); } StringId track_name = context_->storage->InternString(writer.GetStringView()); tables::GpuTrackTable::Row track(track_name); track.scope = gpu_render_stage_scope_id_; track_id = context_->track_tracker->InternGpuTrack(track); gpu_hw_queue_ids_.resize(hw_queue_id + 1); gpu_hw_queue_ids_[hw_queue_id] = track_id; } auto render_target_name = FindDebugName(VK_OBJECT_TYPE_FRAMEBUFFER, event.render_target_handle()); auto render_target_name_id = render_target_name.has_value() ? context_->storage->InternString( render_target_name.value().c_str()) : kNullStringId; auto render_pass_name = FindDebugName(VK_OBJECT_TYPE_RENDER_PASS, event.render_pass_handle()); auto render_pass_name_id = render_pass_name.has_value() ? context_->storage->InternString( render_pass_name.value().c_str()) : kNullStringId; auto command_buffer_name = FindDebugName(VK_OBJECT_TYPE_COMMAND_BUFFER, event.command_buffer_handle()); auto command_buffer_name_id = command_buffer_name.has_value() ? context_->storage->InternString( command_buffer_name.value().c_str()) : kNullStringId; tables::GpuSliceTable::Row row; row.ts = ts; row.track_id = track_id; row.name = GetFullStageName(event); row.dur = static_cast<int64_t>(event.duration()); row.context_id = static_cast<int64_t>(event.context()); row.render_target = static_cast<int64_t>(event.render_target_handle()); row.render_target_name = render_target_name_id; row.render_pass = static_cast<int64_t>(event.render_pass_handle()); row.render_pass_name = render_pass_name_id; row.command_buffer = static_cast<int64_t>(event.command_buffer_handle()); row.command_buffer_name = command_buffer_name_id; row.submission_id = event.submission_id(); row.hw_queue_id = hw_queue_id; context_->slice_tracker->ScopedGpu(row, args_callback); } } void GraphicsEventParser::ParseGraphicsFrameEvent(int64_t timestamp, ConstBytes blob) { using GraphicsFrameEvent = protos::pbzero::GraphicsFrameEvent; protos::pbzero::GraphicsFrameEvent_Decoder frame_event(blob.data, blob.size); if (!frame_event.has_buffer_event()) { return; } ConstBytes bufferBlob = frame_event.buffer_event(); protos::pbzero::GraphicsFrameEvent_BufferEvent_Decoder event(bufferBlob.data, bufferBlob.size); if (!event.has_buffer_id()) { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with missing buffer id field."); return; } StringId event_name_id = unknown_event_name_id_; if (event.has_type()) { const auto type = static_cast<size_t>(event.type()); if (type < event_type_name_ids_.size()) { event_name_id = event_type_name_ids_[type]; graphics_frame_stats_map_[event.buffer_id()][type] = timestamp; } else { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with unknown type %zu.", type); } } else { context_->storage->IncrementStats( stats::graphics_frame_event_parser_errors); PERFETTO_ELOG("GraphicsFrameEvent with missing type field."); } const uint32_t buffer_id = event.buffer_id(); StringId layer_name_id; char buffer[4096]; const size_t layerNameMaxLength = 4000; base::StringWriter track_name(buffer, sizeof(buffer)); if (event.has_layer_name()) { const base::StringView layer_name(event.layer_name()); layer_name_id = context_->storage->InternString(layer_name); track_name.AppendString(layer_name.substr(0, layerNameMaxLength)); } else { layer_name_id = no_layer_name_name_id_; track_name.AppendLiteral("unknown_layer"); } track_name.AppendLiteral("[buffer:"); track_name.AppendUnsignedInt(buffer_id); track_name.AppendChar(']'); const StringId track_name_id = context_->storage->InternString(track_name.GetStringView()); const int64_t duration = event.has_duration_ns() ? static_cast<int64_t>(event.duration_ns()) : 0; const uint32_t frame_number = event.has_frame_number() ? event.frame_number() : 0; tables::GpuTrackTable::Row track(track_name_id); track.scope = graphics_event_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); { char frame_number_buffer[256]; base::StringWriter frame_numbers(frame_number_buffer, base::ArraySize(frame_number_buffer)); frame_numbers.AppendUnsignedInt(frame_number); tables::GraphicsFrameSliceTable::Row row; row.ts = timestamp; row.track_id = track_id; row.name = event_name_id; row.dur = duration; row.frame_numbers = context_->storage->InternString(frame_numbers.GetStringView()); row.layer_names = layer_name_id; context_->slice_tracker->ScopedFrameEvent(row); } /* Displayed Frame track */ if (event.type() == GraphicsFrameEvent::PRESENT_FENCE) { // Insert the frame stats for the buffer that was presented auto acquire_ts = graphics_frame_stats_map_[event.buffer_id()] [GraphicsFrameEvent::ACQUIRE_FENCE]; auto queue_ts = graphics_frame_stats_map_[event.buffer_id()][GraphicsFrameEvent::QUEUE]; auto latch_ts = graphics_frame_stats_map_[event.buffer_id()][GraphicsFrameEvent::LATCH]; tables::GraphicsFrameStatsTable::Row stats_row; // AcquireFence can signal before Queue sometimes, so have 0 as a bound. stats_row.queue_to_acquire_time = std::max(acquire_ts - queue_ts, static_cast<int64_t>(0)); stats_row.acquire_to_latch_time = latch_ts - acquire_ts; stats_row.latch_to_present_time = timestamp - latch_ts; auto stats_row_id = context_->storage->mutable_graphics_frame_stats_table()->Insert( stats_row); if (previous_timestamp_ == 0) { const StringId present_track_name_id = context_->storage->InternString("Displayed Frame"); tables::GpuTrackTable::Row present_track(present_track_name_id); present_track.scope = graphics_event_scope_id_; present_track_id_ = context_->track_tracker->InternGpuTrack(present_track); } // The displayed frame is a slice from one present fence to another present // fence. If multiple buffers have present fence at the same time, they all // are shown on screen at the same time. So that particular displayed frame // slice should include info from all those buffers in it. // Since the events are parsed one by one, the following bookkeeping is // needed to create the slice properly. if (previous_timestamp_ == timestamp && previous_timestamp_ != 0) { // Same timestamp as previous present fence. This buffer should also // contribute to this slice. present_frame_name_.AppendLiteral(", "); present_frame_name_.AppendUnsignedInt(buffer_id); // Append Layer names present_frame_layer_name_.AppendLiteral(", "); present_frame_layer_name_.AppendString(event.layer_name()); // Append Frame numbers present_frame_numbers_.AppendLiteral(", "); present_frame_numbers_.AppendUnsignedInt(frame_number); // Add the current stats row to the list of stats that go with this frame graphics_frame_stats_idx_.push_back(stats_row_id.row); } else { if (previous_timestamp_ != 0) { StringId present_frame_layer_name_id = context_->storage->InternString( present_frame_layer_name_.GetStringView()); // End the current slice that's being tracked. const auto opt_slice_id = context_->slice_tracker->EndFrameEvent( timestamp, present_track_id_); if (opt_slice_id) { // The slice could have had additional buffers in it, so we need to // update the table. auto* graphics_frame_slice_table = context_->storage->mutable_graphics_frame_slice_table(); uint32_t row_idx = *graphics_frame_slice_table->id().IndexOf(*opt_slice_id); StringId frame_name_id = context_->storage->InternString( present_frame_name_.GetStringView()); graphics_frame_slice_table->mutable_name()->Set(row_idx, frame_name_id); StringId present_frame_numbers_id = context_->storage->InternString( present_frame_numbers_.GetStringView()); graphics_frame_slice_table->mutable_frame_numbers()->Set( row_idx, present_frame_numbers_id); graphics_frame_slice_table->mutable_layer_names()->Set( row_idx, present_frame_layer_name_id); // Set the slice_id for the frame_stats rows under this displayed // frame auto* slice_table = context_->storage->mutable_slice_table(); uint32_t slice_idx = *slice_table->id().IndexOf(*opt_slice_id); for (uint32_t i = 0; i < graphics_frame_stats_idx_.size(); i++) { context_->storage->mutable_graphics_frame_stats_table() ->mutable_slice_id() ->Set(graphics_frame_stats_idx_[i], slice_idx); } } present_frame_layer_name_.reset(); present_frame_name_.reset(); present_frame_numbers_.reset(); graphics_frame_stats_idx_.clear(); } // Start a new slice present_frame_name_.AppendUnsignedInt(buffer_id); previous_timestamp_ = timestamp; present_frame_layer_name_.AppendString(event.layer_name()); present_frame_numbers_.AppendUnsignedInt(frame_number); present_event_name_id_ = context_->storage->InternString(present_frame_name_.GetStringView()); graphics_frame_stats_idx_.push_back(stats_row_id.row); tables::GraphicsFrameSliceTable::Row row; row.ts = timestamp; row.track_id = present_track_id_; row.name = present_event_name_id_; context_->slice_tracker->BeginFrameEvent(row); } } } void GraphicsEventParser::UpdateVulkanMemoryAllocationCounters( UniquePid upid, const VulkanMemoryEvent::Decoder& event) { StringId track_str_id = kNullStringId; TrackId track = kInvalidTrackId; auto allocation_scope = VulkanMemoryEvent::SCOPE_UNSPECIFIED; uint32_t memory_type = std::numeric_limits<uint32_t>::max(); switch (event.source()) { case VulkanMemoryEvent::SOURCE_DRIVER: allocation_scope = static_cast<VulkanMemoryEvent::AllocationScope>( event.allocation_scope()); if (allocation_scope == VulkanMemoryEvent::SCOPE_UNSPECIFIED) return; switch (event.operation()) { case VulkanMemoryEvent::OP_CREATE: vulkan_driver_memory_counters_[allocation_scope] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY: vulkan_driver_memory_counters_[allocation_scope] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_BIND: case VulkanMemoryEvent::OP_DESTROY_BOUND: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindAllocationScopeCounterString( allocation_scope); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_driver_memory_counters_[allocation_scope], track); break; case VulkanMemoryEvent::SOURCE_DEVICE_MEMORY: memory_type = static_cast<uint32_t>(event.memory_type()); switch (event.operation()) { case VulkanMemoryEvent::OP_CREATE: vulkan_device_memory_counters_allocate_[memory_type] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY: vulkan_device_memory_counters_allocate_[memory_type] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_BIND: case VulkanMemoryEvent::OP_DESTROY_BOUND: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindMemoryTypeCounterString( memory_type, VulkanMemoryTracker::DeviceCounterType::kAllocationCounter); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_device_memory_counters_allocate_[memory_type], track); break; case VulkanMemoryEvent::SOURCE_BUFFER: case VulkanMemoryEvent::SOURCE_IMAGE: memory_type = static_cast<uint32_t>(event.memory_type()); switch (event.operation()) { case VulkanMemoryEvent::OP_BIND: vulkan_device_memory_counters_bind_[memory_type] += event.memory_size(); break; case VulkanMemoryEvent::OP_DESTROY_BOUND: vulkan_device_memory_counters_bind_[memory_type] -= event.memory_size(); break; case VulkanMemoryEvent::OP_UNSPECIFIED: case VulkanMemoryEvent::OP_CREATE: case VulkanMemoryEvent::OP_DESTROY: case VulkanMemoryEvent::OP_ANNOTATIONS: return; } track_str_id = vulkan_memory_tracker_.FindMemoryTypeCounterString( memory_type, VulkanMemoryTracker::DeviceCounterType::kBindCounter); track = context_->track_tracker->InternProcessCounterTrack(track_str_id, upid); context_->event_tracker->PushCounter( event.timestamp(), vulkan_device_memory_counters_bind_[memory_type], track); break; case VulkanMemoryEvent::SOURCE_UNSPECIFIED: case VulkanMemoryEvent::SOURCE_DEVICE: return; } } void GraphicsEventParser::ParseVulkanMemoryEvent( PacketSequenceStateGeneration* sequence_state, ConstBytes blob) { using protos::pbzero::InternedData; VulkanMemoryEvent::Decoder vulkan_memory_event(blob.data, blob.size); tables::VulkanMemoryAllocationsTable::Row vulkan_memory_event_row; vulkan_memory_event_row.source = vulkan_memory_tracker_.FindSourceString( static_cast<VulkanMemoryEvent::Source>(vulkan_memory_event.source())); vulkan_memory_event_row.operation = vulkan_memory_tracker_.FindOperationString( static_cast<VulkanMemoryEvent::Operation>( vulkan_memory_event.operation())); vulkan_memory_event_row.timestamp = vulkan_memory_event.timestamp(); vulkan_memory_event_row.upid = context_->process_tracker->GetOrCreateProcess(vulkan_memory_event.pid()); if (vulkan_memory_event.has_device()) vulkan_memory_event_row.device = static_cast<int64_t>(vulkan_memory_event.device()); if (vulkan_memory_event.has_device_memory()) vulkan_memory_event_row.device_memory = static_cast<int64_t>(vulkan_memory_event.device_memory()); if (vulkan_memory_event.has_heap()) vulkan_memory_event_row.heap = vulkan_memory_event.heap(); if (vulkan_memory_event.has_memory_type()) vulkan_memory_event_row.memory_type = vulkan_memory_event.memory_type(); if (vulkan_memory_event.has_caller_iid()) { vulkan_memory_event_row.function_name = vulkan_memory_tracker_ .GetInternedString<InternedData::kFunctionNamesFieldNumber>( sequence_state, static_cast<uint64_t>(vulkan_memory_event.caller_iid())); } if (vulkan_memory_event.has_object_handle()) vulkan_memory_event_row.object_handle = static_cast<int64_t>(vulkan_memory_event.object_handle()); if (vulkan_memory_event.has_memory_address()) vulkan_memory_event_row.memory_address = static_cast<int64_t>(vulkan_memory_event.memory_address()); if (vulkan_memory_event.has_memory_size()) vulkan_memory_event_row.memory_size = static_cast<int64_t>(vulkan_memory_event.memory_size()); if (vulkan_memory_event.has_allocation_scope()) vulkan_memory_event_row.scope = vulkan_memory_tracker_.FindAllocationScopeString( static_cast<VulkanMemoryEvent::AllocationScope>( vulkan_memory_event.allocation_scope())); UpdateVulkanMemoryAllocationCounters(vulkan_memory_event_row.upid.value(), vulkan_memory_event); auto* allocs = context_->storage->mutable_vulkan_memory_allocations_table(); VulkanAllocId id = allocs->Insert(vulkan_memory_event_row).id; if (vulkan_memory_event.has_annotations()) { auto inserter = context_->args_tracker->AddArgsTo(id); for (auto it = vulkan_memory_event.annotations(); it; ++it) { protos::pbzero::VulkanMemoryEventAnnotation::Decoder annotation(*it); auto key_id = vulkan_memory_tracker_ .GetInternedString<InternedData::kVulkanMemoryKeysFieldNumber>( sequence_state, static_cast<uint64_t>(annotation.key_iid())); if (annotation.has_int_value()) { inserter.AddArg(key_id, Variadic::Integer(annotation.int_value())); } else if (annotation.has_double_value()) { inserter.AddArg(key_id, Variadic::Real(annotation.double_value())); } else if (annotation.has_string_iid()) { auto string_id = vulkan_memory_tracker_ .GetInternedString<InternedData::kVulkanMemoryKeysFieldNumber>( sequence_state, static_cast<uint64_t>(annotation.string_iid())); inserter.AddArg(key_id, Variadic::String(string_id)); } } } } void GraphicsEventParser::ParseGpuLog(int64_t ts, ConstBytes blob) { protos::pbzero::GpuLog::Decoder event(blob.data, blob.size); tables::GpuTrackTable::Row track(gpu_log_track_name_id_); track.scope = gpu_log_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { if (event.has_tag()) { inserter->AddArg( tag_id_, Variadic::String(context_->storage->InternString(event.tag()))); } if (event.has_log_message()) { inserter->AddArg(log_message_id_, Variadic::String(context_->storage->InternString( event.log_message()))); } }; auto severity = static_cast<size_t>(event.severity()); StringId severity_id = severity < log_severity_ids_.size() ? log_severity_ids_[static_cast<size_t>(event.severity())] : log_severity_ids_[log_severity_ids_.size() - 1]; tables::GpuSliceTable::Row row; row.ts = ts; row.track_id = track_id; row.name = severity_id; row.dur = 0; context_->slice_tracker->ScopedGpu(row, args_callback); } void GraphicsEventParser::ParseVulkanApiEvent(int64_t ts, ConstBytes blob) { protos::pbzero::VulkanApiEvent::Decoder vk_event(blob.data, blob.size); if (vk_event.has_vk_debug_utils_object_name()) { protos::pbzero::VulkanApiEvent_VkDebugUtilsObjectName::Decoder event( vk_event.vk_debug_utils_object_name()); debug_marker_names_[event.object_type()][event.object()] = event.object_name().ToStdString(); } if (vk_event.has_vk_queue_submit()) { protos::pbzero::VulkanApiEvent_VkQueueSubmit::Decoder event( vk_event.vk_queue_submit()); // Once flow table is implemented, we can create a nice UI that link the // vkQueueSubmit to GpuRenderStageEvent. For now, just add it as in a GPU // track so that they can appear close to the render stage slices. tables::GpuTrackTable::Row track(vk_event_track_id_); track.scope = vk_event_scope_id_; TrackId track_id = context_->track_tracker->InternGpuTrack(track); tables::GpuSliceTable::Row row; row.ts = ts; row.dur = static_cast<int64_t>(event.duration_ns()); row.track_id = track_id; row.name = vk_queue_submit_id_; if (event.has_vk_command_buffers()) { row.command_buffer = static_cast<int64_t>(*event.vk_command_buffers()); } row.submission_id = event.submission_id(); auto args_callback = [this, &event](ArgsTracker::BoundInserter* inserter) { inserter->AddArg(context_->storage->InternString("pid"), Variadic::Integer(event.pid())); inserter->AddArg(context_->storage->InternString("tid"), Variadic::Integer(event.tid())); }; context_->slice_tracker->ScopedGpu(row, args_callback); } } } // namespace trace_processor } // namespace perfetto
43.063781
107
0.687834
kuscsik
6981d94a4378de6858f672b08a598c7278f2b7d8
1,887
cpp
C++
ext/nuvo_image/src/SSIM.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
null
null
null
ext/nuvo_image/src/SSIM.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
5
2016-08-02T13:33:02.000Z
2020-11-03T15:22:52.000Z
ext/nuvo_image/src/SSIM.cpp
crema/nuvo-image
365e4a54429fe4180e03adb1968ab9989e7ee5fb
[ "MIT" ]
null
null
null
#include "SSIM.h" int QualitySSIM::InterpolationTargetSSIM(const QualitySSIM& min, const QualitySSIM& max, const double targetSSIM) { auto slope = (max.quality - min.quality) / (max.ssim - min.ssim); return (int)round(slope * (targetSSIM - min.ssim)) + min.quality; } SSIMData::SSIMData(const cv::Mat& mat) { mat.convertTo(image, CV_32F); imageSquare = image.mul(image); GaussianBlur(image, imageBlur, cv::Size(11, 11), 1.5); imageBlurSquare = imageBlur.mul(imageBlur); GaussianBlur(imageSquare, sigma, cv::Size(11, 11), 1.5); sigma -= imageBlurSquare; } double SSIMData::GetSSIM(const SSIMData& a, const SSIMData& b) { const double C1 = 6.5025, C2 = 58.5225; auto& I1 = a.image; auto& I2 = b.image; auto& I1_2 = a.imageSquare; auto& I2_2 = b.imageSquare; cv::Mat I1_I2 = I1.mul(I2); // I1 * I2 /*************************** END INITS **********************************/ auto& mu1 = a.imageBlur; auto& mu2 = b.imageBlur; auto& mu1_2 = a.imageBlurSquare; auto& mu2_2 = b.imageBlurSquare; cv::Mat mu1_mu2 = mu1.mul(mu2); auto& sigma1_2 = a.sigma; auto& sigma2_2 = b.sigma; cv::Mat sigma12; GaussianBlur(I1_I2, sigma12, cv::Size(11, 11), 1.5); sigma12 -= mu1_mu2; ///////////////////////////////// FORMULA //////////////////////////////// cv::Mat t1, t2, t3; t1 = 2 * mu1_mu2 + C1; t2 = 2 * sigma12 + C2; t3 = t1.mul(t2); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2)) t1 = mu1_2 + mu2_2 + C1; t2 = sigma1_2 + sigma2_2 + C2; t1 = t1.mul(t2); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2)) cv::Mat ssim_map; divide(t3, t1, ssim_map); // ssim_map = t3./t1; cv::Scalar mssim = mean(ssim_map); // mssim = average of ssim map if (mssim[1] == 0 && mssim[2] == 0 && mssim[3] == 0) { return mssim[0]; } else { auto ssim = (mssim[0] + mssim[1] + mssim[2]) / 3; return ssim; } }
28.164179
115
0.578166
crema
6986813ff0789e8d9032fa6ecfba6411feee985c
965
cpp
C++
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
5
2019-04-07T05:39:11.000Z
2020-07-23T01:43:02.000Z
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
2017 JUST Programming Contest 4.0/B.cpp
lajiyuan/segmentation-fault-training
71dfeeed52b18071a5c8c4d02f5e74fc01c53322
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; const int maxn = 1e5+10; #define dbg(x) cout<<#x<<" = "<<x<<endl #define ok cout<<"OK"<<endl int a[maxn]; int main() { int t; scanf("%d",&t); while(t--) { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); int pos; for(int i=1;i<=n;i++) { if(a[i]!=-1) { pos=i; break; } } for(int i=pos-1;i>=1;i--) { if(a[i]==-1) a[i]=((a[i+1]-1)+m)%m; else continue; } for(int i=pos;i<=n;i++) { if(a[i]==-1) a[i]=(a[i-1]+1)%m; else continue; } for(int i=1;i<=n;i++) { printf("%d",a[i]); if(i!=n) printf(" "); } printf("\n"); } return 0; }
20.978261
49
0.344041
lajiyuan
698c5a84910801cc8b5f76fef3de78143080b527
1,004
cpp
C++
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/229_majority_element_II/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int len = nums.size(), num1, num2, count1 = 0, count2 = 0; vector<int> res; for (int i = 0; i < len; i ++) { if (num1 == nums[i]) count1 ++; else if (num2 == nums[i]) count2 ++; else if (count1 == 0) { count1 ++; num1 = nums[i]; } else if (count2 == 0) { count2 ++; num2 = nums[i]; } else { count1 --; count2 --; } } count1 = 0; count2 = 0; for (int i = 0; i < len; i ++) { if (num1 == nums[i]) count1 ++; if (num2 == nums[i]) count2 ++; } if (count1 > len/3) res.push_back(num1); if (count2 > len/3) res.push_back(num2); return res; } };
25.1
66
0.351594
zszyellow
7e36458397b0c141e4c22925d02cd9f818d67f96
460
cpp
C++
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
4
2019-01-27T01:00:44.000Z
2019-01-29T02:09:55.000Z
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
null
null
null
Pointers/second.cpp
dealbisac/cprograms
89af58a30295099b45406cf192f4c4eb4a06f9fe
[ "Unlicense" ]
1
2019-02-04T11:34:40.000Z
2019-02-04T11:34:40.000Z
#include <stdio.h> int main() { int* pc, c; c = 22; printf("Address of c: %u\n", &c); printf("Value of c: %d\n\n", c); pc = &c; printf("Address of pointer pc: %u\n", pc); printf("Content of pointer pc: %d\n\n", *pc); c = 11; printf("Address of pointer pc: %u\n", pc); printf("Content of pointer pc: %d\n\n", *pc); *pc = 2; printf("Address of c: %u\n", &c); printf("Value of c: %d\n\n", c); return 0; }
20
48
0.506522
dealbisac
7e3fcda429c2b500a22fb361bfcdbd774bc2878c
2,152
cxx
C++
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEER/AliMatrixSq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/**********************************************************************************************/ /* */ /* Abstract class for matrix used for */ /* millepede2 operation. */ /* Works for expandable square matrices */ /* of arbitrary dimension */ /* Author: [email protected] */ /* */ /* */ /**********************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> // #include "TClass.h" #include "TMath.h" #include "AliMatrixSq.h" // ClassImp(AliMatrixSq) AliMatrixSq & AliMatrixSq::operator=(const AliMatrixSq &src) { // = operator if (this == &src) return *this; TMatrixDBase::operator=(src); fSymmetric = src.fSymmetric; return *this; } //___________________________________________________________ void AliMatrixSq::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const { // fill vecOut by matrix*vecIn // vector should be of the same size as the matrix for (int i=GetSize();i--;) { vecOut[i] = 0.0; for (int j=GetSize();j--;) vecOut[i] += vecIn[j]*(*this)(i,j); } // } //___________________________________________________________ void AliMatrixSq::PrintCOO() const { // print matrix in COO sparse format // // get number of non-zero elements int nnz = 0; int sz = GetSize(); for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if (Query(ir,ic)!=0) nnz++; // printf("%d %d %d\n",sz,sz,nnz); double vl; for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if ((vl=Query(ir,ic))!=0) printf("%d %d %f\n",ir,ic,vl); // }
36.474576
110
0.416822
AllaMaevskaya
7e40272a65b220d2f28ce34196ff3a7edd152cd9
84
hpp
C++
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
1
2019-09-28T09:40:08.000Z
2019-09-28T09:40:08.000Z
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
null
null
null
traits/sqrtconstexpr.hpp
colorhistory/cplusplus-general-programming
3ece924a2ab34711a55a45bc41e2b74384956204
[ "MIT" ]
null
null
null
#ifndef SQRTCONSTEXPR_HPP #define SQRTCONSTEXPR_HPP #endif // SQRTCONSTEXPR_HPP
12
27
0.809524
colorhistory
7e4cf839ec626c68ac4dcd037d21183a2e16d7b1
573
cpp
C++
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/stmt/compound_stmt.cpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
#include <toy_compiler/munster/ast/stmt/compound_stmt.hpp> #include <toy_compiler/munster/ast/utility.hpp> namespace munster::ast { compound_stmt::compound_stmt(std::vector<node_ptr>&& statements) { make_family<stmt>(std::move(statements)); } void compound_stmt::accept(visitor_variant& visitor) const { for (const auto& child : children()) { child->accept(visitor); } visit_node(visitor, *this); } auto compound_stmt::to_string() const -> std::string { return "compound_stmt"; } } // namespace munster::ast
23.875
83
0.670157
Wmbat
7e5a18f46883b774602c845cb7b711df0457a7d7
42,777
hpp
C++
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/ScaFES_Grid.hpp
nih23/MRIDrivenHeatSimulation
de6d16853df1faf44c700d1fc06584351bf6c816
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* ScaFES * Copyright (c) 2011-2015, ZIH, TU Dresden, Federal Republic of Germany. * For details, see the files COPYING and LICENSE in the base directory * of the package. */ /** * @file ScaFES_Grid.hpp * @brief Contains the class template Grid. */ #ifndef SCAFES_GRID_HPP_ #define SCAFES_GRID_HPP_ #include "ScaFES_Config.hpp" #include <iterator> #include <vector> #ifdef SCAFES_HAVE_BOOST #include <boost/version.hpp> #endif #ifdef SCAFES_HAVE_BOOST_SERIALIZATION // Forward declaration. namespace boost { namespace serialization { class access; } } #include <boost/serialization/version.hpp> #if BOOST_VERSION < 105900 #include <boost/serialization/pfto.hpp> #endif #include <boost/serialization/vector.hpp> #include <boost/config/suffix.hpp> #endif #include "ScaFES_Ntuple.hpp" #include "ScaFES_Ntuple_FreeFunctions.hpp" namespace ScaFES { /******************************************************************************* ******************************************************************************/ /** * \class Grid * @brief The class template \c Grid represents a structured grid * of dimension \c DIM, where \c DIM is the template parameter of the class * template. A grid is a \c DIM - dimensional hypercuboid. * * The grid nodes are numbered in two different ways: * <ul> * <li> globally, i.e. all grid nodes of the WHOLE MPI domain are numbered * lexicographically, </li> * <li> locally, i.e. all grid nodes of ONE MPI partition are numbered * lexicographically. </li> * </ul> * * As the nodes of the grid are lexicographically numbered, the first and * the last node number of the grid together with its corresponding coordinates * have to be stored, only. * * Due to the lexicographical node numbering, the coordinates of all nodes * can be easily computed. For this purpose, the method \c coordinates() was * provided. * * Furthermore, the class contains an iterator class. As the iterator is * designed like an STL iterator, it can be applied completely analogously. * The most important components of the inner class \c Iterator are the member * methods \c idxNode() and \c idxScalarNode(). The first one returns * the current node number in tuple notation, the second on returns * the current node number as a scalar number. * * Numbering of grid nodes for DIM = 3 of a grid with n^3 nodes: * Gap in y-direction: n (1, n+1, 2*n+1, 3*n+1,...) * Gap in z-direction: n^2 (n^2, 2*n^2, 3*n^2,....) * *-----------------* n^3 * / /| * / / | * / / | * / (n-1)*n^2+n / | * *----------------* | * | | * n^2 * | | / * | | / * | | / * | |/ * 1 *----------------* n * * \n Numbering of grid faces for DIM = 3: * ^ ^ * | / Back = 3 * | Top = 4/ * / * *-----------------* * / /| * / / | * / / | * / / | * *-----------------* | * | | * * <------ | | / -------> * Left=1 | | / Right = 0 * | | / * | |/ * *-----------------* * Right: direction = 0 * Left: direction = 1 | Bottom = 5 * Top: direction = 2 | * Bottom: direction = 3 | * Front: direction = 4 v * Back: direction = 5 */ template <std::size_t DIM = 3> class Grid { public: /*---------------------------------------------------------------------- | INTERNAL CLASSES. ----------------------------------------------------------------------*/ /** Class for iterating through the grid.*/ class Iterator : public std::iterator<std::random_access_iterator_tag, ScaFES::Ntuple<int, DIM>> { public: /*-------------------------------------------------------------- | LIFE CYCLE METHODS. --------------------------------------------------------------*/ /** Creates own constructor. * \param gridIter Given grid over which will be iterated. * \param idxNode Iteration will start from this node. */ Iterator(const Grid<DIM>* gridIter, const ScaFES::Ntuple<int, DIM>& idxNode); /*-------------------------------------------------------------- | GETTER METHODS. --------------------------------------------------------------*/ /** Returns the index of the current node. */ const ScaFES::Ntuple<int, DIM>& idxNode() const; /** Returns the scalar index of the current node. */ const unsigned long int& idxScalarNode() const; /*-------------------------------------------------------------- | COMPARISON METHODS. --------------------------------------------------------------*/ /** Checks if the local node number of this iterator is unequal * to the one of the given iterator. */ bool operator!=(const Iterator& other) const; /** Checks if the local node number of this iterator is smaller * than the one of the given iterator. */ bool operator<(const Iterator& other) const; /*-------------------------------------------------------------- | WORK METHODS. --------------------------------------------------------------*/ /** Returns the index of the current node. */ const ScaFES::Ntuple<int, DIM>& operator*(); /** Increases the current local and the current global * node number. * \remarks Prefix variant. */ Iterator& operator++(); /** Increases the current local and the current global * node number. * \remarks Postfix variant. */ Iterator operator++(int /*incr*/); private: /*-------------------------------------------------------------- | MEMBER VARIABLES. --------------------------------------------------------------*/ /** Grid over which should be iterated. */ const Grid<DIM>* mGridIter; /** Index of current node. */ ScaFES::Ntuple<int, DIM> mIdxNode; /** Scalar index of current node. */ unsigned long int mIdxScalarNode; /*-------------------------------------------------------------- | INTERNAL WORK METHODS. --------------------------------------------------------------*/ /** Increases the current local and the current global node * number iterating "columnwise" through the grid. */ Iterator& nextStyleC(); /** Increases the current local and the current global node * number iterating "rowwise" through the grid. */ Iterator& nextStyleFortran(); /*-------------------------------------------------------------- | FRIEND CLASSES. --------------------------------------------------------------*/ friend class Grid<DIM>; }; /*---------------------------------------------------------------------- | TYPE DEFINITIONS. ----------------------------------------------------------------------*/ /** Type definition for iterator class analogously to STL class. */ typedef Iterator iterator; /** Type definition for iterator class analogously to STL class. */ typedef const Iterator const_iterator; /** Type definition for iterator class analogously to STL class. */ typedef ScaFES::Ntuple<int, DIM>& reference_type; /*---------------------------------------------------------------------- | FRIEND CLASSES. ----------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION friend class boost::serialization::access; #endif /*---------------------------------------------------------------------- | LIFE CYCLE METHODS. ----------------------------------------------------------------------*/ /** Creates the default constructor. */ Grid(); /** Creates a new grid with given first global node number and * given last global node together with its corresponding coordinates. * TODO: Reason for pass-by-value of coordinates?! [KF], 2015-11-17 * \param idxNodeFirst Index of first node. * \param idxNodeLast Index of last node. * \param coordNodeFirst Coordinates of first node. * \param coordNodeLast Coordinates of last node. */ Grid(const ScaFES::Ntuple<int, DIM>& idxNodeFirst, const ScaFES::Ntuple<int, DIM>& idxNodeLast, ScaFES::Ntuple<double, DIM> coordNodeFirst, ScaFES::Ntuple<double, DIM> coordNodeLast); /** Creates own copy constructor. */ Grid(const Grid<DIM>& rhs); /** Creates own assignment operator using the copy-and-swap idiom. */ Grid& operator=(Grid<DIM> rhs); /** Creates own destructor. */ ~Grid(); /*---------------------------------------------------------------------- | GETTER METHODS. ----------------------------------------------------------------------*/ /** Returns the dimension of the grid. */ std::size_t dimGrid() const; /** Returns the index of the first node. */ const ScaFES::Ntuple<int, DIM>& idxNodeFirst() const; /** Returns the component \c idx of the index of the first node. */ const int& idxNodeFirst(const int& idx) const; /** Returns the index of the last node. */ const ScaFES::Ntuple<int, DIM>& idxNodeLast() const; /** Returns the component \c idx of the index of the last node. */ const int& idxNodeLast(const int& idx) const; /** Returns the number of nodes of the grid in each direction. */ const ScaFES::Ntuple<int, DIM>& nNodes() const; /** Returns the number of nodes of the grid in one given direction. */ const int& nNodes(const int& idx) const; /** Returns the total number of nodes of the grid. */ int nNodesTotal() const; /** Returns the coordinates of the first node. */ const ScaFES::Ntuple<double, DIM>& coordNodeFirst() const; /** Returns the coordinates of the last node. */ const ScaFES::Ntuple<double, DIM>& coordNodeLast() const; /** Returns the grid size in all directions. */ const ScaFES::Ntuple<double, DIM>& gridsize() const; /** Returns the grid size in one given direction. */ const double& gridsize(const int& idx) const; /** Returns if the grid is numbered in C style notation. */ const bool& isNumberedStyleC() const; /*---------------------------------------------------------------------- | COMPARISON METHODS. ----------------------------------------------------------------------*/ /** Tests if two grids are equal. */ bool operator==(const Grid<DIM>& rhs) const; /** Tests if two grids are not equal. */ bool operator!=(const Grid<DIM>& rhs) const; /*---------------------------------------------------------------------- | WORK METHODS. ----------------------------------------------------------------------*/ /** Returns an iterator which will start with the first node of the * underlying grid. */ iterator begin() const; /** Returns an iterator which will start with the last node of the * underlying grid. */ iterator end() const; /** Computes the corresponding scalar node number of a given node number * of the grid. * \param idxNode ScaFES::Ntuple<int,DIM> of a given node. */ unsigned long int idxNodeTuple2Scalar(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given node number * of the grid. * \param idxNodeScalar Scalar index of a given node. * \param idxNode ScaFES::Ntuple<int,DIM> of a given node. */ void idxNodeTuple2Scalar(unsigned long int& idxNodeScalar, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding node number from a given scalar * node number. * \param idxScalarNode Scalar index of a given node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2Tuple(const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number from a given scalar * node number. * \param idxNode ScaFES::Ntuple<int,DIM> tuple of a given node. * \param idxScalarNode Scalar index of a given node number. */ void idxNodeScalar2Tuple(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; /** Computes the coordinates of a given node number of the grid. * \param idxNode Given node number */ ScaFES::Ntuple<double, DIM> coordinates(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Returns true if the first node number is equal or smaller the * the last node number, i.e. if the grid consists of at * least one node. */ bool valid() const; /** Returns true if a given node number is inside the grid. */ bool inside(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Extends the underlying grid by a given border width into a * given direction and returns the new modified grid. * The coordinates of the extended grid will remain the same as before, * whereas the number of nodes within the same physical domain will * increases. * \param dir Direction to expand. * \param nLayers Number of layers to expand into the given dir. * \remarks The ordering of the direction is as given in the * description of this class. */ Grid<DIM> extend(const int& dir, const int& nLayers); /** Returns the union of this grid and another given grid. * It will be assumed that both grids have the same grid sizes! * \return Grid gg(min(mIdxNodeFirst, rhs.idxNodeFirst), * max(mIdxNodeLast, rhs.idxNodeLast)) */ Grid<DIM> unionWith(const Grid<DIM>& rhs) const; /** Returns the intersection of this grid and another given grid. * It will be assumed that both grids have the same grid sizes! * \return Grid gg(max(mIdxNodeFirst, rhs.idxNodeFirst), * min(mIdxNodeLast, rhs.idxNodeLast)) */ Grid<DIM> intersectWith(const Grid<DIM>& rhs) const; #ifdef SCAFES_HAVE_BOOST_SERIALIZATION /** Serializes the class. */ template <class Archive> void serialize(Archive& ar, const unsigned int version); #endif /** Returns all direct neighboured LOCAL node numbers * of a given node number. */ Ntuple<unsigned long int, 2 * DIM> connect(const ScaFES::Ntuple<int, DIM>& idxNode); /** Determines the neighbour global node into a given direction * of a global node number. */ ScaFES::Ntuple<int, DIM> neigh(const ScaFES::Ntuple<int, DIM>& idxNode, const int& dir) const; /*---------------------------------------------------------------------- | FREE METHODS. ----------------------------------------------------------------------*/ /** Swaps the members of two grids. */ template <std::size_t SS> friend void swap(ScaFES::Grid<SS>& first, ScaFES::Grid<SS>& second); /** Overloads the output operator. */ template <std::size_t SS> friend std::ostream& operator<<(std::ostream& output, const ScaFES::Grid<SS>& rhs); protected: /*---------------------------------------------------------------------- | MEMBER VARIABLES. ----------------------------------------------------------------------*/ /** First node number of the grid. */ ScaFES::Ntuple<int, DIM> mIdxNodeFirst; /** Last node number of the grid. */ ScaFES::Ntuple<int, DIM> mIdxNodeLast; /** Number of nodes of the grid in all directions. */ ScaFES::Ntuple<int, DIM> mNnodes; /** Coordinate of the first node number. */ ScaFES::Ntuple<double, DIM> mCoordNodeFirst; /** Coordinate of the last node number. */ ScaFES::Ntuple<double, DIM> mCoordNodeLast; /** Grid size in all directions. */ ScaFES::Ntuple<double, DIM> mGridsize; /** Is grid numbered in C style notation (alternative: FORTRAN style).*/ bool mIsNumberedStyleC; private: /*---------------------------------------------------------------------- | INTERNAL METHODS. ----------------------------------------------------------------------*/ /** Computes the corresponding scalar node number of a given * node number of the grid using the C style. * \param idxNode Given node number */ unsigned long int idxNodeTuple2ScalarStyleC(const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the C style. * \param idxScalarNode Corresponding scalar node number (return value). * \param idxNode Given node number. */ void idxNodeTuple2ScalarStyleC(unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the FORTRAN style. * \param idxNode Given node number. * \return Corresponding scalar node number. */ unsigned long int idxNodeTuple2ScalarStyleFortran( const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding scalar node number of a given * node number of the grid using the FORTRAN style. * \param idxScalarNode Corresponding scalar node number (return value). * \param idxNode Given node number. */ void idxNodeTuple2ScalarStyleFortran( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the C style. * \param idxScalarNode Given scalar node number * \return Corresponding node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2TupleStyleC(const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the C style. * \param idxNode Corresponding node number (return value). * \param idxScalarNode Given scalar node number */ void idxNodeScalar2TupleStyleC(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the Fortran style. * \param idxScalarNode Given scalar node number. * \return Corresponding node number. */ ScaFES::Ntuple<int, DIM> idxNodeScalar2TupleStyleFortran( const unsigned long int& idxScalarNode) const; /** Computes the corresponding node number of a given scalar * node number of the grid using the Fortran style. * \param idxNode Corresponding node number (return value). * \param idxScalarNode Given scalar node number. */ void idxNodeScalar2TupleStyleFortran(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const; }; // End of class. // /******************************************************************************* * FREE METHODS. ******************************************************************************/ /** Swaps two objects of the class \c Grid. */ template <std::size_t DIM> void swap(ScaFES::Grid<DIM>& first, ScaFES::Grid<DIM>& second); /*----------------------------------------------------------------------------*/ /** Preprares writing an object of the class \c Grid to output. */ template <std::size_t DIM> std::ostream& operator<<(std::ostream& output, const ScaFES::Grid<DIM>& gg); /******************************************************************************* * LIFE CYCLE METHODS. ******************************************************************************/ template <std::size_t DIM> inline Grid<DIM>::Grid() : mIdxNodeFirst(0), mIdxNodeLast(1), mNnodes(2), mCoordNodeFirst(0.0), mCoordNodeLast(1.0), mGridsize(1.0), mIsNumberedStyleC(false) { } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::Grid(const ScaFES::Ntuple<int, DIM>& idxNodeFirst, const ScaFES::Ntuple<int, DIM>& idxNodeLast, ScaFES::Ntuple<double, DIM> coordNodeFirst, ScaFES::Ntuple<double, DIM> coordNodeLast) : mIdxNodeFirst(idxNodeFirst), mIdxNodeLast(idxNodeLast), mNnodes(idxNodeLast - idxNodeFirst + ScaFES::Ntuple<int, DIM>(1)), mCoordNodeFirst(coordNodeFirst), mCoordNodeLast(coordNodeLast), mGridsize(), mIsNumberedStyleC(false) { if (0 < this->nNodes().size()) { for (std::size_t ii = 0; ii < DIM; ++ii) { this->mGridsize[ii] = (coordNodeLast.elem(ii) - coordNodeFirst.elem(ii)) / (this->nNodes().elem(ii) - 1); } } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::Grid(const Grid<DIM>& from) : mIdxNodeFirst(from.idxNodeFirst()), mIdxNodeLast(from.idxNodeLast()), mNnodes(from.nNodes()), mCoordNodeFirst(from.coordNodeFirst()), mCoordNodeLast(from.coordNodeLast()), mGridsize(from.gridsize()), mIsNumberedStyleC(from.isNumberedStyleC()) { } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>& Grid<DIM>::operator=(Grid<DIM> rhs) { ScaFES::swap(*this, rhs); return *this; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM>::~Grid() { } /******************************************************************************* * GETTER METHODS. ******************************************************************************/ template <std::size_t DIM> inline std::size_t Grid<DIM>::dimGrid() const { return DIM; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::idxNodeFirst() const { return this->mIdxNodeFirst; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::idxNodeFirst(const int& idx) const { return this->mIdxNodeFirst.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::idxNodeLast() const { return this->mIdxNodeLast; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::idxNodeLast(const int& idx) const { return this->mIdxNodeLast.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::nNodes() const { return this->mNnodes; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const int& Grid<DIM>::nNodes(const int& idx) const { return this->mNnodes.elem(idx); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline int Grid<DIM>::nNodesTotal() const { return this->mNnodes.size(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::coordNodeFirst() const { return this->mCoordNodeFirst; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::coordNodeLast() const { return this->mCoordNodeLast; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const ScaFES::Ntuple<double, DIM>& Grid<DIM>::gridsize() const { return this->mGridsize; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const double& Grid<DIM>::gridsize(const int& ii) const { return this->mGridsize.elem(ii); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const bool& Grid<DIM>::isNumberedStyleC() const { return this->mIsNumberedStyleC; } /******************************************************************************* * WORK METHODS. ******************************************************************************/ template <std::size_t DIM> inline typename Grid<DIM>::iterator Grid<DIM>::begin() const { return iterator(this, this->mIdxNodeFirst); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::iterator Grid<DIM>::end() const { return iterator(this, this->mIdxNodeLast); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2Scalar(const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2Scalar(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2Scalar(unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { if (this->mIsNumberedStyleC) { this->idxNodeTuple2ScalarStyleC(idxScalarNode, idxNode); } else { this->idxNodeTuple2ScalarStyleFortran(idxScalarNode, idxNode); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2Tuple(const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2Tuple(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2Tuple(ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { if (this->mIsNumberedStyleC) { this->idxNodeScalar2TupleStyleC(idxNode, idxScalarNode); } else { this->idxNodeScalar2TupleStyleFortran(idxNode, idxScalarNode); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<double, DIM> Grid<DIM>::coordinates(const ScaFES::Ntuple<int, DIM>& idxNode) const { ScaFES::Ntuple<double, DIM> coord(0.0); for (std::size_t ii = 0; ii < DIM; ++ii) { coord[ii] = this->coordNodeFirst().elem(ii) + this->gridsize(ii) * (idxNode.elem(ii) - this->idxNodeFirst().elem(ii)); } return coord; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::valid() const { return (this->mIdxNodeFirst <= this->mIdxNodeLast); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::inside(const ScaFES::Ntuple<int, DIM>& idxNode) const { return ((this->mIdxNodeFirst <= idxNode) && (idxNode <= this->mIdxNodeLast)); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::extend(const int& dir, const int& nLayers) { ScaFES::Ntuple<int, DIM> idxNodeFirst(this->mIdxNodeFirst); ScaFES::Ntuple<int, DIM> idxNodeLast(this->mIdxNodeLast); int idx = dir / 2; if (0 == (dir % 2)) { idxNodeLast[idx] += nLayers; } else { idxNodeFirst[idx] -= nLayers; } return Grid<DIM>(idxNodeFirst, idxNodeLast, this->coordNodeFirst(), this->coordNodeLast()); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::unionWith(const Grid<DIM>& rhs) const { ScaFES::Ntuple<double, DIM> coordNodeFirstNew; ScaFES::Ntuple<double, DIM> coordNodeLastNew; ScaFES::Ntuple<int, DIM> idxNodeFirstNew = ScaFES::min(idxNodeFirst(), rhs.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeLastNew = ScaFES::max(idxNodeLast(), rhs.idxNodeLast()); if (idxNodeFirstNew == this->idxNodeFirst()) { coordNodeFirstNew = this->coordNodeFirst(); } else { coordNodeFirstNew = rhs.coordNodeFirst(); } if (idxNodeLastNew == this->idxNodeLast()) { coordNodeLastNew = this->coordNodeLast(); } else { coordNodeLastNew = rhs.coordNodeLast(); } return ScaFES::Grid<DIM>(idxNodeFirstNew, idxNodeLastNew, coordNodeFirstNew, coordNodeLastNew); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Grid<DIM> Grid<DIM>::intersectWith(const Grid<DIM>& rhs) const { ScaFES::Ntuple<double, DIM> coordNodeFirstNew; ScaFES::Ntuple<double, DIM> coordNodeLastNew; ScaFES::Ntuple<int, DIM> idxNodeFirstNew = ScaFES::max(this->idxNodeFirst(), rhs.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeLastNew = ScaFES::min(this->idxNodeLast(), rhs.idxNodeLast()); if (idxNodeFirstNew == this->idxNodeFirst()) { coordNodeFirstNew = this->coordNodeFirst(); } else { coordNodeFirstNew = rhs.coordNodeFirst(); } if (idxNodeLastNew == this->idxNodeLast()) { coordNodeLastNew = this->coordNodeLast(); } else { coordNodeLastNew = rhs.coordNodeLast(); } return ScaFES::Grid<DIM>(idxNodeFirstNew, idxNodeLastNew, coordNodeFirstNew, coordNodeLastNew); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::operator==(const Grid<DIM>& rhs) const { return (this->idxNodeFirst() == rhs.idxNodeFirst() && this->idxNodeLast() == rhs.idxNodeLast()); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::operator!=(const Grid<DIM>& rhs) const { return !(*this == rhs); } /*----------------------------------------------------------------------------*/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION template <std::size_t DIM> template <class Archive> inline void Grid<DIM>::serialize(Archive& ar, const unsigned int version) { if (1 <= version) { ar&(this->mIdxNodeFirst); ar&(this->mIdxNodeLast); ar&(this->mNnodes); ar&(this->mCoordNodeFirst); ar&(this->mCoordNodeLast); ar&(this->mGridsize); ar&(this->mIsNumberedStyleC); } } #endif /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline Ntuple<unsigned long int, 2 * DIM> Grid<DIM>::connect(const ScaFES::Ntuple<int, DIM>& idxNode) { // First, set up connectivity for ALL nodes (also for the boundary nodes). // Then, correct the connectivity entries at the boundary nodes. unsigned long int gap; unsigned long int idxScalarNode; ScaFES::Ntuple<unsigned long int, 2 * DIM> neighIdxNode; idxScalarNode = this->idxNodeTuple2Scalar(idxNode); gap = 1; for (std::size_t kk = 0; kk < DIM; ++kk) { neighIdxNode[2 * kk] = idxScalarNode - gap; neighIdxNode[2 * kk + 1] = idxScalarNode + gap; // Adapt boundary of hypercube. if (idxNode.elem(kk) == this->idxNodeFirst(kk)) { neighIdxNode[2 * kk] = -(2 * kk + 1); } else if (idxNode.elem(kk) == this->idxNodeLast(kk)) { neighIdxNode[2 * kk + 1] = -(2 * kk + 2); } gap *= this->nNodes(kk); } return neighIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::neigh(const ScaFES::Ntuple<int, DIM>& idxNode, const int& dir) const { // Adapt boundary of hypercube. ScaFES::Ntuple<int, DIM> neighIdxNode(idxNode); int idx = dir / 2; if (0 == (dir % 2)) { if (idxNode.elem(idx) == this->idxNodeFirst(idx)) { for (std::size_t ii = 0; ii < DIM; ++ii) { neighIdxNode[ii] = -(dir + 1); } } else { --(neighIdxNode[idx]); } } else { if (idxNode.elem(idx) == this->idxNodeLast(idx)) { for (std::size_t ii = 0; ii < DIM; ++ii) { neighIdxNode[ii] = -(dir + 1); } } else { ++(neighIdxNode[idx]); } } return neighIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2ScalarStyleC( const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2ScalarStyleC(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2ScalarStyleC( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { idxScalarNode = idxNode.elem(0) - this->idxNodeFirst(0); for (std::size_t ii = 1; ii < DIM; ++ii) { idxScalarNode = idxScalarNode * this->nNodes(ii) + idxNode.elem(ii) - this->idxNodeFirst(ii); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline unsigned long int Grid<DIM>::idxNodeTuple2ScalarStyleFortran( const ScaFES::Ntuple<int, DIM>& idxNode) const { unsigned long int idxScalarNode = 0L; this->idxNodeTuple2ScalarStyleFortran(idxScalarNode, idxNode); return idxScalarNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeTuple2ScalarStyleFortran( unsigned long int& idxScalarNode, const ScaFES::Ntuple<int, DIM>& idxNode) const { idxScalarNode = idxNode.elem(DIM - 1) - this->idxNodeFirst(DIM - 1); const int dimLocal = DIM; for (int ii = dimLocal - 2; ii >= 0; --ii) { idxScalarNode = idxScalarNode * this->nNodes(ii) + idxNode.elem(ii) - this->idxNodeFirst(ii); } } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2TupleStyleC( const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2TupleStyleC(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2TupleStyleC( ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { int tmp = idxScalarNode; for (std::size_t ii = DIM - 1; ii > 0; --ii) { idxNode[ii] = (tmp % this->nNodes(ii)) + this->idxNodeFirst(ii); tmp /= (this->nNodes(ii)); } idxNode[0] = tmp; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline ScaFES::Ntuple<int, DIM> Grid<DIM>::idxNodeScalar2TupleStyleFortran( const unsigned long int& idxScalarNode) const { ScaFES::Ntuple<int, DIM> idxNode; this->idxNodeScalar2TupleStyleFortran(idxNode, idxScalarNode); return idxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline void Grid<DIM>::idxNodeScalar2TupleStyleFortran( ScaFES::Ntuple<int, DIM>& idxNode, const unsigned long int& idxScalarNode) const { int tmp = idxScalarNode; for (std::size_t ii = 0; ii < DIM; ++ii) { idxNode[ii] = (tmp % this->nNodes(ii)) + this->idxNodeFirst(ii); tmp /= (this->nNodes(ii)); } } /******************************************************************************* * INLINED OPERATORS (FREE FUNCTIONS) ******************************************************************************/ template <std::size_t DIM> inline void swap(Grid<DIM>& first, Grid<DIM>& second) { ScaFES::swap(first.mIdxNodeFirst, second.mIdxNodeFirst); ScaFES::swap(first.mIdxNodeLast, second.mIdxNodeLast); ScaFES::swap(first.mNnodes, second.mNnodes); ScaFES::swap(first.mCoordNodeFirst, second.mCoordNodeFirst); ScaFES::swap(first.mCoordNodeLast, second.mCoordNodeLast); ScaFES::swap(first.mGridsize, second.mGridsize); std::swap(first.mIsNumberedStyleC, second.mIsNumberedStyleC); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline std::ostream& operator<<(std::ostream& output, const Grid<DIM>& gg) { output << "* GRID:" << std::endl << " -Node First:" << gg.idxNodeFirst() << std::endl << " -Node Last: " << gg.idxNodeLast() << std::endl << " -Coordinates(Node First): " << gg.coordNodeFirst() << std::endl << " -Coordinates(Node Last): " << gg.coordNodeLast() << std::endl; return output; } /******************************************************************************* * INTERNAL CLASS ITERATOR: LIFE CYCLE METHODS. ******************************************************************************/ template <std::size_t DIM> inline Grid<DIM>::Iterator::Iterator(const Grid<DIM>* gridIter, const ScaFES::Ntuple<int, DIM>& idxNode) : mGridIter(gridIter), mIdxNode(idxNode), mIdxScalarNode(gridIter->idxNodeTuple2Scalar(idxNode)) { // TODO: Check if \c idxNode is inside underlying grid. } /******************************************************************************* * INTERNAL CLASS ITERATOR: GETTER METHODS. ******************************************************************************/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::Iterator::idxNode() const { return this->mIdxNode; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline const unsigned long int& Grid<DIM>::Iterator::idxScalarNode() const { return this->mIdxScalarNode; } /******************************************************************************* * INTERNAL CLASS ITERATOR: COMPARISON METHODS. ******************************************************************************/ template <std::size_t DIM> inline bool Grid<DIM>::Iterator::operator!=(const Iterator& other) const { return (*this < other) || (other < *this); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline bool Grid<DIM>::Iterator::operator<(const Iterator& it) const { return (this->idxScalarNode() <= it.idxScalarNode()); } /******************************************************************************* * INTERNAL CLASS ITERATOR: WORK METHODS. ******************************************************************************/ template <std::size_t DIM> inline const ScaFES::Ntuple<int, DIM>& Grid<DIM>::Iterator::operator*() { return this->idxNode(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::operator++() { if (this->mGridIter->isNumberedStyleC()) { return this->nextStyleC(); } return this->nextStyleFortran(); } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator Grid<DIM>::Iterator::operator++(int /*incr*/) { Iterator tmp = *this; ++(*this); return tmp; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::nextStyleC() { ++(this->mIdxScalarNode); ++(this->mIdxNode[DIM - 1]); const int DIM_MINUS_ONE = DIM - 1; for (int ii = DIM_MINUS_ONE; ii > 0; --ii) { if (this->mIdxNode.elem(ii) > this->mGridIter->idxNodeLast(ii)) { this->mIdxNode[ii] = this->mGridIter->idxNodeFirst(ii); ++(this->mIdxNode[ii - 1]); } } return *this; } /*----------------------------------------------------------------------------*/ template <std::size_t DIM> inline typename Grid<DIM>::Iterator& Grid<DIM>::Iterator::nextStyleFortran() { ++(this->mIdxScalarNode); ++(this->mIdxNode[0]); const int DIM_MINUS_ONE = DIM - 1; for (int ii = 0; ii < DIM_MINUS_ONE; ++ii) { if (this->mIdxNode.elem(ii) > this->mGridIter->idxNodeLast(ii)) { this->mIdxNode[ii] = this->mGridIter->idxNodeFirst(ii); ++(this->mIdxNode[ii + 1]); } } return *this; } } // End of namespace. // /******************************************************************************* ******************************************************************************/ #ifdef SCAFES_HAVE_BOOST_SERIALIZATION namespace boost { namespace serialization { /** Designed to set the boost serialization version of a class template. */ template <std::size_t DIM> struct version<ScaFES::Grid<DIM>> { /** Sets the version number for serialization. */ BOOST_STATIC_CONSTANT(unsigned long int, value = 2); }; } // namespace serialization } // namespace boost #endif #endif
36.718455
81
0.510648
nih23
7e5d1dedcd0ae12c2a1c8a9eacf5e0ecd79c8ded
5,998
cpp
C++
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
Source/Common/Platform/NMR_ExportStream_GCC_Win32.cpp
geaz/lib3mf
fd07e571a869f5c495a3beea014d341d67c9d405
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2019 3MF Consortium 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. Abstract: NMR_ExportStream_GCC_Win32.cpp implements the CExportStream_GCC_Win32 Class. This is an abstract base stream class for exporting with GCC under Windows. --*/ #include "Common/Platform/NMR_ExportStream_GCC_Win32.h" #include "Common/NMR_Exception.h" #ifdef __GCC_WIN32 #include "Common/NMR_Exception_Windows.h" #endif // __GCC_WIN32 namespace NMR { #ifdef __GCC_WIN32 CExportStream_GCC_Win32::CExportStream_GCC_Win32(_In_ const nfWChar * pwszFileName) { if (pwszFileName == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); // Create handle m_hHandle = CreateFileW (pwszFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (m_hHandle == INVALID_HANDLE_VALUE) throw CNMRException_Windows(NMR_ERROR_COULDNOTCREATESTREAM, GetLastError()); } CExportStream_GCC_Win32::~CExportStream_GCC_Win32() { if (m_hHandle != INVALID_HANDLE_VALUE) { CloseHandle(m_hHandle); m_hHandle = 0; } } nfBool CExportStream_GCC_Win32::seekPosition(_In_ nfUint64 position, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = position; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_BEGIN); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfBool CExportStream_GCC_Win32::seekForward(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = bytes; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_CURRENT); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfBool CExportStream_GCC_Win32::seekFromEnd(_In_ nfUint64 bytes, _In_ nfBool bHasToSucceed) { HRESULT hResult = S_OK; nfBool bSuccess = true; LARGE_INTEGER nPosition; nPosition.QuadPart = bytes; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_END); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) bSuccess = false; } if (bSuccess && (!bHasToSucceed)) throw CNMRException_Windows(NMR_ERROR_COULDNOTSEEKSTREAM, hResult); return bSuccess; } nfUint64 CExportStream_GCC_Win32::getPosition() { HRESULT hResult = S_OK; LARGE_INTEGER nPosition; nPosition.QuadPart = 0; nPosition.LowPart = SetFilePointer(m_hHandle, nPosition.LowPart, &nPosition.HighPart, FILE_CURRENT); if (nPosition.LowPart == INVALID_SET_FILE_POINTER) { hResult = GetLastError(); if (hResult != S_OK) throw CNMRException_Windows(NMR_ERROR_COULDNOTGETSTREAMPOSITION, hResult); } return nPosition.QuadPart; } nfUint64 CExportStream_GCC_Win32::writeBuffer(_In_ const void * pBuffer, _In_ nfUint64 cbTotalBytesToWrite) { if (pBuffer == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); const nfByte * pBufP = (const nfByte *) pBuffer; nfUint64 cbBytesLeft = cbTotalBytesToWrite; nfUint64 cbTotalBytesWritten = 0; while (cbBytesLeft > 0) { nfUint32 cbBytesToWrite; long unsigned int cbWrittenBytes = 0; if (cbBytesLeft > NMR_EXPORTSTREAM_WRITEBUFFERSIZE) { cbBytesToWrite = NMR_EXPORTSTREAM_WRITEBUFFERSIZE; } else { cbBytesToWrite = (nfUint32) cbBytesLeft; } if (!WriteFile(m_hHandle, pBufP, cbBytesToWrite, &cbWrittenBytes, nullptr)) { throw CNMRException_Windows(NMR_ERROR_COULDNOTWRITESTREAM, GetLastError()); } if (cbWrittenBytes != cbBytesToWrite) throw CNMRException(NMR_ERROR_COULDNOTWRITEFULLDATA); pBufP += cbWrittenBytes; cbTotalBytesWritten += cbWrittenBytes; cbBytesLeft -= cbWrittenBytes; } return cbTotalBytesWritten; } #endif // __GCC_WIN32 }
32.247312
109
0.702568
geaz
7e5f898ee06344f571798d3c6d9564a146bd2e6e
10,645
hpp
C++
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
map.hpp
majermou/ft_containers
b46a6941689819a74bb86cc2bd1b85fd7252ace7
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: majermou <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/08 17:07:39 by majermou #+# #+# */ /* Updated: 2021/10/28 14:55:05 by majermou ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MAP_HPP #define MAP_HPP #include "avl_tree.hpp" #include "reverse_iterator.hpp" #include "vector.hpp" template<typename T> struct Iterator; template<typename T> struct ConstIterator; namespace ft { template < typename Key, typename T, typename Compare = std::less<Key>, typename Alloc = std::allocator<pair<const Key,T> > > class map { public: typedef Key key_type; typedef T mapped_type; typedef pair<const key_type,mapped_type> value_type; typedef Compare key_compare; typedef Alloc allocator_type; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference const_refernce; typedef typename allocator_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef typename allocator_type::difference_type difference_type; typedef typename allocator_type::size_type size_type; typedef Iterator<value_type> iterator; typedef ConstIterator<value_type> const_iterator; typedef ReverseIterator<iterator> reverse_iterator; typedef ReverseIterator<const_iterator> const_reverse_iterator; class value_compare : public std::binary_function<value_type, value_type, bool> { friend class map; protected: key_compare comp; value_compare(key_compare c) : comp(c) {} public: bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first); } }; private: value_compare m_comp; allocator_type m_allocator; Avl_tree<value_type,value_compare> m_Avl_tree; typedef typename Avl_tree<value_type,value_compare>::AvlNode AvlNode; public: explicit map(const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) : m_comp(comp), m_allocator(alloc), m_Avl_tree(value_compare(m_comp)) { } template <class InputIterator> map(InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) : m_comp(comp), m_allocator(alloc), m_Avl_tree(value_compare(comp)) { insert(first, last); } map (const map& x): m_comp(x.m_comp), m_allocator(x.m_allocator), m_Avl_tree(value_compare(m_comp)) { insert(x.begin(), x.end()); } ~map() { } map& operator=(const map& x) { if (this != &x) { clear(); insert(x.begin(), x.end()); } return *this; } iterator begin() { if (!m_Avl_tree.getMinValNode()) return iterator(m_Avl_tree.getEndNode()); return iterator(m_Avl_tree.getMinValNode()); } const_iterator begin() const { if (!m_Avl_tree.getMinValNode()) return const_iterator(m_Avl_tree.getEndNode()); return const_iterator(m_Avl_tree.getMinValNode()); } iterator end() { return iterator(m_Avl_tree.getEndNode()); } const_iterator end() const { return const_iterator(m_Avl_tree.getEndNode()); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_Avl_tree.isEmpty(); } size_type size() const { return m_Avl_tree.getSize(); } size_type max_size() const { return m_Avl_tree.getMaxSize(); } mapped_type& operator[](const key_type& k) { return (*((insert(ft::make_pair(k,mapped_type()))).first)).second; } pair<iterator,bool> insert(const value_type& val) { AvlNode node = m_Avl_tree.search(val); if (node == m_Avl_tree.getEndNode()) { m_Avl_tree.insert(val); return ft::make_pair(iterator(m_Avl_tree.search(val)), true); } return ft::make_pair(iterator(node), false); } iterator insert(iterator position, const value_type& val) { AvlNode node = m_Avl_tree.search(val); if (node == m_Avl_tree.getEndNode()) { insert(val); return iterator(m_Avl_tree.search(val)); } return iterator(node); position++; } template <class InputIterator> void insert(InputIterator first, InputIterator last) { while (first != last) { insert(ft::make_pair(first->first,first->second)); first++; } } void erase(iterator position) { if (position != iterator(NULL)) { m_Avl_tree.remove(ft::make_pair(position->first,position->second)); } } size_type erase(const key_type& k) { if (m_Avl_tree.search(ft::make_pair(k,mapped_type())) == m_Avl_tree.getEndNode()) { return 0; } m_Avl_tree.remove(ft::make_pair(k,mapped_type())); return 1; } void erase(iterator first, iterator last) { while (first != last) { erase(first++); } } void swap(map& x) { m_Avl_tree.swap(x.m_Avl_tree); } void clear() { m_Avl_tree.clear(); } key_compare key_comp() const { return key_compare(); } value_compare value_comp() const { return value_compare(m_comp); } iterator find(const key_type& k) { return iterator(m_Avl_tree.search(ft::make_pair(k,mapped_type()))); } const_iterator find(const key_type& k) const { return const_iterator(m_Avl_tree.search(ft::make_pair(k,mapped_type()))); } size_type count(const key_type& k) const { return (m_Avl_tree.search(ft::make_pair(k,mapped_type())) == m_Avl_tree.getEndNode()) ? 0 : 1; } iterator lower_bound(const key_type& k) { return iterator(m_Avl_tree.lower_bound(ft::make_pair(k,mapped_type()))); } const_iterator lower_bound(const key_type& k) const { return const_iterator(m_Avl_tree.lower_bound(ft::make_pair(k,mapped_type()))); } iterator upper_bound(const key_type& k) { return iterator(m_Avl_tree.upper_bound(ft::make_pair(k,mapped_type()))); } const_iterator upper_bound(const key_type& k) const { return const_iterator(m_Avl_tree.upper_bound(ft::make_pair(k,mapped_type()))); } ft::pair<const_iterator,const_iterator> equal_range(const key_type& k) const { return ft::make_pair(lower_bound(k), upper_bound(k)); } ft::pair<iterator,iterator> equal_range(const key_type& k) { return ft::make_pair(lower_bound(k), upper_bound(k)); } allocator_type get_allocator() const { return allocator_type(); } }; } template<typename T> struct Iterator{ typedef T value_type; typedef T* pointer; typedef T& reference; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef Iterator<T> Self; typedef typename Node<T>::NodePtr NodePtr; Iterator(): m_node() {} explicit Iterator(NodePtr x): m_node(x) {} reference operator*() const { return (m_node)->data; } pointer operator->() const { return &(m_node)->data; } Self operator++() { m_node = Avl_tree_increment<NodePtr>(m_node); return *this; } Self operator++(int) { Self tmp = *this; m_node = Avl_tree_increment<NodePtr>(m_node); return tmp; } Self operator--() { m_node = Avl_tree_decrement<NodePtr>(m_node); return *this; } Self operator--(int) { Self tmp = *this; m_node = Avl_tree_decrement<NodePtr>(m_node); return tmp; } bool operator==(const Self& x) const { return m_node == x.m_node; } bool operator!=(const Self& x) const { return m_node != x.m_node; } NodePtr m_node; }; template<typename T> struct ConstIterator { typedef T value_type; typedef const T* pointer; typedef const T& reference; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef Iterator<T> iterator; typedef ConstIterator<T> Self; typedef typename Node<T>::Const_NodePtr NodePtr; ConstIterator(): m_node() { } explicit ConstIterator(NodePtr x): m_node(x) { } ConstIterator(const iterator& it): m_node(it.m_node) { } reference operator*() const { return (m_node)->data; } pointer operator->() const { return &(m_node)->data; } Self& operator++() { m_node = Avl_tree_increment<NodePtr>(m_node); return *this; } Self operator++(int) { Self tmp = *this; m_node = Avl_tree_increment<NodePtr>(m_node); return tmp; } Self& operator--() { m_node = Avl_tree_decrement<NodePtr>(m_node); return *this; } Self operator--(int) { Self tmp = *this; m_node = Avl_tree_decrement<NodePtr>(m_node); return tmp; } bool operator==(const Self& x) const { return m_node == x.m_node; } bool operator!=(const Self& x) const { return m_node != x.m_node; } NodePtr m_node; }; template<typename NodePtr> bool operator==(const Iterator<NodePtr>& x, const ConstIterator<NodePtr>& y) { return x.m_node == y.m_node; } template<typename NodePtr> bool operator!=(const Iterator<NodePtr>& x, const ConstIterator<NodePtr>& y) { return x.m_node != y.m_node; } #endif // MAP_HPP
32.063253
98
0.584688
majermou