hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3764cc4b84406d41e5a8ca372a2e8f204b4dfab6
1,144
cpp
C++
src/input/InputHandler.cpp
Estebanan/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
3
2019-07-31T06:13:41.000Z
2021-04-04T15:32:40.000Z
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
src/input/InputHandler.cpp
MarcelIwanicki/glSolarSystem
fd57ca572a039d57f7944cc03bced96159918dfa
[ "MIT" ]
null
null
null
#include "InputHandler.h" static constexpr unsigned int MAX_KEYS = 1024; static constexpr unsigned int MAX_MOUSEBUTTONS = 32; static bool keys[MAX_KEYS] = {false}; static bool mousebuttons[MAX_MOUSEBUTTONS] = {false}; static int mouse_x; static int mouse_y; bool InputHandler::isKeyPressed(unsigned int key) { if(key >= 0 && key < MAX_KEYS) return keys[key]; else return false; } bool InputHandler::isMouseButtonPressed(unsigned int mousebutton) { if(mousebutton >= 0 && mousebutton < MAX_MOUSEBUTTONS) return mousebuttons[mousebutton]; else return false; } void InputHandler::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { keys[key] = action != GLFW_RELEASE; } void InputHandler::mouseButtonCallback(GLFWwindow *window, int button, int action, int mods) { mousebuttons[button] = action != GLFW_RELEASE; } void InputHandler::cursorPositionCallback(GLFWwindow *window, double xpos, double ypos) { mouse_x = xpos; mouse_y = ypos; } int InputHandler::getMouseX() { return mouse_x; } int InputHandler::getMouseY() { return mouse_y; }
24.869565
97
0.714161
Estebanan
3766f6f9125d4549e0161570c5f138a8acec49e9
1,991
cpp
C++
fluffy/core/src/api/modules.cpp
Lo-X/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2015-12-27T14:42:53.000Z
2018-04-18T07:28:05.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
3
2018-04-27T14:26:29.000Z
2021-01-29T16:28:18.000Z
fluffy/core/src/api/modules.cpp
lazybobcat/fluffy
24acf297ca81c611053fd4f55ea0988d65e84168
[ "WTFPL" ]
null
null
null
#include <fluffy/api/context.hpp> #include <fluffy/api/modules.hpp> #include <fluffy/graphics/shader.hpp> #include <fluffy/graphics/texture.hpp> #include <fluffy/input/input.hpp> #include <fluffy/resources/resource_library.hpp> using namespace Fluffy; void ModuleRegistry::registerModule(BaseModule* module) { ModuleType type = module->getType(); auto it = mRegistry.find(type); if (it != mRegistry.end()) { FLUFFY_LOG_WARN("Module '{}' of type '{}' has already been registered. Removing it.", it->second->getName(), EnumNames::ModuleType[(int)type]); delete it->second; } mRegistry[type] = module; } std::map<ModuleType, BaseModule*> ModuleRegistry::getModules() const { return mRegistry; } BaseModule* ModuleRegistry::getModule(ModuleType type) const { auto it = mRegistry.find(type); if (it != mRegistry.end()) { return it->second; } return nullptr; } /**********************************************************************************************************************/ void SystemModule::initialize(const Context& context) { mResources = CreateUnique<ResourceLibrary>(context); mResources->init<Texture2D>(); // mResources->init<Shader>(); } void SystemModule::terminate() { } ResourceLibrary& SystemModule::getResources() const { return *mResources; } /**********************************************************************************************************************/ VideoModule::VideoModule(Window::Definition&& windowDefinition) : mWindowDefinition(windowDefinition) { } void VideoModule::initialize(const Context& context) { mWindow = createWindow(mWindowDefinition); } void VideoModule::terminate() { } /**********************************************************************************************************************/ void InputModule::initialize(const Context& context) { Input::create(context.video->getWindow()); } void InputModule::terminate() { }
24.580247
151
0.575088
Lo-X
376853218b7f464eea1549c8f70589ea89b5519c
634
cpp
C++
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
test/testworker.cpp
43437/EventLoop
46a8f6d67201669e9f57a51df83263a5e5d5eddb
[ "MIT" ]
null
null
null
#include "testall.h" #include "cworkplace.h" #include <iostream> #include "cworkerbuilder.h" #include "cluaworker.h" namespace KOT { void TestWorker() { std::cout << "===========TestWorker==========" << std::endl; CLuaWorkerBuilder builder; builder.SetWorkerPath("../script/test/"); // builder.AddEnvPath("../script/test/?.lua"); // TestWorkerBuilder builder; CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker1")); CWorkPlace::GetInstance().AddWorker(builder.SetWorkerID("worker2")); CWorkPlace::GetInstance().Exec(); std::cout << "=============================" << std::endl; } }
26.416667
72
0.623028
43437
3769d204cf627abd6b7049c46d29850bf6eade8b
3,454
cpp
C++
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
6
2016-06-08T05:29:49.000Z
2020-05-26T14:07:01.000Z
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
src/Game.cpp
Mobiletainment/Connect-Four
5627d103dc977af19447136fb1fb9f8a925d8cec
[ "MIT", "Unlicense" ]
null
null
null
#include "precomp.h" #include "Game.h" using namespace std; CL_GraphicContext *Game::gc; string Game::winner; Game::Game(CL_DisplayWindow &window) { gc = &window.get_gc(); board = &Board::GetInstance(); startMessage = new string("Press [1] to start first, or\n\n\nPress [2] to start with computer"); whichPlayer[0] = "Player White (You)"; whichPlayer[1] = "Player Black (Computer)"; } Game::~Game(){ delete player; delete computer; } void Game::Run(CL_DisplayWindow &window){ game_display_window = window; *gc = window.get_gc(); quit = false; CL_Slot slot_key_down = window.get_ic().get_keyboard().sig_key_down().connect(this, &Game::OnKeyDown); function<void(string)> callbackFunction; callbackFunction = &(Game::PlayerHasWonNotification); player = new Player(*gc, callbackFunction); player->AttachKeyboard(game_display_window); computer = new PlayerNPC(*gc,callbackFunction); sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); //Set up font CL_FontDescription system_font_desc; system_font_desc.set_typeface_name("courier new"); CL_Font_System system_font(*gc, system_font_desc); system_font.set_font_metrics(CL_FontMetrics(7.0f)); string spacing = " "; string columnIdentifiers = "Use keys: [1] [2] [3] [4] [5] [6] [7]"; system_font.draw_text(*gc, 10, 20, *startMessage); window.flip(0); while (startMessage != nullptr) { CL_KeepAlive::process(); } char numberOfMinMaxCalls[32]; numberOfMinMaxCalls[0] = '\0'; while (!quit) { gc->clear(CL_Colorf(20, 56, 108)); int currentPlayer = board->Turn % 2; if (currentPlayer == 0) system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[0]); else system_font.draw_text(*gc, 10, 20, "Current Turn: " + whichPlayer[1]); //Draw column numbers system_font.draw_text(*gc, 10, 120, columnIdentifiers); board->Draw(*gc); system_font.draw_text(*gc, 350, 50, numberOfMinMaxCalls); system_font.draw_text(*gc, 410, 80, horizonMessage); if(!winner.empty()) { system_font.draw_text(*gc, 10, 60, winner); } window.flip(0); CL_KeepAlive::process(); if (currentPlayer == 0) player->WaitForTurn(); else { int minMaxCalls = computer->WaitForTurn(); sprintf_s(numberOfMinMaxCalls, "#MinMaxCalls: %d", minMaxCalls); } } } string Game::GetActivePlayerName(Player *playerKI) { if(playerKI->PlayerIdentifier() == 'o') { return "Black Player"; } else return "White Player"; } void Game::PlayerHasWonNotification(string whosTheWinner) { if (winner.empty()) //only assign winner the first time a winner is determined winner = whosTheWinner; } void Game::OnKeyDown(const CL_InputEvent &key, const CL_InputState &state) { if (key.id == CL_KEY_ESCAPE) quit = true; else if (startMessage != nullptr && key.id == CL_KEY_1) { board->Turn = 0; //player 1 makes all even turns, computer all odd delete startMessage; startMessage = nullptr; } else if (startMessage != nullptr && key.id == CL_KEY_2) { board->Turn = 1; //cheap trick to start with computer instead of player delete startMessage; startMessage = nullptr; } else if (key.id == CL_KEY_UP) { if (PlayerNPC::Horizon < 42) { PlayerNPC::Horizon += 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } else if (key.id == CL_KEY_DOWN) { if (PlayerNPC::Horizon > 0) { PlayerNPC::Horizon -= 1; sprintf_s(horizonMessage, "Horizon: %d", PlayerNPC::Horizon); } } }
24.671429
103
0.690214
Mobiletainment
3769fa67cbbf10f4f4b80414b2bc8a4a39fb5aed
6,302
cpp
C++
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
5
2016-06-14T17:56:47.000Z
2022-02-10T19:54:25.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
42
2016-06-21T20:48:22.000Z
2021-03-23T15:20:51.000Z
libace/filesystem/Path.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
1
2016-10-02T02:58:49.000Z
2016-10-02T02:58:49.000Z
/** * Copyright (c) 2016 Xavier R. Guerin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <ace/filesystem/Path.h> #include <ace/common/String.h> #include <sstream> #include <string> #include <vector> namespace ace { namespace fs { Path::Path(std::string const& v, bool enforceDir) : Path() { std::vector<std::string> elems; common::String::split(v, '/', elems); for (size_t i = 0; i < elems.size(); i += 1) { if (not elems[i].empty() || (elems[i].empty() && (i == 0 or i == elems.size() - 1))) { m_elements.push_back(elems[i]); } } if (not isDirectory() and enforceDir) { m_elements.push_back(std::string()); } } Path::Path(std::vector<std::string> const& c) : m_elements(c) {} Path Path::operator-(Path const& o) const { if (m_elements.empty()) { return Path(); } if (o.empty()) { return Path(*this); } std::vector<std::string> vals; auto ita = m_elements.begin(); auto itb = o.m_elements.begin(); while (ita != m_elements.end() and itb != o.m_elements.end()) { if (*ita != *itb) { break; } ita++, itb++; } if (ita == m_elements.end() || (itb != o.m_elements.end() && not itb->empty())) { return Path(); } while (ita != m_elements.end()) { vals.push_back(*ita++); } return Path(vals); } Path Path::operator/(Path const& o) const { if (o.isAbsolute()) { return Path(); } if (m_elements.empty() or not isDirectory()) { return Path(); } std::vector<std::string> elems(m_elements); elems.erase(--elems.end()); for (auto& e : o.m_elements) { elems.push_back(e); } return Path(elems); } std::string Path::toString() const { std::ostringstream oss; oss << *this; return oss.str(); } Path Path::prune() const { std::vector<std::string> elems(m_elements); if (not elems.empty()) { if ((--elems.end())->empty()) { elems.erase(--elems.end()); } elems.erase(--elems.end()); if (not elems.empty()) { elems.push_back(""); } } return Path(elems); } Path Path::compress() const { std::vector<std::string> elems; for (auto& e : m_elements) { if (e == ".") { continue; } elems.push_back(e); } return Path(elems); } bool Path::isAbsolute() const { if (m_elements.empty()) { return false; } return (*m_elements.begin()).empty(); } bool Path::isDirectory() const { if (m_elements.empty()) { return false; } return (*m_elements.rbegin()).empty(); } std::string Path::prefix(std::string const& a, std::string const& b) { Path pa(a), pb(b); return prefix(pa, pb).toString(); } Path Path::prefix(Path const& a, Path const& b) { std::vector<std::string> vals; if (a.empty() or b.empty()) { return Path(); } auto ita = a.begin(); auto itb = b.begin(); while (ita != a.end() and itb != b.end()) { if (*ita != *itb) { break; } vals.push_back(*ita); ita++, itb++; } if (ita == a.end() and itb == b.end()) { return Path(vals); } else if (ita != a.end() and itb != b.end()) { vals.push_back(std::string()); return Path(vals); } else if ((ita != a.end() and itb == b.end()) || (ita == a.end() and itb != b.end())) { if (not vals.empty()) { vals.erase(--vals.end()); vals.push_back(std::string()); return Path(vals); } } return Path(); } std::ostream& operator<<(std::ostream& o, Path const& p) { for (size_t i = 0; i < p.m_elements.size(); i += 1) { o << p.m_elements[i]; if (i < p.m_elements.size() - 1) { o << "/"; } } return o; } bool Path::operator==(Path const& o) const { return m_elements == o.m_elements; } bool Path::operator!=(Path const& o) const { return m_elements != o.m_elements; } bool Path::empty() const { return m_elements.empty(); } Path::iterator Path::begin() { return m_elements.begin(); } Path::const_iterator Path::begin() const { return m_elements.begin(); } Path::iterator Path::end() { return m_elements.end(); } Path::const_iterator Path::end() const { return m_elements.end(); } Path::reverse_iterator Path::rbegin() { return m_elements.rbegin(); } Path::const_reverse_iterator Path::rbegin() const { return m_elements.rbegin(); } Path::reverse_iterator Path::rend() { return m_elements.rend(); } Path::const_reverse_iterator Path::rend() const { return m_elements.rend(); } Path::iterator Path::up(iterator const& i) { Path::iterator n(i); return --n; } Path::const_iterator Path::up(const_iterator const& i) const { Path::const_iterator n(i); return --n; } Path::iterator Path::down(iterator const& i) { Path::iterator n(i); return ++n; } Path::const_iterator Path::down(const_iterator const& i) const { Path::const_iterator n(i); return ++n; } Path::reverse_iterator Path::up(reverse_iterator const& i) { Path::reverse_iterator n(i); return ++n; } Path::const_reverse_iterator Path::up(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return ++n; } Path::reverse_iterator Path::down(reverse_iterator const& i) { Path::reverse_iterator n(i); return --n; } Path::const_reverse_iterator Path::down(const_reverse_iterator const& i) const { Path::const_reverse_iterator n(i); return --n; } }}
19.571429
80
0.631387
xguerin
376a7ab1b23739b7e20d45adf6fb0641e9c95b0f
2,616
hpp
C++
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.CommonLibrary/domain/analyses/ReducedNumericalModel.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "foundation/axis.SystemBase.hpp" #include "domain/fwd/numerical_model.hpp" #include "foundation/memory/RelativePointer.hpp" #include "Foundation/Axis.CommonLibrary.hpp" namespace axis { namespace domain { namespace analyses { class ModelOperatorFacade; /** * Implements a version of the numerical model with reduced functionality, * so that it can be used with external processing devices. **/ class AXISCOMMONLIBRARY_API ReducedNumericalModel { public: ReducedNumericalModel(NumericalModel& sourceModel, ModelOperatorFacade& op); ~ReducedNumericalModel(void); const ModelDynamics& Dynamics(void) const; ModelDynamics& Dynamics(void); const ModelKinematics& Kinematics(void) const; ModelKinematics& Kinematics(void); size_type GetElementCount(void) const; size_type GetNodeCount(void) const; const axis::domain::elements::FiniteElement& GetElement(size_type index) const; axis::domain::elements::FiniteElement& GetElement(size_type index); const axis::foundation::memory::RelativePointer GetElementPointer(size_type index) const; axis::foundation::memory::RelativePointer GetElementPointer(size_type index); const axis::domain::elements::Node& GetNode(size_type index) const; axis::domain::elements::Node& GetNode(size_type index); const axis::foundation::memory::RelativePointer GetNodePointer(size_type index) const; axis::foundation::memory::RelativePointer GetNodePointer(size_type index); ModelOperatorFacade& GetOperator(void); /** * Creates a facade with reduced functionality that operates on components of an existing * numerical model. * * @param [in,out] sourceModel Source numerical model. * @param [in,out] op The object which provides an interface to external processing * using this model. * * @return A pointer to the reduced numerical model, located in model memory. **/ static axis::foundation::memory::RelativePointer Create(NumericalModel& sourceModel, ModelOperatorFacade& op); private: void *operator new (size_t, void *ptr); void operator delete(void *, void *); ModelOperatorFacade *operator_; axis::foundation::memory::RelativePointer nodeArrayPtr_; axis::foundation::memory::RelativePointer elementArrayPtr_; axis::foundation::memory::RelativePointer outputBucketArrayPtr_; size_type elementCount_; size_type nodeCount_; axis::foundation::memory::RelativePointer kinematics_; axis::foundation::memory::RelativePointer dynamics_; }; } } } // namespace axis::domain::analyses
40.875
96
0.748853
renato-yuzup
376d29ea569b01e2b5a72774aafbc174d75b438a
2,426
cpp
C++
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/css/cssom/CSSNumericValue.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/css/cssom/CSSNumericValue.h" #include "bindings/core/v8/ExceptionState.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/cssom/CSSUnitValue.h" namespace blink { bool CSSNumericValue::IsValidUnit(CSSPrimitiveValue::UnitType unit) { // UserUnits returns true for CSSPrimitiveValue::IsLength below. if (unit == CSSPrimitiveValue::UnitType::kUserUnits) return false; if (unit == CSSPrimitiveValue::UnitType::kNumber || unit == CSSPrimitiveValue::UnitType::kPercentage || CSSPrimitiveValue::IsLength(unit) || CSSPrimitiveValue::IsAngle(unit) || CSSPrimitiveValue::IsTime(unit) || CSSPrimitiveValue::IsFrequency(unit) || CSSPrimitiveValue::IsResolution(unit) || CSSPrimitiveValue::IsFlex(unit)) return true; return false; } CSSPrimitiveValue::UnitType CSSNumericValue::UnitFromName(const String& name) { if (EqualIgnoringASCIICase(name, "number")) return CSSPrimitiveValue::UnitType::kNumber; if (EqualIgnoringASCIICase(name, "percent") || name == "%") return CSSPrimitiveValue::UnitType::kPercentage; return CSSPrimitiveValue::StringToUnitType(name); } CSSNumericValue* CSSNumericValue::parse(const String& css_text, ExceptionState&) { // TODO(meade): Implement return nullptr; } CSSNumericValue* CSSNumericValue::FromCSSValue(const CSSPrimitiveValue& value) { if (value.IsCalculated()) { // TODO(meade): Implement this case. return nullptr; } return CSSUnitValue::FromCSSValue(value); } CSSNumericValue* CSSNumericValue::to(const String& unit_string, ExceptionState& exception_state) { CSSPrimitiveValue::UnitType unit = UnitFromName(unit_string); if (!IsValidUnit(unit)) { exception_state.ThrowDOMException(kSyntaxError, "Invalid unit for conversion"); return nullptr; } if (IsCalculated()) { exception_state.ThrowTypeError( "Conversion of CSSCalcValue is not supported yet"); return nullptr; } CSSUnitValue* result = ToCSSUnitValue(this)->to(unit); if (!result) { exception_state.ThrowTypeError("Incompatible units for conversion"); return nullptr; } return result; } } // namespace blink
34.657143
80
0.706925
metux
3770ca1dd46873dd38256f23ab25bafeb9f6febb
37,357
cpp
C++
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/FrameWork/fMain.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "..\SafeMacros.h" #include "..\Logging\MessageLogger.h" //--------------------------------------------------------------------------- #include <shfolder.h> //--------------------------------------------------------------------------- #include "FrameWorkInterface.h" #include "ZXLogFile.h" #include "ZXPluginManager.h" #include "ZXProjectManager.h" #include "ZXGuiManager.h" #include "fMain.h" #include "fAbout.h" #include "fRenameProject.h" #include "fCopyProject.h" //-- PRAGMA'S --------------------------------------------------------------- #pragma package(smart_init) #pragma link "KRegistry" #pragma link "pngimage" #pragma resource "*.dfm" //--------------------------------------------------------------------------- using namespace Scorpio; using namespace GUI; using namespace Logging; using namespace Interface; using namespace Plugin; using namespace Project; //--------------------------------------------------------------------------- TMRUProjectsVector g_mruList; const TColor g_Colors[] = { clRed, clYellow, clLime, clAqua }; //--------------------------------------------------------------------------- // Constructor /** * Initializes the main form * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::TfrmMain(TComponent* Owner) : TForm(Owner), m_bClosing(false), m_iTopOfButtons(8) { RL_METHOD } //--------------------------------------------------------------------------- // Denstructor /** * Checks all allocate memory is freed * @author Tony Thompson * @date Created 23 April 2005 */ //--------------------------------------------------------------------------- __fastcall TfrmMain::~TfrmMain() { if (NULL != frmAbout) { ZX_LOG_ERROR(lfGeneral, "frmAbout is not freed"); } if (0 != m_SwitcherButtons.size()) { ZX_LOG_ERROR(lfGeneral, "Not all the Switcher Buttons have been freed"); } } //--------------------------------------------------------------------------- // FormCreate /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCreate(TObject *Sender) { RL_METHOD PROTECT_BEGIN RestoreStates(); panTitle->DoubleBuffered = true; // panMRUList->DoubleBuffered = true; panPluginButtons->DoubleBuffered = true; GetLocation(); GetMachines(); UpdateGUI(); edtNewProjectLocation->Text = GetMyDocumentsFolder() + "\\TommyGun\\"; //pgcPlugins->DoubleBuffered = true; Registration(); PROTECT_END } //--------------------------------------------------------------------------- // FormActivate /** * Repositions the form when it is activate (only once though) * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormActivate(TObject *Sender) { RL_METHOD PROTECT_BEGIN static bool bRepositioned = false; if (false == bRepositioned) { bRepositioned = true; int iValue = 0; bool bState = false; if (regScorpio->Read("States", "Top" , iValue)) Top = iValue; if (regScorpio->Read("States", "Left" , iValue)) Left = iValue; if (regScorpio->Read("States", "Maximized" , bState) && bState) WindowState = wsMaximized; } FormResize(NULL); PROTECT_END } //--------------------------------------------------------------------------- // FormCloseQuery /** * Queries the form to see if its OK to close * @param Sender the VCL object that called the method * @param CanClose true if canclose, false if not * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormCloseQuery(TObject *Sender, bool &CanClose) { RL_METHOD PROTECT_BEGIN CanClose = false; if (S_OK == g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_NEW, NULL, 0, 0)) { // notify of closing g_PluginManager.Notify(g_PluginManager.Handle, TZX_VERB_EXIT, NULL, 0, 0); m_bClosing = true; // can close application CanClose = true; } PROTECT_END } //--------------------------------------------------------------------------- // FormClose /** * Event handler for the when the form is created * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormClose(TObject *Sender, TCloseAction &Action) { RL_METHOD PROTECT_BEGIN if (WindowState != wsMaximized) { regScorpio->Write("States", "Top" , Top ); regScorpio->Write("States", "Left" , Left ); regScorpio->Write("States", "Width" , Width ); regScorpio->Write("States", "Height" , Height ); } regScorpio->Write("States", "Maximized" , WindowState == wsMaximized); PROTECT_END } //--------------------------------------------------------------------------- // FormResize /** * Event handler for the when the form is resized * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::FormResize(TObject *Sender) { stsStatus->Panels->Items[0]->Width = stsStatus->ClientWidth - 260 - stsStatus->Panels->Items[1]->Width; stsStatus->Update(); if (pgcPlugins->Width != panPageContainer->Width + 8) { pgcPlugins->Width = panPageContainer->Width + 8; pgcPlugins->Left = -4; } if (pgcPlugins->Height!= panPageContainer->Height + 9) { pgcPlugins->Height = panPageContainer->Height + 9; pgcPlugins->Top = -8; } pgcPlugins->Update(); } //--------------------------------------------------------------------------- // appEventsException /** * Event handler for when an exception occurs * @param Sender the vcl object that caused the event * @param E the exception object * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsException(TObject *Sender, Exception *E) { RL_METHOD ZXPlugin* Plugin = g_PluginManager.CheckException(); if (true == SAFE_PTR(Plugin)) { m_MessageBox.ShowExceptionMessage(Plugin->Description, Plugin->Vendor, (DWORD)Plugin->ModuleAddress, (DWORD)ExceptAddr(), E->Message, true); Plugin->Unload(); } else { if (0 < g_Exceptions.size()) { for (unsigned int i = 0; i < g_Exceptions.size(); ++i) { m_MessageBox.ShowExceptionMessage(g_Exceptions[i].sMessage, g_Exceptions[i].sFile, g_Exceptions[i].sFunc, g_Exceptions[i].iLine); } g_Exceptions.clear(); } else { m_MessageBox.ShowExceptionMessage(E->Message, __FILE__, __FUNC__, __LINE__); } } } //--------------------------------------------------------------------------- // appEventsHint /** * Event handler for when a hint occurs * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::appEventsHint(TObject *Sender) { stsStatus->Panels->Items[0]->Text = Application->Hint; } //--------------------------------------------------------------------------- // mnuHelpAboutClick /** * Event handler for the about menu * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuHelpAboutClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN frmAbout = new TfrmAbout(Application); frmAbout->Execute(); SAFE_DELETE(frmAbout); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewPluginSwitcherClick /** * Toggles the visibility of the plugin switcher * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewPluginSwitcherClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewPluginSwitcher->Checked = !mnuViewPluginSwitcher->Checked; panPluginSwitcher->Visible = mnuViewPluginSwitcher->Checked; regScorpio->Write("States", "Switcher", mnuViewPluginSwitcher->Checked); PROTECT_END } //--------------------------------------------------------------------------- // mnuViewStandardClick /** * Toggles the visibility of the standard toolbar * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewStandardClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN mnuViewStandard->Checked = !mnuViewStandard->Checked; //tbrStandard->Visible = mnuViewStandard->Checked; panToolbars->Visible = mnuViewStandard->Checked; regScorpio->Write("States", "Standard", mnuViewStandard->Checked); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsUpClick /** * Scrolls the plugin buttons down into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsUpClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Top = std::min(0, panPluginButtons->Top + 76); PROTECT_END } //--------------------------------------------------------------------------- // spdPluginsDownClick /** * Scrolls the plugin buttons up into view within the browser * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::spdPluginsDownClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = std::min(0, std::max(panPluginButtonsContainer->Height - m_iTopOfButtons + 64, panPluginButtons->Top - 76)); PROTECT_END } //--------------------------------------------------------------------------- // panPluginButtonsContainerResize /** * Resizes the plugin browser panels * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::panPluginButtonsContainerResize(TObject *Sender) { RL_METHOD PROTECT_BEGIN panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); panPluginButtons->Top = 0; PROTECT_END } //--------------------------------------------------------------------------- // actSwitch01Execute /** * Switches to plugin using the Ctrl+Fn keys * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::actSwitch01Execute(TObject *Sender) { RL_METHOD PROTECT_BEGIN int iPluginIndex = ((TAction*)Sender)->Tag; if (0 <= iPluginIndex && iPluginIndex < (int)m_SwitcherButtons.size()) { PostNotifyEvent(m_SwitcherButtons[iPluginIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } PROTECT_END } //--------------------------------------------------------------------------- // OnPluginButtonClick /** * Event handler for when a plugin buttons is pressed * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::OnPluginButtonClick(TObject *Sender) { RL_METHOD PROTECT_BEGIN //ClearStatusSlots(); //pgcPlugins->ActivePageIndex = ((TComponent*)Sender)->Tag; PostNotifyEvent(m_SwitcherButtons[((TComponent*)Sender)->Tag].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); PROTECT_END } //--------------------------------------------------------------------------- // RestoreStates /** * Restores the states of some form objects * @param Sender the vcl object that caused the event * @author Tony Thompson * @date Created 9 April 2004 */ //--------------------------------------------------------------------------- void __fastcall TfrmMain::RestoreStates(void) { RL_METHOD PROTECT_BEGIN bool bState = true; int iValue = 0; regScorpio->Read("States", "Switcher" , bState); if (bState) mnuViewPluginSwitcherClick(NULL); if (regScorpio->Read("States", "Standard" , bState) && false == bState) mnuViewStandardClick(NULL); if (regScorpio->Read("States", "Width" , iValue) && false == bState) Width = iValue; if (regScorpio->Read("States", "Height" , iValue) && false == bState) Height = iValue; PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::mnuViewOptionsClick(TObject *Sender) { PROTECT_BEGIN g_GuiManager.OptionsShow(); tbrStandard->AutoSize = false; tbrStandard->AutoSize = true; String sFolder; if (regScorpio->Read("ProjectFolder", sFolder)) { edtNewProjectLocation->Text = sFolder; } PROTECT_END } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOptions(void) { bool bValue = true; regScorpio->Read("ShowPluginIcons", bValue); stsStatus->Panels->Items[1]->Width = bValue ? 200 : 0; FormResize(NULL); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::AddSwitcherButton(TZX_HPLUGIN PluginHandle, const String& sCaption) { TSwitcherButton Button; Button.PluginHandle = PluginHandle; Button.IconButton = new KIconButton(NULL); Button.IconButton->Name = "Button" + IntToStr(PluginHandle); Button.IconButton->Caption = sCaption; Button.IconButton->Parent = panPluginButtons; Button.IconButton->Left = 4; Button.IconButton->Top = 8 + (m_SwitcherButtons.size() * 76); Button.IconButton->Height = 68; Button.IconButton->Width = 68; Button.IconButton->Tag = m_SwitcherButtons.size(); Button.IconButton->IconsCold = imgLarge; Button.IconButton->IconsHot = imgLarge; Button.IconButton->IconIndex = -1; Button.IconButton->Grouped = true; Button.IconButton->ColorHighlight = (TColor)0x00F6E8E0;//clInfoBk; Button.IconButton->ColorSelected = (TColor)0x00EED2C1;//clWhite; Button.IconButton->Color = (TColor)0x00846142;//panPluginButtons->Color; //clBtnFace; Button.IconButton->ColorBorder = (TColor)0x00846142; Button.IconButton->ColorBackground = panPluginButtons->Color; //Button.IconButton->Color = clBtnShadow; //Button.IconButton->ColorBorderSelected = clWhite; //Button.IconButton->ColorHighlight = 0x00F6E8E0; //Button.IconButton->ColorSelected = 0x00EED2C1; Button.IconButton->Font->Name = "Octin Stencil Rg"; Button.IconButton->Font->Size = 8; Button.IconButton->CornerWidth = 10; Button.IconButton->CornerHeight = 10; Button.IconButton->OnClick = OnPluginButtonClick; m_SwitcherButtons.push_back(Button); m_SwitcherButtons[0].IconButton->Selected = true; m_iTopOfButtons = 4 + ((m_SwitcherButtons.size()) * 84); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::RemoveSwitcherButton(TZX_HPLUGIN PluginHandle) { // remove the button TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { SAFE_DELETE((*it).IconButton); //SAFE_DELETE((*it).Panel); m_SwitcherButtons.erase(it); break; } } // reposition the remaining buttons for (unsigned int i = 0; i < m_SwitcherButtons.size(); ++i) { m_SwitcherButtons[i].IconButton->Top = 4 + (i * 84); m_SwitcherButtons[i].IconButton->Tag = i; } // resize the panel m_iTopOfButtons = 4 + (m_SwitcherButtons.size() * 84); panPluginButtons->Height = std::max(m_iTopOfButtons, panPluginButtonsContainer->Height); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SetSwitcherBitmap(TZX_HPLUGIN PluginHandle, TImage* Image) { TSwitcherButtonIterator it = m_SwitcherButtons.begin(); for (it = m_SwitcherButtons.begin(); it != m_SwitcherButtons.end(); it++) { if ((*it).PluginHandle == PluginHandle) { int iIndex = imgLarge->AddMasked(Image->Picture->Bitmap, Image->Picture->Bitmap->Canvas->Pixels[0][0]); (*it).IconButton->IconIndex = iIndex; } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::ClearStatusSlots(void) { // clear the status bar slots for the next plugin stsStatus->Panels->Items[2]->Text = ""; stsStatus->Panels->Items[3]->Text = ""; stsStatus->Panels->Items[4]->Text = ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileNewProjectExecute(TObject *Sender) { if (g_ProjectManager.Close()) { ActiveControl = edtNewProjectName; } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileOpenProjectAccept(TObject *Sender) { g_ProjectManager.Load(actFileOpenProject->Dialog->FileName); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileSaveProjectExecute(TObject *Sender) { g_ProjectManager.Save(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFileCloseProjectExecute(TObject *Sender) { g_ProjectManager.Close(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::SwitchToPlugin(TZX_HPLUGIN PluginHandle) { int iPluginIndex = -1; for (int i = 0; i < (int)m_SwitcherButtons.size(); i++) { if (m_SwitcherButtons[i].PluginHandle == PluginHandle) { iPluginIndex = i; break; } } if (0 <= iPluginIndex && iPluginIndex < pgcPlugins->PageCount) { ClearStatusSlots(); m_SwitcherButtons[iPluginIndex].IconButton->Selected = true; pgcPlugins->ActivePageIndex = iPluginIndex; UpdateGUI(); } } //--------------------------------------------------------------------------- AnsiString __fastcall TfrmMain::GetMyDocumentsFolder() { CHAR my_documents[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, my_documents); if (SUCCEEDED(result)) { AnsiString folder = AnsiString(my_documents); AnsiString myDocFolder = StringReplace(folder, "Documents", "My Documents", TReplaceFlags() << rfReplaceAll); if (DirectoryExists(folder)) { return folder; } if (DirectoryExists(myDocFolder)) { return myDocFolder; } } return ""; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdOpenProjectClick(TObject *Sender) { if (DirectoryExists(edtNewProjectLocation->Text)) { actFileOpenProject->Dialog->InitialDir = edtNewProjectLocation->Text; } else { actFileOpenProject->Dialog->InitialDir = GetMyDocumentsFolder() + "\\TommyGun\\"; } actFileOpenProject->Execute(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::edtNewProjectNameChange(TObject *Sender) { lblMessage->Visible = false; UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCreateProjectClick(TObject *Sender) { String sBaseFolder = edtNewProjectLocation->Text; if (sBaseFolder[sBaseFolder.Length()] != '\\') { sBaseFolder += "\\"; } String sProjectFolder = sBaseFolder + edtNewProjectName->Text + "\\"; if (ForceDirectories(sBaseFolder)) { regScorpio->Write("Plugins", "MachineFolder", cmbNewProjectMachine->Text); regScorpio->Write("ProjectFolder", sBaseFolder); String sProjectFile = sProjectFolder + "project.xml" ; //sProjectFile = ChangeFileExt(sProjectFile, ".xml"); if (false == DirectoryExists(sProjectFolder)) { if (ForceDirectories(sProjectFolder)) { // add the file name to the projects list g_ProjectManager.New(sProjectFile, cmbNewProjectMachine->Text); } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "A Project file with that Name already exists at the Location"; lblMessage->Visible = true; } } else { lblMessage->Caption = "Location is not valid please select a new Location"; lblMessage->Visible = true; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateOk(void) { cmdCreateProject->Enabled = !edtNewProjectName->Text.Trim().IsEmpty() && !edtNewProjectLocation->Text.Trim().IsEmpty() && -1 != cmbNewProjectMachine->ItemIndex; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetMachines(void) { cmbNewProjectMachine->Items->Clear(); // read the registry setting and set it to the appropreiate folder String sRegFolder; regScorpio->Read("Plugins", "MachineFolder", sRegFolder); cmbNewProjectMachine->Clear(); cmbNewProjectMachine->ItemIndex = -1; String sPluginsFolder = ExtractFilePath(Application->ExeName) + "Plugins\\_*"; // find the machine specific plugin folders TSearchRec sr; if (0 == FindFirst(sPluginsFolder, faAnyFile, sr)) { do { if ((sr.Attr & faDirectory) == faDirectory) { String sFolder = sr.Name.SubString(2, sr.Name.Length()); cmbNewProjectMachine->Items->Add(sFolder); if (sFolder.LowerCase() == sRegFolder.LowerCase()) { cmbNewProjectMachine->ItemIndex = cmbNewProjectMachine->Items->Count - 1; } } } while(0 == FindNext(sr)); FindClose(sr); } if (cmbNewProjectMachine->ItemIndex == -1 && cmbNewProjectMachine->Items->Count > 0) { cmbNewProjectMachine->ItemIndex = 0; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::GetLocation(void) { String sProjectFolder; if (regScorpio->Read("ProjectFolder", sProjectFolder)) { edtNewProjectLocation->Text = sProjectFolder; } else { edtNewProjectLocation->Text = ExtractFilePath(Application->ExeName) + "Projects\\"; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::FillProjectList(void) { lstProjects->Items->Clear(); g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { TListItem *item = lstProjects->Items->Add(); String sProjectFolder = ExtractFilePath(g_mruList[i].File); sProjectFolder.SetLength(sProjectFolder.Length() - 1); String sFolder = ExtractFileName(sProjectFolder); if (g_mruList[i].Exists) { item->Caption = sFolder; // set the machine name //item->SubItems->Add(g_mruList[i].Machine); item->SubItems->Add(sProjectFolder); item->ImageIndex = -1; int iDate = Now(); if ((int)g_mruList[i].TimeStamp == iDate) { item->SubItems->Add("Today"); } else if ((int)g_mruList[i].TimeStamp == iDate - 1) { item->SubItems->Add("Yesterday"); } else { item->SubItems->Add(g_mruList[i].TimeStamp.FormatString("dddddd")); } } else { item->Caption = sFolder + " (missing)"; // set the machine name item->SubItems->Add("Unknown"); item->SubItems->Add("Unknown"); } } } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsChange(TObject *Sender, TListItem *Item, TItemChange Change) { cmdProjectRemove->Visible = lstProjects->ItemIndex != -1; cmdProjectRestore->Visible = lstProjects->ItemIndex != -1; cmdProjectCopy->Visible = lstProjects->ItemIndex != -1; // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { cmdProjectRemove->Top = 47 + ((lstProjects->Selected->Index - lstProjects->TopItem->Index) * 17/*cmdProjectRemove->Height*/); cmdProjectRestore->Top = cmdProjectRemove->Top; cmdProjectCopy->Top = cmdProjectRemove->Top; } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsClick(TObject *Sender) { lstProjectsChange(NULL, NULL, TItemChange()); // load the selected file if (lstProjects->ItemIndex != -1 && lstProjects->ItemIndex < (int)g_mruList.size()) { g_ProjectManager.Load(g_mruList[lstProjects->ItemIndex].File); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdBrowseClick(TObject *Sender) { dlgBrowse->DefaultFolder = edtNewProjectLocation->Text; dlgBrowse->Title = "Select Project Folder"; if (dlgBrowse->Execute()) { edtNewProjectLocation->Text = dlgBrowse->FileName; } UpdateOk(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::cmdCleanMissingProjectsClick(TObject *Sender) { g_ProjectManager.GetMRUList(g_mruList, true); if (g_mruList.size()) { // fill the projects list view with the time stamp sorted items for (int i = 0; i < (int)g_mruList.size(); ++i) { String sFile = ExtractFileName(g_mruList[i].File); sFile = ChangeFileExt(sFile, ""); if (false == g_mruList[i].Exists || g_mruList[i].Machine.LowerCase() == "unknown") { regScorpio->ClearValue("MRU", IntToStr(i)); } } } FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actFindExecute(TObject *Sender) { TAction* action = dynamic_cast<TAction*>(Sender); if (true == SAFE_PTR(action)) { // send the find message to the active plugin g_PluginManager.NotifyPlugin(TZXN_EDIT_FIND + action->Tag, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::UpdateGUI(void) { // query the active plugin to see what it supports and update the gui bool bEnableFind = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_FIND, NULL, 0, 0); actFind->Enabled = bEnableFind; actFindReplace->Enabled = bEnableFind; actFindNext->Enabled = bEnableFind; actFindPrev->Enabled = bEnableFind; mnuEditFindReplace->Enabled = bEnableFind; bool bEnableCopyCutPaste = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_COPYPASTE, NULL, 0, 0); actEditCopy2->Enabled = bEnableCopyCutPaste; actEditCut2->Enabled = bEnableCopyCutPaste; actEditPaste2->Enabled = bEnableCopyCutPaste; //actEditUndo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_UNDO, NULL, 0, 0); //actEditRedo->Enabled = S_QUERY_YES == g_PluginManager.NotifyPlugin(TZX_QUERY_REDO, NULL, 0, 0); //actEditUndoList->Enabled = actEditUndo->Enabled && actEditRedo->Enabled; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::pgcPluginsChange(TObject *Sender) { PostNotifyEvent(m_SwitcherButtons[pgcPlugins->ActivePageIndex].PluginHandle, TZX_VERB_SWITCH_PLUGIN, NULL, 0, 0); UpdateGUI(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditDeleteExecute(TObject *Sender) { bool bSendDelToControl = false; String sClass = ActiveControl->ClassName(); TCustomEdit* pEdit = dynamic_cast<TCustomEdit*>(ActiveControl); bSendDelToControl = (true == SAFE_PTR(pEdit) && true == pEdit->Enabled); if (bSendDelToControl) { SendMessage(ActiveControl->Handle, WM_KEYDOWN, VK_DELETE, 0); } else { g_PluginManager.NotifyPlugin(TZX_VERB_DELETE, NULL, 0, 0); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRemoveProjectClick(TObject *Sender) { int iAnswer = 0; Message ( mbtError, "Remove or Delete the project?", "You can choose to Remove or Delete the project from the list", "You can choose to either just Remove the project from the list, " "Delete the project folder entirely or " "Cancel this operation and leave the list unchanged.\n\n" "Click,\n\tDelete\tto Delete the project permanently.\n" "\tRemove\tto just Remove the entry from the list.\n" "\tCancel\tto Cancel this operation and leave the entry in the list.", "Cancel", "Remove", "Delete", iAnswer ); if (iAnswer != 0) { g_ProjectManager.Remove(lstProjects->Items->Item[lstProjects->ItemIndex]->Caption, iAnswer == 2); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRenameProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmRenameProject)) { frmRenameProject = new TfrmRenameProject(NULL); } if (true == SAFE_PTR(frmRenameProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmRenameProject->Execute(sOldName)) { // rename the project g_ProjectManager.Rename(sOldName, frmRenameProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmRenameProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popMRUListPopup(TObject *Sender) { popRemoveProject->Enabled = lstProjects->ItemIndex != -1; popRenameProject->Enabled = lstProjects->ItemIndex != -1; } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsColumnClick(TObject *Sender, TListColumn *Column) { static TListColumn *LastColumn = NULL; if (lstProjects->Items->Count) { if (LastColumn) { //LastColumn->ImageIndex = 0; } bool bAscending = g_ProjectManager.SortProjects(Column->Index); //Column->ImageIndex = bAscending ? 2 : 1; LastColumn = Column; FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (ActiveControl != Sender) { ActiveControl = dynamic_cast<TWinControl*>(Sender); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCopyExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_COPY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditCutExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_CUT, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actEditPasteExecute(TObject *Sender) { g_PluginManager.NotifyPlugin(TZX_VERB_PASTE, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popRestoreProjectClick(TObject *Sender) { String sProject = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (sProject.SubString(sProject.Length() - 9, 10) == " (missing)") { sProject = sProject.SubString(1, sProject.Length() - 10); } g_ProjectManager.Restore(sProject); FillProjectList(); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::popCopyProjectClick(TObject *Sender) { if (false == SAFE_PTR(frmCopyProject)) { frmCopyProject = new TfrmCopyProject(NULL); } if (true == SAFE_PTR(frmCopyProject) && lstProjects->ItemIndex != -1) { String sOldName = lstProjects->Items->Item[lstProjects->ItemIndex]->Caption; if (frmCopyProject->Execute(sOldName)) { // rename the project g_ProjectManager.Copy(sOldName, frmCopyProject->edtNewName->Text.Trim()); } SAFE_DELETE(frmCopyProject); FillProjectList(); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::lstProjectsKeyPress(TObject *Sender, char &Key) { if (Key == VK_RETURN && lstProjects->ItemIndex != -1) { lstProjectsClick(NULL); } } //--------------------------------------------------------------------------- void __fastcall TfrmMain::actRunExecute(TObject *Sender) { // send play message g_PluginManager.Notify(NULL, TZXN_GAME_PLAY, NULL, 0, 0); } //--------------------------------------------------------------------------- void __fastcall TfrmMain::Registration(void) { /*const int cVersion = 0x1350; int iVersion = cVersion; bool bState = false; regScorpio->Read("States", "Registered" , bState); regScorpio->Read("States", "RegisteredVersion" , iVersion); if (!bState || iVersion != cVersion) { regScorpio->Write("States", "Registered", true); regScorpio->Write("States", "RegisteredVersion", cVersion); new TRegistrationThread(IdSMTP1, IdMessage1); }*/ } //---------------------------------------------------------------------------
37.171144
164
0.530048
tonyt73
3774044e50975e12b15187b791397878d3fa4378
1,654
cpp
C++
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
3
2018-03-05T13:57:56.000Z
2018-05-03T19:25:05.000Z
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
CodeFromLectures/Structures (2)/Structures/main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; #include "address.h" #include "student.h" void generateStudentFile() { Student students[5]; for (int i = 0; i < 5; ++i) { students[i].name = NULL; readStudent(students[i]); } fstream file("students.dat", ios::out | ios::binary | ios::trunc); if (!file) { cerr << "Problem with the file..."; return; } for (int i = 0; i < 5; ++i) { if (!store(students[i], file)) break; } file.close(); } void printStudentsFromFile() { Student s; s.name = NULL; fstream file("students.dat", ios::in | ios::binary); while (load(s, file)) printStudent(s); file.close(); } void toUpper(char* text) { while (*text) { if (*text >= 'a' && *text <= 'z') { *text = *text - 'a' + 'A'; } ++text; } } void changeNameOfAllInf() { Student s; s.name = NULL; fstream file("students.dat", ios::in | ios::out | ios::binary); if (!file) return; streampos begin = 0; while (load(s, file)) { if (s.program == INFORMATICS) { toUpper(s.name); streampos end = file.tellg(); file.seekp(begin, ios::beg); store(s, file); file.seekg(end, ios::beg); } begin = file.tellg(); } file.close(); } int main() { // generateStudentFile(); printStudentsFromFile(); // changeNameOfAllInf(); // printStudentsFromFile(); }
19.011494
71
0.476421
Stoefff
3779477a90842c9ea994f741358951e2e030df74
105
hpp
C++
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
935
2018-05-23T14:56:18.000Z
2022-03-29T07:27:20.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
314
2018-05-04T15:58:06.000Z
2022-03-30T16:24:17.000Z
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
65
2019-04-21T14:26:51.000Z
2022-03-12T03:16:41.000Z
#pragma once namespace thor { void initializeTimers(); void initTimerOnThisCpu(); } // namespace thor
11.666667
26
0.742857
kITerE
377c25f611fb8ce80317421179313c9ea52cc430
1,956
cpp
C++
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
userland/src/uname.cpp
Marc-JB/PeregrineOS
2f4069211bca2341f0bab050bfb9cc803a59f510
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <sys/utsname.h> #include <string> #include <vector> #include <any> using namespace std; typedef unsigned short int ushort; void run(vector<string>); utsname getUname() { utsname uts; if (uname(&uts) < 0) throw "uname() failed"; return uts; } int main(int argc, char** argv){ vector<string> args; for(int i = 0; i < argc; ++i) args.push_back(string(argv[i])); try { run(args); } catch (string errorMessage){ perror(errorMessage.c_str()); return 1; } catch (any error) { return 1; } return 0; } void run(vector<string> args) { utsname uts = getUname(); bool flag_s = args.size() == 1; bool flag_n = false; bool flag_r = false; bool flag_m = false; if (args.size() > 1) { for (ushort i = 1u; i < args.size(); ++i) { if (args[i][0] == '-') { for (ushort j = 1u; j < args[i].length(); ++j) { switch (args[i][j]) { case 's': flag_s = true; break; case 'n': flag_n = true; break; case 'r': flag_r = true; break; case 'm': flag_m = true; break; case 'a': flag_s = flag_n = flag_r = flag_m = true; break; } } } } } if (!flag_s && !flag_n && !flag_r && !flag_m) flag_s = true; if (flag_s) printf("%s ", uts.sysname); if (flag_n) printf("%s ", uts.nodename); if (flag_r) printf("%s ", uts.release); if (flag_m) printf("%s ", uts.machine); printf("\n"); return void(); }
26.794521
69
0.416155
Marc-JB
3780ccd6e1370bf0a3ac7d3677c50f0c0d0e0db2
2,000
cpp
C++
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
Gecko/src/Gecko/Core/Window.cpp
Liamcreed/Gecko
d3f468f7e809148ad962f0fe969c28aac21236c7
[ "MIT" ]
null
null
null
#include "gkpch.h" #include "Input.h" #include "Window.h" namespace Gecko { void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods); void cursor_position_callback(GLFWwindow *window, double xpos, double ypos); void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); Window::Window(const std::string t, int w, int h) : m_Title(t), m_Width(w), m_Height(h) { if (!glfwInit()) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to initialize GLFW!\n"; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif m_GLFWWindow = glfwCreateWindow(m_Width, m_Height, m_Title.c_str(), NULL, NULL); if (m_GLFWWindow == nullptr) { glfwTerminate(); GK_LOG(GK_ERROR) << "Failed to create GLFWWindow!\n"; } glfwMakeContextCurrent(m_GLFWWindow); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { GK_LOG(GK_ERROR) << "Failed to initialize GLAD!\n"; } glfwSwapInterval(1); glfwSetKeyCallback(m_GLFWWindow, key_callback); glfwSetCursorPosCallback(m_GLFWWindow, cursor_position_callback); glfwSetMouseButtonCallback(m_GLFWWindow, mouse_button_callback); glfwSetScrollCallback(m_GLFWWindow, scroll_callback); } void Window::Update() { glfwPollEvents(); glfwGetWindowSize(m_GLFWWindow, &m_Width, &m_Height); glfwSwapBuffers(m_GLFWWindow); } void Window::Clean() { glfwDestroyWindow(m_GLFWWindow); glfwTerminate(); } Window::~Window() { Clean(); } } // namespace Gecko
32.258065
88
0.6525
Liamcreed
3786ccf7530bb04fb445a71d1f144c15e5628757
11,406
cpp
C++
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
integrations/Raknet/NetworkSystem.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "stdafx.h" #include "NetworkSystem.h" #include "Peer.h" #include "Stream.h" #include "Memory/Allocators.h" #include "Util/Environment.h" #include "Util/Logger.h" #include "Util/_String.h" #include "Network/Messages/ConnectionRequestAccepted.h" #include "Network/Messages/PingResponse.h" #include "Network/Messages/ConnectionLost.h" using namespace Teardrop; using namespace Integration; Raknet::System::System(int maxIncomingConnections, short listenPort) : mMe(0) , mGuid(0) { mMaxIncomingConnections = maxIncomingConnections; mListenPort = listenPort; } Raknet::System::~System() { } Allocator* Raknet::System::s_pAllocator = TD_GET_ALLOCATOR(DEFAULT); void* Raknet::System::malloc(size_t sz) { return s_pAllocator->Allocate(sz TD_ALLOC_SITE); } void* Raknet::System::realloc(void* pMem, size_t sz) { return s_pAllocator->Reallocate(pMem, sz TD_ALLOC_SITE); } void Raknet::System::free(void* pMem) { return s_pAllocator->Deallocate(pMem); } void Raknet::System::setAllocator(Allocator* pAlloc) { assert(pAlloc); s_pAllocator = pAlloc; } Allocator* Raknet::System::getAllocator() { return s_pAllocator; } void Raknet::System::getTypes(Type* typeArray, int& typeCount) { if (typeCount < 1) { typeCount = 0; return; // TODO: throw? } typeArray[0] = System::SYSTEM_NETWORK; typeCount = 1; } Net::Message* Raknet::System::createMessage(unsigned char msgId) { // for now, the TD msg ID is still an unsigned char (tho this // is likely to change once we get lots of messages) if (s_factory[msgId]) return s_factory[msgId](); return 0; } unsigned long long Raknet::System::getTime() { return RakNet::GetTime(); } bool Raknet::System::connect(const String& address, unsigned short port) { return mMe->Connect(address, port, 0, 0); } Teardrop::Net::Peer* Raknet::System::createPeer(Net::Message& msg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(msg.m_pPeer); return new Raknet::Peer(pPeer->mGuid); } void Raknet::System::destroyPeer(Teardrop::Net::Peer* pPeer) { delete pPeer; } Net::MessagePtr Raknet::System::getNextMessage() { Net::MessagePtr pMsg; Packet* pPacket = mMe->Receive(); // we only want to deal with TD messages here -- system/API messages // should be dealt with in a different path if (pPacket) { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Incoming packet: id=%d, len=%d", pPacket->data[0], pPacket->length); Environment::get().pLogger->logMessage(buf); #endif Raknet::Stream bs(pPacket->data, pPacket->length, false); // connected messages need to have their remote endpoint information set up bool bIsConnected = false; switch (pPacket->data[0]) { // disconnected connection request, no guid or systemaddr available case ID_NEW_INCOMING_CONNECTION: Environment::get().pLogger->logMessage("\nNEW INCOMING CONNECTION\n"); break; // Non-system/control messages have their message ID in the second byte case ID_USER_PACKET_ENUM+1: pMsg = createMessage(pPacket->data[1]); if (pMsg) { pMsg->deserialize(bs); bIsConnected = true; } break; // disconnected ping response, no guid or systemaddr available case ID_PONG: pMsg = TD_NEW Net::PingResponse; pMsg->deserialize(bs); break; // we sent out a connect request, and the other end replied in the affirmative; // this is where we set up the ID info for "the other guy", which should be extracted // by whoever processes this message and stored for later use in sending messages // to this remote endpoint case ID_CONNECTION_REQUEST_ACCEPTED: pMsg = TD_NEW Net::ConnectionRequestAccepted; pMsg->deserialize(bs); bIsConnected = true; break; // connected disconnect notice, we need to case ID_CONNECTION_LOST: case ID_DISCONNECTION_NOTIFICATION: pMsg = TD_NEW Net::ConnectionLost; pMsg->deserialize(bs); bIsConnected = true; break; } if (bIsConnected) { pMsg->m_pPeer = TD_NEW Raknet::Peer(pPacket->guid, pPacket->systemAddress); } } return pMsg; } // broadcast to all peers void Raknet::System::send(Net::Message& msg) { SystemAddress dest; Raknet::Stream bs; msg.serialize(bs); #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet (broadcast): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, true); } // send to single peer void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer* pRecipient) { Raknet::Stream bs; msg.serialize(bs); Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipient); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } // send to multiple peers void Raknet::System::send(Net::Message& msg, Teardrop::Net::Peer** pRecipients, int nRecipients) { Raknet::Stream bs; msg.serialize(bs); for (int i=0; i<nRecipients; ++i) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pRecipients[i]); SystemAddress dest; if (pPeer) dest = mMe->GetSystemAddressFromGuid(pPeer->mGuid); else { #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Failed to send outgoing packet (null recipient): id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif return; } #if defined(_DEBUG) char buf[64]; sprintf_s(buf, 64, "[TD] Outgoing packet: id=%s", NetworkSystem::getMessageString(msg.getId())); Environment::get().pLogger->logMessage(buf); #endif mMe->Send( &bs.mBS, (PacketPriority)msg.m_priority, (PacketReliability)msg.m_reliability, char(msg.m_channel), dest, false); } } void Raknet::System::disconnect(Net::Peer* pPeer) { // sending a zero to this method means disconnect ourselves if (pPeer) { Raknet::Peer* pP = static_cast<Raknet::Peer*>(pPeer); mMe->CloseConnection(pP->mAddr, true, 0, HIGH_PRIORITY); } //else // m_pPeer->CloseConnection(UNASSIGNED_SYSTEM_ADDRESS, true, 0, HIGH_PRIORITY); Sleep(500); } void Raknet::System::disconnect(unsigned int addr, unsigned short port) { mMe->CloseConnection( SystemAddress(addr, port), true, 0, HIGH_PRIORITY); Sleep(500); } // for unconnected systems (i.e servers in a server list) void Raknet::System::ping(const char* addr, unsigned short port) { mMe->Ping(addr, port, false); } void Raknet::System::setDisconnectedPingResponse(const char *data, unsigned int dataSize) { mMe->SetOfflinePingResponse(data, dataSize); } // for unconnected systems (i.e available servers on the LAN) void Raknet::System::requestServerInfo(const char* addr) { //InterrogateServer msg; //send(&msg, addr, PORT_GAME_SERVER_CLIENT_LISTENER); } bool Raknet::System::isLocalOrigination(Net::Message* pMsg) { Raknet::Peer* pPeer = static_cast<Raknet::Peer*>(pMsg->m_pPeer); return (mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) == pPeer->mGuid); } unsigned int Raknet::System::getLocalIpV4() { const char * localIp = mMe->GetLocalIP(0); unsigned char ip[4]; unsigned int a, b, c, d; sscanf_s(localIp, "%d.%d.%d.%d", &a, &b, &c, &d); ip[0] = d; ip[1] = c; ip[2] = b; ip[3] = a; return *((unsigned int*)ip); } #include "Network/Messages/Advertise.h" #include "Network/Messages/Unadvertise.h" #include "Network/Messages/PlayerJoinServer.h" #include "Network/Messages/PlayerLeaveServer.h" #include "Network/Messages/PlayerJoinGame.h" #include "Network/Messages/PlayerLeaveGame.h" #include "Network/Messages/UpdateServerState.h" #include "Network/Messages/UpdatePlayerState.h" #include "Network/Messages/GameStarted.h" #include "Network/Messages/GameEnded.h" #include "Network/Messages/PlayerPositionSync.h" #include "Network/Messages/PlayerCommand.h" #include "Network/Messages/InterrogateServer.h" #include "Network/Messages/QueryIFF.h" #include "Network/Messages/ResponseIFF.h" #include "Network/Messages/PlayerEntityVariantChanged.h" #include "RakMemoryOverride.h" #include "PacketLogger.h" class MyLogger : public PacketLogger { public: void WriteLog(const char* msg) { #if defined(_DEBUG) Teardrop::Environment::get().pLogger->logMessage(msg); #endif } }; MyLogger s_logger; using namespace Teardrop::Net; using namespace Raknet; void Raknet::System::initialize() { rakMalloc = Raknet::System::malloc; rakRealloc = Raknet::System::realloc; rakFree = Raknet::System::free; Advertise _a; Unadvertise _u; PlayerJoinServer _pjs; PlayerLeaveServer _pls; PlayerJoinGame _pjg; PlayerLeaveGame _plg; UpdatePlayerState _ups; UpdateServerState _uss; GameStarted _gs; GameEnded _ge; PlayerPositionSync _pps; PlayerCommand _pc; InterrogateServer _ic; QueryIFF _qi; ResponseIFF _ri; PlayerVariantChanged _pvc; // initialize Raknet mMe = RakNetworkFactory::GetRakPeerInterface(); mMe->AttachPlugin(&s_logger); // for now, prevent ping responses entirely (server can reset this later) mMe->SetOfflinePingResponse(0, 0); // startup our peer -- we talk to the master server as well as // game clients through this peer, so make enough to go around SocketDescriptor desc(mListenPort, 0); bool rtn = mMe->Startup(mMaxIncomingConnections, 30, &desc, 1); if (rtn && mMaxIncomingConnections > 2) { mMe->SetMaximumIncomingConnections(mMaxIncomingConnections); } // set our guid and address members mGuid = new RakNetGUID; *mGuid = mMe->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); } void Raknet::System::shutdown() { delete mGuid; mGuid = 0; mMe->Shutdown(300); RakNetworkFactory::DestroyRakPeerInterface(mMe); mMe = 0; }
26.711944
131
0.722865
nbtdev
3787b2e14e8aec29261c5661003b1b503ecae611
5,587
cpp
C++
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
basic_calculator_2.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/basic-calculator-ii/ #include <string> #include <vector> #include <limits> #include "utils.h" namespace basic_calculator_2 { class Solution { public: // Note: The expression must be valid and contain only the following // characters: '0'-'9', '+', '-', '*', '/', ' '. For an empty expression, // returns 0. // // Time: O(n), Space: O(n), n - number of characters // int run(const std::string& s) { if (!s.size()) return 0; struct Operation { int left_operand; char type; }; std::vector<Operation> operations; auto i = s.cbegin(); const auto end = s.cend(); while (i != end) { Operation op; op.left_operand = readOperand(i, end); op.type = readOperator(i, end); while (operations.size()) { const Operation& op_last = operations.back(); if (getOperationPriority(op_last.type) >= getOperationPriority(op.type)) { op.left_operand = doOperation(op_last.type, op_last.left_operand, op.left_operand); operations.pop_back(); } else { break; } } operations.push_back(op); } assert(operations.size() == 1); const Operation& result = operations.front(); return result.left_operand; } private: int readOperand(std::string::const_iterator& begin, const std::string::const_iterator& end) const { std::string s; for (; begin != end; begin++) { const char c = *begin; if (std::isspace(c)) { if (!s.size()) continue; break; } if (!std::isdigit(c)) break; s += c; } return std::atoi(s.c_str()); } char readOperator(std::string::const_iterator& begin, const std::string::const_iterator& end) const { while (begin != end) { const char c = *(begin++); if (std::isspace(c)) continue; return c; } return 0; } int doOperation(char operation, int operand1, int operand2) const { switch (operation) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; } return operand1; } int getOperationPriority(char operation) const { switch (operation) { case '+': case '-': return 1; case '*': case '/': return 2; } return 0; } }; int main() { ASSERT( Solution().run("") == 0 ); ASSERT( Solution().run("0") == 0 ); ASSERT( Solution().run("1") == 1 ); ASSERT( Solution().run("123") == 123 ); ASSERT( Solution().run("0+1") == 1 ); ASSERT( Solution().run("1+0") == 1 ); ASSERT( Solution().run("1+1") == 2 ); ASSERT( Solution().run("1+2") == 3 ); ASSERT( Solution().run("1+10") == 11 ); ASSERT( Solution().run("10+1") == 11 ); ASSERT( Solution().run("0-1") == -1 ); ASSERT( Solution().run("1-0") == 1 ); ASSERT( Solution().run("1-1") == 0 ); ASSERT( Solution().run("1-2") == -1 ); ASSERT( Solution().run("10-1") == 9 ); ASSERT( Solution().run("1-10") == -9 ); ASSERT( Solution().run("0*1") == 0 ); ASSERT( Solution().run("1*0") == 0 ); ASSERT( Solution().run("1*1") == 1 ); ASSERT( Solution().run("1*2") == 2 ); ASSERT( Solution().run("2*1") == 2 ); ASSERT( Solution().run("10*1") == 10 ); ASSERT( Solution().run("0/1") == 0 ); ASSERT( Solution().run("1/1") == 1 ); ASSERT( Solution().run("1/2") == 0 ); ASSERT( Solution().run("2/1") == 2 ); ASSERT( Solution().run("10/1") == 10 ); ASSERT( Solution().run("1+2-3") == 0 ); ASSERT( Solution().run("2-3+1") == 0 ); ASSERT( Solution().run("1+2*3") == 7 ); ASSERT( Solution().run("2*3+1") == 7 ); ASSERT( Solution().run("4+4/2") == 6 ); ASSERT( Solution().run("4/2+4") == 6 ); ASSERT( Solution().run("1-2*3") == -5 ); ASSERT( Solution().run("2*3-1") == 5 ); ASSERT( Solution().run("4-4/2") == 2 ); ASSERT( Solution().run("4/2-4") == -2 ); ASSERT( Solution().run("2*8/4") == 4 ); ASSERT( Solution().run("8/4*2") == 4 ); ASSERT( Solution().run("1+2*8/4-2") == 3 ); ASSERT( Solution().run(" ") == 0 ); ASSERT( Solution().run(" ") == 0 ); ASSERT( Solution().run("1 ") == 1 ); ASSERT( Solution().run(" 1") == 1 ); ASSERT( Solution().run(" 1 ") == 1 ); ASSERT( Solution().run(" 1 + 2 ") == 3 ); ASSERT( Solution().run(" 1 + 2 ") == 3 ); const int MAX = std::numeric_limits<int>::max(); const std::string MAX_STR = std::to_string(MAX); ASSERT( Solution().run(MAX_STR) == MAX ); ASSERT( Solution().run(MAX_STR + "+0") == MAX ); ASSERT( Solution().run(MAX_STR + "-0") == MAX ); ASSERT( Solution().run(MAX_STR + "*0") == 0 ); ASSERT( Solution().run(MAX_STR + "*1") == MAX ); ASSERT( Solution().run(MAX_STR + "/1") == MAX ); ASSERT( Solution().run(MAX_STR + "-1") == MAX-1 ); ASSERT( Solution().run(MAX_STR + "/2") == MAX/2 ); ASSERT( Solution().run(MAX_STR + "-" + MAX_STR) == 0 ); ASSERT( Solution().run(MAX_STR + "/" + MAX_STR) == 1 ); return 0; } }
29.098958
103
0.488992
artureganyan
3788fe0530bfedf4b2e6bad1f465723806fc3ce3
479
cpp
C++
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
1
2022-01-25T10:43:25.000Z
2022-01-25T10:43:25.000Z
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
null
null
null
HASInheritance/HASInheritance.cpp
100dlswjd/Cpp_study
0165bd0421ec8e4f86e72aa5bda847fb5c3f5cfb
[ "MIT" ]
1
2021-07-18T18:05:45.000Z
2021-07-18T18:05:45.000Z
#include<iostream> #include<cstring> class Gun { private: int bullet; public: Gun(int bnum) : bullet(bnum) { } void Shot() { std::cout << "BBANG!" << std::endl; bullet--; } }; class Police : public Gun { private: int handcuffs; public: Police(int bnum, int bcuff) : Gun(bnum), handcuffs(bcuff) { } void PutHandcuff() { std::cout << "SNAP!" << std::endl; handcuffs--; } }; int main(void) { Police pman(5, 3); pman.Shot(); pman.PutHandcuff(); return 0; }
12.605263
58
0.613779
100dlswjd
378971e99a6f2f5ed67bb9bedf76c75a656ef0f4
21,041
cc
C++
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
aeh/src/imgui_sdl_binding.cc
asielorz/aeh
6dbcce0970a558fb7f164b8880a3e834f9f6c8c9
[ "MIT" ]
null
null
null
#if defined AEH_WITH_SDL2 && defined AEH_WITH_IMGUI #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #ifdef _MSC_VER #pragma warning(disable : 4121) // alignment of a member was sensitive to packing #endif #include "imgui_sdl_binding.hh" #include <imgui.h> // SDL,GL3W #include <SDL.h> #include <SDL_syswm.h> #include <gl/gl_core_4_5.hh> // This example is using gl3w to access OpenGL functions (because it is small). You may use glew/glad/glLoadGen/etc. whatever already works for you. namespace aeh::ImGui_SDL { // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. // If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void RenderDrawData(Renderer const & renderer, ImDrawData * draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) ImGuiIO & io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLenum last_active_texture; gl::GetIntegerv(gl::ACTIVE_TEXTURE, (GLint *)&last_active_texture); gl::ActiveTexture(gl::TEXTURE0); GLint last_program; gl::GetIntegerv(gl::CURRENT_PROGRAM, &last_program); GLint last_texture; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); GLint last_sampler; gl::GetIntegerv(gl::SAMPLER_BINDING, &last_sampler); GLint last_array_buffer; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_polygon_mode[2]; gl::GetIntegerv(gl::POLYGON_MODE, last_polygon_mode); GLint last_viewport[4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport); GLint last_scissor_box[4]; gl::GetIntegerv(gl::SCISSOR_BOX, last_scissor_box); GLenum last_blend_src_rgb; gl::GetIntegerv(gl::BLEND_SRC_RGB, (GLint *)&last_blend_src_rgb); GLenum last_blend_dst_rgb; gl::GetIntegerv(gl::BLEND_DST_RGB, (GLint *)&last_blend_dst_rgb); GLenum last_blend_src_alpha; gl::GetIntegerv(gl::BLEND_SRC_ALPHA, (GLint *)&last_blend_src_alpha); GLenum last_blend_dst_alpha; gl::GetIntegerv(gl::BLEND_DST_ALPHA, (GLint *)&last_blend_dst_alpha); GLenum last_blend_equation_rgb; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, (GLint *)&last_blend_equation_rgb); GLenum last_blend_equation_alpha; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, (GLint *)&last_blend_equation_alpha); GLboolean last_enable_blend = gl::IsEnabled(gl::BLEND); GLboolean last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE); GLboolean last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST); GLboolean last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill gl::Enable(gl::BLEND); gl::BlendEquation(gl::FUNC_ADD); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); gl::Disable(gl::CULL_FACE); gl::Disable(gl::DEPTH_TEST); gl::Enable(gl::SCISSOR_TEST); gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL); // Setup viewport, orthographic projection matrix gl::Viewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float ortho_projection[4][4] = { { 2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; gl::UseProgram(renderer.ShaderHandle); gl::Uniform1i(renderer.AttribLocationTex, 0); gl::UniformMatrix4fv(renderer.AttribLocationProjMtx, 1, gl::FALSE_, &ortho_projection[0][0]); gl::BindSampler(0, 0); // Rely on combined texture/sampler state. // Recreate the VAO every time // (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.) GLuint vao_handle = 0; gl::GenVertexArrays(1, &vao_handle); gl::BindVertexArray(vao_handle); gl::BindBuffer(gl::ARRAY_BUFFER, renderer.VboHandle); gl::EnableVertexAttribArray(renderer.AttribLocationPosition); gl::EnableVertexAttribArray(renderer.AttribLocationUV); gl::EnableVertexAttribArray(renderer.AttribLocationColor); gl::VertexAttribPointer(renderer.AttribLocationPosition, 2, gl::FLOAT, gl::FALSE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, pos)); gl::VertexAttribPointer(renderer.AttribLocationUV, 2, gl::FLOAT, gl::FALSE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, uv)); gl::VertexAttribPointer(renderer.AttribLocationColor, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(ImDrawVert), (GLvoid *)IM_OFFSETOF(ImDrawVert, col)); // Draw for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList * cmd_list = draw_data->CmdLists[n]; const ImDrawIdx * idx_buffer_offset = 0; gl::BindBuffer(gl::ARRAY_BUFFER, renderer.VboHandle); gl::BufferData(gl::ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid *)cmd_list->VtxBuffer.Data, gl::STREAM_DRAW); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, renderer.ElementsHandle); gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid *)cmd_list->IdxBuffer.Data, gl::STREAM_DRAW); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd * pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { gl::BindTexture(gl::TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); gl::Scissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); gl::DrawElements(gl::TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? gl::UNSIGNED_SHORT : gl::UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } gl::DeleteVertexArrays(1, &vao_handle); // Restore modified GL state gl::UseProgram(last_program); gl::BindTexture(gl::TEXTURE_2D, last_texture); gl::BindSampler(0, last_sampler); gl::ActiveTexture(last_active_texture); gl::BindVertexArray(last_vertex_array); gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer); gl::BlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); gl::BlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); if (last_enable_blend) gl::Enable(gl::BLEND); else gl::Disable(gl::BLEND); if (last_enable_cull_face) gl::Enable(gl::CULL_FACE); else gl::Disable(gl::CULL_FACE); if (last_enable_depth_test) gl::Enable(gl::DEPTH_TEST); else gl::Disable(gl::DEPTH_TEST); if (last_enable_scissor_test) gl::Enable(gl::SCISSOR_TEST); else gl::Disable(gl::SCISSOR_TEST); gl::PolygonMode(gl::FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); gl::Viewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); gl::Scissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); } static const char * GetClipboardText(void *) { return SDL_GetClipboardText(); } static void SetClipboardText(void *, const char * text) { SDL_SetClipboardText(text); } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. bool ProcessEvent(Renderer & renderer, SDL_Event const * event) { ImGuiIO & io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.x > 0) io.MouseWheelH += 1; if (event->wheel.x < 0) io.MouseWheelH -= 1; if (event->wheel.y > 0) io.MouseWheel += 1; if (event->wheel.y < 0) io.MouseWheel -= 1; return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) renderer.MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) renderer.MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) renderer.MousePressed[2] = true; return true; } case SDL_TEXTINPUT: { io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.scancode; IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)); io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); return true; } } return false; } void CreateFontsTexture(Renderer & renderer) { // Build texture atlas ImGuiIO & io = ImGui::GetIO(); unsigned char * pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Upload texture to graphics system GLint last_texture; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); gl::GenTextures(1, &renderer.FontTexture); gl::BindTexture(gl::TEXTURE_2D, renderer.FontTexture); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR); gl::PixelStorei(gl::UNPACK_ROW_LENGTH, 0); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)renderer.FontTexture; // Restore state gl::BindTexture(gl::TEXTURE_2D, last_texture); } void RefreshFontsTexture(Renderer & renderer) { if (!HasDeviceObjects(renderer)) { // No device objects them. Create them. CreateDeviceObjects(renderer); } else { // Already has device objecs. Just reset the font texture. InvalidateFontsTexture(renderer); CreateFontsTexture(renderer); } } bool CreateDeviceObjects(Renderer & renderer) { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture); gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer); gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar * vertex_shader = "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 FraUV;\n" "out vec4 FraColor;\n" "void main()\n" "{\n" " FraUV = UV;\n" " FraColor = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar * fragment_shader = "uniform sampler2D Texture;\n" "in vec2 FraUV;\n" "in vec4 FraColor;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = FraColor * texture( Texture, FraUV.st);\n" "}\n"; GLchar const * vertex_shader_with_version[2] = { renderer.GlslVersion, vertex_shader }; GLchar const * fragment_shader_with_version[2] = { renderer.GlslVersion, fragment_shader }; renderer.ShaderHandle = gl::CreateProgram(); renderer.VertHandle = gl::CreateShader(gl::VERTEX_SHADER); renderer.FragHandle = gl::CreateShader(gl::FRAGMENT_SHADER); gl::ShaderSource(renderer.VertHandle, 2, vertex_shader_with_version, NULL); gl::ShaderSource(renderer.FragHandle, 2, fragment_shader_with_version, NULL); gl::CompileShader(renderer.VertHandle); gl::CompileShader(renderer.FragHandle); gl::AttachShader(renderer.ShaderHandle, renderer.VertHandle); gl::AttachShader(renderer.ShaderHandle, renderer.FragHandle); gl::LinkProgram(renderer.ShaderHandle); renderer.AttribLocationTex = gl::GetUniformLocation(renderer.ShaderHandle, "Texture"); renderer.AttribLocationProjMtx = gl::GetUniformLocation(renderer.ShaderHandle, "ProjMtx"); renderer.AttribLocationPosition = gl::GetAttribLocation(renderer.ShaderHandle, "Position"); renderer.AttribLocationUV = gl::GetAttribLocation(renderer.ShaderHandle, "UV"); renderer.AttribLocationColor = gl::GetAttribLocation(renderer.ShaderHandle, "Color"); gl::GenBuffers(1, &renderer.VboHandle); gl::GenBuffers(1, &renderer.ElementsHandle); ImGui_SDL::CreateFontsTexture(renderer); // Restore modified GL state gl::BindTexture(gl::TEXTURE_2D, last_texture); gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer); gl::BindVertexArray(last_vertex_array); return true; } void InvalidateFontsTexture(Renderer & renderer) { if (renderer.FontTexture) { gl::DeleteTextures(1, &renderer.FontTexture); ImGui::GetIO().Fonts->TexID = 0; renderer.FontTexture = 0; } } void InvalidateDeviceObjects(Renderer & renderer) { if (renderer.VboHandle) gl::DeleteBuffers(1, &renderer.VboHandle); if (renderer.ElementsHandle) gl::DeleteBuffers(1, &renderer.ElementsHandle); renderer.VboHandle = renderer.ElementsHandle = 0; if (renderer.ShaderHandle && renderer.VertHandle) gl::DetachShader(renderer.ShaderHandle, renderer.VertHandle); if (renderer.VertHandle) gl::DeleteShader(renderer.VertHandle); renderer.VertHandle = 0; if (renderer.ShaderHandle && renderer.FragHandle) gl::DetachShader(renderer.ShaderHandle, renderer.FragHandle); if (renderer.FragHandle) gl::DeleteShader(renderer.FragHandle); renderer.FragHandle = 0; if (renderer.ShaderHandle) gl::DeleteProgram(renderer.ShaderHandle); renderer.ShaderHandle = 0; InvalidateFontsTexture(renderer); } bool HasDeviceObjects(Renderer const & renderer) { return renderer.ShaderHandle != 0; } bool Init(Renderer & renderer, SDL_Window * window, const char * glsl_version) { // Store GL version string so we can refer to it later in case we recreate shaders. if (glsl_version == NULL) glsl_version = "#version 150"; IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(renderer.GlslVersion)); strcpy(renderer.GlslVersion, glsl_version); strcat(renderer.GlslVersion, "\n"); // Setup back-end capabilities flags ImGuiIO & io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT; io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X; io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y; io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z; io.SetClipboardTextFn = ImGui_SDL::SetClipboardText; io.GetClipboardTextFn = ImGui_SDL::GetClipboardText; io.ClipboardUserData = NULL; renderer.MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); renderer.MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); renderer.MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); renderer.MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); renderer.MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); renderer.MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); renderer.MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #else (void)window; #endif return true; } void Shutdown(Renderer & renderer) { // Destroy SDL mouse cursors for (SDL_Cursor * const cursor : renderer.MouseCursors) SDL_FreeCursor(cursor); memset(renderer.MouseCursors, 0, sizeof(renderer.MouseCursors)); // Destroy OpenGL objects ImGui_SDL::InvalidateDeviceObjects(renderer); } void NewFrame(Renderer & renderer, SDL_Window * window) { if (!HasDeviceObjects(renderer)) ImGui_SDL::CreateDeviceObjects(renderer); ImGuiIO & io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); io.DeltaTime = renderer.Time > 0 ? (float)((double)(current_time - renderer.Time) / frequency) : (float)(1.0f / 60.0f); renderer.Time = current_time; // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler) int mx, my; Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my); io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); io.MouseDown[0] = renderer.MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = renderer.MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = renderer.MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; renderer.MousePressed[0] = renderer.MousePressed[1] = renderer.MousePressed[2] = false; // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016) #if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4) if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0) io.MousePos = ImVec2((float)mx, (float)my); bool any_mouse_button_down = false; for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++) any_mouse_button_down |= io.MouseDown[n]; if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0) SDL_CaptureMouse(SDL_TRUE); if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0) SDL_CaptureMouse(SDL_FALSE); #else if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0) io.MousePos = ImVec2((float)mx, (float)my); #endif // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0) { ImGuiMouseCursor cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None) { SDL_ShowCursor(0); } else { SDL_SetCursor(renderer.MouseCursors[cursor] ? renderer.MouseCursors[cursor] : renderer.MouseCursors[ImGuiMouseCursor_Arrow]); SDL_ShowCursor(1); } } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); } } // namespace aeh::ImGui_SDL #endif // AEH_WITH_SDL2 && AEH_WITH_IMGUI
44.111111
244
0.740126
asielorz
378a8d3d6ef3cd2a57365c051682f558de2d86b3
943
cpp
C++
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/68_text_justification/solution.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<string> res; // num reprents the number of words in every row // cur is the current sum of lengths of added words int num, cur; for (int i = 0; i < words.size(); i += num) { for (num = cur = 0; i + num < words.size() && cur + words[i+num].size() <= maxWidth - num; num ++) cur += words[i+num].size(); string tmp = words[i]; for (int j = 0; j < num - 1; j ++) { if (i + num >= words.size()) tmp += " "; else tmp += string((maxWidth-cur) / (num-1) + (j < (maxWidth-cur) % (num-1)), ' '); tmp += words[i+j+1]; } tmp += string(maxWidth - tmp.size(), ' '); res.push_back(tmp); } return res; } };
34.925926
111
0.435843
zszyellow
378b5453822e8722875760675501fe3bfa67f4fd
463
cpp
C++
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-3/Program 3.4.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* write a program that performs LL COMPOUND assignment operations on an integer*/ #include"iostream" #include"conio.h" using namespace std; main() { int a=10; cout<<" Values of a "<<a<<endl; a+=5; cout<<"Values of a+=5 : "<<a<<endl; a-=5; cout<<"Values of a-=5 : "<<a<<endl; a*=2; cout<<"Values of a*=2 : "<<a<<endl; a/=2; cout<<"values of a/=2 : "<<a<<endl; a%=2; cout<<"values of a%=2 : "<<a<<endl; getch(); }
19.291667
69
0.537797
JahanzebNawaz
3795da8821bd6ffe8c5ee2562e4a6098e40ec5dd
2,657
cpp
C++
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/tuning/kernels/invert.cpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file uses the auto-tuner to tune the invert OpenCL kernels. // // ================================================================================================= #include "tuning/kernels/invert.hpp" // Shortcuts to the clblast namespace using half = clblast::half; using float2 = clblast::float2; using double2 = clblast::double2; // Main function (not within the clblast namespace) int main(int argc, char *argv[]) { const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv); switch(clblast::GetPrecision(command_line_args)) { case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<half>, clblast::InvertTestValidArguments<half>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<half>, clblast::InvertSetArguments<half>); break; case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<float>, clblast::InvertTestValidArguments<float>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<float>, clblast::InvertSetArguments<float>); break; case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<double>, clblast::InvertTestValidArguments<double>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<double>, clblast::InvertSetArguments<double>); break; case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<float2>, clblast::InvertTestValidArguments<float2>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<float2>, clblast::InvertSetArguments<float2>); break; case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, 0, clblast::InvertGetTunerDefaults, clblast::InvertGetTunerSettings<double2>, clblast::InvertTestValidArguments<double2>, clblast::InvertSetConstraints, clblast::InvertComputeLocalMemSize<double2>, clblast::InvertSetArguments<double2>); break; } return 0; } // =================================================================================================
75.914286
324
0.700414
vbkaisetsu
379660dcd5087fcecb1536dbfcc7bc3261befd38
129
hpp
C++
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/vector_angle.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:03e7fef2ca71e571577cdf63f979796b3db5d2d1dc938db5c767359822f146d4 size 1652
32.25
75
0.883721
realtehcman
379691a259e1f33731f12d3e463e148b22cb7abc
14,463
cpp
C++
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
sources/DisplayIa.cpp
usernameHed/Worms
35ee28362b936b46d24e7c911a46a2cfd615128b
[ "MIT" ]
null
null
null
#include "Display.hh" #include "AICore.hh" bool Display::iaIsPlaying() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return (false); int idTeam = this->listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->listPlayers[this->gameloop.getWormsPlayer()][1]; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getType() == IA) { //std::cout << "IA PLAY !" << std::endl; return (true); } //std::cout << "player PLAY !" << std::endl; return (false); } void Display::iaExportInfo() { std::cout << "send info to LUA..." << std::endl; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; //int idTeam = this->listPlayers[this->gameloop.getWormsPlayer()][0]; //int idWorms = this->listPlayers[this->gameloop.getWormsPlayer()][1]; AICore ac(*this); //LUARes res; ac.fillArray(); this->iaPlay.setIaMove(ac.executeBrain()); if (this->iaPlay.getIaMove().idWorms == -1) //TODO: IA TIR DIRECT { LUARes tmplua; tmplua.idWorms = 0; tmplua.weaponType = 0; if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->iaPlay.setIaMove(tmplua); } this->iaPlay.setAttack(false); this->iaPlay.reset(); } int Display::sign(int x) const { if (x < 0) return (-1); return 1; } bool Display::testLine(int x1, int y1, int x2, int y2) { int x = x2; int y = y2; int dy = y2 - y1; int dx = x2 - x1; if (std::abs(dy) > std::abs(dx)) { for(y = y1; y != y2; y += this->sign(dy)) { x = x1 + ( y - y1 ) * dx / dy; //this->island.change(x, y, SAND); if (this->island.isDestructible(this->island.getMapping(x, y))) return (false); } } else { for( x = x1; x != x2; x += this->sign(dx)) { y = y1 + ( x - x1 ) * dy / dx; //this->island.change(x, y, SAND); if (this->island.isDestructible(this->island.getMapping(x, y))) return (false); } } if (this->island.isDestructible(this->island.getMapping(x2, y2))) return (false); return (true); } bool Display::testIfToMuchFalling(int x, int y) { /////////////////// don't turn if is falling ! int z = y; while (z + 1 < this->island.getSizeY() - 1 && (!(this->island.isDestructible(this->island.getMapping(x, z))))) { ++z; if (z > this->island.getSizeY() - 5) return (false); } if (z - y >= (this->gameloop.getHeightWorms() * 5) || z > this->island.getSizeY() - 5) { std::cout << "FUCK FUCK FUCK !" << std::endl; return (false); } return (true); } void Display::hideWorms() { std::cout << "hide !" << std::endl; if (!this->checkNbPlayer(this->iaPlay.getIaMove().idWorms)) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeamTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][0]; int idWormsTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][1]; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; if ((this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() == DYNAMIT && this->iaPlay.hideHoriz > this->iaPlay.maxHideDynamit) || (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() != DYNAMIT && this->iaPlay.hideHoriz > this->iaPlay.maxHide)) return; this->iaPlay.hideHoriz++; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; int xEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().x; int yEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().y; int right = (x > xEnemy) ? -1 : 1; if (this->testIfToMuchFalling(x, y - right)) this->changeHoriz(x, y, idTeam, idWorms, -right); else this->changeHoriz(x, y, idTeam, idWorms, right); if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() != DYNAMIT) return; if (this->iaPlay.jumpHide < this->iaPlay.jumpHideMax) { std::cout << "jump hide" << std::endl; if (this->jump(x, y, idTeam, idWorms, JUMP_WORMS)) { ++this->iaPlay.jumpHide; } return; } } bool Display::testIsGroundDown(int x, int y) { int z = y; while (z + 1 < this->island.getSizeY() - 2) { if (this->island.isDestructible(this->island.getMapping(x, z))) { std::cout << "ok down" << std::endl; return (true); } ++z; } std::cout << "not ok" << std::endl; return (false); } void Display::iaMoveAfterJump() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; if (this->iaPlay.paraTime >= this->iaPlay.paraTimeMax) return; ++this->iaPlay.paraTime; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) { std::cout << "right" << std::endl; if (this->testIsGroundDown(x + 1, y) && this->testIsGroundDown(x + 2, y) && this->testIsGroundDown(x + 3, y) && this->testIsGroundDown(x + 4, y) && this->testIsGroundDown(x + 5, y) ) this->changeHoriz(x, y, idTeam, idWorms, 1); else this->changeHoriz(x, y, idTeam, idWorms, -1); } else { std::cout << "left" << std::endl; if (this->testIsGroundDown(x - 1, y) && this->testIsGroundDown(x - 2, y) && this->testIsGroundDown(x - 3, y) && this->testIsGroundDown(x - 4, y) && this->testIsGroundDown(x - 5, y) ) this->changeHoriz(x, y, idTeam, idWorms, -1); else this->changeHoriz(x, y, idTeam, idWorms, 1); } } void Display::iaPlaying() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; if (!this->weapons->getCanUsWeapon() && this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getWeaponsType() == JUMPTHOUGHTWALL) { this->iaMoveAfterJump(); return; } if (this->iaPlay.getAttack()) { this->hideWorms(); return; } if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getLife().getPv() < 5) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = -1; this->iaPlay.setIaMove(tmplua); this->iaNoLoSe(); return; } if (this->iaPlay.getIaMove().weaponType == 0) this->iaCac(); else if (this->iaPlay.getIaMove().weaponType == 1) this->iaDirect(); else if (this->iaPlay.getIaMove().weaponType == 2) this->iaIndirect(); else this->iaNoLoSe(); } void Display::iaJump() { if (!this->weapons->getCanUsWeapon()) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(JUMPTHOUGHTWALL); if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->weapons->attack(); } void Display::iaCac() { std::cout << "cac !" << std::endl; std::cout << "attack the worms: " << this->iaPlay.getIaMove().idWorms << std::endl; if (!this->checkNbPlayer(this->iaPlay.getIaMove().idWorms)) return; if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeamTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][0]; int idWormsTarget = this->gameloop.listPlayers[this->iaPlay.getIaMove().idWorms][1]; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; int xEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().x; int yEnemy = this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getPos().y; int right = (x > xEnemy) ? -1 : 1; /*if (std::abs(y - yEnemy) > this->gameloop.getHeightWorms() * 10) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = 1; this->iaPlay.setIaMove(tmplua); return; }*/ std::vector<int> wormsHit = this->weapons->getIaHit(x, y, this->gameloop.getWormsPlayer(), right); int i = 0; while (i < wormsHit.size()) { if (!this->checkNbPlayer(wormsHit[i])) { ++i; continue; } int tmpIdTeam = this->gameloop.listPlayers[wormsHit[i]][0]; //if (wormsHit[i] == this->iaPlay.getIaMove().idWorms) if (tmpIdTeam != idTeam) { std::cout << "CAC ATTACK !!" << std::endl; //random CAC ! WeaponsType tmpWeaponType = DYNAMIT; if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 3) tmpWeaponType = FINGER; else if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 25) tmpWeaponType = POUNCH; else if (this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getLife().getPv() <= 30) tmpWeaponType = BASEBALL; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(tmpWeaponType); if (!this->gameloop.menuSet) this->affWeaponsHUD(); if (tmpWeaponType == DYNAMIT) { int tmpRand = std::rand() % 100; if (tmpRand < 5) tmpWeaponType = FINGER; else if (tmpRand < 20) tmpWeaponType = BASEBALL; else if (tmpRand < 70 - ((this->gameloop.difficulty == HARD_GAME) ? ((this->gameloop.getWormsFromGameLoop(idTeamTarget, idWormsTarget).getType() == HUMAN) ? 25 : 0) : 0) ) tmpWeaponType = POUNCH; else { if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) this->dynamity(x + this->gameloop.getWidthWorm(), y); else this->dynamity(x - this->gameloop.getWidthWorm(), y); } } std::cout << "WEAPOIN TYPE: " << tmpWeaponType << std::endl; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(tmpWeaponType); if (!this->gameloop.menuSet) this->affWeaponsHUD(); this->weapons->attack(); ////////////////// this->displayWeaponType(); this->gameloop.setPhase(4); this->gameloop.setWaitTimeAfterAttack(); this->gameloop._debugTimerGame = 0.0; ////////////////// this->iaPlay.setAttack(true); return; } ++i; } int tmpXDebug = x; int tmpYDebug = y; if (!this->testIfToMuchFalling(x, y + right)) { std::cout << "MEGAJUMP ?" << std::endl; if (right > 0 && x > (this->island.getSizeX() / 100) * 70) this->changeHoriz(x, y, idTeam, idWorms, -right); else if (right < 0 && x < (this->island.getSizeX() / 100) * 30) this->changeHoriz(x, y, idTeam, idWorms, -right); this->iaJump(); return; } if (!this->changeHoriz(x, y, idTeam, idWorms, right)) { if (this->iaPlay.jumpFocus < this->iaPlay.jumpFocusMax) { std::cout << "JUMPPPPPPPPPPPPp" << std::endl; if (this->jump(x, y, idTeam, idWorms, JUMP_WORMS)) { ++this->iaPlay.jumpFocus; } return; } this->iaPlay.jumpDebugFocus++; std::cout << "err: " << this->iaPlay.jumpDebugFocus << std::endl; if (this->iaPlay.jumpDebugFocus > this->iaPlay.jumpDebugFocusMax) { LUARes tmplua; tmplua.idWorms = this->iaPlay.getIaMove().idWorms; tmplua.weaponType = -1; this->iaPlay.setIaMove(tmplua); } } /*if (!(tmpXDebug == x && tmpYDebug == y)) { x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; }*/ } void Display::iaDirect() { std::cout << "direct !" << std::endl; } void Display::iaIndirect() { std::cout << "indirect !" << std::endl; } void Display::iaNoLoSe() { if (!this->checkNbPlayer(this->gameloop.getWormsPlayer())) return; int idTeam = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][0]; int idWorms = this->gameloop.listPlayers[this->gameloop.getWormsPlayer()][1]; int x = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().x; int y = this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getPos().y; if (this->gameloop.menuSet) return; this->gameloop.getWormsFromGameLoop(idTeam, idWorms).setWeaponsType(DRILL); if (!this->gameloop.menuSet) this->affWeaponsHUD(); int right = -1; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) right = 1; if (!this->testIfToMuchFalling(x, y + right)) right *= -1; if (this->changeHoriz(x, y, idTeam, idWorms, right)) return; int angleToFind = 140; if (this->iaPlay.angleTmpDrill == -420042) { if (y > this->island.getSizeY() - this->gameloop.getHeightWorms() * 2) angleToFind = 65 - 55 + (rand() % 70); else angleToFind = 140 - 55 + (rand() % 70); this->iaPlay.angleTmpDrill = angleToFind; } else { if (y > this->island.getSizeY() - this->gameloop.getHeightWorms() * 2) this->iaPlay.angleTmpDrill = 65 - 55 + (rand() % 70); //this->iaPlay.angleTmpDrill = this->iaPlay.angleTmpDrill - 5 } if (this->gameloop._tmpAngle != this->iaPlay.angleTmpDrill) { if (this->gameloop._tmpAngle < this->iaPlay.angleTmpDrill) this->weapons->addAngleCursor(-1); else this->weapons->addAngleCursor(1); } else { std::cout << "drill !" << std::endl; bool tmpAdvance = false; if (this->gameloop.getWormsFromGameLoop(idTeam, idWorms).getDirection() == RIGHT) { if (this->testIfToMuchFalling(x, y + 1)) tmpAdvance = this->changeHoriz(x, y, idTeam, idWorms, 1); } else { if (this->testIfToMuchFalling(x, y - 1)) tmpAdvance = this->changeHoriz(x, y, idTeam, idWorms, -1); } //if (!tmpAdvance) this->actionRepeat(idTeam, idWorms, true); this->actionRepeat(idTeam, idWorms, true); } std::cout << "anglezfc: " << this->gameloop._tmpAngle << std::endl; }
30.194154
175
0.637212
usernameHed
3798209ae059cf42db81e73227fe89d750a5922f
8,860
cpp
C++
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
3
2015-07-04T03:35:51.000Z
2017-09-10T08:23:25.000Z
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
LLY/LLY/util/FuncUnitl.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
#include <glm/gtc/matrix_transform.hpp> #include "FuncUnitl.h" #include <fbxsdk.h> namespace lly_util { GLenum to_usage(lly::VertexUsage usage) { switch (usage) { case lly::VertexUsage::STATIC_DRAW: return GL_STATIC_DRAW; case lly::VertexUsage::STATIC_COPY: return GL_STATIC_COPY; case lly::VertexUsage::STATIC_READ: return GL_STATIC_READ; case lly::VertexUsage::STREAM_DRAW: return GL_STREAM_DRAW; case lly::VertexUsage::STREAM_COPY: return GL_STREAM_COPY; case lly::VertexUsage::STREAM_READ: return GL_STREAM_READ; case lly::VertexUsage::DYNAMIC_DRAW: return GL_DYNAMIC_DRAW; case lly::VertexUsage::DYNAMIC_COPY: return GL_DYNAMIC_COPY; case lly::VertexUsage::DYNAMIC_READ: return GL_DYNAMIC_READ; } return 0; } GLenum to_draw_mode(lly::DrawType mode) { switch (mode) { case lly::DrawType::POINTS: return GL_POINTS; case lly::DrawType::LINE_STRIP: return GL_LINE_STRIP; case lly::DrawType::LINE_LOOP: return GL_LINE_LOOP; case lly::DrawType::LINES: return GL_LINES; case lly::DrawType::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP; case lly::DrawType::TRIANGLE_FAN: return GL_TRIANGLE_FAN; case lly::DrawType::TRIANGLES: return GL_TRIANGLES; case lly::DrawType::QUAD_STRIP: return GL_QUAD_STRIP; case lly::DrawType::QUADS: return GL_QUADS; case lly::DrawType::POLYGON: return GL_POLYGON; } return 0; } GLenum to_color_format(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return GL_BGRA; case lly::ColorFormat::RGBA8888: return GL_RGBA; case lly::ColorFormat::RGB888: return GL_RGB; case lly::ColorFormat::RGB565: return GL_RGB565; case lly::ColorFormat::A8: return GL_ALPHA; case lly::ColorFormat::I8: return GL_LUMINANCE; case lly::ColorFormat::AI88: return GL_LUMINANCE_ALPHA; case lly::ColorFormat::RGBA4444: return GL_RGBA; case lly::ColorFormat::RGB5A1: return GL_RGBA; case lly::ColorFormat::RG16: return GL_RG16; case lly::ColorFormat::RG16F: return GL_RG16F; case lly::ColorFormat::R32F: return GL_R32F; case lly::ColorFormat::DEPTH_COMPONENT: return GL_DEPTH_COMPONENT; } return GL_RGBA; } int to_color_bpp(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return 32; case lly::ColorFormat::RGBA8888: return 32; case lly::ColorFormat::RG16: return 32; case lly::ColorFormat::RG16F: return 32; case lly::ColorFormat::R32F: return 32; case lly::ColorFormat::RGB888: return 24; case lly::ColorFormat::RGB565: return 16; case lly::ColorFormat::A8: return 8; case lly::ColorFormat::I8: return 8; case lly::ColorFormat::AI88: return 16; case lly::ColorFormat::RGBA4444: return 16; case lly::ColorFormat::RGB5A1: return 16; case lly::ColorFormat::DEPTH_COMPONENT: return 32; } return 32; } GLenum to_color_type(lly::ColorFormat format) { switch (format) { case lly::ColorFormat::BGRA8888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGBA8888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RG16: return GL_UNSIGNED_SHORT; case lly::ColorFormat::RG16F: return GL_HALF_FLOAT; case lly::ColorFormat::R32F: return GL_FLOAT; case lly::ColorFormat::RGB888: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGB565: return GL_UNSIGNED_SHORT_5_6_5; case lly::ColorFormat::A8: return GL_UNSIGNED_BYTE; case lly::ColorFormat::I8: return GL_UNSIGNED_BYTE; case lly::ColorFormat::AI88: return GL_UNSIGNED_BYTE; case lly::ColorFormat::RGBA4444: return GL_UNSIGNED_SHORT_4_4_4_4; case lly::ColorFormat::RGB5A1: return GL_UNSIGNED_SHORT_5_5_5_1; case lly::ColorFormat::DEPTH_COMPONENT: return GL_FLOAT; } return GL_UNSIGNED_BYTE; } GLenum to_min_filter(lly::TextureMinFilter filter) { return GL_LINEAR; } GLenum to_mag_filter(lly::TextureMagFilter filter) { return GL_LINEAR; } GLuint to_position(lly::VertexAttribPosition position) { switch (position) { case lly::VertexAttribPosition::POSITION: return 0; case lly::VertexAttribPosition::NORMAL: return 1; case lly::VertexAttribPosition::COLOR: return 2; case lly::VertexAttribPosition::TANGENT: return 3; case lly::VertexAttribPosition::TEXCOOD0: return 4; case lly::VertexAttribPosition::TEXCOOD1: return 5; case lly::VertexAttribPosition::TEXCOOD2: return 6; case lly::VertexAttribPosition::TEXCOOD3: return 7; case lly::VertexAttribPosition::TEXCOOD4: return 8; case lly::VertexAttribPosition::TEXCOOD5: return 9; case lly::VertexAttribPosition::TEXCOOD6: return 10; case lly::VertexAttribPosition::TEXCOOD7: return 11; case lly::VertexAttribPosition::WEIGHT0: return 12; case lly::VertexAttribPosition::WEIGHT1: return 13; case lly::VertexAttribPosition::WEIGHT2: return 14; case lly::VertexAttribPosition::WEIGHT3: return 15; } return 0; } GLenum to_data_type(lly::DataType type) { switch (type) { case lly::DataType::BYTE: return GL_BYTE; case lly::DataType::UNSIGNED_BYTE: return GL_UNSIGNED_BYTE; case lly::DataType::SHORT: return GL_SHORT; case lly::DataType::UNSIGNED_SHORT: return GL_UNSIGNED_SHORT; case lly::DataType::FIXED: return GL_FIXED; case lly::DataType::FLOAT: return GL_FLOAT; } return GL_FLOAT; } GLenum to_blend_factor(lly::BlendFactor factor) { switch (factor) { case lly::BlendFactor::DST_ALPHA: return GL_DST_ALPHA; case lly::BlendFactor::DST_COLOR: return GL_DST_COLOR; case lly::BlendFactor::ONE: return GL_ONE; case lly::BlendFactor::ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA; case lly::BlendFactor::ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR; case lly::BlendFactor::ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA; case lly::BlendFactor::SRC_ALPHA: return GL_SRC_ALPHA; case lly::BlendFactor::SRC_ALPHA_SATURATE: return GL_SRC_ALPHA_SATURATE; case lly::BlendFactor::ZERO: return GL_ZERO; } return GL_ZERO; } GLenum to_alpha_test_func(lly::AlphaTestFunc func) { switch (func) { case lly::AlphaTestFunc::ALWAYS: return GL_ALWAYS; case lly::AlphaTestFunc::NEVER: return GL_NEVER; case lly::AlphaTestFunc::LESS: return GL_LESS; case lly::AlphaTestFunc::LEQUAL: return GL_LEQUAL; case lly::AlphaTestFunc::EQUAL: return GL_EQUAL; case lly::AlphaTestFunc::GREATER: return GL_GREATER; case lly::AlphaTestFunc::GEQUAL: return GL_GEQUAL; case lly::AlphaTestFunc::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_depth_func(lly::DepthFunc func) { switch (func) { case lly::DepthFunc::ALWAYS: return GL_ALWAYS; case lly::DepthFunc::NEVER: return GL_NEVER; case lly::DepthFunc::LESS: return GL_LESS; case lly::DepthFunc::LEQUAL: return GL_LEQUAL; case lly::DepthFunc::EQUAL: return GL_EQUAL; case lly::DepthFunc::GREATER: return GL_GREATER; case lly::DepthFunc::GEQUAL: return GL_GEQUAL; case lly::DepthFunc::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_cull_fase_side(lly::CullFaceSide side) { switch (side) { case lly::CullFaceSide::FRONT: return GL_FRONT; case lly::CullFaceSide::BACK: return GL_BACK; } return GL_BACK; } GLenum to_front_face(lly::FrontFace front) { switch (front) { case lly::FrontFace::CCW: return GL_CCW; case lly::FrontFace::CW: return GL_CW; } return GL_CCW; } GLenum to_stencil_func(lly::StencilFuncType func) { switch (func) { case lly::StencilFuncType::ALWAYS: return GL_ALWAYS; case lly::StencilFuncType::NEVER: return GL_NEVER; case lly::StencilFuncType::LESS: return GL_LESS; case lly::StencilFuncType::LEQUAL: return GL_LEQUAL; case lly::StencilFuncType::EQUAL: return GL_EQUAL; case lly::StencilFuncType::GREATER: return GL_GREATER; case lly::StencilFuncType::GEQUAL: return GL_GEQUAL; case lly::StencilFuncType::NOTEQUAL: return GL_NOTEQUAL; } return GL_ALWAYS; } GLenum to_stencil_op(lly::StencilOpType func) { switch (func) { case lly::StencilOpType::KEEP: return GL_KEEP; case lly::StencilOpType::ZERO: return GL_ZERO; case lly::StencilOpType::REPLACE: return GL_REPLACE; case lly::StencilOpType::INCR: return GL_INCR; case lly::StencilOpType::DECR: return GL_DECR; case lly::StencilOpType::INVERT: return GL_INVERT; } return GL_KEEP; } GLenum to_warp(lly::TextureWrap wrap) { switch (wrap) { case lly::TextureWrap::REPEAT: return GL_REPEAT; case lly::TextureWrap::CLAMP: return GL_CLAMP; case lly::TextureWrap::CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE; } return GL_CLAMP_TO_EDGE; } bool eq(float a, float b) { return fabs(a - b) < 0.0000000001; } glm::mat4 to_sqt(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) { glm::mat4 ret = glm::mat4_cast(rotation); ret = glm::scale(ret, scale); //ret[0][0] *= scale.x; //ret[1][1] *= scale.y; //ret[2][2] *= scale.z; ret[3][0] = position.x; ret[3][1] = position.y; ret[3][2] = position.z; return ret; } }
30.979021
95
0.743567
ooeyusea
3798fa32cc12ed069b75b3e143c4ca518e0cacac
11,658
inl
C++
mnn/feedforward_impl.inl
defgsus/mnn
8d07bcfc0136f295624b2aaa071543b4ea4eecc7
[ "MIT" ]
null
null
null
mnn/feedforward_impl.inl
defgsus/mnn
8d07bcfc0136f295624b2aaa071543b4ea4eecc7
[ "MIT" ]
null
null
null
mnn/feedforward_impl.inl
defgsus/mnn
8d07bcfc0136f295624b2aaa071543b4ea4eecc7
[ "MIT" ]
null
null
null
/** @file feedforward_impl.inl @brief FeedForward layer implementation <p>(c) 2016, stefan.berke@modular-audio-graphics.com</p> <p>All rights reserved</p> <p>created 1/19/2016</p> */ #define MNN_TEMPLATE template <typename Float, class ActFunc> #define MNN_FEEDFORWARD FeedForward<Float, ActFunc> MNN_TEMPLATE MNN_FEEDFORWARD::FeedForward(size_t nrIn, size_t nrOut, Float learnRate, bool doBias) : learnRate_ (learnRate) , learnRateBias_(.1) , momentum_ (.1) , doBias_ (doBias) , doSoftmax_ (false) { resize(nrIn, nrOut); } MNN_TEMPLATE MNN_FEEDFORWARD::~FeedForward() { } MNN_TEMPLATE FeedForward<Float, ActFunc>& MNN_FEEDFORWARD::operator = (const Layer<Float>& layer) { auto net = dynamic_cast<const FeedForward<Float, ActFunc>*>(&layer); if (!net) return *this; input_ = net->input_; bias_ = net->bias_; output_ = net->output_; weight_ = net->weight_; prevDelta_ = net->prevDelta_; learnRate_ = net->learnRate_; learnRateBias_ = net->learnRateBias_; momentum_ = net->momentum_; doSoftmax_ = net->doSoftmax_; doBias_ = net->doBias_; return *this; } // ---------------- io ------------------- MNN_TEMPLATE void MNN_FEEDFORWARD::serialize(std::ostream& s) const { s << id(); // activation s << " " << ActFunc::static_name(); // version s << " " << 1; // settings s << " " << learnRate_ << " " << momentum_ << " " << doBias_ << " " << doSoftmax_ << "\n"; // dimension s << " " << input_.size() << " " << output_.size() << "\n"; // bias if (doBias_) for (auto b : bias_) s << " " << b; s << "\n"; // weights for (auto w : weight_) s << " " << w; } MNN_TEMPLATE void MNN_FEEDFORWARD::deserialize(std::istream& s) { std::string str; s >> str; if (str != id()) MNN_EXCEPTION("Expected '" << id() << "' in stream, found '" << str << "'"); // activation s >> str; // version int ver; s >> ver; if (ver > 1) MNN_EXCEPTION("Wrong version in " << name()); // settings s >> learnRate_ >> momentum_ >> doBias_ >> doSoftmax_; // dimension size_t numIn, numOut; s >> numIn >> numOut; resize(numIn, numOut); // bias if (doBias_) for (auto& b : bias_) s >> b; // weights for (auto& w : weight_) s >> w; } // ----------- nn interface -------------- MNN_TEMPLATE void MNN_FEEDFORWARD::resize(size_t nrIn, size_t nrOut) { input_.resize(nrIn); output_.resize(nrOut); bias_.resize(nrOut); weight_.resize(nrIn * nrOut); prevDelta_.resize(nrIn * nrOut); } MNN_TEMPLATE void MNN_FEEDFORWARD::grow(size_t nrIn, size_t nrOut, Float randomDev) { if (nrIn < numIn() || nrOut < numOut()) return; // copy weights std::vector<Float> weight(nrIn * nrOut), // and biases bias(nrOut); size_t o; for (o=0; o<output_.size(); ++o) { size_t i; for (i=0; i<input_.size(); ++i) weight[o * nrIn + i] = weight_[o * input_.size() + i]; // choose random input to copy size_t ri = size_t(rand()) % input_.size(); // run through additional inputs for (; i<nrIn; ++i) weight[o * nrIn + i] = weight_[o * input_.size() + ri] + rndg(Float(0), randomDev); // copy biases bias[o] = bias_[o]; } // run through additional outputs for (; o<nrOut; ++o) { // choose random input and output to copy size_t ro = size_t(rand()) % output_.size(); size_t ri = size_t(rand()) % input_.size(); size_t i; for (i=0; i<input_.size(); ++i) weight[o * nrIn + i] = weight_[ro * input_.size() + i]; for (; i<nrIn; ++i) weight[o * nrIn + i] = weight_[ro * input_.size() + ri] + rndg(Float(0), randomDev); bias[o] = bias_[ro]; } // assign new weights and biases weight_ = weight; bias_ = bias; // resize other buffers input_.resize(nrIn); for (auto&f : input_) f = 0; output_.resize(nrOut); for (auto&f : output_) f = 0; prevDelta_.resize(nrIn * nrOut); for (auto&f : prevDelta_) f = 0; } MNN_TEMPLATE void MNN_FEEDFORWARD::brainwash(Float amp) { // reset in/out for (auto& f : input_) f = 0.; for (auto& f : output_) f = 0.; // reset momentum for (auto& m : prevDelta_) m = 0.; if (input_.empty() || output_.empty()) return; // randomize weights (assume normalized states) Float f = amp / std::sqrt(input_.size()); for (auto e = weight_.begin(); e != weight_.end(); ++e) *e = rnd(-f, f); // randomize bias f = amp / output_.size(); for (auto& b : bias_) b = rnd(-f, f); } // ----------- propagation --------------- MNN_TEMPLATE void MNN_FEEDFORWARD::fprop(const Float * input, Float * output) { // copy to internal data for (auto i = input_.begin(); i != input_.end(); ++i, ++input) *i = *input; // propagate if (doBias_) DenseMatrix::fprop_bias<Float, ActFunc>( &input_[0], &output_[0], &bias_[0], &weight_[0], input_.size(), output_.size()); else DenseMatrix::fprop<Float, ActFunc>( &input_[0], &output_[0], &weight_[0], input_.size(), output_.size()); if (doSoftmax_) apply_softmax(&output_[0], output_.size()); // copy to caller std::copy(output_.begin(), output_.end(), output); } MNN_TEMPLATE void MNN_FEEDFORWARD::bprop(const Float * error, Float * error_output, Float learn_rate) { // calculate error derivative if (errorDer_.size() != output_.size()) errorDer_.resize(output_.size()); for (size_t i=0; i<output_.size(); ++i) errorDer_[i] = ActFunc::derivative(error[i], output_[i]); // pass error through if (error_output) DenseMatrix::bprop<Float>( error_output, &errorDer_[0], &weight_[0], input_.size(), output_.size()); if (learn_rate > 0.) { // gradient descent on weights if (learnRate_ > 0.) DenseMatrix::gradient_descent<Float, Activation::Linear>( &input_[0], &output_[0], &errorDer_[0], &weight_[0], &prevDelta_[0], input_.size(), output_.size(), learn_rate * learnRate_, momentum_); // gradient descent on biases if (doBias_ && learnRateBias_ > 0.) DenseMatrix::gradient_descent_bias<Float, Activation::Linear>( &output_[0], &errorDer_[0], &bias_[0], output_.size(), learn_rate * learnRateBias_); } } MNN_TEMPLATE void MNN_FEEDFORWARD::reconstruct(const Float* input, Float* reconstruction) { // get code for input if (doBias_) DenseMatrix::fprop_bias<Float, ActFunc>( input, &output_[0], &bias_[0], &weight_[0], input_.size(), output_.size()); else DenseMatrix::fprop<Float, ActFunc>( input, &output_[0], &weight_[0], input_.size(), output_.size()); // get reconstruction from code DenseMatrix::fprop_transpose<Float, ActFunc>( &output_[0], reconstruction, &weight_[0], output_.size(), input_.size()); } MNN_TEMPLATE Float MNN_FEEDFORWARD::reconstructionTraining( const Float *dec_input, const Float* true_input, Float global_learn_rate) { // copy to input for (auto i = input_.begin(); i != input_.end(); ++i, ++dec_input) *i = *dec_input; // get reconstruction space if (reconInput_.size() != input_.size()) reconInput_.resize(input_.size()); if (reconError_.size() != input_.size()) reconError_.resize(input_.size()); if (reconOutput_.size() != output_.size()) reconOutput_.resize(output_.size()); // get code for input if (doBias_) DenseMatrix::fprop_bias<Float, ActFunc>( &input_[0], &output_[0], &bias_[0], &weight_[0], input_.size(), output_.size()); else DenseMatrix::fprop<Float, ActFunc>( &input_[0], &output_[0], &weight_[0], input_.size(), output_.size()); if (doSoftmax_) apply_softmax(&output_[0], output_.size()); // get reconstruction from code DenseMatrix::fprop_transpose<Float, ActFunc>( &output_[0], &reconInput_[0], &weight_[0], output_.size(), input_.size()); // get reconstruction error Float err_sum = 0.; auto inp = true_input, err = &reconError_[0]; for (auto i : reconInput_) { Float e = *inp++ - i; err_sum += std::abs(e); *err++ = ActFunc::derivative(e, i); } err_sum /= input_.size(); // sum errors into code vector DenseMatrix::fprop<Float, Activation::Linear>( &reconError_[0], &reconOutput_[0], &weight_[0], input_.size(), output_.size()); // gradient descent using reconstruction error DenseMatrix::gradient_descent_transpose<Float, Activation::Linear>( &output_[0], &reconInput_[0], &reconError_[0], &weight_[0], &prevDelta_[0], output_.size(), input_.size(), global_learn_rate * learnRate_, momentum_); // gradient descent using code error DenseMatrix::gradient_descent<Float, Activation::Linear>( &input_[0], &output_[0], &reconOutput_[0], &weight_[0], &prevDelta_[0], input_.size(), output_.size(), global_learn_rate * learnRate_, momentum_); // gradient descent on biases using code error if (doBias_) DenseMatrix::gradient_descent_bias<Float, Activation::Linear>( &output_[0], &reconOutput_[0], &bias_[0], output_.size(), global_learn_rate * learnRateBias_); return err_sum; } // ----------- info ----------------------- MNN_TEMPLATE Float MNN_FEEDFORWARD::getWeightAverage() const { Float a = 0.; for (auto w : weight_) a += std::abs(w); if (!weight_.empty()) a /= weight_.size(); return a; } MNN_TEMPLATE void MNN_FEEDFORWARD::info(std::ostream &out, const std::string& pf) const { out << pf << "name : " << name() << "\n" << pf << "learnrate : " << learnRate_; if (doBias_) out << " (bias: " << learnRateBias_ << ")"; out << "\n" << pf << "momentum : " << momentum_ << "\n" << pf << "activation : " << ActFunc::static_name(); if (doSoftmax_) out << " (softmax)"; out << "\n" << pf << "inputs : " << numIn() << "\n" << pf << "outputs : " << numOut() << "\n" << pf << "parameters : " << numParameters() << std::endl; } MNN_TEMPLATE void MNN_FEEDFORWARD::dump(std::ostream &out) const { out << "inputs:"; for (auto v : input_) out << " " << v; out << "\noutputs:"; for (auto v : output_) out << " " << v; if (doBias_) { out << "\nbias:"; for (auto v : bias_) out << " " << v; } out << "\nweights:"; for (auto v : weight_) out << " " << v; out << std::endl; } #undef MNN_TEMPLATE #undef MNN_FEEDFORWARD
27.048724
85
0.536027
defgsus
379adf1e3c6e043d387b79fecbcb391ca333c0d2
127
cpp
C++
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
ComponentsLayer/CAN/CANRegistration.cpp
bddwyx/CylinderLoop
05621336b1b2415d7e583d9847020abd06e3eed6
[ "MIT" ]
null
null
null
// // Created by bddwy on 2021/1/26. // #include "CANRegistration.h" //CANCommunication CANCommunication::CAN1Communication;
15.875
55
0.748031
bddwyx
379c5c70d1cbe30871f057b6ccd60ba64c5f9305
548
hpp
C++
include/EDDIFrontEnd.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
24
2015-10-08T23:08:50.000Z
2021-09-18T21:15:01.000Z
include/EDDIFrontEnd.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
1
2016-02-29T20:20:45.000Z
2016-03-03T07:16:53.000Z
include/EDDIFrontEnd.hpp
wichtounet/eddic
66398a493a499eab5d1f465f93f9f099a2140d59
[ "MIT" ]
5
2015-08-09T09:53:52.000Z
2021-09-18T21:15:05.000Z
//======================================================================= // Copyright Baptiste Wicht 2011-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef EDDI_FRONT_END_H #define EDDI_FRONT_END_H #include "FrontEnd.hpp" namespace eddic { struct EDDIFrontEnd : public FrontEnd { std::unique_ptr<mtac::Program> compile(const std::string& file, Platform platform); }; } #endif
24.909091
87
0.54562
wichtounet
379ce0f47f09fcb877aa9528c7b7efaa6a527d08
1,716
cc
C++
aegis/src/model/ModifySearchConditionRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
aegis/src/model/ModifySearchConditionRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
aegis/src/model/ModifySearchConditionRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/aegis/model/ModifySearchConditionRequest.h> using AlibabaCloud::Aegis::Model::ModifySearchConditionRequest; ModifySearchConditionRequest::ModifySearchConditionRequest() : RpcServiceRequest("aegis", "2016-11-11", "ModifySearchCondition") {} ModifySearchConditionRequest::~ModifySearchConditionRequest() {} std::string ModifySearchConditionRequest::getFilterConditions()const { return filterConditions_; } void ModifySearchConditionRequest::setFilterConditions(const std::string& filterConditions) { filterConditions_ = filterConditions; setCoreParameter("FilterConditions", filterConditions); } std::string ModifySearchConditionRequest::getSourceIp()const { return sourceIp_; } void ModifySearchConditionRequest::setSourceIp(const std::string& sourceIp) { sourceIp_ = sourceIp; setCoreParameter("SourceIp", sourceIp); } std::string ModifySearchConditionRequest::getName()const { return name_; } void ModifySearchConditionRequest::setName(const std::string& name) { name_ = name; setCoreParameter("Name", name); }
28.131148
92
0.7669
iamzken
379f7c9d953ec2979a9e7154e6a4fdb766deac9a
7,584
cpp
C++
UIImplementation/Source/Preferences/DefaultEditorPreferencesPage.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
6
2017-06-17T00:03:14.000Z
2019-02-03T03:17:39.000Z
UIImplementation/Source/Preferences/DefaultEditorPreferencesPage.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
98
2016-08-31T12:49:09.000Z
2020-11-01T19:39:28.000Z
UIImplementation/Source/Preferences/DefaultEditorPreferencesPage.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
1
2019-02-03T03:17:40.000Z
2019-02-03T03:17:40.000Z
/* Copyright (c) 2015-2019 Xavier Leclercq Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Preferences/DefaultEditorPreferencesPage.h" #include "PreferencesDialogUtilities.h" #include "WindowIDs.h" #include <wx/sizer.h> #include <wx/fontdlg.h> namespace CodeSmithy { DefaultEditorPreferencesPage::DefaultEditorPreferencesPage(wxWindow *parent, AppSettings& appSettings) : wxPanel(parent, wxID_ANY), m_appSettings(appSettings), m_newSettings(appSettings.editorSettings().defaultSettings()), m_selectedTheme(0), m_overrideThemeCheckBox(0), m_fontFaceName(0), m_fontSize(0), m_fontButton(0), m_applyButton(0) { m_appSettings.themes().getAllThemes(m_themes); for (size_t i = 0; i < m_themes.size(); ++i) { if (m_themes[i]->name() == m_newSettings.themeName()) { m_selectedTheme = m_themes[i].get(); } } wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL); m_overrideThemeCheckBox = new wxCheckBox(this, PreferencesDefaultEditorOverrideThemeCheckBoxID, "Override theme"); m_overrideThemeCheckBox->SetValue(m_newSettings.overrideTheme()); m_fontFaceName = new wxTextCtrl(this, wxID_ANY); m_fontFaceName->SetValue(appSettings.editorSettings().defaultSettings().fontSettings().faceName()); m_fontFaceName->SetEditable(false); m_fontSize = new wxSpinCtrl(this, PreferencesDefaultEditorSizeSelectionButtonID, wxEmptyString, wxDefaultPosition, wxSize(50, wxDefaultCoord)); m_fontSize->SetMin(6); m_fontSize->SetMax(30); m_fontSize->SetValue(appSettings.editorSettings().defaultSettings().fontSettings().pointSize()); m_fontButton = new wxButton(this, PreferencesDefaultEditorFontSelectionButtonID, "Select Font..."); if (!m_overrideThemeCheckBox->IsChecked()) { m_fontFaceName->Disable(); m_fontSize->Disable(); m_fontButton->Disable(); } m_formatExample = new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxSize(wxDefaultCoord, 150), wxTE_MULTILINE); m_formatExample->SetValue("int main(int argc, char* argv[])\r\n{\r\n\treturn 0;\r\n}\r\n"); updateExample(); m_applyButton = new wxButton(this, PreferencesDefaultEditorPreferencesApplyButtonID, "Apply"); m_applyButton->Disable(); wxChoice * themeChoice = PreferencesDialogUtilities::createThemeSelectionChoice(this, PreferencesDefaultEditorThemeChoiceID, m_themes, m_newSettings.themeName()); wxSizer* themeSizer = PreferencesDialogUtilities::createThemeSelectionSizer(this, "Selected theme:", themeChoice); wxSizer* fontInfoSizer = PreferencesDialogUtilities::createFontSettingsSizer(m_overrideThemeCheckBox, m_fontFaceName, m_fontSize, m_fontButton); topSizer->Add(themeSizer, 0, wxEXPAND | wxLEFT | wxRIGHT, 10); topSizer->Add(fontInfoSizer, 0, wxEXPAND | wxALL, 10); topSizer->Add(m_formatExample, 0, wxEXPAND | wxALL, 2); topSizer->Add(m_applyButton); SetSizer(topSizer); } void DefaultEditorPreferencesPage::onThemeChanged(wxCommandEvent& evt) { m_selectedTheme = m_themes[evt.GetSelection()].get(); m_newSettings.setThemeName(m_selectedTheme->name()); updateExample(); updateApplyButtonStatus(); } void DefaultEditorPreferencesPage::onOverrideThemeChanged(wxCommandEvent& evt) { m_newSettings.setOverrideTheme(m_overrideThemeCheckBox->IsChecked()); if (evt.IsChecked()) { m_fontFaceName->Enable(); m_fontSize->Enable(); m_fontButton->Enable(); } else { m_fontFaceName->Disable(); m_fontSize->Disable(); m_fontButton->Disable(); } updateExample(); updateApplyButtonStatus(); } void DefaultEditorPreferencesPage::onPointSizeChanged(wxSpinEvent& evt) { m_newSettings.fontSettings().setPointSize(m_fontSize->GetValue()); updateExample(); updateApplyButtonStatus(); } void DefaultEditorPreferencesPage::onSelectFont(wxCommandEvent& evt) { wxFontDialog* fontDialog = new wxFontDialog(this); wxFontData& fontData = fontDialog->GetFontData(); wxFont font = fontData.GetInitialFont(); font.SetFaceName(m_fontFaceName->GetValue()); font.SetPointSize(m_fontSize->GetValue()); fontData.SetInitialFont(font); if (fontDialog->ShowModal() == wxID_OK) { wxFontData data = fontDialog->GetFontData(); m_fontFaceName->SetValue(data.GetChosenFont().GetFaceName()); m_fontSize->SetValue(data.GetChosenFont().GetPointSize()); std::string faceName = data.GetChosenFont().GetFaceName(); m_newSettings.fontSettings().setFaceName(faceName); m_newSettings.fontSettings().setPointSize(data.GetChosenFont().GetPointSize()); updateExample(); updateApplyButtonStatus(); } fontDialog->Destroy(); } void DefaultEditorPreferencesPage::onApply(wxCommandEvent& evt) { m_appSettings.editorSettings().defaultSettings() = m_newSettings; m_appSettings.save(); m_applyButton->Disable(); } void DefaultEditorPreferencesPage::updateExample() { wxFont font = m_formatExample->GetFont(); if (m_newSettings.overrideTheme()) { font.SetFaceName(m_newSettings.fontSettings().faceName()); font.SetPointSize(m_newSettings.fontSettings().pointSize()); } else { // TODO : this causes a crash //std::shared_ptr<EditorTheme> editorTheme = m_selectedTheme->getDefaultEditorTheme(); //font.SetFaceName(editorTheme->mainTextFontSettings().faceName()); //font.SetPointSize(editorTheme->mainTextFontSettings().pointSize()); } m_formatExample->SetFont(font); } void DefaultEditorPreferencesPage::updateApplyButtonStatus() { if (m_appSettings.editorSettings().defaultSettings() != m_newSettings) { m_applyButton->Enable(); } else { m_applyButton->Disable(); } } wxBEGIN_EVENT_TABLE(DefaultEditorPreferencesPage, wxPanel) EVT_CHOICE(PreferencesDefaultEditorThemeChoiceID, DefaultEditorPreferencesPage::onThemeChanged) EVT_CHECKBOX(PreferencesDefaultEditorOverrideThemeCheckBoxID, DefaultEditorPreferencesPage::onOverrideThemeChanged) EVT_SPINCTRL(PreferencesDefaultEditorSizeSelectionButtonID, DefaultEditorPreferencesPage::onPointSizeChanged) EVT_BUTTON(PreferencesDefaultEditorFontSelectionButtonID, DefaultEditorPreferencesPage::onSelectFont) EVT_BUTTON(PreferencesDefaultEditorPreferencesApplyButtonID, DefaultEditorPreferencesPage::onApply) wxEND_EVENT_TABLE() }
38.892308
147
0.731804
codesmithyide
37abbca612abf42da704b67d5cc9bf5c1235a53c
1,430
cpp
C++
Woopsi/libwoopsi/src/packedfont16.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
14
2016-01-25T01:01:25.000Z
2021-07-02T22:49:27.000Z
Woopsi/libwoopsi/src/packedfont16.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
1
2021-07-29T23:14:59.000Z
2021-07-29T23:14:59.000Z
Woopsi/libwoopsi/src/packedfont16.cpp
ant512/Woopsi
e7a568dc5e16ae772a5cad850527861ac2c2e703
[ "BSD-3-Clause" ]
4
2016-01-25T01:01:45.000Z
2021-09-04T23:39:10.000Z
#include "packedfont16.h" #include "mutablebitmapbase.h" using namespace WoopsiUI; // // pixeldata is an array of u16 values, each of which represents // a single pixel. // void PackedFont16::renderChar( const u16* pixelData, u16 pixelsPerRow, MutableBitmapBase* bitmap, u16 colour, s16 x, s16 y, u16 clipX1, u16 clipY1, u16 clipX2, u16 clipY2) { // Abort if there is nothing to render if ((clipY2 < y) || (clipY1 > y + getHeight() - 1) || (x > clipX2) || (x + pixelsPerRow - 1 < clipX1)) return; // adjust clipY2 to be the last row+1 in the glyph // so we only write while (y<=clipY2) if (clipY2 > y + getHeight() - 1) { clipY2 = y + getHeight() - 1; } // skip over font data corresponding to pixels ABOVE // the clipping rectangle. if (y < clipY1) { u16 rowsToSkip = clipY1 - y; u16 pixelsToSkip = rowsToSkip * pixelsPerRow; y = clipY1; pixelData += pixelsToSkip; } // now output pixels till we reach the end while (y <= clipY2) { // get pointer to next row in output u16 rowCount = pixelsPerRow; u16 rowX = x; while (rowCount-- > 0) { // get next pixel u16 pixel = *pixelData++; // if we need to, write it to the bitmap if ( pixel // non-transparent pixel && rowX >= clipX1 && rowX <= clipX2 // not clipped X-wise ) { bitmap->setPixel(rowX, y, colour ? colour : pixel); } rowX++; } // move output pointer down one row y++; } }
23.064516
64
0.634266
ant512
37aedb045dbe174d4c086b645dbec114137159a8
2,999
hpp
C++
blast/include/objmgr/impl/annot_finder.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
blast/include/objmgr/impl/annot_finder.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
blast/include/objmgr/impl/annot_finder.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJECTS_OBJMGR_IMPL___ANNOT_FINDER__HPP #define OBJECTS_OBJMGR_IMPL___ANNOT_FINDER__HPP /* $Id: annot_finder.hpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Maxim Didenko * * File Description: * */ #include <corelib/ncbiobj.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) class CTSE_Info; class CAnnotName; class CSeq_feat; class CSeq_align; class CSeq_graph; class CSeq_entry_Info; class CAnnotObject_Info; class CSeq_annot_Info; class CAnnot_descr; class IFindContext; class NCBI_XOBJMGR_EXPORT CSeq_annot_Finder { public: CSeq_annot_Finder(CTSE_Info& tse); const CAnnotObject_Info* Find(const CSeq_entry_Info& entry, const CAnnotName& name, const CSeq_feat& feat); const CAnnotObject_Info* Find(const CSeq_entry_Info& entry, const CAnnotName& name, const CSeq_align& align); const CAnnotObject_Info* Find(const CSeq_entry_Info& entry, const CAnnotName& name, const CSeq_graph& graph); const CSeq_annot_Info* Find(const CSeq_entry_Info& entry, const CAnnotName& name, const CAnnot_descr& descr); const CSeq_annot_Info* Find(const CSeq_entry_Info& entry, const CAnnotName& name); private: void x_Find(const CSeq_entry_Info& entry, const CAnnotName& name, IFindContext& context); CTSE_Info& m_TSE; }; inline CSeq_annot_Finder::CSeq_annot_Finder(CTSE_Info& tse) : m_TSE(tse) { } END_SCOPE(objects) END_NCBI_SCOPE #endif //OBJECTS_OBJMGR_IMPL___ANNOT_FINDER__HPP
31.568421
77
0.642881
mycolab
37af0a4f38530af2840f6bdcd0bb83a91d08aa6f
2,053
cpp
C++
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
2
2021-03-03T12:09:21.000Z
2021-06-19T03:18:53.000Z
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
1
2018-07-23T14:14:59.000Z
2018-07-23T14:14:59.000Z
54288411-save-a-list-of-qpixmaps-to-ico-file/save_pixmaps_to_ico.cpp
cbuchart/stackoverflow
8de12ccb4ff60762955298dfa0e4c6eca63b63ae
[ "Unlicense" ]
3
2018-07-23T14:04:46.000Z
2021-12-19T22:53:37.000Z
#include <qlist.h> #include <qpixmap.h> #include <qfileinfo.h> #include <qfile.h> #include <qtemporaryfile.h> namespace { template<typename T> void write(QFile& f, const T t) { f.write((const char*)&t, sizeof(t)); } } bool savePixmapsToICO(const QList<QPixmap>& pixmaps, const QString& path) { static_assert(sizeof(short) == 2, "short int is not 2 bytes"); static_assert(sizeof(int) == 4, "int is not 4 bytes"); QFile f(path); if (!f.open(QFile::OpenModeFlag::WriteOnly)) return false; // Header write<short>(f, 0); write<short>(f, 1); write<short>(f, pixmaps.count()); QList<int> images_size; for (int ii = 0; ii < pixmaps.count(); ++ii) { QTemporaryFile temp; temp.setAutoRemove(true); if (!temp.open()) return false; const auto& pixmap = pixmaps[ii]; pixmap.save(&temp, "PNG"); temp.close(); images_size.push_back(QFileInfo(temp).size()); } // Images directory constexpr unsigned int entry_size = sizeof(char) + sizeof(char) + sizeof(char) + sizeof(char) + sizeof(short) + sizeof(short) + sizeof(unsigned int) + sizeof(unsigned int); static_assert(entry_size == 16, "wrong entry size"); unsigned int offset = 3 * sizeof(short) + pixmaps.count() * entry_size; for (int ii = 0; ii < pixmaps.count(); ++ii) { const auto& pixmap = pixmaps[ii]; if (pixmap.width() > 256 || pixmap.height() > 256) continue; write<char>(f, pixmap.width() == 256 ? 0 : pixmap.width()); write<char>(f, pixmap.height() == 256 ? 0 : pixmap.height()); write<char>(f, 0); // palette size write<char>(f, 0); // reserved write<short>(f, 1); // color planes write<short>(f, pixmap.depth()); // bits-per-pixel write<unsigned int>(f, images_size[ii]); // size of image in bytes write<unsigned int>(f, offset); // offset offset += images_size[ii]; } for (int ii = 0; ii < pixmaps.count(); ++ii) { const auto& pixmap = pixmaps[ii]; if (pixmap.width() > 256 || pixmap.height() > 256) continue; pixmap.save(&f, "PNG"); } return true; }
29.328571
174
0.627862
cbuchart
37af8092b4a0a0816a929b7d6407ee1eae772b08
9,597
cpp
C++
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
src/HtmlDOM.cpp
liferili/HTML-Formatter
3ebf2a9814c8e077f98e2ef6d8135292d6387a76
[ "MIT" ]
null
null
null
// // Created by Liferov Ilia (liferili) on 5/12/16. // #include <fstream> #include <sstream> #include <deque> #include "HtmlDOM.h" #include "DoctypeNode.h" #include "PairTagNode.h" #include "SingleTagNode.h" #include "CommentNode.h" #include "TextNode.h" #include "ErrorTagNode.h" #include <algorithm> #include "StringHelper.h" using namespace std; //factory method. chooses type of tree node, creates it and pushes it to the html DOM tree void AddTag(string& tag, int line, deque<shared_ptr<PairTagNode>>& nodeStack, const HtmlElementCollection& htmlElements, HtmlErrorList& errors){ if (tag.substr(0,1)!="/"){ //if it is a opening tag if (tag.substr(tag.length()-1,1)=="/") tag=tag.substr(0,tag.length()-1); string checker=tag.substr(0,9); StringHelper::toLower(checker); if (checker =="!doctype "){ // if it is a doctype shared_ptr<DoctypeNode> ptr (new DoctypeNode(tag,line)); (*nodeStack.begin())->pushChild(ptr); } else if (tag.length()>=5 && ((tag.substr(0,3)=="!--" && tag.substr(tag.length()-2,2)=="--") || (tag.substr(0,4)=="!--[" && tag.substr(tag.length()-1,1)=="]") || (tag.substr(0,2)=="![" && tag.substr(tag.length()-3,3)=="]--"))){ // if it is a (conditional) comment shared_ptr<CommentNode> ptr (new CommentNode(tag, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //parsing element`s string to name and attributes vector<string> tokens; istringstream iss(tag); string tmp, token; getline(iss,tmp,' '); tokens.push_back(tmp); while(getline(iss,tmp,' ')){ token+=tmp; iss.seekg(-2,iss.cur); if (iss.peek()=='"'){ tokens.push_back(tmp); token.clear(); } else token+=" "; iss.seekg(2,iss.cur); } if (token!="") tokens.push_back(token); //---------------------------------------------- if (tokens.empty()){ //tag is empty <> errors.pushError(HtmlError("Empty tag", line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //tag is not empty string forSearch=tokens[0]; StringHelper::toLower(forSearch); auto it=htmlElements.elementCollection.find(forSearch); if (it==htmlElements.elementCollection.end()){ //undefined tag, pushing it into DOM as ErrorTag string errorMessage="Undefined tag \""+tokens[0]+"\""; errors.pushError(HtmlError(errorMessage, line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ if (it->second->isPaired()){ //element requires closing tag shared_ptr<PairTagNode> ptr (new PairTagNode(tokens[0], line, tokens)); (*nodeStack.begin())->pushChild(ptr); nodeStack.push_front(ptr); } else{ //element doesnt require closing tag shared_ptr<SingleTagNode> ptr(new SingleTagNode(tokens[0], line, tokens)); (*nodeStack.begin())->pushChild(ptr); } } } } } else{ //if it is a closing tag string closingTag=tag.substr(1,tag.length()-1); string lastInStack=(*nodeStack.begin())->getTagName(); StringHelper::toLower(closingTag); StringHelper::toLower(lastInStack); if (closingTag==lastInStack){ // exact match with the top of the stack (*nodeStack.begin())->setClosingTag(tag); nodeStack.pop_front(); } else{ auto it=htmlElements.elementCollection.find(closingTag); if (it==htmlElements.elementCollection.end()){ //if closing tag is undefined. Just pushing it into DOM as ErrorTag string errorMessage="Undefined tag \"\\"+tag.substr(1,tag.length())+"\""; errors.pushError(HtmlError(errorMessage,line)); string tagToText="<"+tag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } else{ //known tag. Checking if it was opened somewhere earlier auto stackIterator=nodeStack.begin(); for(; stackIterator!=nodeStack.end(); stackIterator++){ string name=(*stackIterator)->getTagName(); StringHelper::toLower(name); if (name==closingTag) break; } if (stackIterator!=nodeStack.end()){ //appropriate tag is not the last in stack string errorMessage; int cnt=0; for(auto i=nodeStack.begin(); i!=stackIterator; i++){ errorMessage="Closing tag for element \""+(*i)->getTagName()+"\"(opened on line: "+to_string((*i)->getLineNumber())+") expected"; errors.pushError(HtmlError(errorMessage, line)); cnt++; } for(auto i=0; i<cnt; i++) nodeStack.pop_front(); (*nodeStack.begin())->setClosingTag(tag); nodeStack.pop_front(); } else{ //tag has not been opened string errorMessage="End tag for element \""+tag.substr(1,tag.length())+"\" which is not open"; errors.pushError(HtmlError(errorMessage,line)); string tagToText="<"+closingTag+">"; shared_ptr<ErrorTagNode> ptr (new ErrorTagNode(tagToText, line)); (*nodeStack.begin())->pushChild(ptr); } } } } } //creates text node and pushes it to the html DOM tree void AddText(string& text, int line, deque<shared_ptr<PairTagNode>>& nodeStack){ StringHelper::trim(text); if (text!=" " && text!="\n" && text!=""){ //we dont need empty I suppose shared_ptr<TextNode> ptr (new TextNode(text, line)); (*nodeStack.begin())->pushChild(ptr); } } //helping function. deletes spaces from string void DeleteSpaces(string& src){ if (src.length()>=5 && ((src.substr(0,3))!="!--" || (src.substr(src.length()-2,2))!="--")){ auto it= unique(src.begin(), src.end(), [](char l, char r){return (l==r) && (l==' ');}); src.erase(it,src.end()); } } void HtmlDOM::createDOM(string inputFileName, const HtmlElementCollection& htmlElements, HtmlErrorList& errors) { ifstream inFile(inputFileName); if (!inFile.good()) throw Error("Cannot open input file \""+inputFileName+"\"."); bool readingTag=false; int lineNumber=0; string tmp, tag, text, piece; //creating the TOP node (represents the whole html document) deque<shared_ptr<PairTagNode>> nodeStack; vector<string> shame; shared_ptr<TopNode> top (new TopNode(lineNumber, shame)); this->top=top; nodeStack.push_front(top); //parsing input file into tags nad character data while(getline(inFile,tmp)){ lineNumber++; istringstream tmpLine(tmp); while (1) { if (readingTag) { getline(tmpLine, piece, '>'); if (tmpLine.eof()) { tag += piece; break; } else { tag += piece; DeleteSpaces(tag); AddTag(tag, lineNumber, nodeStack, htmlElements, errors); tag.clear(); readingTag = false; } } else { getline(tmpLine, piece, '<'); if (tmpLine.eof()) { text += piece; break; } else { text += piece; DeleteSpaces(text); if (!text.empty()) AddText(text, lineNumber, nodeStack); text.clear(); readingTag = true; } } } } //check the stack if there are any elements that should be closed while(nodeStack.size()!=1){ string errorMessage="Missing closing tag for \""+(*nodeStack.begin())->getTagName()+"\". Tag opens on line "+to_string((*nodeStack.begin())->getLineNumber()); errors.pushError(HtmlError(errorMessage, lineNumber)); nodeStack.pop_front(); } inFile.close(); } void HtmlDOM::validateDocument(HtmlElementCollection &elements, HtmlErrorList &errors)const { this->top->validate(elements, errors); } void HtmlDOM::printHtmlDocument(const string &ofileName, Format &format, HtmlElementCollection& collection) const { ofstream ofile(ofileName); if (!ofile.good()) throw Error("Cannot open output file \""+ofileName+"\""); cout << "Printing formatted document to \""+ofileName+"\" ..." << endl; this->top->print(format, ofile, collection); cout << "Done!" << endl << endl; }
40.838298
166
0.530791
liferili
37b0c710dfe57fb3fec4ee13e1cf78a22226997e
4,296
cpp
C++
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/MeshDrawable.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
/** @file MeshDrawable.cpp Copyright 2016 Computational Topology Group, University of Kaiserslautern 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. Author(s): C.Garth, T.Biedert */ #include <vector> #include "ugl/GLHelper.hpp" #include "ugl/MeshDrawable.hpp" namespace ugl { MeshDrawable::MeshDrawable( MeshData& data) : m_boundingBox( data.getBoundingBox() ), m_drawSurface( true ), m_drawEdges( false ), m_alpha( 1.0f ) { prepareShaderProgram(); prepareVertexArrays( data ); } /** * @brief Returns the addresses of the parameters which should be GUI controllable. * @param drawSurface * @param drawEdges * @param alpha */ void MeshDrawable::getTweakableParameters(bool** drawSurface, bool** drawEdges, float** alpha) { *drawSurface = &this->m_drawSurface; *drawEdges = &this->m_drawEdges; *alpha = &this->m_alpha; } // ------------------------------------------------------------------------- void MeshDrawable::prepareShaderProgram() { m_program.addImportPath("shader"); // add shader m_program.addShaderFromSourceFile( COMBINED, "ugl/mesh.glsl" ); m_program.addAttributeLocation( "vertexPosition", 0u ); m_program.addAttributeLocation( "vertexNormal", 1u ); } // ------------------------------------------------------------------------- void MeshDrawable::prepareVertexArrays( MeshData& data ) { // set up the vertex arrays and attribute bindings glGenVertexArrays( 1, &m_vertexArray ); glBindVertexArray( m_vertexArray ); // prepare vertex position buffer m_vertexPositionBuffer = GLHelper::prepareStaticBuffer( data.getPoints() ); glBindBuffer( GL_ARRAY_BUFFER, m_vertexPositionBuffer ); glVertexAttribPointer( 0u, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); glEnableVertexAttribArray( 0u ); glBindBuffer( GL_ARRAY_BUFFER, 0u ); // prepare vertex normal buffer m_vertexNormalBuffer = GLHelper::prepareStaticBuffer( data.getVertexNormals() ); glBindBuffer( GL_ARRAY_BUFFER, m_vertexNormalBuffer ); glVertexAttribPointer( 1u, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); glEnableVertexAttribArray( 1u ); glBindBuffer( GL_ARRAY_BUFFER, 0u ); // prepare triangle index buffer m_triangleBuffer = GLHelper::prepareStaticBuffer( data.getTriangles() ); m_triangleCount = data.getTriangleCount() * 3; // prepare edge index buffer m_edgeBuffer = GLHelper::prepareStaticBuffer( data.getEdges() ); m_edgeCount = data.getEdgeCount() * 2; // NOTE: we do not bind an ELEMENT_ARRAY here, since we will switch // on the fly between triangle and edge indices depending on render mode glBindVertexArray( 0u ); } // ------------------------------------------------------------------------- void MeshDrawable::draw( const StateSet& state ) { m_stateSet.setParent(state); UniformSet& uniforms = m_stateSet.getOrCreateUniforms(); ModeSet& modes = m_stateSet.getOrCreateModes(); uniforms.set( "alpha", m_alpha ); // set render modes and issue draw calls glBindVertexArray( m_vertexArray ); if( m_drawSurface ) { modes.clear( "LINE_MODE" ); // bind program and add uniforms m_stateSet.apply( m_program ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_triangleBuffer ); glDrawElements( GL_TRIANGLES, m_triangleCount, GL_UNSIGNED_INT, nullptr ); } if( m_drawEdges ) { modes.set( "LINE_MODE", 1 ); // bind program and add uniforms m_stateSet.apply( m_program ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_edgeBuffer ); glDrawElements( GL_LINES, m_edgeCount, GL_UNSIGNED_INT, nullptr ); } glBindVertexArray( 0u ); // done drawing } } // namespace ugl
29.424658
94
0.661778
dermegges
37b21f7f2aecd231395c94033afee6f56fd957e3
4,227
cpp
C++
third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/inspector/InspectorTracingAgent.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "core/inspector/InspectorTracingAgent.h" #include "core/frame/LocalFrame.h" #include "core/inspector/IdentifiersFactory.h" #include "core/inspector/InspectedFrames.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/InspectorWorkerAgent.h" #include "core/loader/FrameLoader.h" #include "platform/instrumentation/tracing/TraceEvent.h" namespace blink { using protocol::Maybe; using protocol::Response; namespace TracingAgentState { const char kSessionId[] = "sessionId"; } namespace { const char kDevtoolsMetadataEventCategory[] = TRACE_DISABLED_BY_DEFAULT("devtools.timeline"); } InspectorTracingAgent::InspectorTracingAgent(Client* client, InspectorWorkerAgent* worker_agent, InspectedFrames* inspected_frames) : layer_tree_id_(0), client_(client), worker_agent_(worker_agent), inspected_frames_(inspected_frames) {} DEFINE_TRACE(InspectorTracingAgent) { visitor->Trace(worker_agent_); visitor->Trace(inspected_frames_); InspectorBaseAgent::Trace(visitor); } void InspectorTracingAgent::Restore() { EmitMetadataEvents(); } void InspectorTracingAgent::FrameStartedLoading(LocalFrame* frame, FrameLoadType type) { if (frame != inspected_frames_->Root() || !IsReloadLoadType(type)) return; client_->ShowReloadingBlanket(); } void InspectorTracingAgent::FrameStoppedLoading(LocalFrame* frame) { if (frame != inspected_frames_->Root()) client_->HideReloadingBlanket(); } void InspectorTracingAgent::start(Maybe<String> categories, Maybe<String> options, Maybe<double> buffer_usage_reporting_interval, Maybe<String> transfer_mode, Maybe<protocol::Tracing::TraceConfig> config, std::unique_ptr<StartCallback> callback) { DCHECK(!IsStarted()); if (config.isJust()) { callback->sendFailure(Response::Error( "Using trace config on renderer targets is not supported yet.")); return; } instrumenting_agents_->addInspectorTracingAgent(this); state_->setString(TracingAgentState::kSessionId, IdentifiersFactory::CreateIdentifier()); client_->EnableTracing(categories.fromMaybe(String())); EmitMetadataEvents(); callback->sendSuccess(); } void InspectorTracingAgent::end(std::unique_ptr<EndCallback> callback) { client_->DisableTracing(); InnerDisable(); callback->sendSuccess(); } bool InspectorTracingAgent::IsStarted() const { return !SessionId().IsEmpty(); } String InspectorTracingAgent::SessionId() const { String result; if (state_) state_->getString(TracingAgentState::kSessionId, &result); return result; } void InspectorTracingAgent::EmitMetadataEvents() { TRACE_EVENT_INSTANT1(kDevtoolsMetadataEventCategory, "TracingStartedInPage", TRACE_EVENT_SCOPE_THREAD, "data", InspectorTracingStartedInFrame::Data( SessionId(), inspected_frames_->Root())); if (layer_tree_id_) SetLayerTreeId(layer_tree_id_); worker_agent_->SetTracingSessionId(SessionId()); } void InspectorTracingAgent::SetLayerTreeId(int layer_tree_id) { layer_tree_id_ = layer_tree_id; TRACE_EVENT_INSTANT1( kDevtoolsMetadataEventCategory, "SetLayerTreeId", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSetLayerTreeId::Data(SessionId(), layer_tree_id_)); } void InspectorTracingAgent::RootLayerCleared() { if (IsStarted()) client_->HideReloadingBlanket(); } Response InspectorTracingAgent::disable() { InnerDisable(); return Response::OK(); } void InspectorTracingAgent::InnerDisable() { client_->HideReloadingBlanket(); instrumenting_agents_->removeInspectorTracingAgent(this); state_->remove(TracingAgentState::kSessionId); worker_agent_->SetTracingSessionId(String()); } } // namespace blink
31.311111
80
0.698604
metux
37b341834d3486fa902db75e4afb765712eb2e84
2,206
hpp
C++
printscan/print/spooler/spoolss/splwow64/server/basecls.hpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/print/spooler/spoolss/splwow64/server/basecls.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/print/spooler/spoolss/splwow64/server/basecls.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef __BASECLS_HPP__ #define __BASECLS_HPP__ /*++ Copyright (C) 2000 Microsoft Corporation All rights reserved. Module Name: ldmgr.hpp Abstract: This file contains the declararion of some base classes that are utilized by other classes(objects) in the surrogate process So far we have 2 of these o Printer Driver class o Ref Count Class Author: Khaled Sedky (khaleds) 18-Jan-2000 Revision History: --*/ class TRefCntMgr { public: TRefCntMgr( VOID ); virtual ~TRefCntMgr( VOID ); virtual DWORD AddRef( VOID ); virtual DWORD Release( VOID ); private: LONG m_cRefCnt; }; class TClassID { public: char szClassID[32]; inline TClassID(char *pszCallerID) { ZeroMemory(szClassID,32); StringCchCopyA(szClassID, 32, pszCallerID); } }; class TPrinterDriver { public: TPrinterDriver( VOID ); virtual ~TPrinterDriver( VOID ); protected: HMODULE LoadPrinterDriver( IN HANDLE hPrinter ); }; #endif //__BASECLS_HPP__
23.72043
84
0.31777
npocmaka
37b3a9d320f0c5447242fbdcff4ff763dcec47e2
306
cpp
C++
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/4-var_scopes/60-global_symbolic_constants/src/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
#include <iostream> #include "constants.h" int main(){ std::cout << "Constant pi have value:\t\t" << Constants::pi << "\n"; std::cout << "Constant avogadro have value:\t" << Constants::avogadro << "\n"; std::cout << "Constant my_gravity have value:\t" << Constants::my_gravity << "\n"; return 0; }
25.5
83
0.627451
mitsiu-carreno
37b562d25d15dcbaaba466745b5a895f67dac0ee
3,563
cpp
C++
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
null
null
null
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
null
null
null
SharedModule/Threads/threadeventshelper.cpp
HowCanidothis-zz/DevLib
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
[ "MIT" ]
1
2020-07-27T02:23:38.000Z
2020-07-27T02:23:38.000Z
#include "threadeventshelper.h" #include <QMutexLocker> #include "SharedModule/internal.hpp" ThreadEvent::ThreadEvent(ThreadEvent::FEventHandler handler, const AsyncResult& result) : m_handler(handler) , m_result(result) {} void ThreadEvent::call() { try { m_handler(); m_result.Resolve(true); } catch (...) { m_result.Resolve(false); } } TagThreadEvent::TagThreadEvent(TagThreadEvent::TagsCache* tagsCache, const Name& tag, ThreadEvent::FEventHandler handler, const AsyncResult& result) : ThreadEvent(handler, result) , m_tag(tag) , m_tagsCache(tagsCache) { Q_ASSERT(!tagsCache->contains(tag)); tagsCache->insert(tag, this); } void TagThreadEvent::removeTag() { m_tagsCache->remove(m_tag); } void TagThreadEvent::call() { try { m_handler(); m_result.Resolve(true); } catch (...) { m_result.Resolve(false); } } ThreadEventsContainer::ThreadEventsContainer() : m_isPaused(false) , m_interupted(false) { } void ThreadEventsContainer::Continue() { if(!m_isPaused) { return; } m_isPaused = false; m_eventsPaused.wakeAll(); } AsyncResult ThreadEventsContainer::Asynch(const Name& tag, ThreadEvent::FEventHandler handler) { QMutexLocker locker(&m_eventsMutex); AsyncResult result; auto find = m_tagEventsMap.find(tag); if(find == m_tagEventsMap.end()) { auto tagEvent = new TagThreadEvent(&m_tagEventsMap, tag, handler, result); m_events.push(tagEvent); } else { find.value()->m_handler = handler; result = find.value()->m_result; } return result; } void ThreadEventsContainer::Pause(const FOnPause& onPause) { if(m_isPaused) { return; } m_onPause = onPause; m_isPaused = true; if(m_events.empty()) { Asynch([]{}); } while (!m_events.empty() && m_eventsMutex.tryLock()) { m_eventsMutex.unlock(); } } AsyncResult ThreadEventsContainer::Asynch(ThreadEvent::FEventHandler handler) { QMutexLocker locker(&m_eventsMutex); AsyncResult result; m_events.push(new ThreadEvent(handler, result)); return result; } void ThreadEventsContainer::clearEvents() { m_interupted = true; ProcessEvents(); QMutexLocker locker(&m_eventsMutex); while(!m_events.empty()) { delete m_events.front(); m_events.pop(); } m_interupted = false; } void ThreadEventsContainer::ProcessEvents() { QMutexLocker locker(&m_eventsMutex); while(!m_interupted && !m_events.empty()) { // from spurious wakeups m_eventsProcessed.wait(&m_eventsMutex); } } void ThreadEventsContainer::callEvents() { while(!m_interupted && !m_events.empty()) { ScopedPointer<ThreadEvent> event; { QMutexLocker locker(&m_eventsMutex); event = m_events.front(); m_events.pop(); event->removeTag(); } event->call(); } m_eventsProcessed.wakeAll(); } void ThreadEventsContainer::callPauseableEvents() { while(!m_interupted && !m_events.empty()) { ScopedPointer<ThreadEvent> event; { if(m_isPaused) { m_onPause(); } QMutexLocker locker(&m_eventsMutex); event = m_events.front(); m_events.pop(); while(m_isPaused) { m_eventsPaused.wait(&m_eventsMutex); } event->removeTag(); } event->call(); } m_eventsProcessed.wakeAll(); }
22.408805
148
0.625596
HowCanidothis-zz
37bb8374d97ff3c0b171fe06c2696f5ccd27ddbf
1,944
cpp
C++
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/test/BoostUnitTest/FabricGlobalsInitializationFixture.Test.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include "stdafx.h" #include <boost/test/unit_test.hpp> #include "Common/FabricGlobals.h" using namespace std; using namespace Common; /* Global fixture used to initialize the fabric globals This runs before any test case runs and is used to mark the singleton instance of fabric globals in this module as primary. This is intended for use in any unit test that is testing a component that is below fabric common in the hierarchy It assumes that the config is in a .cfg file or store -> fails otherwise */ namespace { ConfigStoreDescriptionUPtr CreateTestConfigStore() { ConfigStoreType::Enum storeType; wstring storeLocation; auto error = FabricEnvironment::GetStoreTypeAndLocation(nullptr, storeType, storeLocation); if (!error.IsSuccess()) { throw std::runtime_error("Failed FabricEnv::GetStoreTypeAndLocation"); } if (storeType == ConfigStoreType::Cfg) { return make_unique<ConfigStoreDescription>( make_shared<FileConfigStore>(storeLocation), *FabricEnvironment::FileConfigStoreEnvironmentVariable, storeLocation); } if (storeType == ConfigStoreType::None) { return make_unique<ConfigStoreDescription>( make_shared<ConfigSettingsConfigStore>(move(ConfigSettings())), L"", L""); } throw std::invalid_argument("Unsupported config store type for test"); } } struct FabricGlobalsInit { FabricGlobalsInit() { FabricGlobals::InitializeAsMaster(&CreateTestConfigStore); } }; BOOST_GLOBAL_FIXTURE(FabricGlobalsInit);
30.375
99
0.609568
vishnuk007
37bc7751f1bb5f51ef22ad2d62bcb04815476f22
5,315
cpp
C++
detector/!old/HoughDetector.lib/src/HoughForestOptionsLoader.cpp
kevromster/freepark
12187de88e3de569864223b87a1f09fc576e5160
[ "Apache-2.0" ]
null
null
null
detector/!old/HoughDetector.lib/src/HoughForestOptionsLoader.cpp
kevromster/freepark
12187de88e3de569864223b87a1f09fc576e5160
[ "Apache-2.0" ]
null
null
null
detector/!old/HoughDetector.lib/src/HoughForestOptionsLoader.cpp
kevromster/freepark
12187de88e3de569864223b87a1f09fc576e5160
[ "Apache-2.0" ]
null
null
null
#include "HoughForestOptionsLoader.h" #include "HoughForestOptions.h" #include "HDException.h" #include "HDLibLog.h" #include "Utils.h" #include <fstream> HoughForestOptionsLoader::HoughForestOptionsLoader(const std::string & _strConfigFileName, HoughForestOptions & _options) : m_options(_options), m_strConfigFileName(_strConfigFileName) { } void HoughForestOptionsLoader::loadAll() { _initKnownOptions(); _loadConfigFile(); _checkAllOptionsSet(); if (!m_options.areCorrect()) throw BadOptionException("Some options are INCORRECT after parsing!"); } void HoughForestOptionsLoader::_initKnownOptions() { m_optionsSetter.addKnownOption("patch_width", &HoughForestOptionsLoader::_setPatchWidth); m_optionsSetter.addKnownOption("patch_height", &HoughForestOptionsLoader::_setPatchHeight); m_optionsSetter.addKnownOption("train_object_width", &HoughForestOptionsLoader::_setTrainObjectWidth); m_optionsSetter.addKnownOption("train_object_height", &HoughForestOptionsLoader::_setTrainObjectHeight); m_optionsSetter.addKnownOption("patches_count", &HoughForestOptionsLoader::_setPatchesCount); m_optionsSetter.addKnownOption("trees_count", &HoughForestOptionsLoader::_setTreesCount); m_optionsSetter.addKnownOption("trained_forest_path", &HoughForestOptionsLoader::_setTrainedForestPath); m_optionsSetter.addKnownOption("tree_max_depth", &HoughForestOptionsLoader::_setTreeMaxDepth); m_optionsSetter.addKnownOption("tree_min_patches_in_leaf", &HoughForestOptionsLoader::_setMinPatchesInLeaf); m_optionsSetter.addKnownOption("train_tree_iterations_count", &HoughForestOptionsLoader::_setTrainIterationsCount); } void HoughForestOptionsLoader::_setOption(const std::string & _strOption, const std::string & _strValue) { m_optionsSetter.setOption(*this, _strOption, _strValue); } bool HoughForestOptionsLoader::_isKnownOption(const std::string & _strOption) const { return m_optionsSetter.isKnownOption(_strOption); } void HoughForestOptionsLoader::_checkAllOptionsSet() const { m_optionsSetter.checkAllOptionsSet(); } void HoughForestOptionsLoader::_loadConfigFile() { if (m_strConfigFileName.empty()) throw ParseOptionsException("bad config file name"); std::ifstream in(m_strConfigFileName); if (!in.is_open()) throw ParseOptionsException("Main config file not found: " + m_strConfigFileName); const int SZ = 1024; char buffer[SZ]; std::string line; std::vector<std::string> vSplittedLine; for (unsigned int uLine = 1; in.good(); ++uLine) { in.getline(buffer, SZ); if (in.bad()) throw ParseOptionsException("Error reading stream of main config file"); line = buffer; trim(line); if (line.empty() || line.front() == '#') continue; vSplittedLine = split(line, '='); if (vSplittedLine.size() != 2) { LOG(WARNING) << "Wrong option description at line " << uLine << ", ignore it (acceptable format: <option>=<value>)"; continue; } const std::string & strOption = trim(vSplittedLine[0]); const std::string & strValue = trim(vSplittedLine[1]); if (!_isKnownOption(strOption)) { LOG(WARNING) << "Unknown option \"" << strOption << "\" at line " << uLine << ", ignore it"; continue; } // set value HDLOG << "Setting option \"" << strOption << "\" to \"" << strValue << "\"..."; _setOption(strOption, strValue); } } void HoughForestOptionsLoader::_setTrainedForestPath(const std::string & _strOption) { m_options.setTrainedForestPath(_strOption); } void HoughForestOptionsLoader::_setPatchWidth(const std::string & _strOption) { int nWidth = 0; std::istringstream(_strOption) >> nWidth; if (nWidth > 0) m_options.setPatchWidth(nWidth); } void HoughForestOptionsLoader::_setPatchHeight(const std::string & _strOption) { int nHeight = 0; std::istringstream(_strOption) >> nHeight; if (nHeight > 0) m_options.setPatchHeight(nHeight); } void HoughForestOptionsLoader::_setTrainObjectWidth(const std::string & _strOption) { int nWidth = 0; std::istringstream(_strOption) >> nWidth; if (nWidth > 0) m_options.setTrainObjectWidth(nWidth); } void HoughForestOptionsLoader::_setTrainObjectHeight(const std::string & _strOption) { int nHeight = 0; std::istringstream(_strOption) >> nHeight; if (nHeight > 0) m_options.setTrainObjectHeight(nHeight); } void HoughForestOptionsLoader::_setPatchesCount(const std::string & _strOption) { unsigned int uCount = 0; std::istringstream(_strOption) >> uCount; if (uCount > 0) m_options.setPatchesCount(uCount); } void HoughForestOptionsLoader::_setTreesCount(const std::string & _strOption) { unsigned int uCount = 0; std::istringstream(_strOption) >> uCount; if (uCount > 0) m_options.setTreesCount(uCount); } void HoughForestOptionsLoader::_setTreeMaxDepth(const std::string & _strOption) { unsigned int uValue = 0; std::istringstream(_strOption) >> uValue; if (uValue > 0) m_options.setTreeMaxDepth(uValue); } void HoughForestOptionsLoader::_setMinPatchesInLeaf(const std::string & _strOption) { unsigned int uValue = 0; std::istringstream(_strOption) >> uValue; if (uValue > 0) m_options.setMinPatchesInLeaf(uValue); } void HoughForestOptionsLoader::_setTrainIterationsCount(const std::string & _strOption) { unsigned int uValue = 0; std::istringstream(_strOption) >> uValue; if (uValue > 0) m_options.setTrainIterationsCount(uValue); }
32.808642
123
0.762371
kevromster
37bcefe894653a0cffcdc28649dbde3c0ae68ac5
5,398
cpp
C++
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
9
2018-10-18T18:13:14.000Z
2021-07-21T19:55:56.000Z
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2020-08-18T02:07:09.000Z
2020-08-19T12:50:55.000Z
cflw代码库/cflw音频_xa2.cpp
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2019-04-22T20:35:04.000Z
2019-04-22T20:35:04.000Z
#include <cassert> #include <algorithm> #include "cflw音频_xa2.h" namespace cflw::音频::xa2 { using 多媒体::FindChunk; using 多媒体::ReadChunkData; //============================================================================== // 辅助函数 //============================================================================== void f销毁声音(IXAudio2Voice *a) { a->DestroyVoice(); } //============================================================================== // 音频引擎 //============================================================================== C音频::C音频() { }; C音频::~C音频() { if (m音频) { f销毁(); } }; HRESULT C音频::f初始化() { HRESULT hr; hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(hr)) { return hr; } hr = XAudio2Create(&m音频, 0, XAUDIO2_DEFAULT_PROCESSOR); if (FAILED(hr)) { return hr; } hr = m音频->CreateMasteringVoice(&m声音控制); if (FAILED(hr)) { return hr; } return S_OK; }; void C音频::f销毁() { f销毁声音(m声音控制); m声音控制 = nullptr; m音频.Reset(); CoUninitialize(); }; HRESULT C音频::f创建声音(tp声音 &a声音, const std::wstring_view &a文件) { HRESULT hr; C波形文件 v文件; hr = v文件.f打开(a文件); if (FAILED(hr)) { return hr; } if (!v文件.f检查类型()) { return E_FAIL; //不是波形格式 } tp声音 v声音 = std::make_shared<C声音>(); v声音->m格式 = v文件.f读取格式(); const auto &[v数据, v数据大小] = v文件.f读取数据(); v声音->m数据 = std::unique_ptr<std::byte>(v数据); v声音->m大小 = v数据大小; //填充缓冲 v声音->m缓冲.AudioBytes = (UINT32)v数据大小; v声音->m缓冲.pAudioData = (BYTE*)v数据; v声音->m缓冲.Flags = XAUDIO2_END_OF_STREAM; v声音->m缓冲.LoopBegin = XAUDIO2_NO_LOOP_REGION; v声音->m缓冲.LoopLength = 0; v声音->m缓冲.LoopCount = 0; //结束 a声音 = std::move(v声音); return S_OK; }; HRESULT C音频::f创建源声音(tp源声音 &a源声音, const C声音 &a声音, const C混合 &a混合) { IXAudio2SourceVoice *v源声音; HRESULT hr = m音频->CreateSourceVoice(&v源声音, (WAVEFORMATEX*)&a声音.m格式, 0, 2, nullptr, &a混合.m列表); if (FAILED(hr)) { return hr; } a源声音 = std::shared_ptr<IXAudio2SourceVoice>(v源声音, &f销毁声音); return S_OK; } HRESULT C音频::f创建混合(tp混合 &a混合) { tp混合 v混合 = std::make_shared<C混合>(); HRESULT hr = m音频->CreateSubmixVoice(&v混合->m声音, 1, 44100); if (FAILED(hr)) { return hr; } v混合->m发送.Flags = 0; v混合->m发送.pOutputVoice = v混合->m声音; v混合->m列表.pSends = &v混合->m发送; v混合->m列表.SendCount = 1; a混合 = std::move(v混合); return S_OK; } //============================================================================== // 播放控制 //============================================================================== C播放控制::C播放控制() { } void C播放控制::f初始化(C音频 &a) { m音频 = &a; m当前时间 = std::chrono::system_clock::now(); } void C播放控制::f刷新() { for (auto v迭代 = ma播放.begin(); v迭代 != ma播放.end();) { const auto &[v播放, v源声音] = *v迭代; ++v迭代; XAUDIO2_VOICE_STATE v状态; v源声音->GetState(&v状态); if (v状态.BuffersQueued <= 0) { ma播放.erase(v播放); } } m当前时间 = std::chrono::system_clock::now(); } tp播放 C播放控制::f播放(const C声音 &a声音, const C混合 &a混合) { //去重 if (const auto &v找声音 = m声音去重.find(&a声音); v找声音 != m声音去重.end()) { if (const float v时间差 = std::chrono::duration<float>(m当前时间 - v找声音->second).count(); v时间差 <= m声音间隔) { return 0; //重复,不播放 } } //播放 tp播放 v播放 = (++m序号); tp源声音 v源声音; m音频->f创建源声音(v源声音, a声音, a混合); v源声音->SubmitSourceBuffer(&a声音.m缓冲); v源声音->Start(); m声音去重[&a声音] = m当前时间; ma播放[v播放] = v源声音; return v播放; } void C播放控制::f暂停(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Stop(); } } void C播放控制::f恢复(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Start(); } } void C播放控制::f停止(tp播放 a) { if (const auto &v找播放 = ma播放.find(a); v找播放 != ma播放.end()) { v找播放->second->Stop(); ma播放.erase(a); } } void C播放控制::f停止全部() { for (const auto &[v播放, v源声音] : ma播放) { v源声音->Stop(); } ma播放.clear(); } bool C播放控制::fi播放(tp播放 a) { const auto &v找播放 = ma播放.find(a); return v找播放 != ma播放.end(); } void C播放控制::fs重复播放间隔(float a) { m声音间隔 = a; } //============================================================================== // 声音 //============================================================================== C混合::~C混合() { if (m声音) { f销毁声音(m声音); } } void C混合::f销毁() { f销毁声音(m声音); m声音 = nullptr; } void C混合::fs音量(float a) { m声音->SetVolume(a); } float C混合::fg音量() const { float v; m声音->GetVolume(&v); return v; } //============================================================================== // 波形文件 //============================================================================== HRESULT C波形文件::f打开(const std::wstring_view &a文件名) { m文件 = CreateFileW(a文件名.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (INVALID_HANDLE_VALUE == m文件) return HRESULT_FROM_WIN32(GetLastError()); if (INVALID_SET_FILE_POINTER == SetFilePointer(m文件, 0, nullptr, FILE_BEGIN)) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; }; bool C波形文件::f检查类型() const { DWORD v块大小; DWORD v块位置; DWORD v文件类型; FindChunk(m文件, 多媒体::c块RIFF, v块大小, v块位置); ReadChunkData(m文件, &v文件类型, sizeof(DWORD), v块位置); return v文件类型 == 多媒体::c块WAVE; }; WAVEFORMATEXTENSIBLE C波形文件::f读取格式() const { DWORD v块大小; DWORD v块位置; WAVEFORMATEXTENSIBLE v格式; FindChunk(m文件, 多媒体::c块fmt, v块大小, v块位置); ReadChunkData(m文件, &v格式, v块大小, v块位置); return v格式; }; std::pair<std::byte*, size_t> C波形文件::f读取数据() const { DWORD v块大小; DWORD v块位置; FindChunk(m文件, 多媒体::c块data, v块大小, v块位置); std::byte *v数据 = new std::byte[v块大小]; ReadChunkData(m文件, v数据, v块大小, v块位置); return {v数据, v块大小}; }; bool C波形文件::f关闭() { return CloseHandle(m文件); } } //namespace cflw::音频::xa2
24.761468
101
0.546684
cflw
37bed6e1e3ab956939df772f3cc0848f3eef1bdb
3,755
cpp
C++
auditory/example/src/android/wov/WakeOnVoiceService/IWakeonVoice.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
3
2016-11-06T04:55:11.000Z
2019-05-18T06:56:10.000Z
auditory/example/src/android/wov/WakeOnVoiceService/IWakeonVoice.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
null
null
null
auditory/example/src/android/wov/WakeOnVoiceService/IWakeonVoice.cpp
yao-matrix/mProto
e5fecce2693056ac53f7d34d00801829ea1094c3
[ "Apache-2.0" ]
4
2016-11-27T01:08:41.000Z
2021-03-11T05:32:04.000Z
#include <utils/Errors.h> #include <utils/Log.h> #include "IWakeonVoice.h" namespace wakeonvoice { enum { START_LISTEN, STOP_LISTEN, START_ENROLL, STOP_ENROLL, ENABLE_DEBUG, SET_ENROLLTIMES, SET_SECURITYLEVEL, REGISTER_LISTENER, }; status_t BnWakeonVoice::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags ) { LOGI( "onTransact code: %d", code ); switch ( code ) { case START_LISTEN: { CHECK_INTERFACE( IWakeonVoice, data, reply ); reply->writeInt32( this->fnStartListen() ); return OK; } break; case STOP_LISTEN: { CHECK_INTERFACE( IWakeonVoice, data, reply ); int ret = this->fnStopListen(); reply->writeInt32( ret ); return OK; } break; case START_ENROLL: { CHECK_INTERFACE( IWakeonVoice, data, reply ); reply->writeInt32( this->fnStartEnroll() ); return OK; } break; case ENABLE_DEBUG: { CHECK_INTERFACE( IWakeonVoice, data, reply ); int i = data.readInt32(); reply->writeInt32( this->fnEnableDebug( i ) ); return OK; } break; case SET_ENROLLTIMES: { CHECK_INTERFACE( IWakeonVoice, data, reply ); int t = data.readInt32(); reply->writeInt32( this->fnSetEnrollTimes( t ) ); return OK; } break; case SET_SECURITYLEVEL: { CHECK_INTERFACE( IWakeonVoice, data, reply ); int s = data.readInt32(); reply->writeInt32( this->fnSetSecurityLevel( s ) ); return OK; } break; case REGISTER_LISTENER: { CHECK_INTERFACE( IWakeonVoice, data, reply ); sp<IBinder> b = data.readStrongBinder(); sp<IWakeonVoiceClient> c = interface_cast<IWakeonVoiceClient>( b ); reply->writeInt32( this->fnRegisterClient( c ) ); return OK; } break; default: return -1; } } class BpWakeonVoice: public BpInterface<IWakeonVoice> { public: BpWakeonVoice( const sp<IBinder> &impl ) :BpInterface<IWakeonVoice>( impl ) { } virtual int fnStartListen() { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); remote()->transact( START_LISTEN, data, &reply ); return reply.readInt32(); } virtual int fnStopListen() { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); remote()->transact( STOP_LISTEN, data, &reply ); return reply.readInt32(); } virtual int fnStartEnroll() { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); remote()->transact( START_ENROLL, data, &reply ); return reply.readInt32(); } virtual int fnEnableDebug( int i ) { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); data.writeInt32( i ); remote()->transact( ENABLE_DEBUG, data, &reply ); return reply.readInt32(); } virtual int fnSetEnrollTimes( int t ) { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); data.writeInt32( t ); remote()->transact( SET_ENROLLTIMES, data, &reply ); return reply.readInt32(); } virtual int fnSetSecurityLevel( int s ) { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); data.writeInt32( s ); remote()->transact( SET_SECURITYLEVEL, data, &reply ); return reply.readInt32(); } virtual int fnRegisterClient( sp<IWakeonVoiceClient> &c ) { Parcel data, reply; data.writeInterfaceToken( IWakeonVoice::getInterfaceDescriptor() ); data.writeStrongBinder( c->asBinder() ); remote()->transact( REGISTER_LISTENER, data, &reply ); return reply.readInt32(); } }; IMPLEMENT_META_INTERFACE( WakeonVoice, "IWakeonVoice" ); };
22.757576
71
0.666312
yao-matrix
37c41435c9fde829b786c9147ea769d3f3c9bed5
14,360
cpp
C++
contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_two_scale_high_scale_constraint.cpp
sebhoof/gambit_1.5
f9a3f788e3331067c555ae1a030420e903c6fdcd
[ "Unlicense" ]
2
2020-09-08T20:05:27.000Z
2021-04-26T07:57:56.000Z
contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_two_scale_high_scale_constraint.cpp
sebhoof/gambit_1.5
f9a3f788e3331067c555ae1a030420e903c6fdcd
[ "Unlicense" ]
9
2020-10-19T09:56:17.000Z
2021-05-28T06:12:03.000Z
contrib/MassSpectra/flexiblesusy/models/MSSMEFTHiggs_mAmu/MSSMEFTHiggs_mAmu_two_scale_high_scale_constraint.cpp
patscott/gambit_1.4
a50537419918089effc207e8b206489a5cfd2258
[ "Unlicense" ]
5
2020-09-08T02:23:34.000Z
2021-03-23T08:48:04.000Z
// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // FlexibleSUSY is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FlexibleSUSY. If not, see // <http://www.gnu.org/licenses/>. // ==================================================================== // File generated at Thu 10 May 2018 14:40:34 #include "MSSMEFTHiggs_mAmu_two_scale_high_scale_constraint.hpp" #include "MSSMEFTHiggs_mAmu_two_scale_model.hpp" #include "MSSMEFTHiggs_mAmu_info.hpp" #include "wrappers.hpp" #include "logger.hpp" #include "ew_input.hpp" #include "gsl_utils.hpp" #include "minimizer.hpp" #include "raii.hpp" #include "root_finder.hpp" #include "threshold_loop_functions.hpp" #include "numerics2.hpp" #include <cmath> #include <cerrno> #include <cstring> namespace flexiblesusy { #define DERIVEDPARAMETER(p) model->p() #define EXTRAPARAMETER(p) model->get_##p() #define INPUTPARAMETER(p) model->get_input().p #define MODELPARAMETER(p) model->get_##p() #define PHASE(p) model->get_##p() #define BETAPARAMETER(p) beta_functions.get_##p() #define BETAPARAMETER1(l,p) beta_functions_##l##L.get_##p() #define BETA(p) beta_##p #define BETA1(l,p) beta_##l##L_##p #define LowEnergyConstant(p) Electroweak_constants::p #define MZPole Electroweak_constants::MZ #define STANDARDDEVIATION(p) Electroweak_constants::Error_##p #define Pole(p) model->get_physical().p #define SCALE model->get_scale() #define THRESHOLD static_cast<int>(model->get_thresholds()) #define MODEL model #define MODELCLASSNAME MSSMEFTHiggs_mAmu<Two_scale> MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::MSSMEFTHiggs_mAmu_high_scale_constraint( MSSMEFTHiggs_mAmu<Two_scale>* model_) : model(model_) { initialize(); } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::apply() { check_model_ptr(); update_scale(); check_non_perturbative(); } bool MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::check_non_perturbative() { bool problem = false; const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto g3 = MODELPARAMETER(g3); const auto Yd = MODELPARAMETER(Yd); const auto Ye = MODELPARAMETER(Ye); const auto Yu = MODELPARAMETER(Yu); if (MaxAbsValue(g1) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g1, MaxAbsValue(g1), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g1); } if (MaxAbsValue(g2) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g2, MaxAbsValue(g2), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g2); } if (MaxAbsValue(g3) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g3, MaxAbsValue(g3), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::g3); } if (MaxAbsValue(Yd(0,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_0, MaxAbsValue(Yd(0,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_0); } if (MaxAbsValue(Yd(0,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_1, MaxAbsValue(Yd(0,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_1); } if (MaxAbsValue(Yd(0,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_2, MaxAbsValue(Yd(0,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd0_2); } if (MaxAbsValue(Yd(1,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_0, MaxAbsValue(Yd(1,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_0); } if (MaxAbsValue(Yd(1,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_1, MaxAbsValue(Yd(1,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_1); } if (MaxAbsValue(Yd(1,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_2, MaxAbsValue(Yd(1,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd1_2); } if (MaxAbsValue(Yd(2,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_0, MaxAbsValue(Yd(2,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_0); } if (MaxAbsValue(Yd(2,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_1, MaxAbsValue(Yd(2,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_1); } if (MaxAbsValue(Yd(2,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_2, MaxAbsValue(Yd(2,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yd2_2); } if (MaxAbsValue(Ye(0,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_0, MaxAbsValue(Ye(0,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_0); } if (MaxAbsValue(Ye(0,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_1, MaxAbsValue(Ye(0,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_1); } if (MaxAbsValue(Ye(0,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_2, MaxAbsValue(Ye(0,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye0_2); } if (MaxAbsValue(Ye(1,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_0, MaxAbsValue(Ye(1,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_0); } if (MaxAbsValue(Ye(1,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_1, MaxAbsValue(Ye(1,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_1); } if (MaxAbsValue(Ye(1,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_2, MaxAbsValue(Ye(1,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye1_2); } if (MaxAbsValue(Ye(2,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_0, MaxAbsValue(Ye(2,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_0); } if (MaxAbsValue(Ye(2,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_1, MaxAbsValue(Ye(2,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_1); } if (MaxAbsValue(Ye(2,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_2, MaxAbsValue(Ye(2,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Ye2_2); } if (MaxAbsValue(Yu(0,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_0, MaxAbsValue(Yu(0,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_0); } if (MaxAbsValue(Yu(0,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_1, MaxAbsValue(Yu(0,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_1); } if (MaxAbsValue(Yu(0,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_2, MaxAbsValue(Yu(0,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu0_2); } if (MaxAbsValue(Yu(1,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_0, MaxAbsValue(Yu(1,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_0); } if (MaxAbsValue(Yu(1,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_1, MaxAbsValue(Yu(1,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_1); } if (MaxAbsValue(Yu(1,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_2, MaxAbsValue(Yu(1,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu1_2); } if (MaxAbsValue(Yu(2,0)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_0, MaxAbsValue(Yu(2,0)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_0); } if (MaxAbsValue(Yu(2,1)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_1, MaxAbsValue(Yu(2,1)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_1); } if (MaxAbsValue(Yu(2,2)) > 3.5449077018110318) { problem = true; model->get_problems().flag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_2, MaxAbsValue(Yu(2,2)), model->get_scale(), 3.5449077018110318); } else { model->get_problems().unflag_non_perturbative_parameter(MSSMEFTHiggs_mAmu_info::Yu2_2); } return problem; } double MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::get_scale() const { return scale; } double MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::get_initial_scale_guess() const { return initial_scale_guess; } const MSSMEFTHiggs_mAmu_input_parameters& MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::get_input_parameters() const { return model->get_input(); } MSSMEFTHiggs_mAmu<Two_scale>* MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::get_model() const { return model; } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::set_model(Model* model_) { model = cast_model<MSSMEFTHiggs_mAmu<Two_scale>*>(model_); } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::set_scale(double s) { scale = s; } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::clear() { scale = 0.; initial_scale_guess = 0.; model = nullptr; } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::initialize() { check_model_ptr(); initial_scale_guess = 2.e16; scale = initial_scale_guess; } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::update_scale() { check_model_ptr(); scale = 20000000000000000; } void MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>::check_model_ptr() const { if (!model) throw SetupError("MSSMEFTHiggs_mAmu_high_scale_constraint<Two_scale>: " "model pointer is zero!"); } } // namespace flexiblesusy
39.778393
153
0.730641
sebhoof
37c825d359ca65f19879f852aa75cb8aea511cda
1,625
cpp
C++
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
5
2018-02-10T12:33:53.000Z
2021-03-28T09:27:05.000Z
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
null
null
null
d02/ex00/Fixed.class.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
6
2017-11-25T17:34:43.000Z
2020-12-20T12:00:04.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.class.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdarriga <mdarriga@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/17 12:26:20 by mdarriga #+# #+# */ /* Updated: 2015/06/17 13:55:56 by mdarriga ### ########.fr */ /* */ /* ************************************************************************** */ #include "Fixed.class.hpp" int const Fixed::_nBit = 8; Fixed::Fixed(void) { this->_rawBits = 0; std::cout << "Default Constructor called" << std::endl; return ; } Fixed::Fixed(Fixed const &src) { *this = src; std::cout << "Copy constructor called" << std::endl; return ; } Fixed::~Fixed() { std::cout << "Destructor called" << std::endl; return ; } int Fixed::getRawBits(void) const { std::cout << "getRawBits member function called" << std::endl; return this->_rawBits; } void Fixed::setRawBits(int const raw) { this->_rawBits = raw; } Fixed &Fixed::operator=(Fixed const &rhs) { std::cout << "Assignation operator called" << std::endl; if (this != &rhs) this->_rawBits = rhs.getRawBits(); return *this; }
33.163265
80
0.357538
ncoden
56cb13f92dbc1d68a78f29a4143a361e3ffd8184
10,202
cpp
C++
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Map.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
#include "Map.h" #include <Game.h> #include <Common\ResourceMgr.h> #include <Common\Random.h> #include "PlayScene.h" #include "Objects\Entities\Player.h" #include "Rooms\Room.h" #include "Rooms\BossRoom.h" #include "Rooms\FinalBossRoom.h" #include "Rooms\TreasureRoom.h" #include "Rooms\ZombieRoom.h" #include "Rooms\ShooterRoom.h" #include <SFML\Graphics.hpp> #include <conio.h> #include <stdarg.h> //#define MAP_GEN_DEBUG Map::Map(Player *player) : m_pPlayer(player) { m_pCurrentRoom = nullptr; m_pRoomShape = std::make_shared<sf::RectangleShape>(sf::Vector2f(15.f, 7.5f)); m_pRoomShape->setFillColor(sf::Color::Black); GenerateMap(); /*for (auto room : m_rooms) { if (room) { if (room->GetRoomType() == Room::FINAL_BOSS) LoadRoom(room.get()); } }*/ m_isFinalBossOpen = false; Map::LoadRoom(m_rooms[0].get()); } Map::~Map() { } void Map::GenerateMap(int seed) { Random random; if (seed != -1) random = Random(seed); int nAttempts = 0; while (true) { nAttempts++; m_mapRoom.clear(); m_rooms.clear(); m_nBossRooms = 3; m_nFinalBossRooms = 1; m_nTreasureRooms = 3; m_nEmptyRooms = 4; m_nZombieRooms = 5; m_nShooterRooms = 4; m_nRoomsToCreate = m_nRooms = GetNumberOfAvailableRooms(); sf::Vector2i pos; printf("Generating map... Rooms: %d\n", m_nRooms); Generate(Directions::NONE, random, pos, 0); //printf("%d %d\n", m_rooms.size(), m_nRoomsToCreate); if (m_rooms.size() == m_nRoomsToCreate) break; } // set desc for portals for (auto& room : m_rooms) { if (room) { auto pos = room->GetPos(); for (int num = 0; num < 4; ++num) { auto numDir = NumToDir(num); auto numPos = MoveInDir(pos, numDir); if (m_mapRoom.find(std::make_pair(numPos.x, numPos.y)) != m_mapRoom.end()) { room->SetPortalDest(numDir, m_mapRoom[std::make_pair(numPos.x, numPos.y)]); } else { room->CreateMeteor(numDir); } } room->ClosePortals(false); switch (room->GetRoomType()) { case Room::EMPTY: case Room::TREASURE: room->OpenPortals(false); } } } printf("Done in %d attempts!\n", nAttempts); } sf::Vector2i Map::MoveInDir(const sf::Vector2i &pos, Directions::Direction dir) { sf::Vector2i newPos = pos; switch (dir) { case Directions::NW: newPos += sf::Vector2i(-1, -1); break; case Directions::NE: newPos += sf::Vector2i(1, -1); break; case Directions::SE: newPos += sf::Vector2i(1, 1); break; case Directions::SW: newPos += sf::Vector2i(-1, 1); break; } return newPos; } Directions::Direction Map::NumToDir(int num) { switch (num) { case 0: return Directions::NW; case 1: return Directions::NE; case 2: return Directions::SE; case 3: return Directions::SW; } return Directions::NONE; } bool Map::IsNearToSpecialRoom(const sf::Vector2i &oldPos, const sf::Vector2i &newPos) { bool isSpecialRoomNear = false; for (int i = 0; i < 4; ++i) { auto _newPos = MoveInDir(newPos, NumToDir(i)); if (_newPos == oldPos) continue; if (m_mapRoom.find(std::make_pair(_newPos.x, _newPos.y)) != m_mapRoom.end()) { if (m_mapRoom[std::make_pair(_newPos.x, _newPos.y)]->IsSpecialRoom()) isSpecialRoomNear = true; } } return isSpecialRoomNear; } void Map::GenerateTree(Random &random, const sf::Vector2i &pos, int deepLevel, int min, int max) { int nNewRooms = random.Get<int>(std::min(min, m_nRooms), std::min(max, m_nRooms)); m_nRooms -= nNewRooms; PrintTab(deepLevel, "Generating tree: %d", nNewRooms); bool reserved[4] = { false }; for (int i = 0; i < nNewRooms; ++i) { PrintTab(deepLevel, "New: %d", i); sf::Vector2i newRoomPos; Directions::Direction newRoomDir; int nAttempts = 20; while (true) { if (nAttempts <= 0) break; nAttempts--; int num = random.Get<int>(0, 3); if (reserved[num]) continue; auto drawn = NumToDir(num); auto newPos = MoveInDir(pos, drawn); if (m_mapRoom.find(std::make_pair(newPos.x, newPos.y)) == m_mapRoom.end()) { if (IsNearToSpecialRoom(pos, newRoomPos)) continue; newRoomDir = drawn; newRoomPos = newPos; reserved[num] = true; break; } } if (nAttempts <= 0) { m_nRooms++; PrintTab(deepLevel, "Cannot %d", i); continue; } Generate(newRoomDir, random, newRoomPos, ++deepLevel, true); } } bool Map::Generate(Directions::Direction cameFrom, Random &random, const sf::Vector2i &pos, int deepLevel, bool reserved) { if (!reserved) { if (m_nRooms <= 0) return false; } PrintTab(deepLevel, "Creating room... (%d)", m_nRooms); Room *room = nullptr; if (GetNumberOfAvailableRooms() == 0) return false; while (true) { int roomType = 1; if (pos != sf::Vector2i(0, 0)) roomType = random.Get<int>(1, 6); bool created = false; switch (roomType) { case 1: // Empty Room if (m_nEmptyRooms > 0) { room = new Room(this, pos); m_nEmptyRooms--; created = true; } break; case 2: // Treasure Room if (m_nTreasureRooms > 0 && m_nRooms < m_nRoomsToCreate / 2) { room = new TreasureRoom(this, pos); m_nTreasureRooms--; created = true; } break; case 3: // Zombie Room if (m_nZombieRooms > 0) { room = new ZombieRoom(this, pos); m_nZombieRooms--; created = true; } break; case 4: // Boss Room { if (m_nBossRooms > 0 && m_nRooms < m_nRoomsToCreate / 3) { room = new BossRoom(this, pos); m_nBossRooms--; created = true; } break; } case 5: // Shooter Room { if (m_nShooterRooms > 0) { room = new ShooterRoom(this, pos); m_nShooterRooms--; created = true; } } break; case 6: // Final Boss { if (m_nFinalBossRooms > 0) { room = new FinalBossRoom(this, pos); m_nFinalBossRooms--; created = true; } } break; } if (created) break; } PrintTab(deepLevel, "Created: %d on (%d, %d)", room->GetRoomType(), pos.x, pos.y); m_rooms.push_back(std::shared_ptr<Room>(room)); m_mapRoom[std::make_pair(pos.x, pos.y)] = room; if (room->IsSpecialRoom()) { PrintTab(deepLevel, "Special room: Return without childs"); return true; } int generateNewTree = 2; if (cameFrom != Directions::NONE) generateNewTree = random.Get<int>(1, 4); if (generateNewTree == 2) { int min = 2; if (cameFrom == Directions::NONE) { min = 3; } GenerateTree(random, pos, ++deepLevel, min); } else { sf::Vector2i newRoomPos = MoveInDir(pos, cameFrom); PrintTab(deepLevel, "Next line"); deepLevel++; if (IsNearToSpecialRoom(pos, newRoomPos)) GenerateTree(random, pos, deepLevel); else { m_nRooms--; if (Generate(cameFrom, random, newRoomPos, deepLevel)) { GenerateTree(random, pos, deepLevel); } } } return false; } void Map::PrintTab(int deepLevel, char * str, ...) { #ifdef MAP_GEN_DEBUG for (int i = 0; i <= deepLevel; ++i) { printf(" "); } char buffer[256]; va_list args; va_start(args, str); vsnprintf(buffer, 256, str, args); va_end(args); char buffer2[512] = { 0 }; sprintf(buffer2, "[%d] %s (R: %d, T: %d B: %d Z: %d E: %d", deepLevel, buffer, m_nRooms, m_nTreasureRooms, m_nBossRooms, m_nZombieRooms, m_nEmptyRooms); puts(buffer2); #endif } int Map::GetNumberOfAvailableRooms() { return m_nEmptyRooms + m_nTreasureRooms + m_nZombieRooms + m_nShooterRooms + m_nBossRooms + m_nFinalBossRooms; } void Map::LoadRoom(Room *room) { if (room == nullptr) return; if (m_pCurrentRoom) m_pCurrentRoom->RemoveObject(m_pPlayer); m_pCurrentRoom = room; if (m_pCurrentRoom->GetVisibleStatus() != Room::SHOWN) PlayScene::Get()->AddScore(1000); m_pCurrentRoom->AddObject(m_pPlayer, false); m_pCurrentRoom->SetVisibleStatus(Room::SHOWN); auto setVisibity = [this] (Directions::Direction dir) { auto room = m_pCurrentRoom->GetPortalDest(dir); if (room && room->GetVisibleStatus() == Room::HIDDEN) room->SetVisibleStatus(Room::HALF); }; setVisibity(Directions::NE); setVisibity(Directions::NW); setVisibity(Directions::SE); setVisibity(Directions::SW); int notDiscoveredBosses = 0; for (auto room : m_rooms) { if (room) { if (room->GetRoomType() == Room::BOSS && room->GetVisibleStatus() != Room::SHOWN) notDiscoveredBosses++; } } if (notDiscoveredBosses == 0) m_isFinalBossOpen = true; } void Map::RenderHud(sf::RenderWindow *window) { if (m_pCurrentRoom) m_pCurrentRoom->RenderHud(window); sf::Vector2f centerPos; centerPos.x = Game::Get()->GetWindowSize().x / 2.f; centerPos.y = (Game::Get()->GetWindowSize().y - Game::Get()->GetPlayAreaSize().y) / 2.f; float offset = 1.f; auto currentPos = m_pCurrentRoom->GetPos(); for (auto& room : m_rooms) { if (room) { auto pos = room->GetPos() - currentPos; sf::Vector2f newPos; newPos.x = pos.x * (offset + m_pRoomShape->getSize().x) + 500.f; newPos.y = pos.y * (offset + m_pRoomShape->getSize().y); if ((centerPos + newPos).y > 130) continue; if (room.get() == m_pCurrentRoom) m_pRoomShape->setFillColor(sf::Color::White); else { if (room->GetVisibleStatus() == Room::SHOWN) m_pRoomShape->setFillColor(room->GetRoomColor()); else if (room->GetVisibleStatus() == Room::HALF) m_pRoomShape->setFillColor(sf::Color(255, 255, 255, 50)); else m_pRoomShape->setFillColor(sf::Color::Transparent); } m_pRoomShape->setPosition(centerPos + newPos); window->draw(*m_pRoomShape); } } } void Map::RenderGame(sf::RenderWindow *window) { if (m_pCurrentRoom) m_pCurrentRoom->RenderGame(window); } void Map::Pulse(float deltaTime) { if (m_pCurrentRoom) m_pCurrentRoom->Pulse(deltaTime); } void Map::Event(sf::Event *e) { if (m_pCurrentRoom) m_pCurrentRoom->Event(e); #ifdef _DEBUG if (e->type == sf::Event::KeyPressed) { switch (e->key.code) { case sf::Keyboard::G: { m_pCurrentRoom = nullptr; GenerateMap(); Map::LoadRoom(m_rooms[0].get()); } break; case sf::Keyboard::X: { for (auto room : m_rooms) { if (room) { room->SetVisibleStatus(Room::SHOWN); } } } break; } } #endif }
18.684982
153
0.63517
Harry09
56cf1dd19f125028f80f65ce8b1c857f59aca332
1,083
cpp
C++
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
src/core/Environment.cpp
phoenixwxy/markdown
dfafa68524a639cb492b464146e83c256807a356
[ "MIT" ]
null
null
null
// // Created by mi on 2021/4/8. // #include "Environment.h" Environment *Environment::GetInstance() { static Environment s_Environment; if (EnvStatus::Initialize == s_Environment.m_CurrentStatus) { s_Environment.InitCaps(); } return &s_Environment; } Environment::Environment() : m_Version("0.0.0") , m_CurrentStatus(EnvStatus::Invalid) { Initialize(); } Environment::~Environment() { m_CurrentStatus = EnvStatus::Invalid; } void Environment::Initialize() { m_CurrentStatus = EnvStatus::Initialize; } void Environment::InitCaps() { m_CurrentStatus = EnvStatus::Running; m_CurrentStatus = EnvStatus::Done; } std::string Environment::GetVersion() { if (!m_Version.empty()) { m_Version.clear(); } m_Version.append(std::to_string(MAJOR_VERSION)); m_Version.append("."); m_Version.append(std::to_string(MINOR_VERSION)); m_Version.append("."); m_Version.append(std::to_string(PATCH_VERSION)); if (m_Version.empty()) { m_Version.assign("0.0.0"); } return m_Version; }
19.690909
65
0.662973
phoenixwxy
56d096a390d722384d54795ab77357c4e7250d7a
1,174
cpp
C++
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCpp/Net/Services/Microsoft/Cognitive/CVTagImageResult.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#include "CVTagImageResult.h" #include "../../../../Bundle.h" #include "../../../../AnyArray.h" namespace EasyCpp { namespace Net { namespace Services { namespace Microsoft { namespace Cognitive { CVTagImageResult::CVTagImageResult() { } CVTagImageResult::~CVTagImageResult() { } const std::vector<CVImageTag>& CVTagImageResult::getTags() const { return _tags; } const CVImageMetadata & CVTagImageResult::getMetadata() const { return _metadata; } const std::string & CVTagImageResult::getRequestId() const { return _request_id; } AnyValue CVTagImageResult::toAnyValue() const { return Bundle({ { "tags", toAnyArraySerialize(_tags) }, { "requestId", _request_id }, { "metadata", _metadata.toAnyValue() } }); } void CVTagImageResult::fromAnyValue(const AnyValue & state) { Bundle b = state.as<Bundle>(); _tags = fromAnyArray<CVImageTag>(b.get("tags")); _request_id = b.get<std::string>("requestId"); _metadata = b.get<CVImageMetadata>("metadata"); } } } } } }
20.241379
69
0.59029
Thalhammer
56d300c32f1ad29c49c26264cdb88ead90ce3ea8
5,229
cpp
C++
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/src/EReg.cpp
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
// Generated by Haxe 4.2.0-rc.1+cb30bd580 #include <hxcpp.h> #ifndef INCLUDED_EReg #include <EReg.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_359fe5fd855fee60_28_new,"EReg","new",0x8b859e81,"EReg.new","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",28,0x5a2fdacd) HX_LOCAL_STACK_FRAME(_hx_pos_359fe5fd855fee60_36_match,"EReg","match",0x18fda1a6,"EReg.match","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",36,0x5a2fdacd) HX_LOCAL_STACK_FRAME(_hx_pos_359fe5fd855fee60_45_matched,"EReg","matched",0x8ce62f85,"EReg.matched","/usr/local/lib/haxe/std/cpp/_std/EReg.hx",45,0x5a2fdacd) void EReg_obj::__construct(::String r,::String opt){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_28_new) HXLINE( 29) ::Array< ::String > a = opt.split(HX_("g",67,00,00,00)); HXLINE( 30) this->global = (a->length > 1); HXLINE( 31) if (this->global) { HXLINE( 32) opt = a->join(HX_("",00,00,00,00)); } HXLINE( 33) this->r = _hx_regexp_new_options(r,opt); } Dynamic EReg_obj::__CreateEmpty() { return new EReg_obj; } void *EReg_obj::_hx_vtable = 0; Dynamic EReg_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< EReg_obj > _hx_result = new EReg_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool EReg_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x022d4033; } bool EReg_obj::match(::String s){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_36_match) HXLINE( 37) bool p = _hx_regexp_match(this->r,s,0,s.length); HXLINE( 38) if (p) { HXLINE( 39) this->last = s; } else { HXLINE( 41) this->last = null(); } HXLINE( 42) return p; } HX_DEFINE_DYNAMIC_FUNC1(EReg_obj,match,return ) ::String EReg_obj::matched(int n){ HX_STACKFRAME(&_hx_pos_359fe5fd855fee60_45_matched) HXLINE( 46) ::String m = _hx_regexp_matched(this->r,n); HXLINE( 47) return m; } HX_DEFINE_DYNAMIC_FUNC1(EReg_obj,matched,return ) EReg_obj::EReg_obj() { } void EReg_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(EReg); HX_MARK_MEMBER_NAME(r,"r"); HX_MARK_MEMBER_NAME(last,"last"); HX_MARK_MEMBER_NAME(global,"global"); HX_MARK_END_CLASS(); } void EReg_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(r,"r"); HX_VISIT_MEMBER_NAME(last,"last"); HX_VISIT_MEMBER_NAME(global,"global"); } ::hx::Val EReg_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"r") ) { return ::hx::Val( r ); } break; case 4: if (HX_FIELD_EQ(inName,"last") ) { return ::hx::Val( last ); } break; case 5: if (HX_FIELD_EQ(inName,"match") ) { return ::hx::Val( match_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"global") ) { return ::hx::Val( global ); } break; case 7: if (HX_FIELD_EQ(inName,"matched") ) { return ::hx::Val( matched_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val EReg_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"r") ) { r=inValue.Cast< ::Dynamic >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"last") ) { last=inValue.Cast< ::String >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"global") ) { global=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EReg_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("r",72,00,00,00)); outFields->push(HX_("last",56,0a,ad,47)); outFields->push(HX_("global",63,31,b2,a7)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo EReg_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(EReg_obj,r),HX_("r",72,00,00,00)}, {::hx::fsString,(int)offsetof(EReg_obj,last),HX_("last",56,0a,ad,47)}, {::hx::fsBool,(int)offsetof(EReg_obj,global),HX_("global",63,31,b2,a7)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *EReg_obj_sStaticStorageInfo = 0; #endif static ::String EReg_obj_sMemberFields[] = { HX_("r",72,00,00,00), HX_("last",56,0a,ad,47), HX_("global",63,31,b2,a7), HX_("match",45,49,23,03), HX_("matched",e4,3c,7c,89), ::String(null()) }; ::hx::Class EReg_obj::__mClass; void EReg_obj::__register() { EReg_obj _hx_dummy; EReg_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("EReg",0f,4a,da,2d); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(EReg_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< EReg_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EReg_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EReg_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
30.940828
157
0.689233
TrilateralX
56d3c461411a5626da33eb5d3efb336af0a6735e
331
cpp
C++
src/gtexture.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
51
2017-02-01T14:50:03.000Z
2022-01-14T11:19:51.000Z
src/gtexture.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
null
null
null
src/gtexture.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
9
2018-07-20T07:47:39.000Z
2020-10-31T16:26:08.000Z
#include "gincu/gtexture.h" namespace gincu { GTexture::GTexture() { } GTexture::GTexture(const std::shared_ptr<GTextureData> & data) : data(data) { } GSize GTexture::getSize() const { return this->data->getSize(); } bool GTexture::isValid() const { return (this->data && this->data->isValid()); } } //namespace gincu
11.413793
62
0.670695
wqking
56d99f5671a754fde3e62047fcf4a395f7b0e351
109,845
hpp
C++
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_impl_force.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
#pragma once #include"tree_walk.hpp" namespace ParticleSimulator{ /////////////////////////////////////////////////// // // FUNCTIONS OF WALK+FORCE WITH DOUBLE BUFFERING // /////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Index, List:Index //////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndex(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 wtime_offset = GetWtime(); ret = calcForceMultiWalkIndexImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, flag_keep_list, clear); time_profile_.calc_force += GetWtime() - wtime_offset; return ret; } //////////// Walk+Force, Kernel:Index, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); // send all epj and spj Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; S32 ** id_spj_dummy = NULL; S32 * n_spj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, (const S32**)id_spj_dummy, n_spj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), true); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); interaction_list_.n_sp_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_sp_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_sp_.clearSize(); } //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk+1] static S32 ** n_spj_disp_thread;// [n_thread][n_walk+1] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_ar; static S64 * n_interaction_ep_sp_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_spj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; //static ReallocatableArray<S32> * n_disp_epj_tmp; //static ReallocatableArray<S32> * n_disp_spj_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_spj_ar; id_spj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; n_interaction_ep_sp_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_spj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; //n_disp_epj_tmp = new ReallocatableArray<S32>[n_thread]; //n_disp_spj_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; //for(int wg=0; wg<n_ipg%n_loop_max; wg++){ for(int wg=0; wg<wg_tmp; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } //for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ for(int wg=wg_tmp; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = n_interaction_ep_sp_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); const S32 adr_tree_sp_first = spj_org_.size(); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = n_sp_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; n_spj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_spj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); //n_disp_epj_tmp[ith].clearSize(); //n_disp_spj_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, Tspj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], spj_sorted_, adr_spj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, adr_tree_sp_first, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } for(S32 i=0; i<adr_spj_tmp[ith].size(); i++){ mass_tmp += spj_sorted_[ adr_spj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ //if(Comm::getRank()==0) std::cerr<<"mass_tmp= "<<mass_tmp<<std::endl; //n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; //n_spj_array[iw] = spj_for_force_[ith].size() - n_sp_cum_thread[ith]; //interaction_list_.n_ep_[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; //interaction_list_.n_sp_[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_spj_ar[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; #if 0 if(Comm::getRank()==0){ std::cout<<"Multi:yes, index:yes id_ipg= "<<id_ipg <<" target_box= "<<target_box.vertex_ <<" n_epi= "<<ipg_[id_ipg].n_ptcl_ <<" n_epj= "<<n_epj_ar[iw] <<" n_spj= "<<n_spj_ar[iw] <<" tc_glb_[0].mom_.vertex_out_= "<<tc_glb_[0].mom_.vertex_out_ <<" tc_glb_[0].n_ptcl_= "<<tc_glb_[0].n_ptcl_ <<std::endl; } #endif n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_sp_cum_thread[ith] = adr_spj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_ar[ith] += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope //if(Comm::getRank()==0) std::cerr<<"OK"<<std::endl; //Comm::barrier(); //exit(1); if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = interaction_list_.n_disp_sp_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; interaction_list_.n_sp_[id_ipg] = n_spj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; interaction_list_.n_disp_sp_[id_ipg+1] = interaction_list_.n_disp_sp_[id_ipg] + interaction_list_.n_sp_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); interaction_list_.adr_sp_.resizeNoInitialize( interaction_list_.n_disp_sp_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } S32 adr_sp = interaction_list_.n_disp_sp_[adr_ipg]; const S32 k_sp_h = n_spj_disp_thread[i][j]; const S32 k_sp_e = n_spj_disp_thread[i][j+1]; for(S32 k=k_sp_h; k<k_sp_e; k++, adr_sp++){ interaction_list_.adr_sp_[adr_sp] = adr_spj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); id_spj_ar[iw] = adr_spj_tmp[ith].getPointer(n_sp_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); id_spj_ar[iw] = adr_spj_tmp[ith].getPointer(n_sp_head); } #endif pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_ar[i]; } //std::cerr<<"(A) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Index, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), true); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); } //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; //for(int wg=0; wg<n_ipg%n_loop_max; wg++){ for(int wg=0; wg<wg_tmp; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } //for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ for(int wg=wg_tmp; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; id_epj_ar[iw] = adr_epj_tmp[ith].getPointer(n_ep_head); } #endif pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = 0; n_interaction_ep_ep_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; } //std::cerr<<"(B) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } ////////////////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Ptcl, List:Ptcl ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalk(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 wtime_offset = GetWtime(); ret = calcForceMultiWalkImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, clear); time_profile_.calc_force += GetWtime() - wtime_offset; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Ptcl, Force:Long////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); //const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> walk_grp; static std::vector<S32> walk_grp_disp; walk_grp.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) walk_grp_disp.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 * n_epi_array; static S32 * n_epi_array_prev; static S32 * n_epj_array; static S32 * n_spj_array; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static S32 ** n_spj_disp_thread;// [n_thread][n_walk] static Tepi ** epi_array; // array of pointer *[n_walk] static Tepj ** epj_array; // array of pointer *[n_walk] static Tspj ** spj_array; // array of pointer *[n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_array; static S64 * n_interaction_ep_sp_array; if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epi_array = new S32[n_walk_limit]; n_epi_array_prev = new S32[n_walk_limit]; n_epj_array = new S32[n_walk_limit]; n_spj_array = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; epi_array = new Tepi*[n_walk_limit]; epj_array = new Tepj*[n_walk_limit]; spj_array = new Tspj*[n_walk_limit]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_array = new S64[n_thread]; n_interaction_ep_sp_array = new S64[n_thread]; first = false; } walk_grp_disp[0] = 0; //const S32 wg_tmp = n_ipg > 0 ? n_ipg%n_loop_max : 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ //for(int wg=0; wg<wg_tmp; wg++){ walk_grp[wg] = n_ipg / n_loop_max + 1; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ //for(int wg=wg_tmp; wg<n_loop_max; wg++){ walk_grp[wg] = n_ipg / n_loop_max; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_array[i] = n_interaction_ep_sp_array[i] = 0; } bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = walk_grp[wg]; const S32 walk_grp_head = walk_grp_disp[wg]; for(int i=0; i<n_thread; i++){ n_ep_cum_thread[i] = n_sp_cum_thread[i] = cnt_thread[i] = 0; n_epj_disp_thread[i][0] = 0; n_spj_disp_thread[i][0] = 0; epj_for_force_[i].clearSize(); spj_for_force_[i].clearSize(); } const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_array[iw] = ipg_[id_ipg].n_ptcl_; epi_array[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); makeInteractionList(id_ipg, false); n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; n_spj_array[iw] = spj_for_force_[ith].size() - n_sp_cum_thread[ith]; n_ep_cum_thread[ith] = epj_for_force_[ith].size(); n_sp_cum_thread[ith] = spj_for_force_[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_array[ith] += ((S64)n_epj_array[iw]*(S64)n_epi_array[iw]); n_interaction_ep_sp_array[ith] += ((S64)n_spj_array[iw]*(S64)n_epi_array[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); spj_array[iw] = spj_for_force_[ith].getPointer(n_sp_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve #else //original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); spj_array[iw] = spj_for_force_[ith].getPointer(n_sp_head); } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_array, n_epi_array, (const Tepj**)epj_array, n_epj_array, (const Tspj**)spj_array, n_spj_array); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_array_prev[iw] = n_epi_array[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_array[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_array[i]; } //std::cerr<<"(C) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Ptcl, Force:Short////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool clear){ //std::cerr<<"rank(A)= "<<Comm::getRank()<<std::endl; const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; //const S32 n_ipg_amari = (n_ipg > 0) ? n_ipg%n_walk_limit : 0; n_walk_local_ += n_ipg; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); //const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg_amari==0 ? 0 : 1); static std::vector<S32> walk_grp; static std::vector<S32> walk_grp_disp; walk_grp.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) walk_grp_disp.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 * n_epi_array; static S32 * n_epi_array_prev; static S32 * n_epj_array; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tepi ** epi_array; // array of pointer *[n_walk] static Tepj ** epj_array; // array of pointer *[n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_array; if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epi_array = new S32[n_walk_limit]; n_epi_array_prev = new S32[n_walk_limit]; n_epj_array = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; epi_array = new Tepi*[n_walk_limit]; epj_array = new Tepj*[n_walk_limit]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_array = new S64[n_thread]; first = false; } walk_grp_disp[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ walk_grp[wg] = (n_ipg/n_loop_max) + 1; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ walk_grp[wg] = n_ipg / n_loop_max; walk_grp_disp[wg+1] = walk_grp_disp[wg] + walk_grp[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_array[i] = 0; } bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = walk_grp[wg]; const S32 walk_grp_head = walk_grp_disp[wg]; for(int i=0; i<n_thread; i++){ n_ep_cum_thread[i] = cnt_thread[i] = 0; n_epj_disp_thread[i][0] = 0; epj_for_force_[i].clearSize(); } const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_array[iw] = ipg_[id_ipg].n_ptcl_; epi_array[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); makeInteractionList(id_ipg, false); n_epj_array[iw] = epj_for_force_[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = epj_for_force_[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_array[ith] += (S64)n_epj_array[iw]*(S64)n_epi_array[iw]; iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // retrieve for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; epj_array[iw] = epj_for_force_[ith].getPointer(n_ep_head); } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_array, n_epi_array, (const Tepj**)epj_array, n_epj_array); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_array_prev[iw] = n_epi_array[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; //std::cerr<<"rank(E)= "<<Comm::getRank()<<std::endl; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_array_prev, force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_array[i]; } //std::cerr<<"(D) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; //std::cerr<<"rank(Z)= "<<Comm::getRank()<<std::endl; return ret; } ////////////////////////////////////////////////// //////////// Walk+Force, Kernel:Ptcl, List:Index ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNew(Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ if(tag_max <= 0){ PARTICLE_SIMULATOR_PRINT_ERROR("tag_max is illegal. In currente version, tag_max must be 1"); Abort(-1); } force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } S32 ret = 0; const F64 time_offset = GetWtime(); ret = calcForceMultiWalkIndexNewImpl(typename TSM::force_type(), pfunc_dispatch, pfunc_retrieve, tag_max, n_walk_limit, flag_keep_list, clear); time_profile_.calc_force += GetWtime() - time_offset; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Index Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNewImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); interaction_list_.n_sp_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_sp_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_sp_.clearSize(); } const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static S32 ** n_spj_disp_thread;// [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S32 * n_sp_cum_thread; static S64 * n_interaction_ep_ep_ar; static S64 * n_interaction_ep_sp_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_spj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tspj*> spj_ar; spj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; n_spj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; n_spj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_sp_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; n_interaction_ep_sp_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_spj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = n_interaction_ep_sp_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); const S32 adr_tree_sp_first = spj_org_.size(); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = n_sp_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; n_spj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_spj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, Tspj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], spj_sorted_, adr_spj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, adr_tree_sp_first, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } for(S32 i=0; i<adr_spj_tmp[ith].size(); i++){ mass_tmp += spj_sorted_[ adr_spj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_spj_ar[iw] = adr_spj_tmp[ith].size() - n_sp_cum_thread[ith]; #if 0 if(Comm::getRank()==0){ std::cout<<"Multi:yes, index:no id_ipg= "<<id_ipg <<" target_box= "<<target_box.vertex_ <<" n_epi= "<<ipg_[id_ipg].n_ptcl_ <<" n_epj= "<<n_epj_ar[iw] <<" n_spj= "<<n_spj_ar[iw] <<" tc_glb_[0].mom_.vertex_out_= "<<tc_glb_[0].mom_.vertex_out_ <<" tc_glb_[0].n_ptcl_= "<<tc_glb_[0].n_ptcl_ <<std::endl; } #endif n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_sp_cum_thread[ith] = adr_spj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_spj_disp_thread[ith][cnt_thread[ith]+1] = n_sp_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_ar[ith] += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = interaction_list_.n_disp_sp_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; interaction_list_.n_sp_[id_ipg] = n_spj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; interaction_list_.n_disp_sp_[id_ipg+1] = interaction_list_.n_disp_sp_[id_ipg] + interaction_list_.n_sp_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); interaction_list_.adr_sp_.resizeNoInitialize( interaction_list_.n_disp_sp_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } S32 adr_sp = interaction_list_.n_disp_sp_[adr_ipg]; const S32 k_sp_h = n_spj_disp_thread[i][j]; const S32 k_sp_e = n_spj_disp_thread[i][j+1]; for(S32 k=k_sp_h; k<k_sp_e; k++, adr_sp++){ interaction_list_.adr_sp_[adr_sp] = adr_spj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #if 1 epj_for_force_[0].clearSize(); spj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } S32 * id_spj = adr_spj_tmp[ith].getPointer(n_sp_head); for(S32 jp=0; jp<n_spj_ar[iw]; jp++){ spj_for_force_[0].push_back( spj_sorted_[id_spj[jp]] ); } } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve epj_for_force_[0].clearSize(); spj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 n_sp_head = n_spj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } S32 * id_spj = adr_spj_tmp[ith].getPointer(n_sp_head); for(S32 jp=0; jp<n_spj_ar[iw]; jp++){ spj_for_force_[0].push_back( spj_sorted_[id_spj[jp]] ); } } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = n_interaction_ep_sp_ = 0; n_interaction_ep_ep_local_ = n_interaction_ep_sp_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; n_interaction_ep_sp_local_ += n_interaction_ep_sp_ar[i]; } //std::cerr<<"(E) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Walk+Force, Kernel:Ptcl, List:Index Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> S32 TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceMultiWalkIndexNewImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 tag_max, const S32 n_walk_limit, const bool flag_keep_list, const bool clear){ const F64 offset_core = GetWtime(); static bool first = true; S32 ret = 0; S32 tag = 0; const S32 n_thread = Comm::getNumberOfThread(); //force_sorted_.resizeNoInitialize(n_loc_tot_); //force_org_.resizeNoInitialize(n_loc_tot_); const S32 n_ipg = ipg_.size(); if(n_ipg <= 0) return 0; n_walk_local_ += n_ipg; if(flag_keep_list){ interaction_list_.n_ep_.resizeNoInitialize(n_ipg); interaction_list_.n_disp_ep_.resizeNoInitialize(n_ipg+1); interaction_list_.adr_ep_.clearSize(); } const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (walk_grp[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); static S32 * iw2ith; static S32 * iw2cnt; static S32 ** n_epj_disp_thread; // [n_thread][n_walk] static Tforce ** force_array; // array of pointer *[n_walk] static Tforce ** force_prev_array; // array of pointer *[n_walk] static S32 * cnt_thread; static S32 * n_ep_cum_thread; static S64 * n_interaction_ep_ep_ar; static ReallocatableArray<S32> * adr_epj_tmp; static ReallocatableArray<S32> * adr_ipg_tmp; static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epi_ar_prev; n_epi_ar_prev.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepi*> epi_ar; // array of pointer *[n_walk] epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); if(first){ iw2ith = new S32[n_walk_limit]; iw2cnt = new S32[n_walk_limit]; n_epj_disp_thread = new S32*[n_thread]; force_array = new Tforce*[n_walk_limit]; force_prev_array = new Tforce*[n_walk_limit]; for(int i=0; i<n_thread; i++){ n_epj_disp_thread[i] = new S32[n_walk_limit+1]; } cnt_thread = new S32[n_thread]; n_ep_cum_thread = new S32[n_thread]; n_interaction_ep_ep_ar = new S64[n_thread]; adr_epj_tmp = new ReallocatableArray<S32>[n_thread]; adr_ipg_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_ar[i] = 0; } const F64 r_crit_sq = (length_ * length_) / (theta_ * theta_); bool first_loop = true; S32 n_walk_prev = 0; if(n_ipg > 0){ for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 walk_grp_head = n_disp_walk_ar[wg]; const F64 offset_calc_force__core__walk_tree = GetWtime(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); n_ep_cum_thread[ith] = cnt_thread[ith] = 0; n_epj_disp_thread[ith][0] = 0; adr_epj_tmp[ith].clearSize(); adr_ipg_tmp[ith].clearSize(); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; adr_ipg_tmp[ith].push_back(id_ipg); const S32 first_adr_ip = ipg_[id_ipg].adr_ptcl_; const S32 ith = Comm::getThreadNum(); n_epi_ar[iw] = ipg_[id_ipg].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_array[iw] = force_sorted_.getPointer(first_adr_ip); TargetBox<TSM> target_box; GetTargetBox<TSM>(ipg_[id_ipg], target_box); S32 adr_tc = 0; MakeListUsingTreeRecursiveTop <TSM, TreeCell<Tmomglb>, TreeParticle, Tepj, WALK_MODE_NORMAL, TagChopLeafTrue> (tc_glb_, adr_tc, tp_glb_, epj_sorted_, adr_epj_tmp[ith], target_box, r_crit_sq, n_leaf_limit_, F64vec(0.0)); /* F64 mass_tmp = 0.0; for(S32 i=0; i<adr_epj_tmp[ith].size(); i++){ mass_tmp += epj_sorted_[ adr_epj_tmp[ith][i] ].mass; } assert(fmod(mass_tmp, 1.0)==0.0); */ n_epj_ar[iw] = adr_epj_tmp[ith].size() - n_ep_cum_thread[ith]; n_ep_cum_thread[ith] = adr_epj_tmp[ith].size(); n_epj_disp_thread[ith][cnt_thread[ith]+1] = n_ep_cum_thread[ith]; n_interaction_ep_ep_ar[ith] += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); iw2ith[iw] = ith; iw2cnt[iw] = cnt_thread[ith]; cnt_thread[ith]++; } // end of OMP for } // end of OMP parallel scope if(flag_keep_list){ interaction_list_.n_disp_ep_[0] = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_ep_[id_ipg] = n_epj_ar[iw]; } for(int iw=0; iw<n_walk; iw++){ const S32 id_ipg = walk_grp_head + iw; interaction_list_.n_disp_ep_[id_ipg+1] = interaction_list_.n_disp_ep_[id_ipg] + interaction_list_.n_ep_[id_ipg]; } interaction_list_.adr_ep_.resizeNoInitialize( interaction_list_.n_disp_ep_[walk_grp_head+n_walk] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<adr_ipg_tmp[i].size(); j++){ const S32 adr_ipg = adr_ipg_tmp[i][j]; S32 adr_ep = interaction_list_.n_disp_ep_[adr_ipg]; const S32 k_ep_h = n_epj_disp_thread[i][j]; const S32 k_ep_e = n_epj_disp_thread[i][j+1]; for(S32 k=k_ep_h; k<k_ep_e; k++, adr_ep++){ interaction_list_.adr_ep_[adr_ep] = adr_epj_tmp[i][k]; } } } } time_profile_.calc_force__core__walk_tree += GetWtime() - offset_calc_force__core__walk_tree; #if 1 epj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } } S64 n_epj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve #else // original if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // retrieve epj_for_force_[0].clearSize(); for(S32 iw=0; iw<n_walk; iw++){ S32 ith = iw2ith[iw]; S32 cnt = iw2cnt[iw]; S32 n_ep_head = n_epj_disp_thread[ith][cnt]; S32 * id_epj = adr_epj_tmp[ith].getPointer(n_ep_head); for(S32 jp=0; jp<n_epj_ar[iw]; jp++){ epj_for_force_[0].push_back( epj_sorted_[id_epj[jp]] ); } } S64 n_epj_cnt = 0; for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } #endif ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); first_loop = false; for(int iw=0; iw<n_walk; iw++){ n_epi_ar_prev[iw] = n_epi_ar[iw]; force_prev_array[iw] = force_array[iw]; } n_walk_prev = n_walk; } // end of walk group loop ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar_prev.getPointer(), force_prev_array); } // if(n_ipg > 0) else{ ni_ave_ = nj_ave_ = n_interaction_ep_ep_ = 0; n_interaction_ep_ep_local_ = 0; } for(int i=0; i<n_thread; i++){ n_interaction_ep_ep_local_ += n_interaction_ep_ep_ar[i]; } //std::cerr<<"(F) n_interaction_ep_ep_local_= "<<n_interaction_ep_ep_local_<<std::endl; time_profile_.calc_force__core += GetWtime() - offset_core; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; return ret; } //////////// Kernel:Ptcl, List:Index ////////////// ////////////////////////////////////////////////// /////////////////////////////////////////////////// // // FUNCTIONS OF FORCE WITHOUT WALK // (MUST BE USED AFTER WALK) // /////////////////////////////////////////////////// //////////////////////////////////////////////////// //////////// Force Only, Kernel:Index, List:Index ////////////// //////////// Force Only, Kernel:Index, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_spj_ar; id_spj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; S32 ** id_spj_dummy = NULL; S32 * n_spj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, (const S32**)id_spj_dummy, n_spj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), true); const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); n_walk_prev = n_walk; first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else //original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), (const S32**)id_spj_ar.getPointer(), n_spj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), spj_sorted_.getPointer(), spj_sorted_.size(), false); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } //////////// Force Only, Kernel:Index, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32*> id_epj_ar; id_epj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } Tepi ** epi_dummy = NULL; S32 * n_epi_dummy = NULL; S32 ** id_epj_dummy = NULL; S32 * n_epj_dummy = NULL; pfunc_dispatch(0, 0, (const Tepi**)epi_dummy, n_epi_dummy, (const S32**)id_epj_dummy, n_epj_dummy, epj_sorted_.getPointer(), epj_sorted_.size(), true); const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); n_walk_prev = n_walk; first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); //S32 n_ep_head = interaction_list_.n_disp_ep_[id_walk]; n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); } pfunc_dispatch(0, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const S32**)id_epj_ar.getPointer(), n_epj_ar.getPointer(), epj_sorted_.getPointer(), epj_sorted_.size(), false); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } /////////////////////////////////////////////////// //////////// Force Only, Kernel:Ptcl, List:Index ////////////// //////////// Force Only, Kernel:Ptcl, List:Index, Force:Long ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkNewImpl(TagForceLong, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ //F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<S32> n_spj_ar; n_spj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tspj*> spj_ar; spj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; n_walk_prev = (wg>0) ? n_walk_ar[wg-1] : 0; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } const S64 n_sp_head = interaction_list_.n_disp_sp_[n_walk_head]; const S64 n_sp_end = interaction_list_.n_disp_sp_[n_walk_head+n_walk]; const S64 n_spj_tot = n_sp_end - n_sp_head; spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp+n_sp_head] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; //id_epj_ar[iw] = interaction_list_.adr_ep_.getPointer(interaction_list_.n_disp_ep_[id_walk]); n_spj_ar[iw] = interaction_list_.n_sp_[id_walk]; //id_spj_ar[iw] = interaction_list_.adr_sp_.getPointer(interaction_list_.n_disp_sp_[id_walk]); n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); n_interaction_ep_sp_local_ += ((S64)n_spj_ar[iw]*(S64)n_epi_ar[iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } const S64 n_sp_head = interaction_list_.n_disp_sp_[n_walk_head]; const S64 n_sp_end = interaction_list_.n_disp_sp_[n_walk_head+n_walk]; const S64 n_spj_tot = n_sp_end - n_sp_head; spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp+n_sp_head] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } /* const S64 n_epj_tot = interaction_list_.adr_ep_.size(); epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp] ]; } const S64 n_spj_tot = interaction_list_.adr_sp_.size(); spj_for_force_[0].resizeNoInitialize(n_spj_tot); for(S32 jp=0; jp<n_spj_tot; jp++){ spj_for_force_[0][jp] = spj_sorted_[ interaction_list_.adr_sp_[jp] ]; } S64 n_epj_cnt = 0; S64 n_spj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); spj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); spj_ar[iw] = spj_for_force_[0].getPointer(n_spj_cnt); n_epj_cnt += n_epj_ar[iw]; n_spj_cnt += n_spj_ar[iw]; } */ ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer(), (const Tspj**)spj_ar.getPointer(), n_spj_ar.getPointer()); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } /* std::cerr<<"epj_sorted_.size()= "<<epj_sorted_.size() <<" spj_sorted_.size()= "<<spj_sorted_.size()<<std::endl; */ copyForceOriginalOrder(); //time_profile_.calc_force += GetWtime() - time_offset; } //////////// Force Only, Kernel:Ptcl, List:Index, Force:Short ////////////// template<class TSM, class Tforce, class Tepi, class Tepj, class Tmomloc, class Tmomglb, class Tspj> template<class Tfunc_dispatch, class Tfunc_retrieve> void TreeForForce<TSM, Tforce, Tepi, Tepj, Tmomloc, Tmomglb, Tspj>:: calcForceNoWalkForMultiWalkNewImpl(TagForceShort, Tfunc_dispatch pfunc_dispatch, Tfunc_retrieve pfunc_retrieve, const S32 n_walk_limit, const bool clear){ F64 time_offset = GetWtime(); S32 ret = 0; S32 tag = 0; static ReallocatableArray<Tepi*> epi_ar; epi_ar.resizeNoInitialize(n_walk_limit); #if 1 static ReallocatableArray<S32> n_epi_ar[2]; n_epi_ar[0].resizeNoInitialize(n_walk_limit); n_epi_ar[1].resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar[2]; force_ar[0].resizeNoInitialize(n_walk_limit); force_ar[1].resizeNoInitialize(n_walk_limit); #else static ReallocatableArray<S32> n_epi_ar; n_epi_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tforce*> force_ar; force_ar.resizeNoInitialize(n_walk_limit); #endif static ReallocatableArray<S32> n_epj_ar; n_epj_ar.resizeNoInitialize(n_walk_limit); static ReallocatableArray<Tepj*> epj_ar; epj_ar.resizeNoInitialize(n_walk_limit); force_sorted_.resizeNoInitialize(n_loc_tot_); force_org_.resizeNoInitialize(n_loc_tot_); if(clear){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot_; i++){ force_sorted_[i].clear(); force_org_[i].clear(); } } const S64 n_ipg = ipg_.size(); if(n_ipg <= 0) return; const S32 n_loop_max = n_ipg/n_walk_limit + (n_ipg%n_walk_limit==0 ? 0 : 1); static std::vector<S32> n_walk_ar; n_walk_ar.resize(n_loop_max); // group of walk (n_walk_ar[i] < n_walk_limit) static std::vector<S32> n_disp_walk_ar; n_disp_walk_ar.resize(n_loop_max+1); n_disp_walk_ar[0] = 0; for(int wg=0; wg<n_ipg%n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max + 1; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } for(int wg=n_ipg%n_loop_max; wg<n_loop_max; wg++){ n_walk_ar[wg] = n_ipg / n_loop_max; n_disp_walk_ar[wg+1] = n_disp_walk_ar[wg] + n_walk_ar[wg]; } bool first_loop = true; if(n_ipg > 0){ #if 1 S32 n_walk=-1, n_walk_prev=-1, lane_0=-1, lane_1=-1; for(int wg=0; wg<n_loop_max; wg++){ n_walk = n_walk_ar[wg]; n_walk_prev = (wg>0) ? n_walk_ar[wg-1] : 0; const S32 n_walk_head = n_disp_walk_ar[wg]; lane_0 = wg % 2; lane_1 = (wg+1) % 2; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); n_epi_ar[lane_0][iw] = ipg_[id_walk].n_ptcl_; force_ar[lane_0][iw] = force_sorted_.getPointer(first_adr_ip); n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[lane_0][iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } S64 n_epj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } if(!first_loop){ ret += pfunc_retrieve(tag, n_walk_prev, n_epi_ar[lane_1].getPointer(), force_ar[lane_1].getPointer()); } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar[lane_0].getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); first_loop = false; } ret += pfunc_retrieve(tag, n_walk, n_epi_ar[lane_0].getPointer(), force_ar[lane_0].getPointer()); #else // original for(int wg=0; wg<n_loop_max; wg++){ const S32 n_walk = n_walk_ar[wg]; const S32 n_walk_head = n_disp_walk_ar[wg]; for(S32 iw=0; iw<n_walk; iw++){ const S32 id_walk = n_walk_head + iw; const S32 first_adr_ip = ipg_[id_walk].adr_ptcl_; n_epi_ar[iw] = ipg_[id_walk].n_ptcl_; epi_ar[iw] = epi_sorted_.getPointer(first_adr_ip); force_ar[iw] = force_sorted_.getPointer(first_adr_ip); //S32 n_ep_head = interaction_list_.n_disp_ep_[id_walk]; n_epj_ar[iw] = interaction_list_.n_ep_[id_walk]; n_interaction_ep_ep_local_ += ((S64)n_epj_ar[iw]*(S64)n_epi_ar[iw]); } const S64 n_ep_head = interaction_list_.n_disp_ep_[n_walk_head]; const S64 n_ep_end = interaction_list_.n_disp_ep_[n_walk_head+n_walk]; const S64 n_epj_tot = n_ep_end - n_ep_head; epj_for_force_[0].resizeNoInitialize(n_epj_tot); for(S32 jp=0; jp<n_epj_tot; jp++){ epj_for_force_[0][jp] = epj_sorted_[ interaction_list_.adr_ep_[jp+n_ep_head] ]; } S64 n_epj_cnt = 0; epj_ar.resizeNoInitialize(n_walk); for(S32 iw=0; iw<n_walk; iw++){ epj_ar[iw] = epj_for_force_[0].getPointer(n_epj_cnt); n_epj_cnt += n_epj_ar[iw]; } ret += pfunc_dispatch(tag, n_walk, (const Tepi**)epi_ar.getPointer(), n_epi_ar.getPointer(), (const Tepj**)epj_ar.getPointer(), n_epj_ar.getPointer()); ret += pfunc_retrieve(tag, n_walk, n_epi_ar.getPointer(), force_ar.getPointer()); } #endif } time_profile_.calc_force__core += GetWtime() - time_offset; const F64 offset_copy_original_order = GetWtime(); copyForceOriginalOrder(); time_profile_.calc_force__copy_original_order += GetWtime() - offset_copy_original_order; } }
48.198771
165
0.537694
Guo-astro
56e03753132a571f60eb153d39a3093b7563e714
1,457
hpp
C++
src/core/stores/preferences_store.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
3
2019-04-26T17:48:24.000Z
2021-11-08T20:21:51.000Z
src/core/stores/preferences_store.hpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
90
2019-04-25T17:23:10.000Z
2022-02-12T19:49:55.000Z
src/core/stores/preferences_store.hpp
judoassistant/judoassistant
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
[ "MIT" ]
null
null
null
#pragma once #include "core/serialize.hpp" #include "core/draw_systems/draw_system_identifier.hpp" class DrawSystem; struct DrawSystemPreference { std::size_t playerLowerLimit; DrawSystemIdentifier drawSystem; DrawSystemPreference() = default; DrawSystemPreference(std::size_t playerLowerLimit, DrawSystemIdentifier drawSystem); template<typename Archive> void serialize(Archive& ar, uint32_t const version) { ar(playerLowerLimit, drawSystem); } }; enum class ScoreboardStylePreference { NATIONAL, INTERNATIONAL }; enum class MatchCardStylePreference { NATIONAL }; class PreferencesStore { public: PreferencesStore(); template<typename Archive> void serialize(Archive& ar, uint32_t const version) { ar(mPreferredDrawSystems, mScoreboardStyle, mMatchCardStyle); } const std::vector<DrawSystemPreference>& getPreferredDrawSystems() const; std::vector<DrawSystemPreference>& getPreferredDrawSystems(); DrawSystemIdentifier getPreferredDrawSystem(std::size_t size) const; ScoreboardStylePreference getScoreboardStyle() const; void setScoreboardStyle(ScoreboardStylePreference style); MatchCardStylePreference getMatchCardStyle() const; void setMatchCardStyle(MatchCardStylePreference style); private: std::vector<DrawSystemPreference> mPreferredDrawSystems; ScoreboardStylePreference mScoreboardStyle; MatchCardStylePreference mMatchCardStyle; };
29.14
88
0.780371
svendcsvendsen
56e1bb2c38688018ae446fdfbdf16fecc19f6f1e
2,371
hpp
C++
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
9
2019-07-23T10:31:18.000Z
2022-03-15T19:29:26.000Z
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
5
2019-09-11T22:31:29.000Z
2022-01-25T18:26:56.000Z
headers/USRP_file_writer.hpp
zjc263/GPU_SDR
a57a29925b915c6eb995eb3c76c4ec34f96c3a0b
[ "Apache-2.0" ]
7
2019-08-29T20:47:56.000Z
2021-06-10T15:07:35.000Z
#pragma once #ifndef FILE_WRITER_INCLUDED #define FILE_WRITER_INCLUDED #include "USRP_server_settings.hpp" #include "USRP_server_diagnostic.hpp" #include "USRP_server_memory_management.hpp" #include "USRP_server_network.hpp" #include <ctime> #include "H5Cpp.h" #include "H5CompType.h" using namespace H5; class H5_file_writer{ public: rx_queue* stream_queue; //the initialization needs a rx queue to get packets and a memory to dispose of them //NOTE: the file writer should always be the last element of the chain unless using a very fast storage support H5_file_writer(rx_queue* init_queue, preallocator<float2>* init_memory); H5_file_writer(Sync_server *streaming_server); void start(usrp_param* global_params); bool stop(bool force = false); void close(); //in case of pointers update in the TXRX class method set() those functions have to be called //this is because memory size adjustments on rx_output preallocator void update_pointers(rx_queue* init_queue, preallocator<float2>* init_memory); void update_pointers(Sync_server *streaming_server); private: //datatype used by HDF5 api CompType *complex_data_type;//(sizeof(float2)); //pointer to the h5 file H5File *file; //pointer to the raw_data group (single USRP writer) Group *group; //pointers to possible groups for representing USRP X300 data Group *A_TXRX; Group *B_TXRX; Group *A_RX2; Group *B_RX2; //dataspace for H5 file writing DataSpace *dataspace; //rank of the raw_data's datasets and dimensions int dspace_rank; hsize_t *dimsf; //pointer to the memory recycler preallocator<float2>* memory; //pointer to the thread boost::thread* binary_writer; std::atomic<bool> writing_in_progress; void write_properties(Group *measure_group, param* parameters_group); std::string get_name(); void clean_queue(); //force the joining of the thread std::atomic<bool> force_close; void write_files(); }; #endif
29.6375
119
0.628005
zjc263
56e60da5edd2a8a47f26a5d1f3da10aec00e152e
6,887
hpp
C++
include/worksheet.hpp
Alexhuszagh/libxlsxwriterpp
82d89c90e86f9e976fec872e09c1abe68dbed1e8
[ "BSD-2-Clause-FreeBSD" ]
2
2017-07-25T04:30:08.000Z
2018-01-29T17:47:25.000Z
include/worksheet.hpp
Alexhuszagh/libxlsxwriterpp
82d89c90e86f9e976fec872e09c1abe68dbed1e8
[ "BSD-2-Clause-FreeBSD" ]
2
2017-07-24T15:44:16.000Z
2017-09-13T11:59:34.000Z
include/worksheet.hpp
Alexhuszagh/libxlsxwriterpp
82d89c90e86f9e976fec872e09c1abe68dbed1e8
[ "BSD-2-Clause-FreeBSD" ]
4
2017-03-08T22:41:25.000Z
2021-09-11T03:10:01.000Z
// :copyright: (c) 2017 Alex Huszagh. // :license: FreeBSD, see LICENSE.md for more details. /** * C++ bindings for libxlsxwriter worksheets. */ #pragma once #include "chart.hpp" #include "common.hpp" #include "format.hpp" #include <deque> #include <xlsxwriter/worksheet.h> namespace xlsxwriter { // ENUMS // ----- enum class PaperType: uint8_t { DEFAULT = 0, LETTER, LETTER_SMALL, TABLOID, LEDGER, LEGAL, STATEMENT, EXECUTIVE, A3, A4, A4_SMALL, A5, B5, FOLIO, QUARTO, NOTE = 18, ENVELOPE_9, ENVELOPE_10, ENVELOPE_11, ENVELOPE_12, ENVELOPE_14, C_SIZE_SHEET, D_SIZE_SHEET, E_SIZE_SHEET, ENVELOPE_DL, ENVELOPE_C3, ENVELOPE_C4, ENVELOPE_C5, ENVELOPE_C6, ENVELOPE_C65, ENVELOPE_B4, ENVELOPE_B5, ENVELOPE_B6, ENVELOPE, MONARCH, FANFOLD, GERMAN_STD_FANFOLD, GERMAN_LEGAL_FANFOLD, }; enum class Gridlines: uint8_t { HIDE_ALL = 0, SHOW_SCREEN, SHOW_PRINT, SHOW_ALL, }; // OBJECTS // ------- typedef lxw_row_col_options RowColOptions; typedef lxw_col_options ColumnOptions; typedef lxw_image_options ImageOptions; typedef lxw_protection Protection; class Worksheet { protected: lxw_worksheet *ptr = nullptr; friend class Workbook; Worksheet(lxw_worksheet *ptr); public: Worksheet() = default; Worksheet(const Worksheet&) = default; Worksheet & operator=(const Worksheet&) = default; Worksheet(Worksheet &&other) = default; Worksheet & operator=(Worksheet &&other) = default; // WRITE // NUMBER void write(const Row row, const Column col, const double number, const Format &format = Format()); void write_number(const Row row, const Column col, const double number, const Format &format = Format()); // BLANK void write(const Row row, const Column col, const std::nullptr_t nullp, const Format &format = Format()); void write_blank(const Row row, const Column col, const std::nullptr_t nullp, const Format &format = Format()); // STRING void write(const Row row, const Column col, const std::string &string, const Format &format = Format()); void write_string(const Row row, const Column col, const std::string &string, const Format &format = Format()); // BOOLEAN void write(const Row row, const Column col, const bool value, const Format &format = Format()); void write_boolean(const Row row, const Column col, const bool value, const Format &format = Format()); // DATETIME void write(const Row row, const Column col, const Datetime &date, const Format &format = Format()); void write_datetime(const Row row, const Column col, const Datetime &date, const Format &format = Format()); // URL void write_url(const Row row, const Column col, const std::string &url, const Format &format = Format(), const std::string &string = "", const std::string &tooltip = ""); // FORMULA void write_formula(const Row row, const Column col, const std::string &formula, const Format &format = Format(), const double result = 0); void write_array_formula(const Row first_row, const Column first_col, const Row last_row, const Column last_col, const std::string &formula, const Format &format = Format(), const double result = 0); // FORMAT void set_row(const Row row, const double height, const Format &format = Format(), const RowColOptions &options = RowColOptions {0}); void set_column(const Column first_col, const Column last_col, const double width, const Format &format = Format(), const RowColOptions &options = RowColOptions {0}); void merge_range(const Row first_row, const Column first_col, const Row last_row, const Column last_col, const std::string &string, const Format &format = Format()); void insert_chart(const Row row, const Column col, const Chart &chart, const ImageOptions &options = ImageOptions {0}); void insert_image(const Row row, const Column col, const std::string &filename, const ImageOptions &options = ImageOptions {0}); void autofilter(const Row first_row, const Column first_col, const Row last_row, const Column last_col); void activate(); void select(); void hide(); void set_first_sheet(); void freeze_panes(const Row row, const Column col); void freeze_panes(const Row first_row, const Column first_col, const Row top_row, const Column top_col); void split_panes(const Row row, const Column col); void split_panes(const Row first_row, const Column first_col, const Row top_row, const Column top_col); void set_selection(const Row first_row, const Column first_col, const Row last_row, const Column last_col); void set_landscape(); void set_portrait(); void set_page_view(); void set_paper(const PaperType type); void set_margins(const double left, const double right, const double top, const double bottom); void set_header(const std::string &string, const double margin = 0.3); void set_footer(const std::string &string, const double margin = 0.3); void set_h_pagebreaks(Rows &rows); void set_h_pagebreaks(Rows &&rows); void set_v_pagebreaks(Columns &columns); void set_v_pagebreaks(Columns &&columns); void print_across(); void set_zoom(const uint16_t scale); void gridlines(const Gridlines options); void center_horizontally(); void center_vertically(); void print_row_col_headers(); void repeat_rows(const Row first_row, const Row last_row); void repeat_columns(const Column first_col, const Column last_col); void print_area(const Row first_row, const Column first_col, const Row last_row, const Column last_col); void fit_to_pages(const uint16_t width, const uint16_t height); void set_start_page(const uint16_t start_page); void set_print_scale(const uint16_t scale); void right_to_left(); void hide_zero(); void set_tab_color(const Color color); void protect(const std::string &password, const Protection &options); void set_default_row(const double height, const bool hide_unused_rows); }; typedef std::deque<Worksheet> Worksheets; } /* xlsxwriter */
25.890977
58
0.636126
Alexhuszagh
56e9ae1a35acb8f55871ba01a225bbe3c1a56f84
3,745
cpp
C++
doc/Programs/LecturePrograms/programs/Blocking/parallelblocking.cpp
GabrielSCabrera/ComputationalPhysics2
a840b97b651085090f99bf6a11abab57100c2e85
[ "CC0-1.0" ]
87
2015-01-21T08:29:56.000Z
2022-03-28T07:11:53.000Z
doc/Programs/LecturePrograms/programs/Blocking/parallelblocking.cpp
GabrielSCabrera/ComputationalPhysics2
a840b97b651085090f99bf6a11abab57100c2e85
[ "CC0-1.0" ]
3
2020-01-18T10:43:38.000Z
2020-02-08T13:15:42.000Z
doc/Programs/LecturePrograms/programs/Blocking/parallelblocking.cpp
GabrielSCabrera/ComputationalPhysics2
a840b97b651085090f99bf6a11abab57100c2e85
[ "CC0-1.0" ]
54
2015-02-09T10:02:00.000Z
2022-03-07T10:44:14.000Z
// Gathering mcint results from files and summarizing results // usage: ./mcint_fromfile.x <n_procs> // where n_procs are the number of processors used in mcint simulation using namespace std; #include <cmath> #include <iostream> // std io #include <iomanip> // std io #include <fstream> // file io #include <sstream> // string io #include <sys/stat.h> // to get size of file // find mean of values in vals double mean(double *vals, int n_vals){ double m=0; for(int i=0; i<n_vals; i++){ m+=vals[i]; } return m/double(n_vals); } // calculate mean and variance of vals, results stored in res void meanvar(double *vals, int n_vals, double *res){ double m2=0, m=0, val; for(int i=0; i<n_vals; i++){ val=vals[i]; m+=val; m2+=val*val; } m /= double(n_vals); m2 /= double(n_vals); res[0] = m; res[1] = m2-(m*m); } // find mean and variance of blocks of size block_size. // mean and variance are stored in res void blocking(double *vals, int n_vals, int block_size, double *res){ // note: integer division will waste some values int n_blocks = n_vals/block_size; /* cerr << "n_vals=" << n_vals << ", block_size=" << block_size << endl; if(n_vals%block_size > 0) cerr << "lost " << n_vals%block_size << " values due to integer division" << endl; */ double* block_vals = new double[n_blocks]; for(int i=0; i<n_blocks; i++){ block_vals[i] = mean(vals+i*block_size, block_size); } meanvar(block_vals, n_blocks, res); delete block_vals; } int main (int nargs, char* args[]) { int n_procs, min_block_size, max_block_size, n_block_samples; // Read from screen a possible new vaue of n if (nargs > 4) { n_procs = atoi(args[1]); min_block_size = atoi(args[2]); max_block_size = atoi(args[3]); n_block_samples = atoi(args[4]); } else{ cerr << "usage: ./mcint_blocking.x <n_procs> <min_bloc_size> " << "<max_block_size> <n_block_samples>" << endl; exit(1); } // get file size using stat struct stat result; int local_n,n; if(stat("blocks_rank0.dat", &result) == 0){ local_n = result.st_size/sizeof(double); n = local_n*n_procs; } else{ cerr << "error in getting file size" << endl; exit(1); } // get all mc results from files double* mc_results = new double[n]; for(int i=0; i<n_procs; i++){ ostringstream ost; ost << "blocks_rank" << i << ".dat"; ifstream infile; infile.open(ost.str().c_str(), ios::in | ios::binary); infile.read((char*)&(mc_results[i*local_n]),result.st_size); infile.close(); } // and summarize double mean, sigma; double res[2]; meanvar(mc_results, n, res); mean = res[0]; sigma= res[1]; cout << "Value of integral = " << mean << " Analytic result = " << acos(-1.0) << endl; cout << "Value of variance = " << sigma << endl; ///n-(total_sum*total_sum/(n*n)) << endl; cout << "Standard deviation = " << sqrt(sigma/(n-1.0)) << endl; // Open file for writing, writing results in formated output for plotting: ofstream outfile; outfile.open("blockres.dat", ios::out); outfile << setprecision(10); double* block_results = new double[n_block_samples]; int block_size, block_step_length; block_step_length = (max_block_size-min_block_size)/n_block_samples; // loop over block sizes for(int i=0; i<n_block_samples; i++){ block_size = min_block_size+i*block_step_length; cerr << "her? " << block_size << endl; blocking(mc_results, n, block_size, res); mean = res[0]; sigma = res[1]; // formated output outfile << block_size << "\t" << sqrt(sigma/((n/block_size)-1.0)) << endl; } outfile.close(); return 0; }
23.853503
78
0.626435
GabrielSCabrera
56ebb968ba92f8bfbfed3c459f23b269fdb50ab0
579
cpp
C++
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
3
2020-08-27T03:55:40.000Z
2020-09-28T17:29:48.000Z
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
null
null
null
Lab_7/Q2/function_overloading.cpp
pranav2012/Object-Oriented-Programming-In-C
6ff8fc15ea9f0a44659bdf630975ccfdf6ab1ffb
[ "MIT" ]
1
2020-12-08T11:35:17.000Z
2020-12-08T11:35:17.000Z
#include<iostream> using namespace std; int area(int); int area(int,int); float area(float,float); int main() { int s,l,b; float bs,ht; cout<<"Enter side of a square: "; cin>>s; cout<<"Enter length and breadth of rectangle: "; cin>>l>>b; cout<<"Enter base and height of triangle: "; cin>>bs>>ht; cout<<"Area of square is "<<area(s); cout<<"\nArea of rectangle is "<<area(l,b); cout<<"\nArea of triangle is "<<area(bs,ht)<<"\n"; } int area(int s) { return(s*s); } int area(int l,int b) { return(l*b); } float area(float bs,float ht) { return((bs*ht)/2); }
18.677419
54
0.620035
pranav2012
56ec7bc330ab4bef20982ad0244d497b49547411
147
hpp
C++
include/natalie/types.hpp
davidot/natalie
e5159bacb3831c1720063360570810c0fd2c3ae9
[ "MIT" ]
1
2021-11-17T22:01:36.000Z
2021-11-17T22:01:36.000Z
include/natalie/types.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
include/natalie/types.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #define NAT_INT_MIN INT64_MIN #define NAT_INT_MAX INT64_MAX namespace Natalie { using nat_int_t = int64_t; }
11.307692
29
0.768707
davidot
56f00a45a0b1db96e22a94e286cfb58c0774ebe2
537
cpp
C++
UCF Camp/2017 Contest No. 2/one.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2020-10-16T18:14:30.000Z
2020-10-16T18:14:30.000Z
UCF Camp/2017 Contest No. 2/one.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
null
null
null
UCF Camp/2017 Contest No. 2/one.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2021-01-06T04:45:38.000Z
2021-01-06T04:45:38.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <set> #include <string.h> using namespace std; int main(){ int a, b, maxGCD = 1; scanf("%d %d", &a, &b); for(int i = 1; i <= b; i++){ int lower = a/i; if(a%i != 0) lower++; int high = b/i; if(high-lower+1 > 1) maxGCD = i; } int ret = maxGCD; if(a%maxGCD == 0) ret = a; else ret *= (a/maxGCD+1); cout << ret << " " << ret+maxGCD << '\n'; return 0; }
20.653846
49
0.515829
hardik0899
56f34317250f150f24f5135f02fea980b0f3b444
106
cpp
C++
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
src/opera/tcppacket.cpp
Flasew/opera-sim
1f64017883689c115b8442acab7ef52846ab2c18
[ "BSD-3-Clause" ]
null
null
null
#include "tcppacket.h" PacketDB<TcpPacket> TcpPacket::_packetdb; PacketDB<TcpAck> TcpAck::_packetdb;
21.2
42
0.764151
Flasew
56f5669f234a76ed22fd3e56c98b758224877344
679
cpp
C++
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
luohenyueji/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
293
2019-04-05T14:31:22.000Z
2022-03-30T10:04:51.000Z
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
hktkfly6/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
2
2019-04-05T14:31:04.000Z
2021-11-26T09:27:54.000Z
ITEM 10-19/ITEM10 HuMoments/shapeMatcher.cpp
hktkfly6/OpenCV-Practical-Exercise
8a747b05b5c56d5be4611c5e72c8983f6b96d81d
[ "MIT" ]
149
2019-04-06T10:51:13.000Z
2022-03-31T01:34:47.000Z
#include "pch.h" #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { Mat im1 = imread("./image/S0.png",IMREAD_GRAYSCALE); Mat im2 = imread("./image/K0.png",IMREAD_GRAYSCALE); Mat im3 = imread("./image/S4.png",IMREAD_GRAYSCALE); double m1 = matchShapes(im1, im1, CONTOURS_MATCH_I2, 0); double m2 = matchShapes(im1, im2, CONTOURS_MATCH_I2, 0); double m3 = matchShapes(im1, im3, CONTOURS_MATCH_I2, 0); cout << "Shape Distances Between " << endl << "-------------------------" << endl; cout << "S0.png and S0.png : " << m1 << endl; cout << "S0.png and K0.png : " << m2 << endl; cout << "S0.png and S4.png : " << m3 << endl; }
30.863636
84
0.617084
luohenyueji
56f74ff70e4a016d75d77729972c677f850f456a
1,942
cpp
C++
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
1
2017-11-21T01:25:19.000Z
2017-11-21T01:25:19.000Z
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
null
null
null
Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.cpp
RobertAcksel/UnrealCS
16d6f4989ef2f8622363009ebc6509b67c35a57e
[ "MIT" ]
null
null
null
#include "MonoCallbackScheduler.h" #include "MonoPluginPrivatePCH.h" bool MonoCallbackScheduler::AddTickableObject(MonoObject * obj) { if(obj == nullptr) return false; MonoClass * ObjectClass = mono_object_get_class(obj); TickObject Data; Data.removed = false; Data.Obj = obj; Data.TickMethod = mono_class_get_method_from_name(ObjectClass, "Tick", 1); if(Data.TickMethod == nullptr) return false; //attrs.name Data.gc_handle = mono_gchandle_new(obj, 1); for(int32 i = 0; i < TickObjects.Num(); i++) { if(TickObjects[i].removed) { TickObjects[i] = Data; return true; } } TickObjects.Add(Data); return true; } bool MonoCallbackScheduler::RemoveTickableObject(MonoObject * obj) { for(int32 i = 0; i < TickObjects.Num(); i++) { if(TickObjects[i].Obj == obj && !TickObjects[i].removed) { TickObjects[i].Obj = nullptr; mono_gchandle_free(TickObjects[i].gc_handle); TickObjects[i].removed = true; return true; } } return false; } void MonoCallbackScheduler::Tick(float DeltaTime) { for(int32 i = 0; i < TickObjects.Num(); i++) { if(!TickObjects[i].removed) { void * args[]{ &DeltaTime }; MonoObject * exception = nullptr; MonoObject * ret = mono_runtime_invoke(TickObjects[i].TickMethod, TickObjects[i].Obj, args, &exception); if(exception) { mono_print_unhandled_exception(exception); } } } } void MonoCallbackScheduler::HotReload() { //Remove all tickable objects for(int32 i = 0; i < TickObjects.Num(); i++) { if(!TickObjects[i].removed) { mono_gchandle_free(TickObjects[i].gc_handle); } } TickObjects.Empty(); }
28.558824
117
0.572091
RobertAcksel
56f826e8358547dcae3d8d04b66b055d28548051
2,789
cpp
C++
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
buildcc/lib/target/src/target/tasks.cpp
d-winsor/build_in_cpp
581c827fd8c69a7258175e360847676861a5c7b0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Niket Naidu. 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 "target/target.h" #include <algorithm> #include "env/assert_fatal.h" #include "env/logging.h" #include "target/util.h" #include "fmt/format.h" namespace { constexpr const char *const kPchTaskName = "Pch"; constexpr const char *const kCompileTaskName = "Objects"; constexpr const char *const kLinkTaskName = "Target"; } // namespace namespace buildcc::base { void CompilePch::Task() { task_ = target_.tf_.emplace([&](tf::Subflow &subflow) { BuildCompile(); // For Graph generation for (const auto &p : target_.GetCurrentPchFiles()) { std::string name = p.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); subflow.placeholder().name(name); } }); task_.name(kPchTaskName); } void CompileObject::Task() { compile_task_ = target_.tf_.emplace([&](tf::Subflow &subflow) { std::vector<fs::path> source_files; std::vector<fs::path> dummy_source_files; BuildObjectCompile(source_files, dummy_source_files); for (const auto &s : source_files) { std::string name = s.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); (void)subflow .emplace([this, s]() { bool success = Command::Execute(GetObjectData(s).command); env::assert_fatal(success, "Could not compile source"); }) .name(name); } // For graph generation for (const auto &ds : dummy_source_files) { std::string name = ds.lexically_relative(env::get_project_root_dir()).string(); std::replace(name.begin(), name.end(), '\\', '/'); (void)subflow.placeholder().name(name); } }); compile_task_.name(kCompileTaskName); } void LinkTarget::Task() { task_ = target_.tf_.emplace([&]() { BuildLink(); }); task_.name(kLinkTaskName); } void Target::TaskDeps() { // NOTE, PCH may not be used if (!compile_pch_.GetTask().empty()) { compile_object_.GetTask().succeed(compile_pch_.GetTask()); } link_target_.GetTask().succeed(compile_object_.GetTask()); } } // namespace buildcc::base
28.752577
75
0.662603
d-winsor
56fbc38ea543637a2e94ad8355f09036344b9d42
376
cpp
C++
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/mlcmst_solver.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
#include <mlcmst_solver.hpp> #include <utility> namespace MLCMST { MLCMST_Solver::~MLCMST_Solver() = default; MLCMST_Solver::Result::Result( std::optional<network::MLCST> mlcmst, std::optional<double> lower_bound, double wall_time, bool finished ) : mlcst(std::move(mlcmst)), lower_bound(std::move(lower_bound)), wall_time(wall_time), finished(finished) { } }
23.5
112
0.731383
qaskai
56ffdb1efbe44ece05cdf7a223b4597422a08c75
3,297
cpp
C++
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
snippets/0x01/work_string.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
// author: a.voss@fh-aachen.de #include <iostream> using namespace std; int main() { cout << endl << "--- " << __FILE__ << " ---" << endl << endl; string s{"Beispiel"}; // (A) cout << "01| s='" << s << "'" << endl; // (B) cout << "-----" << endl; cout << "02| s+s='" << s + s << "' (op+)" << endl; // (C) cout << "03| s[1]='" << s[1] << "' (op[])" << endl; // (D) s += "!"; // (E) cout << "04| s='" << s << "' (op+=)" << endl; cout << "-----" << endl; cout << "05| s.size()=" << s.size() << endl; // (F) cout << "06| s.empty()=" << s.empty() << endl; // (G) cout << "07| s.at(1)='" << s.at(1) << "'" << endl; // (H) cout << "08| s.substr(1,3)='" // (I) << s.substr(1, 3) << "'" << endl; cout << "-----" << endl; string::size_type pos; // (J) bool found; found = ((pos = s.find("spiel")) != string::npos); // (K), (L) cout << "09| find(\"spiel\") ok? " << found << ", pos=" << pos << endl; found = ((pos = s.find("Reis")) != string::npos); cout << "10| find(\"Reis\") ok? " << found << endl; found = ((pos = s.rfind("i")) != string::npos); // (M) cout << "11| rfind(\"i\") ok? " << found << ", pos=" << pos << endl; cout << "-----" << endl; string rep1{"Bei"}; pos = s.find(rep1); s.replace(pos, rep1.size(), "Fussball"); // (N) cout << "12| s.replace(...), s='" << s << "'" << endl; string rep2{"!"}; pos = s.find(rep2); s.erase(pos, rep2.size()); // (O) cout << "13| s.erase(...), s='" << s << "'" << endl; s.insert(0, "XXL-"); // (P) cout << "14| insert(0,\"XXL-\"), s='" << s << "'" << endl; s.append("e"); // (Q) cout << "15| append(\"e\"), s='" << s << "'" << endl; cout << endl << "--- " << __FILE__ << " ---" << endl << endl; return 0; } /* Kommentierung * * (A) Definition eines 'string'. * * (B) Die Ausgabe auf cout. * * (C) Strings können 'addiert' werden, d.h. über '+' werden sie * aneinander gehängt. * * (D) Über '[pos]' können einzelne Zeichen gelesen werden, ohne Test * der Grenzen. * * (E) Der Operator '+=' hängt Zeichen oder Texte an. * * (F) 'size' gibt die Länge des Strings zurück, 0 ist möglich. * * (G) 'empty' testet, ob der String leer ist (Größe 0). * * (H) 'at' liest Zeichen an einer Position, aber mit Test der Grenzen. * * (I) 'substr' liest einen Teilstring ab einer Position für eine * gegebene Länge. * * (J) 'size_type' ist der Datentyp, der eine Position im String aufnehmen * kann. * * (K) 'find' sucht ein Muster und gibt die Position zurück. * * (L) Die Konstante 'npos' wird zurück gegeben, wenn keine Muster * gefunden wurde. * * (M) 'rfind' sucht vom Ende. * * (N) 'replace' ersetzt im String ab einer Position für eine * gegebene Länge den dortigen Text mit einem neuen. * * (O) 'erase' löscht im String ab einer Position für eine * gegebene Länge. * * (P) 'insert' fügt an einer Position neuen Text ein. * * (Q) 'append' hängt Text an. * */
28.921053
75
0.451319
pblan
710333d9b59b7b7c45ae70aa97ed0921c00c7e97
1,332
cpp
C++
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
1
2017-12-01T14:57:16.000Z
2017-12-01T14:57:16.000Z
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
src/fps_ros_bridge/fps_tracker_client_node.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
#include "fps_mapper/RichPointMsg.h" #include "fps_mapper/StampedCloudMsg.h" #include <ros/ros.h> #include "txt_io/message_writer.h" #include "tf/transform_listener.h" #include "fps_ros_msgs.h" using namespace fps_mapper; using namespace std; txt_io::MessageWriter writer; tf::TransformListener* _listener = 0; void cloudCallback(const StampedCloudMsgConstPtr& msg, Eigen::Isometry3f& pose, fps_mapper::Cloud& dest){ if (_listener) { tf::StampedTransform transform; try{ _listener->waitForTransform("tracker_origin_frame_id", msg->header.frame_id, msg->header.stamp, ros::Duration(0.1) ); _listener->lookupTransform ("tracker_origin_frame_id", msg->header.frame_id, msg->header.stamp, transform); } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); } pose = tfTransform2eigen(transform); msg2cloud(dest,msg->cloud); } } int main(int argc, char** argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; Eigen::Isometry3f ref_pose, curr_pose; fps_mapper::Cloud ref_cloud, curr_cloud; ros::Subscriber sub_curr = n.subscribe<fps_mapper::StampedCloudMsg>("/tracker/current_cloud", 10, boost::bind(cloudCallback, _1, curr_pose, curr_cloud)); _listener = new tf::TransformListener(n); ros::spin(); }
27.183673
155
0.70045
Lab-RoCoCo
710d1f47b82a57c1befddff0bda5eb106beeeb1a
240
cpp
C++
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
bitwise/bitwiseQs4.cpp
rrishabhj/ALGORITHM
a5204575b2e7417b5f5e1243687179294fdca290
[ "MIT" ]
null
null
null
/* Detect if two integers have opposite signs */ #include<iostream> #include<stdio.h> using namespace std; bool checkOppositeSign(int a, int b){ return ( (a^b) < 0); } int main() { cout<<checkOppositeSign(3,-4)<<endl; return(0); }
15
48
0.666667
rrishabhj
710e19173a528a1de0e06012e05e48004448ccfc
19,179
cc
C++
zircon/kernel/kernel/timer.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
zircon/kernel/kernel/timer.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
zircon/kernel/kernel/timer.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Fuchsia Authors // Copyright (c) 2008-2014 Travis Geiselbrecht // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT /** * @file * @brief Kernel timer subsystem * @defgroup timer Timers * * The timer subsystem allows functions to be scheduled for later * execution. Each timer object is used to cause one function to * be executed at a later time. * * Timer callback functions are called in interrupt context. * * @{ */ #include "kernel/timer.h" #include <assert.h> #include <debug.h> #include <err.h> #include <inttypes.h> #include <lib/affine/ratio.h> #include <lib/counters.h> #include <platform.h> #include <stdlib.h> #include <trace.h> #include <zircon/compiler.h> #include <zircon/listnode.h> #include <zircon/time.h> #include <zircon/types.h> #include <kernel/align.h> #include <kernel/lockdep.h> #include <kernel/mp.h> #include <kernel/percpu.h> #include <kernel/sched.h> #include <kernel/spinlock.h> #include <kernel/stats.h> #include <kernel/thread.h> #include <platform/timer.h> #define LOCAL_TRACE 0 // Total number of timers set. Always increasing. KCOUNTER(timer_created_counter, "timer.created") // Number of timers merged into an existing timer because of slack. KCOUNTER(timer_coalesced_counter, "timer.coalesced") // Number of timers that have fired (i.e. callback was invoked). KCOUNTER(timer_fired_counter, "timer.fired") // Number of timers that were successfully canceled. Attempts to cancel a timer that is currently // firing are not counted. KCOUNTER(timer_canceled_counter, "timer.canceled") // Default platform ticks hook. This hook will be replaced with the appropriate // source of time for the platform, selected during platform initialization. zx_ticks_t (*current_ticks)(void) = [](void) -> zx_ticks_t { return 0; }; namespace { spin_lock_t timer_lock __CPU_ALIGN_EXCLUSIVE = SPIN_LOCK_INITIAL_VALUE; DECLARE_SINGLETON_LOCK_WRAPPER(TimerLock, timer_lock); affine::Ratio gTicksToTime; uint64_t gTicksPerSecond; } // anonymous namespace void platform_set_ticks_to_time_ratio(const affine::Ratio& ticks_to_time) { // ASSERT that we are not calling this function twice. Once set, this ratio // may not change. DEBUG_ASSERT(gTicksPerSecond == 0); DEBUG_ASSERT(ticks_to_time.numerator() != 0); DEBUG_ASSERT(ticks_to_time.denominator() != 0); gTicksToTime = ticks_to_time; gTicksPerSecond = gTicksToTime.Inverse().Scale(ZX_SEC(1)); } const affine::Ratio& platform_get_ticks_to_time_ratio(void) { return gTicksToTime; } zx_time_t current_time(void) { return gTicksToTime.Scale(current_ticks()); } zx_ticks_t ticks_per_second(void) { return gTicksPerSecond; } // Set the platform's oneshot timer to the minimum of its current deadline and |new_deadline|. // // Call this when the timer queue's head changes. // // Can only be called when interrupts are disabled and current CPU is |cpu|. static void update_platform_timer(uint cpu, zx_time_t new_deadline) { DEBUG_ASSERT(arch_ints_disabled()); DEBUG_ASSERT(cpu == arch_curr_cpu_num()); if (new_deadline < percpu::Get(cpu).next_timer_deadline) { LTRACEF("rescheduling timer for %" PRIi64 " nsecs\n", new_deadline); platform_set_oneshot_timer(new_deadline); percpu::Get(cpu).next_timer_deadline = new_deadline; } } static void insert_timer_in_queue(uint cpu, Timer* timer, zx_time_t earliest_deadline, zx_time_t latest_deadline) { DEBUG_ASSERT(arch_ints_disabled()); LTRACEF("timer %p, cpu %u, scheduled %" PRIi64 "\n", timer, cpu, timer->scheduled_time_); // For inserting the timer we consider several cases. In general we // want to coalesce with the current timer unless we can prove that // either that: // 1- there is no slack overlap with current timer OR // 2- the next timer is a better fit. // // In diagrams that follow // - Let |e| be the current (existing) timer deadline // - Let |t| be the deadline of the timer we are inserting // - Let |n| be the next timer deadline if any // - Let |x| be the end of the list (not a timer) // - Let |(| and |)| the earliest_deadline and latest_deadline. // Timer* entry; list_for_every_entry (&percpu::Get(cpu).timer_queue, entry, Timer, node_) { if (entry->scheduled_time_ > latest_deadline) { // New timer latest is earlier than the current timer. // Just add upfront as is, without slack. // // ---------t---)--e-------------------------------> time // timer->slack_ = 0ll; list_add_before(&entry->node_, &timer->node_); return; } if (entry->scheduled_time_ >= timer->scheduled_time_) { // New timer slack overlaps and is to the left (or equal). We // coalesce with current by scheduling late. // // --------(----t---e-)----------------------------> time // timer->slack_ = zx_time_sub_time(entry->scheduled_time_, timer->scheduled_time_); timer->scheduled_time_ = entry->scheduled_time_; kcounter_add(timer_coalesced_counter, 1); list_add_after(&entry->node_, &timer->node_); return; } if (entry->scheduled_time_ < earliest_deadline) { // new timer earliest is later than the current timer. This case // is handled in a future iteration. // // ----------------e--(---t-----------------------> time // continue; } // New timer is to the right of current timer and there is overlap // with the current timer, but could the next timer (if any) be // a better fit? // // -------------(--e---t-----?-------------------> time // const Timer* next = list_next_type(&percpu::Get(cpu).timer_queue, &entry->node_, Timer, node_); if (next != NULL) { if (next->scheduled_time_ <= timer->scheduled_time_) { // The new timer is to the right of the next timer. There is no // chance the current timer is a better fit. // // -------------(--e---n---t----------------------> time // continue; } if (next->scheduled_time_ < latest_deadline) { // There is slack overlap with the next timer, and also with the // current timer. Which coalescing is a better match? // // --------------(-e---t---n-)-----------------------> time // zx_duration_t delta_entry = zx_time_sub_time(timer->scheduled_time_, entry->scheduled_time_); zx_duration_t delta_next = zx_time_sub_time(next->scheduled_time_, timer->scheduled_time_); if (delta_next < delta_entry) { // New timer is closer to the next timer, handle it in the // next iteration. continue; } } } // Handles the remaining cases, note that there is overlap with // the current timer. // // 1- this is the last timer (next == NULL) or // 2- there is no overlap with the next timer, or // 3- there is overlap with both current and next but // current is closer. // // So we coalesce by scheduling early. // timer->slack_ = zx_time_sub_time(entry->scheduled_time_, timer->scheduled_time_); timer->scheduled_time_ = entry->scheduled_time_; kcounter_add(timer_coalesced_counter, 1); list_add_after(&entry->node_, &timer->node_); return; } // Walked off the end of the list and there was no overlap. timer->slack_ = 0; list_add_tail(&percpu::Get(cpu).timer_queue, &timer->node_); } Timer::~Timer() { // Ensure that we are not on any cpu's list. ZX_DEBUG_ASSERT(!list_in_list(&node_)); // Ensure that we are not active on some cpu. ZX_DEBUG_ASSERT(active_cpu_ == -1); } void Timer::Set(const Deadline& deadline, Callback callback, void* arg) { LTRACEF("timer %p deadline.when %" PRIi64 " deadline.slack.amount %" PRIi64 " deadline.slack.mode %u callback %p arg %p\n", this, deadline.when(), deadline.slack().amount(), deadline.slack().mode(), callback, arg); DEBUG_ASSERT(magic_ == kMagic); DEBUG_ASSERT(deadline.slack().mode() <= TIMER_SLACK_LATE); DEBUG_ASSERT(deadline.slack().amount() >= 0); if (list_in_list(&node_)) { panic("timer %p already in list\n", this); } const zx_time_t latest_deadline = deadline.latest(); const zx_time_t earliest_deadline = deadline.earliest(); Guard<spin_lock_t, IrqSave> guard{TimerLock::Get()}; uint cpu = arch_curr_cpu_num(); bool currently_active = (active_cpu_ == (int)cpu); if (unlikely(currently_active)) { // the timer is active on our own cpu, we must be inside the callback if (cancel_) { return; } } else if (unlikely(active_cpu_ >= 0)) { panic("timer %p currently active on a different cpu %d\n", this, active_cpu_); } // Set up the structure. scheduled_time_ = deadline.when(); callback_ = callback; arg_ = arg; cancel_ = false; // We don't need to modify active_cpu_ because it is managed by timer_tick(). LTRACEF("scheduled time %" PRIi64 "\n", scheduled_time_); insert_timer_in_queue(cpu, this, earliest_deadline, latest_deadline); kcounter_add(timer_created_counter, 1); if (list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_) == this) { // we just modified the head of the timer queue update_platform_timer(cpu, deadline.when()); } } void TimerQueue::PreemptReset(zx_time_t deadline) { DEBUG_ASSERT(arch_ints_disabled()); uint cpu = arch_curr_cpu_num(); LTRACEF("preempt timer cpu %u deadline %" PRIi64 "\n", cpu, deadline); percpu::Get(cpu).preempt_timer_deadline = deadline; update_platform_timer(cpu, deadline); } void TimerQueue::PreemptCancel() { DEBUG_ASSERT(arch_ints_disabled()); uint cpu = arch_curr_cpu_num(); percpu::Get(cpu).preempt_timer_deadline = ZX_TIME_INFINITE; // Note, we're not updating the platform timer. It's entirely possible the timer queue is empty // and the preemption timer is the only reason the platform timer is set. To know that, we'd // need to acquire a lock and look at the queue. Rather than pay that cost, leave the platform // timer as is and expect the recipient to handle spurious wakeups. } bool Timer::Cancel() { DEBUG_ASSERT(magic_ == kMagic); Guard<spin_lock_t, IrqSave> guard{TimerLock::Get()}; uint cpu = arch_curr_cpu_num(); // mark the timer as canceled cancel_ = true; mb(); // see if we're trying to cancel the timer we're currently in the middle of handling if (unlikely(active_cpu_ == (int)cpu)) { // zero it out callback_ = nullptr; arg_ = nullptr; // we're done, so return back to the callback return false; } bool callback_not_running; // if the timer is in a queue, remove it and adjust hardware timers if needed if (list_in_list(&node_)) { callback_not_running = true; // save a copy of the old head of the queue so later we can see if we modified the head Timer* oldhead = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); // remove our timer from the queue list_delete(&node_); kcounter_add(timer_canceled_counter, 1); // TODO(cpu): if after removing |timer| there is one other single timer with // the same scheduled_time and slack non-zero then it is possible to return // that timer to the ideal scheduled_time. // see if we've just modified the head of this cpu's timer queue. // if we modified another cpu's queue, we'll just let it fire and sort itself out if (unlikely(oldhead == this)) { // timer we're canceling was at head of queue, see if we should update platform timer Timer* newhead = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); if (newhead) { update_platform_timer(cpu, newhead->scheduled_time_); } else if (percpu::Get(cpu).next_timer_deadline == ZX_TIME_INFINITE) { LTRACEF("clearing old hw timer, preempt timer not set, nothing in the queue\n"); platform_stop_timer(); } } } else { callback_not_running = false; } guard.Release(); // wait for the timer to become un-busy in case a callback is currently active on another cpu while (active_cpu_ >= 0) { arch_spinloop_pause(); } // zero it out callback_ = nullptr; arg_ = nullptr; return callback_not_running; } // called at interrupt time to process any pending timers void timer_tick(zx_time_t now) { Timer* timer; DEBUG_ASSERT(arch_ints_disabled()); CPU_STATS_INC(timer_ints); uint cpu = arch_curr_cpu_num(); LTRACEF("cpu %u now %" PRIi64 ", sp %p\n", cpu, now, __GET_FRAME()); // platform timer has fired, no deadline is set percpu::Get(cpu).next_timer_deadline = ZX_TIME_INFINITE; // service preempt timer before acquiring the timer lock if (now >= percpu::Get(cpu).preempt_timer_deadline) { percpu::Get(cpu).preempt_timer_deadline = ZX_TIME_INFINITE; sched_preempt_timer_tick(now); } Guard<spin_lock_t, NoIrqSave> guard{TimerLock::Get()}; for (;;) { // see if there's an event to process timer = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); if (likely(timer == 0)) { break; } LTRACEF("next item on timer queue %p at %" PRIi64 " now %" PRIi64 " (%p, arg %p)\n", timer, timer->scheduled_time_, now, timer->callback_, timer->arg_); if (likely(now < timer->scheduled_time_)) { break; } // process it LTRACEF("timer %p\n", timer); DEBUG_ASSERT_MSG(timer && timer->magic_ == Timer::kMagic, "ASSERT: timer failed magic check: timer %p, magic 0x%x\n", timer, (uint)timer->magic_); list_delete(&timer->node_); // mark the timer busy timer->active_cpu_ = cpu; // Unlocking the spinlock in CallUnlocked acts as a memory barrier. // Now that the timer is off of the list, release the spinlock to handle // the callback, then re-acquire in case it is requeued. guard.CallUnlocked([timer, now]() { LTRACEF("dequeued timer %p, scheduled %" PRIi64 "\n", timer, timer->scheduled_time_); CPU_STATS_INC(timers); kcounter_add(timer_fired_counter, 1); LTRACEF("timer %p firing callback %p, arg %p\n", timer, timer->callback_, timer->arg_); timer->callback_(timer, now, timer->arg_); DEBUG_ASSERT(arch_ints_disabled()); }); // mark it not busy timer->active_cpu_ = -1; mb(); } // get the deadline of the event at the head of the queue (if any) zx_time_t deadline = ZX_TIME_INFINITE; timer = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); if (timer) { deadline = timer->scheduled_time_; // has to be the case or it would have fired already DEBUG_ASSERT(deadline > now); } // we're done manipulating the timer queue guard.Release(); // set the platform timer to the *soonest* of queue event and preempt timer if (percpu::Get(cpu).preempt_timer_deadline < deadline) { deadline = percpu::Get(cpu).preempt_timer_deadline; } update_platform_timer(cpu, deadline); } zx_status_t Timer::TrylockOrCancel(spin_lock_t* lock) { // spin trylocking on the passed in spinlock either waiting for it // to grab or the passed in timer to be canceled. while (unlikely(spin_trylock(lock))) { // we failed to grab it, check for cancel if (cancel_) { // we were canceled, so bail immediately return ZX_ERR_TIMED_OUT; } // tell the arch to wait arch_spinloop_pause(); } return ZX_OK; } void TimerQueue::TransitionOffCpu(uint old_cpu) { Guard<spin_lock_t, IrqSave> guard{TimerLock::Get()}; uint cpu = arch_curr_cpu_num(); Timer* old_head = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); Timer *entry = NULL, *tmp_entry = NULL; // Move all timers from old_cpu to this cpu list_for_every_entry_safe (&percpu::Get(old_cpu).timer_queue, entry, tmp_entry, Timer, node_) { list_delete(&entry->node_); // We lost the original asymmetric slack information so when we combine them // with the other timer queue they are not coalesced again. // TODO(cpu): figure how important this case is. insert_timer_in_queue(cpu, entry, entry->scheduled_time_, entry->scheduled_time_); // Note, we do not increment the "created" counter here because we are simply moving these // timers from one queue to another and we already counted them when they were first // created. } Timer* new_head = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); if (new_head != NULL && new_head != old_head) { // we just modified the head of the timer queue update_platform_timer(cpu, new_head->scheduled_time_); } // the old cpu has no tasks left, so reset the deadlines percpu::Get(old_cpu).preempt_timer_deadline = ZX_TIME_INFINITE; percpu::Get(old_cpu).next_timer_deadline = ZX_TIME_INFINITE; } void TimerQueue::ThawPercpu(void) { DEBUG_ASSERT(arch_ints_disabled()); Guard<spin_lock_t, NoIrqSave> guard{TimerLock::Get()}; uint cpu = arch_curr_cpu_num(); // reset next_timer_deadline so that update_platform_timer will reconfigure the timer percpu::Get(cpu).next_timer_deadline = ZX_TIME_INFINITE; zx_time_t deadline = percpu::Get(cpu).preempt_timer_deadline; Timer* t = list_peek_head_type(&percpu::Get(cpu).timer_queue, Timer, node_); if (t) { if (t->scheduled_time_ < deadline) { deadline = t->scheduled_time_; } } guard.Release(); update_platform_timer(cpu, deadline); } // print a timer queue dump into the passed in buffer static void dump_timer_queues(char* buf, size_t len) { size_t ptr = 0; zx_time_t now = current_time(); Guard<spin_lock_t, IrqSave> guard{TimerLock::Get()}; for (uint i = 0; i < percpu::processor_count(); i++) { if (mp_is_cpu_online(i)) { ptr += snprintf(buf + ptr, len - ptr, "cpu %u:\n", i); Timer* t; zx_time_t last = now; list_for_every_entry (&percpu::Get(i).timer_queue, t, Timer, node_) { zx_duration_t delta_now = zx_time_sub_time(t->scheduled_time_, now); zx_duration_t delta_last = zx_time_sub_time(t->scheduled_time_, last); ptr += snprintf(buf + ptr, len - ptr, "\ttime %" PRIi64 " delta_now %" PRIi64 " delta_last %" PRIi64 " func %p arg %p\n", t->scheduled_time_, delta_now, delta_last, t->callback_, t->arg_); last = t->scheduled_time_; } } } } #include <lib/console.h> static int cmd_timers(int argc, const cmd_args* argv, uint32_t flags) { const size_t timer_buffer_size = PAGE_SIZE; // allocate a buffer to dump the timer queue into to avoid reentrancy issues with the // timer spinlock char* buf = static_cast<char*>(malloc(timer_buffer_size)); if (!buf) { return ZX_ERR_NO_MEMORY; } dump_timer_queues(buf, timer_buffer_size); printf("%s", buf); free(buf); return 0; } STATIC_COMMAND_START STATIC_COMMAND_MASKED("timers", "dump the current kernel timer queues", &cmd_timers, CMD_AVAIL_NORMAL) STATIC_COMMAND_END(kernel)
33.647368
100
0.675009
casey
711020af09a3f06b18191dc1e7c0b122afa1cf7f
4,088
cpp
C++
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
11
2016-12-11T02:17:58.000Z
2021-11-24T03:27:01.000Z
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
null
null
null
src/plugin/xlog/xlog.cpp
willenchou/xservers
0f8b262571ed7c0465d90ef807a9a540e97de379
[ "Apache-2.0" ]
2
2016-12-11T10:48:00.000Z
2021-07-10T07:10:55.000Z
#include "xlog.h" #ifdef OS_WIN #include <windows.h> #endif #include <include/xservice_intf.h> namespace x { LogService* _logService = new LogService(); LogIocService* _logIocService = new LogIocService(); LogMngService* _logMngService = new LogMngService(); LogService::LogService(){ isSync_ = true; level_ = LOG_LEVEL_DEBUG; } LogService::~LogService(){ } void LogService::Init(){ CreateLogDir(); XMLElement* config = _logIocService->GetConfig(); if(config) { XMLElement* argsNode = config->FirstChildElement("args"); if(argsNode) { isSync_ = argsNode->BoolAttribute("sync"); level_ = argsNode->IntAttribute("level"); } } } void LogService::UnInit(){ } void LogService::Start(){ if(!isSync_){ Thread::Start(); } } void LogService::Stop(){ if(!isSync_){ Thread::Stop(); } } long LogService::Run(){ while(1){ { ScopedLock lock(mutex_); LogItem* item = queue_.Top(); while(item){ WriteLog(item->time, item->level, item->content); queue_.Pop(); item = queue_.Top(); } } event_.Wait(100); } return 0L; } void LogService::AddLog(char* owner, int level, const char* location, char* content){ if(level < level_) return; time_t currTime; time(&currTime); struct tm * timeinfo = localtime(&currTime); char logStr[1024]; snprintf(logStr, sizeof(logStr)-1, "[%02d:%02d:%02d][%d][%s][%s][%s]", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, level, owner, content, location); if(isSync_){ WriteLog(currTime, level, logStr); }else{ ScopedLock lock(mutex_); LogItem* item = queue_.Bottom(); if(item){ item->time = currTime; item->level = level; strncpy(item->content, logStr, sizeof(item->content)); } queue_.Push(); event_.Reset(); } } void LogService::CreateLogDir(){ if(ACCESS(LOG_DIR, 0) != 0){ MKDIR(LOG_DIR); } } void LogService::WriteLog(time_t time, int level, char* str){ struct tm * timeinfo = localtime(&time); char filePath[1024]; snprintf(filePath, sizeof(filePath), "%s/%04d-%02d-%02d-%s.log", LOG_DIR, timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, _logIocService->GetArg(ARGS_APP_NAME)); FILE* f = fopen(filePath, "a+"); if(f){ fputs(str, f); fputs("\n", f); fclose(f); } if(level == LOG_LEVEL_DEBUG) printf("%s\n", str); } LogIocService::LogIocService(){ } LogIocService::~LogIocService(){ } IContainer* LogIocService::GetContainer() { return container_; } XMLElement* LogIocService::GetConfig() { return config_; } const char* LogIocService::GetArg(const char* name) { ArgMap::iterator it = args_.find(std::string(name)); if(it != args_.end()){ return it->second.c_str(); } return NULL; } void LogIocService::SetContainer(IContainer* container) { container_ = container; } void LogIocService::SetConfig(XMLElement* config) { config_ = config; } void LogIocService::SetArg(const char* name, const char* value) { args_[std::string(name)] = std::string(value); } LogMngService::LogMngService(){ } LogMngService::~LogMngService(){ } void LogMngService::OnEvent(int eventType){ switch(eventType){ case MANAGER_EVENT_INIT : if(_logService) _logService->Init(); break; case MANAGER_EVENT_START : if(_logService) _logService->Start(); break; case MANAGER_EVENT_STOP : if(_logService) _logService->Stop(); break; case MANAGER_EVENT_UNINIT : if(_logService) _logService->UnInit(); break; } } }//namespace x void FUNC_CALL GetPluginInfo(x::PluginInfo& info){ info.caption = PLUGIN_LOG; info.version = __DATE__""__TIME__; } bool FUNC_CALL GetServiceInfo(int index, x::ServiceInfo& info){ switch(index){ case 0: info.id = SID_LOG; info.caption = ""; info.version = __DATE__":"__TIME__; return true; default:return false; } } x::IService* FUNC_CALL GetService(const char* id){ if(strcmp(id, SID_LOG) == 0){ return x::_logService; }else if(strcmp(id, SID_IOC) == 0){ return x::_logIocService; }else if(strcmp(id, SID_MANAGER) == 0){ return x::_logMngService; } return NULL; }
18.497738
85
0.670254
willenchou
711168fa4b89ea9e14d489e15a76ce0962562e54
780
cpp
C++
P11725.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
6
2020-04-08T09:05:38.000Z
2022-01-20T08:09:48.000Z
P11725.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
null
null
null
P11725.cpp
daily-boj/SkyLightQP
5038819b6ad31f94d84a66c7679c746a870bb857
[ "Unlicense" ]
1
2020-05-23T21:17:10.000Z
2020-05-23T21:17:10.000Z
#include <iostream> #include <vector> using namespace std; vector<int> graph[100001] = {}; int check[100001] = {}; int parents[100001] = {}; void dfs(int start) { check[start] = 1; for(int i = 0; i < graph[start].size(); i++) { int node = graph[start][i]; if(check[node]) continue; parents[node] = start; dfs(node); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int N; cin >> N; for(int i = 0; i < (N - 1); i++) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } check[1] = 1; parents[1] = 0; dfs(1); for(int i = 2; i <= N; i++) { cout << parents[i] << "\n"; } return 0; }
16.595745
50
0.479487
daily-boj
7111a51a8969653c67e938d64d7a78de970f5b35
3,297
cpp
C++
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
src/obproxy/prometheus/ob_prometheus_utils.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX PROXY #include "prometheus/ob_prometheus_utils.h" #include "lib/oblog/ob_log.h" namespace oceanbase { namespace obproxy { namespace prometheus { using namespace oceanbase::common; const char* ObProxyPrometheusUtils::get_metric_lable(ObPrometheusMetrics metric) { switch(metric) { case PROMETHEUS_PREPARE_SEND_REQUEST_TIME: return "prepare"; case PROMETHEUS_SERVER_PROCESS_REQUEST_TIME: return "server"; case PROMETHEUS_REQUEST_TOTAL_TIME: return "total"; default: return "UNKNOWN"; } } const char* ObProxyPrometheusUtils::get_type_lable(ObPrometheusEntryType type) { switch(type) { case TBALE_ENTRY: return "table_entry"; case PARTITION_ENTRY: return "partition_entry"; case ROUTE_ENTRY: return "route_entry"; default: return "UNKNOWN"; } } int ObProxyPrometheusUtils::calc_buf_size(ObVector<ObPrometheusLabel> *labels, uint32_t &buf_size) { int ret = OB_SUCCESS; buf_size = 0; for (int i = 0; i < labels->size(); i++) { ObPrometheusLabel &label = labels->at(i); if (label.is_value_need_alloc()) { buf_size += label.get_value().length(); } } return ret; } int ObProxyPrometheusUtils::copy_label_hash(ObVector<ObPrometheusLabel> *labels, ObVector<ObPrometheusLabel> &dst_labels, unsigned char *buf, uint32_t buf_len) { int ret = OB_SUCCESS; uint64_t offset = 0; for (int i = 0; i < labels->size() && OB_SUCC(ret); i++) { ObPrometheusLabel &label = labels->at(i); ObPrometheusLabel new_label; new_label.set_key(label.get_key()); if (label.is_value_need_alloc()) { if (buf != NULL && offset + label.get_value().length() <= buf_len) { ObString value; MEMCPY(buf + offset, label.get_value().ptr(), label.get_value().length()); value.assign_ptr(reinterpret_cast<char *>(buf + offset), label.get_value().length()); offset += label.get_value().length(); new_label.set_value(value); } else { ret = OB_ERR_UNEXPECTED; LOG_WARN("copy label meet unexpected error", K(offset), "value len", label.get_value().length(), K(buf_len)); } } else { new_label.set_value(label.get_value()); } if (OB_FAIL(dst_labels.push_back(new_label))) { LOG_WARN("put label into metric failed", K(new_label), K(ret)); } } return ret; } ObVector<ObPrometheusLabel>& ObProxyPrometheusUtils::get_thread_label_vector() { static __thread ObVector<ObPrometheusLabel> prometheus_thread_labels(10); return prometheus_thread_labels; } } // end of namespace prometheus } // end of namespace obproxy } // end of namespace oceanbase
28.669565
98
0.680619
stutiredboy
7115d1c31aa36071e9a5e88a4f00c823330369a0
3,636
cpp
C++
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
1
2018-12-06T00:45:23.000Z
2018-12-06T00:45:23.000Z
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
null
null
null
src/Button.cpp
18/PasswordManager
85a6fb03f1fea6a8494a13ccce5550ab9b414811
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Krystian Stasiowski #include "Button.h" Button::Button(unsigned x, unsigned y, Color textcolor, Color backgroundcolor, Color selectedtextcolor, Color selectedbackgroundcolor, Color activatedtextcolor, const std::string& text, const std::string& selectedtext, const std::string& activatedtext, const std::function<void()>& activateaction, const std::function<void()>& deactivateaction, bool centered, bool show, bool activated) : Object(x, y, show), textcolor_(textcolor), backgroundcolor_(backgroundcolor), selectedtextcolor_(selectedtextcolor), selectedbackgroundcolor_(selectedbackgroundcolor), activatedtextcolor_(activatedtextcolor), text_(text), selectedtext_(selectedtext), activatedtext_(activatedtext), activateaction_(activateaction), deactivateaction_(deactivateaction), activated_(activated), selected_(false) { if (centered) x_ = (Console::GetSize().X - text.length()) / 2; if (show) Show(true); } void Button::Select() { Select(!selected_); } void Button::Select(bool select) { selected_ = select; if (!select) { if (activated_) { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, backgroundcolor_); } else { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } } else { if (activated_) { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, text_.length()); Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } } } void Button::Press() { Press(!activated_); } bool Button::Hidden() const { return !show_; } void Button::Press(bool press) { activated_ = press; if (!press) { if (selected_) { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, activatedtext_.length()); Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } deactivateaction_(); } else { if (selected_) { Console::ClearAt(x_, y_, selectedtext_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } else { Console::ClearAt(x_, y_, text_.length()); Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, selectedbackgroundcolor_); } activateaction_(); } } void Button::Show(bool show) { show_ = show; if (show) { if (activated_) { Console::WriteLineAt(x_, y_, activatedtext_, activatedtextcolor_, backgroundcolor_); } else if (selected_) { Console::WriteLineAt(x_, y_, selectedtext_, selectedtextcolor_, selectedbackgroundcolor_); } else { Console::WriteLineAt(x_, y_, text_, textcolor_, backgroundcolor_); } } else { if (activated_) { Console::ClearAt(x_, y_, activatedtext_.length()); } else if (selected_) { Console::ClearAt(x_, y_, selectedtext_.length()); } else { Console::ClearAt(x_, y_, text_.length()); } } } bool Button::Activated() const { return activated_; } bool Button::Selected() const { return selected_; } void Button::Move(int x, int y) { bool show = show_; if (show) Show(false); x_ = x; y_ = y; if (show) Show(true); }
24.734694
393
0.671617
18
711a1142d59343cc79012d7dee410650f9de72a6
369
cpp
C++
leetcode/338. Counting Bits/s1.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/338. Counting Bits/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/338. Counting Bits/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/counting-bits // Author: github.com/lzl124631x // Time: O(N) // Space: O(1) class Solution { public: vector<int> countBits(int num) { vector<int> ans(num + 1); for (int i = 1; i <= num; i *= 2) { ans[i] = 1; for (int j = 1; j < i && i + j <= num; ++j) ans[i + j] = ans[i] + ans[j]; } return ans; } };
24.6
79
0.520325
joycse06
711ac4d152e37cfec06cbed271607d3fe49f4d05
161
hpp
C++
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
osc-seq-cpp/src/filesystem/filesystem.hpp
Acaruso/osc-seq-cpp
14d2d5ce0fdad8d183e19781a279f9442db9c79f
[ "MIT" ]
null
null
null
#pragma once #include "../store/store.hpp" #include <string> void save_file(std::string path, Store& store); void open_file(std::string path, Store& store);
16.1
47
0.714286
Acaruso
7120d2b8ad8f6661da8a204eac1f2483f0a485c1
1,449
cpp
C++
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
11
2020-04-25T02:37:13.000Z
2021-08-08T13:08:36.000Z
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
null
null
null
primary/grmath.cpp
Wiladams/nd
9575e050c18225a138255a39de6c50954db2e731
[ "MIT" ]
null
null
null
#include "grmath.h" vec3 random_in_unit_disk() { while (true) { auto p = vec3(random_double_range(-1, 1), random_double_range(-1, 1), 0); if (p.lengthSquared() >= 1) continue; return p; } } vec3 random_unit_vector() { auto a = random_double_range(0, 2 * maths::Pi); auto z = random_double_range(-1, 1); auto r = sqrt(1 - z * z); return vec3(r * cos(a), r * sin(a), z); } vec3 random_in_unit_sphere() { while (true) { //auto p = vec3::random(-1, 1); auto p = random_vec3_range(-1, 1); if (p.lengthSquared() >= 1) continue; return p; } } vec3 random_in_hemisphere(const vec3& normal) { vec3 in_unit_sphere = random_in_unit_sphere(); if (dot(in_unit_sphere, normal) > 0.0) // In the same hemisphere as the normal return in_unit_sphere; else return -in_unit_sphere; } // These are here to be universal, but should probably // be in p5.cpp, or a specific app, like threed //template <> template <> vec<3, int> ::vec(const vec<3, float>& v) : x(int(v.x + .5f)), y(int(v.y + .5f)), z(int(v.z + .5f)) {} //template <> template <> vec<3, float>::vec(const vec<3, int>& v) : x((float)v.x), y((float)v.y), z((float)v.z) {} //template <> template <> vec<2, int> ::vec(const vec<2, float>& v) : x(int(v.x + .5f)), y(int(v.y + .5f)) {} //template <> template <> vec<2, float>::vec(const vec<2, int>& v) : x((float)v.x), y((float)v.y) {}
33.697674
129
0.585921
Wiladams
71255f887615f6b95557818672f14a96ac2dd586
5,904
hpp
C++
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
null
null
null
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
8
2021-12-30T22:07:39.000Z
2022-02-04T21:13:53.000Z
include/Simple-Utility/functional.hpp
DNKpp/Simple-Utility
db2d6cb1cc3849704f18272f8ce2d2bc05ad06a7
[ "BSL-1.0" ]
1
2020-08-19T13:02:58.000Z
2020-08-19T13:02:58.000Z
// Copyright Dominic Koepke 2019 - 2022. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #ifndef SL_UTILITY_FUNCTIONAL_HPP #define SL_UTILITY_FUNCTIONAL_HPP #pragma once #include <concepts> #include <functional> #include <type_traits> namespace sl::functional::detail { template <class TDerived> struct pipe; template <class TFunc1, class TFunc2> class composition_fn : public pipe<composition_fn<TFunc1, TFunc2>> { public: using function_type1 = TFunc1; using function_type2 = TFunc2; template <class TArg1, class TArg2> constexpr composition_fn ( TArg1&& arg1, TArg2&& arg2 ) noexcept(std::is_nothrow_constructible_v<TFunc1, TArg1> && std::is_nothrow_constructible_v<TFunc2, TArg2>) : m_Func1{ std::forward<TArg1>(arg1) }, m_Func2{ std::forward<TArg2>(arg2) } {} template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... v ) const noexcept(noexcept(std::invoke( std::declval<const TFunc2&>(), std::invoke(std::declval<const TFunc1&>(), std::forward<TArgs>(v)...) ))) { return std::invoke( m_Func2, std::invoke(m_Func1, std::forward<TArgs>(v)...) ); } template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... v ) noexcept(noexcept(std::invoke( std::declval<TFunc2&>(), std::invoke(std::declval<TFunc1&>(), std::forward<TArgs>(v)...) ))) { return std::invoke( m_Func2, std::invoke(m_Func1, std::forward<TArgs>(v)...) ); } private: [[no_unique_address]] TFunc1 m_Func1{}; [[no_unique_address]] TFunc2 m_Func2{}; }; template <class TFunc1, class TFunc2> composition_fn(TFunc1, TFunc2) -> composition_fn<std::remove_cvref_t<TFunc1>, std::remove_cvref_t<TFunc2>>; template <class TDerived> struct pipe { template <class TOther> constexpr auto operator | ( TOther&& other ) && noexcept(noexcept(composition_fn{ static_cast<TDerived&&>(*this), std::forward<TOther>(other) })) { return composition_fn{ static_cast<TDerived&&>(*this), std::forward<TOther>(other) }; } template <class TOther> constexpr auto operator | ( TOther&& other ) const & noexcept(noexcept(composition_fn{ static_cast<const TDerived&>(*this), std::forward<TOther>(other) })) { return composition_fn{ static_cast<const TDerived&>(*this), std::forward<TOther>(other) }; } template <class TLhs> friend constexpr auto operator | ( TLhs&& lhs, pipe&& rhs ) noexcept(noexcept(composition_fn{ std::forward<TLhs>(lhs), static_cast<TDerived&&>(rhs) })) requires (!requires { lhs.operator|(std::move(rhs)); }) { return composition_fn{ std::forward<TLhs>(lhs), static_cast<TDerived&&>(rhs) }; } template <class TLhs> friend constexpr auto operator | ( TLhs&& lhs, const pipe& rhs ) noexcept(noexcept(composition_fn{ std::forward<TLhs>(lhs), static_cast<const TDerived&>(rhs) })) requires (!requires { lhs.operator|(rhs); }) { return composition_fn{ std::forward<TLhs>(lhs), static_cast<const TDerived&>(rhs) }; } }; } namespace sl::functional { /** * \brief Helper type which accepts a functional type and enables pipe chaining. * \tparam TFunc The functional type. */ template <class TFunc> class transform_fn : public detail::pipe<transform_fn<TFunc>> { public: using function_type = TFunc; /** * \brief Forwards the constructor arguments to the internal functional object. * \tparam TArgs The constructor argument types. * \param args The constructor arguments. */ template <class... TArgs> requires std::constructible_from<TFunc, TArgs...> explicit constexpr transform_fn ( TArgs&&... args ) noexcept(std::is_nothrow_constructible_v<TFunc, TArgs...>) : m_Func{ std::forward<TArgs>(args)... } {} /** * \brief Invokes the internal functional with the given arguments. * \tparam TArgs The argument types. * \param args The arguments. * \return Returns as received by invocation. */ template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... args ) const noexcept(noexcept(std::invoke(std::declval<const TFunc&>(), args...))) { return std::invoke(m_Func, std::forward<TArgs>(args)...); } /** * \copydoc operator()() */ template <class... TArgs> constexpr decltype(auto) operator () ( TArgs&&... args ) noexcept(noexcept(std::invoke(std::declval<TFunc&>(), args...))) { return std::invoke(m_Func, std::forward<TArgs>(args)...); } private: [[no_unique_address]] TFunc m_Func{}; }; /** * \brief Deduction guide. * \tparam TFunc Type of the given functional. */ template <class TFunc> transform_fn(TFunc) -> transform_fn<std::remove_cvref_t<TFunc>>; /** * \brief Functional object which static_cast the given argument to the target type on invocation. * \tparam TTarget The target type. */ template <class TTarget> inline constexpr transform_fn as{ []<class T>(T&& v) -> TTarget { return static_cast<TTarget>(std::forward<T>(v)); } }; /** * \brief Functional object which retrieves an object of a specific type from a tuple-like argument. * \tparam T The type to be retrieved. */ template <class T> inline constexpr transform_fn get{ []<class TTuple>(TTuple&& v) -> decltype(auto) { using std::get; return get<T>(std::forward<TTuple>(v)); } }; /** * \brief Functional object which retrieves an object at a specific index from a tuple-like argument. * \tparam VIndex The index of type to be retrieved. */ template <std::size_t VIndex> inline constexpr transform_fn get_at{ []<class TTuple>(TTuple&& v) -> decltype(auto) { using std::get; return get<VIndex>(std::forward<TTuple>(v)); } }; } #endif
23.902834
114
0.664634
DNKpp
712ba4926cb9a14eb7070608306e25d84e34ba23
1,708
cpp
C++
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/TutorialHUD/Widget_KeyInput/Widget_KeyInputItem.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Widget_KeyInputItem.h" #include "Components/TextBlock.h" #include "Components/Image.h" void UWidget_KeyInputItem::NativeConstruct() { Super::NativeConstruct(); m_pKeyText = Cast<UTextBlock>(GetWidgetFromName(TEXT("KeyText"))); if (m_pKeyText == nullptr) { ULOG(TEXT("KeyText is nullptr")); return; } m_pKeyImg = Cast<UImage>(GetWidgetFromName(TEXT("KeyImg"))); if (m_pKeyImg == nullptr) { ULOG(TEXT("KeyImg is nullptr")); return; } } void UWidget_KeyInputItem::NativeDestruct() { Super::NativeDestruct(); if (m_pKeyText != nullptr) { if (m_pKeyText->IsValidLowLevel()) { m_pKeyText = nullptr; } } if (m_pKeyImg != nullptr) { if (m_pKeyImg->IsValidLowLevel()) { m_pKeyImg = nullptr; } } } void UWidget_KeyInputItem::NativeTick(const FGeometry& MyGeometry, float InDeltaTime) { Super::NativeTick(MyGeometry, InDeltaTime); } void UWidget_KeyInputItem::SetKeyText(const FText sKeyText, UTexture2D* pKeyImg) { if (m_pKeyText != nullptr) { m_sKeyState = sKeyText; if (pKeyImg == nullptr) { m_pKeyImg->SetBrushFromTexture(nullptr); m_pKeyImg->SetVisibility(ESlateVisibility::Hidden); m_pKeyText->SetVisibility(ESlateVisibility::SelfHitTestInvisible); m_pKeyText->SetText(sKeyText); } else { m_pKeyText->SetVisibility(ESlateVisibility::Hidden); m_pKeyImg->SetVisibility(ESlateVisibility::SelfHitTestInvisible); m_pKeyImg->SetBrushFromTexture(pKeyImg, true); } } } FText UWidget_KeyInputItem::GetKeyText() { if (m_pKeyText == nullptr) { ULOG(TEXT("KeyText is nullptr")); return FText::GetEmpty(); } return m_sKeyState; }
19.860465
85
0.719555
Bornsoul
7131f890a3ef8d9bcf687f797837a21c1b13a034
625
cpp
C++
C++/1259-Handshakes-That-Dont-Cross/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/1259-Handshakes-That-Dont-Cross/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/1259-Handshakes-That-Dont-Cross/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
typedef long long ll; const ll kMod = 1000000007LL; class Solution { public: int numberOfWays(int num_people) { // convert it to a smaller problem vector<ll> memo(num_people + 1, 0); return static_cast<int>(helper(num_people, &memo)); } private: ll helper(int n, vector<ll> * memo) { if (n == 0 || n == 2) return 1; if((*memo)[n] != 0) return (*memo)[n]; ll ans = 0; for(int i = 2; i <= n; i += 2) { ans = (ans + helper(i - 2, memo) * helper(n - i, memo) % kMod) % kMod; } (*memo)[n] = ans; return ans; } };
27.173913
82
0.5008
wyaadarsh
7133ba40787d62c5e2c79058379ec01cab13c57b
8,259
cpp
C++
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/vision/features/feature_channels/hog_extractor.cpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
/* * hog_extractor.cpp * * Created on: Mar 22, 2012 * Author: Juergen Gall, mdantone */ #include <deque> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "hog_extractor.h" #include "cpp/vision/min_max_filter.hpp" using namespace std; using namespace cv; namespace vision { namespace features { namespace feature_channels { void HOGExtractor::extractFeatureChannels9(const cv::Mat& img, std::vector<cv::Mat>& Channels, bool use_max_filter) { // 9 feature channels // 3+9 channels: Lab + HOGlike features with 9 bins const int FEATURE_CHANNELS = 9; Channels.resize(FEATURE_CHANNELS); for (int c=0; c<FEATURE_CHANNELS; ++c) Channels[c].create(img.rows,img.cols, CV_8U); if( MIN(img.cols, img.rows) < 5 ){ cout <<"image is too small for HoG Extractor"<< endl; return; } Mat I_x; Mat I_y; // |I_x|, |I_y| Sobel(img,I_x,CV_16S,1,0,3); Sobel(img,I_y,CV_16S,0,1,3); //convertScaleAbs( I_x, Channels[3], 0.25); //convertScaleAbs( I_y, Channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; Mat Iorient(img.rows,img.cols, CV_8UC1); Mat Imagn(img.rows,img.cols, CV_8UC1); if (I_x.isContinuous() && I_y.isContinuous() && Iorient.isContinuous() && Imagn.isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Iorient.ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( ( atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f ) * 80 ); } } // Magnitude of gradients for (int y = 0; y < rows; y++) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Imagn.ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(Iorient, Imagn, Channels, 0); //max filter if( use_max_filter ) { for(int c=0; c<Channels.size(); ++c) ::vision::MinMaxFilter::maxfilt(Channels[c], 5); } } void HOGExtractor::extractFeatureChannels15(const cv::Mat& img, std::vector<cv::Mat>& Channels) { // 9 feature channels // 3+9 channels: Lab + HOGlike features with 9 bins const int FEATURE_CHANNELS = 15; Channels.resize(FEATURE_CHANNELS); for (int c=0; c<FEATURE_CHANNELS; ++c) Channels[c].create(img.rows,img.cols, CV_8U); if( MIN(img.cols, img.rows) < 5 ){ cout <<"image is too small for HoG Extractor"<< endl; return; } Mat I_x; Mat I_y; // Get intensity cvtColor( img, Channels[0], CV_RGB2GRAY ); // |I_x|, |I_y| Sobel(Channels[0],I_x,CV_16S,1,0,3); Sobel(Channels[0],I_y,CV_16S,0,1,3); //convertScaleAbs( I_x, Channels[3], 0.25); //convertScaleAbs( I_y, Channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; if (I_x.isContinuous() && I_y.isContinuous() && Channels[1].isContinuous() && Channels[2].isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Channels[1].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( ( atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f ) * 80 ); } } // Magnitude of gradients for (int y = 0; y < rows; y++) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = Channels[2].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(Channels[1], Channels[2], Channels, 3); // |I_xx|, |I_yy| //Sobel(Channels[0],I_x,CV_16S, 2,0,3); //convertScaleAbs( I_x, Channels[5], 0.25); //Sobel(Channels[0],I_y,CV_16S, 0,2,3); //convertScaleAbs( I_y, Channels[6], 0.25); // L, a, b Mat imgRGB(img.size(), CV_8UC3); cvtColor( img, imgRGB, CV_RGB2Lab ); // Split color channels // overwriting the first 3 channels // Mat out[] = { Channels[0], Channels[1], Channels[2] }; // int from_to[] = { 0,0 , 1,1, 2,2 }; // mixChannels( &imgRGB, 1, out, 3, from_to, 3 ); split(imgRGB, &Channels[0]); // min filter for(int c=0; c<3; ++c) MinMaxFilter::minfilt(Channels[c], Channels[c+12], 5); //max filter for(int c=0; c<12; ++c) MinMaxFilter::maxfilt(Channels[c], 5); #if 0 // Debug namedWindow( "Show", CV_WINDOW_AUTOSIZE ); for(int i=0; i<FEATURE_CHANNELS; i++) { imshow( "Show", Channels[i] ); waitKey(0); } #endif } void HOGExtractor::extractFeatureChannels(const Mat& img, std::vector<cv::Mat>& channels) { // 32 feature channels // 7+9 channels: L, a, b, |I_x|, |I_y|, |I_xx|, |I_yy|, HOGlike features // with 9 bins (weighted orientations 5x5 neighborhood) // 16+16 channels: minfilter + MinMaxFilter::maxfilter on 5x5 neighborhood assert( img.channels() == 3); channels.resize(32); for(int c=0; c<32; ++c) channels[c].create(img.rows,img.cols, CV_8U); Mat I_x; Mat I_y; // Get intensity cvtColor( img, channels[0], CV_RGB2GRAY ); // |I_x|, |I_y| Sobel(channels[0],I_x,CV_16S,1,0,3); Sobel(channels[0],I_y,CV_16S,0,1,3); convertScaleAbs( I_x, channels[3], 0.25); convertScaleAbs( I_y, channels[4], 0.25); int rows = I_x.rows; int cols = I_y.cols; if (I_x.isContinuous() && I_y.isContinuous() && channels[1].isContinuous() && channels[2].isContinuous()) { cols *= rows; rows = 1; } for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = channels[1].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { // Avoid division by zero float tx = (float)ptr_Ix[x] + (float)copysign(0.000001f, (float)ptr_Ix[x]); // Scaling [-pi/2 pi/2] -> [0 80*pi] ptr_out[x]=saturate_cast<uchar>( (atan((float)ptr_Iy[x]/tx)+3.14159265f/2.0f) * 80); } } // Magnitude of gradients for( int y = 0; y < rows; y++ ) { short* ptr_Ix = I_x.ptr<short>(y); short* ptr_Iy = I_y.ptr<short>(y); uchar* ptr_out = channels[2].ptr<uchar>(y); for( int x = 0; x < cols; x++ ) { ptr_out[x] = saturate_cast<uchar>( sqrt((float)ptr_Ix[x]*(float)ptr_Ix[x] + (float)ptr_Iy[x]*(float)ptr_Iy[x])); } } // 9-bin HOG feature stored at vImg[7] - vImg[15] hog.extractOBin(channels[1], channels[2], channels, 7); // |I_xx|, |I_yy| Sobel(channels[0],I_x,CV_16S, 2,0,3); convertScaleAbs( I_x, channels[5], 0.25); Sobel(channels[0],I_y,CV_16S, 0,2,3); convertScaleAbs( I_y, channels[6], 0.25); // L, a, b Mat img_; cvtColor( img, img_, CV_RGB2Lab ); // Split color channels Mat out[] = { channels[0], channels[1], channels[2] }; int from_to[] = { 0,0 , 1,1, 2,2 }; mixChannels( &img_, 1, out, 3, from_to, 3 ); // int num_treads = boost::thread::hardware_concurrency(); { // boost::thread_pool::executor e(num_treads); // min filter for(int c=0; c<16; ++c){ // e.submit(boost::bind(&HOGExtractor::minfilt, // channels[old_size+c], channels[old_size+c+16], 5 )); MinMaxFilter::minfilt(channels[c], channels[c+16], 5); } // e.join_all(); } { // boost::thread_pool::executor e(num_treads); // max filter for(int c=0; c<16; ++c){ // e.submit(boost::bind(&HOGExtractor::MinMaxFilter::maxfilt, channels[old_size+c], 5 )); MinMaxFilter::maxfilt(channels[c], 5); } // e.join_all(); } #if 0 // Debug namedWindow( "Show", CV_WINDOW_AUTOSIZE ); for(int i=0; i<32; i++) { imshow( "Show", channels[old_size+i] ); waitKey(0); } #endif } } // namespace vision } // namespace features } // namespace feature_channels
26.053628
93
0.61097
umariqb
7134a171029c8236655c90b40fb7939124c1e53c
12,145
cpp
C++
samples/WIoT-WM01_WM-N400MSE/WIZnet-IoTShield-WM-N400MSE-SMS/main.cpp
Wiznet/wiznet-iot-shield-mbed-kr
5fbaa28136be6106e216c0a2838bbfb4e5cf6adb
[ "Apache-2.0" ]
13
2019-03-26T12:07:12.000Z
2021-09-23T08:35:51.000Z
samples/WIoT-WM01_WM-N400MSE/WIZnet-IoTShield-WM-N400MSE-SMS/main.cpp
Wiznet/wiznet-iot-shield-mbed-kr
5fbaa28136be6106e216c0a2838bbfb4e5cf6adb
[ "Apache-2.0" ]
null
null
null
samples/WIoT-WM01_WM-N400MSE/WIZnet-IoTShield-WM-N400MSE-SMS/main.cpp
Wiznet/wiznet-iot-shield-mbed-kr
5fbaa28136be6106e216c0a2838bbfb4e5cf6adb
[ "Apache-2.0" ]
14
2019-04-20T05:21:46.000Z
2021-11-04T02:20:46.000Z
/* WIZnet IoT Shield Cat.M1 Sample code for Arm MBED * Copyright (c) 2019 WIZnet Co., Ltd. * SPDX-License-Identifier: Apache-2.0 */ /* * 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 "mbed.h" #include <string> #define RET_OK 1 #define RET_NOK -1 #define DEBUG_ENABLE 1 #define DEBUG_DISABLE 0 #define ON 1 #define OFF 0 #define MAX_BUF_SIZE 1024 #define WM01_APN_PROTOCOL_IPv4 1 #define WM01_APN_PROTOCOL_IPv6 2 #define WM01_DEFAULT_TIMEOUT 1000 #define WM01_CONNECT_TIMEOUT 15000 #define WM01_SEND_TIMEOUT 500 #define WM01_RECV_TIMEOUT 500 #define WM01_APN_PROTOCOL WM01_APN_PROTOCOL_IPv6 #define WM01_DEFAULT_BAUD_RATE 115200 #define WM01_PARSER_DELIMITER "\r\n" #define CATM1_APN_SKT "lte-internet.sktelecom.com" #define CATM1_DEVICE_NAME_WM01 "WM01" #define DEVNAME CATM1_DEVICE_NAME_WM01 #define devlog(f_, ...) if(CATM1_DEVICE_DEBUG == DEBUG_ENABLE) { pc.printf("\r\n[%s] ", DEVNAME); pc.printf((f_), ##__VA_ARGS__); } #define myprintf(f_, ...) {pc.printf("\r\n[MAIN] "); pc.printf((f_), ##__VA_ARGS__);} /* Pin configuraiton */ // Cat.M1 #define MBED_CONF_IOTSHIELD_CATM1_TX D8 #define MBED_CONF_IOTSHIELD_CATM1_RX D2 #define MBED_CONF_IOTSHIELD_CATM1_RESET D7 #define MBED_CONF_IOTSHIELD_CATM1_PWRKEY D9 // Sensors #define MBED_CONF_IOTSHIELD_SENSOR_CDS A0 #define MBED_CONF_IOTSHIELD_SENSOR_TEMP A1 /* Debug message settings */ #define WM01_PARSER_DEBUG DEBUG_DISABLE #define CATM1_DEVICE_DEBUG DEBUG_ENABLE /* SMS */ #define SMS_EOF 0x1A #define MAX_SMS_SIZE 100 // have to modify phone number char phone_number[] = "010xxxxxxxx"; char send_message[] = "WIZnet Cat.M1 IoT shield is powered on"; // Functions: Print information void printInfo(void); // Functions: Module Status void waitCatM1Ready(void); int8_t setEchoStatus_WM01(bool onoff); int8_t getUsimStatus_WM01(void); int8_t getNetworkStatus_WM01(void); // Functions: SMS int8_t initSMS_WM01(void); int8_t sendSMS_WM01(char *da, char *msg, int len); int checkRecvSMS_WM01(void); int8_t recvSMS_WM01(int msg_idx, char *datetime, char *da, char *msg); int8_t deleteSMS_WM01(int msg_idx); int8_t deleteAllSMS_WM01(int delflag); Serial pc(USBTX, USBRX); // USB debug UARTSerial *_serial; // Cat.M1 module ATCmdParser *_parser; DigitalOut _RESET_WM01(MBED_CONF_IOTSHIELD_CATM1_RESET); DigitalOut _PWRKEY_WM01(MBED_CONF_IOTSHIELD_CATM1_PWRKEY); void serialPcInit(void) { pc.baud(115200); pc.format(8, Serial::None, 1); } void serialDeviceInit(PinName tx, PinName rx, int baudrate) { _serial = new UARTSerial(tx, rx, baudrate); } void serialAtParserInit(const char *delimiter, bool debug_en) { _parser = new ATCmdParser(_serial); _parser->debug_on(debug_en); _parser->set_delimiter(delimiter); _parser->set_timeout(WM01_DEFAULT_TIMEOUT); } void catm1DeviceInit(void) { serialDeviceInit( MBED_CONF_IOTSHIELD_CATM1_TX, MBED_CONF_IOTSHIELD_CATM1_RX, WM01_DEFAULT_BAUD_RATE); serialAtParserInit( WM01_PARSER_DELIMITER, WM01_PARSER_DEBUG); } void catm1DeviceReset_WM01(void) { _RESET_WM01 = 1; _PWRKEY_WM01 = 1; wait_ms(300); _RESET_WM01 = 0; _PWRKEY_WM01 = 0; wait_ms(400); _RESET_WM01 = 1; wait_ms(1000); } // ---------------------------------------------------------------- // Main routine // ---------------------------------------------------------------- int main() { serialPcInit(); catm1DeviceInit(); myprintf("Waiting for Cat.M1 Module Ready...\r\n"); catm1DeviceReset_WM01(); waitCatM1Ready(); wait_ms(5000); myprintf("System Init Complete\r\n"); printInfo(); setEchoStatus_WM01(OFF); getUsimStatus_WM01(); getNetworkStatus_WM01(); // SMS configuration if(initSMS_WM01() != RET_OK) { myprintf("[SMS Init] failed\r\n"); } // Send a message if(sendSMS_WM01(phone_number, send_message, strlen(send_message)) == RET_OK) { myprintf("[SMS Send] to %s, \"%s\"\r\n", phone_number, send_message); } #if 0 // Delete messages deleteAllSMS_WM01(3); #endif char date_time[25] = {0, }; char dest_addr[20] = {0, }; char recv_message[MAX_SMS_SIZE] = {0, }; int msg_idx; while(1) { // SMS receive check msg_idx = checkRecvSMS_WM01(); if(msg_idx > RET_NOK) // SMS received { // Receive a message memset(recv_message, 0x00, MAX_SMS_SIZE); if(recvSMS_WM01(msg_idx, date_time, dest_addr, recv_message) == RET_OK) { myprintf("[SMS Recv] from %s, %s, \"%s\"\r\n", dest_addr, date_time, recv_message); } } } } // ---------------------------------------------------------------- // Functions: Print information // ---------------------------------------------------------------- void printInfo(void) { myprintf("WIZnet IoT Shield for Arm MBED"); myprintf("LTE Cat.M1 Version"); myprintf("================================================="); myprintf(">> Target Board: WIoT-WM01 (Woorinet WM-N400MSE)"); myprintf(">> Sample Code: SMS Test"); myprintf("=================================================\r\n"); } // ---------------------------------------------------------------- // Functions: Cat.M1 Status // ---------------------------------------------------------------- void waitCatM1Ready(void) { while(1) { if(_parser->send("AT") && _parser->recv("OK")) { myprintf("WM01 is Available\r\n"); return; } } } int8_t setEchoStatus_WM01(bool onoff) { int8_t ret = RET_NOK; char _buf[10]; sprintf((char *)_buf, "ATE%d", onoff); if(_parser->send(_buf) && _parser->recv("OK")) { devlog("Turn Echo %s : success\r\n", onoff ? "ON" : "OFF"); ret = RET_OK; } else { devlog("Turn Echo %s : failed\r\n", onoff ? "ON" : "OFF"); } return ret; } int8_t getUsimStatus_WM01(void) { int8_t ret = RET_NOK; if(_parser->send("AT$$STAT?") && _parser->recv("$$STAT:READY") && _parser->recv("OK")) { devlog("USIM Status : READY\r\n"); ret = RET_OK; } else { devlog("Retrieving USIM Status failed\r\n"); } return ret; } int8_t getNetworkStatus_WM01(void) { int8_t ret = RET_NOK; int val, stat; if(_parser->send("AT+CEREG?") && _parser->recv("+CEREG: %d,%d", &val, &stat) && _parser->recv("OK")) { if((val == 0) && (stat == 1)) { devlog("Network Status : attached\r\n"); ret = RET_OK; } else { devlog("Network Status : %d, %d\r\n", val, stat); } } else { devlog("Network Status : Error\r\n"); } return ret; } // ---------------------------------------------------------------- // Functions: Cat.M1 SMS // ---------------------------------------------------------------- int8_t initSMS_WM01(void) { int8_t ret = RET_NOK; bool msgformat, charset, recvset = false; // 0 = PDU mode / 1 = Text mode if(_parser->send("AT+CMGF=1") && _parser->recv("OK")) // Set SMS message format as text mode { devlog("SMS message format : Text mode\r\n"); msgformat = true; } // "GSM" / "IRA" / "USC2" if(_parser->send("AT+CSCS=\"GSM\"") && _parser->recv("OK")) // Set character set as GSM { devlog("SMS character set : GSM\r\n"); charset = true; } if(_parser->send("AT*SKT*NEWMSG=4098") && _parser->recv("OK")) { devlog("Tele service ID set : 4098\r\n"); recvset = true; } if(msgformat && charset && recvset) { ret = RET_OK; } return ret; } int8_t sendSMS_WM01(char *da, char *msg, int len) { int8_t ret = RET_NOK; bool done = false; int msg_idx = 0; _parser->set_timeout(WM01_CONNECT_TIMEOUT); _parser->send("AT+CMGS=\"%s\"", da); // DA(Destination address, Phone number) if(!done && _parser->recv(">")) { done = (_parser->write(msg, len) <= 0) & _parser->send("%c", SMS_EOF); } if(!done) { done = (_parser->recv("+CMGS: %d", &msg_idx) && _parser->recv("OK")); if(done) { devlog(">> SMS send success : index %d\r\n", msg_idx); ret = RET_OK; } } _parser->set_timeout(WM01_DEFAULT_TIMEOUT); return ret; } int checkRecvSMS_WM01(void) { bool received = false; int ret = RET_NOK; int msg_idx = 0; int tele_service_id = 0; _parser->set_timeout(1); received = _parser->recv("*SKT*NEWMSG:%d", &msg_idx); _parser->set_timeout(WM01_DEFAULT_TIMEOUT); if(received) { ret = msg_idx; devlog("<< SMS received : index %d\r\n", msg_idx); } return ret; } int8_t recvSMS_WM01(int msg_idx, char *datetime, char *da, char *msg) { int8_t ret = RET_NOK; bool done = false; char type[15] = {0, }; char recv_msg[MAX_SMS_SIZE] = {0, }; char *search_pt; int i = 0; Timer t; memset(recv_msg, 0x00, MAX_SMS_SIZE); _parser->set_timeout(WM01_RECV_TIMEOUT); if(_parser->send("AT+CMGR=%d", msg_idx) && _parser->recv("+CMGR: \"%[^\"]\",\"%[^\"]\",,\"%[^\"]\"", type, da, datetime)) { // timer start t.start(); while(!done && (t.read_ms() < WM01_DEFAULT_TIMEOUT)) { _parser->read(&recv_msg[i++], 1); search_pt = strstr(recv_msg, "OK"); if(search_pt != 0) { done = true; // break; } } if(i > 8) { memcpy(msg, recv_msg + 2, i - 8); devlog("<< SMS receive success : index %d\r\n", msg_idx); ret = RET_OK; } } _parser->set_timeout(WM01_DEFAULT_TIMEOUT); _parser->flush(); return ret; } int8_t deleteSMS_WM01(int msg_idx) { int8_t ret = RET_NOK; if(_parser->send("AT+CMGD=%d", msg_idx) && _parser->recv("OK")) { devlog("Message index[%d] has been deleted\r\n", msg_idx); ret = RET_OK; } return ret; } int8_t deleteAllSMS_WM01(int delflag) { int8_t ret = RET_NOK; // delflag == 1; // Delete all read messages from storage // delflag == 2; // Delete all read messages from storage and sent mobile originated messages // delflag == 3; // Delete all read messages from storage, sent and unsent mobile originated messages // delflag == 4; // Delete all messages from storage if(_parser->send("AT+CMGD=0,%d", delflag) && _parser->recv("OK")) { devlog("All messages has been deleted (delflag : %d)\r\n", delflag); ret = RET_OK; } return ret; }
25.354906
144
0.539481
Wiznet
7136d585e28bc662454d5dffa282fa54b103b441
729
cpp
C++
tests/functionality/structures/matrices/dense/mathematical.cpp
szymonmaszke/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
10
2018-06-06T01:51:17.000Z
2021-01-02T15:17:00.000Z
tests/functionality/structures/matrices/dense/mathematical.cpp
vyzyv/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
2
2018-11-28T12:15:46.000Z
2018-12-16T00:03:38.000Z
tests/functionality/structures/matrices/dense/mathematical.cpp
szymonmaszke/numpp
9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9
[ "MIT" ]
2
2017-08-06T13:58:27.000Z
2018-04-06T06:45:22.000Z
#include "../../../../utilities/catch.hpp" #include "numpp/structures/matrices/dense.hpp" TEST_CASE( "dense matrix functions tests", "[mathemathical][matrix][dense][constexpr]" ){ constexpr numpp::matrix::dense<double, 4, 5> matrix{ 1.2, -4.5, 12412.3, 12512., 294.2352, 2, 5.35, -412.3, 12, 0, -34, 0, 0, 0, 4.5, 3, 1.3, 1.7, 0, 0.1 }; SECTION("log tests"){ constexpr auto matrix_log = std::log(matrix); REQUIRE(matrix_log(1,1) == std::log(matrix(1,1))); REQUIRE(matrix_log(2,3) == std::log(matrix(2,3))); } SECTION("pow tests"){ constexpr auto matrix_pow = std::pow(matrix, 2); REQUIRE(matrix_pow(1,1) == std::pow(matrix(1,1))); REQUIRE(matrix_pow(2,3) == std::pow(matrix(2,3))); } }
27
54
0.615912
szymonmaszke
713835ea7ab96a01ba37edae5b5b3ff5d5a60123
3,382
cpp
C++
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
3
2019-05-14T07:19:59.000Z
2019-05-14T08:08:25.000Z
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
null
null
null
cppLib/code/dep/G3D/source/Stopwatch.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
1
2018-08-08T07:39:16.000Z
2018-08-08T07:39:16.000Z
/** @file Stopwatch.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2005-10-05 @edited 2009-03-14 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "G3D/Stopwatch.h" #include "G3D/System.h" namespace G3D { Stopwatch::Stopwatch(const std::string& myName) : myName(myName), inBetween(false), lastTockTime(-1), lastDuration(0), lastCycleCount(0), m_fps(0), emwaFPS(0), m_smoothFPS(0), emwaDuration(0) { computeOverhead(); reset(); } void Stopwatch::computeOverhead() { cycleOverhead = 0; tick(); tock(); cycleOverhead = elapsedCycles(); } void Stopwatch::tick() { // This is 'alwaysAssert' instead of 'debugAssert' // since people rarely profile in debug mode. alwaysAssertM(! inBetween, "Stopwatch::tick() called twice in a row."); inBetween = true; // We read RDTSC twice here, but it is more abstract to implement this // way and at least we're reading the cycle count last. timeStart = System::time(); System::beginCycleCount(cycleStart); } void Stopwatch::tock() { System::endCycleCount(cycleStart); RealTime now = System::time(); lastDuration = now - timeStart; if (abs(emwaDuration - lastDuration) > max(emwaDuration, lastDuration) * 0.50) { // Off by more than 50% emwaDuration = lastDuration; } else { emwaDuration = lastDuration * 0.05 + emwaDuration * 0.95; } lastCycleCount = cycleStart - cycleOverhead; if (lastCycleCount < 0) { lastCycleCount = 0; } if (lastTockTime != -1.0) { m_fps = 1.0 / (now - lastTockTime); const double blend = 0.01; emwaFPS = m_fps * blend + emwaFPS * (1.0 - blend); double maxDiscrepancyPercentage = 0.25; if (abs(emwaFPS - m_fps) > max(emwaFPS, m_fps) * maxDiscrepancyPercentage) { // The difference between emwa and m_fps is way off, so // update emwa directly. emwaFPS = m_fps * 0.20 + emwaFPS * 0.80; } // Update m_smoothFPS only when the value varies significantly. // We round so as to not mislead the user as to the accuracy of // the number. if (m_smoothFPS == 0) { m_smoothFPS = m_fps; } else if (emwaFPS <= 20) { if (::fabs(m_smoothFPS - emwaFPS) > 0.75) { // Small number and display is off by more than 0.75; round to the nearest 0.1 m_smoothFPS = floor(emwaFPS * 10.0 + 0.5) / 10.0; } } else if (::fabs(m_smoothFPS - emwaFPS) > 1.25) { // Large number and display is off by more than 1.25; round to the nearest 1.0 m_smoothFPS = floor(emwaFPS + 0.5); } } lastTockTime = now; alwaysAssertM(inBetween, "Stopwatch::tock() called without matching tick."); inBetween = false; } void Stopwatch::reset() { prevTime = startTime = System::time(); prevMark = "start"; } void Stopwatch::after(const std::string& s) { RealTime now = System::time(); if (m_enabled) { debugPrintf("%s: %10s - %8fs since %s (%fs since start)\n", myName.c_str(), s.c_str(), now - prevTime, prevMark.c_str(), now - startTime); } prevTime = now; prevMark = s; } }
27.950413
94
0.591366
DrYaling
7139ae3f426ce0c226b223ded51c7ea9c63c3e71
4,122
cpp
C++
test/unit_0/test_detection_of_pressing_a_button.cpp
venth/webhook-button
b4b58ae813f7d8e0c6f1d8b770f380024043d7a5
[ "MIT" ]
3
2019-06-25T18:24:59.000Z
2021-05-25T22:39:46.000Z
test/unit_0/test_detection_of_pressing_a_button.cpp
venth/webhook-button
b4b58ae813f7d8e0c6f1d8b770f380024043d7a5
[ "MIT" ]
null
null
null
test/unit_0/test_detection_of_pressing_a_button.cpp
venth/webhook-button
b4b58ae813f7d8e0c6f1d8b770f380024043d7a5
[ "MIT" ]
2
2019-06-25T19:32:37.000Z
2020-11-23T15:45:16.000Z
#include <unity.h> #include <etl/message_bus.h> #include "button_messages.h" #include "ButtonPressingDetector.h" #include "assertions/MessageBusVerifier.h" ButtonPressingDetector *inLoopProcessor; etl::imessage_bus *bus; assertions::MessageBusVerifier *busVerifier; void emits_loop_initiated_message_every_time_during_loop_iteration() { // when button is up etl::send_message(*bus, ButtonUpMessage::of(10)); // then nothing was received to the bus assertions::assertThat(busVerifier) .receivedNoMessagesOfType(MessageType::BUTTON_PRESSED); } void dont_emit_pressed_message_when_it_is_newly_created_and_button_is_down() { // when button is down etl::send_message(*bus, ButtonDownMessage::of(10)); // then nothing was received to the bus assertions::assertThat(busVerifier) .receivedNoMessagesOfType(MessageType::BUTTON_PRESSED); } void emits_pressed_message_when_button_is_released_after_first_is_down() { // given button is down etl::send_message(*bus, ButtonDownMessage::of(10)); // when button is up etl::send_message(*bus, ButtonUpMessage::of(20)); // then emits pressed message assertions::assertThat(busVerifier) .receivedMessagesOfType(1, MessageType::BUTTON_PRESSED); } void calculates_duration_of_pressed_message_between_time_when_button_is_up_and_first_occurrence_when_button_was_down() { // given button is down etl::send_message(*bus, ButtonDownMessage::of(10)); // when button is up etl::send_message(*bus, ButtonUpMessage::of(30)); // then calculates duration of pressed message between up and first down message appearance assertions::assertThat(busVerifier) .receivedMessagesOfType(1, MessageType::BUTTON_PRESSED) .received(ButtonPressedMessage::of(10, 20)); } void calculates_duration_of_pressed_message_between_time_when_button_is_up_and_first_occurrence_when_button_was_down_despite_of_many_down_after_first() { // given button is down etl::send_message(*bus, ButtonDownMessage::of(10)); // and button is down etl::send_message(*bus, ButtonDownMessage::of(12)); // and button is down etl::send_message(*bus, ButtonDownMessage::of(14)); // and button is down etl::send_message(*bus, ButtonDownMessage::of(20)); // when button is up etl::send_message(*bus, ButtonUpMessage::of(30)); // then calculates duration of pressed message between up and first down message appearance assertions::assertThat(busVerifier) .receivedMessagesOfType(1, MessageType::BUTTON_PRESSED) .received(ButtonPressedMessage::of(10, 20)); } void setUp() { bus = new etl::message_bus<2>(); inLoopProcessor = new ButtonPressingDetector(*bus); busVerifier = new assertions::MessageBusVerifier(); bus->subscribe(*inLoopProcessor); bus->subscribe(*busVerifier); } void tearDown() { delete inLoopProcessor; delete busVerifier; delete bus; } void execute_tests() { UNITY_BEGIN(); RUN_TEST(emits_loop_initiated_message_every_time_during_loop_iteration); RUN_TEST(dont_emit_pressed_message_when_it_is_newly_created_and_button_is_down); RUN_TEST(emits_pressed_message_when_button_is_released_after_first_is_down); RUN_TEST(calculates_duration_of_pressed_message_between_time_when_button_is_up_and_first_occurrence_when_button_was_down); RUN_TEST(calculates_duration_of_pressed_message_between_time_when_button_is_up_and_first_occurrence_when_button_was_down_despite_of_many_down_after_first); UNITY_END(); } #ifdef ARDUINO #include <FS.h> //this needs to be first, or it all crashes and burns... #include <Arduino.h> #include <SoftwareSerial.h> SoftwareSerial ESPserial(2, 3); // RX | TX void setup() { // *** Additional Code that fixed my problem **** Serial.begin(9600); ESPserial.begin(9600); delay(1000); Serial.println("Ready"); ESPserial.println("AT+GMR"); execute_tests(); } void loop() { } #else int main(int argc, char **argv) { execute_tests(); return 0; } #endif
29.442857
159
0.739932
venth
7142ada1847c6a703e24bcca79e470d6ff2ef011
15,222
cpp
C++
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-19T13:45:40.000Z
2020-12-10T20:21:03.000Z
dali/internal/text/text-abstraction/bidirectional-support-impl.cpp
expertisesolutions/dali-adaptor
810bf4dea833ea7dfbd2a0c82193bc0b3b155011
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/text/text-abstraction/bidirectional-support-impl.h> // EXTERNAL INCLUDES #include <memory.h> #include <fribidi/fribidi.h> #include <dali/integration-api/debug.h> #include <dali/devel-api/common/singleton-service.h> namespace Dali { namespace TextAbstraction { namespace Internal { namespace { typedef unsigned char BidiDirection; // Internal charcter's direction. const BidiDirection LEFT_TO_RIGHT = 0u; const BidiDirection NEUTRAL = 1u; const BidiDirection RIGHT_TO_LEFT = 2u; /** * @param[in] paragraphDirection The FriBiDi paragraph's direction. * * @return Whether the paragraph is right to left. */ bool GetBidiParagraphDirection( FriBidiParType paragraphDirection ) { switch( paragraphDirection ) { case FRIBIDI_PAR_RTL: // Right-To-Left paragraph. case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph. { return true; } case FRIBIDI_PAR_LTR: // Left-To-Right paragraph. case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph. case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph. { return false; } } return false; } BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection ) { switch( characterDirection ) { case FRIBIDI_TYPE_LTR: // Left-To-Right letter. { return LEFT_TO_RIGHT; } case FRIBIDI_TYPE_AL: // Arabic Letter. case FRIBIDI_TYPE_RTL: // Right-To-Left letter. { return RIGHT_TO_LEFT; } case FRIBIDI_TYPE_AN: // Arabic Numeral. case FRIBIDI_TYPE_ES: // European number Separator. case FRIBIDI_TYPE_ET: // European number Terminator. case FRIBIDI_TYPE_EN: // European Numeral. default : { return NEUTRAL; } } } } struct BidirectionalSupport::Plugin { /** * Stores bidirectional info per paragraph. */ struct BidirectionalInfo { FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...) FriBidiLevel* embeddedLevels; ///< Embedded levels. FriBidiParType paragraphDirection; ///< The paragraph's direction. }; Plugin() : mParagraphBidirectionalInfo(), mFreeIndices() {} ~Plugin() { // free all resources. for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(), endIt = mParagraphBidirectionalInfo.End(); it != endIt; ++it ) { BidirectionalInfo* info = *it; free( info->embeddedLevels ); free( info->characterTypes ); delete info; } } BidiInfoIndex CreateInfo( const Character* const paragraph, Length numberOfCharacters, bool matchSystemLanguageDirection, LayoutDirection::Type layoutDirection ) { // Reserve memory for the paragraph's bidirectional info. BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo(); bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) ); if( !bidirectionalInfo->characterTypes ) { delete bidirectionalInfo; return 0; } bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) ); if( !bidirectionalInfo->embeddedLevels ) { free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; return 0; } // Retrieve the type of each character.. fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes ); // Retrieve the paragraph's direction. bidirectionalInfo->paragraphDirection = matchSystemLanguageDirection == true ? ( layoutDirection == LayoutDirection::RIGHT_TO_LEFT ? FRIBIDI_PAR_RTL : FRIBIDI_PAR_LTR ) : ( fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters ) ); // Retrieve the embedding levels. if (fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels ) == 0) { free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; return 0; } // Store the bidirectional info and return the index. BidiInfoIndex index = 0u; if( 0u != mFreeIndices.Count() ) { Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u; index = *it; mFreeIndices.Remove( it ); *( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo; } else { index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() ); mParagraphBidirectionalInfo.PushBack( bidirectionalInfo ); } return index; } void DestroyInfo( BidiInfoIndex bidiInfoIndex ) { if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() ) { return; } // Retrieve the paragraph's bidirectional info. Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex; BidirectionalInfo* bidirectionalInfo = *it; if( NULL != bidirectionalInfo ) { // Free resources and destroy the container. free( bidirectionalInfo->embeddedLevels ); free( bidirectionalInfo->characterTypes ); delete bidirectionalInfo; *it = NULL; } // Add the index to the free indices vector. mFreeIndices.PushBack( bidiInfoIndex ); } void Reorder( BidiInfoIndex bidiInfoIndex, CharacterIndex firstCharacterIndex, Length numberOfCharacters, CharacterIndex* visualToLogicalMap ) { const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC; // Retrieve the paragraph's bidirectional info. const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); // Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table. for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { visualToLogicalMap[ index ] = index; } // Copy embedded levels as fribidi_reorder_line() may change them. const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel ); FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) ); if( embeddedLevels ) { memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize ); // Reorder the line. if (fribidi_reorder_line( flags, bidirectionalInfo->characterTypes + firstCharacterIndex, numberOfCharacters, 0u, bidirectionalInfo->paragraphDirection, embeddedLevels, NULL, reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) ) == 0) { DALI_LOG_ERROR("fribidi_reorder_line is failed\n"); } // Free resources. free( embeddedLevels ); } } bool GetMirroredText( Character* text, CharacterDirection* directions, Length numberOfCharacters ) const { bool updated = false; for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { // Get a reference to the character inside the text. Character& character = *( text + index ); // Retrieve the mirrored character. FriBidiChar mirroredCharacter = character; bool mirrored = false; if( *( directions + index ) ) { mirrored = fribidi_get_mirror_char( character, &mirroredCharacter ); } updated = updated || mirrored; // Update the character inside the text. character = mirroredCharacter; } return updated; } bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const { // Retrieve the paragraph's bidirectional info. const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); } void GetCharactersDirection( BidiInfoIndex bidiInfoIndex, CharacterDirection* directions, Length numberOfCharacters ) { const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); CharacterDirection previousDirection = paragraphDirection; for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) { CharacterDirection& characterDirection = *( directions + index ); CharacterDirection nextDirection = false; characterDirection = false; // Get the bidi direction. const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) ); if( RIGHT_TO_LEFT == bidiDirection ) { characterDirection = true; nextDirection = true; } else if( NEUTRAL == bidiDirection ) { // For neutral characters it check's the next and previous directions. // If they are equals set that direction. If they are not, sets the paragraph's direction. // If there is no next, sets the paragraph's direction. nextDirection = paragraphDirection; // Look for the next non-neutral character. Length nextIndex = index + 1u; for( ; nextIndex < numberOfCharacters; ++nextIndex ) { BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) ); if( nextBidiDirection != NEUTRAL ) { nextDirection = RIGHT_TO_LEFT == nextBidiDirection; break; } } // Calculate the direction for all the neutral characters. characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection; // Set the direction to all the neutral characters. // The indices from currentIndex + 1u to nextIndex - 1u are neutral characters. ++index; for( ; index < nextIndex; ++index ) { CharacterDirection& nextCharacterDirection = *( directions + index ); nextCharacterDirection = characterDirection; } // Set the direction of the next non-neutral character. if( nextIndex < numberOfCharacters ) { *( directions + nextIndex ) = nextDirection; } } previousDirection = nextDirection; } } Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph. Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector. }; BidirectionalSupport::BidirectionalSupport() : mPlugin( NULL ) { } BidirectionalSupport::~BidirectionalSupport() { delete mPlugin; } TextAbstraction::BidirectionalSupport BidirectionalSupport::Get() { TextAbstraction::BidirectionalSupport bidirectionalSupportHandle; SingletonService service( SingletonService::Get() ); if( service ) { // Check whether the singleton is already created BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) ); if(handle) { // If so, downcast the handle BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() ); bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl ); } else // create and register the object { bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport ); service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle ); } } return bidirectionalSupportHandle; } BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph, Length numberOfCharacters, bool matchSystemLanguageDirection, Dali::LayoutDirection::Type layoutDirection ) { CreatePlugin(); return mPlugin->CreateInfo( paragraph, numberOfCharacters, matchSystemLanguageDirection, layoutDirection ); } void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex ) { CreatePlugin(); mPlugin->DestroyInfo( bidiInfoIndex ); } void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex, CharacterIndex firstCharacterIndex, Length numberOfCharacters, CharacterIndex* visualToLogicalMap ) { CreatePlugin(); mPlugin->Reorder( bidiInfoIndex, firstCharacterIndex, numberOfCharacters, visualToLogicalMap ); } bool BidirectionalSupport::GetMirroredText( Character* text, CharacterDirection* directions, Length numberOfCharacters ) { CreatePlugin(); return mPlugin->GetMirroredText( text, directions, numberOfCharacters ); } bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const { if( !mPlugin ) { return false; } return mPlugin->GetParagraphDirection( bidiInfoIndex ); } void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex, CharacterDirection* directions, Length numberOfCharacters ) { CreatePlugin(); mPlugin->GetCharactersDirection( bidiInfoIndex, directions, numberOfCharacters ); } void BidirectionalSupport::CreatePlugin() { if( !mPlugin ) { mPlugin = new Plugin(); } } } // namespace Internal } // namespace TextAbstraction } // namespace Dali
32.25
178
0.6509
Coquinho
71440bf8a627282b7f74ca76ec1ae778b3dcbc9e
3,127
cpp
C++
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
src/bindings/c++/iccp-c++.cpp
Geof23/sail
d09e5abe212cbc7f40ff61713a5f75a254e52764
[ "BSD-3-Clause-Clear", "MIT" ]
null
null
null
/* This file is part of SAIL (https://github.com/smoked-herring/sail) Copyright (c) 2020 Dmitry Baryshev The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <cstring> #include "sail-common.h" #include "sail.h" #include "sail-c++.h" namespace sail { class SAIL_HIDDEN iccp::pimpl { public: pimpl() : iccp{nullptr, 0} { } ~pimpl() { sail_free(iccp.data); } sail_iccp iccp; }; iccp::iccp() : d(new pimpl) { } iccp::iccp(const iccp &ic) : iccp() { *this = ic; } iccp& iccp::operator=(const iccp &ic) { with_data(ic.data(), ic.data_length()); return *this; } iccp::iccp(iccp &&ic) noexcept { d = ic.d; ic.d = nullptr; } iccp& iccp::operator=(iccp &&ic) { delete d; d = ic.d; ic.d = nullptr; return *this; } iccp::~iccp() { delete d; } bool iccp::is_valid() const { return d->iccp.data != nullptr && d->iccp.data_length > 0; } const void* iccp::data() const { return d->iccp.data; } unsigned iccp::data_length() const { return d->iccp.data_length; } iccp& iccp::with_data(const void *data, unsigned data_length) { sail_free(d->iccp.data); d->iccp.data = nullptr; d->iccp.data_length = 0; if (data == nullptr || data_length == 0) { return *this; } SAIL_TRY_OR_EXECUTE(sail_malloc(data_length, &d->iccp.data), /* on error */ return *this); d->iccp.data_length = data_length; memcpy(d->iccp.data, data, data_length); return *this; } iccp::iccp(const sail_iccp *ic) : iccp() { if (ic == nullptr) { SAIL_LOG_DEBUG("NULL pointer has been passed to sail::iccp(). The object is untouched"); return; } with_data(ic->data, ic->data_length); } sail_status_t iccp::to_sail_iccp(sail_iccp *ic) const { SAIL_CHECK_ICCP_PTR(ic); SAIL_TRY(sail_malloc(d->iccp.data_length, &ic->data)); memcpy(ic->data, d->iccp.data, d->iccp.data_length); ic->data_length = d->iccp.data_length; return SAIL_OK; } }
20.846667
96
0.653342
Geof23
7145e7b7d7b6aae2a27ac8cfd595d6cccdddcbbf
3,013
cpp
C++
passes/idempotent-regions/src/HittingSet.cpp
TUDSSL/WARio
e57fe0857ba3327d42ec0be71b62ed561b7c4b2b
[ "MIT" ]
2
2022-03-14T12:48:18.000Z
2022-03-14T12:48:24.000Z
passes/idempotent-regions/src/HittingSet.cpp
TUDSSL/WARio
e57fe0857ba3327d42ec0be71b62ed561b7c4b2b
[ "MIT" ]
null
null
null
passes/idempotent-regions/src/HittingSet.cpp
TUDSSL/WARio
e57fe0857ba3327d42ec0be71b62ed561b7c4b2b
[ "MIT" ]
null
null
null
#include "Configurations.hpp" #include "PlacementCost.hpp" #include "HittingSet.hpp" using namespace IdempotentRegion; void HittingSet::computeHitCountMap(PathsTy &Paths) { HitCountMap.clear(); for (const auto &Path : Paths) for (const auto &Point : Path) HitCountMap[Point]++; } void HittingSet::removeCutPaths(PathsTy &Paths, Instruction *Cut) { auto it = Paths.begin(); while (it != Paths.end()) { auto &p = *it; if (std::find(p.begin(), p.end(), Cut) != p.end()) { // For each point in the Path that will be removed, we decrement the // corresponding HitCountMap entry for (const auto &Point : *it) HitCountMap[Point]--; // Erase the Path it = Paths.erase(it); } else { ++it; } } } #define hsdbg() if (!PrintDebug) {} else dbg() CutsTy &HittingSet::run(bool PrintDebug) { hsdbg() << "Running HittingSet\n"; int step = 0; PathsTy RemainingPaths = IdempotentPaths; computeHitCountMap(RemainingPaths); while (RemainingPaths.size() > 0) { hsdbg() << "\nStep: " << step << "\n"; hsdbg() << "Remaining Paths: " << RemainingPaths.size() << "\n"; // Calculate the priority Hits*Cost // Track the highest Priority Instruction *Candidate; double CandidatePriority = 0; for (const auto &kv : HitCountMap) { auto *I = kv.first; const auto &H = kv.second; double Priority = (double)H / (double)PC.cost(I); if (Priority > CandidatePriority) { Candidate = I; CandidatePriority = Priority; } } // Debug Information hsdbg() << "Candidate: " << *Candidate << "\n"; hsdbg() << " Priority: " << CandidatePriority << "\n"; hsdbg() << " Hits: " << HitCountMap[Candidate] << "\n"; hsdbg() << " Cost: " << PC.cost(Candidate) << "\n"; hsdbg() << " CostFactors: " << PC.costFactors(Candidate) << "\n"; // Add the Candidate to the Cuts Cuts.insert(Candidate); // Remove the Paths containing the Candidate from the RemainingPaths // Additionally updates the HitCountMap removeCutPaths(RemainingPaths, Candidate); // Increase the step count (debugging) ++step; } // Verify if the Cuts cover all the assert((verify(Cuts) == true) && "Verify failed, not all paths are cut"); /* * Debug information */ hsdbg() << "\nMinimal Cuts:\n"; for (const auto &Cut : Cuts) hsdbg() << *Cut << "\n"; hsdbg() << "\n"; /* * Automated testing output */ hsdbg() << "$CUTS_COUNT: " << Cuts.size() << "\n"; hsdbg() << "$CUTS_COST: " << PC.cost(Cuts) << "\n"; return Cuts; } /* * Check if all the paths have a cut in them */ bool HittingSet::verify(CutsTy &Solution) { int CoveredPaths = 0; for (const auto &Path : IdempotentPaths) { for (const auto &P : Path) { if (Solution.find(P) != Solution.end()) { // Found a cut that breaks the Path CoveredPaths++; break; } } } return (CoveredPaths == IdempotentPaths.size()); }
25.533898
75
0.59542
TUDSSL
7145f113cf2ab526df1efd2d7d5ed5574f7ca300
811
cpp
C++
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0572-Subtree_of_Another_Tree-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 572 Subtree of Another Tree // https://leetcode.com/problems/subtree-of-another-tree // version: 1; create time: 2019-12-30 11:34:15; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSame(TreeNode* s, TreeNode* t) { if (!s && !t) return true; if (!s || !t) return false; return s->val == t->val && isSame(s->left, t->left) && isSame(s->right, t->right); } bool isSubtree(TreeNode* s, TreeNode* t) { if (!s && !t) return true; if (!s || !t) return false; if (isSame(s, t) || isSubtree(s->left, t) || isSubtree(s->right, t)) return true; return false; } };
27.965517
90
0.556104
levendlee
71496eb742eb33b7e02dd510bb4655b3f8e2d692
9,047
hpp
C++
src/include/structures/min_max_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
2
2019-03-18T20:37:47.000Z
2019-03-19T04:51:47.000Z
src/include/structures/min_max_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
1
2019-09-09T02:33:02.000Z
2019-09-09T02:33:02.000Z
src/include/structures/min_max_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
4
2018-02-15T19:17:15.000Z
2020-06-25T13:26:19.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // min_max_heap.hpp // // Contains a template implementation of a min-max heap // #ifndef structures_min_max_heap_hpp #define structures_min_max_heap_hpp #include <vector> #include <cstdint> namespace structures { using namespace std; /* * A dynamic container structure that supports efficient maximum and minimum operations. */ template <typename T> class MinMaxHeap { public: /// Initialize a heap with the values returned by an iterator in linear time template<typename Iter> MinMaxHeap(Iter begin, Iter end); /// Initialize an empty heap MinMaxHeap(); /// Add a value to the heap in logarithmic time inline void push(const T& value); /// Construct a value on the heap in place in logarithmic time template<typename... Args> inline void emplace(Args&&... args); /// Returns the maximum value of the heap in constant time inline const T& max(); /// Returns the minimum value of the heap in constant time inline const T& min(); /// Remove the maximum element of the heap in logarithmic time inline void pop_max(); /// Remove the minimum element of the heap in logarithmic time inline void pop_min(); /// Returns true if the heap contains no values, else false inline bool empty(); /// Returns the number of values in the heap inline size_t size(); private: inline void post_add(); void restore_heap_below(size_t i, int level); void restore_heap_above(size_t i, int level); inline static bool cmp(const T& v1, const T& v2, int level); vector<T> values; }; template <typename T> MinMaxHeap<T>::MinMaxHeap() { // nothing to do } template <typename T> template <typename Iter> MinMaxHeap<T>::MinMaxHeap(Iter begin, Iter end) { for (auto iter = begin; iter != end; iter++) { values.push_back(*iter); } if (values.empty()) { return; } // depth of the current layer of internal nodes int level = -2; // size at which we would begin filling the next level of the tree size_t next_level_begin = 1; while (next_level_begin - 1 < values.size()) { next_level_begin *= 2; level++; } // the range of indices that correspond to the deepest internal layer size_t internal_level_end = next_level_begin / 2 - 1; size_t internal_level_begin = next_level_begin / 4 - 1; // set up the heap invariant from the deepest layer up to the root while (level >= 0) { for (size_t i = internal_level_begin; i < internal_level_end; i++) { restore_heap_below(i, level); } internal_level_end = internal_level_begin; internal_level_begin = (internal_level_begin + 1) / 2 - 1; level--; } } template <typename T> inline bool MinMaxHeap<T>::cmp(const T& v1, const T& v2, int level) { return (level % 2 == 0) != (v1 > v2); } template <typename T> void MinMaxHeap<T>::restore_heap_below(size_t i, int level) { // the range of i's grandchildren size_t rightest = 4 * i + 6; size_t leftest = rightest - 3; if (leftest >= values.size()) { // i has no grandchildren size_t left = 2 * i + 1; size_t right = left + 1; if (left >= values.size()) { // i has no children return; } // find the extremal element among the children size_t most = cmp(values[i], values[left], level) ? i : left; if (right < values.size()) { most = cmp(values[most], values[right], level) ? most : right; } // if necessary swap, no need to recurse further because only one level // below (invariant vacuously maintained) if (most != i) { swap(values[i], values[most]); } } else { // find the extremal element among the grandchildren size_t most = cmp(values[i], values[leftest], level) ? i : leftest; for (size_t j = leftest + 1; j <= rightest; j++) { if (j >= values.size()) { break; } most = cmp(values[most], values[j], level) ? most : j; } bool direct_child_swapped = false; if (leftest + 2 >= values.size()) { // the right child has no children, so we may need to swap with it directly size_t right = 2 * i + 2; if (cmp(values[right], values[most], level)) { swap(values[i], values[right]); direct_child_swapped = true; } } // if we swapped, and not with child (because then it has nogrand children and // invariant is vacuously maintained below) then recurse downward if (!direct_child_swapped && most != i) { swap(values[i], values[most]); size_t intermediate = most <= leftest + 1 ? 2 * i + 1 : 2 * i + 2; if (cmp(values[most], values[intermediate], level + 1)) { swap(values[intermediate], values[most]); } restore_heap_below(most, level + 2); } } } template <typename T> void MinMaxHeap<T>::restore_heap_above(size_t i, int level) { if (i <= 2) { // i has no grandparent return; } // go two layers up to get the next value using the same direction of comparison size_t grandparent = (i + 1) / 4 - 1; if (cmp(values[i], values[grandparent], level - 2)) { // swap and recurse upward swap(values[i], values[grandparent]); restore_heap_above(grandparent, level - 2); } } template <typename T> inline const T& MinMaxHeap<T>::min() { assert(!values.empty()); return values[0]; } template <typename T> inline const T& MinMaxHeap<T>::max() { assert(!values.empty()); if (values.size() == 1) { return values[0]; } else if (values.size() == 2) { return values[1]; } else { return std::max(values[1], values[2]); } } template <typename T> inline void MinMaxHeap<T>::push(const T& value) { values.push_back(value); post_add(); } template <typename T> template <typename... Args> inline void MinMaxHeap<T>::emplace(Args&&... args) { values.emplace_back(std::forward<Args>(args)...); post_add(); } template <typename T> inline void MinMaxHeap<T>::post_add() { if (values.size() == 1) { // no parents to restore invariants in return; } int64_t i = values.size() - 1; size_t parent = (i + 1) / 2 - 1; // depth of the current layer of leaves int level = -1; // size at which we would begin filling the next level of the tree size_t next_level_begin = 1; while (next_level_begin - 1 < values.size()) { next_level_begin *= 2; level++; } // decide whether this value should go in the min or max layers and then recurse upward if (cmp(values[i], values[parent], level - 1)) { swap(values[i], values[parent]); restore_heap_above(parent, level - 1); } else { restore_heap_above(i, level); } } template <typename T> inline void MinMaxHeap<T>::pop_min() { assert(!values.empty()); // move the back value into the minimum value's position and then // restore the invariant values.front() = values.back(); values.pop_back(); restore_heap_below(0, 0); } template <typename T> inline void MinMaxHeap<T>::pop_max() { assert(!values.empty()); if (values.size() <= 2) { // the max is either the only element or the only element in // a max layer values.pop_back(); } else { // get the index of the max value size_t i = values[1] > values[2] ? 1 : 2; // move the value at the back into this position and then restore // the invariant values[i] = values.back(); values.pop_back(); restore_heap_below(i, 1); } } template <typename T> inline size_t MinMaxHeap<T>::size() { return values.size(); } template <typename T> inline bool MinMaxHeap<T>::empty() { return values.empty(); } } #endif /* structures_min_max_heap_hpp */
28.271875
91
0.609042
mr-c
7149ff58d8822b0bd35b5efa19c3277a1bf648c8
1,270
cpp
C++
memory/intrusive_ptr.cpp
xujungp02/boost_guide
328516455d334506f824402455a17afc606ca3bc
[ "Apache-2.0" ]
355
2015-03-06T12:03:51.000Z
2022-03-28T04:15:00.000Z
memory/intrusive_ptr.cpp
lak123456/boost_guide
1886ec8014838717222484f0fe872ecebc324e91
[ "Apache-2.0" ]
1
2017-10-04T18:14:17.000Z
2017-10-09T02:38:12.000Z
memory/intrusive_ptr.cpp
lak123456/boost_guide
1886ec8014838717222484f0fe872ecebc324e91
[ "Apache-2.0" ]
202
2015-03-23T16:16:45.000Z
2022-03-28T07:55:48.000Z
// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #include <boost/smart_ptr.hpp> using namespace boost; ////////////////////////////////////////// struct counted_data { // ... int m_count = 0; ~counted_data() { cout << "dtor" << endl; } }; void intrusive_ptr_add_ref(counted_data* p) { ++p->m_count; } void intrusive_ptr_release(counted_data* p) { if(--p->m_count == 0) { delete p; } } ////////////////////////////////////////// #include <boost/smart_ptr/intrusive_ref_counter.hpp> struct counted_data2 : public intrusive_ref_counter<counted_data2> { ~counted_data2() { cout << "dtor2" << endl; } }; ////////////////////////////////////////// int main() { typedef intrusive_ptr<counted_data> counted_ptr; counted_ptr p(new counted_data); assert(p); assert(p->m_count == 1); counted_ptr p2(p); assert(p->m_count == 2); counted_ptr weak_p(p.get(), false); assert(weak_p->m_count == 2); p2.reset(); assert(!p2); assert(p->m_count == 1); { typedef intrusive_ptr<counted_data2> counted_ptr; counted_ptr p(new counted_data2); assert(p); assert(p->use_count() == 1); } }
17.162162
66
0.540945
xujungp02
714a01cf9a3e539ac437e954820c7df871a975ad
5,591
cpp
C++
python-module/calendar.cpp
russor/uICAL
e5d23b963876185e7e5bb263d18aad99bce365a5
[ "MIT" ]
8
2020-11-20T18:10:24.000Z
2022-03-19T01:37:20.000Z
python-module/calendar.cpp
russor/uICAL
e5d23b963876185e7e5bb263d18aad99bce365a5
[ "MIT" ]
null
null
null
python-module/calendar.cpp
russor/uICAL
e5d23b963876185e7e5bb263d18aad99bce365a5
[ "MIT" ]
5
2021-10-08T04:52:32.000Z
2022-03-14T22:05:13.000Z
/*############################################################################ # Copyright (c) 2020 Source Simian : https://github.com/sourcesimian/uICAL # ############################################################################*/ #include <sstream> #include "uICAL/cppstl.h" #include "uICAL/types.h" #include "uICAL/error.h" #include "uICAL/util.h" #include "uICAL/calendar.h" #include "uICAL/calendarentry.h" #include "uICAL/calendariter.h" #include "uICAL/datetime.h" #include "uICAL/datestamp.h" #include "uICAL/stream.h" #include "uICAL/tz.h" #define PY_SSIZE_T_CLEAN #include <Python.h> #include <structmember.h> #include "error.h" #include "calendar.h" namespace uical_python { static void Calendar_dealloc(CalendarObject *self) { self->calendar = nullptr; Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * Calendar_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { std::ignore = args; std::ignore = kwds; CalendarObject *self; self = (CalendarObject *) type->tp_alloc(type, 0); if (self != NULL) { self->calendar = nullptr; } return (PyObject *) self; } int Calendar_init(CalendarObject *self, PyObject *args, PyObject *kwds) { try { static char const *kwlist[] = {"ical", "begin", "end", NULL}; char *ical = NULL; PyObject *begin = NULL, *end = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OO:__init__", (char**)kwlist, &ical, &begin, &end)) return -1; if (ical == NULL) { PyErr_SetString(PyExc_AttributeError, "ical"); return -1; } std::istringstream _ical(ical); uICAL::istream_stl inp(_ical); uICAL::Calendar_ptr cal = uICAL::Calendar::load(inp); uICAL::DateTime calBegin; uICAL::DateTime calEnd; if (begin && PyUnicode_Check(begin)) { calBegin = uICAL::DateTime(std::string(PyUnicode_AsUTF8(begin))); } if (end && PyUnicode_Check(end)) { calEnd = uICAL::DateTime(std::string(PyUnicode_AsUTF8(end))); } self->calendar = uICAL::new_ptr<uICAL::CalendarIter>(cal, calBegin, calEnd); return 0; } catch (uICAL::Error ex) { PyErr_SetString(UicalError, ex.message.c_str()); return -1; } } static PyObject * Calendar_next(CalendarObject *self, PyObject *Py_UNUSED(ignored)) { try { if (self->calendar->next()) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } catch (uICAL::Error ex) { PyErr_SetString(UicalError, ex.message.c_str()); return 0; } } static PyObject * Calendar_current(CalendarObject *self, PyObject *Py_UNUSED(ignored)) { try { uICAL::CalendarEntry_ptr entry = self->calendar->current(); uICAL::DateTime dtStart = entry->start(); uICAL::DateStamp dsStart = dtStart.datestamp(); PyObject* start = PyTuple_New(7); PyTuple_SetItem(start, 0, PyLong_FromLong(dsStart.year)); PyTuple_SetItem(start, 1, PyLong_FromLong(dsStart.month)); PyTuple_SetItem(start, 2, PyLong_FromLong(dsStart.day)); PyTuple_SetItem(start, 3, PyLong_FromLong(dsStart.hour)); PyTuple_SetItem(start, 4, PyLong_FromLong(dsStart.minute)); PyTuple_SetItem(start, 5, PyLong_FromLong(dsStart.second)); PyTuple_SetItem(start, 6, PyLong_FromLong(dtStart.tz->offset())); PyObject* ret = PyDict_New(); PyDict_SetItemString(ret, "type", PyUnicode_FromString(uICAL::CalendarEntry::asString(entry->type()).c_str())); PyDict_SetItemString(ret, "summary", PyUnicode_FromString(entry->summary().c_str())); PyDict_SetItemString(ret, "start", start); PyDict_SetItemString(ret, "duration", PyLong_FromLong((entry->end() - entry->start()).totalSeconds())); return ret; } catch (uICAL::Error ex) { PyErr_SetString(UicalError, ex.message.c_str()); return 0; } } static PyMethodDef Calendar_methods[] = { {"next", (PyCFunction) Calendar_next, METH_NOARGS, "Test if there is a next value" }, {"current", (PyCFunction) Calendar_current, METH_NOARGS, "Get the latest value" }, {NULL, NULL, 0, NULL} }; static PyTypeObject CalendarType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "uical.Calendar", .tp_basicsize = sizeof(CalendarObject), .tp_itemsize = 0, .tp_dealloc = (destructor) Calendar_dealloc, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_doc = "Iterator object for uICAL::Calendar", .tp_methods = Calendar_methods, .tp_init = (initproc) Calendar_init, .tp_new = Calendar_new, }; bool PyInit_Calendar(PyObject* module) { if (PyType_Ready(&CalendarType) < 0) return false; Py_INCREF(&CalendarType); if (PyModule_AddObject(module, "Calendar", (PyObject *) &CalendarType) < 0) { Py_DECREF(&CalendarType); // TODO error: use of undeclared identifier 'PY_DECREF' return false; } return true; } }
31.767045
123
0.560723
russor
71550a9373d5b509149751cc39a9955751f7aedc
4,806
cpp
C++
src/database/impl/FastaSequenceOutput.cpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
9
2016-09-30T05:44:35.000Z
2020-09-03T19:40:06.000Z
src/database/impl/FastaSequenceOutput.cpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
10
2017-05-05T14:55:16.000Z
2022-01-24T18:21:51.000Z
src/database/impl/FastaSequenceOutput.cpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
1
2020-12-05T21:33:27.000Z
2020-12-05T21:33:27.000Z
/***************************************************************************** * * * PLAST : Parallel Local Alignment Search Tool * * Version 2.3, released November 2015 * * Copyright (c) 2009-2015 Inria-Cnrs-Ens * * * * PLAST is free software; you can redistribute it and/or modify it under * * the Affero GPL ver 3 License, that is compatible with the GNU General * * Public License * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Affero GPL ver 3 License for more details. * *****************************************************************************/ #include <os/impl/DefaultOsFactory.hpp> #include <designpattern/impl/WrapperIterator.hpp> #include <database/impl/FastaSequenceOutput.hpp> #include <stdio.h> #define DEBUG(a) //printf a #define INFO(a) printf a using namespace os; using namespace os::impl; using namespace dp; using namespace dp::impl; /********************************************************************************/ namespace database { namespace impl { /********************************************************************************/ /********************************************************************* ** METHOD : ** PURPOSE : ** INPUT : ** OUTPUT : ** RETURN : ** REMARKS : *********************************************************************/ FastaSequenceOutput::FastaSequenceOutput (ISequenceIterator* iterator, const char* filename, const std::list<std::string>& comments) : _iterator(0), _filename (filename), _comments (comments) { setIterator (iterator); } /********************************************************************* ** METHOD : ** PURPOSE : ** INPUT : ** OUTPUT : ** RETURN : ** REMARKS : *********************************************************************/ FastaSequenceOutput::FastaSequenceOutput (ISequenceIterator* iterator, const char* filename) : _iterator(0), _filename (filename) { setIterator (iterator); } /********************************************************************* ** METHOD : ** PURPOSE : ** INPUT : ** OUTPUT : ** RETURN : ** REMARKS : *********************************************************************/ FastaSequenceOutput::~FastaSequenceOutput () { setIterator (0); } /********************************************************************* ** METHOD : ** PURPOSE : ** INPUT : ** OUTPUT : ** RETURN : ** REMARKS : *********************************************************************/ void FastaSequenceOutput::dump () { /** We iterate the sequences. */ if (_iterator != 0) { /** We create the output file. */ _file = DefaultFactory::file().newFile (_filename.c_str(), "w"); if (_file != 0) { /** We initialize the iteration on the provided comments. */ _itComments = _comments.begin (); /** We launch the iteration. */ _iterator->iterate (this, (Iterator<const ISequence*>::Method) &FastaSequenceOutput::dumpSequence); /** We get rid of the IFile instance. */ delete _file; _file = 0; } } } /********************************************************************* ** METHOD : ** PURPOSE : ** INPUT : ** OUTPUT : ** RETURN : ** REMARKS : *********************************************************************/ void FastaSequenceOutput::dumpSequence (const ISequence* seq) { if (_file != 0 && seq != 0) { char buffer[256]; if (_itComments != _comments.end()) { sprintf (buffer, ">%s", (*_itComments).c_str()); _itComments ++; } else { sprintf (buffer, ">%s",seq->comment); } /** We write the comment. */ _file->println (buffer); /** We split the data in lines of N characters max. */ WrapperIterator it (seq->data.toString(), 60); for (it.first(); ! it.isDone(); it.next()) { _file->println (it.currentItem()); } } } /********************************************************************************/ } } /* end of namespaces. */ /********************************************************************************/
32.04
132
0.394715
nileshpatra
7155d64874e7ce4b6e55b4aa18f88e7c4c6615dd
2,490
cpp
C++
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
Arrays/create.cpp
rajeshkumarblr/datastructures
ca5ebbb44d65272ead8e20cda5f9fee2c326c58a
[ "MIT" ]
null
null
null
#include <iostream> #include <time.h> #include <stdlib.h> #include "arrayops.h" #include "dsutils.h" using namespace std; void allocateArray(int size) { if (arr) { delete[] arr; } arr = new int[size]; n = size; } void createArray(int st, int end, int incr) { int size = (end - st) / incr + 1; allocateArray(size); int val = st; for (int i=0; i<size; i++) { arr[i]= val; val += incr; } } void createArrayValues() { int num; cout << "Create array with specific elements:" << endl; cout << "Enter the number of elements:"; cin >> num; allocateArray(num); for (int i=0; i< num; i++) { cout << "Enter the next element(" << i << ")"; cin >> arr[i]; } printArray("created Array:",arr,n); } void createArrayRandom(int num, int min, int max) { allocateArray(num); srandom(time(NULL)); double mul = ((max - min) / (double) RAND_MAX); for (int i=0; i< num; i++) { arr[i] = min + (rand() * mul); } } void createArrayRandomDriver() { int start, end, incr, num; cout << "Create array with random elements:" << endl; cout << "Enter the number of elements:"; cin >> num; cout << " Enter the range (start end):"; cin >> start >> end; cout << "Entered range is: (" << start << " - " << end << "). number of elements: " << num << endl; createArrayRandom(num, start, end); printArray("created Array:",arr,n); } void createArrayRange() { int start, end, incr; cout << "Create array by range:" << endl; cout << " Enter the range (start end):"; cin >> start >> end; cout << " Enter the increment by value:"; cin >> incr; cout << "Entered range is: (" << start << " - " << end << "). increment by: " << incr << endl; createArray(start, end,incr); printArray("created Array:",arr,n); } static vector<string> menuoptions = { "Return To Main Menu...", "Create array with range of numbers", "Create array with random values", "Create by entering values...", }; void createArrayDriver() { int choice; bool isCreated = false; cout << " Create Array Menu:\n"; do { printArrayDriver(); app->displayMenu(menuoptions); cout << "Enter your choice:"; cin >> choice; switch(choice) { case 0: return; case 1: createArrayRange(); break; case 2: createArrayRandomDriver(); break; case 3: createArrayValues(); break; default: continue; } isCreated = true; } while(!isCreated); }
23.271028
101
0.583936
rajeshkumarblr
71562197278abdecea7b48012d7d31c61d099bc2
228
cpp
C++
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
52
2015-11-27T13:56:00.000Z
2021-12-01T16:33:58.000Z
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
4
2017-06-26T17:59:51.000Z
2021-09-26T17:30:32.000Z
lib/libc/tests/ctype/isalpha.cpp
otaviopace/ananas
849925915b0888543712a8ca625318cd7bca8dd9
[ "Zlib" ]
8
2016-08-26T09:42:27.000Z
2021-12-04T00:21:05.000Z
#include <gtest/gtest.h> #include <ctype.h> TEST(ctype, isalpha) { EXPECT_TRUE(isalpha('a')); EXPECT_TRUE(isalpha('z')); EXPECT_FALSE(isalpha(' ')); EXPECT_FALSE(isalpha('1')); EXPECT_FALSE(isalpha('@')); }
19
31
0.627193
otaviopace
7157aa8407ffc5d2453a56d06f3a30aa281ae1f5
6,608
cc
C++
src/kernel/arch/x86/architecture.cc
cmejj/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
16,500
2015-01-01T00:47:42.000Z
2022-03-31T17:12:02.000Z
src/kernel/arch/x86/architecture.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
66
2015-01-08T15:22:11.000Z
2021-12-16T09:04:37.000Z
src/kernel/arch/x86/architecture.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
3,814
2015-01-01T12:42:31.000Z
2022-03-31T14:26:50.000Z
#include <os.h> #include <x86.h> /* Stack pointer */ extern u32 * stack_ptr; /* Current cpu name */ static char cpu_name[512] = "x86-noname"; /* Detect the type of processor */ char* Architecture::detect(){ cpu_vendor_name(cpu_name); return cpu_name; } /* Start and initialize the architecture */ void Architecture::init(){ io.print("Architecture x86, cpu=%s \n", detect()); io.print("Loading GDT \n"); init_gdt(); asm(" movw $0x18, %%ax \n \ movw %%ax, %%ss \n \ movl %0, %%esp"::"i" (KERN_STACK)); io.print("Loading IDT \n"); init_idt(); io.print("Configure PIC \n"); init_pic(); io.print("Loading Task Register \n"); asm(" movw $0x38, %ax; ltr %ax"); } /* Initialise the list of processus */ void Architecture::initProc(){ firstProc= new Process("kernel"); firstProc->setState(ZOMBIE); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); firstProc->addFile(fsm.path("/dev/tty"),0); plist=firstProc; pcurrent=firstProc; pcurrent->setPNext(NULL); process_st* current=pcurrent->getPInfo(); current->regs.cr3 = (u32) pd0; } /* Reboot the computer */ void Architecture::reboot(){ u8 good = 0x02; while ((good & 0x02) != 0) good = io.inb(0x64); io.outb(0x64, 0xFE); } /* Shutdown the computer */ void Architecture::shutdown(){ // todo } /* Install a interruption handler */ void Architecture::install_irq(int_handler h){ // todo } /* Add a process to the scheduler */ void Architecture::addProcess(Process* p){ p->setPNext(plist); plist=p; } /* Fork a process */ int Architecture::fork(process_st* info,process_st* father){ memcpy((char*)info,(char*)father,sizeof(process_st)); info->pd = pd_copy(father->pd); } /* Initialise a new process */ int Architecture::createProc(process_st* info, char* file, int argc, char** argv){ page *kstack; process_st *previous; process_st *current; char **param, **uparam; u32 stackp; u32 e_entry; int pid; int i; pid = 1; info->pid = pid; if (argc) { param = (char**) kmalloc(sizeof(char*) * (argc+1)); for (i=0 ; i<argc ; i++) { param[i] = (char*) kmalloc(strlen(argv[i]) + 1); strcpy(param[i], argv[i]); } param[i] = 0; } info->pd = pd_create(); INIT_LIST_HEAD(&(info->pglist)); previous = arch.pcurrent->getPInfo(); current=info; asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"((info->pd)->base->p_addr)); e_entry = (u32) load_elf(file,info); if (e_entry == 0) { for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (current->regs.cr3)); pd_destroy(info->pd); return -1; } stackp = USER_STACK - 16; if (argc) { uparam = (char**) kmalloc(sizeof(char*) * argc); for (i=0 ; i<argc ; i++) { stackp -= (strlen(param[i]) + 1); strcpy((char*) stackp, param[i]); uparam[i] = (char*) stackp; } stackp &= 0xFFFFFFF0; // Creation des arguments de main() : argc, argv[]... stackp -= sizeof(char*); *((char**) stackp) = 0; for (i=argc-1 ; i>=0 ; i--) { stackp -= sizeof(char*); *((char**) stackp) = uparam[i]; } stackp -= sizeof(char*); *((char**) stackp) = (char*) (stackp + 4); stackp -= sizeof(char*); *((int*) stackp) = argc; stackp -= sizeof(char*); for (i=0 ; i<argc ; i++) kfree(param[i]); kfree(param); kfree(uparam); } kstack = get_page_from_heap(); // Initialise le reste des registres et des attributs info->regs.ss = 0x33; info->regs.esp = stackp; info->regs.eflags = 0x0; info->regs.cs = 0x23; info->regs.eip = e_entry; info->regs.ds = 0x2B; info->regs.es = 0x2B; info->regs.fs = 0x2B; info->regs.gs = 0x2B; info->regs.cr3 = (u32) info->pd->base->p_addr; info->kstack.ss0 = 0x18; info->kstack.esp0 = (u32) kstack->v_addr + PAGESIZE - 16; info->regs.eax = 0; info->regs.ecx = 0; info->regs.edx = 0; info->regs.ebx = 0; info->regs.ebp = 0; info->regs.esi = 0; info->regs.edi = 0; info->b_heap = (char*) ((u32) info->e_bss & 0xFFFFF000) + PAGESIZE; info->e_heap = info->b_heap; info->signal = 0; for(i=0 ; i<32 ; i++) info->sigfn[i] = (char*) SIG_DFL; arch.pcurrent = (Process*) previous->vinfo; current=arch.pcurrent->getPInfo(); asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(current->regs.cr3)); return 1; } // Destroy a process void Architecture::destroy_process(Process* pp){ disable_interrupt(); u16 kss; u32 kesp; u32 accr3; list_head *p, *n; page *pg; process_st *proccurrent=(arch.pcurrent)->getPInfo(); process_st *pidproc=pp->getPInfo(); // Switch page to the process to destroy asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (pidproc->regs.cr3)); // Free process memory: // - pages used by the executable code // - user stack // - kernel stack // - pages directory // Free process memory list_for_each_safe(p, n, &pidproc->pglist) { pg = list_entry(p, struct page, list); release_page_frame(pg->p_addr); list_del(p); kfree(pg); } release_page_from_heap((char *) ((u32)pidproc->kstack.esp0 & 0xFFFFF000)); // Free pages directory asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(pd0)); pd_destroy(pidproc->pd); asm("mov %0, %%eax ;mov %%eax, %%cr3"::"m" (proccurrent->regs.cr3)); // Remove from the list if (plist==pp){ plist=pp->getPNext(); } else{ Process* l=plist; Process*ol=plist; while (l!=NULL){ if (l==pp){ ol->setPNext(pp->getPNext()); } ol=l; l=l->getPNext(); } } enable_interrupt(); } void Architecture::change_process_father(Process* pe, Process* pere){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getPParent()==pe){ p->setPParent(pere); } p=pn; } } void Architecture::destroy_all_zombie(){ Process* p=plist; Process* pn=NULL; while (p!=NULL){ pn=p->getPNext(); if (p->getState()==ZOMBIE && p->getPid()!=1){ destroy_process(p); delete p; } p=pn; } } /* Set the syscall arguments */ void Architecture::setParam(u32 ret, u32 ret1, u32 ret2, u32 ret3,u32 ret4){ ret_reg[0]=ret; ret_reg[1]=ret1; ret_reg[2]=ret2; ret_reg[3]=ret3; ret_reg[4]=ret4; } /* Enable the interruption */ void Architecture::enable_interrupt(){ asm ("sti"); } /* Disable the interruption */ void Architecture::disable_interrupt(){ asm ("cli"); } /* Get a syscall argument */ u32 Architecture::getArg(u32 n){ if (n<5) return ret_reg[n]; else return 0; } /* Set the return value of syscall */ void Architecture::setRet(u32 ret){ stack_ptr[14] = ret; }
19.550296
82
0.615466
cmejj
715d14a0dcd1f93c08d98a5dd3b4c9ee626e05f3
2,021
cpp
C++
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
8
2020-09-29T17:11:15.000Z
2022-01-29T20:41:33.000Z
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
1
2021-03-08T17:43:05.000Z
2021-03-09T06:35:04.000Z
3rdparty/openbw/bwapi/bwapi/TestAIModule/Source/InterceptorTest.cpp
ratiotile/StardustDevEnvironment
15c512b81579d8bd663db3fa8e0847d4c27f17e8
[ "MIT" ]
1
2021-03-01T04:31:30.000Z
2021-03-01T04:31:30.000Z
#include "InterceptorTest.h" using namespace std; using namespace BWAPI; void InterceptorTest::onStart() { BWAssert(Broodwar->isMultiplayer()==false); BWAssert(Broodwar->isReplay()==false); Broodwar->enableFlag(Flag::UserInput); Broodwar->sendText("show me the money"); int correctCarrierCount = 2; int correctInterceptorCount = 8; BWAssert(Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Carrier)==correctCarrierCount); Broodwar->printf("interceptor count = %d",Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Interceptor)); BWAssert(Broodwar->self()->completedUnitCount(UnitTypes::Protoss_Interceptor)==correctInterceptorCount); int carrierCount=0; int interceptorCount=0; for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) carrierCount++; if (u->getType()==UnitTypes::Protoss_Interceptor) interceptorCount++; } BWAssert(carrierCount==correctCarrierCount); BWAssert(interceptorCount==correctInterceptorCount);//fails because we cannot see interceptors until the first time they leave the carrier. for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) { BWAssert(u->getInterceptorCount()==4); } } } void InterceptorTest::onFrame() { for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Interceptor) Broodwar->drawTextMap(u->getPosition(),"isLoaded = %d",u->isLoaded()); } for (Unit u : Broodwar->self()->getUnits()) { if (!u->isLoaded()) Broodwar->drawTextMap(u->getPosition().x,u->getPosition().y-20,"loaded unit count = %d",u->getLoadedUnits().size()); } for (Unit u : Broodwar->self()->getUnits()) { if (u->getType()==UnitTypes::Protoss_Carrier) { Unitset interceptors = u->getInterceptors(); for (Unit i : interceptors) { Unit c=i->getCarrier(); Broodwar->drawLineMap(i->getPosition(),c->getPosition(),Colors::White); } } } }
34.844828
141
0.682335
ratiotile
715e214cbd79c88f5fffb406c28c97eedfa72939
580
cpp
C++
AcWing/LeetCode究极班/165.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
AcWing/LeetCode究极班/165.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
AcWing/LeetCode究极班/165.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
class Solution { public: int compareVersion(string v1, string v2) { int n = v1.size(), m = v2.size(); for (int i = 0, j = 0; i < n || j < m; ) { int a = i, b = j; while (a < n && v1[a] != '.') a ++; while (b < m && v2[b] != '.') b ++; int x = a == i ? 0 : stoi(v1.substr(i, a - i)); int y = b == j ? 0 : stoi(v2.substr(j ,b - j)); if (x > y) return 1; if (x < y) return -1; i = a + 1, j = b + 1; } return 0; } };
30.526316
59
0.32931
LauZyHou
7160834b20fd537d7941549a1efb729d579636fc
6,444
cpp
C++
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
src/NetProtocol/Protocols/nCiosDiscovery.cpp
Vladimir-Lin/QtNetProtocol
907cc8b5acf96a04d89eb8e68faede77c4a2df1b
[ "MIT" ]
null
null
null
#include <netprotocol.h> N::CiosDiscovery:: CiosDiscovery (void) : UdpDiscovery ( ) , neighbors (NULL) { setParameter ( "Myself" , false ) ; } N::CiosDiscovery::~CiosDiscovery (void) { if ( NotNull(neighbors) ) { if ( neighbors->Used <= 0 ) { delete neighbors ; } else { neighbors->Used-- ; } ; neighbors = NULL ; } ; } bool N::CiosDiscovery::Interpret(int code,QByteArray & line) { QString m ; switch ( code ) { case 0 : if ( ! Parameters [ "Initialize" ] . toBool ( ) ) { if ( Parameters [ "Method" ] . toString ( ) == "Listen" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Interval" , 30 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Probe" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Trying" , 15 ) ; PlaceAddress ( 100 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Broadcast" ) { setParameter ( "Initialize" , true ) ; setParameter ( "Interval" , 100 ) ; PlaceAddress ( 300 ) ; } else { } ; } else { if ( Parameters [ "Method" ] . toString ( ) == "Probe" ) { int trying = Parameters["Trying"].toInt() ; if ( trying > 0 ) { setParameter ( "Trying" , trying - 1 ) ; PlaceAddress ( 100 ) ; } else { setParameter ( "Running" , false ) ; } ; } else if ( Parameters [ "Method" ] . toString ( ) == "Broadcast" ) { PlaceAddress ( 300 ) ; } else if ( Parameters [ "Method" ] . toString ( ) == "Listen" ) { neighbors -> Verify ( ) ; } ; } ; break ; case 100 : m = QString::fromUtf8(line) ; PlaceAddress ( 200 ) ; break ; case 200 : m = QString::fromUtf8(line) ; AcceptAddress ( m ) ; break ; case 300 : m = QString::fromUtf8(line) ; AcceptAddress ( m ) ; PlaceAddress ( 200 ) ; break ; default : break ; } ; return true ; } QString N::CiosDiscovery::LocalAddress(void) { return QString ( "%1:%2" ) . arg ( Parameters [ "Address" ] . toString( ) ) . arg ( Parameters [ "Port" ] . toInt ( ) ) ; } void N::CiosDiscovery::PlaceAddress (int code) { if ( Data ( Output ) . size ( ) > 0 ) return ; QStringList s ; QString m ; s << QString::number ( code ) ; s << LocalAddress ( ) ; s << Parameters [ "Hostname" ] . toString ( ) ; s << Parameters [ "Application" ] . toString ( ) ; if ( Parameters . contains ( "Addresses" ) ) { s << Parameters [ "Addresses" ] . toString ( ) ; } ; m = s . join ( " " ) ; Place ( m ) ; } void N::CiosDiscovery::AcceptAddress (QString address) { if ( address.length() <= 0 ) return ; QStringList s = address . split ( ' ' ) ; if ( s . count ( ) < 3 ) return ; if ( s [ 0 ] == LocalAddress ( ) ) { setParameter ( "Myself" , true ) ; neighbors -> Verify ( ) ; } else { QString addr = s[0] ; QString host = s[1] ; QString apps = s[2] ; if ( s . count ( ) > 3 ) { for (int i=0;i<3;i++) { s . takeFirst ( ) ; } ; neighbors -> Others ( host , s ) ; } ; neighbors -> Update ( addr,host,apps ) ; setParameter ( "Accept" , addr ) ; } ; }
51.552
78
0.257294
Vladimir-Lin
7163ce0e902b4bbefe1d7e45af385505e51aacab
852
cpp
C++
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
src/fig00-test.cpp
carlos-urena/figs-gen
d9161efedddb13a7e067e8efe56bccc904c8e065
[ "MIT" ]
null
null
null
#include <iostream> #include <vec_mat.h> int main( int argc, char *argv[] ) { using namespace std ; cout << "\\documentclass[border=1mm]{standalone}" << endl << "\\input{../src/header.tex}" << endl ; const char * tex = R"tex( \tikzisometrico \begin{tikzpicture}[scale=1.4,isometricXYZ] \ejesvi{0.8}{1.5} \casita %% \circulox{0.4}{1.2} \path (1.2,0.0,0.0) node [above=.7cm,right=.3cm]{$\trota{\alpha,\vx}$}; \circulox{0.4}{1.2} \path (1.2,0.0,0.0) node [above right=.3cm and .5cm]{$\trotax{\theta}$}; \circuloy{0.4}{1.2} \path (0.0,1.2,0.0) node [left=.6cm] {$\trotay{\theta}$} ; \circuloz{0.4}{1.2} \path (0.0,0.0,1.2) node [above left=.3cm and .5cm] {$\trotaz{\theta}$} ; \end{tikzpicture} )tex"; cout << tex << endl << "\\end{document}" << endl ; }
26.625
100
0.543427
carlos-urena
716900084d66edb7864f1780ed8737da398ed885
34,154
cpp
C++
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
14
2015-10-19T01:35:58.000Z
2020-10-09T09:49:04.000Z
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
null
null
null
src/mechanisms.cpp
opendnssec/pkcs11-testing
cac56d02daadf333485c2376058db912dc37053a
[ "BSD-1-Clause" ]
3
2016-01-17T17:26:30.000Z
2022-02-08T09:46:11.000Z
/* $Id$ */ /* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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 AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** mechanisms.cpp Functions for mechanism tests *****************************************************************************/ #include "mechanisms.h" #include "error.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <unistd.h> extern CK_FUNCTION_LIST_PTR p11; int showMechs(char *slot) { CK_MECHANISM_TYPE_PTR pMechanismList; CK_SLOT_ID slotID; CK_RV rv; CK_ULONG ulMechCount; if (slot == NULL) { fprintf(stderr, "ERROR: A slot number must be supplied. " "Use --slot <number>\n"); return 1; } slotID = atoi(slot); // Get the size of the buffer rv = p11->C_GetMechanismList(slotID, NULL_PTR, &ulMechCount); if (rv == CKR_SLOT_ID_INVALID) { fprintf(stderr, "ERROR: The slot does not exist.\n"); return 1; } if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the number of mechanisms. rv=%s\n", rv2string(rv)); return 1; } pMechanismList = (CK_MECHANISM_TYPE_PTR)malloc(ulMechCount * sizeof(CK_MECHANISM_TYPE_PTR)); // Get the mechanism list rv = p11->C_GetMechanismList(slotID, pMechanismList, &ulMechCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the list of mechanisms. rv=%s\n", rv2string(rv)); free(pMechanismList); return 1; } printf("The following mechanisms are supported:\n"); printf("(key size is in bits or bytes depending on mechanism)\n\n"); for (int i = 0; i < ulMechCount; i++) { printMechInfo(slotID, pMechanismList[i]); } free(pMechanismList); return 0; } int testDNSSEC(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; int retVal = 0; printf("\n************************************************\n"); printf("* Testing what DNSSEC algorithms are available *\n"); printf("************************************************\n"); printf("\n(Cannot test GOST since it is not available in PKCS#11 v2.20)\n"); if (testDNSSEC_digest(slotID, hSession)) retVal = 1; if (testDNSSEC_rsa_keygen(slotID, hSession)) retVal = 1; if (testDNSSEC_rsa_sign(slotID, hSession)) retVal = 1; if (testDNSSEC_dsa_keygen(slotID, hSession)) retVal = 1; if (testDNSSEC_dsa_sign(slotID, hSession)) retVal = 1; return retVal; } int testSuiteB(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; int retVal = 0; printf("\n***************************************************\n"); printf("* Testing if NSA Suite B algorithms are available *\n"); printf("***************************************************\n"); if (testSuiteB_AES(slotID, hSession)) retVal = 1; if (testSuiteB_ECDSA(slotID, hSession)) retVal = 1; if (testSuiteB_ECDH(slotID, hSession)) retVal = 1; if (testSuiteB_SHA(slotID, hSession)) retVal = 1; return retVal; } int testSuiteB_AES(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_AES_KEY_GEN, CKM_AES_CBC, CKM_AES_CTR }; printf("\nTesting symmetric encryption\n"); printf("****************************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 128 and 256 bits.\n\n"); for (int i = 0; i < 3; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 16 || info.ulMaxKeySize < 32) { printf("OK, but only support %i-%i bits.\n", info.ulMinKeySize * 8, info.ulMaxKeySize * 8); } else { printf("OK\n"); } } return retVal; } int testSuiteB_ECDSA(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_EC_KEY_PAIR_GEN, CKM_ECDSA }; printf("\nTesting signatures\n"); printf("*********************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 256 and 384 bits.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 256 || info.ulMaxKeySize < 384) { printf("OK, but only support %i-%i bits\n", info.ulMinKeySize, info.ulMaxKeySize); } else { printf("OK\n"); } } return retVal; } int testSuiteB_ECDH(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE }; printf("\nTesting key agreement\n"); printf("*********************\n"); printf(" (Not testing functionality)\n"); printf(" Should support between 256 and 384 bits.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } if (info.ulMinKeySize > 256 || info.ulMaxKeySize < 384) { printf("OK, but only support %i-%i bits\n", info.ulMinKeySize, info.ulMaxKeySize); } else { printf("OK\n"); } } return retVal; } int testSuiteB_SHA(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_SHA256, CKM_SHA384 }; printf("\nTesting digesting\n"); printf("*****************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if the digesting mechanisms are supported.\n"); printf(" If the digesting algorithms are not available, \n"); printf(" then digesting has to be done in the host application.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } int testDNSSEC_digest(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_BYTE_PTR digest; CK_ULONG digestLen; CK_BYTE data[] = {"Text to digest"}; CK_MECHANISM mechanism = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; CK_MECHANISM_TYPE types[] = { CKM_MD5, CKM_SHA_1, CKM_SHA256, CKM_SHA512 }; printf("\nTesting digesting\n"); printf("*****************\n"); printf(" Will test the digesting mechanisms.\n"); printf(" If the algorithm is not available, then digesting has to be done\n"); printf(" in the host application. (MD5 is not recommended to use)\n\n"); for (int i = 0; i < 4; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } mechanism.mechanism = types[i]; rv = p11->C_DigestInit(hSession, &mechanism); if (rv != CKR_OK) { printf("Available, but could not initialize digesting. rv=%s\n", rv2string(rv)); retVal = 1; continue; } rv = p11->C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); if (rv != CKR_OK) { printf("Available, but could not check the size of the digest. rv=%s\n", rv2string(rv)); retVal = 1; continue; } digest = (CK_BYTE_PTR)malloc(digestLen); rv = p11->C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); free(digest); if (rv != CKR_OK) { printf("Available, but could not digest the data. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } int testDNSSEC_rsa_keygen(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_OBJECT_HANDLE hPublicKey, hPrivateKey; CK_BBOOL ckTrue = CK_TRUE; CK_MECHANISM keyGenMechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0}; CK_BYTE publicExponent[] = { 1, 0, 1 }; CK_ATTRIBUTE publicKeyTemplate[] = { { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_WRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_MODULUS_BITS, NULL_PTR, 0 }, { CKA_PUBLIC_EXPONENT, &publicExponent, sizeof(publicExponent) } }; CK_ATTRIBUTE privateKeyTemplate[] = { { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_UNWRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) } }; CK_ULONG keySizes[] = { 512, 768, 1024, 1536, 2048, 3072, 4096 }; printf("\nTesting RSA key generation\n"); printf("**************************\n"); printf(" Will test if RSA key generation is supported.\n"); printf(" DNSSEC support keys up to 4096 bits.\n\n"); printf(" %s: ", getMechName(CKM_RSA_PKCS_KEY_PAIR_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_RSA_PKCS_KEY_PAIR_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); return 1; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); return 1; } if (info.ulMaxKeySize < 4096) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } for (int i = 0; i < 7; i++) { printf(" %i bits: ", keySizes[i]); CK_ULONG keySize = keySizes[i]; publicKeyTemplate[4].pValue = &keySize; publicKeyTemplate[4].ulValueLen = sizeof(keySize); rv = p11->C_GenerateKeyPair(hSession, &keyGenMechanism, publicKeyTemplate, 6, privateKeyTemplate, 6, &hPublicKey, &hPrivateKey); if (rv != CKR_OK) { printf("Failed. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); p11->C_DestroyObject(hSession, hPublicKey); p11->C_DestroyObject(hSession, hPrivateKey); } return retVal; } int testDNSSEC_rsa_sign(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_OBJECT_HANDLE hPublicKey, hPrivateKey; CK_BBOOL ckTrue = CK_TRUE; CK_MECHANISM keyGenMechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0}; CK_BYTE publicExponent[] = { 1, 0, 1 }; CK_ULONG modulusBits = 1024; CK_MECHANISM mechanism = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; CK_ULONG length; CK_BYTE_PTR pSignature; CK_BYTE data[] = {"Text"}; CK_ATTRIBUTE publicKeyTemplate[] = { { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_WRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_MODULUS_BITS, &modulusBits, sizeof(modulusBits) }, { CKA_PUBLIC_EXPONENT, &publicExponent, sizeof(publicExponent) } }; CK_ATTRIBUTE privateKeyTemplate[] = { { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_UNWRAP, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) } }; CK_MECHANISM_TYPE types[] = { CKM_RSA_PKCS, CKM_RSA_X_509, CKM_MD5_RSA_PKCS, CKM_SHA1_RSA_PKCS, CKM_SHA256_RSA_PKCS, CKM_SHA512_RSA_PKCS }; printf("\nTesting RSA signing\n"); printf("*******************\n"); printf(" Will test if RSA signing is supported.\n"); printf(" Doing RAW RSA signing is not recommended (CKM_RSA_X_509)\n"); printf(" If the digesting algorithms are not available, \n"); printf(" then digesting has to be done in the host application.\n"); printf(" Then use the RSA only mechanisms.\n\n"); rv = p11->C_GenerateKeyPair(hSession, &keyGenMechanism, publicKeyTemplate, 6, privateKeyTemplate, 6, &hPublicKey, &hPrivateKey); if (rv != CKR_OK) { printf("Failed to generate a keypair. rv=%s\n", rv2string(rv)); printf("RSA is probably not supported\n"); return 1; } for (int i = 0; i < 6; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } mechanism.mechanism = types[i]; rv = p11->C_SignInit(hSession, &mechanism, hPrivateKey); if (rv != CKR_OK) { printf("Available, but could not initialize signing. rv=%s\n", rv2string(rv)); retVal = 1; continue; } rv = p11->C_Sign(hSession, data, sizeof(data)-1, NULL_PTR, &length); if (rv != CKR_OK) { printf("Available, but could not check the size of the signature. rv=%s\n", rv2string(rv)); retVal = 1; continue; } pSignature = (CK_BYTE_PTR)malloc(length); rv = p11->C_Sign(hSession, data, sizeof(data)-1, pSignature, &length); free(pSignature); if (rv != CKR_OK) { printf("Available, but could not sign the data. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } p11->C_DestroyObject(hSession, hPublicKey); p11->C_DestroyObject(hSession, hPrivateKey); return retVal; } int testDNSSEC_dsa_keygen(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_ULONG keySizes[] = { 512, 640, 768, 896, 1024 }; printf("\nTesting DSA key generation\n"); printf("**************************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if DSA key generation is supported.\n"); printf(" DNSSEC support keys up to 1024 bits.\n\n"); printf(" %s: ", getMechName(CKM_DSA_PARAMETER_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_DSA_PARAMETER_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; } else if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; } else { if (info.ulMaxKeySize < 1024) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } } printf(" %s: ", getMechName(CKM_DSA_KEY_PAIR_GEN)); rv = p11->C_GetMechanismInfo(slotID, CKM_DSA_KEY_PAIR_GEN, &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; } else if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; } else { if (info.ulMaxKeySize < 1024) { printf("OK, but support maximum %i bits\n", info.ulMaxKeySize); } else { printf("OK\n"); } } // for (int i = 0; i < 5; i++) // { // } return retVal; } int testDNSSEC_dsa_sign(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession) { CK_RV rv; CK_MECHANISM_INFO info; int retVal = 0; CK_MECHANISM_TYPE types[] = { CKM_DSA, CKM_DSA_SHA1 }; printf("\nTesting DSA signing\n"); printf("*******************\n"); printf(" (Not testing functionality)\n"); printf(" Will test if DSA signing is supported.\n"); printf(" If the digesting algorithm is not available, \n"); printf(" then digesting has to be done in the host application.\n"); printf(" Then use the DSA only mechanism.\n\n"); for (int i = 0; i < 2; i++) { printf(" %s: ", getMechName(types[i])); rv = p11->C_GetMechanismInfo(slotID, types[i], &info); if (rv == CKR_MECHANISM_INVALID) { printf("Not available\n"); retVal = 1; continue; } if (rv != CKR_OK) { printf("Not available. rv=%s\n", rv2string(rv)); retVal = 1; continue; } printf("OK\n"); } return retVal; } void printMechInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE mechType) { CK_MECHANISM_INFO info; CK_RV rv; info.ulMinKeySize = 0; info.ulMaxKeySize = 0; printf("%-36s", getMechName(mechType)); rv = p11->C_GetMechanismInfo(slotID, mechType, &info); if (rv != CKR_OK) { printf(" Could not get info about the mechanism. rv=%s\n", rv2string(rv)); return; } printMechKeySize(info.ulMinKeySize, info.ulMaxKeySize); printMechFlags(info.flags); } void printMechKeySize(CK_ULONG ulMinKeySize, CK_ULONG ulMaxKeySize) { char buffer[512]; buffer[0] = '\0'; if (ulMinKeySize) { if (ulMaxKeySize > ulMinKeySize) { sprintf(buffer, "%i - %i", ulMinKeySize, ulMaxKeySize); } else { sprintf(buffer, "%i", ulMinKeySize); } } printf("%-14s", buffer); } void printMechFlags(CK_FLAGS flags) { std::string stringFlags = ""; if (flags & CKF_HW) { stringFlags += "HW "; flags ^= CKF_HW; } else { stringFlags += "No-HW "; } if (flags & CKF_ENCRYPT) { stringFlags += "encrypt "; flags ^= CKF_ENCRYPT; } if (flags & CKF_DECRYPT) { stringFlags += "decrypt "; flags ^= CKF_DECRYPT; } if (flags & CKF_DIGEST) { stringFlags += "digest "; flags ^= CKF_DIGEST; } if (flags & CKF_SIGN) { stringFlags += "sign "; flags ^= CKF_SIGN; } if (flags & CKF_SIGN_RECOVER) { stringFlags += "sign-recover "; flags ^= CKF_SIGN_RECOVER; } if (flags & CKF_VERIFY) { stringFlags += "verify "; flags ^= CKF_VERIFY; } if (flags & CKF_VERIFY_RECOVER) { stringFlags += "verify-recover "; flags ^= CKF_VERIFY_RECOVER; } if (flags & CKF_GENERATE) { stringFlags += "generate "; flags ^= CKF_GENERATE; } if (flags & CKF_GENERATE_KEY_PAIR) { stringFlags += "generate-key-pair "; flags ^= CKF_GENERATE_KEY_PAIR; } if (flags & CKF_WRAP) { stringFlags += "wrap "; flags ^= CKF_WRAP; } if (flags & CKF_UNWRAP) { stringFlags += "unwrap "; flags ^= CKF_UNWRAP; } if (flags & CKF_DERIVE) { stringFlags += "derive "; flags ^= CKF_DERIVE; } printf("%s\n", stringFlags.c_str()); } const char* getMechName(CK_MECHANISM_TYPE mechType) { static char buffer[20]; switch (mechType) { case CKM_RSA_PKCS_KEY_PAIR_GEN: return "CKM_RSA_PKCS_KEY_PAIR_GEN"; case CKM_RSA_PKCS: return "CKM_RSA_PKCS"; case CKM_RSA_9796: return "CKM_RSA_9796"; case CKM_RSA_X_509: return "CKM_RSA_X_509"; case CKM_MD2_RSA_PKCS: return "CKM_MD2_RSA_PKCS"; case CKM_MD5_RSA_PKCS: return "CKM_MD5_RSA_PKCS"; case CKM_SHA1_RSA_PKCS: return "CKM_SHA1_RSA_PKCS"; case CKM_RIPEMD128_RSA_PKCS: return "CKM_RIPEMD128_RSA_PKCS"; case CKM_RIPEMD160_RSA_PKCS: return "CKM_RIPEMD160_RSA_PKCS"; case CKM_RSA_PKCS_OAEP: return "CKM_RSA_PKCS_OAEP"; case CKM_RSA_X9_31_KEY_PAIR_GEN: return "CKM_RSA_X9_31_KEY_PAIR_GEN"; case CKM_RSA_X9_31: return "CKM_RSA_X9_31"; case CKM_SHA1_RSA_X9_31: return "CKM_SHA1_RSA_X9_31"; case CKM_RSA_PKCS_PSS: return "CKM_RSA_PKCS_PSS"; case CKM_SHA1_RSA_PKCS_PSS: return "CKM_SHA1_RSA_PKCS_PSS"; case CKM_DSA_KEY_PAIR_GEN: return "CKM_DSA_KEY_PAIR_GEN"; case CKM_DSA: return "CKM_DSA"; case CKM_DSA_SHA1: return "CKM_DSA_SHA1"; case CKM_DH_PKCS_KEY_PAIR_GEN: return "CKM_DH_PKCS_KEY_PAIR_GEN"; case CKM_DH_PKCS_DERIVE: return "CKM_DH_PKCS_DERIVE"; case CKM_X9_42_DH_KEY_PAIR_GEN: return "CKM_X9_42_DH_KEY_PAIR_GEN"; case CKM_X9_42_DH_DERIVE: return "CKM_X9_42_DH_DERIVE"; case CKM_X9_42_DH_HYBRID_DERIVE: return "CKM_X9_42_DH_HYBRID_DERIVE"; case CKM_X9_42_MQV_DERIVE: return "CKM_X9_42_MQV_DERIVE"; case CKM_SHA256_RSA_PKCS: return "CKM_SHA256_RSA_PKCS"; case CKM_SHA384_RSA_PKCS: return "CKM_SHA384_RSA_PKCS"; case CKM_SHA512_RSA_PKCS: return "CKM_SHA512_RSA_PKCS"; case CKM_SHA256_RSA_PKCS_PSS: return "CKM_SHA256_RSA_PKCS_PSS"; case CKM_SHA384_RSA_PKCS_PSS: return "CKM_SHA384_RSA_PKCS_PSS"; case CKM_SHA512_RSA_PKCS_PSS: return "CKM_SHA512_RSA_PKCS_PSS"; case CKM_SHA224_RSA_PKCS: return "CKM_SHA224_RSA_PKCS"; case CKM_SHA224_RSA_PKCS_PSS: return "CKM_SHA224_RSA_PKCS_PSS"; case CKM_RC2_KEY_GEN: return "CKM_RC2_KEY_GEN"; case CKM_RC2_ECB: return "CKM_RC2_ECB"; case CKM_RC2_CBC: return "CKM_RC2_CBC"; case CKM_RC2_MAC: return "CKM_RC2_MAC"; case CKM_RC2_MAC_GENERAL: return "CKM_RC2_MAC_GENERAL"; case CKM_RC2_CBC_PAD: return "CKM_RC2_CBC_PAD"; case CKM_RC4_KEY_GEN: return "CKM_RC4_KEY_GEN"; case CKM_RC4: return "CKM_RC4"; case CKM_DES_KEY_GEN: return "CKM_DES_KEY_GEN"; case CKM_DES_ECB: return "CKM_DES_ECB"; case CKM_DES_CBC: return "CKM_DES_CBC"; case CKM_DES_MAC: return "CKM_DES_MAC"; case CKM_DES_MAC_GENERAL: return "CKM_DES_MAC_GENERAL"; case CKM_DES_CBC_PAD: return "CKM_DES_CBC_PAD"; case CKM_DES2_KEY_GEN: return "CKM_DES2_KEY_GEN"; case CKM_DES3_KEY_GEN: return "CKM_DES3_KEY_GEN"; case CKM_DES3_ECB: return "CKM_DES3_ECB"; case CKM_DES3_CBC: return "CKM_DES3_CBC"; case CKM_DES3_MAC: return "CKM_DES3_MAC"; case CKM_DES3_MAC_GENERAL: return "CKM_DES3_MAC_GENERAL"; case CKM_DES3_CBC_PAD: return "CKM_DES3_CBC_PAD"; case CKM_CDMF_KEY_GEN: return "CKM_CDMF_KEY_GEN"; case CKM_CDMF_ECB: return "CKM_CDMF_ECB"; case CKM_CDMF_CBC: return "CKM_CDMF_CBC"; case CKM_CDMF_MAC: return "CKM_CDMF_MAC"; case CKM_CDMF_MAC_GENERAL: return "CKM_CDMF_MAC_GENERAL"; case CKM_CDMF_CBC_PAD: return "CKM_CDMF_CBC_PAD"; case CKM_DES_OFB64: return "CKM_DES_OFB64"; case CKM_DES_OFB8: return "CKM_DES_OFB8"; case CKM_DES_CFB64: return "CKM_DES_CFB64"; case CKM_DES_CFB8: return "CKM_DES_CFB8"; case CKM_MD2: return "CKM_MD2"; case CKM_MD2_HMAC: return "CKM_MD2_HMAC"; case CKM_MD2_HMAC_GENERAL: return "CKM_MD2_HMAC_GENERAL"; case CKM_MD5: return "CKM_MD5"; case CKM_MD5_HMAC: return "CKM_MD5_HMAC"; case CKM_MD5_HMAC_GENERAL: return "CKM_MD5_HMAC_GENERAL"; case CKM_SHA_1: return "CKM_SHA_1"; case CKM_SHA_1_HMAC: return "CKM_SHA_1_HMAC"; case CKM_SHA_1_HMAC_GENERAL: return "CKM_SHA_1_HMAC_GENERAL"; case CKM_RIPEMD128: return "CKM_RIPEMD128"; case CKM_RIPEMD128_HMAC: return "CKM_RIPEMD128_HMAC"; case CKM_RIPEMD128_HMAC_GENERAL: return "CKM_RIPEMD128_HMAC_GENERAL"; case CKM_RIPEMD160: return "CKM_RIPEMD160"; case CKM_RIPEMD160_HMAC: return "CKM_RIPEMD160_HMAC"; case CKM_RIPEMD160_HMAC_GENERAL: return "CKM_RIPEMD160_HMAC_GENERAL"; case CKM_SHA256: return "CKM_SHA256"; case CKM_SHA256_HMAC: return "CKM_SHA256_HMAC"; case CKM_SHA256_HMAC_GENERAL: return "CKM_SHA256_HMAC_GENERAL"; case CKM_SHA224: return "CKM_SHA224"; case CKM_SHA224_HMAC: return "CKM_SHA224_HMAC"; case CKM_SHA224_HMAC_GENERAL: return "CKM_SHA224_HMAC_GENERAL"; case CKM_SHA384: return "CKM_SHA384"; case CKM_SHA384_HMAC: return "CKM_SHA384_HMAC"; case CKM_SHA384_HMAC_GENERAL: return "CKM_SHA384_HMAC_GENERAL"; case CKM_SHA512: return "CKM_SHA512"; case CKM_SHA512_HMAC: return "CKM_SHA512_HMAC"; case CKM_SHA512_HMAC_GENERAL: return "CKM_SHA512_HMAC_GENERAL"; case CKM_SECURID_KEY_GEN: return "CKM_SECURID_KEY_GEN"; case CKM_SECURID: return "CKM_SECURID"; case CKM_HOTP_KEY_GEN: return "CKM_HOTP_KEY_GEN"; case CKM_HOTP: return "CKM_HOTP"; case CKM_ACTI: return "CKM_ACTI"; case CKM_ACTI_KEY_GEN: return "CKM_ACTI_KEY_GEN"; case CKM_CAST_KEY_GEN: return "CKM_CAST_KEY_GEN"; case CKM_CAST_ECB: return "CKM_CAST_ECB"; case CKM_CAST_CBC: return "CKM_CAST_CBC"; case CKM_CAST_MAC: return "CKM_CAST_MAC"; case CKM_CAST_MAC_GENERAL: return "CKM_CAST_MAC_GENERAL"; case CKM_CAST_CBC_PAD: return "CKM_CAST_CBC_PAD"; case CKM_CAST3_KEY_GEN: return "CKM_CAST3_KEY_GEN"; case CKM_CAST3_ECB: return "CKM_CAST3_ECB"; case CKM_CAST3_CBC: return "CKM_CAST3_CBC"; case CKM_CAST3_MAC: return "CKM_CAST3_MAC"; case CKM_CAST3_MAC_GENERAL: return "CKM_CAST3_MAC_GENERAL"; case CKM_CAST3_CBC_PAD: return "CKM_CAST3_CBC_PAD"; case CKM_CAST128_KEY_GEN: return "CKM_CAST128_KEY_GEN"; case CKM_CAST128_ECB: return "CKM_CAST128_ECB"; case CKM_CAST128_CBC: return "CKM_CAST128_CBC"; case CKM_CAST128_MAC: return "CKM_CAST128_MAC"; case CKM_CAST128_MAC_GENERAL: return "CKM_CAST128_MAC_GENERAL"; case CKM_CAST128_CBC_PAD: return "CKM_CAST128_CBC_PAD"; case CKM_RC5_KEY_GEN: return "CKM_RC5_KEY_GEN"; case CKM_RC5_ECB: return "CKM_RC5_ECB"; case CKM_RC5_CBC: return "CKM_RC5_CBC"; case CKM_RC5_MAC: return "CKM_RC5_MAC"; case CKM_RC5_MAC_GENERAL: return "CKM_RC5_MAC_GENERAL"; case CKM_RC5_CBC_PAD: return "CKM_RC5_CBC_PAD"; case CKM_IDEA_KEY_GEN: return "CKM_IDEA_KEY_GEN"; case CKM_IDEA_ECB: return "CKM_IDEA_ECB"; case CKM_IDEA_CBC: return "CKM_IDEA_CBC"; case CKM_IDEA_MAC: return "CKM_IDEA_MAC"; case CKM_IDEA_MAC_GENERAL: return "CKM_IDEA_MAC_GENERAL"; case CKM_IDEA_CBC_PAD: return "CKM_IDEA_CBC_PAD"; case CKM_GENERIC_SECRET_KEY_GEN: return "CKM_GENERIC_SECRET_KEY_GEN"; case CKM_CONCATENATE_BASE_AND_KEY: return "CKM_CONCATENATE_BASE_AND_KEY"; case CKM_CONCATENATE_BASE_AND_DATA: return "CKM_CONCATENATE_BASE_AND_DATA"; case CKM_CONCATENATE_DATA_AND_BASE: return "CKM_CONCATENATE_DATA_AND_BASE"; case CKM_XOR_BASE_AND_DATA: return "CKM_XOR_BASE_AND_DATA"; case CKM_EXTRACT_KEY_FROM_KEY: return "CKM_EXTRACT_KEY_FROM_KEY"; case CKM_SSL3_PRE_MASTER_KEY_GEN: return "CKM_SSL3_PRE_MASTER_KEY_GEN"; case CKM_SSL3_MASTER_KEY_DERIVE: return "CKM_SSL3_MASTER_KEY_DERIVE"; case CKM_SSL3_KEY_AND_MAC_DERIVE: return "CKM_SSL3_KEY_AND_MAC_DERIVE"; case CKM_SSL3_MASTER_KEY_DERIVE_DH: return "CKM_SSL3_MASTER_KEY_DERIVE_DH"; case CKM_TLS_PRE_MASTER_KEY_GEN: return "CKM_TLS_PRE_MASTER_KEY_GEN"; case CKM_TLS_MASTER_KEY_DERIVE: return "CKM_TLS_MASTER_KEY_DERIVE"; case CKM_TLS_KEY_AND_MAC_DERIVE: return "CKM_TLS_KEY_AND_MAC_DERIVE"; case CKM_TLS_MASTER_KEY_DERIVE_DH: return "CKM_TLS_MASTER_KEY_DERIVE_DH"; case CKM_TLS_PRF: return "CKM_TLS_PRF"; case CKM_SSL3_MD5_MAC: return "CKM_SSL3_MD5_MAC"; case CKM_SSL3_SHA1_MAC: return "CKM_SSL3_SHA1_MAC"; case CKM_MD5_KEY_DERIVATION: return "CKM_MD5_KEY_DERIVATION"; case CKM_MD2_KEY_DERIVATION: return "CKM_MD2_KEY_DERIVATION"; case CKM_SHA1_KEY_DERIVATION: return "CKM_SHA1_KEY_DERIVATION"; case CKM_SHA256_KEY_DERIVATION: return "CKM_SHA256_KEY_DERIVATION"; case CKM_SHA384_KEY_DERIVATION: return "CKM_SHA384_KEY_DERIVATION"; case CKM_SHA512_KEY_DERIVATION: return "CKM_SHA512_KEY_DERIVATION"; case CKM_SHA224_KEY_DERIVATION: return "CKM_SHA224_KEY_DERIVATION"; case CKM_PBE_MD2_DES_CBC: return "CKM_PBE_MD2_DES_CBC"; case CKM_PBE_MD5_DES_CBC: return "CKM_PBE_MD5_DES_CBC"; case CKM_PBE_MD5_CAST_CBC: return "CKM_PBE_MD5_CAST_CBC"; case CKM_PBE_MD5_CAST3_CBC: return "CKM_PBE_MD5_CAST3_CBC"; case CKM_PBE_MD5_CAST128_CBC: return "CKM_PBE_MD5_CAST128_CBC"; case CKM_PBE_SHA1_CAST128_CBC: return "CKM_PBE_SHA1_CAST128_CBC"; case CKM_PBE_SHA1_RC4_128: return "CKM_PBE_SHA1_RC4_128"; case CKM_PBE_SHA1_RC4_40: return "CKM_PBE_SHA1_RC4_40"; case CKM_PBE_SHA1_DES3_EDE_CBC: return "CKM_PBE_SHA1_DES3_EDE_CBC"; case CKM_PBE_SHA1_DES2_EDE_CBC: return "CKM_PBE_SHA1_DES2_EDE_CBC"; case CKM_PBE_SHA1_RC2_128_CBC: return "CKM_PBE_SHA1_RC2_128_CBC"; case CKM_PBE_SHA1_RC2_40_CBC: return "CKM_PBE_SHA1_RC2_40_CBC"; case CKM_PKCS5_PBKD2: return "CKM_PKCS5_PBKD2"; case CKM_PBA_SHA1_WITH_SHA1_HMAC: return "CKM_PBA_SHA1_WITH_SHA1_HMAC"; case CKM_WTLS_PRE_MASTER_KEY_GEN: return "CKM_WTLS_PRE_MASTER_KEY_GEN"; case CKM_WTLS_MASTER_KEY_DERIVE: return "CKM_WTLS_MASTER_KEY_DERIVE"; case CKM_WTLS_MASTER_KEY_DERVIE_DH_ECC: return "CKM_WTLS_MASTER_KEY_DERVIE_DH_ECC"; case CKM_WTLS_PRF: return "CKM_WTLS_PRF"; case CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: return "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE"; case CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: return "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE"; case CKM_KEY_WRAP_LYNKS: return "CKM_KEY_WRAP_LYNKS"; case CKM_KEY_WRAP_SET_OAEP: return "CKM_KEY_WRAP_SET_OAEP"; case CKM_CMS_SIG: return "CKM_CMS_SIG"; case CKM_KIP_DERIVE: return "CKM_KIP_DERIVE"; case CKM_KIP_WRAP: return "CKM_KIP_WRAP"; case CKM_KIP_MAC: return "CKM_KIP_MAC"; case CKM_CAMELLIA_KEY_GEN: return "CKM_CAMELLIA_KEY_GEN"; case CKM_CAMELLIA_ECB: return "CKM_CAMELLIA_ECB"; case CKM_CAMELLIA_CBC: return "CKM_CAMELLIA_CBC"; case CKM_CAMELLIA_MAC: return "CKM_CAMELLIA_MAC"; case CKM_CAMELLIA_MAC_GENERAL: return "CKM_CAMELLIA_MAC_GENERAL"; case CKM_CAMELLIA_CBC_PAD: return "CKM_CAMELLIA_CBC_PAD"; case CKM_CAMELLIA_ECB_ENCRYPT_DATA: return "CKM_CAMELLIA_ECB_ENCRYPT_DATA"; case CKM_CAMELLIA_CBC_ENCRYPT_DATA: return "CKM_CAMELLIA_CBC_ENCRYPT_DATA"; case CKM_CAMELLIA_CTR: return "CKM_CAMELLIA_CTR"; case CKM_ARIA_KEY_GEN: return "CKM_ARIA_KEY_GEN"; case CKM_ARIA_ECB: return "CKM_ARIA_ECB"; case CKM_ARIA_CBC: return "CKM_ARIA_CBC"; case CKM_ARIA_MAC: return "CKM_ARIA_MAC"; case CKM_ARIA_MAC_GENERAL: return "CKM_ARIA_MAC_GENERAL"; case CKM_ARIA_CBC_PAD: return "CKM_ARIA_CBC_PAD"; case CKM_ARIA_ECB_ENCRYPT_DATA: return "CKM_ARIA_ECB_ENCRYPT_DATA"; case CKM_ARIA_CBC_ENCRYPT_DATA: return "CKM_ARIA_CBC_ENCRYPT_DATA"; case CKM_SKIPJACK_KEY_GEN: return "CKM_SKIPJACK_KEY_GEN"; case CKM_SKIPJACK_ECB64: return "CKM_SKIPJACK_ECB64"; case CKM_SKIPJACK_CBC64: return "CKM_SKIPJACK_CBC64"; case CKM_SKIPJACK_OFB64: return "CKM_SKIPJACK_OFB64"; case CKM_SKIPJACK_CFB64: return "CKM_SKIPJACK_CFB64"; case CKM_SKIPJACK_CFB32: return "CKM_SKIPJACK_CFB32"; case CKM_SKIPJACK_CFB16: return "CKM_SKIPJACK_CFB16"; case CKM_SKIPJACK_CFB8: return "CKM_SKIPJACK_CFB8"; case CKM_SKIPJACK_WRAP: return "CKM_SKIPJACK_WRAP"; case CKM_SKIPJACK_PRIVATE_WRAP: return "CKM_SKIPJACK_PRIVATE_WRAP"; case CKM_SKIPJACK_RELAYX: return "CKM_SKIPJACK_RELAYX"; case CKM_KEA_KEY_PAIR_GEN: return "CKM_KEA_KEY_PAIR_GEN"; case CKM_KEA_KEY_DERIVE: return "CKM_KEA_KEY_DERIVE"; case CKM_FORTEZZA_TIMESTAMP: return "CKM_FORTEZZA_TIMESTAMP"; case CKM_BATON_KEY_GEN: return "CKM_BATON_KEY_GEN"; case CKM_BATON_ECB128: return "CKM_BATON_ECB128"; case CKM_BATON_ECB96: return "CKM_BATON_ECB96"; case CKM_BATON_CBC128: return "CKM_BATON_CBC128"; case CKM_BATON_COUNTER: return "CKM_BATON_COUNTER"; case CKM_BATON_SHUFFLE: return "CKM_BATON_SHUFFLE"; case CKM_BATON_WRAP: return "CKM_BATON_WRAP"; case CKM_EC_KEY_PAIR_GEN: return "CKM_EC_KEY_PAIR_GEN"; case CKM_ECDSA: return "CKM_ECDSA"; case CKM_ECDSA_SHA1: return "CKM_ECDSA_SHA1"; case CKM_ECDH1_DERIVE: return "CKM_ECDH1_DERIVE"; case CKM_ECDH1_COFACTOR_DERIVE: return "CKM_ECDH1_COFACTOR_DERIVE"; case CKM_ECMQV_DERIVE: return "CKM_ECMQV_DERIVE"; case CKM_JUNIPER_KEY_GEN: return "CKM_JUNIPER_KEY_GEN"; case CKM_JUNIPER_ECB128: return "CKM_JUNIPER_ECB128"; case CKM_JUNIPER_CBC128: return "CKM_JUNIPER_CBC128"; case CKM_JUNIPER_COUNTER: return "CKM_JUNIPER_COUNTER"; case CKM_JUNIPER_SHUFFLE: return "CKM_JUNIPER_SHUFFLE"; case CKM_JUNIPER_WRAP: return "CKM_JUNIPER_WRAP"; case CKM_FASTHASH: return "CKM_FASTHASH"; case CKM_AES_KEY_GEN: return "CKM_AES_KEY_GEN"; case CKM_AES_ECB: return "CKM_AES_ECB"; case CKM_AES_CBC: return "CKM_AES_CBC"; case CKM_AES_MAC: return "CKM_AES_MAC"; case CKM_AES_MAC_GENERAL: return "CKM_AES_MAC_GENERAL"; case CKM_AES_CBC_PAD: return "CKM_AES_CBC_PAD"; case CKM_AES_CTR: return "CKM_AES_CTR"; case CKM_BLOWFISH_KEY_GEN: return "CKM_BLOWFISH_KEY_GEN"; case CKM_BLOWFISH_CBC: return "CKM_BLOWFISH_CBC"; case CKM_TWOFISH_KEY_GEN: return "CKM_TWOFISH_KEY_GEN"; case CKM_TWOFISH_CBC: return "CKM_TWOFISH_CBC"; case CKM_DES_ECB_ENCRYPT_DATA: return "CKM_DES_ECB_ENCRYPT_DATA"; case CKM_DES_CBC_ENCRYPT_DATA: return "CKM_DES_CBC_ENCRYPT_DATA"; case CKM_DES3_ECB_ENCRYPT_DATA: return "CKM_DES3_ECB_ENCRYPT_DATA"; case CKM_DES3_CBC_ENCRYPT_DATA: return "CKM_DES3_CBC_ENCRYPT_DATA"; case CKM_AES_ECB_ENCRYPT_DATA: return "CKM_AES_ECB_ENCRYPT_DATA"; case CKM_AES_CBC_ENCRYPT_DATA: return "CKM_AES_CBC_ENCRYPT_DATA"; case CKM_DSA_PARAMETER_GEN: return "CKM_DSA_PARAMETER_GEN"; case CKM_DH_PKCS_PARAMETER_GEN: return "CKM_DH_PKCS_PARAMETER_GEN"; case CKM_X9_42_DH_PARAMETER_GEN: return "CKM_X9_42_DH_PARAMETER_GEN"; case CKM_VENDOR_DEFINED: return "CKM_VENDOR_DEFINED"; defult: break; } sprintf(buffer, "0x%08X", mechType); return buffer; }
25.583521
130
0.703988
opendnssec
716c8ceaca06b28f5179b8b5441c557e982f619f
2,213
cpp
C++
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
1
2022-01-23T14:49:51.000Z
2022-01-23T14:49:51.000Z
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
9
2022-02-11T13:09:29.000Z
2022-03-14T12:13:39.000Z
Windows/src/Code_highlighting.cpp
SongZihui-sudo/easyhtmleditor
6ac122e0f6cff16da98adb74da2e3a2dba153748
[ "MIT" ]
null
null
null
#include "../include/Code_highlighting.h" #include "../include/EasyCodingEditor.h" using namespace cht; using namespace edt; edt::easyhtmleditor e1; //设置颜色 void Code_highlighting::Set_color(int wr,int wg,int wb,int br,int bg,int bb){ printf("\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm",wr,wg,wb,br,bg,bb); //\033[38表示前景,\033[48表示背景,三个%d表示混合的数 } //rgb初始化 void Code_highlighting::rgb_init(){ HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); //输入句柄 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //输出句柄 DWORD dwInMode, dwOutMode; GetConsoleMode(hIn, &dwInMode); //获取控制台输入模式 GetConsoleMode(hOut, &dwOutMode); //获取控制台输出模式 dwInMode |= 0x0200; //更改 dwOutMode |= 0x0004; SetConsoleMode(hIn, dwInMode); //设置控制台输入模式 SetConsoleMode(hOut, dwOutMode); //设置控制台输出模式 } //词法分析 bool Code_highlighting::Lexical_analysis(deque <string> ready_highlight){ vector <int> state; vector <cht::pos> postion; for (int i = 0; i < ready_highlight.size(); i++){ int bit_num = 0; int bit_y = 0; int bit_x = 0; int bit = 0; for (int j = 0; j < key_words.size(); j++){ int k = 0; int n = 0; int y = 0; while(ready_highlight[i][k]!='\0'&&key_words[j][n]!='\0'){ if(ready_highlight[i][k]==key_words[j][n]){ k++; n++; } else{ k=k-n+1; n=0; } } if(key_words[j][n]=='\0'){ state.push_back(j); cht::pos p1; p1.y = i; p1.x = k - n; postion.push_back(p1); } //(k-n); //主串中存在该模式返回下标号 else; //主串中不存在该模式 } } for (int i = 0; i < state.size(); i++){ if (state[i]){ e1.SetPos(postion[i].x,postion[i].y); Set_color(1,186,200,0,0,0); cout<<key_words[state[i]]; Set_color(255,255,255,0,0,0); } else; } postion.clear(); state.clear(); ready_highlight.clear(); return false; } //读取文件 bool Code_highlighting::read_setting_files(string language){ if (language == "c" || language == "cpp"){ fstream out_setting; out_setting.open("../Code_highlighting/c_setting.txt"); string out_str; if (out_setting){ while (getline(out_setting,out_str)){ key_words.push_back(out_str); } } else{ cerr<<"can not open the files!!!"<<endl; return false; } } else; return true; }
24.318681
77
0.621329
SongZihui-sudo
7175c2c3c49bf787331bffc1580fe566c969736d
340
cpp
C++
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
Linked List/Circular Linked List/Implementation.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node* next; Node(int d){ data=d; next=NULL; } }; int main() { Node *head=new Node(10); head->next=new Node(5); head->next->next=new Node(20); head->next->next->next=new Node(15); head->next->next->next->next=head; return 0; }
15.454545
37
0.576471
shouryagupta21
717b1bb2b1520881b511c7300b21c58576389883
1,016
cpp
C++
SPOJ/FACTMUL.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/FACTMUL.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/FACTMUL.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> const long long MOD = 1LL*186583*587117; using namespace std; typedef long long LL; typedef pair<int,int> pii; LL fact[10000010],res[10000010]; LL mulmod(LL a,LL b) { LL result = 0; while(b) { if((b&1)) result = (result + a)%MOD; a = (2*a)%MOD; b>>=1; } return result % MOD; } void calc() { fact[0] = 1; res[0] = 1 ; for(int i=1;i<=587117;i++) { fact[i] = (i%MOD * fact[i-1]%MOD)%MOD; res[i] = mulmod(res[i-1],fact[i]); } } int main() { LL n; cin>>n; if(n>=587117) cout<<0<<endl; else { fact[0] = 1; res[0] = 1 ; for(int i=1;i<=n;i++) { fact[i] = (i%MOD * fact[i-1]%MOD)%MOD; res[i] = mulmod(res[i-1],fact[i]); } cout<<res[n]<<endl; } return 0; }
17.220339
50
0.479331
aqfaridi
717b4675bb0fa8a8b367a36c16022bd188a65522
101
cpp
C++
GameExample/Proxy.cpp
alwayssmile11a1/MultiplayerGameServer
cd4227ecc5fe1b44d427bcbd76c050a8130d2200
[ "MIT" ]
null
null
null
GameExample/Proxy.cpp
alwayssmile11a1/MultiplayerGameServer
cd4227ecc5fe1b44d427bcbd76c050a8130d2200
[ "MIT" ]
null
null
null
GameExample/Proxy.cpp
alwayssmile11a1/MultiplayerGameServer
cd4227ecc5fe1b44d427bcbd76c050a8130d2200
[ "MIT" ]
null
null
null
#include "Proxy.h" int Proxy::playerId; int Proxy::playerNetworkGameObjectId; int Proxy::teamNumber;
20.2
37
0.792079
alwayssmile11a1
71820553d922ccffc2c5735d4282b3e3c8facc08
1,560
cpp
C++
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
null
null
null
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
29
2020-10-21T07:34:55.000Z
2021-01-12T15:15:53.000Z
tests/core/gui/widgets/PanelTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
1
2020-10-19T19:30:40.000Z
2020-10-19T19:30:40.000Z
#include <catch2/catch.hpp> #include "core/gui/widgets/Panel.h" #include "core/gui/widgets/VerticalLayout.h" #include "core/gui/widgets/Button.h" #include "TestsUtils.h" TEST_CASE("[Panel]") { auto vLayout = ire::core::gui::VerticalLayout::create({ 200, 200 }); auto button = ire::core::gui::Button::create(); vLayout->add(std::move(button), "Button"); auto button1 = ire::core::gui::Button::create(); vLayout->add(std::move(button1), "Button1"); auto panel = ire::core::gui::Panel::create({300, 300}, std::move(vLayout), "VerticalLayout"); SECTION("WidgetType") { REQUIRE(panel->getType().getName() == "Panel"); } SECTION("Background color and Outline ") { panel->setBackgroundColor(sf::Color::Magenta); REQUIRE(panel->getBackgroundColor() == sf::Color::Magenta); panel->setOutlineColor(sf::Color::Red); REQUIRE(panel->getOutlineColor() == sf::Color::Red); panel->setOutlineThickness(15); REQUIRE(panel->getOutlineThickness() == 15); } SECTION("Position and Size") { panel->setPosition({ 25, 50 }); REQUIRE(areAlmostEqual(panel->getPosition(), sf::Vector2f({ 25, 50 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getPosition(), sf::Vector2f({ 25, 50 }))); REQUIRE(areAlmostEqual(panel->getSize(), sf::Vector2f({ 300, 300 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getSize(), sf::Vector2f({ 300, 300 }))); panel->setSize({ 250, 500 }); REQUIRE(areAlmostEqual(panel->getSize(), sf::Vector2f({ 250, 500 }))); REQUIRE(areAlmostEqual(panel->getLayout()->getSize(), sf::Vector2f({ 250, 500 }))); } }
31.2
94
0.674359
Kubaaa96